@libp2p/webrtc 4.1.10 → 5.0.0-d101aac4b
Sign up to get free protection for your applications and to get access to all the features.
- package/README.md +4 -4
- package/dist/index.min.js +5 -6
- package/dist/src/error.d.ts +5 -25
- package/dist/src/error.d.ts.map +1 -1
- package/dist/src/error.js +18 -54
- package/dist/src/error.js.map +1 -1
- package/dist/src/index.d.ts +4 -4
- package/dist/src/index.js +4 -4
- package/dist/src/pb/message.d.ts +2 -2
- package/dist/src/pb/message.d.ts.map +1 -1
- package/dist/src/pb/message.js +10 -7
- package/dist/src/pb/message.js.map +1 -1
- package/dist/src/private-to-private/initiate-connection.d.ts.map +1 -1
- package/dist/src/private-to-private/initiate-connection.js +10 -8
- package/dist/src/private-to-private/initiate-connection.js.map +1 -1
- package/dist/src/private-to-private/pb/message.d.ts +2 -2
- package/dist/src/private-to-private/pb/message.d.ts.map +1 -1
- package/dist/src/private-to-private/pb/message.js +10 -7
- package/dist/src/private-to-private/pb/message.js.map +1 -1
- package/dist/src/private-to-private/signaling-stream-handler.d.ts.map +1 -1
- package/dist/src/private-to-private/signaling-stream-handler.js +9 -8
- package/dist/src/private-to-private/signaling-stream-handler.js.map +1 -1
- package/dist/src/private-to-private/transport.d.ts.map +1 -1
- package/dist/src/private-to-private/transport.js +6 -7
- package/dist/src/private-to-private/transport.js.map +1 -1
- package/dist/src/private-to-private/util.d.ts +1 -0
- package/dist/src/private-to-private/util.d.ts.map +1 -1
- package/dist/src/private-to-private/util.js +5 -5
- package/dist/src/private-to-private/util.js.map +1 -1
- package/dist/src/private-to-public/sdp.d.ts.map +1 -1
- package/dist/src/private-to-public/sdp.js +7 -6
- package/dist/src/private-to-public/sdp.js.map +1 -1
- package/dist/src/private-to-public/transport.d.ts +2 -1
- package/dist/src/private-to-public/transport.d.ts.map +1 -1
- package/dist/src/private-to-public/transport.js +12 -10
- package/dist/src/private-to-public/transport.js.map +1 -1
- package/dist/src/stream.js +6 -6
- package/dist/src/stream.js.map +1 -1
- package/package.json +15 -15
- package/src/error.ts +18 -64
- package/src/index.ts +4 -4
- package/src/pb/message.ts +10 -8
- package/src/private-to-private/initiate-connection.ts +11 -8
- package/src/private-to-private/pb/message.ts +10 -8
- package/src/private-to-private/signaling-stream-handler.ts +10 -8
- package/src/private-to-private/transport.ts +6 -7
- package/src/private-to-private/util.ts +5 -5
- package/src/private-to-public/sdp.ts +7 -6
- package/src/private-to-public/transport.ts +14 -12
- package/src/stream.ts +6 -6
- package/dist/typedoc-urls.json +0 -8
package/dist/index.min.js
CHANGED
@@ -1,10 +1,9 @@
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PWebrtc = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
2
|
-
"use strict";var Libp2PWebrtc=(()=>{var pd=Object.create;var oo=Object.defineProperty;var md=Object.getOwnPropertyDescriptor;var gd=Object.getOwnPropertyNames;var yd=Object.getPrototypeOf,wd=Object.prototype.hasOwnProperty;var bd=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),xt=(r,t)=>{for(var e in t)oo(r,e,{get:t[e],enumerable:!0})},nl=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of gd(t))!wd.call(r,o)&&o!==e&&oo(r,o,{get:()=>t[o],enumerable:!(n=md(t,o))||n.enumerable});return r};var xd=(r,t,e)=>(e=r!=null?pd(yd(r)):{},nl(t||!r||!r.__esModule?oo(e,"default",{value:r,enumerable:!0}):e,r)),Ed=r=>nl(oo({},"__esModule",{value:!0}),r);var pf=bd(an=>{"use strict";var hg="[object ArrayBuffer]",Ue=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===hg}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},fc="string",dg=/^[0-9a-f]+$/i,pg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,mg=/^[a-zA-Z0-9-_]+$/,us=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=Ue.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Qt=class{static toString(t,e=!1){let n=Ue.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},fs=class r{static isHex(t){return typeof t===fc&&dg.test(t)}static isBase64(t){return typeof t===fc&&pg.test(t)}static isBase64Url(t){return typeof t===fc&&mg.test(t)}static ToString(t,e="utf8"){let n=Ue.toUint8Array(t);switch(e.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Qt.toString(n,!0);case"utf16":case"utf16be":return Qt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Qt.fromString(t,!0);case"utf16":case"utf16be":return Qt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=Ue.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return us.fromString(t);case"utf16":case"utf16be":return Qt.fromString(t);case"utf16le":case"usc2":return Qt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return us.toString(t);case"utf16":case"utf16be":return Qt.toString(t);case"utf16le":case"usc2":return Qt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=Ue.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Ue.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Qt.toString(t,e)}static FromUtf16String(t,e=!1){return Qt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};fs.DEFAULT_UTF8_ENCODING="utf8";function gg(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function yg(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function wg(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}an.BufferSourceConverter=Ue;an.Convert=fs;an.assign=gg;an.combine=yg;an.isEqual=wg});var _y={};xt(_y,{webRTC:()=>Iy,webRTCDirect:()=>By});var so=Symbol.for("@libp2p/peer-id");function ol(r){return r!=null&&!!r[so]}var io=Symbol.for("@libp2p/transport");var sl;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(sl||(sl={}));var D=class extends Error{code;props;constructor(t,e,n){super(t),this.code=e,this.name=n?.name??"CodeError",this.props=n??{}}};var ao=(r,...t)=>{try{[...t]}catch{}};var co=class extends EventTarget{#t=new Map;constructor(){super(),ao(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new vd(t,e))}},vd=globalThis.CustomEvent;var Ur=Symbol.for("@libp2p/service-capabilities"),il=Symbol.for("@libp2p/service-dependencies");var pi={};xt(pi,{base58btc:()=>pt,base58flickr:()=>kd});var ow=new Uint8Array(0);function al(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function Se(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function cl(r){return new TextEncoder().encode(r)}function ll(r){return new TextDecoder().decode(r)}function Ad(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(w){if(w instanceof Uint8Array||(ArrayBuffer.isView(w)?w=new Uint8Array(w.buffer,w.byteOffset,w.byteLength):Array.isArray(w)&&(w=Uint8Array.from(w))),!(w instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(w.length===0)return"";for(var g=0,d=0,y=0,x=w.length;y!==x&&w[y]===0;)y++,g++;for(var p=(x-y)*u+1>>>0,A=new Uint8Array(p);y!==x;){for(var C=w[y],T=0,B=p-1;(C!==0||T<d)&&B!==-1;B--,T++)C+=256*A[B]>>>0,A[B]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");d=T,y++}for(var _=p-d;_!==p&&A[_]===0;)_++;for(var k=c.repeat(g);_<p;++_)k+=r.charAt(A[_]);return k}function h(w){if(typeof w!="string")throw new TypeError("Expected String");if(w.length===0)return new Uint8Array;var g=0;if(w[g]!==" "){for(var d=0,y=0;w[g]===c;)d++,g++;for(var x=(w.length-g)*l+1>>>0,p=new Uint8Array(x);w[g];){var A=e[w.charCodeAt(g)];if(A===255)return;for(var C=0,T=x-1;(A!==0||C<y)&&T!==-1;T--,C++)A+=a*p[T]>>>0,p[T]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");y=C,g++}if(w[g]!==" "){for(var B=x-y;B!==x&&p[B]===0;)B++;for(var _=new Uint8Array(d+(x-B)),k=d;B!==x;)_[k++]=p[B++];return _}}}function m(w){var g=h(w);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:h,decode:m}}var Sd=Ad,Bd=Sd,fl=Bd;var ui=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},fi=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),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 hl(this,t)}},hi=class{decoders;constructor(t){this.decoders=t}or(t){return hl(this,t)}decode(t){let e=t[0],n=this.decoders[e];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 hl(r,t){return new hi({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var di=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new ui(t,e,n),this.decoder=new fi(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Pr({name:r,prefix:t,encode:e,decode:n}){return new di(r,t,e,n)}function Ge({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=fl(e,r);return Pr({prefix:t,name:r,encode:n,decode:s=>Se(o(s))})}function Id(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function _d(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function ht({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Pr({prefix:t,name:r,encode(o){return _d(o,n,e)},decode(o){return Id(o,n,e,r)}})}var pt=Ge({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kd=Ge({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var mi={};xt(mi,{base10:()=>Rd});var Rd=Ge({prefix:"9",name:"base10",alphabet:"0123456789"});var gi={};xt(gi,{base16:()=>Td,base16upper:()=>Cd});var Td=ht({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Cd=ht({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yi={};xt(yi,{base2:()=>Nd});var Nd=ht({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var wi={};xt(wi,{base256emoji:()=>Od});var dl=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}"),Ld=dl.reduce((r,t,e)=>(r[e]=t,r),[]),Dd=dl.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Ud(r){return r.reduce((t,e)=>(t+=Ld[e],t),"")}function Pd(r){let t=[];for(let e of r){let n=Dd[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Od=Pr({prefix:"\u{1F680}",name:"base256emoji",encode:Ud,decode:Pd});var bi={};xt(bi,{base32:()=>Be,base32hex:()=>Fd,base32hexpad:()=>$d,base32hexpadupper:()=>Wd,base32hexupper:()=>Kd,base32pad:()=>Hd,base32padupper:()=>Vd,base32upper:()=>Md,base32z:()=>Gd});var Be=ht({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Md=ht({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Hd=ht({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Vd=ht({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Fd=ht({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Kd=ht({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$d=ht({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Wd=ht({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Gd=ht({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var xi={};xt(xi,{base36:()=>qd,base36upper:()=>zd});var qd=Ge({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zd=Ge({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Ai={};xt(Ai,{base64:()=>Ei,base64pad:()=>jd,base64url:()=>vi,base64urlpad:()=>Yd});var Ei=ht({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jd=ht({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),vi=ht({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Yd=ht({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Si={};xt(Si,{base8:()=>Zd});var Zd=ht({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Bi={};xt(Bi,{identity:()=>Xd});var Xd=Pr({prefix:"\0",name:"identity",encode:r=>ll(r),decode:r=>cl(r)});var xw=new TextEncoder,Ew=new TextDecoder;var ki={};xt(ki,{identity:()=>Ie});var te={};xt(te,{Digest:()=>fr,create:()=>Gt,decode:()=>qe,equals:()=>_i});var tp=gl,pl=128,ep=127,rp=~ep,np=Math.pow(2,31);function gl(r,t,e){t=t||[],e=e||0;for(var n=e;r>=np;)t[e++]=r&255|pl,r/=128;for(;r&rp;)t[e++]=r&255|pl,r>>>=7;return t[e]=r|0,gl.bytes=e-n+1,t}var op=Ii,sp=128,ml=127;function Ii(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ii.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&ml)<<o:(i&ml)*Math.pow(2,o),o+=7}while(i>=sp);return Ii.bytes=s-n,e}var ip=Math.pow(2,7),ap=Math.pow(2,14),cp=Math.pow(2,21),lp=Math.pow(2,28),up=Math.pow(2,35),fp=Math.pow(2,42),hp=Math.pow(2,49),dp=Math.pow(2,56),pp=Math.pow(2,63),mp=function(r){return r<ip?1:r<ap?2:r<cp?3:r<lp?4:r<up?5:r<fp?6:r<hp?7:r<dp?8:r<pp?9:10},gp={encode:tp,decode:op,encodingLength:mp},yp=gp,bn=yp;function xn(r,t=0){return[bn.decode(r,t),bn.decode.bytes]}function Or(r,t,e=0){return bn.encode(r,t,e),t}function Mr(r){return bn.encodingLength(r)}function Gt(r,t){let e=t.byteLength,n=Mr(r),o=n+Mr(e),s=new Uint8Array(o+e);return Or(r,s,0),Or(e,s,n),s.set(t,o),new fr(r,e,t,s)}function qe(r){let t=Se(r),[e,n]=xn(t),[o,s]=xn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new fr(e,o,i,t)}function _i(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&al(r.bytes,e.bytes)}}var fr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var yl=0,wp="identity",wl=Se;function bp(r){return Gt(yl,wl(r))}var Ie={code:yl,name:wp,encode:wl,digest:bp};var Ci={};xt(Ci,{sha256:()=>kt,sha512:()=>xp});function Ti({name:r,code:t,encode:e}){return new Ri(r,t,e)}var Ri=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Gt(this.code,e):e.then(n=>Gt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function xl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var kt=Ti({name:"sha2-256",code:18,encode:xl("SHA-256")}),xp=Ti({name:"sha2-512",code:19,encode:xl("SHA-512")});function El(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return vp(e,Ni(r),t??pt.encoder);default:return Ap(e,Ni(r),t??Be.encoder)}}var vl=new WeakMap;function Ni(r){let t=vl.get(r);if(t==null){let e=new Map;return vl.set(r,e),e}return t}var Yt=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,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:e}=this;if(t!==En)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Sp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:e}=this.multihash,n=Gt(t,e);return r.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 r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&_i(t.multihash,n.multihash)}toString(t){return El(this,t)}toJSON(){return{"/":El(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 e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??Al(n,o,s.bytes))}else if(e[Bp]===!0){let{version:n,multihash:o,code:s}=e,i=qe(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="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(e!==En)throw new Error(`Version 0 CID must use dag-pb (code: ${En}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=Al(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,En,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=Se(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new fr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,h]=xn(t.subarray(e));return e+=h,f},o=n(),s=En;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Ep(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ni(s).set(n,t),s}};function Ep(r,t){switch(r[0]){case"Q":{let e=t??pt;return[pt.prefix,e.decode(`${pt.prefix}${r}`)]}case pt.prefix:{let e=t??pt;return[pt.prefix,e.decode(r)]}case Be.prefix:{let e=t??Be;return[Be.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function vp(r,t,e){let{prefix:n}=e;if(n!==pt.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Ap(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var En=112,Sp=18;function Al(r,t,e){let n=Mr(r),o=n+Mr(t),s=new Uint8Array(o+e.byteLength);return Or(r,s,0),Or(t,s,n),s.set(e,o),s}var Bp=Symbol.for("@ipld/js-cid/CID");var me={...Bi,...yi,...Si,...mi,...gi,...bi,...xi,...pi,...Ai,...wi},Kw={...Ci,...ki};function Et(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function vt(r=0){return new Uint8Array(r)}function At(r=0){return new Uint8Array(r)}function Bl(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Sl=Bl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Li=Bl("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=At(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),Ip={utf8:Sl,"utf-8":Sl,hex:me.base16,latin1:Li,ascii:Li,binary:Li,...me},uo=Ip;function Z(r,t="utf8"){let e=uo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function G(r,t="utf8"){let e=uo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var _l=Symbol.for("nodejs.util.inspect.custom"),Il=Object.values(me).map(r=>r.decoder).reduce((r,t)=>r.or(t),me.identity.decoder),kl=114,Pi=36,Oi=37,vn=class{type;multihash;privateKey;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,this.privateKey=t.privateKey,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[so]=!0;toString(){return this.string==null&&(this.string=pt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return Yt.createV1(kl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Et(this.multihash.bytes,t);if(typeof t=="string")return hr(t).equals(this);if(t?.multihash?.bytes!=null)return Et(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[_l](){return`PeerId(${this.toString()})`}},Hr=class extends vn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Vr=class extends vn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},Fr=class extends vn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}},Di=2336,Ui=class{type="url";multihash;privateKey;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Ie.digest(Z(this.url))}[_l](){return`PeerId(${this.url})`}[so]=!0;toString(){return this.toCID().toString()}toCID(){return Yt.createV1(Di,this.multihash)}toBytes(){return this.toCID().bytes}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};function hr(r,t){if(t=t??Il,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=qe(pt.decode(`z${r}`));return r.startsWith("12D")?new Vr({multihash:e}):r.startsWith("16U")?new Fr({multihash:e}):new Hr({multihash:e})}return _p(Il.decode(r))}function _p(r){try{let t=qe(r);if(t.code===Ie.code){if(t.digest.length===Pi)return new Vr({multihash:t});if(t.digest.length===Oi)return new Fr({multihash:t})}if(t.code===kt.code)return new Hr({multihash:t})}catch{return kp(Yt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function kp(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==kl&&r.code!==Di)throw new Error("Supplied PeerID CID is invalid");if(r.code===Di){let e=G(r.multihash.digest);return new Ui(new URL(e))}let t=r.multihash;if(t.code===kt.code)return new Hr({multihash:r.multihash});if(t.code===Ie.code){if(t.digest.length===Pi)return new Vr({multihash:r.multihash});if(t.digest.length===Oi)return new Fr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Mi(r,t){return r.length===Pi?new Vr({multihash:Gt(Ie.code,r),privateKey:t}):r.length===Oi?new Fr({multihash:Gt(Ie.code,r),privateKey:t}):new Hr({multihash:await kt.digest(r),publicKey:r,privateKey:t})}var Tp=Math.pow(2,7),Cp=Math.pow(2,14),Np=Math.pow(2,21),Hi=Math.pow(2,28),Vi=Math.pow(2,35),Fi=Math.pow(2,42),Ki=Math.pow(2,49),tt=128,Lt=127;function st(r){if(r<Tp)return 1;if(r<Cp)return 2;if(r<Np)return 3;if(r<Hi)return 4;if(r<Vi)return 5;if(r<Fi)return 6;if(r<Ki)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function $i(r,t,e=0){switch(st(r)){case 8:t[e++]=r&255|tt,r/=128;case 7:t[e++]=r&255|tt,r/=128;case 6:t[e++]=r&255|tt,r/=128;case 5:t[e++]=r&255|tt,r/=128;case 4:t[e++]=r&255|tt,r>>>=7;case 3:t[e++]=r&255|tt,r>>>=7;case 2:t[e++]=r&255|tt,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Lp(r,t,e=0){switch(st(r)){case 8:t.set(e++,r&255|tt),r/=128;case 7:t.set(e++,r&255|tt),r/=128;case 6:t.set(e++,r&255|tt),r/=128;case 5:t.set(e++,r&255|tt),r/=128;case 4:t.set(e++,r&255|tt),r>>>=7;case 3:t.set(e++,r&255|tt),r>>>=7;case 2:t.set(e++,r&255|tt),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function Wi(r,t){let e=r[t],n=0;if(n+=e&Lt,e<tt||(e=r[t+1],n+=(e&Lt)<<7,e<tt)||(e=r[t+2],n+=(e&Lt)<<14,e<tt)||(e=r[t+3],n+=(e&Lt)<<21,e<tt)||(e=r[t+4],n+=(e&Lt)*Hi,e<tt)||(e=r[t+5],n+=(e&Lt)*Vi,e<tt)||(e=r[t+6],n+=(e&Lt)*Fi,e<tt)||(e=r[t+7],n+=(e&Lt)*Ki,e<tt))return n;throw new RangeError("Could not decode varint")}function Dp(r,t){let e=r.get(t),n=0;if(n+=e&Lt,e<tt||(e=r.get(t+1),n+=(e&Lt)<<7,e<tt)||(e=r.get(t+2),n+=(e&Lt)<<14,e<tt)||(e=r.get(t+3),n+=(e&Lt)<<21,e<tt)||(e=r.get(t+4),n+=(e&Lt)*Hi,e<tt)||(e=r.get(t+5),n+=(e&Lt)*Vi,e<tt)||(e=r.get(t+6),n+=(e&Lt)*Fi,e<tt)||(e=r.get(t+7),n+=(e&Lt)*Ki,e<tt))return n;throw new RangeError("Could not decode varint")}function ge(r,t,e=0){return t==null&&(t=At(st(r))),t instanceof Uint8Array?$i(r,t,e):Lp(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Wi(r,t):Dp(r,t)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=At(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var fo=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let h=Number.parseInt(f,t);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var Rl=45,Pp=15,Kr=new fo;function Gi(r){if(!(r.length>Pp))return Kr.new(r).parseWith(()=>Kr.readIPv4Addr())}function qi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Rl))return Kr.new(r).parseWith(()=>Kr.readIPv6Addr())}function ho(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Rl))return Kr.new(r).parseWith(()=>Kr.readIPAddr())}var vb=parseInt("0xFFFF",16),Ab=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function po(r){return!!Gi(r)}function mo(r){return!!qi(r)}function go(r){return!!ho(r)}var Nl=po,Fp=mo,zi=function(r){let t=0;if(r=r.toString().trim(),Nl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Fp(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Nl(e[n]),i;s&&(i=zi(e[n]),e[n]=G(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,G(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},Ll=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var $r={},ji={},$p=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];$p.forEach(r=>{let t=Wp(...r);ji[t.code]=t,$r[t.name]=t});function Wp(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function et(r){if(typeof r=="number"){if(ji[r]!=null)return ji[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if($r[r]!=null)return $r[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var ix=et("ip4"),ax=et("ip6"),cx=et("ipcidr");function Ji(r,t){switch(et(r).code){case 4:case 41:return qp(t);case 42:return Xi(t);case 6:case 273:case 33:case 132:return Pl(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Xi(t);case 421:return Zp(t);case 444:return Ul(t);case 445:return Ul(t);case 466:return Yp(t);case 481:return globalThis.encodeURIComponent(Xi(t));default:return G(t,"base16")}}function Qi(r,t){switch(et(r).code){case 4:return Dl(t);case 41:return Dl(t);case 42:return Zi(t);case 6:case 273:case 33:case 132:return ta(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Zi(t);case 421:return zp(t);case 444:return Xp(t);case 445:return Jp(t);case 466:return jp(t);case 481:return Zi(globalThis.decodeURIComponent(t));default:return Z(t,"base16")}}var Yi=Object.values(me).map(r=>r.decoder),Gp=function(){let r=Yi[0].or(Yi[1]);return Yi.slice(2).forEach(t=>r=r.or(t)),r}();function Dl(r){if(!go(r))throw new Error("invalid ip address");return zi(r)}function qp(r){let t=Ll(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!go(t))throw new Error("invalid ip address");return t}function ta(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Pl(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Zi(r){let t=Z(r),e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function Xi(r){let t=ee(r);if(r=r.slice(st(t)),r.length!==t)throw new Error("inconsistent lengths");return G(r)}function zp(r){let t;r[0]==="Q"||r[0]==="1"?t=qe(pt.decode(`z${r}`)).bytes:t=Yt.parse(r).multihash.bytes;let e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function jp(r){let t=Gp.decode(r),e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function Yp(r){let t=ee(r),e=r.slice(st(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+G(e,"base64url")}function Zp(r){let t=ee(r),e=r.slice(st(t));if(e.length!==t)throw new Error("inconsistent lengths");return G(e,"base58btc")}function Xp(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=Be.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=ta(n);return yt([e,o],e.length+o.length)}function Jp(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=Be.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=ta(n);return yt([e,o],e.length+o.length)}function Ul(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=G(t,"base32"),o=Pl(e);return`${n}:${o}`}function Ol(r){r=ea(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=et(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw Hl("invalid address: "+r);if(a.path===!0){n=ea(o.slice(s).join("/")),t.push([a.code,Qi(a.code,n)]),e.push([a.code,n]);break}let c=Qi(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ji(a.code,c)])}return{string:Ml(e),bytes:na(t),tuples:t,stringTuples:e,path:n}}function ra(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=st(s),a=et(s),c=Qp(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw Hl("Invalid address Uint8Array: "+G(r,"base16"));t.push([s,l]);let u=Ji(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Ml(e),tuples:t,stringTuples:e,path:n}}function Ml(r){let t=[];return r.map(e=>{let n=et(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),ea(t.join("/"))}function na(r){return yt(r.map(t=>{let e=et(t[0]),n=Uint8Array.from(ge(e.code));return t.length>1&&t[1]!=null&&(n=yt([n,t[1]])),n}))}function Qp(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ee(t instanceof Uint8Array?t:Uint8Array.from(t));return e+st(e)}}function ea(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Hl(r){return new Error("Error parsing address: "+r)}var tm=Symbol.for("nodejs.util.inspect.custom"),oa=Symbol.for("@multiformats/js-multiaddr/multiaddr"),em=[et("dns").code,et("dns4").code,et("dns6").code,et("dnsaddr").code],yo=class r{bytes;#t;#e;#r;#n;[oa]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=ra(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Ol(t)}else if(Fl(t))e=ra(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=et("tcp"),a=et("udp"),c=et("ip4"),l=et("ip6"),u=et("dns6"),f=et("ip6zone");for(let[m,w]of this.stringTuples())m===f.code&&(s=`%${w??""}`),em.includes(m)&&(e=i.name,o=443,n=`${w??""}${s}`,t=m===u.code?6:4),(m===i.code||m===a.code)&&(e=et(m).name,o=parseInt(w??"")),(m===c.code||m===l.code)&&(e=et(m).name,n=`${w??""}${s}`,t=m===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},et(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>et(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(na(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===$r.p2p.code&&t.push([n,o]),n===$r["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?G(pt.decode(`z${n}`),"base58btc"):G(Yt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Et(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Vl.get(e.name);if(n==null)throw new D(`no available resolver for ${e.name}`,"ERR_NO_AVAILABLE_RESOLVER");return(await n(this,t)).map(s=>re(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[tm](){return`Multiaddr(${this.#t})`}};var Vl=new Map;function Fl(r){return!!r?.[oa]}function re(r){return new yo(r)}var rm=r=>r.toString().split("/").slice(1),Sn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),J=r=>({match:t=>Sn(e=>e===r).match(t),pattern:r}),xo=()=>({match:r=>Sn(t=>typeof t=="string").match(r),pattern:"{string}"}),Eo=()=>({match:r=>Sn(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),Rt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{pt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),wo=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{vi.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),St=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),Zt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),rt=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function mt(...r){function t(o){let s=rm(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matches:e,exactMatch:n}}var ia=rt(J("dns4"),xo()),aa=rt(J("dns6"),xo()),ca=rt(J("dnsaddr"),xo()),Kl=rt(J("dns"),xo()),Ox=mt(ia),Mx=mt(aa),Hx=mt(ca),Vx=mt(Zt(Kl,ca,ia,aa)),$l=rt(J("ip4"),Sn(po)),Wl=rt(J("ip6"),Sn(mo)),Gl=Zt($l,Wl),ye=Zt(Gl,Kl,ia,aa,ca),Fx=mt(ye),Kx=mt($l),$x=mt(Wl),Wx=mt(Gl),la=rt(ye,J("tcp"),Eo()),Bn=rt(ye,J("udp"),Eo()),Gx=mt(la),qx=mt(Bn),ua=rt(Bn,J("quic")),vo=rt(Bn,J("quic-v1")),nm=Zt(ua,vo),zx=mt(ua),jx=mt(vo),sa=Zt(ye,la,Bn,ua,vo),ql=Zt(rt(sa,J("ws"),St(Rt()))),Yx=mt(ql),zl=Zt(rt(sa,J("wss"),St(Rt())),rt(sa,J("tls"),J("ws"),St(Rt()))),Zx=mt(zl),jl=rt(Bn,J("webrtc-direct"),St(wo()),St(wo()),St(Rt())),Yl=mt(jl),Zl=rt(vo,J("webtransport"),St(wo()),St(wo()),St(Rt())),Xx=mt(Zl),bo=Zt(ql,zl,rt(la,St(Rt())),rt(nm,St(Rt())),rt(ye,St(Rt())),jl,Zl,Rt()),Jx=mt(bo),om=rt(bo,J("p2p-circuit"),Rt()),Qx=mt(om),sm=Zt(rt(bo,J("p2p-circuit"),J("webrtc"),St(Rt())),rt(bo,J("webrtc"),St(Rt())),J("webrtc")),Xl=mt(sm),im=Zt(rt(ye,J("tcp"),Eo(),J("http"),St(Rt())),rt(ye,J("http"),St(Rt()))),t1=mt(im),am=Zt(rt(ye,J("tcp"),Zt(rt(J("443"),J("http")),rt(Eo(),J("https"))),St(Rt())),rt(ye,J("tls"),J("http"),St(Rt())),rt(ye,J("https"),St(Rt()))),e1=mt(am);var qt;(function(r){r.ERR_ALREADY_ABORTED="ERR_ALREADY_ABORTED",r.ERR_DATA_CHANNEL="ERR_DATA_CHANNEL",r.ERR_CONNECTION_CLOSED="ERR_CONNECTION_CLOSED",r.ERR_HASH_NOT_SUPPORTED="ERR_HASH_NOT_SUPPORTED",r.ERR_INVALID_MULTIADDR="ERR_INVALID_MULTIADDR",r.ERR_INVALID_FINGERPRINT="ERR_INVALID_FINGERPRINT",r.ERR_INVALID_PARAMETERS="ERR_INVALID_PARAMETERS",r.ERR_NOT_IMPLEMENTED="ERR_NOT_IMPLEMENTED",r.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS",r.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS="ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS"})(qt||(qt={}));var ze=class extends D{constructor(t,e){super(`WebRTC transport error: ${t}`,e??""),this.name="WebRTCTransportError"}};var fa=class extends ze{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`,qt.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function ya(r,t){return new fa(r,t)}var ha=class extends ze{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`,qt.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function Ao(r){return new ha(r)}var da=class extends ze{constructor(t){super(`There was a problem with a provided argument: ${t}`,qt.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function In(r){return new da(r)}var pa=class extends ze{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`,qt.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function wa(r,t){return new pa(r,t)}var ma=class extends ze{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`,qt.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function Jl(r){return new ma(r)}var ga=class extends ze{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `,qt.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function Ql(r){return new ga(r)}var tu=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},cm=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var lm=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var um=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var fm=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var hm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var dm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,pm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,eu=3,mm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",dm]],ru=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function ou(r){return r?nu(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new hm:typeof navigator<"u"?nu(navigator.userAgent):wm()}function gm(r){return r!==""&&mm.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function nu(r){var t=gm(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new fm;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<eu&&(o=tu(tu([],o,!0),bm(eu-o.length),!0)):o=[];var s=o.join("."),i=ym(r),a=pm.exec(r);return a&&a[1]?new um(e,s,i,a[1]):new cm(e,s,i)}function ym(r){for(var t=0,e=ru.length;t<e;t++){var n=ru[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function wm(){var r=typeof process<"u"&&process.version;return r?new lm(process.version.slice(1)):null}function bm(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function dt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Wr=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},ba=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},su=r=>globalThis.DOMException===void 0?new ba(r):new DOMException(r),iu=r=>{let t=r.reason===void 0?su("This operation was aborted."):r.reason;return t instanceof Error?t:su(t)};function dr(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:h}=t;h.aborted&&u(iu(h)),h.addEventListener("abort",()=>{u(iu(h))})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Wr;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(h){u(h)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(h){u(h)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var au=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var cu=ou(),_n=cu!=null&&cu.name==="firefox",So=async function*(){},Bo=async r=>{},xm=30*1e3;function lu(r,t,e=xm,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=dt(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await dr(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function kn(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??au.map(t=>({urls:[t]})),r}var pr=class{log;peerConnection;remoteAddr;timeline;metrics;source=So();sink=Bo;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Io=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},Gr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Io(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Io(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var xa=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function je(r={}){return Em(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function Em(r,t){t=t??{};let e=t.onEnd,n=new Gr,o,s,i,a=dt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((d,y)=>{s=x=>{s=null,n.push(x);try{d(r(n))}catch(p){y(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=dt()})}},l=d=>s!=null?s(d):(n.push(d),o),u=d=>(n=new Gr,s!=null?s({error:d}):(n.push({error:d}),o)),f=d=>{if(i)return o;if(t?.objectMode!==!0&&d?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:d})},h=d=>i?o:(i=!0,d!=null?u(d):l({done:!0})),m=()=>(n=new Gr,h(),{done:!0}),w=d=>(h(d),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:m,throw:w,push:f,end:h,get readableLength(){return n.size},onEmpty:async d=>{let y=d?.signal;if(y?.throwIfAborted(),n.isEmpty())return;let x,p;y!=null&&(x=new Promise((A,C)=>{p=()=>{C(new xa)},y.addEventListener("abort",p)}));try{await Promise.race([a.promise,x])}finally{p!=null&&y!=null&&y?.removeEventListener("abort",p)}}},e==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(d){return g.throw(d),e!=null&&(e(d),e=void 0),{done:!0}},return(){return g.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(d){return g.end(d),e!=null&&(e(d),e=void 0),o},get readableLength(){return g.readableLength},onEmpty:d=>g.onEmpty(d)},o}var _o=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function _e(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new _o(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new _o(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var fu=Symbol.for("@achingbrain/uint8arraylist");function uu(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function ko(r){return!!r?.[fu]}var lt=class r{bufs;length;[fu]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(ko(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(ko(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=uu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=uu(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(ko(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return yt(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:yt(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!ko(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let h=l;h>=0;h--){let m=this.get(f+h);if(n[h]!==m){u=Math.max(1,h-a[m]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=vt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=At(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=vt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=vt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=vt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Et(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function hu(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function du(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function pu(r,t){let e=hu(r).return?.();du(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var vm="ERR_STREAM_RESET",Am="ERR_SINK_INVALID_STATE",Sm=5e3;function Ea(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ro=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=dt(),this.closed=dt(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??Sm,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=je({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new D(`writable end state is "${this.writeStatus}" not "ready"`,Am);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);Ea(o)&&await o}let n=()=>{pu(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new lt(o):o;let s=this.sendData(o,e);Ea(s)&&(this.sendingData=dt(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await _e(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),e==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(t={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await _e(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await _e(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await _e(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();Ea(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new D("stream reset",vm);this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function To(r){return r[Symbol.asyncIterator]!=null}var Co=r=>{let t=st(r),e=At(t);return ge(r,e),Co.bytes=t,e};Co.bytes=0;function Rn(r,t){t=t??{};let e=t.lengthEncoder??Co;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return To(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Rn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Co;return new lt(e(r.byteLength),r)};var No=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Lo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Do=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Tn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Bm=8,Im=1024*1024*4,mr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(mr||(mr={}));var va=r=>{let t=ee(r);return va.bytes=st(t),t};va.bytes=0;function gr(r,t){let e=new lt,n=mr.LENGTH,o=-1,s=t?.lengthDecoder??va,i=t?.maxLengthLength??Bm,a=t?.maxDataLength??Im;function*c(){for(;e.byteLength>0;){if(n===mr.LENGTH)try{if(o=s(e),o<0)throw new No("Invalid message length");if(o>a)throw new Lo("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=mr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Do("Message length length too long");break}throw l}if(n===mr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=mr.LENGTH}}}return To(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Tn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Tn("Unexpected end of input")}()}gr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return gr(n,{...t??{},onLength:s=>{e=s}})};var km=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function Rm(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=km(r),f=(...m)=>{let w=e.multiArgs?m:m[0];e.filter&&!e.filter(w)||(c.push(w),e.count===c.length&&(n(),s(c)))},h=m=>{n(),i(m)};n=()=>{for(let m of a)u(m,f);for(let m of e.rejectionEvents)u(m,h)};for(let m of a)l(m,f);for(let m of e.rejectionEvents)l(m,h);e.signal&&e.signal.addEventListener("abort",()=>{h(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=dr(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function Aa(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Rm(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Sa=new Float32Array([-0]),Ye=new Uint8Array(Sa.buffer);function mu(r,t,e){Sa[0]=r,t[e]=Ye[0],t[e+1]=Ye[1],t[e+2]=Ye[2],t[e+3]=Ye[3]}function gu(r,t){return Ye[0]=r[t],Ye[1]=r[t+1],Ye[2]=r[t+2],Ye[3]=r[t+3],Sa[0]}var Ba=new Float64Array([-0]),Dt=new Uint8Array(Ba.buffer);function yu(r,t,e){Ba[0]=r,t[e]=Dt[0],t[e+1]=Dt[1],t[e+2]=Dt[2],t[e+3]=Dt[3],t[e+4]=Dt[4],t[e+5]=Dt[5],t[e+6]=Dt[6],t[e+7]=Dt[7]}function wu(r,t){return Dt[0]=r[t],Dt[1]=r[t+1],Dt[2]=r[t+2],Dt[3]=r[t+3],Dt[4]=r[t+4],Dt[5]=r[t+5],Dt[6]=r[t+6],Dt[7]=r[t+7],Ba[0]}var Tm=BigInt(Number.MAX_SAFE_INTEGER),Cm=BigInt(Number.MIN_SAFE_INTEGER),zt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return yr;if(t<Tm&&t>Cm)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>bu&&(o=0n,++n>bu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return yr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):yr}},yr=new zt(0,0);yr.toBigInt=function(){return 0n};yr.zzEncode=yr.zzDecode=function(){return this};yr.length=function(){return 1};var bu=4294967296n;function xu(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Eu(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function Ia(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function ne(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function Uo(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var _a=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,ne(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw ne(this,4);return Uo(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ne(this,4);return Uo(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ne(this,4);let t=gu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ne(this,4);let t=wu(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw ne(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Eu(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw ne(this,t);this.pos+=t}else do if(this.pos>=this.len)throw ne(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new zt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw ne(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw ne(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw ne(this,8);let t=Uo(this.buf,this.pos+=4),e=Uo(this.buf,this.pos+=4);return new zt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=Wi(this.buf,this.pos);return this.pos+=st(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function ka(r){return new _a(r instanceof Uint8Array?r:r.subarray())}function oe(r,t,e){let n=ka(r);return t.decode(n,void 0,e)}function Ra(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return At(i);o+i>t&&(n=At(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var wr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ta(){}var Na=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Nm=Ra();function Lm(r){return globalThis.Buffer!=null?At(r):Nm(r)}var Nn=class{len;head;tail;states;constructor(){this.len=0,this.head=new wr(Ta,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new wr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new La((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Po,10,zt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=zt.fromBigInt(t);return this._push(Po,e.length(),e)}uint64Number(t){return this._push($i,st(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=zt.fromBigInt(t).zzEncode();return this._push(Po,e.length(),e)}sint64Number(t){let e=zt.fromNumber(t).zzEncode();return this._push(Po,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ca,1,t?1:0)}fixed32(t){return this._push(Cn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=zt.fromBigInt(t);return this._push(Cn,4,e.lo)._push(Cn,4,e.hi)}fixed64Number(t){let e=zt.fromNumber(t);return this._push(Cn,4,e.lo)._push(Cn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(mu,4,t)}double(t){return this._push(yu,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ca,1,0):this.uint32(e)._push(Um,e,t)}string(t){let e=xu(t);return e!==0?this.uint32(e)._push(Ia,e,t):this._push(Ca,1,0)}fork(){return this.states=new Na(this),this.head=this.tail=new wr(Ta,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new wr(Ta,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=Lm(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ca(r,t,e){t[e]=r&255}function Dm(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var La=class extends wr{next;constructor(t,e){super(Dm,t,e),this.next=void 0}};function Po(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function Cn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function Um(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(Nn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Pm,t,r),this},Nn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Om,t,r),this});function Pm(r,t,e){t.set(r,e)}function Om(r,t,e){r.length<40?Ia(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Z(r),e)}function Da(){return new Nn}function se(r,t){let e=Da();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var qr;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(qr||(qr={}));function Oo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function br(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return Oo("enum",qr.VARINT,e,n)}function ie(r,t){return Oo("message",qr.LENGTH_DELIMITED,r,t)}var Ot;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(e||(e={})),function(o){o.codec=()=>br(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=ie((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.flag=r.Flag.codec().decode(o);break;case 2:i.message=o.bytes();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>se(o,r.codec()),r.decode=o=>oe(o,r.codec())})(Ot||(Ot={}));var Mm=2*1024*1024,Hm=30*1e3,Mo=16*1024;function Vm(r=Mo){let t=st(r-st(r)),e=1+st(Object.keys(Ot.Flag).length-1),n=1,o=r-t-e-n,s=st(o);return t+e+n+s}var Fm=Vm(),Km=5e3,$m=5e3,Ua=class extends Ro{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await dr(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=je(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Hm,this.maxBufferedAmount=t.maxBufferedAmount??Mm,this.maxMessageSize=(t.maxMessageSize??Mo)-Fm,this.receiveFinAck=dt(),this.finAckTimeout=t.closeTimeout??Km,this.openTimeout=t.openTimeout??$m,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new D("Unknown datachannel state","ERR_INVALID_STATE")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of gr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new lt(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await Aa(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof Wr?new D(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`,"ERR_BUFFER_CLEAR_TIMEOUT"):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new D(`Invalid datachannel state - ${this.channel.readyState}`,"ERR_INVALID_STATE");this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await Aa(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Ot.encode({message:n}),s=Rn.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Ot.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Ot.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await _e(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorCode:"ERR_FIN_ACK_NOT_RECEIVED"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(Ot.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Ot.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Ot.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Ot.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Ot.Flag.RESET&&this.reset(),e.flag===Ot.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Ot.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Ot.encode({flag:t}),n=Rn.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s",t.toString(),o)}return!1}};function zr(r){let{channel:t,direction:e}=r;return new Ua({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Au="/webrtc",Ze=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Au,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=zr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(t){return new Pa(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Pa=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??Au,this.metrics=e.metrics,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=zr({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(o,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(o),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(o)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),lu(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=So();sink=Bo;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=zr({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(e,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(e),this.metrics?.increment({outgoing_stream:!0}),e}};var xr=globalThis.RTCPeerConnection,Ho=globalThis.RTCSessionDescription,Su=globalThis.RTCIceCandidate;var Oa=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=dt(),this.haveNext=dt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=dt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=dt(),await _e(this.readNext.promise,e?.signal,e)}};function Bu(){return new Oa}var Vo=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ma=class extends Error{code;constructor(t,e){super(t),this.code=e}},Ha=class extends Ma{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Iu(r,t){let e=Bu();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new lt;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new Ha("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:h}=await Promise.race([n.next(),l]);return f===!0?new lt:h}for(;o.byteLength<i;){let{value:f,done:h}=await Promise.race([n.next(),l]);if(h===!0)throw new Vo("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Fo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ko=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},$o=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Ln(r,t={}){let e=Iu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=st(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??ge;return{read:async i=>{let a=-1,c=new lt;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Fo("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new $o("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ko("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new lt(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new lt(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Wo(r,t){let e=Ln(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var jt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Ft;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>br(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=ie((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s)=>{let i={},a=s==null?o.len:o.pos+s;for(;o.pos<a;){let c=o.uint32();switch(c>>>3){case 1:i.type=r.Type.codec().decode(o);break;case 2:i.data=o.string();break;default:o.skipType(c&7);break}}return i})),n),r.encode=o=>se(o,r.codec()),r.decode=o=>oe(o,r.codec())})(Ft||(Ft={}));var Go=async(r,t,e)=>{try{let n=dt();for(Gm(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==Ft.Type.ICE_CANDIDATE)throw new D("ICE candidate message expected","ERR_NOT_ICE_CANDIDATE");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new jt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Su(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new jt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0)throw n}};function Wm(r){return _n?r.iceConnectionState:r.connectionState}function Gm(r,t){r[_n?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Wm(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new D("RTCPeerConnection was closed","ERR_CONNECTION_CLOSED_BEFORE_CONNECTED"));break;default:break}}}async function _u({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=ku(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new D("Relay peer was missing","ERR_INVALID_ADDRESS");let h=s.getConnections(hr(f)),m,w=!1;h.length===0?(l?.(new jt("webrtc:dial-relay")),m=await i.dial(u,{signal:e,onProgress:l}),w=!0):(l?.(new jt("webrtc:reuse-relay-connection")),m=h[0]);try{l?.(new jt("webrtc:open-signaling-stream"));let g=await m.newStream(qo,{signal:e,runOnTransientConnection:!0}),d=Wo(g).pb(Ft),y=new xr(r),x=new Ze({logger:c},{peerConnection:y,dataChannelOptions:t});try{let p=y.createDataChannel("init");y.onicecandidate=({candidate:B})=>{let _=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),d.write({type:Ft.Type.ICE_CANDIDATE,data:_},{signal:e}).catch(k=>{a.error("error sending ICE candidate",k)})},y.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let A=await y.createOffer().catch(B=>{throw a.error("could not execute createOffer",B),new D("Failed to set createOffer","ERR_SDP_HANDSHAKE_FAILED")});a.trace("initiator send SDP offer %s",A.sdp),l?.(new jt("webrtc:send-sdp-offer")),await d.write({type:Ft.Type.SDP_OFFER,data:A.sdp},{signal:e}),await y.setLocalDescription(A).catch(B=>{throw a.error("could not execute setLocalDescription",B),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),l?.(new jt("webrtc:read-sdp-answer"));let C=await d.read({signal:e});if(C.type!==Ft.Type.SDP_ANSWER)throw new D("Remote should send an SDP answer","ERR_SDP_HANDSHAKE_FAILED");a.trace("initiator receive SDP answer %s",C.data);let T=new Ho({type:"answer",sdp:C.data});return await y.setRemoteDescription(T).catch(B=>{throw a.error("could not execute setRemoteDescription",B),new D("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")}),a.trace("initiator read candidates until connected"),l?.(new jt("webrtc:read-ice-candidates")),await Go(y,d,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new jt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await g.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:y,muxerFactory:x}}catch(p){throw a.error("outgoing signaling error",p),y.close(),g.abort(p),p}finally{y.onicecandidate=null,y.onicecandidateerror=null}}finally{if(w)try{await m.close({signal:e})}catch(g){m.abort(g)}}}var qm=U("dns4"),zm=U("dns6"),jm=U("dnsaddr"),Er=gt(U("dns"),jm,qm,zm),Yo=gt(U("ip4"),U("ip6")),jr=gt(K(Yo,U("tcp")),K(Er,U("tcp"))),Zo=K(Yo,U("udp")),Ym=K(Zo,U("utp")),Zm=K(Zo,U("quic")),Xm=K(Zo,U("quic-v1")),Va=gt(K(jr,U("ws")),K(Er,U("ws"))),zo=gt(K(Va,U("p2p")),Va),Fa=gt(K(jr,U("wss")),K(Er,U("wss")),K(jr,U("tls"),U("ws")),K(Er,U("tls"),U("ws"))),jo=gt(K(Fa,U("p2p")),Fa),Ka=gt(K(jr,U("http")),K(Yo,U("http")),K(Er,U("http"))),$a=gt(K(jr,U("https")),K(Yo,U("https")),K(Er,U("https"))),Ru=K(Zo,U("webrtc-direct"),U("certhash")),Nu=gt(K(Ru,U("p2p")),Ru),Tu=K(Xm,U("webtransport"),U("certhash"),U("certhash")),Lu=gt(K(Tu,U("p2p")),Tu),Du=gt(K(zo,U("p2p-webrtc-star"),U("p2p")),K(jo,U("p2p-webrtc-star"),U("p2p")),K(zo,U("p2p-webrtc-star")),K(jo,U("p2p-webrtc-star"))),R2=gt(K(zo,U("p2p-websocket-star"),U("p2p")),K(jo,U("p2p-websocket-star"),U("p2p")),K(zo,U("p2p-websocket-star")),K(jo,U("p2p-websocket-star"))),Uu=gt(K(Ka,U("p2p-webrtc-direct"),U("p2p")),K($a,U("p2p-webrtc-direct"),U("p2p")),K(Ka,U("p2p-webrtc-direct")),K($a,U("p2p-webrtc-direct"))),vr=gt(Va,Fa,Ka,$a,Du,Uu,jr,Ym,Zm,Er,Nu,Lu),T2=gt(K(vr,U("p2p-stardust"),U("p2p")),K(vr,U("p2p-stardust"))),Xe=gt(K(vr,U("p2p")),Du,Uu,Nu,Lu,U("p2p")),Cu=gt(K(Xe,U("p2p-circuit"),Xe),K(Xe,U("p2p-circuit")),K(U("p2p-circuit"),Xe),K(vr,U("p2p-circuit")),K(U("p2p-circuit"),vr),U("p2p-circuit")),Pu=()=>gt(K(Cu,Pu),Cu),ke=Pu(),C2=gt(K(ke,Xe,ke),K(Xe,ke),K(ke,Xe),ke,Xe);var N2=gt(K(ke,U("webrtc"),U("p2p")),K(ke,U("webrtc")),K(vr,U("webrtc"),U("p2p")),K(vr,U("webrtc")),U("webrtc"));function Ou(r){function t(e){let n;try{n=re(e)}catch{return!1}let o=r(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function K(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(o=>(n=typeof o=="function"?o().partialMatch(e):o.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Ou(t),partialMatch:t}}function gt(...r){function t(n){let o=null;return r.some(s=>{let i=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return i!=null?(o=i,!0):!1}),o}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Ou(t),partialMatch:t}}function U(r){let t=r;function e(o){let s;try{s=re(o)}catch{return!1}let i=s.protoNames();return i.length===1&&i[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var Xo=class extends co{peerId;transportManager;shutdownController;constructor(t,e){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>ke.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function Mu({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Wo(t).pb(Ft);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ft.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(h=>{o.error("error sending ICE candidate",h)})};let a=await s.read({signal:e});if(a.type!==Ft.Type.SDP_OFFER)throw new D(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `,"ERR_SDP_HANDSHAKE_FAILED");o.trace("recipient receive SDP offer %s",a.data);let c=new Ho({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new D("Failed to set remoteDescription","ERR_SDP_HANDSHAKE_FAILED")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new D("Failed to create answer","ERR_SDP_HANDSHAKE_FAILED")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Ft.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),o.trace("recipient read candidates until connected"),await Go(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(r.connectionState!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=re(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var Jm="/webrtc",Qm="/p2p-circuit",qo="/webrtc-signaling/0.0.1",t0=30*1e3,Jo=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,ao(1/0,this.shutdownController.signal),t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[io]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Ur]=["@libp2p/transport"];[il]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(qo,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnTransientConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(qo),this._started=!1}createListener(t){return new Xo(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Xl.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await _u({rtcConfiguration:await kn(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new pr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??t0),o=new xr(await kn(this.init.rtcConfiguration)),s=new Ze(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Mu({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new pr(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function ku(r){let t=r.toString().split(Jm+"/");if(t.length!==2)throw new D("webrtc protocol was not present in multiaddr",qt.ERR_INVALID_MULTIADDR);if(!t[0].includes(Qm))throw new D("p2p-circuit protocol was not present in multiaddr",qt.ERR_INVALID_MULTIADDR);let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new D("destination peer id was missing",qt.ERR_INVALID_MULTIADDR);let s=e.protos().pop();if(s===void 0)throw new D("invalid multiaddr",qt.ERR_INVALID_MULTIADDR);return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:hr(o)}}var lc={};xt(lc,{Ed25519PrivateKey:()=>Tr,Ed25519PublicKey:()=>Vn,generateKeyPair:()=>lg,generateKeyPairFromSeed:()=>df,unmarshalEd25519PrivateKey:()=>ag,unmarshalEd25519PublicKey:()=>cg});function Xt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Je(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function e0(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Yr(r,...t){if(!e0(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function Ar(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Je(r.outputLen),Je(r.blockLen)}function Zr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Hu(r,t){Yr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Sr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Jr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ae=(r,t)=>r<<32-t|r>>>t;var uv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var r0=async()=>{};async function Vu(r,t,e){let n=Date.now();for(let o=0;o<r;o++){e(o);let s=Date.now()-n;s>=0&&s<t||(await r0(),n+=s)}}function Fu(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ce(r){return typeof r=="string"&&(r=Fu(r)),Yr(r),r}function Wa(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Yr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Xr=class{clone(){return this._cloneInto()}},n0={}.toString;function Ku(r,t){if(t!==void 0&&n0.call(t)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,t)}function Qo(r){let t=n=>r().update(ce(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function Br(r=32){if(Sr&&typeof Sr.getRandomValues=="function")return Sr.getRandomValues(new Uint8Array(r));if(Sr&&typeof Sr.randomBytes=="function")return Sr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function o0(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var $u=(r,t,e)=>r&t^~r&e,Wu=(r,t,e)=>r&t^r&e^t&e,Qr=class extends Xr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Jr(this.buffer)}update(t){Zr(this);let{view:e,buffer:n,blockLen:o}=this;t=ce(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Jr(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Zr(this),Hu(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;o0(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Jr(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var ts=BigInt(4294967295),Ga=BigInt(32);function Gu(r,t=!1){return t?{h:Number(r&ts),l:Number(r>>Ga&ts)}:{h:Number(r>>Ga&ts)|0,l:Number(r&ts)|0}}function s0(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=Gu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var i0=(r,t)=>BigInt(r>>>0)<<Ga|BigInt(t>>>0),a0=(r,t,e)=>r>>>e,c0=(r,t,e)=>r<<32-e|t>>>e,l0=(r,t,e)=>r>>>e|t<<32-e,u0=(r,t,e)=>r<<32-e|t>>>e,f0=(r,t,e)=>r<<64-e|t>>>e-32,h0=(r,t,e)=>r>>>e-32|t<<64-e,d0=(r,t)=>t,p0=(r,t)=>r,m0=(r,t,e)=>r<<e|t>>>32-e,g0=(r,t,e)=>t<<e|r>>>32-e,y0=(r,t,e)=>t<<e-32|r>>>64-e,w0=(r,t,e)=>r<<e-32|t>>>64-e;function b0(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var x0=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),E0=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,v0=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),A0=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,S0=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),B0=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var I0={fromBig:Gu,split:s0,toBig:i0,shrSH:a0,shrSL:c0,rotrSH:l0,rotrSL:u0,rotrBH:f0,rotrBL:h0,rotr32H:d0,rotr32L:p0,rotlSH:m0,rotlSL:g0,rotlBH:y0,rotlBL:w0,add:b0,add3L:x0,add3H:E0,add4L:v0,add4H:A0,add5H:B0,add5L:S0},z=I0;var[_0,k0]=z.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Qe=new Uint32Array(80),tr=new Uint32Array(80),qa=class extends Qr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:h,Gh:m,Gl:w,Hh:g,Hl:d}=this;return[t,e,n,o,s,i,a,c,l,u,f,h,m,w,g,d]}set(t,e,n,o,s,i,a,c,l,u,f,h,m,w,g,d){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=h|0,this.Gh=m|0,this.Gl=w|0,this.Hh=g|0,this.Hl=d|0}process(t,e){for(let p=0;p<16;p++,e+=4)Qe[p]=t.getUint32(e),tr[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let A=Qe[p-15]|0,C=tr[p-15]|0,T=z.rotrSH(A,C,1)^z.rotrSH(A,C,8)^z.shrSH(A,C,7),B=z.rotrSL(A,C,1)^z.rotrSL(A,C,8)^z.shrSL(A,C,7),_=Qe[p-2]|0,k=tr[p-2]|0,F=z.rotrSH(_,k,19)^z.rotrBH(_,k,61)^z.shrSH(_,k,6),N=z.rotrSL(_,k,19)^z.rotrBL(_,k,61)^z.shrSL(_,k,6),O=z.add4L(B,N,tr[p-7],tr[p-16]),$=z.add4H(O,T,F,Qe[p-7],Qe[p-16]);Qe[p]=$|0,tr[p]=O|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:h,Fh:m,Fl:w,Gh:g,Gl:d,Hh:y,Hl:x}=this;for(let p=0;p<80;p++){let A=z.rotrSH(f,h,14)^z.rotrSH(f,h,18)^z.rotrBH(f,h,41),C=z.rotrSL(f,h,14)^z.rotrSL(f,h,18)^z.rotrBL(f,h,41),T=f&m^~f&g,B=h&w^~h&d,_=z.add5L(x,C,B,k0[p],tr[p]),k=z.add5H(_,y,A,T,_0[p],Qe[p]),F=_|0,N=z.rotrSH(n,o,28)^z.rotrBH(n,o,34)^z.rotrBH(n,o,39),O=z.rotrSL(n,o,28)^z.rotrBL(n,o,34)^z.rotrBL(n,o,39),$=n&s^n&a^s&a,I=o&i^o&c^i&c;y=g|0,x=d|0,g=m|0,d=w|0,m=f|0,w=h|0,{h:f,l:h}=z.add(l|0,u|0,k|0,F|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let R=z.add3L(F,O,I);n=z.add3H(R,k,N,$),o=R|0}({h:n,l:o}=z.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=z.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=z.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=z.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:h}=z.add(this.Eh|0,this.El|0,f|0,h|0),{h:m,l:w}=z.add(this.Fh|0,this.Fl|0,m|0,w|0),{h:g,l:d}=z.add(this.Gh|0,this.Gl|0,g|0,d|0),{h:y,l:x}=z.add(this.Hh|0,this.Hl|0,y|0,x|0),this.set(n,o,s,i,a,c,l,u,f,h,m,w,g,d,y,x)}roundClean(){Qe.fill(0),tr.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Dn=Qo(()=>new qa);var rs={};xt(rs,{aInRange:()=>Tt,abool:()=>le,abytes:()=>tn,bitGet:()=>D0,bitLen:()=>Xa,bitMask:()=>Pn,bitSet:()=>U0,bytesToHex:()=>Te,bytesToNumberBE:()=>Ce,bytesToNumberLE:()=>ue,concatBytes:()=>Le,createHmacDrbg:()=>Ja,ensureBytes:()=>it,equalBytes:()=>N0,hexToBytes:()=>_r,hexToNumber:()=>Za,inRange:()=>Un,isBytes:()=>er,memoized:()=>kr,notImplemented:()=>O0,numberToBytesBE:()=>rr,numberToBytesLE:()=>Ne,numberToHexUnpadded:()=>Ir,numberToVarBytesBE:()=>C0,utf8ToBytes:()=>L0,validateObject:()=>Jt});var Ya=BigInt(0),es=BigInt(1),R0=BigInt(2);function er(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function tn(r){if(!er(r))throw new Error("Uint8Array expected")}function le(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var T0=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Te(r){tn(r);let t="";for(let e=0;e<r.length;e++)t+=T0[r[e]];return t}function Ir(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Za(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var Re={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function qu(r){if(r>=Re._0&&r<=Re._9)return r-Re._0;if(r>=Re._A&&r<=Re._F)return r-(Re._A-10);if(r>=Re._a&&r<=Re._f)return r-(Re._a-10)}function _r(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=qu(r.charCodeAt(s)),a=qu(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ce(r){return Za(Te(r))}function ue(r){return tn(r),Za(Te(Uint8Array.from(r).reverse()))}function rr(r,t){return _r(r.toString(16).padStart(t*2,"0"))}function Ne(r,t){return rr(r,t).reverse()}function C0(r){return _r(Ir(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=_r(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(er(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function Le(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];tn(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function N0(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function L0(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var za=r=>typeof r=="bigint"&&Ya<=r;function Un(r,t,e){return za(r)&&za(t)&&za(e)&&t<=r&&r<e}function Tt(r,t,e,n){if(!Un(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function Xa(r){let t;for(t=0;r>Ya;r>>=es,t+=1);return t}function D0(r,t){return r>>BigInt(t)&es}function U0(r,t,e){return r|(e?es:Ya)<<BigInt(t)}var Pn=r=>(R0<<BigInt(r-1))-es,ja=r=>new Uint8Array(r),zu=r=>Uint8Array.from(r);function Ja(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=ja(r),o=ja(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=ja())=>{o=a(zu([0]),f),n=a(),f.length!==0&&(o=a(zu([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<t;){n=a();let m=n.slice();h.push(m),f+=n.length}return Le(...h)};return(f,h)=>{i(),c(f);let m;for(;!(m=h(l()));)c();return i(),m}}var P0={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||er(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function Jt(r,t,e={}){let n=(o,s,i)=>{let a=P0[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var O0=()=>{throw new Error("not implemented")};function kr(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var Bt=BigInt(0),ut=BigInt(1),Rr=BigInt(2),M0=BigInt(3),Qa=BigInt(4),ju=BigInt(5),Yu=BigInt(8),H0=BigInt(9),V0=BigInt(16);function Q(r,t){let e=r%t;return e>=Bt?e:t+e}function tc(r,t,e){if(e<=Bt||t<Bt)throw new Error("Expected power/modulo > 0");if(e===ut)return Bt;let n=ut;for(;t>Bt;)t&ut&&(n=n*r%e),r=r*r%e,t>>=ut;return n}function at(r,t,e){let n=r;for(;t-- >Bt;)n*=n,n%=e;return n}function ns(r,t){if(r===Bt||t<=Bt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=Q(r,t),n=t,o=Bt,s=ut,i=ut,a=Bt;for(;e!==Bt;){let l=n/e,u=n%e,f=o-i*l,h=s-a*l;n=e,e=u,o=i,s=a,i=f,a=h}if(n!==ut)throw new Error("invert: does not exist");return Q(o,t)}function F0(r){let t=(r-ut)/Rr,e,n,o;for(e=r-ut,n=0;e%Rr===Bt;e/=Rr,n++);for(o=Rr;o<r&&tc(o,t,r)!==r-ut;o++);if(n===1){let i=(r+ut)/Qa;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(e+ut)/Rr;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),h=a.pow(c,e);for(;!a.eql(h,a.ONE);){if(a.eql(h,a.ZERO))return a.ZERO;let m=1;for(let g=a.sqr(h);m<l&&!a.eql(g,a.ONE);m++)g=a.sqr(g);let w=a.pow(u,ut<<BigInt(l-m-1));u=a.sqr(w),f=a.mul(f,w),h=a.mul(h,u),l=m}return f}}function K0(r){if(r%Qa===M0){let t=(r+ut)/Qa;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%Yu===ju){let t=(r-ju)/Yu;return function(n,o){let s=n.mul(o,Rr),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,Rr),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%V0,F0(r)}var Zu=(r,t)=>(Q(r,t)&ut)===ut,$0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ec(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=$0.reduce((n,o)=>(n[o]="function",n),t);return Jt(r,e)}function W0(r,t,e){if(e<Bt)throw new Error("Expected power > 0");if(e===Bt)return r.ONE;if(e===ut)return t;let n=r.ONE,o=t;for(;e>Bt;)e&ut&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ut;return n}function G0(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function rc(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function nr(r,t,e=!1,n={}){if(r<=Bt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=rc(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=K0(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Pn(o),ZERO:Bt,ONE:ut,create:c=>Q(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return Bt<=c&&c<r},is0:c=>c===Bt,isOdd:c=>(c&ut)===ut,neg:c=>Q(-c,r),eql:(c,l)=>c===l,sqr:c=>Q(c*c,r),add:(c,l)=>Q(c+l,r),sub:(c,l)=>Q(c-l,r),mul:(c,l)=>Q(c*l,r),pow:(c,l)=>W0(a,c,l),div:(c,l)=>Q(c*ns(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ns(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>G0(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Ne(c,s):rr(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?ue(c):Ce(c)}});return Object.freeze(a)}function Xu(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function nc(r){let t=Xu(r);return t+Math.ceil(t/2)}function Ju(r,t,e=!1){let n=r.length,o=Xu(t),s=nc(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?Ce(r):ue(r),a=Q(i,t-ut)+ut;return e?Ne(a,o):rr(a,o)}var z0=BigInt(0),oc=BigInt(1),sc=new WeakMap,Qu=new WeakMap;function os(r,t){let e=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>t)throw new Error(`Wrong window size=${s}, should be [1..${t}]`)},o=s=>{n(s);let i=Math.ceil(t/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:e,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>z0;)i&oc&&(a=a.add(c)),c=c.double(),i>>=oc;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),l=[],u=s,f=u;for(let h=0;h<a;h++){f=u,l.push(f);for(let m=1;m<c;m++)f=f.add(u),l.push(f);u=f.double()}return l},wNAF(s,i,a){let{windows:c,windowSize:l}=o(s),u=r.ZERO,f=r.BASE,h=BigInt(2**s-1),m=2**s,w=BigInt(s);for(let g=0;g<c;g++){let d=g*l,y=Number(a&h);a>>=w,y>l&&(y-=m,a+=oc);let x=d,p=d+Math.abs(y)-1,A=g%2!==0,C=y<0;y===0?f=f.add(e(A,i[x])):u=u.add(e(C,i[p]))}return{p:u,f}},wNAFCached(s,i,a){let c=Qu.get(s)||1,l=sc.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&sc.set(s,a(l))),this.wNAF(c,l,i)},setWindowSize(s,i){n(i),Qu.set(s,i),sc.delete(s)}}}function ss(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((u,f)=>{if(!t.isValid(u))throw new Error(`wrong scalar at index ${f}`)}),e.forEach((u,f)=>{if(!(u instanceof r))throw new Error(`wrong point at index ${f}`)});let o=Xa(BigInt(e.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/s)*s,l=r.ZERO;for(let u=c;u>=0;u-=s){a.fill(r.ZERO);for(let h=0;h<n.length;h++){let m=n[h],w=Number(m>>BigInt(u)&BigInt(i));a[w]=a[w].add(e[h])}let f=r.ZERO;for(let h=a.length-1,m=r.ZERO;h>0;h--)m=m.add(a[h]),f=f.add(m);if(l=l.add(f),u!==0)for(let h=0;h<s;h++)l=l.double()}return l}function On(r){return ec(r.Fp),Jt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...rc(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var fe=BigInt(0),Kt=BigInt(1),is=BigInt(2),j0=BigInt(8),Y0={zip215:!0};function Z0(r){let t=On(r);return Jt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function tf(r){let t=Z0(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=is<<BigInt(a*8)-Kt,u=e.create,f=nr(t.n,t.nBitLength),h=t.uvRatio||((E,b)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(b))}}catch{return{isValid:!1,value:fe}}}),m=t.adjustScalarBytes||(E=>E),w=t.domain||((E,b,S)=>{if(le("phflag",S),b.length||S)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,b){Tt("coordinate "+E,b,fe,l)}function d(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let y=kr((E,b)=>{let{ex:S,ey:v,ez:L}=E,P=E.is0();b==null&&(b=P?j0:e.inv(L));let V=u(S*b),W=u(v*b),q=u(L*b);if(P)return{x:fe,y:Kt};if(q!==Kt)throw new Error("invZ was invalid");return{x:V,y:W}}),x=kr(E=>{let{a:b,d:S}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:v,ey:L,ez:P,et:V}=E,W=u(v*v),q=u(L*L),j=u(P*P),X=u(j*j),nt=u(W*b),ot=u(j*u(nt+q)),ct=u(X+u(S*u(W*q)));if(ot!==ct)throw new Error("bad point: equation left != right (1)");let Pt=u(v*L),bt=u(P*V);if(Pt!==bt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(b,S,v,L){this.ex=b,this.ey=S,this.ez=v,this.et=L,g("x",b),g("y",S),g("z",v),g("t",L),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof p)throw new Error("extended point not allowed");let{x:S,y:v}=b||{};return g("x",S),g("y",v),new p(S,v,Kt,u(S*v))}static normalizeZ(b){let S=e.invertBatch(b.map(v=>v.ez));return b.map((v,L)=>v.toAffine(S[L])).map(p.fromAffine)}static msm(b,S){return ss(p,f,b,S)}_setWindowSize(b){T.setWindowSize(this,b)}assertValidity(){x(this)}equals(b){d(b);let{ex:S,ey:v,ez:L}=this,{ex:P,ey:V,ez:W}=b,q=u(S*W),j=u(P*L),X=u(v*W),nt=u(V*L);return q===j&&X===nt}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:b}=t,{ex:S,ey:v,ez:L}=this,P=u(S*S),V=u(v*v),W=u(is*u(L*L)),q=u(b*P),j=S+v,X=u(u(j*j)-P-V),nt=q+V,ot=nt-W,ct=q-V,Pt=u(X*ot),bt=u(nt*ct),Vt=u(X*ct),Ae=u(ot*nt);return new p(Pt,bt,Ae,Vt)}add(b){d(b);let{a:S,d:v}=t,{ex:L,ey:P,ez:V,et:W}=this,{ex:q,ey:j,ez:X,et:nt}=b;if(S===BigInt(-1)){let Zc=u((P-L)*(j+q)),Xc=u((P+L)*(j-q)),li=u(Xc-Zc);if(li===fe)return this.double();let Jc=u(V*is*nt),Qc=u(W*is*X),tl=Qc+Jc,el=Xc+Zc,rl=Qc-Jc,ud=u(tl*li),fd=u(el*rl),hd=u(tl*rl),dd=u(li*el);return new p(ud,fd,dd,hd)}let ot=u(L*q),ct=u(P*j),Pt=u(W*v*nt),bt=u(V*X),Vt=u((L+P)*(q+j)-ot-ct),Ae=bt-Pt,yn=bt+Pt,wn=u(ct-S*ot),id=u(Vt*Ae),ad=u(yn*wn),cd=u(Vt*wn),ld=u(Ae*yn);return new p(id,ad,ld,cd)}subtract(b){return this.add(b.negate())}wNAF(b){return T.wNAFCached(this,b,p.normalizeZ)}multiply(b){let S=b;Tt("scalar",S,Kt,n);let{p:v,f:L}=this.wNAF(S);return p.normalizeZ([v,L])[0]}multiplyUnsafe(b){let S=b;return Tt("scalar",S,fe,n),S===fe?C:this.equals(C)||S===Kt?this:this.equals(A)?this.wNAF(S).p:T.unsafeLadder(this,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,n).is0()}toAffine(b){return y(this,b)}clearCofactor(){let{h:b}=t;return b===Kt?this:this.multiplyUnsafe(b)}static fromHex(b,S=!1){let{d:v,a:L}=t,P=e.BYTES;b=it("pointHex",b,P),le("zip215",S);let V=b.slice(),W=b[P-1];V[P-1]=W&-129;let q=ue(V),j=S?l:e.ORDER;Tt("pointHex.y",q,fe,j);let X=u(q*q),nt=u(X-Kt),ot=u(v*X-L),{isValid:ct,value:Pt}=h(nt,ot);if(!ct)throw new Error("Point.fromHex: invalid y coordinate");let bt=(Pt&Kt)===Kt,Vt=(W&128)!==0;if(!S&&Pt===fe&&Vt)throw new Error("Point.fromHex: x=0 and x_0=1");return Vt!==bt&&(Pt=u(-Pt)),p.fromAffine({x:Pt,y:q})}static fromPrivateKey(b){return k(b).point}toRawBytes(){let{x:b,y:S}=this.toAffine(),v=Ne(S,e.BYTES);return v[v.length-1]|=b&Kt?128:0,v}toHex(){return Te(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,Kt,u(t.Gx*t.Gy)),p.ZERO=new p(fe,Kt,Kt,fe);let{BASE:A,ZERO:C}=p,T=os(p,a*8);function B(E){return Q(E,n)}function _(E){return B(ue(E))}function k(E){let b=a;E=it("private key",E,b);let S=it("hashed private key",s(E),2*b),v=m(S.slice(0,b)),L=S.slice(b,2*b),P=_(v),V=A.multiply(P),W=V.toRawBytes();return{head:v,prefix:L,scalar:P,point:V,pointBytes:W}}function F(E){return k(E).pointBytes}function N(E=new Uint8Array,...b){let S=Le(...b);return _(s(w(S,it("context",E),!!o)))}function O(E,b,S={}){E=it("message",E),o&&(E=o(E));let{prefix:v,scalar:L,pointBytes:P}=k(b),V=N(S.context,v,E),W=A.multiply(V).toRawBytes(),q=N(S.context,W,P,E),j=B(V+q*L);Tt("signature.s",j,fe,n);let X=Le(W,Ne(j,e.BYTES));return it("result",X,a*2)}let $=Y0;function I(E,b,S,v=$){let{context:L,zip215:P}=v,V=e.BYTES;E=it("signature",E,2*V),b=it("message",b),P!==void 0&&le("zip215",P),o&&(b=o(b));let W=ue(E.slice(V,2*V)),q,j,X;try{q=p.fromHex(S,P),j=p.fromHex(E.slice(0,V),P),X=A.multiplyUnsafe(W)}catch{return!1}if(!P&&q.isSmallOrder())return!1;let nt=N(L,j.toRawBytes(),q.toRawBytes(),b);return j.add(q.multiplyUnsafe(nt)).subtract(X).clearCofactor().equals(p.ZERO)}return A._setWindowSize(8),{CURVE:t,getPublicKey:F,sign:O,verify:I,ExtendedPoint:p,utils:{getExtendedPublicKey:k,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,b=p.BASE){return b._setWindowSize(E),b.multiply(BigInt(3)),b}}}}var en=BigInt(0),ic=BigInt(1);function X0(r){return Jt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function ef(r){let t=X0(r),{P:e}=t,n=x=>Q(x,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(x=>x),c=t.powPminus2||(x=>tc(x,e-BigInt(2),e));function l(x,p,A){let C=n(x*(p-A));return p=n(p-C),A=n(A+C),[p,A]}let u=(t.a-BigInt(2))/BigInt(4);function f(x,p){Tt("u",x,en,e),Tt("scalar",p,en,e);let A=p,C=x,T=ic,B=en,_=x,k=ic,F=en,N;for(let $=BigInt(o-1);$>=en;$--){let I=A>>$⁣F^=I,N=l(F,T,_),T=N[0],_=N[1],N=l(F,B,k),B=N[0],k=N[1],F=I;let R=T+B,E=n(R*R),b=T-B,S=n(b*b),v=E-S,L=_+k,P=_-k,V=n(P*R),W=n(L*b),q=V+W,j=V-W;_=n(q*q),k=n(C*n(j*j)),T=n(E*S),B=n(v*(E+n(u*v)))}N=l(F,T,_),T=N[0],_=N[1],N=l(F,B,k),B=N[0],k=N[1];let O=c(B);return n(T*O)}function h(x){return Ne(n(x),s)}function m(x){let p=it("u coordinate",x,s);return i===32&&(p[31]&=127),ue(p)}function w(x){let p=it("scalar",x),A=p.length;if(A!==s&&A!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${A}`);return ue(a(p))}function g(x,p){let A=m(p),C=w(x),T=f(A,C);if(T===en)throw new Error("Invalid private or public key received");return h(T)}let d=h(t.Gu);function y(x){return g(x,d)}return{scalarMult:g,scalarMultBase:y,getSharedSecret:(x,p)=>g(x,p),getPublicKey:x=>y(x),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:d}}var Mn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),rf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Ov=BigInt(0),J0=BigInt(1),nf=BigInt(2),Q0=BigInt(3),tg=BigInt(5),eg=BigInt(8);function of(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Mn,a=r*r%s*r%s,c=at(a,nf,s)*a%s,l=at(c,J0,s)*r%s,u=at(l,tg,s)*l%s,f=at(u,t,s)*u%s,h=at(f,e,s)*f%s,m=at(h,n,s)*h%s,w=at(m,o,s)*m%s,g=at(w,o,s)*m%s,d=at(g,t,s)*u%s;return{pow_p_5_8:at(d,nf,s)*r%s,b2:a}}function sf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function rg(r,t){let e=Mn,n=Q(t*t*t,e),o=Q(n*n*t,e),s=of(r*o).pow_p_5_8,i=Q(r*n*s,e),a=Q(t*i*i,e),c=i,l=Q(i*rf,e),u=a===r,f=a===Q(-r,e),h=a===Q(-r*rf,e);return u&&(i=c),(f||h)&&(i=l),Zu(i,e)&&(i=Q(-i,e)),{isValid:u||f,value:i}}var ng=nr(Mn,void 0,!0),og={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:ng,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:eg,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Dn,randomBytes:Br,adjustScalarBytes:sf,uvRatio:rg},rn=tf(og);var Hn=ef({P:Mn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Mn,{pow_p_5_8:e,b2:n}=of(r);return Q(at(e,Q0,t)*n,t)},adjustScalarBytes:sf,randomBytes:Br});var nn=32,De=64,as=32;function af(){let r=rn.utils.randomPrivateKey(),t=rn.getPublicKey(r);return{privateKey:ff(r,t),publicKey:t}}function cf(r){if(r.length!==as)throw new TypeError('"seed" must be 32 bytes in length.');if(!(r instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, or Uint8Array.');let t=r,e=rn.getPublicKey(t);return{privateKey:ff(t,e),publicKey:e}}function lf(r,t){let e=r.subarray(0,as);return rn.sign(t instanceof Uint8Array?t:t.subarray(),e)}function uf(r,t,e){return rn.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function ff(r,t){let e=new Uint8Array(De);for(let n=0;n<as;n++)e[n]=r[n],e[as+n]=t[n];return e}var Mt={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw Object.assign(new Error("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api"),{code:"ERR_MISSING_WEB_CRYPTO"});return t}};var ac={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function hf(r){let t=r?.algorithm??"AES-GCM",e=r?.keyLength??16,n=r?.nonceLength??12,o=r?.digest??"SHA-256",s=r?.saltLength??16,i=r?.iterations??32767,a=Mt.get();e*=8;async function c(f,h){let m=a.getRandomValues(new Uint8Array(s)),w=a.getRandomValues(new Uint8Array(n)),g={name:t,iv:w};typeof h=="string"&&(h=Z(h));let d;if(h.length===0){d=await a.subtle.importKey("jwk",ac,{name:"AES-GCM"},!0,["encrypt"]);try{let x={name:"PBKDF2",salt:m,iterations:i,hash:{name:o}},p=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(x,p,{name:t,length:e},!0,["encrypt"])}catch{d=await a.subtle.importKey("jwk",ac,{name:"AES-GCM"},!0,["encrypt"])}}else{let x={name:"PBKDF2",salt:m,iterations:i,hash:{name:o}},p=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(x,p,{name:t,length:e},!0,["encrypt"])}let y=await a.subtle.encrypt(g,d,f);return yt([m,g.iv,new Uint8Array(y)])}async function l(f,h){let m=f.subarray(0,s),w=f.subarray(s,s+n),g=f.subarray(s+n),d={name:t,iv:w};typeof h=="string"&&(h=Z(h));let y;if(h.length===0)try{let p={name:"PBKDF2",salt:m,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(p,A,{name:t,length:e},!0,["decrypt"])}catch{y=await a.subtle.importKey("jwk",ac,{name:"AES-GCM"},!0,["decrypt"])}else{let p={name:"PBKDF2",salt:m,iterations:i,hash:{name:o}},A=await a.subtle.importKey("raw",h,{name:"PBKDF2"},!1,["deriveKey"]);y=await a.subtle.deriveKey(p,A,{name:t,length:e},!0,["decrypt"])}let x=await a.subtle.decrypt(d,y,g);return new Uint8Array(x)}return{encrypt:c,decrypt:l}}async function on(r,t){let n=await hf().encrypt(r,t);return Ei.encode(n)}var ft;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(ft||(ft={}));var cc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(cc||(cc={}));(function(r){r.codec=()=>br(cc)})(ft||(ft={}));var we;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:o.Type=ft.codec().decode(e);break;case 2:o.Data=e.bytes();break;default:e.skipType(i&7);break}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(we||(we={}));var be;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),ft.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:o.Type=ft.codec().decode(e);break;case 2:o.Data=e.bytes();break;default:e.skipType(i&7);break}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(be||(be={}));var Vn=class{_key;constructor(t){this._key=sn(t,nn)}verify(t,e){return uf(this._key,e,t)}marshal(){return this._key}get bytes(){return we.encode({Type:ft.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Xt(t)?t.then(({bytes:e})=>e):t.bytes}},Tr=class{_key;_publicKey;constructor(t,e){this._key=sn(t,De),this._publicKey=sn(e,nn)}sign(t){return lf(this._key,t)}get public(){return new Vn(this._publicKey)}marshal(){return this._key}get bytes(){return be.encode({Type:ft.Ed25519,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=kt.digest(this.bytes),e;return Xt(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let t=Ie.digest(this.public.bytes);return pt.encode(t.bytes).substring(1)}async export(t,e="libp2p-key"){if(e==="libp2p-key")return on(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function ag(r){if(r.length>De){r=sn(r,De+nn);let n=r.subarray(0,De),o=r.subarray(De,r.length);return new Tr(n,o)}r=sn(r,De);let t=r.subarray(0,De),e=r.subarray(nn);return new Tr(t,e)}function cg(r){return r=sn(r,nn),new Vn(r)}async function lg(){let{privateKey:r,publicKey:t}=af();return new Tr(r,t)}async function df(r){let{privateKey:t,publicKey:e}=cf(r);return new Tr(t,e)}function sn(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new D(`Key must be a Uint8Array of length ${t}, got ${r.length}`,"ERR_INVALID_KEY_TYPE");return r}var bc={};xt(bc,{MAX_RSA_KEY_SIZE:()=>Xn,RsaPrivateKey:()=>fn,RsaPublicKey:()=>Zn,fromJwk:()=>Pg,generateKeyPair:()=>Og,unmarshalRsaPrivateKey:()=>yc,unmarshalRsaPublicKey:()=>Ug});function Cr(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Br(r)}var cr={};xt(cr,{exportToPem:()=>Tg,importFromPem:()=>Cg,jwkToPkcs1:()=>Ig,jwkToPkix:()=>kg,pkcs1ToJwk:()=>Bg,pkixToJwk:()=>_g});var ls=class extends Xr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Ar(t);let n=ce(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return Zr(this),this.iHash.update(t),this}digestInto(t){Zr(this),Yr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},or=(r,t,e)=>new ls(r,t).update(e).digest();or.create=(r,t)=>new ls(r,t);function ug(r,t,e,n){Ar(r);let o=Ku({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Je(s),Je(i),Je(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=ce(t),l=ce(e),u=new Uint8Array(i),f=or.create(r,c),h=f._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:f,PRFSalt:h}}function fg(r,t,e,n,o){return r.destroy(),t.destroy(),n&&n.destroy(),o.fill(0),e}async function uc(r,t,e,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=ug(r,t,e,n),u,f=new Uint8Array(4),h=Jr(f),m=new Uint8Array(c.outputLen);for(let w=1,g=0;g<s;w++,g+=c.outputLen){let d=a.subarray(g,g+c.outputLen);h.setInt32(0,w,!1),(u=l._cloneInto(u)).update(f).digestInto(m),d.set(m.subarray(0,d.length)),await Vu(o-1,i,()=>{c._cloneInto(u).update(m).digestInto(m);for(let y=0;y<d.length;y++)d[y]^=m[y]})}return fg(c,l,a,u,m)}var Y=xd(pf());function Nr(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function sr(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*t);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function hs(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function hc(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=Nr(e,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,Nr(s,8)-n}function mf(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=sr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=sr(t,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function gf(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function $t(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var fA=Math.log(2);function ds(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function dc(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function He(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var Kn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return dc(this.items)}},Fn=[new Uint8Array([1])],yf="0123456789";var ln="",de=new ArrayBuffer(0),pc=new Uint8Array(0),$n="EndOfContent",bf="OCTET STRING",xf="BIT STRING";function Ve(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?Y.BufferSourceConverter.toUint8Array(s.valueHex):pc}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!He(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",de)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:Y.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Pe=class{constructor({blockLength:t=0,error:e=ln,warnings:n=[],valueBeforeDecode:o=pc}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=Y.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:Y.Convert.ToHex(this.valueBeforeDecodeView)}}};Pe.NAME="baseBlock";var Ut=class extends Pe{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Ut.NAME="valueBlock";var ps=class extends Ve(Pe){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?Y.BufferSourceConverter.toUint8Array(t.valueHex):pc,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",de}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=sr(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=Y.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let h=new Uint8Array(u);for(let m=0;m<l.length;m++)h[m]=l[m];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let h=0;h<c;h++)f[h]=l[h];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=Nr(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};ps.NAME="identificationBlock";var ms=class extends Pe{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=Y.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=Nr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=sr(this.length,8);if(o.byteLength>127)return this.error="Too big length",de;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};ms.NAME="lengthBlock";var M={},Ct=class extends Pe{constructor({name:t=ln,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new ps(o),this.lenBlock=new ms(o),this.valueBlock=s?new s(o):new Ut(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(t,e){let n=e||new Kn;e||Ef(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?de:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():Y.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${Y.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return gf(e,n)}};Ct.NAME="BaseBlock";function Ef(r){if(r instanceof M.Constructed)for(let t of r.valueBlock.value)Ef(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var gs=class extends Ct{constructor({value:t=ln,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};gs.NAME="BaseStringBlock";var ys=class extends Ve(Ut){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};ys.NAME="PrimitiveValueBlock";var vf,ws=class extends Ct{constructor(t={}){super(t,ys),this.idBlock.isConstructed=!1}};vf=ws;M.Primitive=vf;ws.NAME="PRIMITIVE";function xg(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function Xs(r,t=0,e=r.length){let n=t,o=new Ct({},Ut),s=new Pe;if(!He(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=Ct;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=M.EndOfContent;break;case 1:c=M.Boolean;break;case 2:c=M.Integer;break;case 3:c=M.BitString;break;case 4:c=M.OctetString;break;case 5:c=M.Null;break;case 6:c=M.ObjectIdentifier;break;case 10:c=M.Enumerated;break;case 12:c=M.Utf8String;break;case 13:c=M.RelativeObjectIdentifier;break;case 14:c=M.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=M.Sequence;break;case 17:c=M.Set;break;case 18:c=M.NumericString;break;case 19:c=M.PrintableString;break;case 20:c=M.TeletexString;break;case 21:c=M.VideotexString;break;case 22:c=M.IA5String;break;case 23:c=M.UTCTime;break;case 24:c=M.GeneralizedTime;break;case 25:c=M.GraphicString;break;case 26:c=M.VisibleString;break;case 27:c=M.GeneralString;break;case 28:c=M.UniversalString;break;case 29:c=M.CharacterString;break;case 30:c=M.BmpString;break;case 31:c=M.DATE;break;case 32:c=M.TimeOfDay;break;case 33:c=M.DateTime;break;case 34:c=M.Duration;break;default:{let l=o.idBlock.isConstructed?new M.Constructed:new M.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?M.Constructed:M.Primitive}return o=xg(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function un(r){if(!r.byteLength){let t=new Ct({},Ut);return t.error="Input buffer has zero length",{offset:-1,result:t}}return Xs(Y.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Eg(r,t){return r?1:t}var xe=class extends Ut{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=Y.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;Eg(this.isIndefiniteForm,n)>0;){let i=Xs(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===$n)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===$n?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new Kn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?de:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};xe.NAME="ConstructedValueBlock";var Af,ir=class extends Ct{constructor(t={}){super(t,xe),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
2
|
+
"use strict";var Libp2PWebrtc=(()=>{var jh=Object.create;var qn=Object.defineProperty;var Zh=Object.getOwnPropertyDescriptor;var Xh=Object.getOwnPropertyNames;var Yh=Object.getPrototypeOf,Jh=Object.prototype.hasOwnProperty;var Qh=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Nt=(r,t)=>{for(var e in t)qn(r,e,{get:t[e],enumerable:!0})},Wc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xh(t))!Jh.call(r,o)&&o!==e&&qn(r,o,{get:()=>t[o],enumerable:!(n=Zh(t,o))||n.enumerable});return r};var td=(r,t,e)=>(e=r!=null?jh(Yh(r)):{},Wc(t||!r||!r.__esModule?qn(e,"default",{value:r,enumerable:!0}):e,r)),ed=r=>Wc(qn({},"__esModule",{value:!0}),r);var Wl=Qh(Dr=>{"use strict";var Am="[object ArrayBuffer]",Ae=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===Am}static toArrayBuffer(t){return this.isArrayBuffer(t)?t:t.byteLength===t.buffer.byteLength||t.byteOffset===0&&t.byteLength===t.buffer.byteLength?t.buffer:this.toUint8Array(t.buffer).slice(t.byteOffset,t.byteOffset+t.byteLength).buffer}static toUint8Array(t){return this.toView(t,Uint8Array)}static toView(t,e){if(t.constructor===e)return t;if(this.isArrayBuffer(t))return new e(t);if(this.isArrayBufferView(t))return new e(t.buffer,t.byteOffset,t.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(t){return this.isArrayBufferView(t)||this.isArrayBuffer(t)}static isArrayBufferView(t){return ArrayBuffer.isView(t)||t&&this.isArrayBuffer(t.buffer)}static isEqual(t,e){let n=r.toUint8Array(t),o=r.toUint8Array(e);if(n.length!==o.byteLength)return!1;for(let s=0;s<n.length;s++)if(n[s]!==o[s])return!1;return!0}static concat(...t){let e;Array.isArray(t[0])&&!(t[1]instanceof Function)||Array.isArray(t[0])&&t[1]instanceof Function?e=t[0]:t[t.length-1]instanceof Function?e=t.slice(0,t.length-1):e=t;let n=0;for(let i of e)n+=i.byteLength;let o=new Uint8Array(n),s=0;for(let i of e){let a=this.toUint8Array(i);o.set(a,s),s+=a.length}return t[t.length-1]instanceof Function?this.toView(o,t[t.length-1]):o.buffer}},ba="string",Bm=/^[0-9a-f]+$/i,Im=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,Cm=/^[a-zA-Z0-9-_]+$/,yo=class{static fromString(t){let e=unescape(encodeURIComponent(t)),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);return n.buffer}static toString(t){let e=Ae.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Gt=class{static toString(t,e=!1){let n=Ae.toArrayBuffer(t),o=new DataView(n),s="";for(let i=0;i<n.byteLength;i+=2){let a=o.getUint16(i,e);s+=String.fromCharCode(a)}return s}static fromString(t,e=!1){let n=new ArrayBuffer(t.length*2),o=new DataView(n);for(let s=0;s<t.length;s++)o.setUint16(s*2,t.charCodeAt(s),e);return n}},bo=class r{static isHex(t){return typeof t===ba&&Bm.test(t)}static isBase64(t){return typeof t===ba&&Im.test(t)}static isBase64Url(t){return typeof t===ba&&Cm.test(t)}static ToString(t,e="utf8"){let n=Ae.toUint8Array(t);switch(e.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return Gt.toString(n,!0);case"utf16":case"utf16be":return Gt.toString(n);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromString(t,e="utf8"){if(!t)return new ArrayBuffer(0);switch(e.toLowerCase()){case"utf8":return this.FromUtf8String(t);case"binary":return this.FromBinary(t);case"hex":return this.FromHex(t);case"base64":return this.FromBase64(t);case"base64url":return this.FromBase64Url(t);case"utf16le":return Gt.fromString(t,!0);case"utf16":case"utf16be":return Gt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=Ae.toUint8Array(t);if(typeof btoa<"u"){let n=this.ToString(e,"binary");return btoa(n)}else return Buffer.from(e).toString("base64")}static FromBase64(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64(e))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(e)):new Uint8Array(Buffer.from(e,"base64")).buffer}static FromBase64Url(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isBase64Url(e))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(e.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(t){return this.ToBase64(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.FromBinary(t);case"utf8":return yo.fromString(t);case"utf16":case"utf16be":return Gt.fromString(t);case"utf16le":case"usc2":return Gt.fromString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToUtf8String(t,e=r.DEFAULT_UTF8_ENCODING){switch(e){case"ascii":return this.ToBinary(t);case"utf8":return yo.toString(t);case"utf16":case"utf16be":return Gt.toString(t);case"utf16le":case"usc2":return Gt.toString(t,!0);default:throw new Error(`Unknown type of encoding '${e}'`)}}static FromBinary(t){let e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);return n.buffer}static ToBinary(t){let e=Ae.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=Ae.toUint8Array(t),n="",o=e.length;for(let s=0;s<o;s++){let i=e[s];i<16&&(n+="0"),n+=i.toString(16)}return n}static FromHex(t){let e=this.formatString(t);if(!e)return new ArrayBuffer(0);if(!r.isHex(e))throw new TypeError("Argument 'hexString' is not HEX encoded");e.length%2&&(e=`0${e}`);let n=new Uint8Array(e.length/2);for(let o=0;o<e.length;o=o+2){let s=e.slice(o,o+2);n[o/2]=parseInt(s,16)}return n.buffer}static ToUtf16String(t,e=!1){return Gt.toString(t,e)}static FromUtf16String(t,e=!1){return Gt.fromString(t,e)}static Base64Padding(t){let e=4-t.length%4;if(e<4)for(let n=0;n<e;n++)t+="=";return t}static formatString(t){return t?.replace(/[\n\r\t ]/g,"")||""}};bo.DEFAULT_UTF8_ENCODING="utf8";function km(r,...t){let e=arguments[0];for(let n=1;n<arguments.length;n++){let o=arguments[n];for(let s in o)e[s]=o[s]}return e}function Tm(...r){let t=r.map(o=>o.byteLength).reduce((o,s)=>o+s),e=new Uint8Array(t),n=0;return r.map(o=>new Uint8Array(o)).forEach(o=>{for(let s of o)e[n++]=s}),e.buffer}function Nm(r,t){if(!(r&&t)||r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<r.byteLength;o++)if(e[o]!==n[o])return!1;return!0}Dr.BufferSourceConverter=Ae;Dr.Convert=bo;Dr.assign=km;Dr.combine=Tm;Dr.isEqual=Nm});var Hg={};Nt(Hg,{webRTC:()=>Og,webRTCDirect:()=>Pg});var ui=Symbol.for("@libp2p/peer-id");var zn=Symbol.for("@libp2p/transport");var qc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(qc||(qc={}));var Gn=class extends Error{static name="UnexpectedPeerError";constructor(t="Unexpected Peer"){super(t),this.name="UnexpectedPeerError"}};var tt=class extends Error{static name="InvalidParametersError";constructor(t="Invalid parameters"){super(t),this.name="InvalidParametersError"}},vr=class extends Error{static name="InvalidPublicKeyError";constructor(t="Invalid public key"){super(t),this.name="InvalidPublicKeyError"}};var jn=class extends Error{static name="ConnectionFailedError";constructor(t="Connection failed"){super(t),this.name="ConnectionFailedError"}};var Zn=class extends Error{static name="StreamResetError";constructor(t="The stream has been reset"){super(t),this.name="StreamResetError"}},tr=class extends Error{static name="StreamStateError";constructor(t="The stream is in an invalid state"){super(t),this.name="StreamStateError"}};var Xn=class extends Error{static name="InvalidMultihashError";constructor(t="Invalid Multihash"){super(t),this.name="InvalidMultihashError"}};var Yn=class extends Error{static name="InvalidMessageError";constructor(t="Invalid message"){super(t),this.name="InvalidMessageError"}};var tn=class extends Error{static name="TimeoutError";constructor(t="Timed out"){super(t),this.name="TimeoutError"}};var er=class extends Error{static name="UnsupportedKeyTypeError";constructor(t="Unsupported key type"){super(t),this.name="UnsupportedKeyTypeError"}};var Jn=(r,...t)=>{try{[...t]}catch{}};var Qn=class extends EventTarget{#t=new Map;constructor(){super(),Jn(1/0,this)}listenerCount(t){let e=this.#t.get(t);return e==null?0:e.length}addEventListener(t,e,n){super.addEventListener(t,e,n);let o=this.#t.get(t);o==null&&(o=[],this.#t.set(t,o)),o.push({callback:e,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(t,e,n){super.removeEventListener(t.toString(),e??null,n);let o=this.#t.get(t);o!=null&&(o=o.filter(({callback:s})=>s!==e),this.#t.set(t,o))}dispatchEvent(t){let e=super.dispatchEvent(t),n=this.#t.get(t.type);return n==null||(n=n.filter(({once:o})=>!o),this.#t.set(t.type,n)),e}safeDispatchEvent(t,e={}){return this.dispatchEvent(new CustomEvent(t,e))}};var Sr=Symbol.for("@libp2p/service-capabilities"),zc=Symbol.for("@libp2p/service-dependencies");var mi={};Nt(mi,{base58btc:()=>nt,base58flickr:()=>ad});var mw=new Uint8Array(0);function Gc(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function ge(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);throw new Error("Unknown type, must be binary type")}function jc(r){return new TextEncoder().encode(r)}function Zc(r){return new TextDecoder().decode(r)}function rd(r,t){if(r.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),n=0;n<e.length;n++)e[n]=255;for(var o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(e[i]!==255)throw new TypeError(s+" is ambiguous");e[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function f(x){if(x instanceof Uint8Array||(ArrayBuffer.isView(x)?x=new Uint8Array(x.buffer,x.byteOffset,x.byteLength):Array.isArray(x)&&(x=Uint8Array.from(x))),!(x instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(x.length===0)return"";for(var m=0,h=0,g=0,b=x.length;g!==b&&x[g]===0;)g++,m++;for(var p=(b-g)*u+1>>>0,B=new Uint8Array(p);g!==b;){for(var _=x[g],N=0,A=p-1;(_!==0||N<h)&&A!==-1;A--,N++)_+=256*B[A]>>>0,B[A]=_%a>>>0,_=_/a>>>0;if(_!==0)throw new Error("Non-zero carry");h=N,g++}for(var k=p-h;k!==p&&B[k]===0;)k++;for(var I=c.repeat(m);k<p;++k)I+=r.charAt(B[k]);return I}function d(x){if(typeof x!="string")throw new TypeError("Expected String");if(x.length===0)return new Uint8Array;var m=0;if(x[m]!==" "){for(var h=0,g=0;x[m]===c;)h++,m++;for(var b=(x.length-m)*l+1>>>0,p=new Uint8Array(b);x[m];){var B=e[x.charCodeAt(m)];if(B===255)return;for(var _=0,N=b-1;(B!==0||_<g)&&N!==-1;N--,_++)B+=a*p[N]>>>0,p[N]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");g=_,m++}if(x[m]!==" "){for(var A=b-g;A!==b&&p[A]===0;)A++;for(var k=new Uint8Array(h+(b-A)),I=h;A!==b;)k[I++]=p[A++];return k}}}function w(x){var m=d(x);if(m)return m;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:d,decode:w}}var nd=rd,od=nd,Yc=od;var fi=class{name;prefix;baseEncode;constructor(t,e,n){this.name=t,this.prefix=e,this.baseEncode=n}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},hi=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,e,n){if(this.name=t,this.prefix=e,e.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=e.codePointAt(0),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 Jc(this,t)}},di=class{decoders;constructor(t){this.decoders=t}or(t){return Jc(this,t)}decode(t){let e=t[0],n=this.decoders[e];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 Jc(r,t){return new di({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var pi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,e,n,o){this.name=t,this.prefix=e,this.baseEncode=n,this.baseDecode=o,this.encoder=new fi(t,e,n),this.decoder=new hi(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Ar({name:r,prefix:t,encode:e,decode:n}){return new pi(r,t,e,n)}function Pe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=Yc(e,r);return Ar({prefix:t,name:r,encode:n,decode:s=>ge(o(s))})}function sd(r,t,e,n){let o={};for(let u=0;u<t.length;++u)o[t[u]]=u;let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*e/8|0),a=0,c=0,l=0;for(let u=0;u<s;++u){let f=o[r[u]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<e|f,a+=e,a>=8&&(a-=8,i[l++]=255&c>>a)}if(a>=e||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return i}function id(r,t,e){let n=t[t.length-1]==="=",o=(1<<e)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>e;)i-=e,s+=t[o&a>>i];if(i!==0&&(s+=t[o&a<<e-i]),n)for(;s.length*e&7;)s+="=";return s}function ht({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Ar({prefix:t,name:r,encode(o){return id(o,n,e)},decode(o){return sd(o,n,e,r)}})}var nt=Pe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ad=Pe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var gi={};Nt(gi,{base32:()=>we,base32hex:()=>fd,base32hexpad:()=>dd,base32hexpadupper:()=>pd,base32hexupper:()=>hd,base32pad:()=>ld,base32padupper:()=>ud,base32upper:()=>cd,base32z:()=>md});var we=ht({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cd=ht({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ld=ht({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ud=ht({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fd=ht({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hd=ht({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),dd=ht({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),pd=ht({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),md=ht({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Xt={};Nt(Xt,{Digest:()=>rr,create:()=>Mt,decode:()=>Oe,equals:()=>yi});var gd=el,Qc=128,wd=127,yd=~wd,bd=Math.pow(2,31);function el(r,t,e){t=t||[],e=e||0;for(var n=e;r>=bd;)t[e++]=r&255|Qc,r/=128;for(;r&yd;)t[e++]=r&255|Qc,r>>>=7;return t[e]=r|0,el.bytes=e-n+1,t}var xd=wi,Ed=128,tl=127;function wi(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw wi.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&tl)<<o:(i&tl)*Math.pow(2,o),o+=7}while(i>=Ed);return wi.bytes=s-n,e}var vd=Math.pow(2,7),Sd=Math.pow(2,14),Ad=Math.pow(2,21),Bd=Math.pow(2,28),Id=Math.pow(2,35),Cd=Math.pow(2,42),kd=Math.pow(2,49),Td=Math.pow(2,56),Nd=Math.pow(2,63),_d=function(r){return r<vd?1:r<Sd?2:r<Ad?3:r<Bd?4:r<Id?5:r<Cd?6:r<kd?7:r<Td?8:r<Nd?9:10},Ld={encode:gd,decode:xd,encodingLength:_d},Rd=Ld,en=Rd;function rn(r,t=0){return[en.decode(r,t),en.decode.bytes]}function Br(r,t,e=0){return en.encode(r,t,e),t}function Ir(r){return en.encodingLength(r)}function Mt(r,t){let e=t.byteLength,n=Ir(r),o=n+Ir(e),s=new Uint8Array(o+e);return Br(r,s,0),Br(e,s,n),s.set(t,o),new rr(r,e,t,s)}function Oe(r){let t=ge(r),[e,n]=rn(t),[o,s]=rn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new rr(e,o,i,t)}function yi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&Gc(r.bytes,e.bytes)}}var rr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};function rl(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return Dd(e,bi(r),t??nt.encoder);default:return Pd(e,bi(r),t??we.encoder)}}var nl=new WeakMap;function bi(r){let t=nl.get(r);if(t==null){let e=new Map;return nl.set(r,e),e}return t}var At=class r{code;version;multihash;bytes;"/";constructor(t,e,n,o){this.code=e,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:e}=this;if(t!==nn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==Od)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(e)}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:e}=this.multihash,n=Mt(t,e);return r.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 r.equals(this,t)}static equals(t,e){let n=e;return n!=null&&t.code===n.code&&t.version===n.version&&yi(t.multihash,n.multihash)}toString(t){return rl(this,t)}toJSON(){return{"/":rl(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 e=t;if(e instanceof r)return e;if(e["/"]!=null&&e["/"]===e.bytes||e.asCID===e){let{version:n,code:o,multihash:s,bytes:i}=e;return new r(n,o,s,i??ol(n,o,s.bytes))}else if(e[Hd]===!0){let{version:n,multihash:o,code:s}=e,i=Oe(o);return r.create(n,s,i)}else return null}static create(t,e,n){if(typeof e!="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(e!==nn)throw new Error(`Version 0 CID must use dag-pb (code: ${nn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=ol(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,nn,t)}static createV1(t,e){return r.create(1,t,e)}static decode(t){let[e,n]=r.decodeFirst(t);if(n.length!==0)throw new Error("Incorrect length");return e}static decodeFirst(t){let e=r.inspectBytes(t),n=e.size-e.multihashSize,o=ge(t.subarray(n,n+e.multihashSize));if(o.byteLength!==e.multihashSize)throw new Error("Incorrect length");let s=o.subarray(e.multihashSize-e.digestSize),i=new rr(e.multihashCode,e.digestSize,s,o);return[e.version===0?r.createV0(i):r.createV1(e.codec,i),t.subarray(e.size)]}static inspectBytes(t){let e=0,n=()=>{let[f,d]=rn(t.subarray(e));return e+=d,f},o=n(),s=nn;if(o===18?(o=0,e=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=e,a=n(),c=n(),l=e+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(t,e){let[n,o]=Ud(t,e),s=r.decode(o);if(s.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return bi(s).set(n,t),s}};function Ud(r,t){switch(r[0]){case"Q":{let e=t??nt;return[nt.prefix,e.decode(`${nt.prefix}${r}`)]}case nt.prefix:{let e=t??nt;return[nt.prefix,e.decode(r)]}case we.prefix:{let e=t??we;return[we.prefix,e.decode(r)]}default:{if(t==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[r[0],t.decode(r)]}}}function Dd(r,t,e){let{prefix:n}=e;if(n!==nt.prefix)throw Error(`Cannot string encode V0 in ${e.name} encoding`);let o=t.get(n);if(o==null){let s=e.encode(r).slice(1);return t.set(n,s),s}else return o}function Pd(r,t,e){let{prefix:n}=e,o=t.get(n);if(o==null){let s=e.encode(r);return t.set(n,s),s}else return o}var nn=112,Od=18;function ol(r,t,e){let n=Ir(r),o=n+Ir(t),s=new Uint8Array(o+e.byteLength);return Br(r,s,0),Br(t,s,n),s.set(e,o),s}var Hd=Symbol.for("@ipld/js-cid/CID");var xi={};Nt(xi,{identity:()=>ye});var sl=0,Md="identity",il=ge;function Vd(r){return Mt(sl,il(r))}var ye={code:sl,name:Md,encode:il,digest:Vd};function Dt(r,t){if(r===t)return!0;if(r.byteLength!==t.byteLength)return!1;for(let e=0;e<r.byteLength;e++)if(r[e]!==t[e])return!1;return!0}function eo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Fd(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Cr(r,...t){if(!Fd(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function on(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");eo(r.outputLen),eo(r.blockLen)}function kr(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function al(r,t){Cr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var nr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var ro=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Yt=(r,t)=>r<<32-t|r>>>t;var Pw=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function cl(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function He(r){return typeof r=="string"&&(r=cl(r)),Cr(r),r}function Ei(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Cr(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}var Tr=class{clone(){return this._cloneInto()}},Ow={}.toString;function no(r){let t=n=>r().update(He(n)).digest(),e=r();return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=()=>r(),t}function sn(r=32){if(nr&&typeof nr.getRandomValues=="function")return nr.getRandomValues(new Uint8Array(r));if(nr&&typeof nr.randomBytes=="function")return nr.randomBytes(r);throw new Error("crypto.getRandomValues must be defined")}function Kd(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}var ll=(r,t,e)=>r&t^~r&e,ul=(r,t,e)=>r&t^r&e^t&e,Nr=class extends Tr{constructor(t,e,n,o){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=o,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=ro(this.buffer)}update(t){kr(this);let{view:e,buffer:n,blockLen:o}=this;t=He(t);let s=t.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=ro(t);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(t.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(e,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){kr(this),al(t,this),this.finished=!0;let{buffer:e,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;e[i++]=128,this.buffer.subarray(i).fill(0),this.padOffset>o-i&&(this.process(n,0),i=0);for(let f=i;f<o;f++)e[f]=0;Kd(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=ro(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],s)}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:e,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return t.length=o,t.pos=a,t.finished=s,t.destroyed=i,o%e&&t.buffer.set(n),t}};var oo=BigInt(4294967295),vi=BigInt(32);function fl(r,t=!1){return t?{h:Number(r&oo),l:Number(r>>vi&oo)}:{h:Number(r>>vi&oo)|0,l:Number(r&oo)|0}}function $d(r,t=!1){let e=new Uint32Array(r.length),n=new Uint32Array(r.length);for(let o=0;o<r.length;o++){let{h:s,l:i}=fl(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var Wd=(r,t)=>BigInt(r>>>0)<<vi|BigInt(t>>>0),qd=(r,t,e)=>r>>>e,zd=(r,t,e)=>r<<32-e|t>>>e,Gd=(r,t,e)=>r>>>e|t<<32-e,jd=(r,t,e)=>r<<32-e|t>>>e,Zd=(r,t,e)=>r<<64-e|t>>>e-32,Xd=(r,t,e)=>r>>>e-32|t<<64-e,Yd=(r,t)=>t,Jd=(r,t)=>r,Qd=(r,t,e)=>r<<e|t>>>32-e,tp=(r,t,e)=>t<<e|r>>>32-e,ep=(r,t,e)=>t<<e-32|r>>>64-e,rp=(r,t,e)=>r<<e-32|t>>>64-e;function np(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var op=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),sp=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,ip=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),ap=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,cp=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),lp=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var up={fromBig:fl,split:$d,toBig:Wd,shrSH:qd,shrSL:zd,rotrSH:Gd,rotrSL:jd,rotrBH:Zd,rotrBL:Xd,rotr32H:Yd,rotr32L:Jd,rotlSH:Qd,rotlSL:tp,rotlBH:ep,rotlBL:rp,add:np,add3L:op,add3H:sp,add4L:ip,add4H:ap,add5H:lp,add5L:cp},q=up;var[fp,hp]=q.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(r=>BigInt(r))),Me=new Uint32Array(80),Ve=new Uint32Array(80),Si=class extends Nr{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:t,Al:e,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:w,Gl:x,Hh:m,Hl:h}=this;return[t,e,n,o,s,i,a,c,l,u,f,d,w,x,m,h]}set(t,e,n,o,s,i,a,c,l,u,f,d,w,x,m,h){this.Ah=t|0,this.Al=e|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=w|0,this.Gl=x|0,this.Hh=m|0,this.Hl=h|0}process(t,e){for(let p=0;p<16;p++,e+=4)Me[p]=t.getUint32(e),Ve[p]=t.getUint32(e+=4);for(let p=16;p<80;p++){let B=Me[p-15]|0,_=Ve[p-15]|0,N=q.rotrSH(B,_,1)^q.rotrSH(B,_,8)^q.shrSH(B,_,7),A=q.rotrSL(B,_,1)^q.rotrSL(B,_,8)^q.shrSL(B,_,7),k=Me[p-2]|0,I=Ve[p-2]|0,V=q.rotrSH(k,I,19)^q.rotrBH(k,I,61)^q.shrSH(k,I,6),L=q.rotrSL(k,I,19)^q.rotrBL(k,I,61)^q.shrSL(k,I,6),H=q.add4L(A,L,Ve[p-7],Ve[p-16]),K=q.add4H(H,N,V,Me[p-7],Me[p-16]);Me[p]=K|0,Ve[p]=H|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:w,Fl:x,Gh:m,Gl:h,Hh:g,Hl:b}=this;for(let p=0;p<80;p++){let B=q.rotrSH(f,d,14)^q.rotrSH(f,d,18)^q.rotrBH(f,d,41),_=q.rotrSL(f,d,14)^q.rotrSL(f,d,18)^q.rotrBL(f,d,41),N=f&w^~f&m,A=d&x^~d&h,k=q.add5L(b,_,A,hp[p],Ve[p]),I=q.add5H(k,g,B,N,fp[p],Me[p]),V=k|0,L=q.rotrSH(n,o,28)^q.rotrBH(n,o,34)^q.rotrBH(n,o,39),H=q.rotrSL(n,o,28)^q.rotrBL(n,o,34)^q.rotrBL(n,o,39),K=n&s^n&a^s&a,C=o&i^o&c^i&c;g=m|0,b=h|0,m=w|0,h=x|0,w=f|0,x=d|0,{h:f,l:d}=q.add(l|0,u|0,I|0,V|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let T=q.add3L(V,H,C);n=q.add3H(T,I,L,K),o=T|0}({h:n,l:o}=q.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=q.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=q.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=q.add(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=q.add(this.Eh|0,this.El|0,f|0,d|0),{h:w,l:x}=q.add(this.Fh|0,this.Fl|0,w|0,x|0),{h:m,l:h}=q.add(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:b}=q.add(this.Hh|0,this.Hl|0,g|0,b|0),this.set(n,o,s,i,a,c,l,u,f,d,w,x,m,h,g,b)}roundClean(){Me.fill(0),Ve.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var hl=no(()=>new Si);var io={};Nt(io,{aInRange:()=>Bt,abool:()=>Jt,abytes:()=>_r,bitGet:()=>yp,bitLen:()=>ki,bitMask:()=>cn,bitSet:()=>bp,bytesToHex:()=>xe,bytesToNumberBE:()=>Ee,bytesToNumberLE:()=>Qt,concatBytes:()=>Se,createHmacDrbg:()=>Ti,ensureBytes:()=>it,equalBytes:()=>gp,hexToBytes:()=>sr,hexToNumber:()=>Ci,inRange:()=>an,isBytes:()=>Fe,memoized:()=>ir,notImplemented:()=>Ep,numberToBytesBE:()=>Ke,numberToBytesLE:()=>ve,numberToHexUnpadded:()=>or,numberToVarBytesBE:()=>mp,utf8ToBytes:()=>wp,validateObject:()=>zt});var Ii=BigInt(0),so=BigInt(1),dp=BigInt(2);function Fe(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function _r(r){if(!Fe(r))throw new Error("Uint8Array expected")}function Jt(r,t){if(typeof t!="boolean")throw new Error(`${r} must be valid boolean, got "${t}".`)}var pp=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function xe(r){_r(r);let t="";for(let e=0;e<r.length;e++)t+=pp[r[e]];return t}function or(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Ci(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var be={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function dl(r){if(r>=be._0&&r<=be._9)return r-be._0;if(r>=be._A&&r<=be._F)return r-(be._A-10);if(r>=be._a&&r<=be._f)return r-(be._a-10)}function sr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);let t=r.length,e=t/2;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(e);for(let o=0,s=0;o<e;o++,s+=2){let i=dl(r.charCodeAt(s)),a=dl(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ee(r){return Ci(xe(r))}function Qt(r){return _r(r),Ci(xe(Uint8Array.from(r).reverse()))}function Ke(r,t){return sr(r.toString(16).padStart(t*2,"0"))}function ve(r,t){return Ke(r,t).reverse()}function mp(r){return sr(or(r))}function it(r,t,e){let n;if(typeof t=="string")try{n=sr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Fe(t))n=Uint8Array.from(t);else throw new Error(`${r} must be hex string or Uint8Array`);let o=n.length;if(typeof e=="number"&&o!==e)throw new Error(`${r} expected ${e} bytes, got ${o}`);return n}function Se(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];_r(o),t+=o.length}let e=new Uint8Array(t);for(let n=0,o=0;n<r.length;n++){let s=r[n];e.set(s,o),o+=s.length}return e}function gp(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}function wp(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Ai=r=>typeof r=="bigint"&&Ii<=r;function an(r,t,e){return Ai(r)&&Ai(t)&&Ai(e)&&t<=r&&r<e}function Bt(r,t,e,n){if(!an(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function ki(r){let t;for(t=0;r>Ii;r>>=so,t+=1);return t}function yp(r,t){return r>>BigInt(t)&so}function bp(r,t,e){return r|(e?so:Ii)<<BigInt(t)}var cn=r=>(dp<<BigInt(r-1))-so,Bi=r=>new Uint8Array(r),pl=r=>Uint8Array.from(r);function Ti(r,t,e){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof t!="number"||t<2)throw new Error("qByteLen must be a number");if(typeof e!="function")throw new Error("hmacFn must be a function");let n=Bi(r),o=Bi(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Bi())=>{o=a(pl([0]),f),n=a(),f.length!==0&&(o=a(pl([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,d=[];for(;f<t;){n=a();let w=n.slice();d.push(w),f+=n.length}return Se(...d)};return(f,d)=>{i(),c(f);let w;for(;!(w=d(l()));)c();return i(),w}}var xp={bigint:r=>typeof r=="bigint",function:r=>typeof r=="function",boolean:r=>typeof r=="boolean",string:r=>typeof r=="string",stringOrUint8Array:r=>typeof r=="string"||Fe(r),isSafeInteger:r=>Number.isSafeInteger(r),array:r=>Array.isArray(r),field:(r,t)=>t.Fp.isValid(r),hash:r=>typeof r=="function"&&Number.isSafeInteger(r.outputLen)};function zt(r,t,e={}){let n=(o,s,i)=>{let a=xp[s];if(typeof a!="function")throw new Error(`Invalid validator "${s}", expected function`);let c=r[o];if(!(i&&c===void 0)&&!a(c,r))throw new Error(`Invalid param ${String(o)}=${c} (${typeof c}), expected ${s}`)};for(let[o,s]of Object.entries(t))n(o,s,!1);for(let[o,s]of Object.entries(e))n(o,s,!0);return r}var Ep=()=>{throw new Error("not implemented")};function ir(r){let t=new WeakMap;return(e,...n)=>{let o=t.get(e);if(o!==void 0)return o;let s=r(e,...n);return t.set(e,s),s}}var wt=BigInt(0),ut=BigInt(1),ar=BigInt(2),vp=BigInt(3),Ni=BigInt(4),ml=BigInt(5),gl=BigInt(8),Sp=BigInt(9),Ap=BigInt(16);function X(r,t){let e=r%t;return e>=wt?e:t+e}function _i(r,t,e){if(e<=wt||t<wt)throw new Error("Expected power/modulo > 0");if(e===ut)return wt;let n=ut;for(;t>wt;)t&ut&&(n=n*r%e),r=r*r%e,t>>=ut;return n}function at(r,t,e){let n=r;for(;t-- >wt;)n*=n,n%=e;return n}function ao(r,t){if(r===wt||t<=wt)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=X(r,t),n=t,o=wt,s=ut,i=ut,a=wt;for(;e!==wt;){let l=n/e,u=n%e,f=o-i*l,d=s-a*l;n=e,e=u,o=i,s=a,i=f,a=d}if(n!==ut)throw new Error("invert: does not exist");return X(o,t)}function Bp(r){let t=(r-ut)/ar,e,n,o;for(e=r-ut,n=0;e%ar===wt;e/=ar,n++);for(o=ar;o<r&&_i(o,t,r)!==r-ut;o++);if(n===1){let i=(r+ut)/Ni;return function(c,l){let u=c.pow(l,i);if(!c.eql(c.sqr(u),l))throw new Error("Cannot find square root");return u}}let s=(e+ut)/ar;return function(a,c){if(a.pow(c,t)===a.neg(a.ONE))throw new Error("Cannot find square root");let l=n,u=a.pow(a.mul(a.ONE,o),e),f=a.pow(c,s),d=a.pow(c,e);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let w=1;for(let m=a.sqr(d);w<l&&!a.eql(m,a.ONE);w++)m=a.sqr(m);let x=a.pow(u,ut<<BigInt(l-w-1));u=a.sqr(x),f=a.mul(f,x),d=a.mul(d,u),l=w}return f}}function Ip(r){if(r%Ni===vp){let t=(r+ut)/Ni;return function(n,o){let s=n.pow(o,t);if(!n.eql(n.sqr(s),o))throw new Error("Cannot find square root");return s}}if(r%gl===ml){let t=(r-ml)/gl;return function(n,o){let s=n.mul(o,ar),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,ar),i),l=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(l),o))throw new Error("Cannot find square root");return l}}return r%Ap,Bp(r)}var wl=(r,t)=>(X(r,t)&ut)===ut,Cp=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Li(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=Cp.reduce((n,o)=>(n[o]="function",n),t);return zt(r,e)}function kp(r,t,e){if(e<wt)throw new Error("Expected power > 0");if(e===wt)return r.ONE;if(e===ut)return t;let n=r.ONE,o=t;for(;e>wt;)e&ut&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ut;return n}function Tp(r,t){let e=new Array(t.length),n=t.reduce((s,i,a)=>r.is0(i)?s:(e[a]=s,r.mul(s,i)),r.ONE),o=r.inv(n);return t.reduceRight((s,i,a)=>r.is0(i)?s:(e[a]=r.mul(s,e[a]),r.mul(s,i)),o),e}function Ri(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function $e(r,t,e=!1,n={}){if(r<=wt)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ri(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=Ip(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:cn(o),ZERO:wt,ONE:ut,create:c=>X(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return wt<=c&&c<r},is0:c=>c===wt,isOdd:c=>(c&ut)===ut,neg:c=>X(-c,r),eql:(c,l)=>c===l,sqr:c=>X(c*c,r),add:(c,l)=>X(c+l,r),sub:(c,l)=>X(c-l,r),mul:(c,l)=>X(c*l,r),pow:(c,l)=>kp(a,c,l),div:(c,l)=>X(c*ao(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ao(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>Tp(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?ve(c,s):Ke(c,s),fromBytes:c=>{if(c.length!==s)throw new Error(`Fp.fromBytes: expected ${s}, got ${c.length}`);return e?Qt(c):Ee(c)}});return Object.freeze(a)}function yl(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let t=r.toString(2).length;return Math.ceil(t/8)}function Ui(r){let t=yl(r);return t+Math.ceil(t/2)}function bl(r,t,e=!1){let n=r.length,o=yl(t),s=Ui(t);if(n<16||n<s||n>1024)throw new Error(`expected ${s}-1024 bytes of input, got ${n}`);let i=e?Ee(r):Qt(r),a=X(i,t-ut)+ut;return e?ve(a,o):Ke(a,o)}var _p=BigInt(0),Di=BigInt(1),Pi=new WeakMap,xl=new WeakMap;function co(r,t){let e=(s,i)=>{let a=i.negate();return s?a:i},n=s=>{if(!Number.isSafeInteger(s)||s<=0||s>t)throw new Error(`Wrong window size=${s}, should be [1..${t}]`)},o=s=>{n(s);let i=Math.ceil(t/s)+1,a=2**(s-1);return{windows:i,windowSize:a}};return{constTimeNegate:e,unsafeLadder(s,i){let a=r.ZERO,c=s;for(;i>_p;)i&Di&&(a=a.add(c)),c=c.double(),i>>=Di;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),l=[],u=s,f=u;for(let d=0;d<a;d++){f=u,l.push(f);for(let w=1;w<c;w++)f=f.add(u),l.push(f);u=f.double()}return l},wNAF(s,i,a){let{windows:c,windowSize:l}=o(s),u=r.ZERO,f=r.BASE,d=BigInt(2**s-1),w=2**s,x=BigInt(s);for(let m=0;m<c;m++){let h=m*l,g=Number(a&d);a>>=x,g>l&&(g-=w,a+=Di);let b=h,p=h+Math.abs(g)-1,B=m%2!==0,_=g<0;g===0?f=f.add(e(B,i[b])):u=u.add(e(_,i[p]))}return{p:u,f}},wNAFCached(s,i,a){let c=xl.get(s)||1,l=Pi.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&Pi.set(s,a(l))),this.wNAF(c,l,i)},setWindowSize(s,i){n(i),xl.set(s,i),Pi.delete(s)}}}function lo(r,t,e,n){if(!Array.isArray(e)||!Array.isArray(n)||n.length!==e.length)throw new Error("arrays of points and scalars must have equal length");n.forEach((u,f)=>{if(!t.isValid(u))throw new Error(`wrong scalar at index ${f}`)}),e.forEach((u,f)=>{if(!(u instanceof r))throw new Error(`wrong point at index ${f}`)});let o=ki(BigInt(e.length)),s=o>12?o-3:o>4?o-2:o?2:1,i=(1<<s)-1,a=new Array(i+1).fill(r.ZERO),c=Math.floor((t.BITS-1)/s)*s,l=r.ZERO;for(let u=c;u>=0;u-=s){a.fill(r.ZERO);for(let d=0;d<n.length;d++){let w=n[d],x=Number(w>>BigInt(u)&BigInt(i));a[x]=a[x].add(e[d])}let f=r.ZERO;for(let d=a.length-1,w=r.ZERO;d>0;d--)w=w.add(a[d]),f=f.add(w);if(l=l.add(f),u!==0)for(let d=0;d<s;d++)l=l.double()}return l}function ln(r){return Li(r.Fp),zt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ri(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var te=BigInt(0),Vt=BigInt(1),uo=BigInt(2),Lp=BigInt(8),Rp={zip215:!0};function Up(r){let t=ln(r);return zt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function El(r){let t=Up(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=uo<<BigInt(a*8)-Vt,u=e.create,f=$e(t.n,t.nBitLength),d=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:te}}}),w=t.adjustScalarBytes||(E=>E),x=t.domain||((E,y,S)=>{if(Jt("phflag",S),y.length||S)throw new Error("Contexts/pre-hash are not supported");return E});function m(E,y){Bt("coordinate "+E,y,te,l)}function h(E){if(!(E instanceof p))throw new Error("ExtendedPoint expected")}let g=ir((E,y)=>{let{ex:S,ey:v,ez:R}=E,D=E.is0();y==null&&(y=D?Lp:e.inv(R));let M=u(S*y),$=u(v*y),W=u(R*y);if(D)return{x:te,y:Vt};if(W!==Vt)throw new Error("invZ was invalid");return{x:M,y:$}}),b=ir(E=>{let{a:y,d:S}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:v,ey:R,ez:D,et:M}=E,$=u(v*v),W=u(R*R),G=u(D*D),Z=u(G*G),ot=u($*y),st=u(G*u(ot+W)),lt=u(Z+u(S*u($*W)));if(st!==lt)throw new Error("bad point: equation left != right (1)");let Ut=u(v*R),gt=u(D*M);if(Ut!==gt)throw new Error("bad point: equation left != right (2)");return!0});class p{constructor(y,S,v,R){this.ex=y,this.ey=S,this.ez=v,this.et=R,m("x",y),m("y",S),m("z",v),m("t",R),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof p)throw new Error("extended point not allowed");let{x:S,y:v}=y||{};return m("x",S),m("y",v),new p(S,v,Vt,u(S*v))}static normalizeZ(y){let S=e.invertBatch(y.map(v=>v.ez));return y.map((v,R)=>v.toAffine(S[R])).map(p.fromAffine)}static msm(y,S){return lo(p,f,y,S)}_setWindowSize(y){N.setWindowSize(this,y)}assertValidity(){b(this)}equals(y){h(y);let{ex:S,ey:v,ez:R}=this,{ex:D,ey:M,ez:$}=y,W=u(S*$),G=u(D*R),Z=u(v*$),ot=u(M*R);return W===G&&Z===ot}is0(){return this.equals(p.ZERO)}negate(){return new p(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:S,ey:v,ez:R}=this,D=u(S*S),M=u(v*v),$=u(uo*u(R*R)),W=u(y*D),G=S+v,Z=u(u(G*G)-D-M),ot=W+M,st=ot-$,lt=W-M,Ut=u(Z*st),gt=u(ot*lt),Ht=u(Z*lt),me=u(st*ot);return new p(Ut,gt,me,Ht)}add(y){h(y);let{a:S,d:v}=t,{ex:R,ey:D,ez:M,et:$}=this,{ex:W,ey:G,ez:Z,et:ot}=y;if(S===BigInt(-1)){let Oc=u((D-R)*(G+W)),Hc=u((D+R)*(G-W)),li=u(Hc-Oc);if(li===te)return this.double();let Mc=u(M*uo*ot),Vc=u($*uo*Z),Fc=Vc+Mc,Kc=Hc+Oc,$c=Vc-Mc,Wh=u(Fc*li),qh=u(Kc*$c),zh=u(Fc*$c),Gh=u(li*Kc);return new p(Wh,qh,Gh,zh)}let st=u(R*W),lt=u(D*G),Ut=u($*v*ot),gt=u(M*Z),Ht=u((R+D)*(W+G)-st-lt),me=gt-Ut,Jr=gt+Ut,Qr=u(lt-S*st),Vh=u(Ht*me),Fh=u(Jr*Qr),Kh=u(Ht*Qr),$h=u(me*Jr);return new p(Vh,Fh,$h,Kh)}subtract(y){return this.add(y.negate())}wNAF(y){return N.wNAFCached(this,y,p.normalizeZ)}multiply(y){let S=y;Bt("scalar",S,Vt,n);let{p:v,f:R}=this.wNAF(S);return p.normalizeZ([v,R])[0]}multiplyUnsafe(y){let S=y;return Bt("scalar",S,te,n),S===te?_:this.equals(_)||S===Vt?this:this.equals(B)?this.wNAF(S).p:N.unsafeLadder(this,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return N.unsafeLadder(this,n).is0()}toAffine(y){return g(this,y)}clearCofactor(){let{h:y}=t;return y===Vt?this:this.multiplyUnsafe(y)}static fromHex(y,S=!1){let{d:v,a:R}=t,D=e.BYTES;y=it("pointHex",y,D),Jt("zip215",S);let M=y.slice(),$=y[D-1];M[D-1]=$&-129;let W=Qt(M),G=S?l:e.ORDER;Bt("pointHex.y",W,te,G);let Z=u(W*W),ot=u(Z-Vt),st=u(v*Z-R),{isValid:lt,value:Ut}=d(ot,st);if(!lt)throw new Error("Point.fromHex: invalid y coordinate");let gt=(Ut&Vt)===Vt,Ht=($&128)!==0;if(!S&&Ut===te&&Ht)throw new Error("Point.fromHex: x=0 and x_0=1");return Ht!==gt&&(Ut=u(-Ut)),p.fromAffine({x:Ut,y:W})}static fromPrivateKey(y){return I(y).point}toRawBytes(){let{x:y,y:S}=this.toAffine(),v=ve(S,e.BYTES);return v[v.length-1]|=y&Vt?128:0,v}toHex(){return xe(this.toRawBytes())}}p.BASE=new p(t.Gx,t.Gy,Vt,u(t.Gx*t.Gy)),p.ZERO=new p(te,Vt,Vt,te);let{BASE:B,ZERO:_}=p,N=co(p,a*8);function A(E){return X(E,n)}function k(E){return A(Qt(E))}function I(E){let y=a;E=it("private key",E,y);let S=it("hashed private key",s(E),2*y),v=w(S.slice(0,y)),R=S.slice(y,2*y),D=k(v),M=B.multiply(D),$=M.toRawBytes();return{head:v,prefix:R,scalar:D,point:M,pointBytes:$}}function V(E){return I(E).pointBytes}function L(E=new Uint8Array,...y){let S=Se(...y);return k(s(x(S,it("context",E),!!o)))}function H(E,y,S={}){E=it("message",E),o&&(E=o(E));let{prefix:v,scalar:R,pointBytes:D}=I(y),M=L(S.context,v,E),$=B.multiply(M).toRawBytes(),W=L(S.context,$,D,E),G=A(M+W*R);Bt("signature.s",G,te,n);let Z=Se($,ve(G,e.BYTES));return it("result",Z,a*2)}let K=Rp;function C(E,y,S,v=K){let{context:R,zip215:D}=v,M=e.BYTES;E=it("signature",E,2*M),y=it("message",y),D!==void 0&&Jt("zip215",D),o&&(y=o(y));let $=Qt(E.slice(M,2*M)),W,G,Z;try{W=p.fromHex(S,D),G=p.fromHex(E.slice(0,M),D),Z=B.multiplyUnsafe($)}catch{return!1}if(!D&&W.isSmallOrder())return!1;let ot=L(R,G.toRawBytes(),W.toRawBytes(),y);return G.add(W.multiplyUnsafe(ot)).subtract(Z).clearCofactor().equals(p.ZERO)}return B._setWindowSize(8),{CURVE:t,getPublicKey:V,sign:H,verify:C,ExtendedPoint:p,utils:{getExtendedPublicKey:I,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=p.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var Lr=BigInt(0),Oi=BigInt(1);function Dp(r){return zt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function vl(r){let t=Dp(r),{P:e}=t,n=b=>X(b,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(b=>b),c=t.powPminus2||(b=>_i(b,e-BigInt(2),e));function l(b,p,B){let _=n(b*(p-B));return p=n(p-_),B=n(B+_),[p,B]}let u=(t.a-BigInt(2))/BigInt(4);function f(b,p){Bt("u",b,Lr,e),Bt("scalar",p,Lr,e);let B=p,_=b,N=Oi,A=Lr,k=b,I=Oi,V=Lr,L;for(let K=BigInt(o-1);K>=Lr;K--){let C=B>>K&Oi;V^=C,L=l(V,N,k),N=L[0],k=L[1],L=l(V,A,I),A=L[0],I=L[1],V=C;let T=N+A,E=n(T*T),y=N-A,S=n(y*y),v=E-S,R=k+I,D=k-I,M=n(D*T),$=n(R*y),W=M+$,G=M-$;k=n(W*W),I=n(_*n(G*G)),N=n(E*S),A=n(v*(E+n(u*v)))}L=l(V,N,k),N=L[0],k=L[1],L=l(V,A,I),A=L[0],I=L[1];let H=c(A);return n(N*H)}function d(b){return ve(n(b),s)}function w(b){let p=it("u coordinate",b,s);return i===32&&(p[31]&=127),Qt(p)}function x(b){let p=it("scalar",b),B=p.length;if(B!==s&&B!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${B}`);return Qt(a(p))}function m(b,p){let B=w(p),_=x(b),N=f(B,_);if(N===Lr)throw new Error("Invalid private or public key received");return d(N)}let h=d(t.Gu);function g(b){return m(b,h)}return{scalarMult:m,scalarMultBase:g,getSharedSecret:(b,p)=>m(b,p),getPublicKey:b=>g(b),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:h}}var un=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Sl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),uy=BigInt(0),Pp=BigInt(1),Al=BigInt(2),Op=BigInt(3),Hp=BigInt(5),Mp=BigInt(8);function Bl(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=un,a=r*r%s*r%s,c=at(a,Al,s)*a%s,l=at(c,Pp,s)*r%s,u=at(l,Hp,s)*l%s,f=at(u,t,s)*u%s,d=at(f,e,s)*f%s,w=at(d,n,s)*d%s,x=at(w,o,s)*w%s,m=at(x,o,s)*w%s,h=at(m,t,s)*u%s;return{pow_p_5_8:at(h,Al,s)*r%s,b2:a}}function Il(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function Vp(r,t){let e=un,n=X(t*t*t,e),o=X(n*n*t,e),s=Bl(r*o).pow_p_5_8,i=X(r*n*s,e),a=X(t*i*i,e),c=i,l=X(i*Sl,e),u=a===r,f=a===X(-r,e),d=a===X(-r*Sl,e);return u&&(i=c),(f||d)&&(i=l),wl(i,e)&&(i=X(-i,e)),{isValid:u||f,value:i}}var Fp=$e(un,void 0,!0),Kp={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Mp,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:hl,randomBytes:sn,adjustScalarBytes:Il,uvRatio:Vp},Cl=El(Kp);var fn=vl({P:un,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=un,{pow_p_5_8:e,b2:n}=Bl(r);return X(at(e,Op,t)*n,t)},adjustScalarBytes:Il,randomBytes:sn});var fo=32;function kl(r,t,e){return Cl.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}var ho=class{type="Ed25519";raw;constructor(t){this.raw=Hi(t,fo)}toMultihash(){return ye.digest(Rr(this))}toCID(){return At.createV1(114,this.toMultihash())}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}verify(t,e){return kl(this.raw,e,t)}};function Mi(r){return r=Hi(r,fo),new ho(r)}function Hi(r,t){if(r=Uint8Array.from(r??[]),r.length!==t)throw new tt(`Key must be a Uint8Array of length ${t}, got ${r.length}`);return r}function yt(r=0){return new Uint8Array(r)}function bt(r=0){return new Uint8Array(r)}var Wp=Math.pow(2,7),qp=Math.pow(2,14),zp=Math.pow(2,21),Vi=Math.pow(2,28),Fi=Math.pow(2,35),Ki=Math.pow(2,42),$i=Math.pow(2,49),J=128,_t=127;function ct(r){if(r<Wp)return 1;if(r<qp)return 2;if(r<zp)return 3;if(r<Vi)return 4;if(r<Fi)return 5;if(r<Ki)return 6;if(r<$i)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Wi(r,t,e=0){switch(ct(r)){case 8:t[e++]=r&255|J,r/=128;case 7:t[e++]=r&255|J,r/=128;case 6:t[e++]=r&255|J,r/=128;case 5:t[e++]=r&255|J,r/=128;case 4:t[e++]=r&255|J,r>>>=7;case 3:t[e++]=r&255|J,r>>>=7;case 2:t[e++]=r&255|J,r>>>=7;case 1:{t[e++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return t}function Gp(r,t,e=0){switch(ct(r)){case 8:t.set(e++,r&255|J),r/=128;case 7:t.set(e++,r&255|J),r/=128;case 6:t.set(e++,r&255|J),r/=128;case 5:t.set(e++,r&255|J),r/=128;case 4:t.set(e++,r&255|J),r>>>=7;case 3:t.set(e++,r&255|J),r>>>=7;case 2:t.set(e++,r&255|J),r>>>=7;case 1:{t.set(e++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return t}function qi(r,t){let e=r[t],n=0;if(n+=e&_t,e<J||(e=r[t+1],n+=(e&_t)<<7,e<J)||(e=r[t+2],n+=(e&_t)<<14,e<J)||(e=r[t+3],n+=(e&_t)<<21,e<J)||(e=r[t+4],n+=(e&_t)*Vi,e<J)||(e=r[t+5],n+=(e&_t)*Fi,e<J)||(e=r[t+6],n+=(e&_t)*Ki,e<J)||(e=r[t+7],n+=(e&_t)*$i,e<J))return n;throw new RangeError("Could not decode varint")}function jp(r,t){let e=r.get(t),n=0;if(n+=e&_t,e<J||(e=r.get(t+1),n+=(e&_t)<<7,e<J)||(e=r.get(t+2),n+=(e&_t)<<14,e<J)||(e=r.get(t+3),n+=(e&_t)<<21,e<J)||(e=r.get(t+4),n+=(e&_t)*Vi,e<J)||(e=r.get(t+5),n+=(e&_t)*Fi,e<J)||(e=r.get(t+6),n+=(e&_t)*Ki,e<J)||(e=r.get(t+7),n+=(e&_t)*$i,e<J))return n;throw new RangeError("Could not decode varint")}function ce(r,t,e=0){return t==null&&(t=bt(ct(r))),t instanceof Uint8Array?Wi(r,t,e):Gp(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?qi(r,t):jp(r,t)}var zi=new Float32Array([-0]),We=new Uint8Array(zi.buffer);function Nl(r,t,e){zi[0]=r,t[e]=We[0],t[e+1]=We[1],t[e+2]=We[2],t[e+3]=We[3]}function _l(r,t){return We[0]=r[t],We[1]=r[t+1],We[2]=r[t+2],We[3]=r[t+3],zi[0]}var Gi=new Float64Array([-0]),Lt=new Uint8Array(Gi.buffer);function Ll(r,t,e){Gi[0]=r,t[e]=Lt[0],t[e+1]=Lt[1],t[e+2]=Lt[2],t[e+3]=Lt[3],t[e+4]=Lt[4],t[e+5]=Lt[5],t[e+6]=Lt[6],t[e+7]=Lt[7]}function Rl(r,t){return Lt[0]=r[t],Lt[1]=r[t+1],Lt[2]=r[t+2],Lt[3]=r[t+3],Lt[4]=r[t+4],Lt[5]=r[t+5],Lt[6]=r[t+6],Lt[7]=r[t+7],Gi[0]}var Zp=BigInt(Number.MAX_SAFE_INTEGER),Xp=BigInt(Number.MIN_SAFE_INTEGER),Wt=class r{lo;hi;constructor(t,e){this.lo=t|0,this.hi=e|0}toNumber(t=!1){if(!t&&this.hi>>>31>0){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(e+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(t=!1){if(t)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let e=~this.lo+1>>>0,n=~this.hi>>>0;return e===0&&(n=n+1>>>0),-(BigInt(e)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(t=!1){return this.toBigInt(t).toString()}zzEncode(){let t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this}zzDecode(){let t=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this}length(){let t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?e===0?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}static fromBigInt(t){if(t===0n)return cr;if(t<Zp&&t>Xp)return this.fromNumber(Number(t));let e=t<0n;e&&(t=-t);let n=t>>32n,o=t-(n<<32n);return e&&(n=~n|0n,o=~o|0n,++o>Ul&&(o=0n,++n>Ul&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return cr;let e=t<0;e&&(t=-t);let n=t>>>0,o=(t-n)/4294967296>>>0;return e&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}static from(t){return typeof t=="number"?r.fromNumber(t):typeof t=="bigint"?r.fromBigInt(t):typeof t=="string"?r.fromBigInt(BigInt(t)):t.low!=null||t.high!=null?new r(t.low>>>0,t.high>>>0):cr}},cr=new Wt(0,0);cr.toBigInt=function(){return 0n};cr.zzEncode=cr.zzDecode=function(){return this};cr.length=function(){return 1};var Ul=4294967296n;function Dl(r){let t=0,e=0;for(let n=0;n<r.length;++n)e=r.charCodeAt(n),e<128?t+=1:e<2048?t+=2:(e&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,t+=4):t+=3;return t}function Pl(r,t,e){if(e-t<1)return"";let o,s=[],i=0,a;for(;t<e;)a=r[t++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(a&31)<<6|r[t++]&63:a>239&&a<365?(a=((a&7)<<18|(r[t++]&63)<<12|(r[t++]&63)<<6|r[t++]&63)-65536,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[t++]&63)<<6|r[t++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function ji(r,t,e){let n=e,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?t[e++]=o:o<2048?(t[e++]=o>>6|192,t[e++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,t[e++]=o>>18|240,t[e++]=o>>12&63|128,t[e++]=o>>6&63|128,t[e++]=o&63|128):(t[e++]=o>>12|224,t[e++]=o>>6&63|128,t[e++]=o&63|128);return e-n}function re(r,t){return RangeError(`index out of range: ${r.pos} + ${t??1} > ${r.len}`)}function po(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Zi=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(t){this.buf=t,this.pos=0,this.len=t.length}uint32(){let t=4294967295;if(t=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(t=(t|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(t=(t|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return t;if((this.pos+=5)>this.len)throw this.pos=this.len,re(this,10);return t}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw re(this,4);return po(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw re(this,4);return po(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw re(this,4);let t=_l(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw re(this,4);let t=Rl(this.buf,this.pos);return this.pos+=8,t}bytes(){let t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw re(this,t);return this.pos+=t,e===n?new Uint8Array(0):this.buf.subarray(e,n)}string(){let t=this.bytes();return Pl(t,0,t.length)}skip(t){if(typeof t=="number"){if(this.pos+t>this.len)throw re(this,t);this.pos+=t}else do if(this.pos>=this.len)throw re(this);while(this.buf[this.pos++]&128);return this}skipType(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(t=this.uint32()&7)!==4;)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${t} at offset ${this.pos}`)}return this}readLongVarint(){let t=new Wt(0,0),e=0;if(this.len-this.pos>4){for(;e<4;++e)if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(this.buf[this.pos]&127)<<28)>>>0,t.hi=(t.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return t;e=0}else{for(;e<3;++e){if(this.pos>=this.len)throw re(this);if(t.lo=(t.lo|(this.buf[this.pos]&127)<<e*7)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(this.buf[this.pos++]&127)<<e*7)>>>0,t}if(this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw re(this);if(t.hi=(t.hi|(this.buf[this.pos]&127)<<e*7+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw re(this,8);let t=po(this.buf,this.pos+=4),e=po(this.buf,this.pos+=4);return new Wt(t,e)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let t=qi(this.buf,this.pos);return this.pos+=ct(t),t}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}};function Xi(r){return new Zi(r instanceof Uint8Array?r:r.subarray())}function ne(r,t,e){let n=Xi(r);return t.decode(n,void 0,e)}var Yi={};Nt(Yi,{base10:()=>Yp});var Yp=Pe({prefix:"9",name:"base10",alphabet:"0123456789"});var Ji={};Nt(Ji,{base16:()=>Jp,base16upper:()=>Qp});var Jp=ht({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Qp=ht({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Qi={};Nt(Qi,{base2:()=>tm});var tm=ht({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ta={};Nt(ta,{base256emoji:()=>sm});var Hl=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}"),em=Hl.reduce((r,t,e)=>(r[e]=t,r),[]),rm=Hl.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function nm(r){return r.reduce((t,e)=>(t+=em[e],t),"")}function om(r){let t=[];for(let e of r){let n=rm[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var sm=Ar({prefix:"\u{1F680}",name:"base256emoji",encode:nm,decode:om});var ea={};Nt(ea,{base36:()=>im,base36upper:()=>am});var im=Pe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),am=Pe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var na={};Nt(na,{base64:()=>cm,base64pad:()=>lm,base64url:()=>ra,base64urlpad:()=>um});var cm=ht({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lm=ht({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ra=ht({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),um=ht({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var oa={};Nt(oa,{base8:()=>fm});var fm=ht({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var sa={};Nt(sa,{identity:()=>hm});var hm=Ar({prefix:"\0",name:"identity",encode:r=>Zc(r),decode:r=>jc(r)});var Gy=new TextEncoder,jy=new TextDecoder;var ca={};Nt(ca,{sha256:()=>dn,sha512:()=>mm});function aa({name:r,code:t,encode:e}){return new ia(r,t,e)}var ia=class{name;code;encode;constructor(t,e,n){this.name=t,this.code=e,this.encode=n}digest(t){if(t instanceof Uint8Array){let e=this.encode(t);return e instanceof Uint8Array?Mt(this.code,e):e.then(n=>Mt(this.code,n))}else throw Error("Unknown type, must be binary type")}};function Vl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var dn=aa({name:"sha2-256",code:18,encode:Vl("SHA-256")}),mm=aa({name:"sha2-512",code:19,encode:Vl("SHA-512")});var lr={...sa,...Qi,...oa,...Yi,...Ji,...gi,...ea,...mi,...na,...ta},ib={...ca,...xi};function Kl(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var Fl=Kl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),la=Kl("ascii","a",r=>{let t="a";for(let e=0;e<r.length;e++)t+=String.fromCharCode(r[e]);return t},r=>{r=r.substring(1);let t=bt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),gm={utf8:Fl,"utf-8":Fl,hex:lr.base16,latin1:la,ascii:la,binary:la,...lr},mo=gm;function et(r,t="utf8"){let e=mo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function ua(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return bt(i);o+i>t&&(n=bt(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var ur=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function fa(){}var da=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},wm=ua();function ym(r){return globalThis.Buffer!=null?bt(r):wm(r)}var mn=class{len;head;tail;states;constructor(){this.len=0,this.head=new ur(fa,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new ur(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new pa((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(go,10,Wt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Wt.fromBigInt(t);return this._push(go,e.length(),e)}uint64Number(t){return this._push(Wi,ct(t),t)}uint64String(t){return this.uint64(BigInt(t))}int64(t){return this.uint64(t)}int64Number(t){return this.uint64Number(t)}int64String(t){return this.uint64String(t)}sint64(t){let e=Wt.fromBigInt(t).zzEncode();return this._push(go,e.length(),e)}sint64Number(t){let e=Wt.fromNumber(t).zzEncode();return this._push(go,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ha,1,t?1:0)}fixed32(t){return this._push(pn,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Wt.fromBigInt(t);return this._push(pn,4,e.lo)._push(pn,4,e.hi)}fixed64Number(t){let e=Wt.fromNumber(t);return this._push(pn,4,e.lo)._push(pn,4,e.hi)}fixed64String(t){return this.fixed64(BigInt(t))}sfixed64(t){return this.fixed64(t)}sfixed64Number(t){return this.fixed64Number(t)}sfixed64String(t){return this.fixed64String(t)}float(t){return this._push(Nl,4,t)}double(t){return this._push(Ll,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ha,1,0):this.uint32(e)._push(xm,e,t)}string(t){let e=Dl(t);return e!==0?this.uint32(e)._push(ji,e,t):this._push(ha,1,0)}fork(){return this.states=new da(this),this.head=this.tail=new ur(fa,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ur(fa,0,0),this.len=0),this}ldelim(){let t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=t.next,this.tail=e,this.len+=n),this}finish(){let t=this.head.next,e=ym(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ha(r,t,e){t[e]=r&255}function bm(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var pa=class extends ur{next;constructor(t,e){super(bm,t,e),this.next=void 0}};function go(r,t,e){for(;r.hi!==0;)t[e++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)t[e++]=r.lo&127|128,r.lo=r.lo>>>7;t[e++]=r.lo}function pn(r,t,e){t[e]=r&255,t[e+1]=r>>>8&255,t[e+2]=r>>>16&255,t[e+3]=r>>>24}function xm(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(mn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Em,t,r),this},mn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(vm,t,r),this});function Em(r,t,e){t.set(r,e)}function vm(r,t,e){r.length<40?ji(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(et(r),e)}function ma(){return new mn}function oe(r,t){let e=ma();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Ur;(function(r){r[r.VARINT=0]="VARINT",r[r.BIT64=1]="BIT64",r[r.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",r[r.START_GROUP=3]="START_GROUP",r[r.END_GROUP=4]="END_GROUP",r[r.BIT32=5]="BIT32"})(Ur||(Ur={}));function wo(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function fr(r){function t(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let e=function(s,i){let a=t(s);i.int32(a)},n=function(s){let i=s.int32();return t(i)};return wo("enum",Ur.VARINT,e,n)}function se(r,t){return wo("message",Ur.LENGTH_DELIMITED,r,t)}var xt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1"})(xt||(xt={}));var ga;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1"})(ga||(ga={}));(function(r){r.codec=()=>fr(ga)})(xt||(xt={}));var le;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),xt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=xt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>oe(e,r.codec()),r.decode=(e,n)=>ne(e,r.codec(),n)})(le||(le={}));var wa;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.Type!=null&&(n.uint32(8),xt.codec().encode(e.Type,n)),e.Data!=null&&(n.uint32(18),n.bytes(e.Data)),o.lengthDelimited!==!1&&n.ldelim()},(e,n,o={})=>{let s={},i=n==null?e.len:e.pos+n;for(;e.pos<i;){let a=e.uint32();switch(a>>>3){case 1:{s.Type=xt.codec().decode(e);break}case 2:{s.Data=e.bytes();break}default:{e.skipType(a&7);break}}}return s})),t),r.encode=e=>oe(e,r.codec()),r.decode=(e,n)=>ne(e,r.codec(),n)})(wa||(wa={}));var Bn={};Nt(Bn,{MAX_RSA_KEY_SIZE:()=>cs,generateRSAKeyPair:()=>Mu,jwkToJWKKeyPair:()=>Vu,jwkToPkcs1:()=>Hm,jwkToPkix:()=>Ia,jwkToRSAPrivateKey:()=>Hu,pkcs1ToJwk:()=>Du,pkcs1ToRSAPrivateKey:()=>Ou,pkixToJwk:()=>Pu,pkixToRSAPublicKey:()=>Ca});var Sm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),qe=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ze=new Uint32Array(64),ya=class extends Nr{constructor(){super(64,32,8,!1),this.A=qe[0]|0,this.B=qe[1]|0,this.C=qe[2]|0,this.D=qe[3]|0,this.E=qe[4]|0,this.F=qe[5]|0,this.G=qe[6]|0,this.H=qe[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)ze[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let d=ze[f-15],w=ze[f-2],x=Yt(d,7)^Yt(d,18)^d>>>3,m=Yt(w,17)^Yt(w,19)^w>>>10;ze[f]=m+ze[f-7]+x+ze[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=Yt(a,6)^Yt(a,11)^Yt(a,25),w=u+d+ll(a,c,l)+Sm[f]+ze[f]|0,m=(Yt(n,2)^Yt(n,13)^Yt(n,22))+ul(n,o,s)|0;u=l,l=c,c=a,a=i+w|0,i=s,s=o,o=n,n=w+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ze.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ue=no(()=>new ya);var j=td(Wl());function hr(r,t){let e=0;if(r.length===1)return r[0];for(let n=r.length-1;n>=0;n--)e+=r[r.length-1-n]*Math.pow(2,t*n);return e}function Ge(r,t,e=-1){let n=e,o=r,s=0,i=Math.pow(2,t);for(let a=1;a<8;a++){if(r<i){let c;if(n<0)c=new ArrayBuffer(a),s=a;else{if(n<a)return new ArrayBuffer(0);c=new ArrayBuffer(n),s=n}let l=new Uint8Array(c);for(let u=a-1;u>=0;u--){let f=Math.pow(2,u*t);l[s-u-1]=Math.floor(o/f),o-=l[s-u-1]*f}return c}i*=Math.pow(2,t)}return new ArrayBuffer(0)}function xo(...r){let t=0,e=0;for(let s of r)t+=s.length;let n=new ArrayBuffer(t),o=new Uint8Array(n);for(let s of r)o.set(s,e),e+=s.length;return o}function xa(){let r=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let a=r[0]===255&&r[1]&128,c=r[0]===0&&(r[1]&128)===0;(a||c)&&this.warnings.push("Needlessly long format")}let t=new ArrayBuffer(this.valueHex.byteLength),e=new Uint8Array(t);for(let a=0;a<this.valueHex.byteLength;a++)e[a]=0;e[0]=r[0]&128;let n=hr(e,8),o=new ArrayBuffer(this.valueHex.byteLength),s=new Uint8Array(o);for(let a=0;a<this.valueHex.byteLength;a++)s[a]=r[a];return s[0]&=127,hr(s,8)-n}function ql(r){let t=r<0?r*-1:r,e=128;for(let n=1;n<8;n++){if(t<=e){if(r<0){let i=e-t,a=Ge(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=Ge(t,8,n),s=new Uint8Array(o);if(s[0]&128){let i=o.slice(0),a=new Uint8Array(i);o=new ArrayBuffer(o.byteLength+1),s=new Uint8Array(o);for(let c=0;c<i.byteLength;c++)s[c+1]=a[c];s[0]=0}return o}e*=Math.pow(2,8)}return new ArrayBuffer(0)}function zl(r,t){if(r.byteLength!==t.byteLength)return!1;let e=new Uint8Array(r),n=new Uint8Array(t);for(let o=0;o<e.length;o++)if(e[o]!==n[o])return!1;return!0}function Ft(r,t){let e=r.toString(10);if(t<e.length)return"";let n=t-e.length,o=new Array(n);for(let i=0;i<n;i++)o[i]="0";return o.join("").concat(e)}var Fb=Math.log(2);function Eo(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Ea(r){let t=0,e=0;for(let o=0;o<r.length;o++){let s=r[o];t+=s.byteLength}let n=new Uint8Array(t);for(let o=0;o<r.length;o++){let s=r[o];n.set(new Uint8Array(s),e),e+=s.byteLength}return n.buffer}function ke(r,t,e,n){return t instanceof Uint8Array?t.byteLength?e<0?(r.error="Wrong parameter: inputOffset less than zero",!1):n<0?(r.error="Wrong parameter: inputLength less than zero",!1):t.byteLength-e-n<0?(r.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):!0:(r.error="Wrong parameter: inputBuffer has zero length",!1):(r.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}var wn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return Ea(this.items)}},gn=[new Uint8Array([1])],Gl="0123456789";var Mr="",ie=new ArrayBuffer(0),va=new Uint8Array(0),yn="EndOfContent",Zl="OCTET STRING",Xl="BIT STRING";function Te(r){var t;return t=class extends r{constructor(...n){var o;super(...n);let s=n[0]||{};this.isHexOnly=(o=s.isHexOnly)!==null&&o!==void 0?o:!1,this.valueHexView=s.valueHex?j.BufferSourceConverter.toUint8Array(s.valueHex):va}get valueHex(){return this.valueHexView.slice().buffer}set valueHex(n){this.valueHexView=new Uint8Array(n)}fromBER(n,o,s){let i=n instanceof ArrayBuffer?new Uint8Array(n):n;if(!ke(this,i,o,s))return-1;let a=o+s;return this.valueHexView=i.subarray(o,a),this.valueHexView.length?(this.blockLength=s,a):(this.warnings.push("Zero buffer length"),o)}toBER(n=!1){return this.isHexOnly?n?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",ie)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:j.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Be=class{constructor({blockLength:t=0,error:e=Mr,warnings:n=[],valueBeforeDecode:o=va}={}){this.blockLength=t,this.error=e,this.warnings=n,this.valueBeforeDecodeView=j.BufferSourceConverter.toUint8Array(o)}static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(t){this.valueBeforeDecodeView=new Uint8Array(t)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:j.Convert.ToHex(this.valueBeforeDecodeView)}}};Be.NAME="baseBlock";var Rt=class extends Be{fromBER(t,e,n){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(t,e){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}};Rt.NAME="valueBlock";var vo=class extends Te(Be){constructor({idBlock:t={}}={}){var e,n,o,s;super(),t?(this.isHexOnly=(e=t.isHexOnly)!==null&&e!==void 0?e:!1,this.valueHexView=t.valueHex?j.BufferSourceConverter.toUint8Array(t.valueHex):va,this.tagClass=(n=t.tagClass)!==null&&n!==void 0?n:-1,this.tagNumber=(o=t.tagNumber)!==null&&o!==void 0?o:-1,this.isConstructed=(s=t.isConstructed)!==null&&s!==void 0?s:!1):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(t=!1){let e=0;switch(this.tagClass){case 1:e|=0;break;case 2:e|=64;break;case 3:e|=128;break;case 4:e|=192;break;default:return this.error="Unknown tag class",ie}if(this.isConstructed&&(e|=32),this.tagNumber<31&&!this.isHexOnly){let o=new Uint8Array(1);if(!t){let s=this.tagNumber;s&=31,e|=s,o[0]=e}return o.buffer}if(!this.isHexOnly){let o=Ge(this.tagNumber,7),s=new Uint8Array(o),i=o.byteLength,a=new Uint8Array(i+1);if(a[0]=e|31,!t){for(let c=0;c<i-1;c++)a[c+1]=s[c]|128;a[i]=s[i-1]}return a.buffer}let n=new Uint8Array(this.valueHexView.byteLength+1);if(n[0]=e|31,!t){let o=this.valueHexView;for(let s=0;s<o.length-1;s++)n[s+1]=o[s]|128;n[this.valueHexView.byteLength]=o[o.length-1]}return n.buffer}fromBER(t,e,n){let o=j.BufferSourceConverter.toUint8Array(t);if(!ke(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;switch(s[0]&192){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(s[0]&32)===32,this.isHexOnly=!1;let a=s[0]&31;if(a!==31)this.tagNumber=a,this.blockLength=1;else{let c=1,l=this.valueHexView=new Uint8Array(255),u=255;for(;s[c]&128;){if(l[c-1]=s[c]&127,c++,c>=s.length)return this.error="End of input reached before message was fully decoded",-1;if(c===u){u+=255;let d=new Uint8Array(u);for(let w=0;w<l.length;w++)d[w]=l[w];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let d=0;d<c;d++)f[d]=l[d];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=hr(l,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(this.tagClass===1&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return e+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}};vo.NAME="identificationBlock";var So=class extends Be{constructor({lenBlock:t={}}={}){var e,n,o;super(),this.isIndefiniteForm=(e=t.isIndefiniteForm)!==null&&e!==void 0?e:!1,this.longFormUsed=(n=t.longFormUsed)!==null&&n!==void 0?n:!1,this.length=(o=t.length)!==null&&o!==void 0?o:0}fromBER(t,e,n){let o=j.BufferSourceConverter.toUint8Array(t);if(!ke(this,o,e,n))return-1;let s=o.subarray(e,e+n);if(s.length===0)return this.error="Zero buffer length",-1;if(s[0]===255)return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=s[0]===128,this.isIndefiniteForm)return this.blockLength=1,e+this.blockLength;if(this.longFormUsed=!!(s[0]&128),this.longFormUsed===!1)return this.length=s[0],this.blockLength=1,e+this.blockLength;let i=s[0]&127;if(i>8)return this.error="Too big integer",-1;if(i+1>s.length)return this.error="End of input reached before message was fully decoded",-1;let a=e+1,c=o.subarray(a,a+i);return c[i-1]===0&&this.warnings.push("Needlessly long encoded length"),this.length=hr(c,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=i+1,e+this.blockLength}toBER(t=!1){let e,n;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=128),e;if(this.longFormUsed){let o=Ge(this.length,8);if(o.byteLength>127)return this.error="Too big length",ie;if(e=new ArrayBuffer(o.byteLength+1),t)return e;let s=new Uint8Array(o);n=new Uint8Array(e),n[0]=o.byteLength|128;for(let i=0;i<o.byteLength;i++)n[i+1]=s[i];return e}return e=new ArrayBuffer(1),t===!1&&(n=new Uint8Array(e),n[0]=this.length),e}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}};So.NAME="lengthBlock";var P={},It=class extends Be{constructor({name:t=Mr,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new vo(o),this.lenBlock=new So(o),this.valueBlock=s?new s(o):new Rt(o)}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}toBER(t,e){let n=e||new wn;e||Yl(this);let o=this.idBlock.toBER(t);if(n.write(o),this.lenBlock.isIndefiniteForm)n.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(t,n),n.write(new ArrayBuffer(2));else{let s=this.valueBlock.toBER(t);this.lenBlock.length=s.byteLength;let i=this.lenBlock.toBER(t);n.write(i),n.write(s)}return e?ie:n.final()}toJSON(){let t={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(t="ascii"){return t==="ascii"?this.onAsciiEncoding():j.Convert.ToHex(this.toBER())}onAsciiEncoding(){return`${this.constructor.NAME} : ${j.Convert.ToHex(this.valueBlock.valueBeforeDecodeView)}`}isEqual(t){if(this===t)return!0;if(!(t instanceof this.constructor))return!1;let e=this.toBER(),n=t.toBER();return zl(e,n)}};It.NAME="BaseBlock";function Yl(r){if(r instanceof P.Constructed)for(let t of r.valueBlock.value)Yl(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var Ao=class extends It{constructor({value:t=Mr,...e}={},n){super(e,n),t&&this.fromString(t)}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}fromBER(t,e,n){let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}};Ao.NAME="BaseStringBlock";var Bo=class extends Te(Rt){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};Bo.NAME="PrimitiveValueBlock";var Jl,Io=class extends It{constructor(t={}){super(t,Bo),this.idBlock.isConstructed=!1}};Jl=Io;P.Primitive=Jl;Io.NAME="PRIMITIVE";function Lm(r,t){if(r instanceof t)return r;let e=new t;return e.idBlock=r.idBlock,e.lenBlock=r.lenBlock,e.warnings=r.warnings,e.valueBeforeDecodeView=r.valueBeforeDecodeView,e}function is(r,t=0,e=r.length){let n=t,o=new It({},Rt),s=new Be;if(!ke(s,r,t,e))return o.error=s.error,{offset:-1,result:o};if(!r.subarray(t,t+e).length)return o.error="Zero buffer length",{offset:-1,result:o};let a=o.idBlock.fromBER(r,t,e);if(o.idBlock.warnings.length&&o.warnings.concat(o.idBlock.warnings),a===-1)return o.error=o.idBlock.error,{offset:-1,result:o};if(t=a,e-=o.idBlock.blockLength,a=o.lenBlock.fromBER(r,t,e),o.lenBlock.warnings.length&&o.warnings.concat(o.lenBlock.warnings),a===-1)return o.error=o.lenBlock.error,{offset:-1,result:o};if(t=a,e-=o.lenBlock.blockLength,!o.idBlock.isConstructed&&o.lenBlock.isIndefiniteForm)return o.error="Indefinite length form used for primitive encoding form",{offset:-1,result:o};let c=It;switch(o.idBlock.tagClass){case 1:if(o.idBlock.tagNumber>=37&&o.idBlock.isHexOnly===!1)return o.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:o};switch(o.idBlock.tagNumber){case 0:if(o.idBlock.isConstructed&&o.lenBlock.length>0)return o.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:o};c=P.EndOfContent;break;case 1:c=P.Boolean;break;case 2:c=P.Integer;break;case 3:c=P.BitString;break;case 4:c=P.OctetString;break;case 5:c=P.Null;break;case 6:c=P.ObjectIdentifier;break;case 10:c=P.Enumerated;break;case 12:c=P.Utf8String;break;case 13:c=P.RelativeObjectIdentifier;break;case 14:c=P.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=P.Sequence;break;case 17:c=P.Set;break;case 18:c=P.NumericString;break;case 19:c=P.PrintableString;break;case 20:c=P.TeletexString;break;case 21:c=P.VideotexString;break;case 22:c=P.IA5String;break;case 23:c=P.UTCTime;break;case 24:c=P.GeneralizedTime;break;case 25:c=P.GraphicString;break;case 26:c=P.VisibleString;break;case 27:c=P.GeneralString;break;case 28:c=P.UniversalString;break;case 29:c=P.CharacterString;break;case 30:c=P.BmpString;break;case 31:c=P.DATE;break;case 32:c=P.TimeOfDay;break;case 33:c=P.DateTime;break;case 34:c=P.Duration;break;default:{let l=o.idBlock.isConstructed?new P.Constructed:new P.Primitive;l.idBlock=o.idBlock,l.lenBlock=o.lenBlock,l.warnings=o.warnings,o=l}}break;case 2:case 3:case 4:default:c=o.idBlock.isConstructed?P.Constructed:P.Primitive}return o=Lm(o,c),a=o.fromBER(r,t,o.lenBlock.isIndefiniteForm?e:o.lenBlock.length),o.valueBeforeDecodeView=r.subarray(n,n+o.blockLength),{offset:a,result:o}}function Sa(r){if(!r.byteLength){let t=new It({},Rt);return t.error="Input buffer has zero length",{offset:-1,result:t}}return is(j.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function Rm(r,t){return r?1:t}var fe=class extends Rt{constructor({value:t=[],isIndefiniteForm:e=!1,...n}={}){super(n),this.value=t,this.isIndefiniteForm=e}fromBER(t,e,n){let o=j.BufferSourceConverter.toUint8Array(t);if(!ke(this,o,e,n))return-1;if(this.valueBeforeDecodeView=o.subarray(e,e+n),this.valueBeforeDecodeView.length===0)return this.warnings.push("Zero buffer length"),e;let s=e;for(;Rm(this.isIndefiniteForm,n)>0;){let i=is(o,s,n);if(i.offset===-1)return this.error=i.result.error,this.warnings.concat(i.result.warnings),-1;if(s=i.offset,this.blockLength+=i.result.blockLength,n-=i.result.blockLength,this.value.push(i.result),this.isIndefiniteForm&&i.result.constructor.NAME===yn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===yn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new wn;for(let o=0;o<this.value.length;o++)this.value[o].toBER(t,n);return e?ie:n.final()}toJSON(){let t={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let e of this.value)t.value.push(e.toJSON());return t}};fe.NAME="ConstructedValueBlock";var Ql,je=class extends It{constructor(t={}){super(t,fe),this.idBlock.isConstructed=!0}fromBER(t,e,n){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let o=this.valueBlock.fromBER(t,e,this.lenBlock.isIndefiniteForm?n:this.lenBlock.length);return o===-1?(this.error=this.valueBlock.error,o):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),o)}onAsciiEncoding(){let t=[];for(let n of this.valueBlock.value)t.push(n.toString("ascii").split(`
|
3
3
|
`).map(o=>` ${o}`).join(`
|
4
4
|
`));let e=this.idBlock.tagClass===3?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return t.length?`${e} :
|
5
5
|
${t.join(`
|
6
|
-
`)}`:`${e} :`}};Af=ir;M.Constructed=Af;ir.NAME="CONSTRUCTED";var bs=class extends Ut{fromBER(t,e,n){return e}toBER(t){return de}};bs.override="EndOfContentValueBlock";var Sf,xs=class extends Ct{constructor(t={}){super(t,bs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Sf=xs;M.EndOfContent=Sf;xs.NAME=$n;var Bf,ar=class extends Ct{constructor(t={}){super(t,Ut),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};Bf=ar;M.Null=Bf;ar.NAME="NULL";var Es=class extends Ve(Ut){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=Y.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=Y.BufferSourceConverter.toUint8Array(t);return He(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,hc.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};Es.NAME="BooleanValueBlock";var If,vs=class extends Ct{constructor(t={}){super(t,Es),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};If=vs;M.Boolean=If;vs.NAME="BOOLEAN";var As=class extends Ve(xe){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=xe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===$n){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==bf)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?xe.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};As.NAME="OctetStringValueBlock";var _f,Oe=class r extends Ct{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},As),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=Xs(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?ir.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${Y.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return Y.BufferSourceConverter.concat(t)}};_f=Oe;M.OctetString=_f;Oe.NAME=bf;var Ss=class extends Ve(xe){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=xe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===$n){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==xf)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=Y.BufferSourceConverter.toUint8Array(t);if(!He(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=Xs(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,e+n}toBER(t,e){if(this.isConstructed)return xe.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return de;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ss.NAME="BitStringValueBlock";var kf,cn=class extends Ct{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ss),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return ir.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};kf=cn;M.BitString=kf;cn.NAME=xf;var Rf;function vg(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let h=u;h>=0;h--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+e[0];break;default:l=s[i-f]+e[0]}switch(e[0]=l/10,!0){case f>=s.length:s=hs(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=hs(e,s)),s}function wf(r){if(r>=Fn.length)for(let t=Fn.length;t<=r;t++){let e=new Uint8Array([0]),n=Fn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=hs(e,n)),Fn.push(n)}return Fn[r]}function Ag(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-e,!0){case l<0:e=1,s[i-u]=l+10;break;default:e=0,s[i-u]=l}if(e>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-e,l<0)e=1,s[i-u]=l+10;else{e=0,s[i-u]=l;break}return s.slice()}var Wn=class extends Ve(Ut){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=hc.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(mf(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=Ag(wf(n),e),i="-";break;default:e=vg(e,wf(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=yf.charAt(e[c]));return a===!1&&(i+=yf.charAt(0)),i}};Rf=Wn;Wn.NAME="IntegerValueBlock";Object.defineProperty(Rf.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Tf,wt=class r extends Ct{constructor(t={}){super(t,Wn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return ds(),BigInt(this.valueBlock.toString())}static fromBigInt(t){ds();let e=BigInt(t),n=new Kn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(Y.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${Y.Convert.ToHex(a)}`)+e,u=Y.BufferSourceConverter.toUint8Array(Y.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};Tf=wt;M.Integer=Tf;wt.NAME="INTEGER";var Cf,Bs=class extends wt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Cf=Bs;M.Enumerated=Cf;Bs.NAME="ENUMERATED";var Gn=class extends Ve(Ut){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=Y.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Nr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){ds();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=sr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",de;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=Y.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};Gn.NAME="sidBlock";var Is=class extends Ut{constructor({value:t=ln,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Gn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,de;e.push(o)}return dc(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new Gn;if(o>Number.MAX_SAFE_INTEGER){ds();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Is.NAME="ObjectIdentifierValueBlock";var Nf,he=class extends Ct{constructor(t={}){super(t,Is),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Nf=he;M.ObjectIdentifier=Nf;he.NAME="OBJECT IDENTIFIER";var qn=class extends Ve(Pe){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=Y.BufferSourceConverter.toUint8Array(t);if(!He(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=Nr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=sr(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",de;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=Y.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};qn.NAME="relativeSidBlock";var _s=class extends Ut{constructor({value:t=ln,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new qn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,de;n.push(s)}return dc(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new qn;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};_s.NAME="RelativeObjectIdentifierValueBlock";var Lf,ks=class extends Ct{constructor(t={}){super(t,_s),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};Lf=ks;M.RelativeObjectIdentifier=Lf;ks.NAME="RelativeObjectIdentifier";var Df,It=class extends ir{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Df=It;M.Sequence=Df;It.NAME="SEQUENCE";var Uf,Rs=class extends ir{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Uf=Rs;M.Set=Uf;Rs.NAME="SET";var Ts=class extends Ve(Ut){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=ln}toJSON(){return{...super.toJSON(),value:this.value}}};Ts.NAME="StringValueBlock";var Cs=class extends Ts{};Cs.NAME="SimpleStringValueBlock";var Ht=class extends gs{constructor({...t}={}){super(t,Cs)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,Y.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Ht.NAME="SIMPLE STRING";var Ns=class extends Ht{fromBuffer(t){this.valueBlock.valueHexView=Y.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=Y.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=Y.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(Y.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Ns.NAME="Utf8StringValueBlock";var Pf,Me=class extends Ns{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Pf=Me;M.Utf8String=Pf;Me.NAME="UTF8String";var Ls=class extends Ht{fromBuffer(t){this.valueBlock.value=Y.Convert.ToUtf16String(t),this.valueBlock.valueHexView=Y.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(Y.Convert.FromUtf16String(t))}};Ls.NAME="BmpStringValueBlock";var Of,Ds=class extends Ls{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Of=Ds;M.BmpString=Of;Ds.NAME="BMPString";var Us=class extends Ht{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=sr(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};Us.NAME="UniversalStringValueBlock";var Mf,Ps=class extends Us{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Mf=Ps;M.UniversalString=Mf;Ps.NAME="UniversalString";var Hf,Os=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Hf=Os;M.NumericString=Hf;Os.NAME="NumericString";var Vf,Ms=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Vf=Ms;M.PrintableString=Vf;Ms.NAME="PrintableString";var Ff,Hs=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Ff=Hs;M.TeletexString=Ff;Hs.NAME="TeletexString";var Kf,Vs=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Kf=Vs;M.VideotexString=Kf;Vs.NAME="VideotexString";var $f,Fs=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};$f=Fs;M.IA5String=$f;Fs.NAME="IA5String";var Wf,Ks=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Wf=Ks;M.GraphicString=Wf;Ks.NAME="GraphicString";var Gf,zn=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Gf=zn;M.VisibleString=Gf;zn.NAME="VisibleString";var qf,$s=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};qf=$s;M.GeneralString=qf;$s.NAME="GeneralString";var zf,Ws=class extends Ht{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};zf=Ws;M.CharacterString=zf;Ws.NAME="CharacterString";var jf,jn=class extends zn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,Y.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=$t(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=$t(this.month,2),e[2]=$t(this.day,2),e[3]=$t(this.hour,2),e[4]=$t(this.minute,2),e[5]=$t(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};jf=jn;M.UTCTime=jf;jn.NAME="UTCTime";var Yf,Gs=class extends jn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,h=n.indexOf("+"),m="";if(h===-1&&(h=n.indexOf("-"),f=-1),h!==-1){if(m=n.substring(h+1),n=n.substring(0,h),m.length!==2&&m.length!==4)throw new Error("Wrong input string for conversion");let w=parseInt(m.substring(0,2),10);if(isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*w,m.length===4){if(w=parseInt(m.substring(2,4),10),isNaN(w.valueOf()))throw new Error("Wrong input string for conversion");c=f*w}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push($t(this.year,4)),e.push($t(this.month,2)),e.push($t(this.day,2)),e.push($t(this.hour,2)),e.push($t(this.minute,2)),e.push($t(this.second,2)),this.millisecond!==0&&(e.push("."),e.push($t(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Yf=Gs;M.GeneralizedTime=Yf;Gs.NAME="GeneralizedTime";var Zf,qs=class extends Me{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Zf=qs;M.DATE=Zf;qs.NAME="DATE";var Xf,zs=class extends Me{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Xf=zs;M.TimeOfDay=Xf;zs.NAME="TimeOfDay";var Jf,js=class extends Me{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Jf=js;M.DateTime=Jf;js.NAME="DateTime";var Qf,Ys=class extends Me{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Qf=Ys;M.Duration=Qf;Ys.NAME="Duration";var th,Zs=class extends Me{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};th=Zs;M.TIME=th;Zs.NAME="TIME";function Bg(r){let{result:t}=un(r),e=t.valueBlock.value;return{n:G(Ee(e[1].toBigInt()),"base64url"),e:G(Ee(e[2].toBigInt()),"base64url"),d:G(Ee(e[3].toBigInt()),"base64url"),p:G(Ee(e[4].toBigInt()),"base64url"),q:G(Ee(e[5].toBigInt()),"base64url"),dp:G(Ee(e[6].toBigInt()),"base64url"),dq:G(Ee(e[7].toBigInt()),"base64url"),qi:G(Ee(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Ig(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new D("JWK was missing components","ERR_INVALID_PARAMETERS");let e=new It({value:[new wt({value:0}),wt.fromBigInt(ve(Z(r.n,"base64url"))),wt.fromBigInt(ve(Z(r.e,"base64url"))),wt.fromBigInt(ve(Z(r.d,"base64url"))),wt.fromBigInt(ve(Z(r.p,"base64url"))),wt.fromBigInt(ve(Z(r.q,"base64url"))),wt.fromBigInt(ve(Z(r.dp,"base64url"))),wt.fromBigInt(ve(Z(r.dq,"base64url"))),wt.fromBigInt(ve(Z(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function _g(r){let{result:t}=un(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:G(Ee(e[0].toBigInt()),"base64url"),e:G(Ee(e[1].toBigInt()),"base64url")}}function kg(r){if(r.n==null||r.e==null)throw new D("JWK was missing components","ERR_INVALID_PARAMETERS");let e=new It({value:[new It({value:[new he({value:"1.2.840.113549.1.1.1"}),new ar]}),new cn({valueHex:new It({value:[wt.fromBigInt(ve(Z(r.n,"base64url"))),wt.fromBigInt(ve(Z(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Ee(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),o=0,s=0;for(;o<e;)n[o]=parseInt(t.slice(s,s+2),16),o+=1,s+=2;return n}function ve(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}var Rg=16,mc=32,gc=1e4;async function Tg(r,t){let e=Mt.get(),o=new It({value:[new wt({value:0}),new It({value:[new he({value:"1.2.840.113549.1.1.1"}),new ar]}),new Oe({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=Cr(Rg),a=await uc(Dn,t,i,{c:gc,dkLen:mc}),c=Cr(16),l=await e.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),u=await e.subtle.encrypt({name:"AES-CBC",iv:c},l,s),f=new It({value:[new Oe({valueHex:i}),new wt({value:gc}),new wt({value:mc}),new It({value:[new he({value:"1.2.840.113549.2.11"}),new ar]})]}),h=new It({value:[new he({value:"1.2.840.113549.1.5.13"}),new It({value:[new It({value:[new he({value:"1.2.840.113549.1.5.12"}),f]}),new It({value:[new he({value:"2.16.840.1.101.3.4.1.42"}),new Oe({valueHex:c})]})]})]}),w=new It({value:[h,new Oe({valueHex:u})]}).toBER(),g=new Uint8Array(w,0,w.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...G(g,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
7
|
-
`)}async function Cg(r,t){let e=Mt.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=Z(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=un(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:u}=Ng(s),f=await uc(Dn,t,a,{c,dkLen:l}),h=await e.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),m=Yn(await e.subtle.decrypt({name:"AES-CBC",iv:i},h,u)),{result:w}=un(m);n=eh(w)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=Z(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=un(o);n=eh(s)}else throw new D("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return yc(n)}function Ng(r){let t=r.valueBlock.value[0];if(t.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.13")throw new D("Only pkcs5PBES2 encrypted private keys are supported","ERR_INVALID_PARAMS");let n=t.valueBlock.value[1].valueBlock.value[0];if(n.valueBlock.value[0].toString()!=="OBJECT IDENTIFIER : 1.2.840.113549.1.5.12")throw new D("Only pkcs5PBKDF2 key derivation functions are supported","ERR_INVALID_PARAMS");let s=n.valueBlock.value[1],i=Yn(s.valueBlock.value[0].getValue()),a=gc,c=mc;if(s.valueBlock.value.length===3)a=Number(s.valueBlock.value[1].toBigInt()),c=Number(s.valueBlock.value[2].toBigInt());else if(s.valueBlock.value.length===2)throw new D("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key","ERR_INVALID_PARAMS");let l=t.valueBlock.value[1].valueBlock.value[1],u=l.valueBlock.value[0].toString();if(u!=="OBJECT IDENTIFIER : 1.2.840.113549.3.7"){if(u!=="OBJECT IDENTIFIER : 1.3.14.3.2.7"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"){if(u!=="OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42")throw new D("Only AES-CBC encryption schemes are supported","ERR_INVALID_PARAMS")}}}}let f=Yn(l.valueBlock.value[1].getValue());return{cipherText:Yn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:f}}function eh(r){return Yn(r.valueBlock.value[2].getValue())}function Yn(r){return new Uint8Array(r,0,r.byteLength)}async function rh(r){let t=await Mt.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await sh(t);return{privateKey:e[0],publicKey:e[1]}}async function wc(r){let e=[await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Lg(r)],n=await sh({privateKey:e[0],publicKey:e[1]});return{privateKey:n[0],publicKey:n[1]}}async function nh(r,t){let e=await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Mt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function oh(r,t,e){let n=await Mt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Mt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function sh(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Mt.get().subtle.exportKey("jwk",r.privateKey),Mt.get().subtle.exportKey("jwk",r.publicKey)])}async function Lg(r){return Mt.get().subtle.importKey("jwk",{kty:r.kty,n:r.n,e:r.e},{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])}function Js(r){if(r.kty!=="RSA")throw new D("invalid key type","ERR_INVALID_KEY_TYPE");if(r.n==null)throw new D("invalid key modulus","ERR_INVALID_KEY_MODULUS");return Z(r.n,"base64url").length*8}var Xn=8192,Zn=class{_key;constructor(t){this._key=t}verify(t,e){return oh(this._key,e,t)}marshal(){return cr.jwkToPkix(this._key)}get bytes(){return we.encode({Type:ft.RSA,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Xt(t)?t.then(({bytes:e})=>e):t.bytes}},fn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e}genSecret(){return Cr(16)}sign(t){return nh(this._key,t)}get public(){if(this._publicKey==null)throw new D("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Zn(this._publicKey)}marshal(){return cr.jwkToPkcs1(this._key)}get bytes(){return be.encode({Type:ft.RSA,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Xt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return G(t,"base58btc")}async export(t,e="pkcs-8"){if(e==="pkcs-8")return cr.exportToPem(this,t);if(e==="libp2p-key")return on(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function yc(r){let t=cr.pkcs1ToJwk(r);if(Js(t)>Xn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await wc(t);return new fn(e.privateKey,e.publicKey)}function Ug(r){let t=cr.pkixToJwk(r);if(Js(t)>Xn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Zn(t)}async function Pg(r){if(Js(r)>Xn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await wc(r);return new fn(t.privateKey,t.publicKey)}async function Og(r){if(r>Xn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await rh(r);return new fn(t.privateKey,t.publicKey)}var Sc={};xt(Sc,{Secp256k1PrivateKey:()=>Qn,Secp256k1PublicKey:()=>Jn,generateKeyPair:()=>Zg,unmarshalSecp256k1PrivateKey:()=>jg,unmarshalSecp256k1PublicKey:()=>Yg});var Mg=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),lr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ur=new Uint32Array(64),xc=class extends Qr{constructor(){super(64,32,8,!1),this.A=lr[0]|0,this.B=lr[1]|0,this.C=lr[2]|0,this.D=lr[3]|0,this.E=lr[4]|0,this.F=lr[5]|0,this.G=lr[6]|0,this.H=lr[7]|0}get(){let{A:t,B:e,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[t,e,n,o,s,i,a,c]}set(t,e,n,o,s,i,a,c){this.A=t|0,this.B=e|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(t,e){for(let f=0;f<16;f++,e+=4)ur[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let h=ur[f-15],m=ur[f-2],w=ae(h,7)^ae(h,18)^h>>>3,g=ae(m,17)^ae(m,19)^m>>>10;ur[f]=g+ur[f-7]+w+ur[f-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let h=ae(a,6)^ae(a,11)^ae(a,25),m=u+h+$u(a,c,l)+Mg[f]+ur[f]|0,g=(ae(n,2)^ae(n,13)^ae(n,22))+Wu(n,o,s)|0;u=l,l=c,c=a,a=i+m|0,i=s,s=o,o=n,n=m+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){ur.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var hn=Qo(()=>new xc);function ih(r){r.lowS!==void 0&&le("lowS",r.lowS),r.prehash!==void 0&&le("prehash",r.prehash)}function Hg(r){let t=On(r);Jt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Vg,hexToBytes:Fg}=rs,Fe={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Fe;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=Ir(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?Ir(o.length/2|128):"";return`${Ir(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=Fe,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Fe;if(r<Ke)throw new t("integer: negative integers are not allowed");let e=Ir(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Fe;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return Vg(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Fe,o=typeof r=="string"?Fg(r):r;tn(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Fe,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},Ke=BigInt(0),_t=BigInt(1),OA=BigInt(2),ah=BigInt(3),MA=BigInt(4);function Kg(r){let t=Hg(r),{Fp:e}=t,n=nr(t.n,t.nBitLength),o=t.toBytes||((g,d,y)=>{let x=d.toAffine();return Le(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),s=t.fromBytes||(g=>{let d=g.subarray(1),y=e.fromBytes(d.subarray(0,e.BYTES)),x=e.fromBytes(d.subarray(e.BYTES,2*e.BYTES));return{x:y,y:x}});function i(g){let{a:d,b:y}=t,x=e.sqr(g),p=e.mul(x,g);return e.add(e.add(p,e.mul(g,d)),y)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(g){return Un(g,_t,t.n)}function c(g){let{allowedPrivateKeyLengths:d,nByteLength:y,wrapPrivateKey:x,n:p}=t;if(d&&typeof g!="bigint"){if(er(g)&&(g=Te(g)),typeof g!="string"||!d.includes(g.length))throw new Error("Invalid key");g=g.padStart(y*2,"0")}let A;try{A=typeof g=="bigint"?g:Ce(it("private key",g,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof g}`)}return x&&(A=Q(A,p)),Tt("private key",A,_t,p),A}function l(g){if(!(g instanceof h))throw new Error("ProjectivePoint expected")}let u=kr((g,d)=>{let{px:y,py:x,pz:p}=g;if(e.eql(p,e.ONE))return{x:y,y:x};let A=g.is0();d==null&&(d=A?e.ONE:e.inv(p));let C=e.mul(y,d),T=e.mul(x,d),B=e.mul(p,d);if(A)return{x:e.ZERO,y:e.ZERO};if(!e.eql(B,e.ONE))throw new Error("invZ was invalid");return{x:C,y:T}}),f=kr(g=>{if(g.is0()){if(t.allowInfinityPoint&&!e.is0(g.py))return;throw new Error("bad point: ZERO")}let{x:d,y}=g.toAffine();if(!e.isValid(d)||!e.isValid(y))throw new Error("bad point: x or y not FE");let x=e.sqr(y),p=i(d);if(!e.eql(x,p))throw new Error("bad point: equation left != right");if(!g.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class h{constructor(d,y,x){if(this.px=d,this.py=y,this.pz=x,d==null||!e.isValid(d))throw new Error("x required");if(y==null||!e.isValid(y))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(d){let{x:y,y:x}=d||{};if(!d||!e.isValid(y)||!e.isValid(x))throw new Error("invalid affine point");if(d instanceof h)throw new Error("projective point not allowed");let p=A=>e.eql(A,e.ZERO);return p(y)&&p(x)?h.ZERO:new h(y,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(d){let y=e.invertBatch(d.map(x=>x.pz));return d.map((x,p)=>x.toAffine(y[p])).map(h.fromAffine)}static fromHex(d){let y=h.fromAffine(s(it("pointHex",d)));return y.assertValidity(),y}static fromPrivateKey(d){return h.BASE.multiply(c(d))}static msm(d,y){return ss(h,n,d,y)}_setWindowSize(d){w.setWindowSize(this,d)}assertValidity(){f(this)}hasEvenY(){let{y:d}=this.toAffine();if(e.isOdd)return!e.isOdd(d);throw new Error("Field doesn't support isOdd")}equals(d){l(d);let{px:y,py:x,pz:p}=this,{px:A,py:C,pz:T}=d,B=e.eql(e.mul(y,T),e.mul(A,p)),_=e.eql(e.mul(x,T),e.mul(C,p));return B&&_}negate(){return new h(this.px,e.neg(this.py),this.pz)}double(){let{a:d,b:y}=t,x=e.mul(y,ah),{px:p,py:A,pz:C}=this,T=e.ZERO,B=e.ZERO,_=e.ZERO,k=e.mul(p,p),F=e.mul(A,A),N=e.mul(C,C),O=e.mul(p,A);return O=e.add(O,O),_=e.mul(p,C),_=e.add(_,_),T=e.mul(d,_),B=e.mul(x,N),B=e.add(T,B),T=e.sub(F,B),B=e.add(F,B),B=e.mul(T,B),T=e.mul(O,T),_=e.mul(x,_),N=e.mul(d,N),O=e.sub(k,N),O=e.mul(d,O),O=e.add(O,_),_=e.add(k,k),k=e.add(_,k),k=e.add(k,N),k=e.mul(k,O),B=e.add(B,k),N=e.mul(A,C),N=e.add(N,N),k=e.mul(N,O),T=e.sub(T,k),_=e.mul(N,F),_=e.add(_,_),_=e.add(_,_),new h(T,B,_)}add(d){l(d);let{px:y,py:x,pz:p}=this,{px:A,py:C,pz:T}=d,B=e.ZERO,_=e.ZERO,k=e.ZERO,F=t.a,N=e.mul(t.b,ah),O=e.mul(y,A),$=e.mul(x,C),I=e.mul(p,T),R=e.add(y,x),E=e.add(A,C);R=e.mul(R,E),E=e.add(O,$),R=e.sub(R,E),E=e.add(y,p);let b=e.add(A,T);return E=e.mul(E,b),b=e.add(O,I),E=e.sub(E,b),b=e.add(x,p),B=e.add(C,T),b=e.mul(b,B),B=e.add($,I),b=e.sub(b,B),k=e.mul(F,E),B=e.mul(N,I),k=e.add(B,k),B=e.sub($,k),k=e.add($,k),_=e.mul(B,k),$=e.add(O,O),$=e.add($,O),I=e.mul(F,I),E=e.mul(N,E),$=e.add($,I),I=e.sub(O,I),I=e.mul(F,I),E=e.add(E,I),O=e.mul($,E),_=e.add(_,O),O=e.mul(b,E),B=e.mul(R,B),B=e.sub(B,O),O=e.mul(R,$),k=e.mul(b,k),k=e.add(k,O),new h(B,_,k)}subtract(d){return this.add(d.negate())}is0(){return this.equals(h.ZERO)}wNAF(d){return w.wNAFCached(this,d,h.normalizeZ)}multiplyUnsafe(d){Tt("scalar",d,Ke,t.n);let y=h.ZERO;if(d===Ke)return y;if(d===_t)return this;let{endo:x}=t;if(!x)return w.unsafeLadder(this,d);let{k1neg:p,k1:A,k2neg:C,k2:T}=x.splitScalar(d),B=y,_=y,k=this;for(;A>Ke||T>Ke;)A&_t&&(B=B.add(k)),T&_t&&(_=_.add(k)),k=k.double(),A>>=_t,T>>=_t;return p&&(B=B.negate()),C&&(_=_.negate()),_=new h(e.mul(_.px,x.beta),_.py,_.pz),B.add(_)}multiply(d){let{endo:y,n:x}=t;Tt("scalar",d,_t,x);let p,A;if(y){let{k1neg:C,k1:T,k2neg:B,k2:_}=y.splitScalar(d),{p:k,f:F}=this.wNAF(T),{p:N,f:O}=this.wNAF(_);k=w.constTimeNegate(C,k),N=w.constTimeNegate(B,N),N=new h(e.mul(N.px,y.beta),N.py,N.pz),p=k.add(N),A=F.add(O)}else{let{p:C,f:T}=this.wNAF(d);p=C,A=T}return h.normalizeZ([p,A])[0]}multiplyAndAddUnsafe(d,y,x){let p=h.BASE,A=(T,B)=>B===Ke||B===_t||!T.equals(p)?T.multiplyUnsafe(B):T.multiply(B),C=A(this,y).add(A(d,x));return C.is0()?void 0:C}toAffine(d){return u(this,d)}isTorsionFree(){let{h:d,isTorsionFree:y}=t;if(d===_t)return!0;if(y)return y(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:d,clearCofactor:y}=t;return d===_t?this:y?y(h,this):this.multiplyUnsafe(t.h)}toRawBytes(d=!0){return le("isCompressed",d),this.assertValidity(),o(h,this,d)}toHex(d=!0){return le("isCompressed",d),Te(this.toRawBytes(d))}}h.BASE=new h(t.Gx,t.Gy,e.ONE),h.ZERO=new h(e.ZERO,e.ONE,e.ZERO);let m=t.nBitLength,w=os(h,t.endo?Math.ceil(m/2):m);return{CURVE:t,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function $g(r){let t=On(r);return Jt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function ch(r){let t=$g(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(I){return Q(I,n)}function a(I){return ns(I,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Kg({...t,toBytes(I,R,E){let b=R.toAffine(),S=e.toBytes(b.x),v=Le;return le("isCompressed",E),E?v(Uint8Array.from([R.hasEvenY()?2:3]),S):v(Uint8Array.from([4]),S,e.toBytes(b.y))},fromBytes(I){let R=I.length,E=I[0],b=I.subarray(1);if(R===o&&(E===2||E===3)){let S=Ce(b);if(!Un(S,_t,e.ORDER))throw new Error("Point is not on curve");let v=u(S),L;try{L=e.sqrt(v)}catch(W){let q=W instanceof Error?": "+W.message:"";throw new Error("Point is not on curve"+q)}let P=(L&_t)===_t;return(E&1)===1!==P&&(L=e.neg(L)),{x:S,y:L}}else if(R===s&&E===4){let S=e.fromBytes(b.subarray(0,e.BYTES)),v=e.fromBytes(b.subarray(e.BYTES,2*e.BYTES));return{x:S,y:v}}else throw new Error(`Point of length ${R} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),h=I=>Te(rr(I,t.nByteLength));function m(I){let R=n>>_t;return I>R}function w(I){return m(I)?i(-I):I}let g=(I,R,E)=>Ce(I.slice(R,E));class d{constructor(R,E,b){this.r=R,this.s=E,this.recovery=b,this.assertValidity()}static fromCompact(R){let E=t.nByteLength;return R=it("compactSignature",R,E*2),new d(g(R,0,E),g(R,E,2*E))}static fromDER(R){let{r:E,s:b}=Fe.toSig(it("DER",R));return new d(E,b)}assertValidity(){Tt("r",this.r,_t,n),Tt("s",this.s,_t,n)}addRecoveryBit(R){return new d(this.r,this.s,R)}recoverPublicKey(R){let{r:E,s:b,recovery:S}=this,v=T(it("msgHash",R));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let L=S===2||S===3?E+t.n:E;if(L>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let P=S&1?"03":"02",V=c.fromHex(P+h(L)),W=a(L),q=i(-v*W),j=i(b*W),X=c.BASE.multiplyAndAddUnsafe(V,q,j);if(!X)throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return m(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return _r(this.toDERHex())}toDERHex(){return Fe.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return _r(this.toCompactHex())}toCompactHex(){return h(this.r)+h(this.s)}}let y={isValidPrivateKey(I){try{return l(I),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let I=nc(t.n);return Ju(t.randomBytes(I),t.n)},precompute(I=8,R=c.BASE){return R._setWindowSize(I),R.multiply(BigInt(3)),R}};function x(I,R=!0){return c.fromPrivateKey(I).toRawBytes(R)}function p(I){let R=er(I),E=typeof I=="string",b=(R||E)&&I.length;return R?b===o||b===s:E?b===2*o||b===2*s:I instanceof c}function A(I,R,E=!0){if(p(I))throw new Error("first arg must be private key");if(!p(R))throw new Error("second arg must be public key");return c.fromHex(R).multiply(l(I)).toRawBytes(E)}let C=t.bits2int||function(I){let R=Ce(I),E=I.length*8-t.nBitLength;return E>0?R>>BigInt(E):R},T=t.bits2int_modN||function(I){return i(C(I))},B=Pn(t.nBitLength);function _(I){return Tt(`num < 2^${t.nBitLength}`,I,Ke,B),rr(I,t.nByteLength)}function k(I,R,E=F){if(["recovered","canonical"].some(ot=>ot in E))throw new Error("sign() legacy options not supported");let{hash:b,randomBytes:S}=t,{lowS:v,prehash:L,extraEntropy:P}=E;v==null&&(v=!0),I=it("msgHash",I),ih(E),L&&(I=it("prehashed msgHash",b(I)));let V=T(I),W=l(R),q=[_(W),_(V)];if(P!=null&&P!==!1){let ot=P===!0?S(e.BYTES):P;q.push(it("extraEntropy",ot))}let j=Le(...q),X=V;function nt(ot){let ct=C(ot);if(!f(ct))return;let Pt=a(ct),bt=c.BASE.multiply(ct).toAffine(),Vt=i(bt.x);if(Vt===Ke)return;let Ae=i(Pt*i(X+Vt*W));if(Ae===Ke)return;let yn=(bt.x===Vt?0:2)|Number(bt.y&_t),wn=Ae;return v&&m(Ae)&&(wn=w(Ae),yn^=1),new d(Vt,wn,yn)}return{seed:j,k2sig:nt}}let F={lowS:t.lowS,prehash:!1},N={lowS:t.lowS,prehash:!1};function O(I,R,E=F){let{seed:b,k2sig:S}=k(I,R,E),v=t;return Ja(v.hash.outputLen,v.nByteLength,v.hmac)(b,S)}c.BASE._setWindowSize(8);function $(I,R,E,b=N){let S=I;if(R=it("msgHash",R),E=it("publicKey",E),"strict"in b)throw new Error("options.strict was renamed to lowS");ih(b);let{lowS:v,prehash:L}=b,P,V;try{if(typeof S=="string"||er(S))try{P=d.fromDER(S)}catch(bt){if(!(bt instanceof Fe.Err))throw bt;P=d.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:bt,s:Vt}=S;P=new d(bt,Vt)}else throw new Error("PARSE");V=c.fromHex(E)}catch(bt){if(bt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&P.hasHighS())return!1;L&&(R=t.hash(R));let{r:W,s:q}=P,j=T(R),X=a(q),nt=i(j*X),ot=i(W*X),ct=c.BASE.multiplyAndAddUnsafe(V,nt,ot)?.toAffine();return ct?i(ct.x)===W:!1}return{CURVE:t,getPublicKey:x,getSharedSecret:A,sign:O,verify:$,ProjectivePoint:c,Signature:d,utils:y}}function Wg(r){return{hash:r,hmac:(t,...e)=>or(r,t,Wa(...e)),randomBytes:Br}}function lh(r,t){let e=n=>ch({...r,...Wg(n)});return Object.freeze({...e(t),create:e})}var hh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),uh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Gg=BigInt(1),Ec=BigInt(2),fh=(r,t)=>(r+t/Ec)/t;function qg(r){let t=hh,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=at(u,e,t)*u%t,h=at(f,e,t)*u%t,m=at(h,Ec,t)*l%t,w=at(m,o,t)*m%t,g=at(w,s,t)*w%t,d=at(g,a,t)*g%t,y=at(d,c,t)*d%t,x=at(y,a,t)*g%t,p=at(x,e,t)*u%t,A=at(p,i,t)*w%t,C=at(A,n,t)*l%t,T=at(C,Ec,t);if(!vc.eql(vc.sqr(T),r))throw new Error("Cannot find square root");return T}var vc=nr(hh,void 0,void 0,{sqrt:qg}),pe=lh({a:BigInt(0),b:BigInt(7),Fp:vc,n:uh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=uh,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Gg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=fh(s*r,t),c=fh(-n*r,t),l=Q(r-a*e-c*o,t),u=Q(-a*n-c*s,t),f=l>i,h=u>i;if(f&&(l=t-l),h&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:h,k2:u}}}},hn),zA=BigInt(0);var jA=pe.ProjectivePoint;function dh(){return pe.utils.randomPrivateKey()}function ph(r,t){let e=kt.digest(t instanceof Uint8Array?t:t.subarray());if(Xt(e))return e.then(({digest:n})=>pe.sign(n,r).toDERRawBytes()).catch(n=>{throw new D(String(n),"ERR_INVALID_INPUT")});try{return pe.sign(e.digest,r).toDERRawBytes()}catch(n){throw new D(String(n),"ERR_INVALID_INPUT")}}function mh(r,t,e){let n=kt.digest(e instanceof Uint8Array?e:e.subarray());if(Xt(n))return n.then(({digest:o})=>pe.verify(t,o,r)).catch(o=>{throw new D(String(o),"ERR_INVALID_INPUT")});try{return pe.verify(t,n.digest,r)}catch(o){throw new D(String(o),"ERR_INVALID_INPUT")}}function gh(r){return pe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function yh(r){try{pe.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}function Ac(r){try{pe.ProjectivePoint.fromHex(r)}catch(t){throw new D(String(t),"ERR_INVALID_PUBLIC_KEY")}}function wh(r){try{return pe.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}var Jn=class{_key;constructor(t){Ac(t),this._key=t}verify(t,e){return mh(this._key,e,t)}marshal(){return gh(this._key)}get bytes(){return we.encode({Type:ft.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}async hash(){let t=kt.digest(this.bytes),e;return Xt(t)?{bytes:e}=await t:e=t.bytes,e}},Qn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e??wh(t),yh(this._key),Ac(this._publicKey)}sign(t){return ph(this._key,t)}get public(){return new Jn(this._publicKey)}marshal(){return this._key}get bytes(){return be.encode({Type:ft.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return Et(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Xt(t)?t.then(({bytes:e})=>e):t.bytes}async id(){let t=await this.public.hash();return G(t,"base58btc")}async export(t,e="libp2p-key"){if(e==="libp2p-key")return on(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function jg(r){return new Qn(r)}function Yg(r){return new Jn(r)}async function Zg(){let r=dh();return new Qn(r)}var Lr={rsa:bc,ed25519:lc,secp256k1:Sc};function bh(r){let t=Object.keys(Lr).join(" / ");return new D(`invalid or unsupported key type ${r}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function xh(r){let t=we.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case ft.RSA:return Lr.rsa.unmarshalRsaPublicKey(e);case ft.Ed25519:return Lr.ed25519.unmarshalEd25519PublicKey(e);case ft.Secp256k1:return Lr.secp256k1.unmarshalSecp256k1PublicKey(e);default:throw bh(t.Type??"unknown")}}async function Bc(r){let t=be.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case ft.RSA:return Lr.rsa.unmarshalRsaPrivateKey(e);case ft.Ed25519:return Lr.ed25519.unmarshalEd25519PrivateKey(e);case ft.Secp256k1:return Lr.secp256k1.unmarshalSecp256k1PrivateKey(e);default:throw bh(t.Type??"RSA")}}function Ic(){let r=dt(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function Eh(){let r=Ic(),t=Ic();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function Xg(r){return r[Symbol.asyncIterator]!=null}function Jg(...r){let t=[];for(let e of r)Xg(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=je({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var vh=Jg;function Ah(r,...t){if(r==null)throw new Error("Empty pipeline");if(_c(r)){let n=r;r=()=>n.source}else if(Bh(r)||Sh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&_c(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)_c(e[n])&&(e[n]=ty(e[n]));return Qg(...e)}var Qg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Sh=r=>r?.[Symbol.asyncIterator]!=null,Bh=r=>r?.[Symbol.iterator]!=null,_c=r=>r==null?!1:r.sink!=null&&r.source!=null,ty=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=je({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(Sh(s))o=async function*(){yield*s,n.end()};else if(Bh(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return vh(n,o())}return r.source};var dn=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Qs(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function kc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function Rc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Wt(r,...t){if(!Rc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function Tc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function Ih(r,t){Wt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var $e=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),_h=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ey=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!ey)throw new Error("Non little-endian hardware is not supported");function ry(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ti(r){if(typeof r=="string")r=ry(r);else if(Rc(r))r=ei(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function kh(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Rh(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var Cc=(r,t)=>(Object.assign(t,r),t);function Nc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function ei(r){return Uint8Array.from(r)}function We(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var Ch=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),ny=Ch("expand 16-byte k"),oy=Ch("expand 32-byte k"),sy=$e(ny),Nh=$e(oy),AS=Nh.slice();function H(r,t){return r<<t|r>>>32-t}function Lc(r){return r.byteOffset%4===0}var ri=64,iy=16,Lh=2**32-1,Th=new Uint32Array;function ay(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(ri),u=$e(l),f=Lc(o)&&Lc(s),h=f?$e(o):Th,m=f?$e(s):Th;for(let w=0;w<c;i++){if(r(t,e,n,u,i,a),i>=Lh)throw new Error("arx: counter overflow");let g=Math.min(ri,c-w);if(f&&g===ri){let d=w/4;if(w%4!==0)throw new Error("arx: invalid block position");for(let y=0,x;y<iy;y++)x=d+y,m[x]=h[x]^u[y];w+=ri;continue}for(let d=0,y;d<g;d++)y=w+d,s[y]=o[y]^l[d];w+=g}}function Dc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=kh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Qs(o),Qs(i),kc(s),kc(e),(a,c,l,u,f=0)=>{Wt(a),Wt(c),Wt(l);let h=l.length;if(u===void 0&&(u=new Uint8Array(h)),Wt(u),Qs(f),f<0||f>=Lh)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);let m=[],w=a.length,g,d;if(w===32)m.push(g=ei(a)),d=Nh;else if(w===16&&e)g=new Uint8Array(32),g.set(a),g.set(a,16),d=sy,m.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${w}`);Lc(c)||m.push(c=ei(c));let y=$e(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(d,y,$e(c.subarray(0,16)),y),c=c.subarray(16)}let x=16-o;if(x!==c.length)throw new Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){let A=new Uint8Array(12);A.set(c,s?0:12-c.length),c=A,m.push(c)}let p=$e(c);return ay(r,d,y,p,l,u,f,i),We(...m),u}}var Nt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,Uc=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=ti(t),Wt(t,32);let e=Nt(t,0),n=Nt(t,2),o=Nt(t,4),s=Nt(t,6),i=Nt(t,8),a=Nt(t,10),c=Nt(t,12),l=Nt(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Nt(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],h=i[5],m=i[6],w=i[7],g=i[8],d=i[9],y=Nt(t,e+0),x=Nt(t,e+2),p=Nt(t,e+4),A=Nt(t,e+6),C=Nt(t,e+8),T=Nt(t,e+10),B=Nt(t,e+12),_=Nt(t,e+14),k=s[0]+(y&8191),F=s[1]+((y>>>13|x<<3)&8191),N=s[2]+((x>>>10|p<<6)&8191),O=s[3]+((p>>>7|A<<9)&8191),$=s[4]+((A>>>4|C<<12)&8191),I=s[5]+(C>>>1&8191),R=s[6]+((C>>>14|T<<2)&8191),E=s[7]+((T>>>11|B<<5)&8191),b=s[8]+((B>>>8|_<<8)&8191),S=s[9]+(_>>>5|o),v=0,L=v+k*a+F*(5*d)+N*(5*g)+O*(5*w)+$*(5*m);v=L>>>13,L&=8191,L+=I*(5*h)+R*(5*f)+E*(5*u)+b*(5*l)+S*(5*c),v+=L>>>13,L&=8191;let P=v+k*c+F*a+N*(5*d)+O*(5*g)+$*(5*w);v=P>>>13,P&=8191,P+=I*(5*m)+R*(5*h)+E*(5*f)+b*(5*u)+S*(5*l),v+=P>>>13,P&=8191;let V=v+k*l+F*c+N*a+O*(5*d)+$*(5*g);v=V>>>13,V&=8191,V+=I*(5*w)+R*(5*m)+E*(5*h)+b*(5*f)+S*(5*u),v+=V>>>13,V&=8191;let W=v+k*u+F*l+N*c+O*a+$*(5*d);v=W>>>13,W&=8191,W+=I*(5*g)+R*(5*w)+E*(5*m)+b*(5*h)+S*(5*f),v+=W>>>13,W&=8191;let q=v+k*f+F*u+N*l+O*c+$*a;v=q>>>13,q&=8191,q+=I*(5*d)+R*(5*g)+E*(5*w)+b*(5*m)+S*(5*h),v+=q>>>13,q&=8191;let j=v+k*h+F*f+N*u+O*l+$*c;v=j>>>13,j&=8191,j+=I*a+R*(5*d)+E*(5*g)+b*(5*w)+S*(5*m),v+=j>>>13,j&=8191;let X=v+k*m+F*h+N*f+O*u+$*l;v=X>>>13,X&=8191,X+=I*c+R*a+E*(5*d)+b*(5*g)+S*(5*w),v+=X>>>13,X&=8191;let nt=v+k*w+F*m+N*h+O*f+$*u;v=nt>>>13,nt&=8191,nt+=I*l+R*c+E*a+b*(5*d)+S*(5*g),v+=nt>>>13,nt&=8191;let ot=v+k*g+F*w+N*m+O*h+$*f;v=ot>>>13,ot&=8191,ot+=I*u+R*l+E*c+b*a+S*(5*d),v+=ot>>>13,ot&=8191;let ct=v+k*d+F*g+N*w+O*m+$*h;v=ct>>>13,ct&=8191,ct+=I*f+R*u+E*l+b*c+S*a,v+=ct>>>13,ct&=8191,v=(v<<2)+v|0,v=v+L|0,L=v&8191,v=v>>>13,P+=v,s[0]=L,s[1]=P,s[2]=V,s[3]=W,s[4]=q,s[5]=j,s[6]=X,s[7]=nt,s[8]=ot,s[9]=ct}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;We(n)}update(t){Tc(this);let{buffer:e,blockLen:n}=this;t=ti(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){We(this.h,this.r,this.buffer,this.pad)}digestInto(t){Tc(this),Ih(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function cy(r){let t=(n,o)=>r(o).update(ti(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Dh=cy(r=>new Uc(r));function Oh(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],h=t[2],m=t[3],w=t[4],g=t[5],d=t[6],y=t[7],x=o,p=e[0],A=e[1],C=e[2],T=i,B=a,_=c,k=l,F=u,N=f,O=h,$=m,I=w,R=g,E=d,b=y,S=x,v=p,L=A,P=C;for(let W=0;W<s;W+=2)T=T+F|0,S=H(S^T,16),I=I+S|0,F=H(F^I,12),T=T+F|0,S=H(S^T,8),I=I+S|0,F=H(F^I,7),B=B+N|0,v=H(v^B,16),R=R+v|0,N=H(N^R,12),B=B+N|0,v=H(v^B,8),R=R+v|0,N=H(N^R,7),_=_+O|0,L=H(L^_,16),E=E+L|0,O=H(O^E,12),_=_+O|0,L=H(L^_,8),E=E+L|0,O=H(O^E,7),k=k+$|0,P=H(P^k,16),b=b+P|0,$=H($^b,12),k=k+$|0,P=H(P^k,8),b=b+P|0,$=H($^b,7),T=T+N|0,P=H(P^T,16),E=E+P|0,N=H(N^E,12),T=T+N|0,P=H(P^T,8),E=E+P|0,N=H(N^E,7),B=B+O|0,S=H(S^B,16),b=b+S|0,O=H(O^b,12),B=B+O|0,S=H(S^B,8),b=b+S|0,O=H(O^b,7),_=_+$|0,v=H(v^_,16),I=I+v|0,$=H($^I,12),_=_+$|0,v=H(v^_,8),I=I+v|0,$=H($^I,7),k=k+F|0,L=H(L^k,16),R=R+L|0,F=H(F^R,12),k=k+F|0,L=H(L^k,8),R=R+L|0,F=H(F^R,7);let V=0;n[V++]=i+T|0,n[V++]=a+B|0,n[V++]=c+_|0,n[V++]=l+k|0,n[V++]=u+F|0,n[V++]=f+N|0,n[V++]=h+O|0,n[V++]=m+$|0,n[V++]=w+I|0,n[V++]=g+R|0,n[V++]=d+E|0,n[V++]=y+b|0,n[V++]=x+S|0,n[V++]=p+v|0,n[V++]=A+L|0,n[V++]=C+P|0}function ly(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],h=t[4],m=t[5],w=t[6],g=t[7],d=e[0],y=e[1],x=e[2],p=e[3];for(let C=0;C<20;C+=2)o=o+c|0,d=H(d^o,16),h=h+d|0,c=H(c^h,12),o=o+c|0,d=H(d^o,8),h=h+d|0,c=H(c^h,7),s=s+l|0,y=H(y^s,16),m=m+y|0,l=H(l^m,12),s=s+l|0,y=H(y^s,8),m=m+y|0,l=H(l^m,7),i=i+u|0,x=H(x^i,16),w=w+x|0,u=H(u^w,12),i=i+u|0,x=H(x^i,8),w=w+x|0,u=H(u^w,7),a=a+f|0,p=H(p^a,16),g=g+p|0,f=H(f^g,12),a=a+f|0,p=H(p^a,8),g=g+p|0,f=H(f^g,7),o=o+l|0,p=H(p^o,16),w=w+p|0,l=H(l^w,12),o=o+l|0,p=H(p^o,8),w=w+p|0,l=H(l^w,7),s=s+u|0,d=H(d^s,16),g=g+d|0,u=H(u^g,12),s=s+u|0,d=H(d^s,8),g=g+d|0,u=H(u^g,7),i=i+f|0,y=H(y^i,16),h=h+y|0,f=H(f^h,12),i=i+f|0,y=H(y^i,8),h=h+y|0,f=H(f^h,7),a=a+c|0,x=H(x^a,16),m=m+x|0,c=H(c^m,12),a=a+c|0,x=H(x^a,8),m=m+x|0,c=H(c^m,7);let A=0;n[A++]=o,n[A++]=s,n[A++]=i,n[A++]=a,n[A++]=d,n[A++]=y,n[A++]=x,n[A++]=p}var uy=Dc(Oh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),fy=Dc(Oh,{counterRight:!1,counterLength:8,extendNonceFn:ly,allowShortKeys:!1});var hy=new Uint8Array(16),Uh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(hy.subarray(e))},dy=new Uint8Array(32);function Ph(r,t,e,n,o){let s=r(t,e,dy),i=Dh.create(s);o&&Uh(i,o),Uh(i,n);let a=new Uint8Array(16),c=_h(a);Nc(c,0,BigInt(o?o.length:0),!0),Nc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return We(s,a),l}var Mh=r=>(t,e,n)=>(Wt(t,32),Wt(e),{encrypt(s,i){let a=s.length,c=a+16;i?Wt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=Ph(r,t,e,i.subarray(0,-16),n);return i.set(l,a),We(l),i},decrypt(s,i){let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?Wt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=Ph(r,t,e,l,n);if(!Rh(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),We(f),i}}),Pc=Cc({blockSize:64,nonceLength:12,tagLength:16},Mh(uy)),NS=Cc({blockSize:64,nonceLength:24,tagLength:16},Mh(fy));function Vh(r,t,e){return Ar(r),e===void 0&&(e=new Uint8Array(r.outputLen)),or(r,ce(e),ce(t))}var Oc=new Uint8Array([0]),Hh=new Uint8Array;function Fh(r,t,e,n=32){if(Ar(r),Je(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=Hh);let s=new Uint8Array(o*r.outputLen),i=or.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Oc[0]=l+1,a.update(l===0?Hh:c).update(e).update(Oc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Oc.fill(0),s.slice(0,n)}var Mc={hashSHA256(r){return hn(r.subarray())},getHKDF(r,t){let e=Vh(hn,t,r),o=Fh(hn,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=Hn.utils.randomPrivateKey();return{publicKey:Hn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Hn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return Hn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Pc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Pc(n,t,e).decrypt(r.subarray(),o)}};var Kh=Mc;function $h(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var pn=r=>{let t=At(2);return t[0]=r>>8,t[1]=r,t};pn.bytes=2;var to=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};to.bytes=2;function Wh(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Hc(r,t){!t.enabled||!dn||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${G(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${G(r.privateKey,"hex")}`)):t("Missing local static keys."))}function Vc(r,t){!t.enabled||!dn||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${G(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${G(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Gh(r,t){!t.enabled||!dn||t(r?`REMOTE_STATIC_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote static public key.")}function Fc(r,t){!t.enabled||!dn||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Kc(r,t,e){!e.enabled||!dn||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&G(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&G(t.k,"hex")}`))}var ni=class r extends Error{code;constructor(t="Unexpected Peer"){super(t),this.code=r.code}static code="ERR_UNEXPECTED_PEER"},mn=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var py=0,my=4294967295,gy="Cipherstate has reached maximum n, a new handshake must be performed",oi=class{n;bytes;view;constructor(t=py){this.n=t,this.bytes=vt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>my)throw new Error(gy)}};var Dr=vt(0),gn=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new oi(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},$c=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Z(e,"utf-8");this.h=yy(t,n),this.ck=this.h,this.cs=new gn(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new gn(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new lt(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,Dr);return[new gn(this.crypto,t),new gn(this.crypto,e)]}},Wc=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new $c(e,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},eo=class extends Wc{writeMessageA(t){return new lt(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new lt(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new lt(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new mn(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new mn(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new mn(`handshake stage 2 validation fail: ${e.message}`)}}};function yy(r,t){if(t.length<=32){let e=vt(32);return e.set(t),e}else return r.hash(t)}var si;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(si||(si={}));var ro;(function(r){let t;r.codec=()=>(t==null&&(t=ie((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),si.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:vt(0),identitySig:vt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=si.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>se(e,r.codec()),r.decode=e=>oe(e,r.codec())})(ro||(ro={}));async function Gc(r,t,e){let n=await r.sign(qh(t));return ro.encode({identityKey:r.public.bytes,identitySig:n,extensions:e})}async function qc(r,t,e){try{let n=ro.decode(r);if(e){let i=e.subarray();if(!Et(i,n.identityKey))throw new Error(`Payload identity key ${G(n.identityKey,"hex")} does not match expected remote identity key ${G(i,"hex")}`)}if(!t)throw new Error("Remote static does not exist");let o=qh(t);if(!await xh(n.identityKey).verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new ni(n.message)}}function qh(r){let t=Z("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function zh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Gc(s,a.publicKey,l),f=new eo({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Hc(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Dr),t),e.trace("Stage 0 - Initiator finished sending first message."),Vc(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let h=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),Fc(f.re,e),Gh(f.rs,e),e.trace("Initiator going to check remote's signature...");let m=await qc(h,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[w,g]=f.ss.split();return Kc(w,g,e),{payload:m,encrypt:d=>w.encryptWithAd(Dr,d),decrypt:(d,y)=>g.decryptWithAd(Dr,d,y)}}async function jh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Gc(s,a.publicKey,l),f=new eo({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Hc(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),Fc(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Vc(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let h=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let m=await qc(h,f.rs,c),[w,g]=f.ss.split();return Kc(w,g,e),{payload:m,encrypt:d=>g.encryptWithAd(Dr,d),decrypt:(d,y)=>w.decryptWithAd(Dr,d,y)}}var Zh=16;function Xh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),t?.encryptedPackets.increment(),yield new lt(pn(i.byteLength),i)}}}function Jh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-Zh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Zh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var ii=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??Kh;this.crypto=$h(c),this.extensions=o,this.metrics=a?Wh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??vt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Ur]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(...t){let{localPeer:e,connection:n,remotePeer:o,signal:s}=this.parseArgs(t),i=Ln(n,{lengthEncoder:pn,lengthDecoder:to,maxDataLength:65535});if(!e.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let a=await Bc(e.privateKey),c=o?.publicKey,l=await this.performHandshakeInitiator(i,a,c,{signal:s}),u=await this.createSecureConnection(i,l);return n.source=u.source,n.sink=u.sink,{conn:n,remoteExtensions:l.payload.extensions,remotePeer:await Mi(l.payload.identityKey)}}async secureInbound(...t){let{localPeer:e,connection:n,remotePeer:o,signal:s}=this.parseArgs(t),i=Ln(n,{lengthEncoder:pn,lengthDecoder:to,maxDataLength:65535});if(!e.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let a=await Bc(e.privateKey),c=o?.publicKey,l=await this.performHandshakeResponder(i,a,c,{signal:s}),u=await this.createSecureConnection(i,l);return n.source=u.source,n.sink=u.sink,{conn:n,remoteExtensions:l.payload.extensions,remotePeer:await Mi(l.payload.identityKey)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await zh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await jh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=Eh(),s=t.unwrap();return await Ah(n,Xh(e,this.metrics),s,i=>gr(i,{lengthDecoder:to}),Jh(e,this.metrics),n),o}parseArgs(t){return ol(t[0])?{localPeer:t[0],connection:t[1],remotePeer:t[2]}:{localPeer:this.components.peerId,connection:t[0],remotePeer:t[1]?.remotePeer,signal:t[1]?.signal}}};function Qh(r={}){return t=>new ii(t,r)}var zc=Object.values(me).map(r=>r.decoder).reduce((r,t)=>r.or(t));function td(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:by(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw wa("","no fingerprint on local certificate");return n}var wy=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function by(r){return r.match(wy)?.groups?.fingerprint}function xy(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function ai(r){let e=r.stringTuples().filter(n=>n[0]===nd).map(n=>n[1])[0];if(e===void 0||e==="")throw Ao(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function jc(r){return te.decode(zc.decode(r))}function Ey(r){let t=jc(ai(r)),e=Yc(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw wa(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Yc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw Ql(r)}}function vy(r,t){let{host:e,port:n}=r.toOptions(),o=xy(r),[s]=Ey(r);return`v=0
|
6
|
+
`)}`:`${e} :`}};Ql=je;P.Constructed=Ql;je.NAME="CONSTRUCTED";var Co=class extends Rt{fromBER(t,e,n){return e}toBER(t){return ie}};Co.override="EndOfContentValueBlock";var tu,ko=class extends It{constructor(t={}){super(t,Co),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};tu=ko;P.EndOfContent=tu;ko.NAME=yn;var eu,Pr=class extends It{constructor(t={}){super(t,Rt),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(t,e,n){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=n,e+n>t.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):e+n}toBER(t,e){let n=new ArrayBuffer(2);if(!t){let o=new Uint8Array(n);o[0]=5,o[1]=0}return e&&e.write(n),n}onAsciiEncoding(){return`${this.constructor.NAME}`}};eu=Pr;P.Null=eu;Pr.NAME="NULL";var To=class extends Te(Rt){constructor({value:t,...e}={}){super(e),e.valueHex?this.valueHexView=j.BufferSourceConverter.toUint8Array(e.valueHex):this.valueHexView=new Uint8Array(1),t&&(this.value=t)}get value(){for(let t of this.valueHexView)if(t>0)return!0;return!1}set value(t){this.valueHexView[0]=t?255:0}fromBER(t,e,n){let o=j.BufferSourceConverter.toUint8Array(t);return ke(this,o,e,n)?(this.valueHexView=o.subarray(e,e+n),n>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,xa.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};To.NAME="BooleanValueBlock";var ru,No=class extends It{constructor(t={}){super(t,To),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}getValue(){return this.valueBlock.value}setValue(t){this.valueBlock.value=t}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}};ru=No;P.Boolean=ru;No.NAME="BOOLEAN";var _o=class extends Te(fe){constructor({isConstructed:t=!1,...e}={}){super(e),this.isConstructed=t}fromBER(t,e,n){let o=0;if(this.isConstructed){if(this.isHexOnly=!1,o=fe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let s=0;s<this.value.length;s++){let i=this.value[s].constructor.NAME;if(i===yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==Zl)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,o=super.fromBER(t,e,n),this.blockLength=n;return o}toBER(t,e){return this.isConstructed?fe.prototype.toBER.call(this,t,e):t?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}};_o.NAME="OctetStringValueBlock";var nu,Lo=class r extends It{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},_o),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(t,e,n){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,n===0)return this.idBlock.error.length===0&&(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length===0&&(this.blockLength+=this.lenBlock.blockLength),e;if(!this.valueBlock.isConstructed){let s=(t instanceof ArrayBuffer?new Uint8Array(t):t).subarray(e,e+n);try{if(s.byteLength){let i=is(s,0,s.byteLength);i.offset!==-1&&i.offset===n&&(this.valueBlock.value=[i.result])}}catch{}}return super.fromBER(t,e,n)}onAsciiEncoding(){return this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length?je.prototype.onAsciiEncoding.call(this):`${this.constructor.NAME} : ${j.Convert.ToHex(this.valueBlock.valueHexView)}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let t=[];for(let e of this.valueBlock.value)e instanceof r&&t.push(e.valueBlock.valueHexView);return j.BufferSourceConverter.concat(t)}};nu=Lo;P.OctetString=nu;Lo.NAME=Zl;var Ro=class extends Te(fe){constructor({unusedBits:t=0,isConstructed:e=!1,...n}={}){super(n),this.unusedBits=t,this.isConstructed=e,this.blockLength=this.valueHexView.byteLength}fromBER(t,e,n){if(!n)return e;let o=-1;if(this.isConstructed){if(o=fe.prototype.fromBER.call(this,t,e,n),o===-1)return o;for(let a of this.value){let c=a.constructor.NAME;if(c===yn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==Xl)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let l=a.valueBlock;if(this.unusedBits>0&&l.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=l.unusedBits}return o}let s=j.BufferSourceConverter.toUint8Array(t);if(!ke(this,s,e,n))return-1;let i=s.subarray(e,e+n);if(this.unusedBits=i[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let a=i.subarray(1);try{if(a.byteLength){let c=is(a,0,a.byteLength);c.offset!==-1&&c.offset===n-1&&(this.value=[c.result])}}catch{}}return this.valueHexView=i.subarray(1),this.blockLength=i.length,e+n}toBER(t,e){if(this.isConstructed)return fe.prototype.toBER.call(this,t,e);if(t)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return ie;let n=new Uint8Array(this.valueHexView.length+1);return n[0]=this.unusedBits,n.set(this.valueHexView,1),n.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}};Ro.NAME="BitStringValueBlock";var ou,Or=class extends It{constructor({idBlock:t={},lenBlock:e={},...n}={}){var o,s;(o=n.isConstructed)!==null&&o!==void 0||(n.isConstructed=!!(!((s=n.value)===null||s===void 0)&&s.length)),super({idBlock:{isConstructed:n.isConstructed,...t},lenBlock:{...e,isIndefiniteForm:!!n.isIndefiniteForm},...n},Ro),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(t,e,n){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(t,e,n)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return je.prototype.onAsciiEncoding.call(this);{let t=[],e=this.valueBlock.valueHexView;for(let o of e)t.push(o.toString(2).padStart(8,"0"));let n=t.join("");return`${this.constructor.NAME} : ${n.substring(0,n.length-this.valueBlock.unusedBits)}`}}};ou=Or;P.BitString=ou;Or.NAME=Xl;var su;function Um(r,t){let e=new Uint8Array([0]),n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l=0,u=c<i?i:c,f=0;for(let d=u;d>=0;d--,f++){switch(!0){case f<a.length:l=s[i-f]+a[c-f]+e[0];break;default:l=s[i-f]+e[0]}switch(e[0]=l/10,!0){case f>=s.length:s=xo(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=xo(e,s)),s}function jl(r){if(r>=gn.length)for(let t=gn.length;t<=r;t++){let e=new Uint8Array([0]),n=gn[t-1].slice(0);for(let o=n.length-1;o>=0;o--){let s=new Uint8Array([(n[o]<<1)+e[0]]);e[0]=s[0]/10,n[o]=s[0]%10}e[0]>0&&(n=xo(e,n)),gn.push(n)}return gn[r]}function Dm(r,t){let e=0,n=new Uint8Array(r),o=new Uint8Array(t),s=n.slice(0),i=s.length-1,a=o.slice(0),c=a.length-1,l,u=0;for(let f=c;f>=0;f--,u++)switch(l=s[i-u]-a[c-u]-e,!0){case l<0:e=1,s[i-u]=l+10;break;default:e=0,s[i-u]=l}if(e>0)for(let f=i-c+1;f>=0;f--,u++)if(l=s[i-u]-e,l<0)e=1,s[i-u]=l+10;else{e=0,s[i-u]=l;break}return s.slice()}var bn=class extends Te(Rt){constructor({value:t,...e}={}){super(e),this._valueDec=0,e.valueHex&&this.setValueHex(),t!==void 0&&(this.valueDec=t)}setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=xa.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(ql(t))}get valueDec(){return this._valueDec}fromDER(t,e,n,o=0){let s=this.fromBER(t,e,n);if(s===-1)return s;let i=this.valueHexView;return i[0]===0&&i[1]&128?this.valueHexView=i.subarray(1):o!==0&&i.length<o&&(o-i.length>1&&(o=i.length+1),this.valueHexView=i.subarray(o-i.length)),s}toDER(t=!1){let e=this.valueHexView;switch(!0){case(e[0]&128)!==0:{let n=new Uint8Array(this.valueHexView.length+1);n[0]=0,n.set(e,1),this.valueHexView=n}break;case(e[0]===0&&(e[1]&128)===0):this.valueHexView=this.valueHexView.subarray(1);break}return this.toBER(t)}fromBER(t,e,n){let o=super.fromBER(t,e,n);return o===-1||this.setValueHex(),o}toBER(t){return t?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let t=this.valueHexView.length*8-1,e=new Uint8Array(this.valueHexView.length*8/3),n=0,o,s=this.valueHexView,i="",a=!1;for(let c=s.byteLength-1;c>=0;c--){o=s[c];for(let l=0;l<8;l++){if((o&1)===1)switch(n){case t:e=Dm(jl(n),e),i="-";break;default:e=Um(e,jl(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=Gl.charAt(e[c]));return a===!1&&(i+=Gl.charAt(0)),i}};su=bn;bn.NAME="IntegerValueBlock";Object.defineProperty(su.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var iu,Ct=class r extends It{constructor(t={}){super(t,bn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Eo(),BigInt(this.valueBlock.toString())}static fromBigInt(t){Eo();let e=BigInt(t),n=new wn,o=e.toString(16).replace(/^-/,""),s=new Uint8Array(j.Convert.FromHex(o));if(e<0){let a=new Uint8Array(s.length+(s[0]&128?1:0));a[0]|=128;let l=BigInt(`0x${j.Convert.ToHex(a)}`)+e,u=j.BufferSourceConverter.toUint8Array(j.Convert.FromHex(l.toString(16)));u[0]|=128,n.write(u)}else s[0]&128&&n.write(new Uint8Array([0])),n.write(s);return new r({valueHex:n.final()})}convertToDER(){let t=new r({valueHex:this.valueBlock.valueHexView});return t.valueBlock.toDER(),t}convertFromDER(){return new r({valueHex:this.valueBlock.valueHexView[0]===0?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}};iu=Ct;P.Integer=iu;Ct.NAME="INTEGER";var au,Uo=class extends Ct{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};au=Uo;P.Enumerated=au;Uo.NAME="ENUMERATED";var xn=class extends Te(Rt){constructor({valueDec:t=-1,isFirstSid:e=!1,...n}={}){super(n),this.valueDec=t,this.isFirstSid=e}fromBER(t,e,n){if(!n)return e;let o=j.BufferSourceConverter.toUint8Array(t);if(!ke(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=hr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){Eo();let e=BigInt(t).toString(2);for(;e.length%7;)e="0"+e;let n=new Uint8Array(e.length/7);for(let o=0;o<n.length;o++)n[o]=parseInt(e.slice(o*7,o*7+7),2)+(o+1<n.length?128:0);this.fromBER(n.buffer,0,n.length)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ge(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ie;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n}toString(){let t="";if(this.isHexOnly)t=j.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){let e=this.valueDec;this.valueDec<=39?t="0.":this.valueDec<=79?(t="1.",e-=40):(t="2.",e-=80),t+=e.toString()}else t=this.valueDec.toString();return t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}};xn.NAME="sidBlock";var Do=class extends Rt{constructor({value:t=Mr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new xn;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.value.length===0&&(s.isFirstSid=!0),this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t){let e=[];for(let n=0;n<this.value.length;n++){let o=this.value[n].toBER(t);if(o.byteLength===0)return this.error=this.value[n].error,ie;e.push(o)}return Ea(e)}fromString(t){this.value=[];let e=0,n=0,o="",s=!1;do if(n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1,s){let i=this.value[0],a=0;switch(i.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:this.value=[];return}let c=parseInt(o,10);if(isNaN(c))return;i.valueDec=c+a,s=!1}else{let i=new xn;if(o>Number.MAX_SAFE_INTEGER){Eo();let a=BigInt(o);i.valueBigInt=a}else if(i.valueDec=parseInt(o,10),isNaN(i.valueDec))return;this.value.length||(i.isFirstSid=!0,s=!0),this.value.push(i)}while(n!==-1)}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e?(o=`{${o}}`,this.value[n].isFirstSid?t=`2.{${o} - 80}`:t+=o):t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Do.NAME="ObjectIdentifierValueBlock";var cu,Hr=class extends It{constructor(t={}){super(t,Do),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};cu=Hr;P.ObjectIdentifier=cu;Hr.NAME="OBJECT IDENTIFIER";var En=class extends Te(Be){constructor({valueDec:t=0,...e}={}){super(e),this.valueDec=t}fromBER(t,e,n){if(n===0)return e;let o=j.BufferSourceConverter.toUint8Array(t);if(!ke(this,o,e,n))return-1;let s=o.subarray(e,e+n);this.valueHexView=new Uint8Array(n);for(let a=0;a<n&&(this.valueHexView[a]=s[a]&127,this.blockLength++,!!(s[a]&128));a++);let i=new Uint8Array(this.blockLength);for(let a=0;a<this.blockLength;a++)i[a]=this.valueHexView[a];return this.valueHexView=i,s[this.blockLength-1]&128?(this.error="End of input reached before message was fully decoded",-1):(this.valueHexView[0]===0&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=hr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}toBER(t){if(this.isHexOnly){if(t)return new ArrayBuffer(this.valueHexView.byteLength);let o=this.valueHexView,s=new Uint8Array(this.blockLength);for(let i=0;i<this.blockLength-1;i++)s[i]=o[i]|128;return s[this.blockLength-1]=o[this.blockLength-1],s.buffer}let e=Ge(this.valueDec,7);if(e.byteLength===0)return this.error="Error during encoding SID value",ie;let n=new Uint8Array(e.byteLength);if(!t){let o=new Uint8Array(e),s=e.byteLength-1;for(let i=0;i<s;i++)n[i]=o[i]|128;n[s]=o[s]}return n.buffer}toString(){let t="";return this.isHexOnly?t=j.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};En.NAME="relativeSidBlock";var Po=class extends Rt{constructor({value:t=Mr,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new En;if(o=s.fromBER(t,o,n),o===-1)return this.blockLength=0,this.error=s.error,o;this.blockLength+=s.blockLength,n-=s.blockLength,this.value.push(s)}return o}toBER(t,e){let n=[];for(let o=0;o<this.value.length;o++){let s=this.value[o].toBER(t);if(s.byteLength===0)return this.error=this.value[o].error,ie;n.push(s)}return Ea(n)}fromString(t){this.value=[];let e=0,n=0,o="";do{n=t.indexOf(".",e),n===-1?o=t.substring(e):o=t.substring(e,n),e=n+1;let s=new En;if(s.valueDec=parseInt(o,10),isNaN(s.valueDec))return!0;this.value.push(s)}while(n!==-1);return!0}toString(){let t="",e=!1;for(let n=0;n<this.value.length;n++){e=this.value[n].isHexOnly;let o=this.value[n].toString();n!==0&&(t=`${t}.`),e&&(o=`{${o}}`),t+=o}return t}toJSON(){let t={...super.toJSON(),value:this.toString(),sidArray:[]};for(let e=0;e<this.value.length;e++)t.sidArray.push(this.value[e].toJSON());return t}};Po.NAME="RelativeObjectIdentifierValueBlock";var lu,Oo=class extends It{constructor(t={}){super(t,Po),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}getValue(){return this.valueBlock.toString()}setValue(t){this.valueBlock.fromString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}};lu=Oo;P.RelativeObjectIdentifier=lu;Oo.NAME="RelativeObjectIdentifier";var uu,Ie=class extends je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};uu=Ie;P.Sequence=uu;Ie.NAME="SEQUENCE";var fu,Ho=class extends je{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};fu=Ho;P.Set=fu;Ho.NAME="SET";var Mo=class extends Te(Rt){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=Mr}toJSON(){return{...super.toJSON(),value:this.value}}};Mo.NAME="StringValueBlock";var Vo=class extends Mo{};Vo.NAME="SimpleStringValueBlock";var Pt=class extends Ao{constructor({...t}={}){super(t,Vo)}fromBuffer(t){this.valueBlock.value=String.fromCharCode.apply(null,j.BufferSourceConverter.toUint8Array(t))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.charCodeAt(o);this.valueBlock.value=t}};Pt.NAME="SIMPLE STRING";var Fo=class extends Pt{fromBuffer(t){this.valueBlock.valueHexView=j.BufferSourceConverter.toUint8Array(t);try{this.valueBlock.value=j.Convert.ToUtf8String(t)}catch(e){this.warnings.push(`Error during "decodeURIComponent": ${e}, using raw string`),this.valueBlock.value=j.Convert.ToBinary(t)}}fromString(t){this.valueBlock.valueHexView=new Uint8Array(j.Convert.FromUtf8String(t)),this.valueBlock.value=t}};Fo.NAME="Utf8StringValueBlock";var hu,Ce=class extends Fo{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};hu=Ce;P.Utf8String=hu;Ce.NAME="UTF8String";var Ko=class extends Pt{fromBuffer(t){this.valueBlock.value=j.Convert.ToUtf16String(t),this.valueBlock.valueHexView=j.BufferSourceConverter.toUint8Array(t)}fromString(t){this.valueBlock.value=t,this.valueBlock.valueHexView=new Uint8Array(j.Convert.FromUtf16String(t))}};Ko.NAME="BmpStringValueBlock";var du,$o=class extends Ko{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};du=$o;P.BmpString=du;$o.NAME="BMPString";var Wo=class extends Pt{fromBuffer(t){let e=ArrayBuffer.isView(t)?t.slice().buffer:t.slice(0),n=new Uint8Array(e);for(let o=0;o<n.length;o+=4)n[o]=n[o+3],n[o+1]=n[o+2],n[o+2]=0,n[o+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(e))}fromString(t){let e=t.length,n=this.valueBlock.valueHexView=new Uint8Array(e*4);for(let o=0;o<e;o++){let s=Ge(t.charCodeAt(o),8),i=new Uint8Array(s);if(i.length>4)continue;let a=4-i.length;for(let c=i.length-1;c>=0;c--)n[o*4+c+a]=i[c]}this.valueBlock.value=t}};Wo.NAME="UniversalStringValueBlock";var pu,qo=class extends Wo{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};pu=qo;P.UniversalString=pu;qo.NAME="UniversalString";var mu,zo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};mu=zo;P.NumericString=mu;zo.NAME="NumericString";var gu,Go=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};gu=Go;P.PrintableString=gu;Go.NAME="PrintableString";var wu,jo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};wu=jo;P.TeletexString=wu;jo.NAME="TeletexString";var yu,Zo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};yu=Zo;P.VideotexString=yu;Zo.NAME="VideotexString";var bu,Xo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};bu=Xo;P.IA5String=bu;Xo.NAME="IA5String";var xu,Yo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};xu=Yo;P.GraphicString=xu;Yo.NAME="GraphicString";var Eu,vn=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Eu=vn;P.VisibleString=Eu;vn.NAME="VisibleString";var vu,Jo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};vu=Jo;P.GeneralString=vu;Jo.NAME="GeneralString";var Su,Qo=class extends Pt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Su=Qo;P.CharacterString=Su;Qo.NAME="CharacterString";var Au,Sn=class extends vn{constructor({value:t,valueDate:e,...n}={}){if(super(n),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,t){this.fromString(t),this.valueBlock.valueHexView=new Uint8Array(t.length);for(let o=0;o<t.length;o++)this.valueBlock.valueHexView[o]=t.charCodeAt(o)}e&&(this.fromDate(e),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(t){this.fromString(String.fromCharCode.apply(null,j.BufferSourceConverter.toUint8Array(t)))}toBuffer(){let t=this.toString(),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return e}fromDate(t){this.year=t.getUTCFullYear(),this.month=t.getUTCMonth()+1,this.day=t.getUTCDate(),this.hour=t.getUTCHours(),this.minute=t.getUTCMinutes(),this.second=t.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(t){let n=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(t);if(n===null){this.error="Wrong input string for conversion";return}let o=parseInt(n[1],10);o>=50?this.year=1900+o:this.year=2e3+o,this.month=parseInt(n[2],10),this.day=parseInt(n[3],10),this.hour=parseInt(n[4],10),this.minute=parseInt(n[5],10),this.second=parseInt(n[6],10)}toString(t="iso"){if(t==="iso"){let e=new Array(7);return e[0]=Ft(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=Ft(this.month,2),e[2]=Ft(this.day,2),e[3]=Ft(this.hour,2),e[4]=Ft(this.minute,2),e[5]=Ft(this.second,2),e[6]="Z",e.join("")}return super.toString(t)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}};Au=Sn;P.UTCTime=Au;Sn.NAME="UTCTime";var Bu,ts=class extends Sn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,d=n.indexOf("+"),w="";if(d===-1&&(d=n.indexOf("-"),f=-1),d!==-1){if(w=n.substring(d+1),n=n.substring(0,d),w.length!==2&&w.length!==4)throw new Error("Wrong input string for conversion");let x=parseInt(w.substring(0,2),10);if(isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*x,w.length===4){if(x=parseInt(w.substring(2,4),10),isNaN(x.valueOf()))throw new Error("Wrong input string for conversion");c=f*x}}}let l=n.indexOf(".");if(l===-1&&(l=n.indexOf(",")),l!==-1){let f=new Number(`0${n.substring(l)}`);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");s=f.valueOf(),o=n.substring(0,l)}else o=n;switch(!0){case o.length===8:if(i=/(\d{4})(\d{2})(\d{2})/ig,l!==-1)throw new Error("Wrong input string for conversion");break;case o.length===10:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.minute=Math.floor(f),f=60*(f-this.minute),this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===12:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=60*s;this.second=Math.floor(f),f=1e3*(f-this.second),this.millisecond=Math.floor(f)}break;case o.length===14:if(i=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,l!==-1){let f=1e3*s;this.millisecond=Math.floor(f)}break;default:throw new Error("Wrong input string for conversion")}let u=i.exec(o);if(u===null)throw new Error("Wrong input string for conversion");for(let f=1;f<u.length;f++)switch(f){case 1:this.year=parseInt(u[f],10);break;case 2:this.month=parseInt(u[f],10);break;case 3:this.day=parseInt(u[f],10);break;case 4:this.hour=parseInt(u[f],10)+a;break;case 5:this.minute=parseInt(u[f],10)+c;break;case 6:this.second=parseInt(u[f],10);break;default:throw new Error("Wrong input string for conversion")}if(e===!1){let f=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=f.getUTCFullYear(),this.month=f.getUTCMonth(),this.day=f.getUTCDay(),this.hour=f.getUTCHours(),this.minute=f.getUTCMinutes(),this.second=f.getUTCSeconds(),this.millisecond=f.getUTCMilliseconds()}}toString(t="iso"){if(t==="iso"){let e=[];return e.push(Ft(this.year,4)),e.push(Ft(this.month,2)),e.push(Ft(this.day,2)),e.push(Ft(this.hour,2)),e.push(Ft(this.minute,2)),e.push(Ft(this.second,2)),this.millisecond!==0&&(e.push("."),e.push(Ft(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(t)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}};Bu=ts;P.GeneralizedTime=Bu;ts.NAME="GeneralizedTime";var Iu,es=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Iu=es;P.DATE=Iu;es.NAME="DATE";var Cu,rs=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Cu=rs;P.TimeOfDay=Cu;rs.NAME="TimeOfDay";var ku,ns=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};ku=ns;P.DateTime=ku;ns.NAME="DateTime";var Tu,os=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Tu=os;P.Duration=Tu;os.NAME="Duration";var Nu,ss=class extends Ce{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Nu=ss;P.TIME=Nu;ss.NAME="TIME";function z(r,t="utf8"){let e=mo[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var An=class extends Error{constructor(t="An error occurred while verifying a message"){super(t),this.name="VerificationError"}},as=class extends Error{constructor(t="Missing Web Crypto API"){super(t),this.name="WebCryptoMissingError"}};var _u={get(r=globalThis){let t=r.crypto;if(t?.subtle==null)throw new as("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return t}};var Ze=_u;async function Lu(r){let t=await Ze.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),e=await Om(t);return{privateKey:e[0],publicKey:e[1]}}async function Ru(r,t){let e=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Ze.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Uu(r,t,e){let n=await Ze.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Ze.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Om(r){if(r.privateKey==null||r.publicKey==null)throw new tt("Private and public key are required");return Promise.all([Ze.get().subtle.exportKey("jwk",r.privateKey),Ze.get().subtle.exportKey("jwk",r.publicKey)])}function Aa(r){if(r.kty!=="RSA")throw new tt("invalid key type");if(r.n==null)throw new tt("invalid key modulus");return et(r.n,"base64url").length*8}var Vr=class{type="RSA";_key;_raw;_multihash;constructor(t,e){this._key=t,this._multihash=e}get raw(){return this._raw==null&&(this._raw=Bn.jwkToPkix(this._key)),this._raw}toMultihash(){return this._multihash}toCID(){return At.createV1(114,this._multihash)}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}verify(t,e){return Uu(this._key,e,t)}},In=class{type="RSA";_key;_raw;publicKey;constructor(t,e){this._key=t,this.publicKey=e}get raw(){return this._raw==null&&(this._raw=Bn.jwkToPkcs1(this._key)),this._raw}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}sign(t){return Ru(this._key,t)}};var cs=8192,Ba=18;function Du(r){let{result:t}=Sa(r),e=t.valueBlock.value;return{n:z(he(e[1].toBigInt()),"base64url"),e:z(he(e[2].toBigInt()),"base64url"),d:z(he(e[3].toBigInt()),"base64url"),p:z(he(e[4].toBigInt()),"base64url"),q:z(he(e[5].toBigInt()),"base64url"),dp:z(he(e[6].toBigInt()),"base64url"),dq:z(he(e[7].toBigInt()),"base64url"),qi:z(he(e[8].toBigInt()),"base64url"),kty:"RSA",alg:"RS256"}}function Hm(r){if(r.n==null||r.e==null||r.d==null||r.p==null||r.q==null||r.dp==null||r.dq==null||r.qi==null)throw new tt("JWK was missing components");let e=new Ie({value:[new Ct({value:0}),Ct.fromBigInt(de(et(r.n,"base64url"))),Ct.fromBigInt(de(et(r.e,"base64url"))),Ct.fromBigInt(de(et(r.d,"base64url"))),Ct.fromBigInt(de(et(r.p,"base64url"))),Ct.fromBigInt(de(et(r.q,"base64url"))),Ct.fromBigInt(de(et(r.dp,"base64url"))),Ct.fromBigInt(de(et(r.dq,"base64url"))),Ct.fromBigInt(de(et(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Pu(r){let{result:t}=Sa(r),e=t.valueBlock.value[1].valueBlock.value[0].valueBlock.value;return{kty:"RSA",n:z(he(e[0].toBigInt()),"base64url"),e:z(he(e[1].toBigInt()),"base64url")}}function Ia(r){if(r.n==null||r.e==null)throw new tt("JWK was missing components");let e=new Ie({value:[new Ie({value:[new Hr({value:"1.2.840.113549.1.1.1"}),new Pr]}),new Or({valueHex:new Ie({value:[Ct.fromBigInt(de(et(r.n,"base64url"))),Ct.fromBigInt(de(et(r.e,"base64url")))]}).toBER()})]}).toBER();return new Uint8Array(e,0,e.byteLength)}function he(r){let t=r.toString(16);t.length%2>0&&(t=`0${t}`);let e=t.length/2,n=new Uint8Array(e),o=0,s=0;for(;o<e;)n[o]=parseInt(t.slice(s,s+2),16),o+=1,s+=2;return n}function de(r){let t=[];return r.forEach(function(e){let n=e.toString(16);n.length%2>0&&(n=`0${n}`),t.push(n)}),BigInt("0x"+t.join(""))}function Ou(r){let t=Du(r);return Hu(t)}function Ca(r){let t=Pu(r);if(Aa(t)>cs)throw new vr("Key size is too large");let e=ue(le.encode({Type:xt.RSA,Data:r})),n=Mt(Ba,e);return new Vr(t,n)}function Hu(r){if(Aa(r)>cs)throw new tt("Key size is too large");let t=Vu(r),e=ue(le.encode({Type:xt.RSA,Data:Ia(t.publicKey)})),n=Mt(Ba,e);return new In(t.privateKey,new Vr(t.publicKey,n))}async function Mu(r){if(r>cs)throw new tt("Key size is too large");let t=await Lu(r),e=ue(le.encode({Type:xt.RSA,Data:Ia(t.publicKey)})),n=Mt(Ba,e);return new In(t.privateKey,new Vr(t.publicKey,n))}function Vu(r){if(r==null)throw new tt("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}var ls=class extends Tr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,on(t);let n=He(e);if(this.iHash=t.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?t.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=t.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),s.fill(0)}update(t){return kr(this),this.iHash.update(t),this}digestInto(t){kr(this),Cr(t,this.outputLen),this.finished=!0,this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let t=new Uint8Array(this.oHash.outputLen);return this.digestInto(t),t}_cloneInto(t){t||(t=Object.create(Object.getPrototypeOf(this),{}));let{oHash:e,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return t=t,t.finished=o,t.destroyed=s,t.blockLen=i,t.outputLen=a,t.oHash=e._cloneInto(t.oHash),t.iHash=n._cloneInto(t.iHash),t}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Fr=(r,t,e)=>new ls(r,t).update(e).digest();Fr.create=(r,t)=>new ls(r,t);function Fu(r){r.lowS!==void 0&&Jt("lowS",r.lowS),r.prehash!==void 0&&Jt("prehash",r.prehash)}function Mm(r){let t=ln(r);zt(t,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:e,Fp:n,a:o}=t;if(e){if(!n.eql(o,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof e!="object"||typeof e.beta!="bigint"||typeof e.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...t})}var{bytesToNumberBE:Vm,hexToBytes:Fm}=io,Ne={Err:class extends Error{constructor(t=""){super(t)}},_tlv:{encode:(r,t)=>{let{Err:e}=Ne;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length&1)throw new e("tlv.encode: unpadded data");let n=t.length/2,o=or(n);if(o.length/2&128)throw new e("tlv.encode: long form length too big");let s=n>127?or(o.length/2|128):"";return`${or(r)}${s}${o}${t}`},decode(r,t){let{Err:e}=Ne,n=0;if(r<0||r>256)throw new e("tlv.encode: wrong tag");if(t.length<2||t[n++]!==r)throw new e("tlv.decode: wrong tlv");let o=t[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new e("tlv.decode(long): indefinite length not supported");if(c>4)throw new e("tlv.decode(long): byte length is too big");let l=t.subarray(n,n+c);if(l.length!==c)throw new e("tlv.decode: length bytes not complete");if(l[0]===0)throw new e("tlv.decode(long): zero leftmost byte");for(let u of l)i=i<<8|u;if(n+=c,i<128)throw new e("tlv.decode(long): not minimal encoding")}let a=t.subarray(n,n+i);if(a.length!==i)throw new e("tlv.decode: wrong value length");return{v:a,l:t.subarray(n+i)}}},_int:{encode(r){let{Err:t}=Ne;if(r<_e)throw new t("integer: negative integers are not allowed");let e=or(r);if(Number.parseInt(e[0],16)&8&&(e="00"+e),e.length&1)throw new t("unexpected assertion");return e},decode(r){let{Err:t}=Ne;if(r[0]&128)throw new t("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return Vm(r)}},toSig(r){let{Err:t,_int:e,_tlv:n}=Ne,o=typeof r=="string"?Fm(r):r;_r(o);let{v:s,l:i}=n.decode(48,o);if(i.length)throw new t("Invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new t("Invalid signature: left bytes after parsing");return{r:e.decode(a),s:e.decode(l)}},hexFromSig(r){let{_tlv:t,_int:e}=Ne,n=`${t.encode(2,e.encode(r.r))}${t.encode(2,e.encode(r.s))}`;return t.encode(48,n)}},_e=BigInt(0),vt=BigInt(1),bx=BigInt(2),Ku=BigInt(3),xx=BigInt(4);function Km(r){let t=Mm(r),{Fp:e}=t,n=$e(t.n,t.nBitLength),o=t.toBytes||((m,h,g)=>{let b=h.toAffine();return Se(Uint8Array.from([4]),e.toBytes(b.x),e.toBytes(b.y))}),s=t.fromBytes||(m=>{let h=m.subarray(1),g=e.fromBytes(h.subarray(0,e.BYTES)),b=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:g,y:b}});function i(m){let{a:h,b:g}=t,b=e.sqr(m),p=e.mul(b,m);return e.add(e.add(p,e.mul(m,h)),g)}if(!e.eql(e.sqr(t.Gy),i(t.Gx)))throw new Error("bad generator point: equation left != right");function a(m){return an(m,vt,t.n)}function c(m){let{allowedPrivateKeyLengths:h,nByteLength:g,wrapPrivateKey:b,n:p}=t;if(h&&typeof m!="bigint"){if(Fe(m)&&(m=xe(m)),typeof m!="string"||!h.includes(m.length))throw new Error("Invalid key");m=m.padStart(g*2,"0")}let B;try{B=typeof m=="bigint"?m:Ee(it("private key",m,g))}catch{throw new Error(`private key must be ${g} bytes, hex or bigint, not ${typeof m}`)}return b&&(B=X(B,p)),Bt("private key",B,vt,p),B}function l(m){if(!(m instanceof d))throw new Error("ProjectivePoint expected")}let u=ir((m,h)=>{let{px:g,py:b,pz:p}=m;if(e.eql(p,e.ONE))return{x:g,y:b};let B=m.is0();h==null&&(h=B?e.ONE:e.inv(p));let _=e.mul(g,h),N=e.mul(b,h),A=e.mul(p,h);if(B)return{x:e.ZERO,y:e.ZERO};if(!e.eql(A,e.ONE))throw new Error("invZ was invalid");return{x:_,y:N}}),f=ir(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:h,y:g}=m.toAffine();if(!e.isValid(h)||!e.isValid(g))throw new Error("bad point: x or y not FE");let b=e.sqr(g),p=i(h);if(!e.eql(b,p))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(h,g,b){if(this.px=h,this.py=g,this.pz=b,h==null||!e.isValid(h))throw new Error("x required");if(g==null||!e.isValid(g))throw new Error("y required");if(b==null||!e.isValid(b))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:g,y:b}=h||{};if(!h||!e.isValid(g)||!e.isValid(b))throw new Error("invalid affine point");if(h instanceof d)throw new Error("projective point not allowed");let p=B=>e.eql(B,e.ZERO);return p(g)&&p(b)?d.ZERO:new d(g,b,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let g=e.invertBatch(h.map(b=>b.pz));return h.map((b,p)=>b.toAffine(g[p])).map(d.fromAffine)}static fromHex(h){let g=d.fromAffine(s(it("pointHex",h)));return g.assertValidity(),g}static fromPrivateKey(h){return d.BASE.multiply(c(h))}static msm(h,g){return lo(d,n,h,g)}_setWindowSize(h){x.setWindowSize(this,h)}assertValidity(){f(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){l(h);let{px:g,py:b,pz:p}=this,{px:B,py:_,pz:N}=h,A=e.eql(e.mul(g,N),e.mul(B,p)),k=e.eql(e.mul(b,N),e.mul(_,p));return A&&k}negate(){return new d(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:g}=t,b=e.mul(g,Ku),{px:p,py:B,pz:_}=this,N=e.ZERO,A=e.ZERO,k=e.ZERO,I=e.mul(p,p),V=e.mul(B,B),L=e.mul(_,_),H=e.mul(p,B);return H=e.add(H,H),k=e.mul(p,_),k=e.add(k,k),N=e.mul(h,k),A=e.mul(b,L),A=e.add(N,A),N=e.sub(V,A),A=e.add(V,A),A=e.mul(N,A),N=e.mul(H,N),k=e.mul(b,k),L=e.mul(h,L),H=e.sub(I,L),H=e.mul(h,H),H=e.add(H,k),k=e.add(I,I),I=e.add(k,I),I=e.add(I,L),I=e.mul(I,H),A=e.add(A,I),L=e.mul(B,_),L=e.add(L,L),I=e.mul(L,H),N=e.sub(N,I),k=e.mul(L,V),k=e.add(k,k),k=e.add(k,k),new d(N,A,k)}add(h){l(h);let{px:g,py:b,pz:p}=this,{px:B,py:_,pz:N}=h,A=e.ZERO,k=e.ZERO,I=e.ZERO,V=t.a,L=e.mul(t.b,Ku),H=e.mul(g,B),K=e.mul(b,_),C=e.mul(p,N),T=e.add(g,b),E=e.add(B,_);T=e.mul(T,E),E=e.add(H,K),T=e.sub(T,E),E=e.add(g,p);let y=e.add(B,N);return E=e.mul(E,y),y=e.add(H,C),E=e.sub(E,y),y=e.add(b,p),A=e.add(_,N),y=e.mul(y,A),A=e.add(K,C),y=e.sub(y,A),I=e.mul(V,E),A=e.mul(L,C),I=e.add(A,I),A=e.sub(K,I),I=e.add(K,I),k=e.mul(A,I),K=e.add(H,H),K=e.add(K,H),C=e.mul(V,C),E=e.mul(L,E),K=e.add(K,C),C=e.sub(H,C),C=e.mul(V,C),E=e.add(E,C),H=e.mul(K,E),k=e.add(k,H),H=e.mul(y,E),A=e.mul(T,A),A=e.sub(A,H),H=e.mul(T,K),I=e.mul(y,I),I=e.add(I,H),new d(A,k,I)}subtract(h){return this.add(h.negate())}is0(){return this.equals(d.ZERO)}wNAF(h){return x.wNAFCached(this,h,d.normalizeZ)}multiplyUnsafe(h){Bt("scalar",h,_e,t.n);let g=d.ZERO;if(h===_e)return g;if(h===vt)return this;let{endo:b}=t;if(!b)return x.unsafeLadder(this,h);let{k1neg:p,k1:B,k2neg:_,k2:N}=b.splitScalar(h),A=g,k=g,I=this;for(;B>_e||N>_e;)B&vt&&(A=A.add(I)),N&vt&&(k=k.add(I)),I=I.double(),B>>=vt,N>>=vt;return p&&(A=A.negate()),_&&(k=k.negate()),k=new d(e.mul(k.px,b.beta),k.py,k.pz),A.add(k)}multiply(h){let{endo:g,n:b}=t;Bt("scalar",h,vt,b);let p,B;if(g){let{k1neg:_,k1:N,k2neg:A,k2:k}=g.splitScalar(h),{p:I,f:V}=this.wNAF(N),{p:L,f:H}=this.wNAF(k);I=x.constTimeNegate(_,I),L=x.constTimeNegate(A,L),L=new d(e.mul(L.px,g.beta),L.py,L.pz),p=I.add(L),B=V.add(H)}else{let{p:_,f:N}=this.wNAF(h);p=_,B=N}return d.normalizeZ([p,B])[0]}multiplyAndAddUnsafe(h,g,b){let p=d.BASE,B=(N,A)=>A===_e||A===vt||!N.equals(p)?N.multiplyUnsafe(A):N.multiply(A),_=B(this,g).add(B(h,b));return _.is0()?void 0:_}toAffine(h){return u(this,h)}isTorsionFree(){let{h,isTorsionFree:g}=t;if(h===vt)return!0;if(g)return g(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:g}=t;return h===vt?this:g?g(d,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return Jt("isCompressed",h),this.assertValidity(),o(d,this,h)}toHex(h=!0){return Jt("isCompressed",h),xe(this.toRawBytes(h))}}d.BASE=new d(t.Gx,t.Gy,e.ONE),d.ZERO=new d(e.ZERO,e.ONE,e.ZERO);let w=t.nBitLength,x=co(d,t.endo?Math.ceil(w/2):w);return{CURVE:t,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:a}}function $m(r){let t=ln(r);return zt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function $u(r){let t=$m(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(C){return X(C,n)}function a(C){return ao(C,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Km({...t,toBytes(C,T,E){let y=T.toAffine(),S=e.toBytes(y.x),v=Se;return Jt("isCompressed",E),E?v(Uint8Array.from([T.hasEvenY()?2:3]),S):v(Uint8Array.from([4]),S,e.toBytes(y.y))},fromBytes(C){let T=C.length,E=C[0],y=C.subarray(1);if(T===o&&(E===2||E===3)){let S=Ee(y);if(!an(S,vt,e.ORDER))throw new Error("Point is not on curve");let v=u(S),R;try{R=e.sqrt(v)}catch($){let W=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+W)}let D=(R&vt)===vt;return(E&1)===1!==D&&(R=e.neg(R)),{x:S,y:R}}else if(T===s&&E===4){let S=e.fromBytes(y.subarray(0,e.BYTES)),v=e.fromBytes(y.subarray(e.BYTES,2*e.BYTES));return{x:S,y:v}}else throw new Error(`Point of length ${T} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),d=C=>xe(Ke(C,t.nByteLength));function w(C){let T=n>>vt;return C>T}function x(C){return w(C)?i(-C):C}let m=(C,T,E)=>Ee(C.slice(T,E));class h{constructor(T,E,y){this.r=T,this.s=E,this.recovery=y,this.assertValidity()}static fromCompact(T){let E=t.nByteLength;return T=it("compactSignature",T,E*2),new h(m(T,0,E),m(T,E,2*E))}static fromDER(T){let{r:E,s:y}=Ne.toSig(it("DER",T));return new h(E,y)}assertValidity(){Bt("r",this.r,vt,n),Bt("s",this.s,vt,n)}addRecoveryBit(T){return new h(this.r,this.s,T)}recoverPublicKey(T){let{r:E,s:y,recovery:S}=this,v=N(it("msgHash",T));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");let R=S===2||S===3?E+t.n:E;if(R>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let D=S&1?"03":"02",M=c.fromHex(D+d(R)),$=a(R),W=i(-v*$),G=i(y*$),Z=c.BASE.multiplyAndAddUnsafe(M,W,G);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return w(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return sr(this.toDERHex())}toDERHex(){return Ne.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return sr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}let g={isValidPrivateKey(C){try{return l(C),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let C=Ui(t.n);return bl(t.randomBytes(C),t.n)},precompute(C=8,T=c.BASE){return T._setWindowSize(C),T.multiply(BigInt(3)),T}};function b(C,T=!0){return c.fromPrivateKey(C).toRawBytes(T)}function p(C){let T=Fe(C),E=typeof C=="string",y=(T||E)&&C.length;return T?y===o||y===s:E?y===2*o||y===2*s:C instanceof c}function B(C,T,E=!0){if(p(C))throw new Error("first arg must be private key");if(!p(T))throw new Error("second arg must be public key");return c.fromHex(T).multiply(l(C)).toRawBytes(E)}let _=t.bits2int||function(C){let T=Ee(C),E=C.length*8-t.nBitLength;return E>0?T>>BigInt(E):T},N=t.bits2int_modN||function(C){return i(_(C))},A=cn(t.nBitLength);function k(C){return Bt(`num < 2^${t.nBitLength}`,C,_e,A),Ke(C,t.nByteLength)}function I(C,T,E=V){if(["recovered","canonical"].some(st=>st in E))throw new Error("sign() legacy options not supported");let{hash:y,randomBytes:S}=t,{lowS:v,prehash:R,extraEntropy:D}=E;v==null&&(v=!0),C=it("msgHash",C),Fu(E),R&&(C=it("prehashed msgHash",y(C)));let M=N(C),$=l(T),W=[k($),k(M)];if(D!=null&&D!==!1){let st=D===!0?S(e.BYTES):D;W.push(it("extraEntropy",st))}let G=Se(...W),Z=M;function ot(st){let lt=_(st);if(!f(lt))return;let Ut=a(lt),gt=c.BASE.multiply(lt).toAffine(),Ht=i(gt.x);if(Ht===_e)return;let me=i(Ut*i(Z+Ht*$));if(me===_e)return;let Jr=(gt.x===Ht?0:2)|Number(gt.y&vt),Qr=me;return v&&w(me)&&(Qr=x(me),Jr^=1),new h(Ht,Qr,Jr)}return{seed:G,k2sig:ot}}let V={lowS:t.lowS,prehash:!1},L={lowS:t.lowS,prehash:!1};function H(C,T,E=V){let{seed:y,k2sig:S}=I(C,T,E),v=t;return Ti(v.hash.outputLen,v.nByteLength,v.hmac)(y,S)}c.BASE._setWindowSize(8);function K(C,T,E,y=L){let S=C;if(T=it("msgHash",T),E=it("publicKey",E),"strict"in y)throw new Error("options.strict was renamed to lowS");Fu(y);let{lowS:v,prehash:R}=y,D,M;try{if(typeof S=="string"||Fe(S))try{D=h.fromDER(S)}catch(gt){if(!(gt instanceof Ne.Err))throw gt;D=h.fromCompact(S)}else if(typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint"){let{r:gt,s:Ht}=S;D=new h(gt,Ht)}else throw new Error("PARSE");M=c.fromHex(E)}catch(gt){if(gt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&D.hasHighS())return!1;R&&(T=t.hash(T));let{r:$,s:W}=D,G=N(T),Z=a(W),ot=i(G*Z),st=i($*Z),lt=c.BASE.multiplyAndAddUnsafe(M,ot,st)?.toAffine();return lt?i(lt.x)===$:!1}return{CURVE:t,getPublicKey:b,getSharedSecret:B,sign:H,verify:K,ProjectivePoint:c,Signature:h,utils:g}}function Wm(r){return{hash:r,hmac:(t,...e)=>Fr(r,t,Ei(...e)),randomBytes:sn}}function Wu(r,t){let e=n=>$u({...r,...Wm(n)});return Object.freeze({...e(t),create:e})}var Gu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),qu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),qm=BigInt(1),ka=BigInt(2),zu=(r,t)=>(r+t/ka)/t;function zm(r){let t=Gu,e=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%t,u=l*l*r%t,f=at(u,e,t)*u%t,d=at(f,e,t)*u%t,w=at(d,ka,t)*l%t,x=at(w,o,t)*w%t,m=at(x,s,t)*x%t,h=at(m,a,t)*m%t,g=at(h,c,t)*h%t,b=at(g,a,t)*m%t,p=at(b,e,t)*u%t,B=at(p,i,t)*x%t,_=at(B,n,t)*l%t,N=at(_,ka,t);if(!Ta.eql(Ta.sqr(N),r))throw new Error("Cannot find square root");return N}var Ta=$e(Gu,void 0,void 0,{sqrt:zm}),dr=Wu({a:BigInt(0),b:BigInt(7),Fp:Ta,n:qu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=qu,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-qm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=zu(s*r,t),c=zu(-n*r,t),l=X(r-a*e-c*o,t),u=X(-a*n-c*s,t),f=l>i,d=u>i;if(f&&(l=t-l),d&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}}},ue),Tx=BigInt(0);var Nx=dr.ProjectivePoint;function St(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=bt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}function ju(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Zu(r,t,e){let n=dn.digest(e instanceof Uint8Array?e:e.subarray());if(ju(n))return n.then(({digest:o})=>dr.verify(t,o,r)).catch(o=>{throw new An(String(o))});try{return dr.verify(t,n.digest,r)}catch(o){throw new An(String(o))}}var us=class{type="secp256k1";raw;_key;constructor(t){this._key=Yu(t),this.raw=Xu(this._key)}toMultihash(){return ye.digest(Rr(this))}toCID(){return At.createV1(114,this.toMultihash())}toString(){return nt.encode(this.toMultihash().bytes).substring(1)}equals(t){return t==null||!(t.raw instanceof Uint8Array)?!1:Dt(this.raw,t.raw)}verify(t,e){return Zu(this._key,e,t)}};function Na(r){return new us(r)}function Xu(r){return dr.ProjectivePoint.fromHex(r).toRawBytes(!0)}function Yu(r){try{return dr.ProjectivePoint.fromHex(r),r}catch(t){throw new vr(String(t))}}function Cn(r){let{Type:t,Data:e}=le.decode(r),n=e??new Uint8Array;switch(t){case xt.RSA:return Ca(n);case xt.Ed25519:return Mi(n);case xt.secp256k1:return Na(n);default:throw new er}}function Ju(r){let{Type:t,Data:e}=le.decode(r.digest),n=e??new Uint8Array;switch(t){case xt.Ed25519:return Mi(n);case xt.secp256k1:return Na(n);default:throw new er}}function Rr(r){return le.encode({Type:xt[r.type],Data:r.raw})}var Qu=Symbol.for("nodejs.util.inspect.custom"),jm=114,kn=class{type;multihash;publicKey;string;constructor(t){this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[ui]=!0;toString(){return this.string==null&&(this.string=nt.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return At.createV1(jm,this.multihash)}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return Dt(this.multihash.bytes,t);if(typeof t=="string")return this.toString()===t;if(t?.toMultihash()?.bytes!=null)return Dt(this.multihash.bytes,t.toMultihash().bytes);throw new Error("not valid Id")}[Qu](){return`PeerId(${this.toString()})`}},Tn=class extends kn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Nn=class extends kn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.publicKey}},_n=class extends kn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.publicKey}},Zm=2336,fs=class{type="url";multihash;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=ye.digest(et(this.url))}[Qu](){return`PeerId(${this.url})`}[ui]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return At.createV1(Zm,this.toMultihash())}toJSON(){return this.toString()}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=z(t)),t.toString()===this.toString())}};function Kr(r,t){let e;if(r.charAt(0)==="1"||r.charAt(0)==="Q")e=Oe(nt.decode(`z${r}`));else{if(t==null)throw new tt('Please pass a multibase decoder for strings that do not start with "1" or "Q"');e=Oe(t.decode(r))}return Xm(e)}function _a(r){if(r.type==="Ed25519")return new Nn({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new _n({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new Tn({multihash:r.toCID().multihash,publicKey:r});throw new er}function Xm(r){if(Jm(r))return new Tn({multihash:r});if(Ym(r))try{let t=Ju(r);if(t.type==="Ed25519")return new Nn({multihash:r,publicKey:t});if(t.type==="secp256k1")return new _n({multihash:r,publicKey:t})}catch{let e=z(r.digest);return new fs(new URL(e))}throw new Xn("Supplied PeerID Multihash is invalid")}function Ym(r){return r.code===ye.code}function Jm(r){return r.code===dn.code}var hs=class{index=0;input="";new(t){return this.index=0,this.input=t,this}readAtomically(t){let e=this.index,n=t();return n===void 0&&(this.index=e),n}parseWith(t){let e=t();if(this.index===this.input.length)return e}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(t){return this.readAtomically(()=>{let e=this.readChar();if(e===t)return e})}readSeparator(t,e,n){return this.readAtomically(()=>{if(!(e>0&&this.readGivenChar(t)===void 0))return n()})}readNumber(t,e,n,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,t);if(!Number.isNaN(d))return d});if(u===void 0)break;if(s*=t,s+=u,s>l||(i+=1,e!==void 0&&i>e))return}if(i!==0)return!n&&c&&i>1?void 0:s})}readIPv4Addr(){return this.readAtomically(()=>{let t=new Uint8Array(4);for(let e=0;e<t.length;e++){let n=this.readSeparator(".",e,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;t[e]=n}return t})}readIPv6Addr(){let t=e=>{for(let n=0;n<e.length/2;n++){let o=n*2;if(n<e.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return e[o]=i[0],e[o+1]=i[1],e[o+2]=i[2],e[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];e[o]=s>>8,e[o+1]=s&255}return[e.length,!1]};return this.readAtomically(()=>{let e=new Uint8Array(16),[n,o]=t(e);if(n===16)return e;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=t(s.subarray(0,i));return e.set(s.subarray(0,a),16-a),e})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var tf=45,t0=15,$r=new hs;function La(r){if(!(r.length>t0))return $r.new(r).parseWith(()=>$r.readIPv4Addr())}function Ra(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>tf))return $r.new(r).parseWith(()=>$r.readIPv6Addr())}function ds(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>tf))return $r.new(r).parseWith(()=>$r.readIPAddr())}var W1=parseInt("0xFFFF",16),q1=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function ps(r){return!!La(r)}function ms(r){return!!Ra(r)}function gs(r){return!!ds(r)}var nf=ps,s0=ms,Ua=function(r){let t=0;if(r=r.toString().trim(),nf(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(s0(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=nf(e[n]),i;s&&(i=Ua(e[n]),e[n]=z(i.slice(0,2),"base16")),i!=null&&++n<8&&e.splice(n,0,z(i.slice(2,4),"base16"))}if(e[0]==="")for(;e.length<8;)e.unshift("0");else if(e[e.length-1]==="")for(;e.length<8;)e.push("0");else if(e.length<8){for(n=0;n<e.length&&e[n]!=="";n++);let s=[n,1];for(n=9-e.length;n>0;n--)s.push("0");e.splice.apply(e,s)}let o=new Uint8Array(t+16);for(n=0;n<e.length;n++){let s=parseInt(e[n],16);o[t++]=s>>8&255,o[t++]=s&255}return o}throw new Error("invalid ip address")},of=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Wr={},Da={},a0=[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,-1,"ip6zone"],[43,8,"ipcidr"],[53,-1,"dns",!0],[54,-1,"dns4",!0],[55,-1,"dns6",!0],[56,-1,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,-1,"unix",!1,!0],[421,-1,"ipfs"],[421,-1,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,-1,"garlic64"],[448,0,"tls"],[449,-1,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,-1,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,-1,"http-path"],[777,-1,"memory"]];a0.forEach(r=>{let t=c0(...r);Da[t.code]=t,Wr[t.name]=t});function c0(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function Q(r){if(typeof r=="number"){if(Da[r]!=null)return Da[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Wr[r]!=null)return Wr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var k2=Q("ip4"),T2=Q("ip6"),N2=Q("ipcidr");function Ma(r,t){switch(Q(r).code){case 4:case 41:return u0(t);case 42:return Ha(t);case 6:case 273:case 33:case 132:return cf(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Ha(t);case 421:return p0(t);case 444:return af(t);case 445:return af(t);case 466:return d0(t);case 481:return globalThis.encodeURIComponent(Ha(t));default:return z(t,"base16")}}function Va(r,t){switch(Q(r).code){case 4:return sf(t);case 41:return sf(t);case 42:return Oa(t);case 6:case 273:case 33:case 132:return Fa(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Oa(t);case 421:return f0(t);case 444:return m0(t);case 445:return g0(t);case 466:return h0(t);case 481:return Oa(globalThis.decodeURIComponent(t));default:return et(t,"base16")}}var Pa=Object.values(lr).map(r=>r.decoder),l0=function(){let r=Pa[0].or(Pa[1]);return Pa.slice(2).forEach(t=>r=r.or(t)),r}();function sf(r){if(!gs(r))throw new Error("invalid ip address");return Ua(r)}function u0(r){let t=of(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!gs(t))throw new Error("invalid ip address");return t}function Fa(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function cf(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Oa(r){let t=et(r),e=Uint8Array.from(ce(t.length));return St([e,t],e.length+t.length)}function Ha(r){let t=ee(r);if(r=r.slice(ct(t)),r.length!==t)throw new Error("inconsistent lengths");return z(r)}function f0(r){let t;r[0]==="Q"||r[0]==="1"?t=Oe(nt.decode(`z${r}`)).bytes:t=At.parse(r).multihash.bytes;let e=Uint8Array.from(ce(t.length));return St([e,t],e.length+t.length)}function h0(r){let t=l0.decode(r),e=Uint8Array.from(ce(t.length));return St([e,t],e.length+t.length)}function d0(r){let t=ee(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+z(e,"base64url")}function p0(r){let t=ee(r),e=r.slice(ct(t));if(e.length!==t)throw new Error("inconsistent lengths");return z(e,"base58btc")}function m0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==16)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion address.`);let e=we.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=Fa(n);return St([e,o],e.length+o.length)}function g0(r){let t=r.split(":");if(t.length!==2)throw new Error(`failed to parse onion addr: ["'${t.join('", "')}'"]' does not contain a port number`);if(t[0].length!==56)throw new Error(`failed to parse onion addr: ${t[0]} not a Tor onion3 address.`);let e=we.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=Fa(n);return St([e,o],e.length+o.length)}function af(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=z(t,"base32"),o=cf(e);return`${n}:${o}`}function lf(r){r=Ka(r);let t=[],e=[],n=null,o=r.split("/").slice(1);if(o.length===1&&o[0]==="")return{bytes:new Uint8Array,string:"/",tuples:[],stringTuples:[],path:null};for(let s=0;s<o.length;s++){let i=o[s],a=Q(i);if(a.size===0){t.push([a.code]),e.push([a.code]);continue}if(s++,s>=o.length)throw ff("invalid address: "+r);if(a.path===!0){n=Ka(o.slice(s).join("/")),t.push([a.code,Va(a.code,n)]),e.push([a.code,n]);break}let c=Va(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Ma(a.code,c)])}return{string:uf(e),bytes:Wa(t),tuples:t,stringTuples:e,path:n}}function $a(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=ct(s),a=Q(s),c=w0(a,r.slice(o+i));if(c===0){t.push([s]),e.push([s]),o+=i;continue}let l=r.slice(o+i,o+i+c);if(o+=c+i,o>r.length)throw ff("Invalid address Uint8Array: "+z(r,"base16"));t.push([s,l]);let u=Ma(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:uf(e),tuples:t,stringTuples:e,path:n}}function uf(r){let t=[];return r.map(e=>{let n=Q(e[0]);return t.push(n.name),e.length>1&&e[1]!=null&&t.push(e[1]),null}),Ka(t.join("/"))}function Wa(r){return St(r.map(t=>{let e=Q(t[0]),n=Uint8Array.from(ce(e.code));return t.length>1&&t[1]!=null&&(n=St([n,t[1]])),n}))}function w0(r,t){if(r.size>0)return r.size/8;if(r.size===0)return 0;{let e=ee(t instanceof Uint8Array?t:Uint8Array.from(t));return e+ct(e)}}function Ka(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function ff(r){return new Error("Error parsing address: "+r)}var y0=Symbol.for("nodejs.util.inspect.custom"),za=Symbol.for("@multiformats/js-multiaddr/multiaddr"),b0=[Q("dns").code,Q("dns4").code,Q("dns6").code,Q("dnsaddr").code],qa=class extends Error{constructor(t="No available resolver"){super(t),this.name="NoAvailableResolverError"}},ws=class r{bytes;#t;#e;#r;#n;[za]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=$a(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=lf(t)}else if(df(t))e=$a(t.bytes);else throw new Error("addr must be a string, Buffer, or another Multiaddr");this.bytes=e.bytes,this.#t=e.string,this.#e=e.tuples,this.#r=e.stringTuples,this.#n=e.path}toString(){return this.#t}toJSON(){return this.toString()}toOptions(){let t,e,n,o,s="",i=Q("tcp"),a=Q("udp"),c=Q("ip4"),l=Q("ip6"),u=Q("dns6"),f=Q("ip6zone");for(let[w,x]of this.stringTuples())w===f.code&&(s=`%${x??""}`),b0.includes(w)&&(e=i.name,o=443,n=`${x??""}${s}`,t=w===u.code?6:4),(w===i.code||w===a.code)&&(e=Q(w).name,o=parseInt(x??"")),(w===c.code||w===l.code)&&(e=Q(w).name,n=`${x??""}${s}`,t=w===l.code?6:4);if(t==null||e==null||n==null||o==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:e,port:o}}protos(){return this.#e.map(([t])=>Object.assign({},Q(t)))}protoCodes(){return this.#e.map(([t])=>t)}protoNames(){return this.#e.map(([t])=>Q(t).name)}tuples(){return this.#e}stringTuples(){return this.#r}encapsulate(t){return t=new r(t),new r(this.toString()+t.toString())}decapsulate(t){let e=t.toString(),n=this.toString(),o=n.lastIndexOf(e);if(o<0)throw new Error(`Address ${this.toString()} does not contain subaddress: ${t.toString()}`);return new r(n.slice(0,o))}decapsulateCode(t){let e=this.tuples();for(let n=e.length-1;n>=0;n--)if(e[n][0]===t)return new r(Wa(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Wr.p2p.code&&t.push([n,o]),n===Wr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?z(nt.decode(`z${n}`),"base58btc"):z(At.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return Dt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=hf.get(e.name);if(n==null)throw new qa(`no available resolver for ${e.name}`);return(await n(this,t)).map(s=>ae(s))}nodeAddress(){let t=this.toOptions();if(t.transport!=="tcp"&&t.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${t.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:t.family,address:t.host,port:t.port}}isThinWaistAddress(t){let e=(t??this).protos();return!(e.length!==2||e[0].code!==4&&e[0].code!==41||e[1].code!==6&&e[1].code!==273)}[y0](){return`Multiaddr(${this.#t})`}};var hf=new Map;function df(r){return!!r?.[za]}function ae(r){return new ws(r)}var x0=r=>r.toString().split("/").slice(1),Ln=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),Y=r=>({match:t=>Ln(e=>e===r).match(t),pattern:r}),xs=()=>({match:r=>Ln(t=>typeof t=="string").match(r),pattern:"{string}"}),Es=()=>({match:r=>Ln(t=>!isNaN(parseInt(t))).match(r),pattern:"{number}"}),kt=()=>({match:r=>{if(r.length<2||r[0]!=="p2p"&&r[0]!=="ipfs")return!1;if(r[1].startsWith("Q")||r[1].startsWith("1"))try{nt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ys=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{ra.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),Et=r=>({match:t=>{let e=r.match(t);return e===!1?t:e},pattern:`optional(${r.pattern})`}),jt=(...r)=>({match:t=>{let e;for(let n of r){let o=n.match(t);o!==!1&&(e==null||o.length<e.length)&&(e=o)}return e??!1},pattern:`or(${r.map(t=>t.pattern).join(", ")})`}),rt=(...r)=>({match:t=>{for(let e of r){let n=e.match(t);if(n===!1)return!1;t=n}return t},pattern:`and(${r.map(t=>t.pattern).join(", ")})`});function pt(...r){function t(o){let s=x0(o);for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function e(o){return t(o)!==!1}function n(o){let s=t(o);return s===!1?!1:s.length===0}return{matches:e,exactMatch:n}}var ja=rt(Y("dns4"),xs()),Za=rt(Y("dns6"),xs()),Xa=rt(Y("dnsaddr"),xs()),pf=rt(Y("dns"),xs()),oE=pt(ja),sE=pt(Za),iE=pt(Xa),aE=pt(jt(pf,Xa,ja,Za)),mf=rt(Y("ip4"),Ln(ps)),gf=rt(Y("ip6"),Ln(ms)),wf=jt(mf,gf),pe=jt(wf,pf,ja,Za,Xa),cE=pt(pe),lE=pt(mf),uE=pt(gf),fE=pt(wf),Ya=rt(pe,Y("tcp"),Es()),Rn=rt(pe,Y("udp"),Es()),hE=pt(Ya),dE=pt(Rn),Ja=rt(Rn,Y("quic")),vs=rt(Rn,Y("quic-v1")),E0=jt(Ja,vs),pE=pt(Ja),mE=pt(vs),Ga=jt(pe,Ya,Rn,Ja,vs),yf=jt(rt(Ga,Y("ws"),Et(kt()))),gE=pt(yf),bf=jt(rt(Ga,Y("wss"),Et(kt())),rt(Ga,Y("tls"),Y("ws"),Et(kt()))),wE=pt(bf),xf=rt(Rn,Y("webrtc-direct"),Et(ys()),Et(ys()),Et(kt())),Ef=pt(xf),vf=rt(vs,Y("webtransport"),Et(ys()),Et(ys()),Et(kt())),yE=pt(vf),bs=jt(yf,bf,rt(Ya,Et(kt())),rt(E0,Et(kt())),rt(pe,Et(kt())),xf,vf,kt()),bE=pt(bs),v0=rt(bs,Y("p2p-circuit"),kt()),xE=pt(v0),S0=jt(rt(bs,Y("p2p-circuit"),Y("webrtc"),Et(kt())),rt(bs,Y("webrtc"),Et(kt())),Y("webrtc")),Sf=pt(S0),A0=jt(rt(pe,Y("tcp"),Es(),Y("http"),Et(kt())),rt(pe,Y("http"),Et(kt()))),EE=pt(A0),B0=jt(rt(pe,Y("tcp"),jt(rt(Y("443"),Y("http")),rt(Es(),Y("https"))),Et(kt())),rt(pe,Y("tls"),Y("http"),Et(kt())),rt(pe,Y("https"),Et(kt()))),vE=pt(B0);var Af=function(r,t,e){if(e||arguments.length===2)for(var n=0,o=t.length,s;n<o;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return r.concat(s||Array.prototype.slice.call(t))},I0=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var C0=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var k0=function(){function r(t,e,n,o){this.name=t,this.version=e,this.os=n,this.bot=o,this.type="bot-device"}return r}();var T0=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var N0=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var _0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,L0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Bf=3,R0=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",_0]],If=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function kf(r){return r?Cf(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new N0:typeof navigator<"u"?Cf(navigator.userAgent):P0()}function U0(r){return r!==""&&R0.reduce(function(t,e){var n=e[0],o=e[1];if(t)return t;var s=o.exec(r);return!!s&&[n,s]},!1)}function Cf(r){var t=U0(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new T0;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Bf&&(o=Af(Af([],o,!0),O0(Bf-o.length),!0)):o=[];var s=o.join("."),i=D0(r),a=L0.exec(r);return a&&a[1]?new k0(e,s,i,a[1]):new I0(e,s,i)}function D0(r){for(var t=0,e=If.length;t<e;t++){var n=If[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function P0(){var r=typeof process<"u"&&process.version;return r?new C0(process.version.slice(1)):null}function O0(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function dt(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Ss=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},Qa=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Tf=r=>globalThis.DOMException===void 0?new Qa(r):new DOMException(r),Nf=r=>{let t=r.reason===void 0?Tf("This operation was aborted."):r.reason;return t instanceof Error?t:Tf(t)};function pr(r,t){let{milliseconds:e,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=t,i,c=new Promise((l,u)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(t.signal){let{signal:d}=t;d.aborted&&u(Nf(d)),d.addEventListener("abort",()=>{u(Nf(d))})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Ss;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){u(d)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?l():o instanceof Error?u(o):(f.message=o??`Promise timed out after ${e} milliseconds`,u(f))},e),(async()=>{try{l(await r)}catch(d){u(d)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var _f=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var Lf=kf(),Un=Lf!=null&&Lf.name==="firefox",As=async function*(){},Bs=async r=>{},H0=30*1e3;function Rf(r,t,e=H0,n){r.readyState==="open"&&Promise.resolve().then(async()=>{if(r.bufferedAmount>0){n.log("%s drain channel with %d buffered bytes",t,r.bufferedAmount);let o=dt(),s=!1;r.bufferedAmountLowThreshold=0;let i=()=>{s||(n.log("%s drain channel closed before drain",t),o.resolve())};r.addEventListener("close",i,{once:!0}),r.addEventListener("bufferedamountlow",()=>{s=!0,r.removeEventListener("close",i),o.resolve()}),await pr(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Dn(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??_f.map(t=>({urls:[t]})),r}var mr=class{log;peerConnection;remoteAddr;timeline;metrics;source=As();sink=Bs;constructor(t,e){this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=e.remoteAddr,this.timeline=e.timeline,this.peerConnection=e.peerConnection;let n=this.peerConnection.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",this.peerConnection.connectionState,"initial state",n),(this.peerConnection.connectionState==="disconnected"||this.peerConnection.connectionState==="failed"||this.peerConnection.connectionState==="closed")&&(this.timeline.close=Date.now())}}async close(t){this.log.trace("closing connection"),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({close:!0})}abort(t){this.log.error("closing connection due to error",t),this.peerConnection.close(),this.timeline.close=Date.now(),this.metrics?.increment({abort:!0})}};var Is=class{buffer;mask;top;btm;next;constructor(t){if(!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(t){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=t,this.top=this.top+1&this.mask,!0)}shift(){let t=this.buffer[this.btm];if(t!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,t}isEmpty(){return this.buffer[this.btm]===void 0}},qr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Is(this.hwm),this.tail=this.head,this.size=0}calculateSize(t){return t?.byteLength!=null?t.byteLength:1}push(t){if(t?.value!=null&&(this.size+=this.calculateSize(t.value)),!this.head.push(t)){let e=this.head;this.head=e.next=new Is(2*this.head.buffer.length),this.head.push(t)}}shift(){let t=this.tail.shift();if(t===void 0&&this.tail.next!=null){let e=this.tail.next;this.tail.next=null,this.tail=e,t=this.tail.shift()}return t?.value!=null&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}};var tc=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Xe(r={}){return M0(e=>{let n=e.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function M0(r,t){t=t??{};let e=t.onEnd,n=new qr,o,s,i,a=dt(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((h,g)=>{s=b=>{s=null,n.push(b);try{h(r(n))}catch(p){g(p)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=dt()})}},l=h=>s!=null?s(h):(n.push(h),o),u=h=>(n=new qr,s!=null?s({error:h}):(n.push({error:h}),o)),f=h=>{if(i)return o;if(t?.objectMode!==!0&&h?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:h})},d=h=>i?o:(i=!0,h!=null?u(h):l({done:!0})),w=()=>(n=new qr,d(),{done:!0}),x=h=>(d(h),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:w,throw:x,push:f,end:d,get readableLength(){return n.size},onEmpty:async h=>{let g=h?.signal;if(g?.throwIfAborted(),n.isEmpty())return;let b,p;g!=null&&(b=new Promise((B,_)=>{p=()=>{_(new tc)},g.addEventListener("abort",p)}));try{await Promise.race([a.promise,b])}finally{p!=null&&g!=null&&g?.removeEventListener("abort",p)}}},e==null)return o;let m=o;return o={[Symbol.asyncIterator](){return this},next(){return m.next()},throw(h){return m.throw(h),e!=null&&(e(h),e=void 0),{done:!0}},return(){return m.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(h){return m.end(h),e!=null&&(e(h),e=void 0),o},get readableLength(){return m.readableLength},onEmpty:h=>m.onEmpty(h)},o}var Cs=class extends Error{type;code;constructor(t,e,n){super(t??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=e??"ABORT_ERR"}};async function Le(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new Cs(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new Cs(e?.errorMessage,e?.errorCode,e?.errorName);try{return await Promise.race([r,new Promise((s,i)=>{n=()=>{i(o)},t.addEventListener("abort",n)})])}finally{n!=null&&t.removeEventListener("abort",n)}}var Df=Symbol.for("@achingbrain/uint8arraylist");function Uf(r,t){if(t==null||t<0)throw new RangeError("index is out of bounds");let e=0;for(let n of r){let o=e+n.byteLength;if(t<o)return{buf:n,index:t-e};e=o}throw new RangeError("index is out of bounds")}function ks(r){return!!r?.[Df]}var ft=class r{bufs;length;[Df]=!0;constructor(...t){this.bufs=[],this.length=0,t.length>0&&this.appendAll(t)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...t){this.appendAll(t)}appendAll(t){let e=0;for(let n of t)if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.push(n);else if(ks(n))e+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}prepend(...t){this.prependAll(t)}prependAll(t){let e=0;for(let n of t.reverse())if(n instanceof Uint8Array)e+=n.byteLength,this.bufs.unshift(n);else if(ks(n))e+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=e}get(t){let e=Uf(this.bufs,t);return e.buf[e.index]}set(t,e){let n=Uf(this.bufs,t);n.buf[n.index]=e}write(t,e=0){if(t instanceof Uint8Array)for(let n=0;n<t.length;n++)this.set(e+n,t[n]);else if(ks(t))for(let n=0;n<t.length;n++)this.set(e+n,t.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(t){if(t=Math.trunc(t),!(Number.isNaN(t)||t<=0)){if(t===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(t>=this.bufs[0].byteLength)t-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(t),this.length-=t;break}}}slice(t,e){let{bufs:n,length:o}=this._subList(t,e);return St(n,o)}subarray(t,e){let{bufs:n,length:o}=this._subList(t,e);return n.length===1?n[0]:St(n,o)}sublist(t,e){let{bufs:n,length:o}=this._subList(t,e),s=new r;return s.length=o,s.bufs=[...n],s}_subList(t,e){if(t=t??0,e=e??this.length,t<0&&(t=this.length+t),e<0&&(e=this.length+e),t<0||e>this.length)throw new RangeError("index is out of bounds");if(t===e)return{bufs:[],length:0};if(t===0&&e===this.length)return{bufs:this.bufs,length:this.length};let n=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,t>=c)continue;let l=t>=a&&t<c,u=e>a&&e<=c;if(l&&u){if(t===a&&e===c){n.push(i);break}let f=t-a;n.push(i.subarray(f,f+(e-t)));break}if(l){if(t===0){n.push(i);continue}n.push(i.subarray(t-a));continue}if(u){if(e===c){n.push(i);break}n.push(i.subarray(0,e-a));break}n.push(i)}return{bufs:n,length:e-t}}indexOf(t,e=0){if(!ks(t)&&!(t instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=t instanceof Uint8Array?t:t.subarray();if(e=Number(e??0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let f=0;f<s;f++)i[f]=-1;for(let f=0;f<o;f++)i[n[f]]=f;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=e;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let w=this.get(f+d);if(n[d]!==w){u=Math.max(1,d-a[w]);break}}if(u===0)return f}return-1}getInt8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getInt8(0)}setInt8(t,e){let n=bt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,e),this.write(n,t)}getInt16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,e)}setInt16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,e,n),this.write(o,t)}getInt32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,e)}setInt32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,e,n),this.write(o,t)}getBigInt64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,e)}setBigInt64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,e,n),this.write(o,t)}getUint8(t){let e=this.subarray(t,t+1);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint8(0)}setUint8(t,e){let n=bt(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,e),this.write(n,t)}getUint16(t,e){let n=this.subarray(t,t+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,e)}setUint16(t,e,n){let o=yt(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,e,n),this.write(o,t)}getUint32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,e)}setUint32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,e,n),this.write(o,t)}getBigUint64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,e)}setBigUint64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,e,n),this.write(o,t)}getFloat32(t,e){let n=this.subarray(t,t+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,e)}setFloat32(t,e,n){let o=yt(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,e,n),this.write(o,t)}getFloat64(t,e){let n=this.subarray(t,t+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,e)}setFloat64(t,e,n){let o=yt(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,e,n),this.write(o,t)}equals(t){if(t==null||!(t instanceof r)||t.bufs.length!==this.bufs.length)return!1;for(let e=0;e<this.bufs.length;e++)if(!Dt(this.bufs[e],t.bufs[e]))return!1;return!0}static fromUint8Arrays(t,e){let n=new r;return n.bufs=t,e==null&&(e=t.reduce((o,s)=>o+s.byteLength,0)),n.length=e,n}};function Pf(r){if(r!=null){if(typeof r[Symbol.iterator]=="function")return r[Symbol.iterator]();if(typeof r[Symbol.asyncIterator]=="function")return r[Symbol.asyncIterator]();if(typeof r.next=="function")return r}throw new Error("argument is not an iterator or iterable")}function Of(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Hf(r,t){let e=Pf(r).return?.();Of(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var V0=5e3;function ec(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Ts=class{id;direction;timeline;protocol;metadata;source;status;readStatus;writeStatus;log;sinkController;sinkEnd;closed;endErr;streamSource;onEnd;onCloseRead;onCloseWrite;onReset;onAbort;sendCloseWriteTimeout;sendingData;constructor(t){this.sinkController=new AbortController,this.sinkEnd=dt(),this.closed=dt(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=t.metadata??{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=t.sendCloseWriteTimeout??V0,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Xe({onEnd:e=>{e!=null?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}async sink(t){if(this.writeStatus!=="ready")throw new tr(`writable end state is "${this.writeStatus}" not "ready"`);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);ec(o)&&await o}let n=()=>{Hf(t,this.log)};try{this.sinkController.signal.addEventListener("abort",n),this.log.trace("sink reading from source");for await(let o of t){o=o instanceof Uint8Array?new ft(o):o;let s=this.sendData(o,e);ec(s)&&(this.sendingData=dt(),await s,this.sendingData.resolve(),this.sendingData=void 0)}}finally{this.sinkController.signal.removeEventListener("abort",n)}this.log.trace('sink finished reading from source, write status is "%s"',this.writeStatus),this.writeStatus==="writing"&&(this.writeStatus="closing",this.log.trace("send close write to remote"),await this.sendCloseWrite({signal:AbortSignal.timeout(this.sendCloseWriteTimeout)}),this.writeStatus="closed"),this.onSinkEnd()}catch(e){throw this.log.trace("sink ended with error, calling abort with error",e),this.abort(e),e}finally{this.log.trace("resolve sink end"),this.sinkEnd.resolve()}}onSourceEnd(t){this.timeline.closeRead==null&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseRead?.(),this.timeline.closeWrite!=null?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(t){this.timeline.closeWrite==null&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",t!=null&&this.endErr==null&&(this.endErr=t),this.onCloseWrite?.(),this.timeline.closeRead!=null?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),this.status!=="aborted"&&this.status!=="reset"&&(this.status="closed"),this.onEnd!=null&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}async close(t){this.log.trace("closing gracefully"),this.status="closing",await Le(Promise.all([this.closeWrite(t),this.closeRead(t),this.closed.promise]),t?.signal),this.status="closed",this.log.trace("closed gracefully")}async closeRead(t={}){if(this.readStatus==="closing"||this.readStatus==="closed")return;this.log.trace('closing readable end of stream with starting read status "%s"',this.readStatus);let e=this.readStatus;this.readStatus="closing",this.status!=="reset"&&this.status!=="aborted"&&this.timeline.closeRead==null&&(this.log.trace("send close read to remote"),await this.sendCloseRead(t)),e==="ready"&&(this.log.trace("ending internal source queue with %d queued bytes",this.streamSource.readableLength),this.streamSource.end()),this.log.trace("closed readable end of stream")}async closeWrite(t={}){this.writeStatus==="closing"||this.writeStatus==="closed"||(this.log.trace('closing writable end of stream with starting write status "%s"',this.writeStatus),this.writeStatus==="ready"&&(this.log.trace("sink was never sunk, sink an empty array"),await Le(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Le(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Le(this.sinkEnd.promise,t.signal)),this.writeStatus="closed",this.log.trace("closed writable end of stream"))}abort(t){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;this.log("abort with error",t),this.log("try to send reset to remote");let e=this.sendReset();ec(e)&&e.catch(n=>{this.log.error("error sending reset message",n)}),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(t),this.onAbort?.(t)}reset(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset")return;let t=new Zn("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),this.onReset?.()}_closeSinkAndSource(t){this._closeSink(t),this._closeSource(t)}_closeSink(t){this.writeStatus==="writing"&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(t)}_closeSource(t){this.readStatus!=="closing"&&this.readStatus!=="closed"&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(t))}remoteCloseWrite(){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("received remote close write but local source is already closed");return}this.log.trace("remote close write"),this._closeSource()}remoteCloseRead(){if(this.writeStatus==="closing"||this.writeStatus==="closed"){this.log("received remote close read but local sink is already closed");return}this.log.trace("remote close read"),this._closeSink()}destroy(){if(this.status==="closed"||this.status==="aborted"||this.status==="reset"){this.log("received destroy but we are already closed");return}this.log.trace("stream destroyed"),this._closeSinkAndSource()}sourcePush(t){this.streamSource.push(t)}sourceReadableLength(){return this.streamSource.readableLength}};function Ns(r){return r[Symbol.asyncIterator]!=null}var _s=r=>{let t=ct(r),e=bt(t);return ce(r,e),_s.bytes=t,e};_s.bytes=0;function Pn(r,t){t=t??{};let e=t.lengthEncoder??_s;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Ns(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Pn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??_s;return new ft(e(r.byteLength),r)};var Ls=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Rs=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Us=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},On=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var F0=8,K0=1024*1024*4,gr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(gr||(gr={}));var rc=r=>{let t=ee(r);return rc.bytes=ct(t),t};rc.bytes=0;function wr(r,t){let e=new ft,n=gr.LENGTH,o=-1,s=t?.lengthDecoder??rc,i=t?.maxLengthLength??F0,a=t?.maxDataLength??K0;function*c(){for(;e.byteLength>0;){if(n===gr.LENGTH)try{if(o=s(e),o<0)throw new Ls("Invalid message length");if(o>a)throw new Rs("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=gr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Us("Message length length too long");break}throw l}if(n===gr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=gr.LENGTH}}}return Ns(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new On("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new On("Unexpected end of input")}()}wr.fromReader=(r,t)=>{let e=1,n=async function*(){for(;;)try{let{done:s,value:i}=await r.next(e);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{e=1}}();return wr(n,{...t??{},onLength:s=>{e=s}})};var W0=r=>{let t=r.addEventListener||r.on||r.addListener,e=r.removeEventListener||r.off||r.removeListener;if(!t||!e)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(r),removeListener:e.bind(r)}};function q0(r,t,e){let n,o=new Promise((s,i)=>{if(e={rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1,...e},!(e.count>=0&&(e.count===Number.POSITIVE_INFINITY||Number.isInteger(e.count))))throw new TypeError("The `count` option should be at least 0 or more");e.signal?.throwIfAborted();let a=[t].flat(),c=[],{addListener:l,removeListener:u}=W0(r),f=(...w)=>{let x=e.multiArgs?w:w[0];e.filter&&!e.filter(x)||(c.push(x),e.count===c.length&&(n(),s(c)))},d=w=>{n(),i(w)};n=()=>{for(let w of a)u(w,f);for(let w of e.rejectionEvents)u(w,d)};for(let w of a)l(w,f);for(let w of e.rejectionEvents)l(w,d);e.signal&&e.signal.addEventListener("abort",()=>{d(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=pr(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function nc(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=q0(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Ot;(function(r){let t;(function(o){o.FIN="FIN",o.STOP_SENDING="STOP_SENDING",o.RESET="RESET",o.FIN_ACK="FIN_ACK"})(t=r.Flag||(r.Flag={}));let e;(function(o){o[o.FIN=0]="FIN",o[o.STOP_SENDING=1]="STOP_SENDING",o[o.RESET=2]="RESET",o[o.FIN_ACK=3]="FIN_ACK"})(e||(e={})),function(o){o.codec=()=>fr(e)}(t=r.Flag||(r.Flag={}));let n;r.codec=()=>(n==null&&(n=se((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.flag!=null&&(s.uint32(8),r.Flag.codec().encode(o.flag,s)),o.message!=null&&(s.uint32(18),s.bytes(o.message)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.flag=r.Flag.codec().decode(o);break}case 2:{a.message=o.bytes();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>oe(o,r.codec()),r.decode=(o,s)=>ne(o,r.codec(),s)})(Ot||(Ot={}));var z0=2*1024*1024,G0=30*1e3,Ds=16*1024;function j0(r=Ds){let t=ct(r-ct(r)),e=1+ct(Object.keys(Ot.Flag).length-1),n=1,o=r-t-e-n,s=ct(o);return t+e+n+s}var Z0=j0(),X0=5e3,Y0=5e3,oc=class extends Ts{channel;incomingData;maxBufferedAmount;bufferedAmountLowEventTimeout;maxMessageSize;receiveFinAck;finAckTimeout;openTimeout;constructor(t){let e=t.onEnd;switch(t.onEnd=o=>{this.log.trace("readable and writeable ends closed",this.status),Promise.resolve(async()=>{if(!(this.timeline.abort!=null||this.timeline.reset!==null))try{await pr(this.receiveFinAck.promise,{milliseconds:this.finAckTimeout})}catch(s){this.log.error("error receiving FIN_ACK",s)}}).then(()=>{this.incomingData.end(),e?.(o)}).catch(s=>{this.log.error("error ending stream",s)})},super(t),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Xe(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??G0,this.maxBufferedAmount=t.maxBufferedAmount??z0,this.maxMessageSize=(t.maxMessageSize??Ds)-Z0,this.receiveFinAck=dt(),this.finAckTimeout=t.closeTimeout??X0,this.openTimeout=t.openTimeout??Y0,this.channel.readyState){case"open":this.timeline.open=new Date().getTime();break;case"closed":case"closing":(this.timeline.close===void 0||this.timeline.close===0)&&(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new tr("Unknown datachannel state")}this.channel.onopen=o=>{this.timeline.open=new Date().getTime()},this.channel.onclose=o=>{this.receiveFinAck.resolve(),this.close().catch(s=>{this.log.error("error closing stream after channel closed",s)})},this.channel.onerror=o=>{let s=o.error;this.abort(s)},this.channel.onmessage=async o=>{let{data:s}=o;s===null||s.byteLength===0||this.incomingData.push(new Uint8Array(s,0,s.byteLength))};let n=this;Promise.resolve().then(async()=>{for await(let o of wr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new ft(s))}}).catch(o=>{this.log.error("error processing incoming data channel messages",o)})}sendNewStream(){}async _sendMessage(t,e=!0){if(e&&this.channel.bufferedAmount>this.maxBufferedAmount)try{this.log('channel buffer is %d, wait for "bufferedamountlow" event',this.channel.bufferedAmount),await nc(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof tn?new tn(`Timed out waiting for DataChannel buffer to clear after ${this.bufferedAmountLowEventTimeout}ms`):n}if(this.channel.readyState==="closed"||this.channel.readyState==="closing")throw new tr(`Invalid datachannel state - ${this.channel.readyState}`);this.channel.readyState!=="open"&&(this.log('channel state is "%s" and not "open", waiting for "open" event before sending data',this.channel.readyState),await nc(this.channel,"open",{timeout:this.openTimeout}),this.log('channel state is now "%s", sending data',this.channel.readyState)),this.channel.send(t.subarray())}async sendData(t){for(t=t.sublist();t.byteLength>0;){let e=Math.min(t.byteLength,this.maxMessageSize),n=t.subarray(0,e),o=Ot.encode({message:n}),s=Pn.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Ot.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Ot.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Le(this.receiveFinAck.promise,t?.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(n){this.log.error("failed to await FIN_ACK",n)}}else this.log.trace("sending FIN failed, not awaiting FIN_ACK");this.receiveFinAck.resolve()}async sendCloseRead(){await this._sendFlag(Ot.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Ot.decode(t);if(e.flag!==void 0&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',e.flag,this.writeStatus,this.readStatus),e.flag===Ot.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Ot.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Ot.Flag.RESET&&this.reset(),e.flag===Ot.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Ot.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),this.readStatus==="ready")return e.message}async _sendFlag(t){if(this.channel.readyState!=="open")return this.log.trace('not sending flag %s because channel is "%s" and not "open"',this.channel.readyState,t.toString()),!1;this.log.trace("sending flag %s",t.toString());let e=Ot.encode({flag:t}),n=Pn.single(e);try{return await this._sendMessage(n,!1),!0}catch(o){this.log.error("could not send flag %s",t.toString(),o)}return!1}};function zr(r){let{channel:t,direction:e}=r;return new oc({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var Mf="/webrtc",Ye=class{protocol;peerConnection;bufferedStreams=[];metrics;dataChannelOptions;components;log;constructor(t,e){this.components=t,this.peerConnection=e.peerConnection,this.metrics=e.metrics,this.protocol=e.protocol??Mf,this.dataChannelOptions=e.dataChannelOptions??{},this.log=t.logger.forComponent("libp2p:webrtc:datachannelmuxerfactory"),this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),n.label==="init"){this.log.trace("closing early init channel"),n.close();return}let o={},s=zr({channel:n,direction:"inbound",onEnd:i=>{o.onEnd(i)},logger:t.logger,...this.dataChannelOptions});o.stream=s,o.channel=n,o.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter(i=>i.stream.id!==s.id)},this.bufferedStreams.push(o)}}createStreamMuxer(t){return new sc(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},sc=class{init;streams;protocol;log;peerConnection;dataChannelOptions;metrics;logger;constructor(t,e){this.init=e,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=e.streams.map(n=>n.stream),this.peerConnection=e.peerConnection,this.protocol=e.protocol??Mf,this.metrics=e.metrics,this.dataChannelOptions=e.dataChannelOptions??{},this.peerConnection.ondatachannel=({channel:n})=>{if(this.log.trace("incoming datachannel with channel id %d",n.id),n.label==="init"){this.log.trace("closing init channel"),n.close();return}let o=zr({channel:n,direction:"inbound",onEnd:()=>{this.log("incoming channel %s ended with state %s",n.id,n.readyState),this.#t(o,n)},logger:this.logger,...this.dataChannelOptions});this.streams.push(o),this.metrics?.increment({incoming_stream:!0}),e?.onIncomingStream?.(o)},this.init.streams.length>0&&queueMicrotask(()=>{this.init.streams.forEach(n=>{n.onEnd=()=>{this.log("incoming early channel %s ended with state %s",n.channel.id,n.channel.readyState),this.#t(n.stream,n.channel)},this.metrics?.increment({incoming_stream:!0}),this.init?.onIncomingStream?.(n.stream)})})}#t(t,e){this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),Rf(e,`${t.direction} ${t.id} ${t.protocol}`,this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter(n=>n.id!==t.id),this.metrics?.increment({stream_end:!0}),this.init?.onStreamEnd?.(t)}async close(t){try{await Promise.all(this.streams.map(async e=>e.close(t)))}catch(e){this.abort(e)}}abort(t){for(let e of this.streams)e.abort(t)}source=As();sink=Bs;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=zr({channel:t,direction:"outbound",onEnd:()=>{this.log("outgoing channel %s ended with state %s",t.id,t.readyState),this.#t(e,t)},logger:this.logger,...this.dataChannelOptions});return this.streams.push(e),this.metrics?.increment({outgoing_stream:!0}),e}};var yr=globalThis.RTCPeerConnection,Ps=globalThis.RTCSessionDescription,Vf=globalThis.RTCIceCandidate;var ic=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=dt(),this.haveNext=dt()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let t=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=dt(),t}async throw(t){return this.ended=!0,t!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(t)),{done:!0,value:void 0}}async return(){let t={done:!0,value:void 0};return await this._push(void 0),t}async push(t,e){await this._push(t,e)}async end(t,e){t!=null?await this.throw(t):await this._push(void 0,e)}async _push(t,e){if(t!=null&&this.ended)throw new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;t!=null?this.nextResult={done:!1,value:t}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=dt(),await Le(this.readNext.promise,e?.signal,e)}};function Ff(){return new ic}var Os=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var ac=class extends Error{code;constructor(t,e){super(t),this.code=e}},cc=class extends ac{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function Kf(r,t){let e=Ff();r.sink(e).catch(async i=>{await e.end(i)}),r.sink=async i=>{for await(let a of i)await e.push(a);await e.end()};let n=r.source;r.source[Symbol.iterator]!=null?n=r.source[Symbol.iterator]():r.source[Symbol.asyncIterator]!=null&&(n=r.source[Symbol.asyncIterator]());let o=new ft;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new cc("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:d}=await Promise.race([n.next(),l]);return f===!0?new ft:d}for(;o.byteLength<i;){let{value:f,done:d}=await Promise.race([n.next(),l]);if(d===!0)throw new Os("unexpected end of input");o.append(f)}let u=o.sublist(0,i);return o.consume(i),u}finally{c!=null&&a?.signal?.removeEventListener("abort",c)}},write:async(i,a)=>{a?.signal?.throwIfAborted(),i instanceof Uint8Array?await e.push(i,a):await e.push(i.subarray(),a)},unwrap:()=>{if(o.byteLength>0){let i=r.source;r.source=async function*(){t?.yieldBytes===!1?yield o:yield*o,yield*i}()}return r}}}var Hs=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Ms=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Vs=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Hn(r,t={}){let e=Kf(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=ct(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??ce;return{read:async i=>{let a=-1,c=new ft;for(;;){c.append(await e.read(1,i));try{a=n(c)}catch(l){if(l instanceof RangeError)continue;throw l}if(a<0)throw new Hs("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Vs("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Ms("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new ft(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new ft(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Fs(r,t){let e=Hn(r,t),n={read:async(o,s)=>{let i=await e.read(s);return o.decode(i)},write:async(o,s,i)=>{await e.write(s.encode(o),i)},writeV:async(o,s,i)=>{await e.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>e.unwrap()};return n}var qt=class extends Event{type;detail;constructor(t,e){super(t),this.type=t,this.detail=e}};var Je=class extends Error{constructor(t){super(`WebRTC transport error: ${t}`),this.name="WebRTCTransportError"}},Zt=class extends Je{constructor(t="SDP handshake failed"){super(t),this.name="SDPHandshakeFailedError"}};var Mn=class extends Je{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`),this.name="WebRTC/DataChannelError"}},Ks=class extends Je{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`),this.name="WebRTC/InappropriateMultiaddrError"}};var Vn=class extends Je{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`),this.name="WebRTC/InvalidFingerprintError"}};var $s=class extends Je{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`),this.name="WebRTC/UnimplementedError"}},Ws=class extends Je{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `),this.name="WebRTC/UnsupportedHashAlgorithmError"}};var Kt;(function(r){let t;(function(o){o.SDP_OFFER="SDP_OFFER",o.SDP_ANSWER="SDP_ANSWER",o.ICE_CANDIDATE="ICE_CANDIDATE"})(t=r.Type||(r.Type={}));let e;(function(o){o[o.SDP_OFFER=0]="SDP_OFFER",o[o.SDP_ANSWER=1]="SDP_ANSWER",o[o.ICE_CANDIDATE=2]="ICE_CANDIDATE"})(e||(e={})),function(o){o.codec=()=>fr(e)}(t=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=se((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.data!=null&&(s.uint32(18),s.string(o.data)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.data=o.string();break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>oe(o,r.codec()),r.decode=(o,s)=>ne(o,r.codec(),s)})(Kt||(Kt={}));var qs=async(r,t,e)=>{try{let n=dt();for(J0(r,n);;){let o=await Promise.race([n.promise,t.read({signal:e.signal}).catch(()=>{})]);if(o==null){e.signal?.throwIfAborted();break}if(o.type!==Kt.Type.ICE_CANDIDATE)throw new Yn("ICE candidate message expected");let s=JSON.parse(o.data??"null");if(s===""||s===null){e.onProgress?.(new qt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new Vf(s);e.log.trace("%s received new ICE candidate %o",e.direction,s);try{e.onProgress?.(new qt("webrtc:add-ice-candidate",i.candidate)),await r.addIceCandidate(i)}catch(a){e.log.error("%s bad candidate received",e.direction,s,a)}}}catch(n){if(e.log.error("%s error parsing ICE candidate",e.direction,n),e.signal?.aborted===!0&&zs(r)!=="connected")throw n}};function zs(r){return Un?r.iceConnectionState:r.connectionState}function J0(r,t){r[Un?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(zs(r)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new jn("RTCPeerConnection was closed"));break;default:break}}}async function $f({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Wf(o);n?.dialerEvents.increment({open:!0}),a.trace("dialing base address: %a",u);let f=u.getPeerId();if(f==null)throw new tt("Relay peer was missing");let d=s.getConnections(Kr(f)),w,x=!1;d.length===0?(l?.(new qt("webrtc:dial-relay")),w=await i.dial(u,{signal:e,onProgress:l}),x=!0):(l?.(new qt("webrtc:reuse-relay-connection")),w=d[0]);try{l?.(new qt("webrtc:open-signaling-stream"));let m=await w.newStream(Gs,{signal:e,runOnLimitedConnection:!0}),h=Fs(m).pb(Kt),g=new yr(r),b=new Ye({logger:c},{peerConnection:g,dataChannelOptions:t});try{let p=g.createDataChannel("init");g.onicecandidate=({candidate:A})=>{let k=JSON.stringify(A?.toJSON()??null);a.trace("initiator sending ICE candidate %o",A),h.write({type:Kt.Type.ICE_CANDIDATE,data:k},{signal:e}).catch(I=>{a.error("error sending ICE candidate",I)})},g.onicecandidateerror=A=>{a.error("initiator ICE candidate error",A)};let B=await g.createOffer().catch(A=>{throw a.error("could not execute createOffer",A),new Zt("Failed to set createOffer")});a.trace("initiator send SDP offer %s",B.sdp),l?.(new qt("webrtc:send-sdp-offer")),await h.write({type:Kt.Type.SDP_OFFER,data:B.sdp},{signal:e}),await g.setLocalDescription(B).catch(A=>{throw a.error("could not execute setLocalDescription",A),new Zt("Failed to set localDescription")}),l?.(new qt("webrtc:read-sdp-answer")),a.trace("initiator read SDP answer");let _=await h.read({signal:e});if(_.type!==Kt.Type.SDP_ANSWER)throw new Zt("Remote should send an SDP answer");a.trace("initiator received SDP answer %s",_.data);let N=new Ps({type:"answer",sdp:_.data});return await g.setRemoteDescription(N).catch(A=>{throw a.error("could not execute setRemoteDescription",A),new Zt("Failed to set remoteDescription")}),a.trace("initiator read candidates until connected"),l?.(new qt("webrtc:read-ice-candidates")),await qs(g,h,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),p.close(),l?.(new qt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await m.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:g,muxerFactory:b}}catch(p){throw a.error("outgoing signaling error",p),g.close(),m.abort(p),p}finally{g.onicecandidate=null,g.onicecandidateerror=null}}finally{if(x)try{await w.close({signal:e})}catch(m){w.abort(m)}}}var Q0=U("dns4"),tg=U("dns6"),eg=U("dnsaddr"),br=mt(U("dns"),eg,Q0,tg),Xs=mt(U("ip4"),U("ip6")),Gr=mt(F(Xs,U("tcp")),F(br,U("tcp"))),Ys=F(Xs,U("udp")),rg=F(Ys,U("utp")),ng=F(Ys,U("quic")),og=F(Ys,U("quic-v1")),lc=mt(F(Gr,U("ws")),F(br,U("ws"))),js=mt(F(lc,U("p2p")),lc),uc=mt(F(Gr,U("wss")),F(br,U("wss")),F(Gr,U("tls"),U("ws")),F(br,U("tls"),U("ws"))),Zs=mt(F(uc,U("p2p")),uc),fc=mt(F(Gr,U("http")),F(Xs,U("http")),F(br,U("http"))),hc=mt(F(Gr,U("https")),F(Xs,U("https")),F(br,U("https"))),qf=F(Ys,U("webrtc-direct"),U("certhash")),jf=mt(F(qf,U("p2p")),qf),zf=F(og,U("webtransport"),U("certhash"),U("certhash")),Zf=mt(F(zf,U("p2p")),zf),Xf=mt(F(js,U("p2p-webrtc-star"),U("p2p")),F(Zs,U("p2p-webrtc-star"),U("p2p")),F(js,U("p2p-webrtc-star")),F(Zs,U("p2p-webrtc-star"))),bS=mt(F(js,U("p2p-websocket-star"),U("p2p")),F(Zs,U("p2p-websocket-star"),U("p2p")),F(js,U("p2p-websocket-star")),F(Zs,U("p2p-websocket-star"))),Yf=mt(F(fc,U("p2p-webrtc-direct"),U("p2p")),F(hc,U("p2p-webrtc-direct"),U("p2p")),F(fc,U("p2p-webrtc-direct")),F(hc,U("p2p-webrtc-direct"))),xr=mt(lc,uc,fc,hc,Xf,Yf,Gr,rg,ng,br,jf,Zf),xS=mt(F(xr,U("p2p-stardust"),U("p2p")),F(xr,U("p2p-stardust"))),Qe=mt(F(xr,U("p2p")),Xf,Yf,jf,Zf,U("p2p")),Gf=mt(F(Qe,U("p2p-circuit"),Qe),F(Qe,U("p2p-circuit")),F(U("p2p-circuit"),Qe),F(xr,U("p2p-circuit")),F(U("p2p-circuit"),xr),U("p2p-circuit")),Jf=()=>mt(F(Gf,Jf),Gf),Re=Jf(),ES=mt(F(Re,Qe,Re),F(Qe,Re),F(Re,Qe),Re,Qe);var vS=mt(F(Re,U("webrtc"),U("p2p")),F(Re,U("webrtc")),F(xr,U("webrtc"),U("p2p")),F(xr,U("webrtc")),U("webrtc"));function Qf(r){function t(e){let n;try{n=ae(e)}catch{return!1}let o=r(n.protoNames());return o===null?!1:o===!0||o===!1?o:o.length===0}return t}function F(...r){function t(e){if(e.length<r.length)return null;let n=e;return r.some(o=>(n=typeof o=="function"?o().partialMatch(e):o.partialMatch(e),Array.isArray(n)&&(e=n),n===null)),n}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Qf(t),partialMatch:t}}function mt(...r){function t(n){let o=null;return r.some(s=>{let i=typeof s=="function"?s().partialMatch(n):s.partialMatch(n);return i!=null?(o=i,!0):!1}),o}return{toString:function(){return"{ "+r.join(" ")+" }"},input:r,matches:Qf(t),partialMatch:t}}function U(r){let t=r;function e(o){let s;try{s=ae(o)}catch{return!1}let i=s.protoNames();return i.length===1&&i[0]===t}function n(o){return o.length===0?null:o[0]===t?o.slice(1):null}return{toString:function(){return t},matches:e,partialMatch:n}}var Js=class extends Qn{peerId;transportManager;shutdownController;constructor(t,e){super(),this.peerId=t.peerId,this.transportManager=t.transportManager,this.shutdownController=e.shutdownController}async listen(){this.safeDispatchEvent("listening",{})}getAddrs(){return this.transportManager.getListeners().filter(t=>t!==this).map(t=>t.getAddrs().filter(e=>Re.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function th({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Fs(t).pb(Kt);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Kt.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(d=>{o.error("error sending ICE candidate",d)})},o.trace("recipient read SDP offer");let a=await s.read({signal:e});if(a.type!==Kt.Type.SDP_OFFER)throw new Zt(`expected message type SDP_OFFER, received: ${a.type??"undefined"} `);o.trace("recipient received SDP offer %s",a.data);let c=new Ps({type:"offer",sdp:a.data});await r.setRemoteDescription(c).catch(u=>{throw o.error("could not execute setRemoteDescription",u),new Zt("Failed to set remoteDescription")});let l=await r.createAnswer().catch(u=>{throw o.error("could not execute createAnswer",u),new Zt("Failed to create answer")});o.trace("recipient send SDP answer %s",l.sdp),await s.write({type:Kt.Type.SDP_ANSWER,data:l.sdp},{signal:e}),await r.setLocalDescription(l).catch(u=>{throw o.error("could not execute setLocalDescription",u),new Zt("Failed to set localDescription")}),o.trace("recipient read candidates until connected"),await qs(r,s,{direction:"recipient",signal:e,log:o})}catch(a){if(zs(r)!=="connected")throw o.error("error while handling signaling stream from peer %a",n.remoteAddr,a),r.close(),a;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",n.remoteAddr,a)}let i=ae(`/webrtc/p2p/${n.remoteAddr.getPeerId()}`);return o.trace("recipient connected to remote address %s",i),{remoteAddress:i}}var sg="/webrtc",ig="/p2p-circuit",Gs="/webrtc-signaling/0.0.1",ag=30*1e3,Qs=class{components;init;log;_started=!1;metrics;shutdownController;constructor(t,e={}){this.components=t,this.init=e,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,Jn(1/0,this.shutdownController.signal),t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}[zn]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Sr]=["@libp2p/transport"];[zc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Gs,t=>{this._onProtocol(t).catch(e=>{this.log.error("failed to handle incoming connect from %p",t.connection.remotePeer,e)})},{runOnLimitedConnection:!0}),this._started=!0}async stop(){await this.components.registrar.unhandle(Gs),this._started=!1}createListener(t){return new Js(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Sf.exactMatch)}dialFilter(t){return this.listenFilter(t)}async dial(t,e){this.log.trace("dialing address: %a",t);let{remoteAddress:n,peerConnection:o,muxerFactory:s}=await $f({rtcConfiguration:await Dn(this.init.rtcConfiguration),dataChannel:this.init.dataChannel,multiaddr:t,dataChannelOptions:this.init.dataChannel,signal:e.signal,connectionManager:this.components.connectionManager,transportManager:this.components.transportManager,log:this.log,logger:this.components.logger,onProgress:e.onProgress}),i=new mr(this.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:n,metrics:this.metrics?.dialerEvents}),a=await e.upgrader.upgradeOutbound(i,{skipProtection:!0,skipEncryption:!0,muxerFactory:s,onProgress:e.onProgress});return this._closeOnShutdown(o,i),a}async _onProtocol({connection:t,stream:e}){let n=AbortSignal.timeout(this.init.inboundConnectionTimeout??ag),o=new yr(await Dn(this.init.rtcConfiguration)),s=new Ye(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await th({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new mr(this.components,{peerConnection:o,timeline:{open:new Date().getTime()},remoteAddr:i,metrics:this.metrics?.listenerEvents});await this.components.upgrader.upgradeInbound(a,{skipEncryption:!0,skipProtection:!0,muxerFactory:s}),this._closeOnShutdown(o,a)}catch(i){throw this.log.error("incoming signaling error",i),o.close(),e.abort(i),i}}_closeOnShutdown(t,e){let n=()=>{e.close().catch(o=>{this.log.error("could not close WebRTCMultiaddrConnection",o)})};this.shutdownController.signal.addEventListener("abort",n),t.addEventListener("close",()=>{this.shutdownController.signal.removeEventListener("abort",n)})}};function Wf(r){let t=r.toString().split(sg+"/");if(t.length!==2)throw new tt("webrtc protocol was not present in multiaddr");if(!t[0].includes(ig))throw new tt("p2p-circuit protocol was not present in multiaddr");let e=ae(t[0]),o=ae("/"+t[1]).getPeerId();if(o==null)throw new tt("destination peer id was missing");let s=e.protos().pop();if(s===void 0)throw new tt("invalid multiaddr");return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:Kr(o)}}function dc(){let r=dt(),t=!1;return{sink:async e=>{if(t)throw new Error("already piped");t=!0,r.resolve(e)},source:async function*(){yield*await r.promise}()}}function eh(){let r=dc(),t=dc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function cg(r){return r[Symbol.asyncIterator]!=null}function lg(...r){let t=[];for(let e of r)cg(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Xe({objectMode:!0});Promise.resolve().then(async()=>{try{await Promise.all(r.map(async n=>{for await(let o of n)e.push(o)})),e.end()}catch(n){e.end(n)}}),yield*e}()}var rh=lg;function nh(r,...t){if(r==null)throw new Error("Empty pipeline");if(pc(r)){let n=r;r=()=>n.source}else if(sh(r)||oh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&pc(e[e.length-1])&&(e[e.length-1]=e[e.length-1].sink),e.length>2)for(let n=1;n<e.length-1;n++)pc(e[n])&&(e[n]=fg(e[n]));return ug(...e)}var ug=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},oh=r=>r?.[Symbol.asyncIterator]!=null,sh=r=>r?.[Symbol.iterator]!=null,pc=r=>r==null?!1:r.sink!=null&&r.source!=null,fg=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Xe({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(oh(s))o=async function*(){yield*s,n.end()};else if(sh(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return rh(n,o())}return r.source};var jr=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function ti(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function mc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function gc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function $t(r,...t){if(!gc(r))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(r.length))throw new Error(`Uint8Array expected of length ${t}, not of length=${r.length}`)}function wc(r,t=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(t&&r.finished)throw new Error("Hash#digest() has already been called")}function ih(r,t){$t(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Ue=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),ah=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),hg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!hg)throw new Error("Non little-endian hardware is not supported");function dg(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function ei(r){if(typeof r=="string")r=dg(r);else if(gc(r))r=ri(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function ch(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function lh(r,t){if(r.length!==t.length)return!1;let e=0;for(let n=0;n<r.length;n++)e|=r[n]^t[n];return e===0}var yc=(r,t)=>(Object.assign(t,r),t);function bc(r,t,e,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(t,e,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(e>>o&s),a=Number(e&s),c=n?4:0,l=n?0:4;r.setUint32(t+c,i,n),r.setUint32(t+l,a,n)}function ri(r){return Uint8Array.from(r)}function De(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var fh=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),pg=fh("expand 16-byte k"),mg=fh("expand 32-byte k"),gg=Ue(pg),hh=Ue(mg),aA=hh.slice();function O(r,t){return r<<t|r>>>32-t}function xc(r){return r.byteOffset%4===0}var ni=64,wg=16,dh=2**32-1,uh=new Uint32Array;function yg(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(ni),u=Ue(l),f=xc(o)&&xc(s),d=f?Ue(o):uh,w=f?Ue(s):uh;for(let x=0;x<c;i++){if(r(t,e,n,u,i,a),i>=dh)throw new Error("arx: counter overflow");let m=Math.min(ni,c-x);if(f&&m===ni){let h=x/4;if(x%4!==0)throw new Error("arx: invalid block position");for(let g=0,b;g<wg;g++)b=h+g,w[b]=d[b]^u[g];x+=ni;continue}for(let h=0,g;h<m;h++)g=x+h,s[g]=o[g]^l[h];x+=m}}function Ec(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=ch({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return ti(o),ti(i),mc(s),mc(e),(a,c,l,u,f=0)=>{$t(a),$t(c),$t(l);let d=l.length;if(u===void 0&&(u=new Uint8Array(d)),$t(u),ti(f),f<0||f>=dh)throw new Error("arx: counter overflow");if(u.length<d)throw new Error(`arx: output (${u.length}) is shorter than data (${d})`);let w=[],x=a.length,m,h;if(x===32)w.push(m=ri(a)),h=hh;else if(x===16&&e)m=new Uint8Array(32),m.set(a),m.set(a,16),h=gg,w.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${x}`);xc(c)||w.push(c=ri(c));let g=Ue(m);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(h,g,Ue(c.subarray(0,16)),g),c=c.subarray(16)}let b=16-o;if(b!==c.length)throw new Error(`arx: nonce must be ${b} or 16 bytes`);if(b!==12){let B=new Uint8Array(12);B.set(c,s?0:12-c.length),c=B,w.push(c)}let p=Ue(c);return yg(r,h,g,p,l,u,f,i),De(...w),u}}var Tt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,vc=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,t=ei(t),$t(t,32);let e=Tt(t,0),n=Tt(t,2),o=Tt(t,4),s=Tt(t,6),i=Tt(t,8),a=Tt(t,10),c=Tt(t,12),l=Tt(t,14);this.r[0]=e&8191,this.r[1]=(e>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Tt(t,16+2*u)}process(t,e,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],f=i[4],d=i[5],w=i[6],x=i[7],m=i[8],h=i[9],g=Tt(t,e+0),b=Tt(t,e+2),p=Tt(t,e+4),B=Tt(t,e+6),_=Tt(t,e+8),N=Tt(t,e+10),A=Tt(t,e+12),k=Tt(t,e+14),I=s[0]+(g&8191),V=s[1]+((g>>>13|b<<3)&8191),L=s[2]+((b>>>10|p<<6)&8191),H=s[3]+((p>>>7|B<<9)&8191),K=s[4]+((B>>>4|_<<12)&8191),C=s[5]+(_>>>1&8191),T=s[6]+((_>>>14|N<<2)&8191),E=s[7]+((N>>>11|A<<5)&8191),y=s[8]+((A>>>8|k<<8)&8191),S=s[9]+(k>>>5|o),v=0,R=v+I*a+V*(5*h)+L*(5*m)+H*(5*x)+K*(5*w);v=R>>>13,R&=8191,R+=C*(5*d)+T*(5*f)+E*(5*u)+y*(5*l)+S*(5*c),v+=R>>>13,R&=8191;let D=v+I*c+V*a+L*(5*h)+H*(5*m)+K*(5*x);v=D>>>13,D&=8191,D+=C*(5*w)+T*(5*d)+E*(5*f)+y*(5*u)+S*(5*l),v+=D>>>13,D&=8191;let M=v+I*l+V*c+L*a+H*(5*h)+K*(5*m);v=M>>>13,M&=8191,M+=C*(5*x)+T*(5*w)+E*(5*d)+y*(5*f)+S*(5*u),v+=M>>>13,M&=8191;let $=v+I*u+V*l+L*c+H*a+K*(5*h);v=$>>>13,$&=8191,$+=C*(5*m)+T*(5*x)+E*(5*w)+y*(5*d)+S*(5*f),v+=$>>>13,$&=8191;let W=v+I*f+V*u+L*l+H*c+K*a;v=W>>>13,W&=8191,W+=C*(5*h)+T*(5*m)+E*(5*x)+y*(5*w)+S*(5*d),v+=W>>>13,W&=8191;let G=v+I*d+V*f+L*u+H*l+K*c;v=G>>>13,G&=8191,G+=C*a+T*(5*h)+E*(5*m)+y*(5*x)+S*(5*w),v+=G>>>13,G&=8191;let Z=v+I*w+V*d+L*f+H*u+K*l;v=Z>>>13,Z&=8191,Z+=C*c+T*a+E*(5*h)+y*(5*m)+S*(5*x),v+=Z>>>13,Z&=8191;let ot=v+I*x+V*w+L*d+H*f+K*u;v=ot>>>13,ot&=8191,ot+=C*l+T*c+E*a+y*(5*h)+S*(5*m),v+=ot>>>13,ot&=8191;let st=v+I*m+V*x+L*w+H*d+K*f;v=st>>>13,st&=8191,st+=C*u+T*l+E*c+y*a+S*(5*h),v+=st>>>13,st&=8191;let lt=v+I*h+V*m+L*x+H*w+K*d;v=lt>>>13,lt&=8191,lt+=C*f+T*u+E*l+y*c+S*a,v+=lt>>>13,lt&=8191,v=(v<<2)+v|0,v=v+R|0,R=v&8191,v=v>>>13,D+=v,s[0]=R,s[1]=D,s[2]=M,s[3]=$,s[4]=W,s[5]=G,s[6]=Z,s[7]=ot,s[8]=st,s[9]=lt}finalize(){let{h:t,pad:e}=this,n=new Uint16Array(10),o=t[1]>>>13;t[1]&=8191;for(let a=2;a<10;a++)t[a]+=o,o=t[a]>>>13,t[a]&=8191;t[0]+=o*5,o=t[0]>>>13,t[0]&=8191,t[1]+=o,o=t[1]>>>13,t[1]&=8191,t[2]+=o,n[0]=t[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=t[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)t[a]=t[a]&s|n[a];t[0]=(t[0]|t[1]<<13)&65535,t[1]=(t[1]>>>3|t[2]<<10)&65535,t[2]=(t[2]>>>6|t[3]<<7)&65535,t[3]=(t[3]>>>9|t[4]<<4)&65535,t[4]=(t[4]>>>12|t[5]<<1|t[6]<<14)&65535,t[5]=(t[6]>>>2|t[7]<<11)&65535,t[6]=(t[7]>>>5|t[8]<<8)&65535,t[7]=(t[8]>>>8|t[9]<<5)&65535;let i=t[0]+e[0];t[0]=i&65535;for(let a=1;a<8;a++)i=(t[a]+e[a]|0)+(i>>>16)|0,t[a]=i&65535;De(n)}update(t){wc(this);let{buffer:e,blockLen:n}=this;t=ei(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(t,s);continue}e.set(t.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(e,0,!1),this.pos=0)}return this}destroy(){De(this.h,this.r,this.buffer,this.pad)}digestInto(t){wc(this),ih(t,this),this.finished=!0;let{buffer:e,h:n}=this,{pos:o}=this;if(o){for(e[o++]=1;o<16;o++)e[o]=0;this.process(e,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)t[s++]=n[i]>>>0,t[s++]=n[i]>>>8;return t}digest(){let{buffer:t,outputLen:e}=this;this.digestInto(t);let n=t.slice(0,e);return this.destroy(),n}};function bg(r){let t=(n,o)=>r(o).update(ei(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var ph=bg(r=>new vc(r));function wh(r,t,e,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=t[0],f=t[1],d=t[2],w=t[3],x=t[4],m=t[5],h=t[6],g=t[7],b=o,p=e[0],B=e[1],_=e[2],N=i,A=a,k=c,I=l,V=u,L=f,H=d,K=w,C=x,T=m,E=h,y=g,S=b,v=p,R=B,D=_;for(let $=0;$<s;$+=2)N=N+V|0,S=O(S^N,16),C=C+S|0,V=O(V^C,12),N=N+V|0,S=O(S^N,8),C=C+S|0,V=O(V^C,7),A=A+L|0,v=O(v^A,16),T=T+v|0,L=O(L^T,12),A=A+L|0,v=O(v^A,8),T=T+v|0,L=O(L^T,7),k=k+H|0,R=O(R^k,16),E=E+R|0,H=O(H^E,12),k=k+H|0,R=O(R^k,8),E=E+R|0,H=O(H^E,7),I=I+K|0,D=O(D^I,16),y=y+D|0,K=O(K^y,12),I=I+K|0,D=O(D^I,8),y=y+D|0,K=O(K^y,7),N=N+L|0,D=O(D^N,16),E=E+D|0,L=O(L^E,12),N=N+L|0,D=O(D^N,8),E=E+D|0,L=O(L^E,7),A=A+H|0,S=O(S^A,16),y=y+S|0,H=O(H^y,12),A=A+H|0,S=O(S^A,8),y=y+S|0,H=O(H^y,7),k=k+K|0,v=O(v^k,16),C=C+v|0,K=O(K^C,12),k=k+K|0,v=O(v^k,8),C=C+v|0,K=O(K^C,7),I=I+V|0,R=O(R^I,16),T=T+R|0,V=O(V^T,12),I=I+V|0,R=O(R^I,8),T=T+R|0,V=O(V^T,7);let M=0;n[M++]=i+N|0,n[M++]=a+A|0,n[M++]=c+k|0,n[M++]=l+I|0,n[M++]=u+V|0,n[M++]=f+L|0,n[M++]=d+H|0,n[M++]=w+K|0,n[M++]=x+C|0,n[M++]=m+T|0,n[M++]=h+E|0,n[M++]=g+y|0,n[M++]=b+S|0,n[M++]=p+v|0,n[M++]=B+R|0,n[M++]=_+D|0}function xg(r,t,e,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=t[0],l=t[1],u=t[2],f=t[3],d=t[4],w=t[5],x=t[6],m=t[7],h=e[0],g=e[1],b=e[2],p=e[3];for(let _=0;_<20;_+=2)o=o+c|0,h=O(h^o,16),d=d+h|0,c=O(c^d,12),o=o+c|0,h=O(h^o,8),d=d+h|0,c=O(c^d,7),s=s+l|0,g=O(g^s,16),w=w+g|0,l=O(l^w,12),s=s+l|0,g=O(g^s,8),w=w+g|0,l=O(l^w,7),i=i+u|0,b=O(b^i,16),x=x+b|0,u=O(u^x,12),i=i+u|0,b=O(b^i,8),x=x+b|0,u=O(u^x,7),a=a+f|0,p=O(p^a,16),m=m+p|0,f=O(f^m,12),a=a+f|0,p=O(p^a,8),m=m+p|0,f=O(f^m,7),o=o+l|0,p=O(p^o,16),x=x+p|0,l=O(l^x,12),o=o+l|0,p=O(p^o,8),x=x+p|0,l=O(l^x,7),s=s+u|0,h=O(h^s,16),m=m+h|0,u=O(u^m,12),s=s+u|0,h=O(h^s,8),m=m+h|0,u=O(u^m,7),i=i+f|0,g=O(g^i,16),d=d+g|0,f=O(f^d,12),i=i+f|0,g=O(g^i,8),d=d+g|0,f=O(f^d,7),a=a+c|0,b=O(b^a,16),w=w+b|0,c=O(c^w,12),a=a+c|0,b=O(b^a,8),w=w+b|0,c=O(c^w,7);let B=0;n[B++]=o,n[B++]=s,n[B++]=i,n[B++]=a,n[B++]=h,n[B++]=g,n[B++]=b,n[B++]=p}var Eg=Ec(wh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),vg=Ec(wh,{counterRight:!1,counterLength:8,extendNonceFn:xg,allowShortKeys:!1});var Sg=new Uint8Array(16),mh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(Sg.subarray(e))},Ag=new Uint8Array(32);function gh(r,t,e,n,o){let s=r(t,e,Ag),i=ph.create(s);o&&mh(i,o),mh(i,n);let a=new Uint8Array(16),c=ah(a);bc(c,0,BigInt(o?o.length:0),!0),bc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return De(s,a),l}var yh=r=>(t,e,n)=>($t(t,32),$t(e),{encrypt(s,i){let a=s.length,c=a+16;i?$t(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=gh(r,t,e,i.subarray(0,-16),n);return i.set(l,a),De(l),i},decrypt(s,i){let a=s.length,c=a-16;if(a<16)throw new Error("encrypted data must be at least 16 bytes");i?$t(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=gh(r,t,e,l,n);if(!lh(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),De(f),i}}),Sc=yc({blockSize:64,nonceLength:12,tagLength:16},yh(Eg)),gA=yc({blockSize:64,nonceLength:24,tagLength:16},yh(vg));function xh(r,t,e){return on(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Fr(r,He(e),He(t))}var Ac=new Uint8Array([0]),bh=new Uint8Array;function Eh(r,t,e,n=32){if(on(r),eo(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=bh);let s=new Uint8Array(o*r.outputLen),i=Fr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Ac[0]=l+1,a.update(l===0?bh:c).update(e).update(Ac).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Ac.fill(0),s.slice(0,n)}var Bc={hashSHA256(r){return ue(r.subarray())},getHKDF(r,t){let e=xh(ue,t,r),o=Eh(ue,e,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=fn.utils.randomPrivateKey();return{publicKey:fn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:fn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return fn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Sc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Sc(n,t,e).decrypt(r.subarray(),o)}};var vh=Bc;function Sh(r){return{generateKeypair:r.generateX25519KeyPair,dh:(t,e)=>r.generateX25519SharedKey(t.privateKey,e).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}var Zr=r=>{let t=bt(2);return t[0]=r>>8,t[1]=r,t};Zr.bytes=2;var Fn=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let t=0;return t+=r[0]<<8,t+=r[1],t}return r.getUint16(0)};Fn.bytes=2;function Ah(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}function Ic(r,t){!t.enabled||!jr||(r?(t(`LOCAL_STATIC_PUBLIC_KEY ${z(r.publicKey,"hex")}`),t(`LOCAL_STATIC_PRIVATE_KEY ${z(r.privateKey,"hex")}`)):t("Missing local static keys."))}function Cc(r,t){!t.enabled||!jr||(r?(t(`LOCAL_PUBLIC_EPHEMERAL_KEY ${z(r.publicKey,"hex")}`),t(`LOCAL_PRIVATE_EPHEMERAL_KEY ${z(r.privateKey,"hex")}`)):t("Missing local ephemeral keys."))}function Bh(r,t){!t.enabled||!jr||t(r?`REMOTE_STATIC_PUBLIC_KEY ${z(r.subarray(),"hex")}`:"Missing remote static public key.")}function kc(r,t){!t.enabled||!jr||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${z(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Tc(r,t,e){!e.enabled||!jr||(e(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&z(r.k,"hex")}`),e(`CIPHER_STATE_2 ${t.n.getUint64()} ${t.k&&z(t.k,"hex")}`))}var Xr=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var Bg=0,Ig=4294967295,Cg="Cipherstate has reached maximum n, a new handshake must be performed",oi=class{n;bytes;view;constructor(t=Bg){this.n=t,this.bytes=yt(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>Ig)throw new Error(Cg)}};var Er=yt(0),Yr=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new oi(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Nc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=et(e,"utf-8");this.h=kg(t,n),this.ck=this.h,this.cs=new Yr(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new Yr(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new ft(this.h,t))}encryptAndHash(t){let e=this.cs.encryptWithAd(this.h,t);return this.mixHash(e),e}decryptAndHash(t){let e=this.cs.decryptWithAd(this.h,t);return this.mixHash(t),e}split(){let[t,e]=this.crypto.hkdf(this.ck,Er);return[new Yr(this.crypto,t),new Yr(this.crypto,e)]}},_c=class{ss;s;e;rs;re;initiator;crypto;constructor(t){let{crypto:e,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=t;this.crypto=e,this.ss=new Nc(e,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let t=this.crypto.generateKeypair();return this.ss.mixHash(t.publicKey),this.e=t,t.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(t,e=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(t.byteLength<e+32)throw new Error("message is not long enough");this.re=t.sublist(e,e+32),this.ss.mixHash(this.re)}readS(t,e=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(t.byteLength<e+n)throw new Error("message is not long enough");let o=t.sublist(e,e+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},Kn=class extends _c{writeMessageA(t){return new ft(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new ft(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new ft(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new Xr(`handshake stage 0 validation fail: ${e.message}`)}}readMessageB(t){try{this.readE(t),this.readEE();let e=this.readS(t,32);return this.readES(),this.ss.decryptAndHash(t.sublist(32+e))}catch(e){throw new Xr(`handshake stage 1 validation fail: ${e.message}`)}}readMessageC(t){try{let e=this.readS(t);return this.readSE(),this.ss.decryptAndHash(t.sublist(e))}catch(e){throw new Xr(`handshake stage 2 validation fail: ${e.message}`)}}};function kg(r,t){if(t.length<=32){let e=yt(32);return e.set(t),e}else return r.hash(t)}var si;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),e.webtransportCerthashes!=null)for(let s of e.webtransportCerthashes)n.uint32(10),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={webtransportCerthashes:[]},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.webtransportCerthashes.push(e.bytes());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>oe(e,r.codec()),r.decode=e=>ne(e,r.codec())})(si||(si={}));var $n;(function(r){let t;r.codec=()=>(t==null&&(t=se((e,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),e.identityKey!=null&&e.identityKey.byteLength>0&&(n.uint32(10),n.bytes(e.identityKey)),e.identitySig!=null&&e.identitySig.byteLength>0&&(n.uint32(18),n.bytes(e.identitySig)),e.extensions!=null&&(n.uint32(34),si.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:yt(0),identitySig:yt(0)},s=n==null?e.len:e.pos+n;for(;e.pos<s;){let i=e.uint32();switch(i>>>3){case 1:{o.identityKey=e.bytes();break}case 2:{o.identitySig=e.bytes();break}case 4:{o.extensions=si.codec().decode(e,e.uint32());break}default:{e.skipType(i&7);break}}}return o})),t),r.encode=e=>oe(e,r.codec()),r.decode=e=>ne(e,r.codec())})($n||($n={}));async function Lc(r,t,e){let n=await r.sign(Ih(t));return $n.encode({identityKey:Rr(r.publicKey),identitySig:n,extensions:e})}async function Rc(r,t,e){try{let n=$n.decode(r),o=Cn(n.identityKey);if(e?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${e}`);if(!t)throw new Error("Remote static does not exist");let s=Ih(t);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Gn(n.message)}}function Ih(r){let t=et("noise-libp2p-static-key:");return r instanceof Uint8Array?St([t,r],t.length+r.length):(r.prepend(t),r)}async function Ch(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Lc(s,a.publicKey,l),f=new Kn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});Ic(f.s,e),e.trace("Stage 0 - Initiator starting to send first message."),await n.write(f.writeMessageA(Er),t),e.trace("Stage 0 - Initiator finished sending first message."),Cc(f.e,e),e.trace("Stage 1 - Initiator waiting to receive first message from responder...");let d=f.readMessageB(await n.read(t));e.trace("Stage 1 - Initiator received the message."),kc(f.re,e),Bh(f.rs,e),e.trace("Initiator going to check remote's signature...");let w=await Rc(d,f.rs,c);e.trace("All good with the signature!"),e.trace("Stage 2 - Initiator sending third handshake message."),await n.write(f.writeMessageC(u),t),e.trace("Stage 2 - Initiator sent message with signed payload.");let[x,m]=f.ss.split();return Tc(x,m,e),{payload:w,encrypt:h=>x.encryptWithAd(Er,h),decrypt:(h,g)=>m.decryptWithAd(Er,h,g)}}async function kh(r,t){let{log:e,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await Lc(s,a.publicKey,l),f=new Kn({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});Ic(f.s,e),e.trace("Stage 0 - Responder waiting to receive first message."),f.readMessageA(await n.read(t)),e.trace("Stage 0 - Responder received first message."),kc(f.re,e),e.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(f.writeMessageB(u),t),e.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Cc(f.e,e),e.trace("Stage 2 - Responder waiting for third handshake message...");let d=f.readMessageC(await n.read(t));e.trace("Stage 2 - Responder received the message, finished handshake.");let w=await Rc(d,f.rs,c),[x,m]=f.ss.split();return Tc(x,m,e),{payload:w,encrypt:h=>m.encryptWithAd(Er,h),decrypt:(h,g)=>x.decryptWithAd(Er,h,g)}}var Nh=16;function _h(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65519){let s=o+65519;s>n.length&&(s=n.length);let i;n instanceof Uint8Array?i=r.encrypt(n.subarray(o,s)):i=r.encrypt(n.sublist(o,s)),t?.encryptedPackets.increment(),yield new ft(Zr(i.byteLength),i)}}}function Lh(r,t){return async function*(e){for await(let n of e)for(let o=0;o<n.length;o+=65535){let s=o+65535;if(s>n.length&&(s=n.length),s-Nh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Nh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var ii=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;constructor(t,e={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=e,{metrics:a}=t;this.components=t;let c=s??vh;this.crypto=Sh(c),this.extensions=o,this.metrics=a?Ah(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??yt(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Sr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e){let n=Hn(t,{lengthEncoder:Zr,lengthDecoder:Fn,maxDataLength:65535}),o=await this.performHandshakeInitiator(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Cn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:_a(i)}}async secureInbound(t,e){let n=Hn(t,{lengthEncoder:Zr,lengthDecoder:Fn,maxDataLength:65535}),o=await this.performHandshakeResponder(n,this.components.privateKey,e?.remotePeer?.publicKey,e),s=await this.createSecureConnection(n,o);t.source=s.source,t.sink=s.sink;let i=Cn(o.payload.identityKey);return{conn:t,remoteExtensions:o.payload.extensions,remotePeer:_a(i)}}async performHandshakeInitiator(t,e,n,o){let s;try{s=await Ch({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async performHandshakeResponder(t,e,n,o){let s;try{s=await kh({connection:t,privateKey:e,remoteIdentityKey:n,log:this.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:this.extensions},o),this.metrics?.xxHandshakeSuccesses.increment()}catch(i){throw this.metrics?.xxHandshakeErrors.increment(),i}return s}async createSecureConnection(t,e){let[n,o]=eh(),s=t.unwrap();return await nh(n,_h(e,this.metrics),s,i=>wr(i,{lengthDecoder:Fn}),Lh(e,this.metrics),n),o}};function Rh(r={}){return t=>new ii(t,r)}var Uc=Object.values(lr).map(r=>r.decoder).reduce((r,t)=>r.or(t));function Uh(r,t){let e=r.getConfiguration().certificates?.at(0);if(e?.getFingerprints==null){t.log.trace("fetching fingerprint from local SDP");let o=r.localDescription;return o==null?void 0:Ng(o.sdp)}if(t.log.trace("fetching fingerprint from local certificate"),e.getFingerprints().length===0)return;let n=e.getFingerprints()[0].value;if(n==null)throw new Vn("","no fingerprint on local certificate");return n}var Tg=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function Ng(r){return r.match(Tg)?.groups?.fingerprint}function _g(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function ai(r){let e=r.stringTuples().filter(n=>n[0]===Oh).map(n=>n[1])[0];if(e===void 0||e==="")throw new tt(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Dc(r){return Xt.decode(Uc.decode(r))}function Lg(r){let t=Dc(ai(r)),e=Pc(t.code),n=t.digest.reduce((s,i)=>s+i.toString(16).padStart(2,"0"),""),o=n.match(/.{1,2}/g);if(o==null)throw new Vn(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Pc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw new Ws(r)}}function Rg(r,t){let{host:e,port:n}=r.toOptions(),o=_g(r),[s]=Lg(r);return`v=0
|
8
7
|
o=- 0 0 IN ${o} ${e}
|
9
8
|
s=-
|
10
9
|
c=IN ${o} ${e}
|
@@ -17,13 +16,13 @@ a=ice-ufrag:${t}
|
|
17
16
|
a=ice-pwd:${t}
|
18
17
|
a=fingerprint:${s}
|
19
18
|
a=sctp-port:5000
|
20
|
-
a=max-message-size:${
|
19
|
+
a=max-message-size:${Ds}
|
21
20
|
a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host\r
|
22
|
-
`}function
|
21
|
+
`}function Dh(r,t){return{type:"answer",sdp:Rg(r,t)}}function Ph(r,t){if(r.sdp===void 0)throw new tt("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
23
22
|
a=ice-ufrag:`+t+`
|
24
23
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
25
24
|
a=ice-pwd:`+t+`
|
26
|
-
`),r}var
|
25
|
+
`),r}var Hh=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Mh=r=>[...Array(r)].map(()=>Hh.at(Math.floor(Math.random()*Hh.length))).join("");var Dg=1e4,c8=Q("webrtc-direct").code,Oh=Q("certhash").code,ci=class{log;metrics;components;init;constructor(t,e={}){this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=e,t.metrics!=null&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[zn]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Sr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){throw new $s("WebRTCTransport.createListener")}listenFilter(t){return t.filter(Ef.exactMatch)}dialFilter(t){return this.listenFilter(t)}async _connect(t,e){let n=new AbortController,o=n.signal,s=t.getPeerId();if(s===null)throw new Ks("we need to have the remote's PeerId");let i=Kr(s),a=Dc(ai(t)),c=await yr.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:Pc(a.code)}),l=new yr({...await Dn(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((A,k)=>{let I=l.createDataChannel("",{negotiated:!0,id:0}),V=setTimeout(()=>{let L=`Data channel was never opened: state: ${I.readyState}`;this.log.error(L),this.metrics?.dialerEvents.increment({open_error:!0}),k(new Mn("data",L))},Dg);I.onopen=L=>{clearTimeout(V),A(I)},I.onerror=L=>{clearTimeout(V);let K=`Error opening a data channel for handshaking: ${L.target?.toString()??"not specified"}`;this.log.error(K),this.metrics?.dialerEvents.increment({unknown_error:!0}),k(new Mn("data",K))}}),f="libp2p+webrtc+v1/"+Mh(32),d=await l.createOffer(),w=Ph(d,f);await l.setLocalDescription(w);let x=Dh(t,f);await l.setRemoteDescription(x);let m=await u,h=this.generateNoisePrologue(l,a.code,t),g=Rh({prologueBytes:h})(this.components),b=zr({channel:m,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),p={...b,sink:b.sink.bind(b),source:async function*(){for await(let A of b.source)for(let k of A)yield k}()},B=new mr(this.components,{peerConnection:l,remoteAddr:t,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),_=Un?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(_,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":B.close().catch(A=>{this.log.error("error closing connection",A)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let N=new Ye(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await g.secureInbound(p,{signal:o,remotePeer:i}),await e.upgrader.upgradeOutbound(B,{skipProtection:!0,skipEncryption:!0,muxerFactory:N})}catch(u){throw l.close(),u}}generateNoisePrologue(t,e,n){if(t.getConfiguration().certificates?.length===0)throw new tt("no local certificate");let o=Uh(t,{log:this.log});if(o==null)throw new tt("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=et(s,"hex"),a=Mt(e,i),c=Uc.decode(ai(n)),l=et("libp2p-webrtc-noise:");return St([l,a.bytes,c])}};function Pg(r){return t=>new ci(t,r)}function Og(r){return t=>new Qs(t,r)}return ed(Hg);})();
|
27
26
|
/*! Bundled license information:
|
28
27
|
|
29
28
|
pvtsutils/build/index.js:
|