@libp2p/webrtc 4.1.4-0edbfe7af → 4.1.4-1dfb74e79
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/index.min.js +5 -5
- package/package.json +12 -12
package/dist/index.min.js
CHANGED
@@ -1,10 +1,10 @@
|
|
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 ad=Object.create;var to=Object.defineProperty;var cd=Object.getOwnPropertyDescriptor;var ld=Object.getOwnPropertyNames;var ud=Object.getPrototypeOf,fd=Object.prototype.hasOwnProperty;var hd=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),bt=(r,t)=>{for(var e in t)to(r,e,{get:t[e],enumerable:!0})},Xc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ld(t))!fd.call(r,o)&&o!==e&&to(r,o,{get:()=>t[o],enumerable:!(n=cd(t,o))||n.enumerable});return r};var dd=(r,t,e)=>(e=r!=null?ad(ud(r)):{},Xc(t||!r||!r.__esModule?to(e,"default",{value:r,enumerable:!0}):e,r)),pd=r=>Xc(to({},"__esModule",{value:!0}),r);var cf=hd(rn=>{"use strict";var ag="[object ArrayBuffer]",De=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===ag}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}},sc="string",cg=/^[0-9a-f]+$/i,lg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,ug=/^[a-zA-Z0-9-_]+$/,ss=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=De.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Xt=class{static toString(t,e=!1){let n=De.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}},is=class r{static isHex(t){return typeof t===sc&&cg.test(t)}static isBase64(t){return typeof t===sc&&lg.test(t)}static isBase64Url(t){return typeof t===sc&&ug.test(t)}static ToString(t,e="utf8"){let n=De.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 Xt.toString(n,!0);case"utf16":case"utf16be":return Xt.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 Xt.fromString(t,!0);case"utf16":case"utf16be":return Xt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=De.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 ss.fromString(t);case"utf16":case"utf16be":return Xt.fromString(t);case"utf16le":case"usc2":return Xt.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 ss.toString(t);case"utf16":case"utf16be":return Xt.toString(t);case"utf16le":case"usc2":return Xt.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=De.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=De.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 Xt.toString(t,e)}static FromUtf16String(t,e=!1){return Xt.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,"")||""}};is.DEFAULT_UTF8_ENCODING="utf8";function fg(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 hg(...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 dg(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}rn.BufferSourceConverter=De;rn.Convert=is;rn.assign=fg;rn.combine=hg;rn.isEqual=dg});var vy={};bt(vy,{webRTC:()=>Ey,webRTCDirect:()=>xy});var oi=Symbol.for("@libp2p/peer-id");var eo=Symbol.for("@libp2p/transport");var Jc;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Jc||(Jc={}));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 ro=(r,...t)=>{try{[...t]}catch{}};var no=class extends EventTarget{#t=new Map;constructor(){super(),ro(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 md(t,e))}},md=globalThis.CustomEvent;var Tr=Symbol.for("@libp2p/service-capabilities"),Qc=Symbol.for("@libp2p/service-dependencies");var li={};bt(li,{base58btc:()=>dt,base58flickr:()=>Ed});var Qy=new Uint8Array(0);function tl(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 Ae(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 el(r){return new TextEncoder().encode(r)}function rl(r){return new TextDecoder().decode(r)}function gd(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(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var h=0,d=0,x=0,w=m.length;x!==w&&m[x]===0;)x++,h++;for(var b=(w-x)*u+1>>>0,I=new Uint8Array(b);x!==w;){for(var C=m[x],S=0,B=b-1;(C!==0||S<d)&&B!==-1;B--,S++)C+=256*I[B]>>>0,I[B]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");d=S,x++}for(var _=b-d;_!==b&&I[_]===0;)_++;for(var P=c.repeat(h);_<b;++_)P+=r.charAt(I[_]);return P}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var h=0;if(m[h]!==" "){for(var d=0,x=0;m[h]===c;)d++,h++;for(var w=(m.length-h)*l+1>>>0,b=new Uint8Array(w);m[h];){var I=e[m.charCodeAt(h)];if(I===255)return;for(var C=0,S=w-1;(I!==0||C<x)&&S!==-1;S--,C++)I+=a*b[S]>>>0,b[S]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");x=C,h++}if(m[h]!==" "){for(var B=w-x;B!==w&&b[B]===0;)B++;for(var _=new Uint8Array(d+(w-B)),P=d;B!==w;)_[P++]=b[B++];return _}}}function g(m){var h=p(m);if(h)return h;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:g}}var yd=gd,wd=yd,ol=wd;var si=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")}},ii=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 sl(this,t)}},ai=class{decoders;constructor(t){this.decoders=t}or(t){return sl(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 sl(r,t){return new ai({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ci=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 si(t,e,n),this.decoder=new ii(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Nr({name:r,prefix:t,encode:e,decode:n}){return new ci(r,t,e,n)}function Fe({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=ol(e,r);return Nr({prefix:t,name:r,encode:n,decode:s=>Ae(o(s))})}function bd(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 xd(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 ut({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Nr({prefix:t,name:r,encode(o){return xd(o,n,e)},decode(o){return bd(o,n,e,r)}})}var dt=Fe({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ed=Fe({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var ui={};bt(ui,{base10:()=>vd});var vd=Fe({prefix:"9",name:"base10",alphabet:"0123456789"});var fi={};bt(fi,{base16:()=>Ad,base16upper:()=>Sd});var Ad=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Sd=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var hi={};bt(hi,{base2:()=>Bd});var Bd=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var di={};bt(di,{base256emoji:()=>Cd});var il=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}"),Id=il.reduce((r,t,e)=>(r[e]=t,r),[]),_d=il.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function kd(r){return r.reduce((t,e)=>(t+=Id[e],t),"")}function Rd(r){let t=[];for(let e of r){let n=_d[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Cd=Nr({prefix:"\u{1F680}",name:"base256emoji",encode:kd,decode:Rd});var pi={};bt(pi,{base32:()=>Se,base32hex:()=>Dd,base32hexpad:()=>Pd,base32hexpadupper:()=>Od,base32hexupper:()=>Ud,base32pad:()=>Nd,base32padupper:()=>Ld,base32upper:()=>Td,base32z:()=>Md});var Se=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Td=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Nd=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ld=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dd=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ud=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Pd=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Od=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Md=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mi={};bt(mi,{base36:()=>Hd,base36upper:()=>Vd});var Hd=Fe({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Vd=Fe({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var wi={};bt(wi,{base64:()=>gi,base64pad:()=>Fd,base64url:()=>yi,base64urlpad:()=>Kd});var gi=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Fd=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yi=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Kd=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var bi={};bt(bi,{base8:()=>$d});var $d=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xi={};bt(xi,{identity:()=>Wd});var Wd=Nr({prefix:"\0",name:"identity",encode:r=>rl(r),decode:r=>el(r)});var mw=new TextEncoder,gw=new TextDecoder;var Ai={};bt(Ai,{identity:()=>Be});var te={};bt(te,{Digest:()=>cr,create:()=>$t,decode:()=>Ke,equals:()=>vi});var zd=ll,al=128,jd=127,Yd=~jd,Zd=Math.pow(2,31);function ll(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Zd;)t[e++]=r&255|al,r/=128;for(;r&Yd;)t[e++]=r&255|al,r>>>=7;return t[e]=r|0,ll.bytes=e-n+1,t}var Xd=Ei,Jd=128,cl=127;function Ei(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ei.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&cl)<<o:(i&cl)*Math.pow(2,o),o+=7}while(i>=Jd);return Ei.bytes=s-n,e}var Qd=Math.pow(2,7),tp=Math.pow(2,14),ep=Math.pow(2,21),rp=Math.pow(2,28),np=Math.pow(2,35),op=Math.pow(2,42),sp=Math.pow(2,49),ip=Math.pow(2,56),ap=Math.pow(2,63),cp=function(r){return r<Qd?1:r<tp?2:r<ep?3:r<rp?4:r<np?5:r<op?6:r<sp?7:r<ip?8:r<ap?9:10},lp={encode:zd,decode:Xd,encodingLength:cp},up=lp,pn=up;function mn(r,t=0){return[pn.decode(r,t),pn.decode.bytes]}function Lr(r,t,e=0){return pn.encode(r,t,e),t}function Dr(r){return pn.encodingLength(r)}function $t(r,t){let e=t.byteLength,n=Dr(r),o=n+Dr(e),s=new Uint8Array(o+e);return Lr(r,s,0),Lr(e,s,n),s.set(t,o),new cr(r,e,t,s)}function Ke(r){let t=Ae(r),[e,n]=mn(t),[o,s]=mn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new cr(e,o,i,t)}function vi(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&tl(r.bytes,e.bytes)}}var cr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var ul=0,fp="identity",fl=Ae;function hp(r){return $t(ul,fl(r))}var Be={code:ul,name:fp,encode:fl,digest:hp};var Ii={};bt(Ii,{sha256:()=>kt,sha512:()=>dp});function Bi({name:r,code:t,encode:e}){return new Si(r,t,e)}var Si=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?$t(this.code,e):e.then(n=>$t(this.code,n))}else throw Error("Unknown type, must be binary type")}};function dl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var kt=Bi({name:"sha2-256",code:18,encode:dl("SHA-256")}),dp=Bi({name:"sha2-512",code:19,encode:dl("SHA-512")});function pl(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return mp(e,_i(r),t??dt.encoder);default:return gp(e,_i(r),t??Se.encoder)}}var ml=new WeakMap;function _i(r){let t=ml.get(r);if(t==null){let e=new Map;return ml.set(r,e),e}return t}var zt=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!==gn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==yp)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=$t(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&&vi(t.multihash,n.multihash)}toString(t){return pl(this,t)}toJSON(){return{"/":pl(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??gl(n,o,s.bytes))}else if(e[wp]===!0){let{version:n,multihash:o,code:s}=e,i=Ke(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!==gn)throw new Error(`Version 0 CID must use dag-pb (code: ${gn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=gl(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,gn,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=Ae(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 cr(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,p]=mn(t.subarray(e));return e+=p,f},o=n(),s=gn;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]=pp(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 _i(s).set(n,t),s}};function pp(r,t){switch(r[0]){case"Q":{let e=t??dt;return[dt.prefix,e.decode(`${dt.prefix}${r}`)]}case dt.prefix:{let e=t??dt;return[dt.prefix,e.decode(r)]}case Se.prefix:{let e=t??Se;return[Se.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 mp(r,t,e){let{prefix:n}=e;if(n!==dt.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 gp(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 gn=112,yp=18;function gl(r,t,e){let n=Dr(r),o=n+Dr(t),s=new Uint8Array(o+e.byteLength);return Lr(r,s,0),Lr(t,s,n),s.set(e,o),s}var wp=Symbol.for("@ipld/js-cid/CID");var me={...xi,...hi,...bi,...ui,...fi,...pi,...mi,...li,...wi,...di},Ow={...Ii,...Ai};function xt(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 Et(r=0){return new Uint8Array(r)}function vt(r=0){return new Uint8Array(r)}function wl(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var yl=wl("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ki=wl("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=vt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),bp={utf8:yl,"utf-8":yl,hex:me.base16,latin1:ki,ascii:ki,binary:ki,...me},so=bp;function Y(r,t="utf8"){let e=so[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function G(r,t="utf8"){let e=so[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var xl=Symbol.for("nodejs.util.inspect.custom"),bl=Object.values(me).map(r=>r.decoder).reduce((r,t)=>r.or(t),me.identity.decoder),El=114,Ti=36,Ni=37,yn=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()})`}[oi]=!0;toString(){return this.string==null&&(this.string=dt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return zt.createV1(El,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return xt(this.multihash.bytes,t);if(typeof t=="string")return lr(t).equals(this);if(t?.multihash?.bytes!=null)return xt(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[xl](){return`PeerId(${this.toString()})`}},Ur=class extends yn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Pr=class extends yn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},Or=class extends yn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}},Ri=2336,Ci=class{type="url";multihash;privateKey;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Be.digest(Y(this.url))}[xl](){return`PeerId(${this.url})`}[oi]=!0;toString(){return this.toCID().toString()}toCID(){return zt.createV1(Ri,this.multihash)}toBytes(){return this.toCID().bytes}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};function lr(r,t){if(t=t??bl,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=Ke(dt.decode(`z${r}`));return r.startsWith("12D")?new Pr({multihash:e}):r.startsWith("16U")?new Or({multihash:e}):new Ur({multihash:e})}return xp(bl.decode(r))}function xp(r){try{let t=Ke(r);if(t.code===Be.code){if(t.digest.length===Ti)return new Pr({multihash:t});if(t.digest.length===Ni)return new Or({multihash:t})}if(t.code===kt.code)return new Ur({multihash:t})}catch{return Ep(zt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Ep(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==El&&r.code!==Ri)throw new Error("Supplied PeerID CID is invalid");if(r.code===Ri){let e=G(r.multihash.digest);return new Ci(new URL(e))}let t=r.multihash;if(t.code===kt.code)return new Ur({multihash:r.multihash});if(t.code===Be.code){if(t.digest.length===Ti)return new Pr({multihash:r.multihash});if(t.digest.length===Ni)return new Or({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Li(r,t){return r.length===Ti?new Pr({multihash:$t(Be.code,r),privateKey:t}):r.length===Ni?new Or({multihash:$t(Be.code,r),privateKey:t}):new Ur({multihash:await kt.digest(r),publicKey:r,privateKey:t})}var Ap=Math.pow(2,7),Sp=Math.pow(2,14),Bp=Math.pow(2,21),Di=Math.pow(2,28),Ui=Math.pow(2,35),Pi=Math.pow(2,42),Oi=Math.pow(2,49),tt=128,Lt=127;function gt(r){if(r<Ap)return 1;if(r<Sp)return 2;if(r<Bp)return 3;if(r<Di)return 4;if(r<Ui)return 5;if(r<Pi)return 6;if(r<Oi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Mi(r,t,e=0){switch(gt(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 Ip(r,t,e=0){switch(gt(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 Hi(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)*Di,e<tt)||(e=r[t+5],n+=(e&Lt)*Ui,e<tt)||(e=r[t+6],n+=(e&Lt)*Pi,e<tt)||(e=r[t+7],n+=(e&Lt)*Oi,e<tt))return n;throw new RangeError("Could not decode varint")}function _p(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)*Di,e<tt)||(e=r.get(t+5),n+=(e&Lt)*Ui,e<tt)||(e=r.get(t+6),n+=(e&Lt)*Pi,e<tt)||(e=r.get(t+7),n+=(e&Lt)*Oi,e<tt))return n;throw new RangeError("Could not decode varint")}function ge(r,t,e=0){return t==null&&(t=vt(gt(r))),t instanceof Uint8Array?Mi(r,t,e):Ip(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Hi(r,t):_p(r,t)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=vt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var io=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 p=Number.parseInt(f,t);if(!Number.isNaN(p))return p});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 vl=45,Rp=15,Mr=new io;function Vi(r){if(!(r.length>Rp))return Mr.new(r).parseWith(()=>Mr.readIPv4Addr())}function Fi(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>vl))return Mr.new(r).parseWith(()=>Mr.readIPv6Addr())}function ao(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>vl))return Mr.new(r).parseWith(()=>Mr.readIPAddr())}var yb=parseInt("0xFFFF",16),wb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function co(r){return!!Vi(r)}function lo(r){return!!Fi(r)}function uo(r){return!!ao(r)}var Bl=co,Dp=lo,Ki=function(r){let t=0;if(r=r.toString().trim(),Bl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Dp(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=Bl(e[n]),i;s&&(i=Ki(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")},Il=function(r,t=0,e){t=~~t,e=e??r.length-t;let n=new DataView(r.buffer);if(e===4){let o=[];for(let s=0;s<e;s++)o.push(r[t+s]);return o.join(".")}if(e===16){let o=[];for(let s=0;s<e;s+=2)o.push(n.getUint16(t+s).toString(16));return o.join(":").replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}return""};var Hr={},$i={},Pp=[[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"]];Pp.forEach(r=>{let t=Op(...r);$i[t.code]=t,Hr[t.name]=t});function Op(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function et(r){if(typeof r=="number"){if($i[r]!=null)return $i[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Hr[r]!=null)return Hr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var ex=et("ip4"),rx=et("ip6"),nx=et("ipcidr");function zi(r,t){switch(et(r).code){case 4:case 41:return Hp(t);case 42:return qi(t);case 6:case 273:case 33:case 132:return Rl(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return qi(t);case 421:return $p(t);case 444:return kl(t);case 445:return kl(t);case 466:return Kp(t);case 481:return globalThis.encodeURIComponent(qi(t));default:return G(t,"base16")}}function ji(r,t){switch(et(r).code){case 4:return _l(t);case 41:return _l(t);case 42:return Gi(t);case 6:case 273:case 33:case 132:return Yi(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return Gi(t);case 421:return Vp(t);case 444:return Wp(t);case 445:return Gp(t);case 466:return Fp(t);case 481:return Gi(globalThis.decodeURIComponent(t));default:return Y(t,"base16")}}var Wi=Object.values(me).map(r=>r.decoder),Mp=function(){let r=Wi[0].or(Wi[1]);return Wi.slice(2).forEach(t=>r=r.or(t)),r}();function _l(r){if(!uo(r))throw new Error("invalid ip address");return Ki(r)}function Hp(r){let t=Il(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!uo(t))throw new Error("invalid ip address");return t}function Yi(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Rl(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function Gi(r){let t=Y(r),e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function qi(r){let t=ee(r);if(r=r.slice(gt(t)),r.length!==t)throw new Error("inconsistent lengths");return G(r)}function Vp(r){let t;r[0]==="Q"||r[0]==="1"?t=Ke(dt.decode(`z${r}`)).bytes:t=zt.parse(r).multihash.bytes;let e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function Fp(r){let t=Mp.decode(r),e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function Kp(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+G(e,"base64url")}function $p(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return G(e,"base58btc")}function Wp(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=Se.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=Yi(n);return yt([e,o],e.length+o.length)}function Gp(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=Se.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=Yi(n);return yt([e,o],e.length+o.length)}function kl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=G(t,"base32"),o=Rl(e);return`${n}:${o}`}function Cl(r){r=Zi(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 Nl("invalid address: "+r);if(a.path===!0){n=Zi(o.slice(s).join("/")),t.push([a.code,ji(a.code,n)]),e.push([a.code,n]);break}let c=ji(a.code,o[s]);t.push([a.code,c]),e.push([a.code,zi(a.code,c)])}return{string:Tl(e),bytes:Ji(t),tuples:t,stringTuples:e,path:n}}function Xi(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=gt(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 Nl("Invalid address Uint8Array: "+G(r,"base16"));t.push([s,l]);let u=zi(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Tl(e),tuples:t,stringTuples:e,path:n}}function Tl(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}),Zi(t.join("/"))}function Ji(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+gt(e)}}function Zi(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Nl(r){return new Error("Error parsing address: "+r)}var zp=Symbol.for("nodejs.util.inspect.custom"),Qi=Symbol.for("@multiformats/js-multiaddr/multiaddr"),jp=[et("dns").code,et("dns4").code,et("dns6").code,et("dnsaddr").code],fo=class r{bytes;#t;#e;#r;#n;[Qi]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Xi(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Cl(t)}else if(Dl(t))e=Xi(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[g,m]of this.stringTuples())g===f.code&&(s=`%${m??""}`),jp.includes(g)&&(e=i.name,o=443,n=`${m??""}${s}`,t=g===u.code?6:4),(g===i.code||g===a.code)&&(e=et(g).name,o=parseInt(m??"")),(g===c.code||g===l.code)&&(e=et(g).name,n=`${m??""}${s}`,t=g===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(Ji(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Hr.p2p.code&&t.push([n,o]),n===Hr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?G(dt.decode(`z${n}`),"base58btc"):G(zt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return xt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Ll.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)}[zp](){return`Multiaddr(${this.#t})`}};var Ll=new Map;function Dl(r){return!!r?.[Qi]}function re(r){return new fo(r)}var Yp=r=>r.toString().split("/").slice(1),bn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),X=r=>({match:t=>bn(e=>e===r).match(t),pattern:r}),mo=()=>({match:r=>bn(t=>typeof t=="string").match(r),pattern:"{string}"}),go=()=>({match:r=>bn(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{dt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),ho=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{yi.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),At=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=Yp(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 ea=rt(X("dns4"),mo()),ra=rt(X("dns6"),mo()),na=rt(X("dnsaddr"),mo()),Ul=rt(X("dns"),mo()),Nx=pt(ea),Lx=pt(ra),Dx=pt(na),Ux=pt(jt(Ul,na,ea,ra)),Pl=rt(X("ip4"),bn(co)),Ol=rt(X("ip6"),bn(lo)),Ml=jt(Pl,Ol),ye=jt(Ml,Ul,ea,ra,na),Px=pt(ye),Ox=pt(Pl),Mx=pt(Ol),Hx=pt(Ml),oa=rt(ye,X("tcp"),go()),xn=rt(ye,X("udp"),go()),Vx=pt(oa),Fx=pt(xn),sa=rt(xn,X("quic")),yo=rt(xn,X("quic-v1")),Zp=jt(sa,yo),Kx=pt(sa),$x=pt(yo),ta=jt(ye,oa,xn,sa,yo),Hl=jt(rt(ta,X("ws"),At(Rt()))),Wx=pt(Hl),Vl=jt(rt(ta,X("wss"),At(Rt())),rt(ta,X("tls"),X("ws"),At(Rt()))),Gx=pt(Vl),Fl=rt(xn,X("webrtc-direct"),At(ho()),At(ho()),At(Rt())),Kl=pt(Fl),$l=rt(yo,X("webtransport"),At(ho()),At(ho()),At(Rt())),qx=pt($l),po=jt(Hl,Vl,rt(oa,At(Rt())),rt(Zp,At(Rt())),rt(ye,At(Rt())),Fl,$l,Rt()),zx=pt(po),Xp=rt(po,X("p2p-circuit"),Rt()),jx=pt(Xp),Jp=jt(rt(po,X("p2p-circuit"),X("webrtc"),At(Rt())),rt(po,X("webrtc"),At(Rt())),X("webrtc")),Wl=pt(Jp),Qp=jt(rt(ye,X("tcp"),go(),X("http"),At(Rt())),rt(ye,X("http"),At(Rt()))),Yx=pt(Qp),tm=jt(rt(ye,X("tcp"),jt(rt(X("443"),X("http")),rt(go(),X("https"))),At(Rt())),rt(ye,X("tls"),X("http"),At(Rt())),rt(ye,X("https"),At(Rt()))),Zx=pt(tm);var Wt;(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"})(Wt||(Wt={}));var $e=class extends D{constructor(t,e){super(`WebRTC transport error: ${t}`,e??""),this.name="WebRTCTransportError"}};var ia=class extends $e{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`,Wt.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function ha(r,t){return new ia(r,t)}var aa=class extends $e{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`,Wt.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function wo(r){return new aa(r)}var ca=class extends $e{constructor(t){super(`There was a problem with a provided argument: ${t}`,Wt.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function En(r){return new ca(r)}var la=class extends $e{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`,Wt.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function da(r,t){return new la(r,t)}var ua=class extends $e{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`,Wt.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function Gl(r){return new ua(r)}var fa=class extends $e{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `,Wt.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function ql(r){return new fa(r)}var zl=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))},em=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var rm=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var nm=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 om=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var sm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var im=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,am=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,jl=3,cm=[["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",im]],Yl=[["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 Xl(r){return r?Zl(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new sm:typeof navigator<"u"?Zl(navigator.userAgent):fm()}function lm(r){return r!==""&&cm.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 Zl(r){var t=lm(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new om;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<jl&&(o=zl(zl([],o,!0),hm(jl-o.length),!0)):o=[];var s=o.join("."),i=um(r),a=am.exec(r);return a&&a[1]?new nm(e,s,i,a[1]):new em(e,s,i)}function um(r){for(var t=0,e=Yl.length;t<e;t++){var n=Yl[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function fm(){var r=typeof process<"u"&&process.version;return r?new rm(process.version.slice(1)):null}function hm(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function ft(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Vr=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},pa=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},Jl=r=>globalThis.DOMException===void 0?new pa(r):new DOMException(r),Ql=r=>{let t=r.reason===void 0?Jl("This operation was aborted."):r.reason;return t instanceof Error?t:Jl(t)};function ur(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:p}=t;p.aborted&&u(Ql(p)),p.addEventListener("abort",()=>{u(Ql(p))})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Vr;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){u(p)}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(p){u(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var tu=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var eu=Xl(),vn=eu!=null&&eu.name==="firefox",bo=async function*(){},xo=async r=>{},dm=30*1e3;function ru(r,t,e=dm,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=ft(),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 ur(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function An(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??tu.map(t=>({urls:[t]})),r}var fr=class{log;peerConnection;remoteAddr;timeline;metrics;source=bo();sink=xo;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 Eo=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}},Fr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Eo(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 Eo(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 ma=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function We(r={}){return pm(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 pm(r,t){t=t??{};let e=t.onEnd,n=new Fr,o,s,i,a=ft(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((d,x)=>{s=w=>{s=null,n.push(w);try{d(r(n))}catch(b){x(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ft()})}},l=d=>s!=null?s(d):(n.push(d),o),u=d=>(n=new Fr,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})},p=d=>i?o:(i=!0,d!=null?u(d):l({done:!0})),g=()=>(n=new Fr,p(),{done:!0}),m=d=>(p(d),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:m,push:f,end:p,get readableLength(){return n.size},onEmpty:async d=>{let x=d?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let w,b;x!=null&&(w=new Promise((I,C)=>{b=()=>{C(new ma)},x.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&x!=null&&x?.removeEventListener("abort",b)}}},e==null)return o;let h=o;return o={[Symbol.asyncIterator](){return this},next(){return h.next()},throw(d){return h.throw(d),e!=null&&(e(d),e=void 0),{done:!0}},return(){return h.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(d){return h.end(d),e!=null&&(e(d),e=void 0),o},get readableLength(){return h.readableLength},onEmpty:d=>h.onEmpty(d)},o}var vo=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 Ie(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new vo(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new vo(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 ou=Symbol.for("@achingbrain/uint8arraylist");function nu(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 Ao(r){return!!r?.[ou]}var at=class r{bufs;length;[ou]=!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(Ao(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(Ao(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=nu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=nu(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(Ao(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(!Ao(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 p=l;p>=0;p--){let g=this.get(f+p);if(n[p]!==g){u=Math.max(1,p-a[g]);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=vt(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=Et(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=Et(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=Et(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=vt(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=Et(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=Et(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=Et(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=Et(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=Et(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(!xt(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 su(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 iu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function au(r,t){let e=su(r).return?.();iu(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var mm="ERR_STREAM_RESET",gm="ERR_SINK_INVALID_STATE",ym=5e3;function ga(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var So=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=ft(),this.closed=ft(),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??ym,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=We({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"`,gm);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);ga(o)&&await o}let n=()=>{au(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 at(o):o;let s=this.sendData(o,e);ga(s)&&(this.sendingData=ft(),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 Ie(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 Ie(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Ie(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Ie(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();ga(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",mm);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 Bo(r){return r[Symbol.asyncIterator]!=null}var Io=r=>{let t=gt(r),e=vt(t);return ge(r,e),Io.bytes=t,e};Io.bytes=0;function Sn(r,t){t=t??{};let e=t.lengthEncoder??Io;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return Bo(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Sn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??Io;return new at(e(r.byteLength),r)};var _o=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},ko=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ro=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},Bn=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var wm=8,bm=1024*1024*4,hr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(hr||(hr={}));var ya=r=>{let t=ee(r);return ya.bytes=gt(t),t};ya.bytes=0;function dr(r,t){let e=new at,n=hr.LENGTH,o=-1,s=t?.lengthDecoder??ya,i=t?.maxLengthLength??wm,a=t?.maxDataLength??bm;function*c(){for(;e.byteLength>0;){if(n===hr.LENGTH)try{if(o=s(e),o<0)throw new _o("Invalid message length");if(o>a)throw new ko("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=hr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new Ro("Message length length too long");break}throw l}if(n===hr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=hr.LENGTH}}}return Bo(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Bn("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new Bn("Unexpected end of input")}()}dr.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 dr(n,{...t??{},onLength:s=>{e=s}})};var Em=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 vm(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}=Em(r),f=(...g)=>{let m=e.multiArgs?g:g[0];e.filter&&!e.filter(m)||(c.push(m),e.count===c.length&&(n(),s(c)))},p=g=>{n(),i(g)};n=()=>{for(let g of a)u(g,f);for(let g of e.rejectionEvents)u(g,p)};for(let g of a)l(g,f);for(let g of e.rejectionEvents)l(g,p);e.signal&&e.signal.addEventListener("abort",()=>{p(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=ur(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function wa(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=vm(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var ba=new Float32Array([-0]),Ge=new Uint8Array(ba.buffer);function cu(r,t,e){ba[0]=r,t[e]=Ge[0],t[e+1]=Ge[1],t[e+2]=Ge[2],t[e+3]=Ge[3]}function lu(r,t){return Ge[0]=r[t],Ge[1]=r[t+1],Ge[2]=r[t+2],Ge[3]=r[t+3],ba[0]}var xa=new Float64Array([-0]),Dt=new Uint8Array(xa.buffer);function uu(r,t,e){xa[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 fu(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],xa[0]}var Am=BigInt(Number.MAX_SAFE_INTEGER),Sm=BigInt(Number.MIN_SAFE_INTEGER),Gt=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 pr;if(t<Am&&t>Sm)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>hu&&(o=0n,++n>hu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return pr;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):pr}},pr=new Gt(0,0);pr.toBigInt=function(){return 0n};pr.zzEncode=pr.zzDecode=function(){return this};pr.length=function(){return 1};var hu=4294967296n;function du(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 pu(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 Ea(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 Co(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var va=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 Co(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ne(this,4);return Co(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ne(this,4);let t=lu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ne(this,4);let t=fu(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 pu(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 Gt(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=Co(this.buf,this.pos+=4),e=Co(this.buf,this.pos+=4);return new Gt(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=Hi(this.buf,this.pos);return this.pos+=gt(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 Aa(r){return new va(r instanceof Uint8Array?r:r.subarray())}function oe(r,t,e){let n=Aa(r);return t.decode(n,void 0,e)}function Sa(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return vt(i);o+i>t&&(n=vt(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var mr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function Ba(){}var _a=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},Bm=Sa();function Im(r){return globalThis.Buffer!=null?vt(r):Bm(r)}var _n=class{len;head;tail;states;constructor(){this.len=0,this.head=new mr(Ba,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new mr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new ka((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(To,10,Gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Gt.fromBigInt(t);return this._push(To,e.length(),e)}uint64Number(t){return this._push(Mi,gt(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=Gt.fromBigInt(t).zzEncode();return this._push(To,e.length(),e)}sint64Number(t){let e=Gt.fromNumber(t).zzEncode();return this._push(To,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(Ia,1,t?1:0)}fixed32(t){return this._push(In,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Gt.fromBigInt(t);return this._push(In,4,e.lo)._push(In,4,e.hi)}fixed64Number(t){let e=Gt.fromNumber(t);return this._push(In,4,e.lo)._push(In,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(cu,4,t)}double(t){return this._push(uu,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(Ia,1,0):this.uint32(e)._push(km,e,t)}string(t){let e=du(t);return e!==0?this.uint32(e)._push(Ea,e,t):this._push(Ia,1,0)}fork(){return this.states=new _a(this),this.head=this.tail=new mr(Ba,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 mr(Ba,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=Im(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function Ia(r,t,e){t[e]=r&255}function _m(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var ka=class extends mr{next;constructor(t,e){super(_m,t,e),this.next=void 0}};function To(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 In(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 km(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(_n.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Rm,t,r),this},_n.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Cm,t,r),this});function Rm(r,t,e){t.set(r,e)}function Cm(r,t,e){r.length<40?Ea(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Y(r),e)}function Ra(){return new _n}function se(r,t){let e=Ra();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var Kr;(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"})(Kr||(Kr={}));function No(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function gr(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 No("enum",Kr.VARINT,e,n)}function ie(r,t){return No("message",Kr.LENGTH_DELIMITED,r,t)}var Mt;(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=()=>gr(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())})(Mt||(Mt={}));var Tm=2*1024*1024,Nm=30*1e3,Lm=7,Dm=2,Um=256*1024,Pm=5e3,Om=5e3,Ca=class extends So{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 ur(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=We(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Nm,this.maxBufferedAmount=t.maxBufferedAmount??Tm,this.maxMessageSize=(t.maxMessageSize??Um)-Lm-Dm,this.receiveFinAck=ft(),this.finAckTimeout=t.closeTimeout??Pm,this.openTimeout=t.openTimeout??Om,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 dr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new at(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 wa(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof Vr?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 wa(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=Mt.encode({message:n}),s=Sn.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Mt.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Mt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Ie(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(Mt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Mt.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===Mt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Mt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Mt.Flag.RESET&&this.reset(),e.flag===Mt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Mt.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=Mt.encode({flag:t}),n=Sn.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 $r(r){let{channel:t,direction:e}=r;return new Ca({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var gu="/webrtc",qe=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??gu,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=$r({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 Ta(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},Ta=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??gu,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=$r({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),ru(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=bo();sink=xo;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=$r({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,Lo=globalThis.RTCSessionDescription,yu=globalThis.RTCIceCandidate;var Na=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ft(),this.haveNext=ft()}[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=ft(),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=ft(),await Ie(this.readNext.promise,e?.signal,e)}};function wu(){return new Na}var Do=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var La=class extends Error{code;constructor(t,e){super(t),this.code=e}},Da=class extends La{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function bu(r,t){let e=wu();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 at;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new Da("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:p}=await Promise.race([n.next(),l]);return f===!0?new at:p}for(;o.byteLength<i;){let{value:f,done:p}=await Promise.race([n.next(),l]);if(p===!0)throw new Do("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 Uo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Po=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Oo=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function kn(r,t={}){let e=bu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??ge;return{read:async i=>{let a=-1,c=new at;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 Uo("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Oo("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Po("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new at(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new at(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Mo(r,t){let e=kn(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 Ht;(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=()=>gr(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())})(Ht||(Ht={}));var Ho=async(r,t,e)=>{try{let n=ft();for(Hm(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!==Ht.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 qt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new yu(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)throw n}};function Mm(r){return vn?r.iceConnectionState:r.connectionState}function Hm(r,t){r[vn?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Mm(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 xu({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Eu(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 p=s.getConnections(lr(f)),g,m=!1;p.length===0?(l?.(new qt("webrtc:dial-relay")),g=await i.dial(u,{signal:e,onProgress:l}),m=!0):(l?.(new qt("webrtc:reuse-relay-connection")),g=p[0]);try{l?.(new qt("webrtc:open-signaling-stream"));let h=await g.newStream(Vo,{signal:e,runOnTransientConnection:!0}),d=Mo(h).pb(Ht),x=new yr(r),w=new qe({logger:c},{peerConnection:x,dataChannelOptions:t});try{let b=x.createDataChannel("init");x.onicecandidate=({candidate:B})=>{let _=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),d.write({type:Ht.Type.ICE_CANDIDATE,data:_},{signal:e}).catch(P=>{a.error("error sending ICE candidate",P)})},x.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let I=await x.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",I.sdp),l?.(new qt("webrtc:send-sdp-offer")),await d.write({type:Ht.Type.SDP_OFFER,data:I.sdp},{signal:e}),await x.setLocalDescription(I).catch(B=>{throw a.error("could not execute setLocalDescription",B),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),l?.(new qt("webrtc:read-sdp-answer"));let C=await d.read({signal:e});if(C.type!==Ht.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 S=new Lo({type:"answer",sdp:C.data});return await x.setRemoteDescription(S).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 qt("webrtc:read-ice-candidates")),await Ho(x,d,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),b.close(),l?.(new qt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await h.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:x,muxerFactory:w}}catch(b){throw a.error("outgoing signaling error",b),x.close(),h.abort(b),b}finally{x.onicecandidate=null,x.onicecandidateerror=null}}finally{if(m)try{await g.close({signal:e})}catch(h){g.abort(h)}}}var Vm=U("dns4"),Fm=U("dns6"),Km=U("dnsaddr"),wr=mt(U("dns"),Km,Vm,Fm),$o=mt(U("ip4"),U("ip6")),Wr=mt(K($o,U("tcp")),K(wr,U("tcp"))),Wo=K($o,U("udp")),$m=K(Wo,U("utp")),Wm=K(Wo,U("quic")),Gm=K(Wo,U("quic-v1")),Ua=mt(K(Wr,U("ws")),K(wr,U("ws"))),Fo=mt(K(Ua,U("p2p")),Ua),Pa=mt(K(Wr,U("wss")),K(wr,U("wss")),K(Wr,U("tls"),U("ws")),K(wr,U("tls"),U("ws"))),Ko=mt(K(Pa,U("p2p")),Pa),Oa=mt(K(Wr,U("http")),K($o,U("http")),K(wr,U("http"))),Ma=mt(K(Wr,U("https")),K($o,U("https")),K(wr,U("https"))),vu=K(Wo,U("webrtc-direct"),U("certhash")),Bu=mt(K(vu,U("p2p")),vu),Au=K(Gm,U("webtransport"),U("certhash"),U("certhash")),Iu=mt(K(Au,U("p2p")),Au),_u=mt(K(Fo,U("p2p-webrtc-star"),U("p2p")),K(Ko,U("p2p-webrtc-star"),U("p2p")),K(Fo,U("p2p-webrtc-star")),K(Ko,U("p2p-webrtc-star"))),A2=mt(K(Fo,U("p2p-websocket-star"),U("p2p")),K(Ko,U("p2p-websocket-star"),U("p2p")),K(Fo,U("p2p-websocket-star")),K(Ko,U("p2p-websocket-star"))),ku=mt(K(Oa,U("p2p-webrtc-direct"),U("p2p")),K(Ma,U("p2p-webrtc-direct"),U("p2p")),K(Oa,U("p2p-webrtc-direct")),K(Ma,U("p2p-webrtc-direct"))),br=mt(Ua,Pa,Oa,Ma,_u,ku,Wr,$m,Wm,wr,Bu,Iu),S2=mt(K(br,U("p2p-stardust"),U("p2p")),K(br,U("p2p-stardust"))),ze=mt(K(br,U("p2p")),_u,ku,Bu,Iu,U("p2p")),Su=mt(K(ze,U("p2p-circuit"),ze),K(ze,U("p2p-circuit")),K(U("p2p-circuit"),ze),K(br,U("p2p-circuit")),K(U("p2p-circuit"),br),U("p2p-circuit")),Ru=()=>mt(K(Su,Ru),Su),_e=Ru(),B2=mt(K(_e,ze,_e),K(ze,_e),K(_e,ze),_e,ze);var I2=mt(K(_e,U("webrtc"),U("p2p")),K(_e,U("webrtc")),K(br,U("webrtc"),U("p2p")),K(br,U("webrtc")),U("webrtc"));function Cu(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:Cu(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:Cu(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 Go=class extends no{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=>_e.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function Tu({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Mo(t).pb(Ht);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ht.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(p=>{o.error("error sending ICE candidate",p)})};let a=await s.read({signal:e});if(a.type!==Ht.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 Lo({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:Ht.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 Ho(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 qm="/webrtc",zm="/p2p-circuit",Vo="/webrtc-signaling/0.0.1",jm=30*1e3,qo=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,ro(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"})})}[eo]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Tr]=["@libp2p/transport"];[Qc]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Vo,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(Vo),this._started=!1}createListener(t){return new Go(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(Wl.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 xu({rtcConfiguration:await An(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 fr(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??jm),o=new yr(await An(this.init.rtcConfiguration)),s=new qe(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Tu({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new fr(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 Eu(r){let t=r.toString().split(qm+"/");if(t.length!==2)throw new D("webrtc protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);if(!t[0].includes(zm))throw new D("p2p-circuit protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new D("destination peer id was missing",Wt.ERR_INVALID_MULTIADDR);let s=e.protos().pop();if(s===void 0)throw new D("invalid multiaddr",Wt.ERR_INVALID_MULTIADDR);return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:lr(o)}}var nc={};bt(nc,{Ed25519PrivateKey:()=>Br,Ed25519PublicKey:()=>Un,generateKeyPair:()=>og,generateKeyPairFromSeed:()=>af,unmarshalEd25519PrivateKey:()=>rg,unmarshalEd25519PublicKey:()=>ng});function Yt(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 Ym(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Gr(r,...t){if(!Ym(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 xr(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 qr(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 Nu(r,t){Gr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var zo=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 ov=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Zm=async()=>{};async function Lu(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 Zm(),n+=s)}}function Du(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=Du(r)),Gr(r),r}function Ha(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Gr(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 zr=class{clone(){return this._cloneInto()}},Xm={}.toString;function Uu(r,t){if(t!==void 0&&Xm.call(t)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,t)}function jo(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 Er(r=32){if(zo&&typeof zo.getRandomValues=="function")return zo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function Jm(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 Pu=(r,t,e)=>r&t^~r&e,Ou=(r,t,e)=>r&t^r&e^t&e,Yr=class extends zr{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){qr(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){qr(this),Nu(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;Jm(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 Yo=BigInt(4294967295),Va=BigInt(32);function Mu(r,t=!1){return t?{h:Number(r&Yo),l:Number(r>>Va&Yo)}:{h:Number(r>>Va&Yo)|0,l:Number(r&Yo)|0}}function Qm(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}=Mu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var t0=(r,t)=>BigInt(r>>>0)<<Va|BigInt(t>>>0),e0=(r,t,e)=>r>>>e,r0=(r,t,e)=>r<<32-e|t>>>e,n0=(r,t,e)=>r>>>e|t<<32-e,o0=(r,t,e)=>r<<32-e|t>>>e,s0=(r,t,e)=>r<<64-e|t>>>e-32,i0=(r,t,e)=>r>>>e-32|t<<64-e,a0=(r,t)=>t,c0=(r,t)=>r,l0=(r,t,e)=>r<<e|t>>>32-e,u0=(r,t,e)=>t<<e|r>>>32-e,f0=(r,t,e)=>t<<e-32|r>>>64-e,h0=(r,t,e)=>r<<e-32|t>>>64-e;function d0(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var p0=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),m0=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,g0=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),y0=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,w0=(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 x0={fromBig:Mu,split:Qm,toBig:t0,shrSH:e0,shrSL:r0,rotrSH:n0,rotrSL:o0,rotrBH:s0,rotrBL:i0,rotr32H:a0,rotr32L:c0,rotlSH:l0,rotlSL:u0,rotlBH:f0,rotlBL:h0,add:d0,add3L:p0,add3H:m0,add4L:g0,add4H:y0,add5H:b0,add5L:w0},z=x0;var[E0,v0]=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))),Ye=new Uint32Array(80),Ze=new Uint32Array(80),Fa=class extends Yr{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:p,Gh:g,Gl:m,Hh:h,Hl:d}=this;return[t,e,n,o,s,i,a,c,l,u,f,p,g,m,h,d]}set(t,e,n,o,s,i,a,c,l,u,f,p,g,m,h,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=p|0,this.Gh=g|0,this.Gl=m|0,this.Hh=h|0,this.Hl=d|0}process(t,e){for(let b=0;b<16;b++,e+=4)Ye[b]=t.getUint32(e),Ze[b]=t.getUint32(e+=4);for(let b=16;b<80;b++){let I=Ye[b-15]|0,C=Ze[b-15]|0,S=z.rotrSH(I,C,1)^z.rotrSH(I,C,8)^z.shrSH(I,C,7),B=z.rotrSL(I,C,1)^z.rotrSL(I,C,8)^z.shrSL(I,C,7),_=Ye[b-2]|0,P=Ze[b-2]|0,N=z.rotrSH(_,P,19)^z.rotrBH(_,P,61)^z.shrSH(_,P,6),T=z.rotrSL(_,P,19)^z.rotrBL(_,P,61)^z.shrSL(_,P,6),F=z.add4L(B,T,Ze[b-7],Ze[b-16]),W=z.add4H(F,S,N,Ye[b-7],Ye[b-16]);Ye[b]=W|0,Ze[b]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:p,Fh:g,Fl:m,Gh:h,Gl:d,Hh:x,Hl:w}=this;for(let b=0;b<80;b++){let I=z.rotrSH(f,p,14)^z.rotrSH(f,p,18)^z.rotrBH(f,p,41),C=z.rotrSL(f,p,14)^z.rotrSL(f,p,18)^z.rotrBL(f,p,41),S=f&g^~f&h,B=p&m^~p&d,_=z.add5L(w,C,B,v0[b],Ze[b]),P=z.add5H(_,x,I,S,E0[b],Ye[b]),N=_|0,T=z.rotrSH(n,o,28)^z.rotrBH(n,o,34)^z.rotrBH(n,o,39),F=z.rotrSL(n,o,28)^z.rotrBL(n,o,34)^z.rotrBL(n,o,39),W=n&s^n&a^s&a,R=o&i^o&c^i&c;x=h|0,w=d|0,h=g|0,d=m|0,g=f|0,m=p|0,{h:f,l:p}=z.add(l|0,u|0,P|0,N|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=z.add3L(N,F,R);n=z.add3H(E,P,T,W),o=E|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:p}=z.add(this.Eh|0,this.El|0,f|0,p|0),{h:g,l:m}=z.add(this.Fh|0,this.Fl|0,g|0,m|0),{h,l:d}=z.add(this.Gh|0,this.Gl|0,h|0,d|0),{h:x,l:w}=z.add(this.Hh|0,this.Hl|0,x|0,w|0),this.set(n,o,s,i,a,c,l,u,f,p,g,m,h,d,x,w)}roundClean(){Ye.fill(0),Ze.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 Rn=jo(()=>new Fa);var Xo={};bt(Xo,{aInRange:()=>Ct,abool:()=>le,abytes:()=>Zr,bitGet:()=>R0,bitLen:()=>k0,bitMask:()=>Tn,bitSet:()=>C0,bytesToHex:()=>Re,bytesToNumberBE:()=>Ce,bytesToNumberLE:()=>ue,concatBytes:()=>Ne,createHmacDrbg:()=>qa,ensureBytes:()=>st,equalBytes:()=>I0,hexToBytes:()=>vr,hexToNumber:()=>Ga,inRange:()=>Cn,isBytes:()=>Xe,memoized:()=>Ar,notImplemented:()=>N0,numberToBytesBE:()=>Je,numberToBytesLE:()=>Te,numberToHexUnpadded:()=>Fu,numberToVarBytesBE:()=>B0,utf8ToBytes:()=>_0,validateObject:()=>Zt});var Wa=BigInt(0),Zo=BigInt(1),A0=BigInt(2);function Xe(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Zr(r){if(!Xe(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 S0=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Re(r){Zr(r);let t="";for(let e=0;e<r.length;e++)t+=S0[r[e]];return t}function Fu(r){let t=r.toString(16);return t.length&1?`0${t}`:t}function Ga(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return BigInt(r===""?"0":`0x${r}`)}var ke={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Hu(r){if(r>=ke._0&&r<=ke._9)return r-ke._0;if(r>=ke._A&&r<=ke._F)return r-(ke._A-10);if(r>=ke._a&&r<=ke._f)return r-(ke._a-10)}function vr(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=Hu(r.charCodeAt(s)),a=Hu(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 Ga(Re(r))}function ue(r){return Zr(r),Ga(Re(Uint8Array.from(r).reverse()))}function Je(r,t){return vr(r.toString(16).padStart(t*2,"0"))}function Te(r,t){return Je(r,t).reverse()}function B0(r){return vr(Fu(r))}function st(r,t,e){let n;if(typeof t=="string")try{n=vr(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Xe(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 Ne(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Zr(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 I0(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 _0(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Ka=r=>typeof r=="bigint"&&Wa<=r;function Cn(r,t,e){return Ka(r)&&Ka(t)&&Ka(e)&&t<=r&&r<e}function Ct(r,t,e,n){if(!Cn(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function k0(r){let t;for(t=0;r>Wa;r>>=Zo,t+=1);return t}function R0(r,t){return r>>BigInt(t)&Zo}function C0(r,t,e){return r|(e?Zo:Wa)<<BigInt(t)}var Tn=r=>(A0<<BigInt(r-1))-Zo,$a=r=>new Uint8Array(r),Vu=r=>Uint8Array.from(r);function qa(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=$a(r),o=$a(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=$a())=>{o=a(Vu([0]),f),n=a(),f.length!==0&&(o=a(Vu([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<t;){n=a();let g=n.slice();p.push(g),f+=n.length}return Ne(...p)};return(f,p)=>{i(),c(f);let g;for(;!(g=p(l()));)c();return i(),g}}var T0={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"||Xe(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=T0[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 N0=()=>{throw new Error("not implemented")};function Ar(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 St=BigInt(0),ct=BigInt(1),Sr=BigInt(2),L0=BigInt(3),za=BigInt(4),Ku=BigInt(5),$u=BigInt(8),D0=BigInt(9),U0=BigInt(16);function J(r,t){let e=r%t;return e>=St?e:t+e}function ja(r,t,e){if(e<=St||t<St)throw new Error("Expected power/modulo > 0");if(e===ct)return St;let n=ct;for(;t>St;)t&ct&&(n=n*r%e),r=r*r%e,t>>=ct;return n}function it(r,t,e){let n=r;for(;t-- >St;)n*=n,n%=e;return n}function Jo(r,t){if(r===St||t<=St)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=J(r,t),n=t,o=St,s=ct,i=ct,a=St;for(;e!==St;){let l=n/e,u=n%e,f=o-i*l,p=s-a*l;n=e,e=u,o=i,s=a,i=f,a=p}if(n!==ct)throw new Error("invert: does not exist");return J(o,t)}function P0(r){let t=(r-ct)/Sr,e,n,o;for(e=r-ct,n=0;e%Sr===St;e/=Sr,n++);for(o=Sr;o<r&&ja(o,t,r)!==r-ct;o++);if(n===1){let i=(r+ct)/za;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+ct)/Sr;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),p=a.pow(c,e);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let g=1;for(let h=a.sqr(p);g<l&&!a.eql(h,a.ONE);g++)h=a.sqr(h);let m=a.pow(u,ct<<BigInt(l-g-1));u=a.sqr(m),f=a.mul(f,m),p=a.mul(p,u),l=g}return f}}function O0(r){if(r%za===L0){let t=(r+ct)/za;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%$u===Ku){let t=(r-Ku)/$u;return function(n,o){let s=n.mul(o,Sr),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,Sr),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%U0,P0(r)}var Wu=(r,t)=>(J(r,t)&ct)===ct,M0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ya(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=M0.reduce((n,o)=>(n[o]="function",n),t);return Zt(r,e)}function H0(r,t,e){if(e<St)throw new Error("Expected power > 0");if(e===St)return r.ONE;if(e===ct)return t;let n=r.ONE,o=t;for(;e>St;)e&ct&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ct;return n}function V0(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 Za(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function Qo(r,t,e=!1,n={}){if(r<=St)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Za(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=O0(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Tn(o),ZERO:St,ONE:ct,create:c=>J(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return St<=c&&c<r},is0:c=>c===St,isOdd:c=>(c&ct)===ct,neg:c=>J(-c,r),eql:(c,l)=>c===l,sqr:c=>J(c*c,r),add:(c,l)=>J(c+l,r),sub:(c,l)=>J(c-l,r),mul:(c,l)=>J(c*l,r),pow:(c,l)=>H0(a,c,l),div:(c,l)=>J(c*Jo(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Jo(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>V0(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Te(c,s):Je(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 Gu(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 Xa(r){let t=Gu(r);return t+Math.ceil(t/2)}function qu(r,t,e=!1){let n=r.length,o=Gu(t),s=Xa(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=J(i,t-ct)+ct;return e?Te(a,o):Je(a,o)}var K0=BigInt(0),Ja=BigInt(1),Qa=new WeakMap,zu=new WeakMap;function ts(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>K0;)i&Ja&&(a=a.add(c)),c=c.double(),i>>=Ja;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),l=[],u=s,f=u;for(let p=0;p<a;p++){f=u,l.push(f);for(let g=1;g<c;g++)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,p=BigInt(2**s-1),g=2**s,m=BigInt(s);for(let h=0;h<c;h++){let d=h*l,x=Number(a&p);a>>=m,x>l&&(x-=g,a+=Ja);let w=d,b=d+Math.abs(x)-1,I=h%2!==0,C=x<0;x===0?f=f.add(e(I,i[w])):u=u.add(e(C,i[b]))}return{p:u,f}},wNAFCached(s,i,a){let c=zu.get(s)||1,l=Qa.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&Qa.set(s,a(l))),this.wNAF(c,l,i)},setWindowSize(s,i){n(i),zu.set(s,i),Qa.delete(s)}}}function Nn(r){return Ya(r.Fp),Zt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Za(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var fe=BigInt(0),Vt=BigInt(1),es=BigInt(2),$0=BigInt(8),W0={zip215:!0};function G0(r){let t=Nn(r);return Zt(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...t})}function ju(r){let t=G0(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=es<<BigInt(a*8)-Vt,u=e.create,f=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:fe}}}),p=t.adjustScalarBytes||(E=>E),g=t.domain||((E,y,A)=>{if(le("phflag",A),y.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function m(E,y){Ct("coordinate "+E,y,fe,l)}function h(E){if(!(E instanceof w))throw new Error("ExtendedPoint expected")}let d=Ar((E,y)=>{let{ex:A,ey:k,ez:v}=E,L=E.is0();y==null&&(y=L?$0:e.inv(v));let M=u(A*y),V=u(k*y),$=u(v*y);if(L)return{x:fe,y:Vt};if($!==Vt)throw new Error("invZ was invalid");return{x:M,y:V}}),x=Ar(E=>{let{a:y,d:A}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:k,ey:v,ez:L,et:M}=E,V=u(k*k),$=u(v*v),q=u(L*L),Z=u(q*q),Q=u(V*y),ht=u(q*u(Q+$)),ot=u(Z+u(A*u(V*$)));if(ht!==ot)throw new Error("bad point: equation left != right (1)");let nt=u(k*v),Jt=u(L*M);if(nt!==Jt)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(y,A,k,v){this.ex=y,this.ey=A,this.ez=k,this.et=v,m("x",y),m("y",A),m("z",k),m("t",v),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof w)throw new Error("extended point not allowed");let{x:A,y:k}=y||{};return m("x",A),m("y",k),new w(A,k,Vt,u(A*k))}static normalizeZ(y){let A=e.invertBatch(y.map(k=>k.ez));return y.map((k,v)=>k.toAffine(A[v])).map(w.fromAffine)}_setWindowSize(y){C.setWindowSize(this,y)}assertValidity(){x(this)}equals(y){h(y);let{ex:A,ey:k,ez:v}=this,{ex:L,ey:M,ez:V}=y,$=u(A*V),q=u(L*v),Z=u(k*V),Q=u(M*v);return $===q&&Z===Q}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:A,ey:k,ez:v}=this,L=u(A*A),M=u(k*k),V=u(es*u(v*v)),$=u(y*L),q=A+k,Z=u(u(q*q)-L-M),Q=$+M,ht=Q-V,ot=$-M,nt=u(Z*ht),Jt=u(Q*ot),Bt=u(Z*ot),Qt=u(ht*Q);return new w(nt,Jt,Qt,Bt)}add(y){h(y);let{a:A,d:k}=t,{ex:v,ey:L,ez:M,et:V}=this,{ex:$,ey:q,ez:Z,et:Q}=y;if(A===BigInt(-1)){let Wc=u((L-v)*(q+$)),Gc=u((L+v)*(q-$)),ni=u(Gc-Wc);if(ni===fe)return this.double();let qc=u(M*es*Q),zc=u(V*es*Z),jc=zc+qc,Yc=Gc+Wc,Zc=zc-qc,nd=u(jc*ni),od=u(Yc*Zc),sd=u(jc*Zc),id=u(ni*Yc);return new w(nd,od,id,sd)}let ht=u(v*$),ot=u(L*q),nt=u(V*k*Q),Jt=u(M*Z),Bt=u((v+L)*($+q)-ht-ot),Qt=Jt-nt,ar=Jt+nt,dn=u(ot-A*ht),Qn=u(Bt*Qt),td=u(ar*dn),ed=u(Bt*dn),rd=u(Qt*ar);return new w(Qn,td,rd,ed)}subtract(y){return this.add(y.negate())}wNAF(y){return C.wNAFCached(this,y,w.normalizeZ)}multiply(y){let A=y;Ct("scalar",A,Vt,n);let{p:k,f:v}=this.wNAF(A);return w.normalizeZ([k,v])[0]}multiplyUnsafe(y){let A=y;return Ct("scalar",A,fe,n),A===fe?I:this.equals(I)||A===Vt?this:this.equals(b)?this.wNAF(A).p:C.unsafeLadder(this,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(y){return d(this,y)}clearCofactor(){let{h:y}=t;return y===Vt?this:this.multiplyUnsafe(y)}static fromHex(y,A=!1){let{d:k,a:v}=t,L=e.BYTES;y=st("pointHex",y,L),le("zip215",A);let M=y.slice(),V=y[L-1];M[L-1]=V&-129;let $=ue(M),q=A?l:e.ORDER;Ct("pointHex.y",$,fe,q);let Z=u($*$),Q=u(Z-Vt),ht=u(k*Z-v),{isValid:ot,value:nt}=f(Q,ht);if(!ot)throw new Error("Point.fromHex: invalid y coordinate");let Jt=(nt&Vt)===Vt,Bt=(V&128)!==0;if(!A&&nt===fe&&Bt)throw new Error("Point.fromHex: x=0 and x_0=1");return Bt!==Jt&&(nt=u(-nt)),w.fromAffine({x:nt,y:$})}static fromPrivateKey(y){return _(y).point}toRawBytes(){let{x:y,y:A}=this.toAffine(),k=Te(A,e.BYTES);return k[k.length-1]|=y&Vt?128:0,k}toHex(){return Re(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,Vt,u(t.Gx*t.Gy)),w.ZERO=new w(fe,Vt,Vt,fe);let{BASE:b,ZERO:I}=w,C=ts(w,a*8);function S(E){return J(E,n)}function B(E){return S(ue(E))}function _(E){let y=a;E=st("private key",E,y);let A=st("hashed private key",s(E),2*y),k=p(A.slice(0,y)),v=A.slice(y,2*y),L=B(k),M=b.multiply(L),V=M.toRawBytes();return{head:k,prefix:v,scalar:L,point:M,pointBytes:V}}function P(E){return _(E).pointBytes}function N(E=new Uint8Array,...y){let A=Ne(...y);return B(s(g(A,st("context",E),!!o)))}function T(E,y,A={}){E=st("message",E),o&&(E=o(E));let{prefix:k,scalar:v,pointBytes:L}=_(y),M=N(A.context,k,E),V=b.multiply(M).toRawBytes(),$=N(A.context,V,L,E),q=S(M+$*v);Ct("signature.s",q,fe,n);let Z=Ne(V,Te(q,e.BYTES));return st("result",Z,a*2)}let F=W0;function W(E,y,A,k=F){let{context:v,zip215:L}=k,M=e.BYTES;E=st("signature",E,2*M),y=st("message",y),L!==void 0&&le("zip215",L),o&&(y=o(y));let V=ue(E.slice(M,2*M)),$,q,Z;try{$=w.fromHex(A,L),q=w.fromHex(E.slice(0,M),L),Z=b.multiplyUnsafe(V)}catch{return!1}if(!L&&$.isSmallOrder())return!1;let Q=N(v,q.toRawBytes(),$.toRawBytes(),y);return q.add($.multiplyUnsafe(Q)).subtract(Z).clearCofactor().equals(w.ZERO)}return b._setWindowSize(8),{CURVE:t,getPublicKey:P,sign:T,verify:W,ExtendedPoint:w,utils:{getExtendedPublicKey:_,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=w.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var Xr=BigInt(0),tc=BigInt(1);function q0(r){return Zt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Yu(r){let t=q0(r),{P:e}=t,n=w=>J(w,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(w=>w),c=t.powPminus2||(w=>ja(w,e-BigInt(2),e));function l(w,b,I){let C=n(w*(b-I));return b=n(b-C),I=n(I+C),[b,I]}let u=(t.a-BigInt(2))/BigInt(4);function f(w,b){Ct("u",w,Xr,e),Ct("scalar",b,Xr,e);let I=b,C=w,S=tc,B=Xr,_=w,P=tc,N=Xr,T;for(let W=BigInt(o-1);W>=Xr;W--){let R=I>>W&tc;N^=R,T=l(N,S,_),S=T[0],_=T[1],T=l(N,B,P),B=T[0],P=T[1],N=R;let E=S+B,y=n(E*E),A=S-B,k=n(A*A),v=y-k,L=_+P,M=_-P,V=n(M*E),$=n(L*A),q=V+$,Z=V-$;_=n(q*q),P=n(C*n(Z*Z)),S=n(y*k),B=n(v*(y+n(u*v)))}T=l(N,S,_),S=T[0],_=T[1],T=l(N,B,P),B=T[0],P=T[1];let F=c(B);return n(S*F)}function p(w){return Te(n(w),s)}function g(w){let b=st("u coordinate",w,s);return i===32&&(b[31]&=127),ue(b)}function m(w){let b=st("scalar",w),I=b.length;if(I!==s&&I!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${I}`);return ue(a(b))}function h(w,b){let I=g(b),C=m(w),S=f(I,C);if(S===Xr)throw new Error("Invalid private or public key received");return p(S)}let d=p(t.Gu);function x(w){return h(w,d)}return{scalarMult:h,scalarMultBase:x,getSharedSecret:(w,b)=>h(w,b),getPublicKey:w=>x(w),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:d}}var Ln=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Zu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Tv=BigInt(0),z0=BigInt(1),Xu=BigInt(2),j0=BigInt(3),Y0=BigInt(5),Z0=BigInt(8);function Ju(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Ln,a=r*r%s*r%s,c=it(a,Xu,s)*a%s,l=it(c,z0,s)*r%s,u=it(l,Y0,s)*l%s,f=it(u,t,s)*u%s,p=it(f,e,s)*f%s,g=it(p,n,s)*p%s,m=it(g,o,s)*g%s,h=it(m,o,s)*g%s,d=it(h,t,s)*u%s;return{pow_p_5_8:it(d,Xu,s)*r%s,b2:a}}function Qu(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function X0(r,t){let e=Ln,n=J(t*t*t,e),o=J(n*n*t,e),s=Ju(r*o).pow_p_5_8,i=J(r*n*s,e),a=J(t*i*i,e),c=i,l=J(i*Zu,e),u=a===r,f=a===J(-r,e),p=a===J(-r*Zu,e);return u&&(i=c),(f||p)&&(i=l),Wu(i,e)&&(i=J(-i,e)),{isValid:u||f,value:i}}var J0=Qo(Ln,void 0,!0),Q0={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:J0,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Z0,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Rn,randomBytes:Er,adjustScalarBytes:Qu,uvRatio:X0},Jr=ju(Q0);var Dn=Yu({P:Ln,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Ln,{pow_p_5_8:e,b2:n}=Ju(r);return J(it(e,j0,t)*n,t)},adjustScalarBytes:Qu,randomBytes:Er});var Qr=32,Le=64,rs=32;function tf(){let r=Jr.utils.randomPrivateKey(),t=Jr.getPublicKey(r);return{privateKey:of(r,t),publicKey:t}}function ef(r){if(r.length!==rs)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=Jr.getPublicKey(t);return{privateKey:of(t,e),publicKey:e}}function rf(r,t){let e=r.subarray(0,rs);return Jr.sign(t instanceof Uint8Array?t:t.subarray(),e)}function nf(r,t,e){return Jr.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function of(r,t){let e=new Uint8Array(Le);for(let n=0;n<rs;n++)e[n]=r[n],e[rs+n]=t[n];return e}var Pt={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 ec={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function sf(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=Pt.get();e*=8;async function c(f,p){let g=a.getRandomValues(new Uint8Array(s)),m=a.getRandomValues(new Uint8Array(n)),h={name:t,iv:m};typeof p=="string"&&(p=Y(p));let d;if(p.length===0){d=await a.subtle.importKey("jwk",ec,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(w,b,{name:t,length:e},!0,["encrypt"])}catch{d=await a.subtle.importKey("jwk",ec,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(w,b,{name:t,length:e},!0,["encrypt"])}let x=await a.subtle.encrypt(h,d,f);return yt([g,h.iv,new Uint8Array(x)])}async function l(f,p){let g=f.subarray(0,s),m=f.subarray(s,s+n),h=f.subarray(s+n),d={name:t,iv:m};typeof p=="string"&&(p=Y(p));let x;if(p.length===0)try{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},I=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);x=await a.subtle.deriveKey(b,I,{name:t,length:e},!0,["decrypt"])}catch{x=await a.subtle.importKey("jwk",ec,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},I=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);x=await a.subtle.deriveKey(b,I,{name:t,length:e},!0,["decrypt"])}let w=await a.subtle.decrypt(d,x,h);return new Uint8Array(w)}return{encrypt:c,decrypt:l}}async function tn(r,t){let n=await sf().encrypt(r,t);return gi.encode(n)}var lt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(lt||(lt={}));var rc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(rc||(rc={}));(function(r){r.codec=()=>gr(rc)})(lt||(lt={}));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),lt.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=lt.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),lt.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=lt.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 Un=class{_key;constructor(t){this._key=en(t,Qr)}verify(t,e){return nf(this._key,e,t)}marshal(){return this._key}get bytes(){return we.encode({Type:lt.Ed25519,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(t)?t.then(({bytes:e})=>e):t.bytes}},Br=class{_key;_publicKey;constructor(t,e){this._key=en(t,Le),this._publicKey=en(e,Qr)}sign(t){return rf(this._key,t)}get public(){return new Un(this._publicKey)}marshal(){return this._key}get bytes(){return be.encode({Type:lt.Ed25519,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}async hash(){let t=kt.digest(this.bytes),e;return Yt(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let t=Be.digest(this.public.bytes);return dt.encode(t.bytes).substring(1)}async export(t,e="libp2p-key"){if(e==="libp2p-key")return tn(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function rg(r){if(r.length>Le){r=en(r,Le+Qr);let n=r.subarray(0,Le),o=r.subarray(Le,r.length);return new Br(n,o)}r=en(r,Le);let t=r.subarray(0,Le),e=r.subarray(Qr);return new Br(t,e)}function ng(r){return r=en(r,Qr),new Un(r)}async function og(){let{privateKey:r,publicKey:t}=tf();return new Br(r,t)}async function af(r){let{privateKey:t,publicKey:e}=ef(r);return new Br(t,e)}function en(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 dc={};bt(dc,{MAX_RSA_KEY_SIZE:()=>qn,RsaPrivateKey:()=>an,RsaPublicKey:()=>Gn,fromJwk:()=>Tg,generateKeyPair:()=>Ng,unmarshalRsaPrivateKey:()=>fc,unmarshalRsaPublicKey:()=>Cg});function Ir(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return Er(r)}var nr={};bt(nr,{exportToPem:()=>Bg,importFromPem:()=>Ig,jwkToPkcs1:()=>Eg,jwkToPkix:()=>Ag,pkcs1ToJwk:()=>xg,pkixToJwk:()=>vg});var os=class extends zr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,xr(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 qr(this),this.iHash.update(t),this}digestInto(t){qr(this),Gr(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()}},Qe=(r,t,e)=>new os(r,t).update(e).digest();Qe.create=(r,t)=>new os(r,t);function sg(r,t,e,n){xr(r);let o=Uu({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=Qe.create(r,c),p=f._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:f,PRFSalt:p}}function ig(r,t,e,n,o){return r.destroy(),t.destroy(),n&&n.destroy(),o.fill(0),e}async function oc(r,t,e,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=sg(r,t,e,n),u,f=new Uint8Array(4),p=jr(f),g=new Uint8Array(c.outputLen);for(let m=1,h=0;h<s;m++,h+=c.outputLen){let d=a.subarray(h,h+c.outputLen);p.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(g),d.set(g.subarray(0,d.length)),await Lu(o-1,i,()=>{c._cloneInto(u).update(g).digestInto(g);for(let x=0;x<d.length;x++)d[x]^=g[x]})}return ig(c,l,a,u,g)}var j=dd(cf());function _r(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 tr(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 as(...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 ic(){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=_r(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,_r(s,8)-n}function lf(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=tr(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=tr(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 uf(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 sA=Math.log(2);function cs(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function ac(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 Me(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 On=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return ac(this.items)}},Pn=[new Uint8Array([1])],ff="0123456789";var on="",de=new ArrayBuffer(0),cc=new Uint8Array(0),Mn="EndOfContent",df="OCTET STRING",pf="BIT STRING";function He(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):cc}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(!Me(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:j.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Ue=class{constructor({blockLength:t=0,error:e=on,warnings:n=[],valueBeforeDecode:o=cc}={}){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)}}};Ue.NAME="baseBlock";var Ut=class extends Ue{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 ls=class extends He(Ue){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):cc,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=tr(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(!Me(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 p=new Uint8Array(u);for(let g=0;g<l.length;g++)p[g]=l[g];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let p=0;p<c;p++)f[p]=l[p];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=_r(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}}};ls.NAME="identificationBlock";var us=class extends Ue{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(!Me(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=_r(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=tr(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}}};us.NAME="lengthBlock";var O={},Tt=class extends Ue{constructor({name:t=on,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new ls(o),this.lenBlock=new us(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 On;e||mf(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():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 uf(e,n)}};Tt.NAME="BaseBlock";function mf(r){if(r instanceof O.Constructed)for(let t of r.valueBlock.value)mf(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var fs=class extends Tt{constructor({value:t=on,...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}'`}};fs.NAME="BaseStringBlock";var hs=class extends He(Ut){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};hs.NAME="PrimitiveValueBlock";var gf,ds=class extends Tt{constructor(t={}){super(t,hs),this.idBlock.isConstructed=!1}};gf=ds;O.Primitive=gf;ds.NAME="PRIMITIVE";function mg(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 qs(r,t=0,e=r.length){let n=t,o=new Tt({},Ut),s=new Ue;if(!Me(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=Tt;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=O.EndOfContent;break;case 1:c=O.Boolean;break;case 2:c=O.Integer;break;case 3:c=O.BitString;break;case 4:c=O.OctetString;break;case 5:c=O.Null;break;case 6:c=O.ObjectIdentifier;break;case 10:c=O.Enumerated;break;case 12:c=O.Utf8String;break;case 13:c=O.RelativeObjectIdentifier;break;case 14:c=O.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=O.Sequence;break;case 17:c=O.Set;break;case 18:c=O.NumericString;break;case 19:c=O.PrintableString;break;case 20:c=O.TeletexString;break;case 21:c=O.VideotexString;break;case 22:c=O.IA5String;break;case 23:c=O.UTCTime;break;case 24:c=O.GeneralizedTime;break;case 25:c=O.GraphicString;break;case 26:c=O.VisibleString;break;case 27:c=O.GeneralString;break;case 28:c=O.UniversalString;break;case 29:c=O.CharacterString;break;case 30:c=O.BmpString;break;case 31:c=O.DATE;break;case 32:c=O.TimeOfDay;break;case 33:c=O.DateTime;break;case 34:c=O.Duration;break;default:{let l=o.idBlock.isConstructed?new O.Constructed:new O.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?O.Constructed:O.Primitive}return o=mg(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 sn(r){if(!r.byteLength){let t=new Tt({},Ut);return t.error="Input buffer has zero length",{offset:-1,result:t}}return qs(j.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function gg(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=j.BufferSourceConverter.toUint8Array(t);if(!Me(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(;gg(this.isIndefiniteForm,n)>0;){let i=qs(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===Mn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Mn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new On;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 yf,er=class extends Tt{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 ud=Object.create;var eo=Object.defineProperty;var fd=Object.getOwnPropertyDescriptor;var hd=Object.getOwnPropertyNames;var dd=Object.getPrototypeOf,pd=Object.prototype.hasOwnProperty;var md=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),bt=(r,t)=>{for(var e in t)eo(r,e,{get:t[e],enumerable:!0})},Qc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hd(t))!pd.call(r,o)&&o!==e&&eo(r,o,{get:()=>t[o],enumerable:!(n=fd(t,o))||n.enumerable});return r};var gd=(r,t,e)=>(e=r!=null?ud(dd(r)):{},Qc(t||!r||!r.__esModule?eo(e,"default",{value:r,enumerable:!0}):e,r)),yd=r=>Qc(eo({},"__esModule",{value:!0}),r);var ff=md(nn=>{"use strict";var ug="[object ArrayBuffer]",De=class r{static isArrayBuffer(t){return Object.prototype.toString.call(t)===ug}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}},ac="string",fg=/^[0-9a-f]+$/i,hg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,dg=/^[a-zA-Z0-9-_]+$/,as=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=De.toUint8Array(t),n="";for(let s=0;s<e.length;s++)n+=String.fromCharCode(e[s]);return decodeURIComponent(escape(n))}},Xt=class{static toString(t,e=!1){let n=De.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}},cs=class r{static isHex(t){return typeof t===ac&&fg.test(t)}static isBase64(t){return typeof t===ac&&hg.test(t)}static isBase64Url(t){return typeof t===ac&&dg.test(t)}static ToString(t,e="utf8"){let n=De.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 Xt.toString(n,!0);case"utf16":case"utf16be":return Xt.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 Xt.fromString(t,!0);case"utf16":case"utf16be":return Xt.fromString(t);default:throw new Error(`Unknown type of encoding '${e}'`)}}static ToBase64(t){let e=De.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 as.fromString(t);case"utf16":case"utf16be":return Xt.fromString(t);case"utf16le":case"usc2":return Xt.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 as.toString(t);case"utf16":case"utf16be":return Xt.toString(t);case"utf16le":case"usc2":return Xt.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=De.toUint8Array(t),n="";for(let o=0;o<e.length;o++)n+=String.fromCharCode(e[o]);return n}static ToHex(t){let e=De.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 Xt.toString(t,e)}static FromUtf16String(t,e=!1){return Xt.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,"")||""}};cs.DEFAULT_UTF8_ENCODING="utf8";function pg(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 mg(...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 gg(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}nn.BufferSourceConverter=De;nn.Convert=cs;nn.assign=pg;nn.combine=mg;nn.isEqual=gg});var By={};bt(By,{webRTC:()=>Sy,webRTCDirect:()=>Ay});var ro=Symbol.for("@libp2p/peer-id");function tl(r){return r!=null&&!!r[ro]}var no=Symbol.for("@libp2p/transport");var el;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(el||(el={}));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 oo=(r,...t)=>{try{[...t]}catch{}};var so=class extends EventTarget{#t=new Map;constructor(){super(),oo(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 wd(t,e))}},wd=globalThis.CustomEvent;var Nr=Symbol.for("@libp2p/service-capabilities"),rl=Symbol.for("@libp2p/service-dependencies");var fi={};bt(fi,{base58btc:()=>dt,base58flickr:()=>Sd});var rw=new Uint8Array(0);function nl(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 Ae(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 ol(r){return new TextEncoder().encode(r)}function sl(r){return new TextDecoder().decode(r)}function bd(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(m){if(m instanceof Uint8Array||(ArrayBuffer.isView(m)?m=new Uint8Array(m.buffer,m.byteOffset,m.byteLength):Array.isArray(m)&&(m=Uint8Array.from(m))),!(m instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(m.length===0)return"";for(var h=0,d=0,x=0,w=m.length;x!==w&&m[x]===0;)x++,h++;for(var b=(w-x)*u+1>>>0,I=new Uint8Array(b);x!==w;){for(var C=m[x],S=0,B=b-1;(C!==0||S<d)&&B!==-1;B--,S++)C+=256*I[B]>>>0,I[B]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");d=S,x++}for(var _=b-d;_!==b&&I[_]===0;)_++;for(var P=c.repeat(h);_<b;++_)P+=r.charAt(I[_]);return P}function p(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var h=0;if(m[h]!==" "){for(var d=0,x=0;m[h]===c;)d++,h++;for(var w=(m.length-h)*l+1>>>0,b=new Uint8Array(w);m[h];){var I=e[m.charCodeAt(h)];if(I===255)return;for(var C=0,S=w-1;(I!==0||C<x)&&S!==-1;S--,C++)I+=a*b[S]>>>0,b[S]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");x=C,h++}if(m[h]!==" "){for(var B=w-x;B!==w&&b[B]===0;)B++;for(var _=new Uint8Array(d+(w-B)),P=d;B!==w;)_[P++]=b[B++];return _}}}function g(m){var h=p(m);if(h)return h;throw new Error(`Non-${t} character`)}return{encode:f,decodeUnsafe:p,decode:g}}var xd=bd,Ed=xd,al=Ed;var ai=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")}},ci=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 cl(this,t)}},li=class{decoders;constructor(t){this.decoders=t}or(t){return cl(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 cl(r,t){return new li({...r.decoders??{[r.prefix]:r},...t.decoders??{[t.prefix]:t}})}var ui=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 ai(t,e,n),this.decoder=new ci(t,e,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Lr({name:r,prefix:t,encode:e,decode:n}){return new ui(r,t,e,n)}function Ke({name:r,prefix:t,alphabet:e}){let{encode:n,decode:o}=al(e,r);return Lr({prefix:t,name:r,encode:n,decode:s=>Ae(o(s))})}function vd(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 Ad(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 ut({name:r,prefix:t,bitsPerChar:e,alphabet:n}){return Lr({prefix:t,name:r,encode(o){return Ad(o,n,e)},decode(o){return vd(o,n,e,r)}})}var dt=Ke({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sd=Ke({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var hi={};bt(hi,{base10:()=>Bd});var Bd=Ke({prefix:"9",name:"base10",alphabet:"0123456789"});var di={};bt(di,{base16:()=>Id,base16upper:()=>_d});var Id=ut({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_d=ut({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var pi={};bt(pi,{base2:()=>kd});var kd=ut({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var mi={};bt(mi,{base256emoji:()=>Ld});var ll=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}"),Rd=ll.reduce((r,t,e)=>(r[e]=t,r),[]),Cd=ll.reduce((r,t,e)=>(r[t.codePointAt(0)]=e,r),[]);function Td(r){return r.reduce((t,e)=>(t+=Rd[e],t),"")}function Nd(r){let t=[];for(let e of r){let n=Cd[e.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${e}`);t.push(n)}return new Uint8Array(t)}var Ld=Lr({prefix:"\u{1F680}",name:"base256emoji",encode:Td,decode:Nd});var gi={};bt(gi,{base32:()=>Se,base32hex:()=>Od,base32hexpad:()=>Hd,base32hexpadupper:()=>Vd,base32hexupper:()=>Md,base32pad:()=>Ud,base32padupper:()=>Pd,base32upper:()=>Dd,base32z:()=>Fd});var Se=ut({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Dd=ut({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ud=ut({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Pd=ut({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Od=ut({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Md=ut({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Hd=ut({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Vd=ut({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Fd=ut({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var yi={};bt(yi,{base36:()=>Kd,base36upper:()=>$d});var Kd=Ke({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),$d=Ke({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var xi={};bt(xi,{base64:()=>wi,base64pad:()=>Wd,base64url:()=>bi,base64urlpad:()=>Gd});var wi=ut({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Wd=ut({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),bi=ut({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Gd=ut({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ei={};bt(Ei,{base8:()=>qd});var qd=ut({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var vi={};bt(vi,{identity:()=>zd});var zd=Lr({prefix:"\0",name:"identity",encode:r=>sl(r),decode:r=>ol(r)});var ww=new TextEncoder,bw=new TextDecoder;var Bi={};bt(Bi,{identity:()=>Be});var te={};bt(te,{Digest:()=>lr,create:()=>$t,decode:()=>$e,equals:()=>Si});var Zd=hl,ul=128,Xd=127,Jd=~Xd,Qd=Math.pow(2,31);function hl(r,t,e){t=t||[],e=e||0;for(var n=e;r>=Qd;)t[e++]=r&255|ul,r/=128;for(;r&Jd;)t[e++]=r&255|ul,r>>>=7;return t[e]=r|0,hl.bytes=e-n+1,t}var tp=Ai,ep=128,fl=127;function Ai(r,n){var e=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Ai.bytes=0,new RangeError("Could not decode varint");i=r[s++],e+=o<28?(i&fl)<<o:(i&fl)*Math.pow(2,o),o+=7}while(i>=ep);return Ai.bytes=s-n,e}var rp=Math.pow(2,7),np=Math.pow(2,14),op=Math.pow(2,21),sp=Math.pow(2,28),ip=Math.pow(2,35),ap=Math.pow(2,42),cp=Math.pow(2,49),lp=Math.pow(2,56),up=Math.pow(2,63),fp=function(r){return r<rp?1:r<np?2:r<op?3:r<sp?4:r<ip?5:r<ap?6:r<cp?7:r<lp?8:r<up?9:10},hp={encode:Zd,decode:tp,encodingLength:fp},dp=hp,mn=dp;function gn(r,t=0){return[mn.decode(r,t),mn.decode.bytes]}function Dr(r,t,e=0){return mn.encode(r,t,e),t}function Ur(r){return mn.encodingLength(r)}function $t(r,t){let e=t.byteLength,n=Ur(r),o=n+Ur(e),s=new Uint8Array(o+e);return Dr(r,s,0),Dr(e,s,n),s.set(t,o),new lr(r,e,t,s)}function $e(r){let t=Ae(r),[e,n]=gn(t),[o,s]=gn(t.subarray(n)),i=t.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new lr(e,o,i,t)}function Si(r,t){if(r===t)return!0;{let e=t;return r.code===e.code&&r.size===e.size&&e.bytes instanceof Uint8Array&&nl(r.bytes,e.bytes)}}var lr=class{code;size;digest;bytes;constructor(t,e,n,o){this.code=t,this.size=e,this.digest=n,this.bytes=o}};var dl=0,pp="identity",pl=Ae;function mp(r){return $t(dl,pl(r))}var Be={code:dl,name:pp,encode:pl,digest:mp};var ki={};bt(ki,{sha256:()=>kt,sha512:()=>gp});function _i({name:r,code:t,encode:e}){return new Ii(r,t,e)}var Ii=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?$t(this.code,e):e.then(n=>$t(this.code,n))}else throw Error("Unknown type, must be binary type")}};function gl(r){return async t=>new Uint8Array(await crypto.subtle.digest(r,t))}var kt=_i({name:"sha2-256",code:18,encode:gl("SHA-256")}),gp=_i({name:"sha2-512",code:19,encode:gl("SHA-512")});function yl(r,t){let{bytes:e,version:n}=r;switch(n){case 0:return wp(e,Ri(r),t??dt.encoder);default:return bp(e,Ri(r),t??Se.encoder)}}var wl=new WeakMap;function Ri(r){let t=wl.get(r);if(t==null){let e=new Map;return wl.set(r,e),e}return t}var zt=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!==yn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(e.code!==xp)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=$t(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&&Si(t.multihash,n.multihash)}toString(t){return yl(this,t)}toJSON(){return{"/":yl(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??bl(n,o,s.bytes))}else if(e[Ep]===!0){let{version:n,multihash:o,code:s}=e,i=$e(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!==yn)throw new Error(`Version 0 CID must use dag-pb (code: ${yn}) block encoding`);return new r(t,e,n,n.bytes)}case 1:{let o=bl(t,e,n.bytes);return new r(t,e,n,o)}default:throw new Error("Invalid version")}}static createV0(t){return r.create(0,yn,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=Ae(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 lr(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,p]=gn(t.subarray(e));return e+=p,f},o=n(),s=yn;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]=yp(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 Ri(s).set(n,t),s}};function yp(r,t){switch(r[0]){case"Q":{let e=t??dt;return[dt.prefix,e.decode(`${dt.prefix}${r}`)]}case dt.prefix:{let e=t??dt;return[dt.prefix,e.decode(r)]}case Se.prefix:{let e=t??Se;return[Se.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 wp(r,t,e){let{prefix:n}=e;if(n!==dt.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 bp(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 yn=112,xp=18;function bl(r,t,e){let n=Ur(r),o=n+Ur(t),s=new Uint8Array(o+e.byteLength);return Dr(r,s,0),Dr(t,s,n),s.set(e,o),s}var Ep=Symbol.for("@ipld/js-cid/CID");var me={...vi,...pi,...Ei,...hi,...di,...gi,...yi,...fi,...xi,...mi},Vw={...ki,...Bi};function xt(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 Et(r=0){return new Uint8Array(r)}function vt(r=0){return new Uint8Array(r)}function El(r,t,e,n){return{name:r,prefix:t,encoder:{name:r,prefix:t,encode:e},decoder:{decode:n}}}var xl=El("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Ci=El("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=vt(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}),vp={utf8:xl,"utf-8":xl,hex:me.base16,latin1:Ci,ascii:Ci,binary:Ci,...me},ao=vp;function Y(r,t="utf8"){let e=ao[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.decoder.decode(`${e.prefix}${r}`)}function G(r,t="utf8"){let e=ao[t];if(e==null)throw new Error(`Unsupported encoding "${t}"`);return e.encoder.encode(r).substring(1)}var Al=Symbol.for("nodejs.util.inspect.custom"),vl=Object.values(me).map(r=>r.decoder).reduce((r,t)=>r.or(t),me.identity.decoder),Sl=114,Li=36,Di=37,wn=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()})`}[ro]=!0;toString(){return this.string==null&&(this.string=dt.encode(this.multihash.bytes).slice(1)),this.string}toCID(){return zt.createV1(Sl,this.multihash)}toBytes(){return this.multihash.bytes}toJSON(){return this.toString()}equals(t){if(t==null)return!1;if(t instanceof Uint8Array)return xt(this.multihash.bytes,t);if(typeof t=="string")return ur(t).equals(this);if(t?.multihash?.bytes!=null)return xt(this.multihash.bytes,t.multihash.bytes);throw new Error("not valid Id")}[Al](){return`PeerId(${this.toString()})`}},Pr=class extends wn{type="RSA";publicKey;constructor(t){super({...t,type:"RSA"}),this.publicKey=t.publicKey}},Or=class extends wn{type="Ed25519";publicKey;constructor(t){super({...t,type:"Ed25519"}),this.publicKey=t.multihash.digest}},Mr=class extends wn{type="secp256k1";publicKey;constructor(t){super({...t,type:"secp256k1"}),this.publicKey=t.multihash.digest}},Ti=2336,Ni=class{type="url";multihash;privateKey;publicKey;url;constructor(t){this.url=t.toString(),this.multihash=Be.digest(Y(this.url))}[Al](){return`PeerId(${this.url})`}[ro]=!0;toString(){return this.toCID().toString()}toCID(){return zt.createV1(Ti,this.multihash)}toBytes(){return this.toCID().bytes}equals(t){return t==null?!1:(t instanceof Uint8Array&&(t=G(t)),t.toString()===this.toString())}};function ur(r,t){if(t=t??vl,r.charAt(0)==="1"||r.charAt(0)==="Q"){let e=$e(dt.decode(`z${r}`));return r.startsWith("12D")?new Or({multihash:e}):r.startsWith("16U")?new Mr({multihash:e}):new Pr({multihash:e})}return Ap(vl.decode(r))}function Ap(r){try{let t=$e(r);if(t.code===Be.code){if(t.digest.length===Li)return new Or({multihash:t});if(t.digest.length===Di)return new Mr({multihash:t})}if(t.code===kt.code)return new Pr({multihash:t})}catch{return Sp(zt.decode(r))}throw new Error("Supplied PeerID CID is invalid")}function Sp(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Sl&&r.code!==Ti)throw new Error("Supplied PeerID CID is invalid");if(r.code===Ti){let e=G(r.multihash.digest);return new Ni(new URL(e))}let t=r.multihash;if(t.code===kt.code)return new Pr({multihash:r.multihash});if(t.code===Be.code){if(t.digest.length===Li)return new Or({multihash:r.multihash});if(t.digest.length===Di)return new Mr({multihash:r.multihash})}throw new Error("Supplied PeerID CID is invalid")}async function Ui(r,t){return r.length===Li?new Or({multihash:$t(Be.code,r),privateKey:t}):r.length===Di?new Mr({multihash:$t(Be.code,r),privateKey:t}):new Pr({multihash:await kt.digest(r),publicKey:r,privateKey:t})}var Ip=Math.pow(2,7),_p=Math.pow(2,14),kp=Math.pow(2,21),Pi=Math.pow(2,28),Oi=Math.pow(2,35),Mi=Math.pow(2,42),Hi=Math.pow(2,49),tt=128,Lt=127;function gt(r){if(r<Ip)return 1;if(r<_p)return 2;if(r<kp)return 3;if(r<Pi)return 4;if(r<Oi)return 5;if(r<Mi)return 6;if(r<Hi)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Vi(r,t,e=0){switch(gt(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 Rp(r,t,e=0){switch(gt(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 Fi(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)*Pi,e<tt)||(e=r[t+5],n+=(e&Lt)*Oi,e<tt)||(e=r[t+6],n+=(e&Lt)*Mi,e<tt)||(e=r[t+7],n+=(e&Lt)*Hi,e<tt))return n;throw new RangeError("Could not decode varint")}function Cp(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)*Pi,e<tt)||(e=r.get(t+5),n+=(e&Lt)*Oi,e<tt)||(e=r.get(t+6),n+=(e&Lt)*Mi,e<tt)||(e=r.get(t+7),n+=(e&Lt)*Hi,e<tt))return n;throw new RangeError("Could not decode varint")}function ge(r,t,e=0){return t==null&&(t=vt(gt(r))),t instanceof Uint8Array?Vi(r,t,e):Rp(r,t,e)}function ee(r,t=0){return r instanceof Uint8Array?Fi(r,t):Cp(r,t)}function yt(r,t){t==null&&(t=r.reduce((o,s)=>o+s.length,0));let e=vt(t),n=0;for(let o of r)e.set(o,n),n+=o.length;return e}var co=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 p=Number.parseInt(f,t);if(!Number.isNaN(p))return p});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 Bl=45,Np=15,Hr=new co;function Ki(r){if(!(r.length>Np))return Hr.new(r).parseWith(()=>Hr.readIPv4Addr())}function $i(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Bl))return Hr.new(r).parseWith(()=>Hr.readIPv6Addr())}function lo(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>Bl))return Hr.new(r).parseWith(()=>Hr.readIPAddr())}var xb=parseInt("0xFFFF",16),Eb=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function uo(r){return!!Ki(r)}function fo(r){return!!$i(r)}function ho(r){return!!lo(r)}var kl=uo,Op=fo,Wi=function(r){let t=0;if(r=r.toString().trim(),kl(r)){let e=new Uint8Array(t+4);return r.split(/\./g).forEach(n=>{e[t++]=parseInt(n,10)&255}),e}if(Op(r)){let e=r.split(":",8),n;for(n=0;n<e.length;n++){let s=kl(e[n]),i;s&&(i=Wi(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")},Rl=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 Vr={},Gi={},Hp=[[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"]];Hp.forEach(r=>{let t=Vp(...r);Gi[t.code]=t,Vr[t.name]=t});function Vp(r,t,e,n,o){return{code:r,size:t,name:e,resolvable:!!n,path:!!o}}function et(r){if(typeof r=="number"){if(Gi[r]!=null)return Gi[r];throw new Error(`no protocol with code: ${r}`)}else if(typeof r=="string"){if(Vr[r]!=null)return Vr[r];throw new Error(`no protocol with name: ${r}`)}throw new Error(`invalid protocol id type: ${typeof r}`)}var ox=et("ip4"),sx=et("ip6"),ix=et("ipcidr");function Yi(r,t){switch(et(r).code){case 4:case 41:return Kp(t);case 42:return ji(t);case 6:case 273:case 33:case 132:return Nl(t).toString();case 53:case 54:case 55:case 56:case 400:case 449:case 777:return ji(t);case 421:return qp(t);case 444:return Tl(t);case 445:return Tl(t);case 466:return Gp(t);case 481:return globalThis.encodeURIComponent(ji(t));default:return G(t,"base16")}}function Zi(r,t){switch(et(r).code){case 4:return Cl(t);case 41:return Cl(t);case 42:return zi(t);case 6:case 273:case 33:case 132:return Xi(parseInt(t,10));case 53:case 54:case 55:case 56:case 400:case 449:case 777:return zi(t);case 421:return $p(t);case 444:return zp(t);case 445:return jp(t);case 466:return Wp(t);case 481:return zi(globalThis.decodeURIComponent(t));default:return Y(t,"base16")}}var qi=Object.values(me).map(r=>r.decoder),Fp=function(){let r=qi[0].or(qi[1]);return qi.slice(2).forEach(t=>r=r.or(t)),r}();function Cl(r){if(!ho(r))throw new Error("invalid ip address");return Wi(r)}function Kp(r){let t=Rl(r,0,r.length);if(t==null)throw new Error("ipBuff is required");if(!ho(t))throw new Error("invalid ip address");return t}function Xi(r){let t=new ArrayBuffer(2);return new DataView(t).setUint16(0,r),new Uint8Array(t)}function Nl(r){return new DataView(r.buffer).getUint16(r.byteOffset)}function zi(r){let t=Y(r),e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function ji(r){let t=ee(r);if(r=r.slice(gt(t)),r.length!==t)throw new Error("inconsistent lengths");return G(r)}function $p(r){let t;r[0]==="Q"||r[0]==="1"?t=$e(dt.decode(`z${r}`)).bytes:t=zt.parse(r).multihash.bytes;let e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function Wp(r){let t=Fp.decode(r),e=Uint8Array.from(ge(t.length));return yt([e,t],e.length+t.length)}function Gp(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return"u"+G(e,"base64url")}function qp(r){let t=ee(r),e=r.slice(gt(t));if(e.length!==t)throw new Error("inconsistent lengths");return G(e,"base58btc")}function zp(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=Se.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=Xi(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=Se.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=Xi(n);return yt([e,o],e.length+o.length)}function Tl(r){let t=r.slice(0,r.length-2),e=r.slice(r.length-2),n=G(t,"base32"),o=Nl(e);return`${n}:${o}`}function Ll(r){r=Ji(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 Ul("invalid address: "+r);if(a.path===!0){n=Ji(o.slice(s).join("/")),t.push([a.code,Zi(a.code,n)]),e.push([a.code,n]);break}let c=Zi(a.code,o[s]);t.push([a.code,c]),e.push([a.code,Yi(a.code,c)])}return{string:Dl(e),bytes:ta(t),tuples:t,stringTuples:e,path:n}}function Qi(r){let t=[],e=[],n=null,o=0;for(;o<r.length;){let s=ee(r,o),i=gt(s),a=et(s),c=Yp(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 Ul("Invalid address Uint8Array: "+G(r,"base16"));t.push([s,l]);let u=Yi(s,l);if(e.push([s,u]),a.path===!0){n=u;break}}return{bytes:Uint8Array.from(r),string:Dl(e),tuples:t,stringTuples:e,path:n}}function Dl(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}),Ji(t.join("/"))}function ta(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 Yp(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+gt(e)}}function Ji(r){return"/"+r.trim().split("/").filter(t=>t).join("/")}function Ul(r){return new Error("Error parsing address: "+r)}var Zp=Symbol.for("nodejs.util.inspect.custom"),ea=Symbol.for("@multiformats/js-multiaddr/multiaddr"),Xp=[et("dns").code,et("dns4").code,et("dns6").code,et("dnsaddr").code],po=class r{bytes;#t;#e;#r;#n;[ea]=!0;constructor(t){t==null&&(t="");let e;if(t instanceof Uint8Array)e=Qi(t);else if(typeof t=="string"){if(t.length>0&&t.charAt(0)!=="/")throw new Error(`multiaddr "${t}" must start with a "/"`);e=Ll(t)}else if(Ol(t))e=Qi(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[g,m]of this.stringTuples())g===f.code&&(s=`%${m??""}`),Xp.includes(g)&&(e=i.name,o=443,n=`${m??""}${s}`,t=g===u.code?6:4),(g===i.code||g===a.code)&&(e=et(g).name,o=parseInt(m??"")),(g===c.code||g===l.code)&&(e=et(g).name,n=`${m??""}${s}`,t=g===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(ta(e.slice(0,n)));return this}getPeerId(){try{let t=[];this.stringTuples().forEach(([n,o])=>{n===Vr.p2p.code&&t.push([n,o]),n===Vr["p2p-circuit"].code&&(t=[])});let e=t.pop();if(e?.[1]!=null){let n=e[1];return n[0]==="Q"||n[0]==="1"?G(dt.decode(`z${n}`),"base58btc"):G(zt.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){return this.#n}equals(t){return xt(this.bytes,t.bytes)}async resolve(t){let e=this.protos().find(s=>s.resolvable);if(e==null)return[this];let n=Pl.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)}[Zp](){return`Multiaddr(${this.#t})`}};var Pl=new Map;function Ol(r){return!!r?.[ea]}function re(r){return new po(r)}var Jp=r=>r.toString().split("/").slice(1),xn=r=>({match:t=>t.length<1?!1:r(t[0])?t.slice(1):!1,pattern:"fn"}),X=r=>({match:t=>xn(e=>e===r).match(t),pattern:r}),yo=()=>({match:r=>xn(t=>typeof t=="string").match(r),pattern:"{string}"}),wo=()=>({match:r=>xn(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{dt.decode(`z${r[1]}`)}catch{return!1}else return!1;return r.slice(2)},pattern:"/p2p/{peerid}"}),mo=()=>({match:r=>{if(r.length<2||r[0]!=="certhash")return!1;try{bi.decode(r[1])}catch{return!1}return r.slice(2)},pattern:"/certhash/{certhash}"}),At=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=Jp(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 na=rt(X("dns4"),yo()),oa=rt(X("dns6"),yo()),sa=rt(X("dnsaddr"),yo()),Ml=rt(X("dns"),yo()),Ux=pt(na),Px=pt(oa),Ox=pt(sa),Mx=pt(jt(Ml,sa,na,oa)),Hl=rt(X("ip4"),xn(uo)),Vl=rt(X("ip6"),xn(fo)),Fl=jt(Hl,Vl),ye=jt(Fl,Ml,na,oa,sa),Hx=pt(ye),Vx=pt(Hl),Fx=pt(Vl),Kx=pt(Fl),ia=rt(ye,X("tcp"),wo()),En=rt(ye,X("udp"),wo()),$x=pt(ia),Wx=pt(En),aa=rt(En,X("quic")),bo=rt(En,X("quic-v1")),Qp=jt(aa,bo),Gx=pt(aa),qx=pt(bo),ra=jt(ye,ia,En,aa,bo),Kl=jt(rt(ra,X("ws"),At(Rt()))),zx=pt(Kl),$l=jt(rt(ra,X("wss"),At(Rt())),rt(ra,X("tls"),X("ws"),At(Rt()))),jx=pt($l),Wl=rt(En,X("webrtc-direct"),At(mo()),At(mo()),At(Rt())),Gl=pt(Wl),ql=rt(bo,X("webtransport"),At(mo()),At(mo()),At(Rt())),Yx=pt(ql),go=jt(Kl,$l,rt(ia,At(Rt())),rt(Qp,At(Rt())),rt(ye,At(Rt())),Wl,ql,Rt()),Zx=pt(go),tm=rt(go,X("p2p-circuit"),Rt()),Xx=pt(tm),em=jt(rt(go,X("p2p-circuit"),X("webrtc"),At(Rt())),rt(go,X("webrtc"),At(Rt())),X("webrtc")),zl=pt(em),rm=jt(rt(ye,X("tcp"),wo(),X("http"),At(Rt())),rt(ye,X("http"),At(Rt()))),Jx=pt(rm),nm=jt(rt(ye,X("tcp"),jt(rt(X("443"),X("http")),rt(wo(),X("https"))),At(Rt())),rt(ye,X("tls"),X("http"),At(Rt())),rt(ye,X("https"),At(Rt()))),Qx=pt(nm);var Wt;(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"})(Wt||(Wt={}));var We=class extends D{constructor(t,e){super(`WebRTC transport error: ${t}`,e??""),this.name="WebRTCTransportError"}};var ca=class extends We{constructor(t,e){super(`[stream: ${t}] data channel error: ${e}`,Wt.ERR_DATA_CHANNEL),this.name="WebRTC/DataChannelError"}};function pa(r,t){return new ca(r,t)}var la=class extends We{constructor(t){super(`There was a problem with the Multiaddr which was passed in: ${t}`,Wt.ERR_INVALID_MULTIADDR),this.name="WebRTC/InappropriateMultiaddrError"}};function xo(r){return new la(r)}var ua=class extends We{constructor(t){super(`There was a problem with a provided argument: ${t}`,Wt.ERR_INVALID_PARAMETERS),this.name="WebRTC/InvalidArgumentError"}};function vn(r){return new ua(r)}var fa=class extends We{constructor(t,e){super(`Invalid fingerprint "${t}" within ${e}`,Wt.ERR_INVALID_FINGERPRINT),this.name="WebRTC/InvalidFingerprintError"}};function ma(r,t){return new fa(r,t)}var ha=class extends We{constructor(t){super(`A method (${t}) was called though it has been intentionally left unimplemented.`,Wt.ERR_NOT_IMPLEMENTED),this.name="WebRTC/UnimplementedError"}};function jl(r){return new ha(r)}var da=class extends We{constructor(t){super(`unsupported hash algorithm code: ${t} please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv `,Wt.ERR_HASH_NOT_SUPPORTED),this.name="WebRTC/UnsupportedHashAlgorithmError"}};function Yl(r){return new da(r)}var Zl=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))},om=function(){function r(t,e,n){this.name=t,this.version=e,this.os=n,this.type="browser"}return r}();var sm=function(){function r(t){this.version=t,this.type="node",this.name="node",this.os=process.platform}return r}();var im=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 am=function(){function r(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return r}();var cm=function(){function r(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return r}();var lm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,um=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Xl=3,fm=[["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",lm]],Jl=[["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 tu(r){return r?Ql(r):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new cm:typeof navigator<"u"?Ql(navigator.userAgent):pm()}function hm(r){return r!==""&&fm.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 Ql(r){var t=hm(r);if(!t)return null;var e=t[0],n=t[1];if(e==="searchbot")return new am;var o=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);o?o.length<Xl&&(o=Zl(Zl([],o,!0),mm(Xl-o.length),!0)):o=[];var s=o.join("."),i=dm(r),a=um.exec(r);return a&&a[1]?new im(e,s,i,a[1]):new om(e,s,i)}function dm(r){for(var t=0,e=Jl.length;t<e;t++){var n=Jl[t],o=n[0],s=n[1],i=s.exec(r);if(i)return o}return null}function pm(){var r=typeof process<"u"&&process.version;return r?new sm(process.version.slice(1)):null}function mm(r){for(var t=[],e=0;e<r;e++)t.push("0");return t}function ft(){let r={};return r.promise=new Promise((t,e)=>{r.resolve=t,r.reject=e}),r}var Fr=class extends Error{constructor(t){super(t),this.name="TimeoutError"}},ga=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}},eu=r=>globalThis.DOMException===void 0?new ga(r):new DOMException(r),ru=r=>{let t=r.reason===void 0?eu("This operation was aborted."):r.reason;return t instanceof Error?t:eu(t)};function fr(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:p}=t;p.aborted&&u(ru(p)),p.addEventListener("abort",()=>{u(ru(p))})}if(e===Number.POSITIVE_INFINITY){r.then(l,u);return}let f=new Fr;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(p){u(p)}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(p){u(p)}})()}).finally(()=>{c.clear()});return c.clear=()=>{s.clearTimeout.call(void 0,i),i=void 0},c}var nu=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"];var ou=tu(),An=ou!=null&&ou.name==="firefox",Eo=async function*(){},vo=async r=>{},gm=30*1e3;function su(r,t,e=gm,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=ft(),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 fr(o.promise,{milliseconds:e})}}).then(async()=>{r.readyState==="open"&&r.close()}).catch(o=>{n.log.error("error closing outbound stream",o)})}async function Sn(r){return r=r??{},typeof r=="function"&&(r=await r()),r.iceServers=r.iceServers??nu.map(t=>({urls:[t]})),r}var hr=class{log;peerConnection;remoteAddr;timeline;metrics;source=Eo();sink=vo;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 Ao=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}},Kr=class{size;hwm;head;tail;constructor(t={}){this.hwm=t.splitLimit??16,this.head=new Ao(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 Ao(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 ya=class extends Error{type;code;constructor(t,e){super(t??"The operation was aborted"),this.type="aborted",this.code=e??"ABORT_ERR"}};function Ge(r={}){return ym(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 ym(r,t){t=t??{};let e=t.onEnd,n=new Kr,o,s,i,a=ft(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((d,x)=>{s=w=>{s=null,n.push(w);try{d(r(n))}catch(b){x(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ft()})}},l=d=>s!=null?s(d):(n.push(d),o),u=d=>(n=new Kr,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})},p=d=>i?o:(i=!0,d!=null?u(d):l({done:!0})),g=()=>(n=new Kr,p(),{done:!0}),m=d=>(p(d),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:g,throw:m,push:f,end:p,get readableLength(){return n.size},onEmpty:async d=>{let x=d?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let w,b;x!=null&&(w=new Promise((I,C)=>{b=()=>{C(new ya)},x.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&x!=null&&x?.removeEventListener("abort",b)}}},e==null)return o;let h=o;return o={[Symbol.asyncIterator](){return this},next(){return h.next()},throw(d){return h.throw(d),e!=null&&(e(d),e=void 0),{done:!0}},return(){return h.return(),e!=null&&(e(),e=void 0),{done:!0}},push:f,end(d){return h.end(d),e!=null&&(e(d),e=void 0),o},get readableLength(){return h.readableLength},onEmpty:d=>h.onEmpty(d)},o}var So=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 Ie(r,t,e){if(t==null)return r;if(t.aborted)return Promise.reject(new So(e?.errorMessage,e?.errorCode,e?.errorName));let n,o=new So(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 au=Symbol.for("@achingbrain/uint8arraylist");function iu(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 Bo(r){return!!r?.[au]}var at=class r{bufs;length;[au]=!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(Bo(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(Bo(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=iu(this.bufs,t);return e.buf[e.index]}set(t,e){let n=iu(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(Bo(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(!Bo(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 p=l;p>=0;p--){let g=this.get(f+p);if(n[p]!==g){u=Math.max(1,p-a[g]);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=vt(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=Et(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=Et(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=Et(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=vt(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=Et(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=Et(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=Et(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=Et(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=Et(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(!xt(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 cu(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 lu(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function uu(r,t){let e=cu(r).return?.();lu(e)&&e.catch(n=>{t.error("could not cause iterator to return",n)})}var wm="ERR_STREAM_RESET",bm="ERR_SINK_INVALID_STATE",xm=5e3;function wa(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Io=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=ft(),this.closed=ft(),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??xm,this.onEnd=t.onEnd,this.onCloseRead=t?.onCloseRead,this.onCloseWrite=t?.onCloseWrite,this.onReset=t?.onReset,this.onAbort=t?.onAbort,this.source=this.streamSource=Ge({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"`,bm);try{this.writeStatus="writing";let e={signal:this.sinkController.signal};if(this.direction==="outbound"){let o=this.sendNewStream(e);wa(o)&&await o}let n=()=>{uu(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 at(o):o;let s=this.sendData(o,e);wa(s)&&(this.sendingData=ft(),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 Ie(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 Ie(this.sink([]),t.signal)),this.writeStatus==="writing"&&(this.sendingData!=null&&await Ie(this.sendingData.promise,t.signal),this.log.trace("aborting source passed to .sink"),this.sinkController.abort(),await Ie(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();wa(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",wm);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 _o(r){return r[Symbol.asyncIterator]!=null}var ko=r=>{let t=gt(r),e=vt(t);return ge(r,e),ko.bytes=t,e};ko.bytes=0;function Bn(r,t){t=t??{};let e=t.lengthEncoder??ko;function*n(o){let s=e(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return _o(r)?async function*(){for await(let o of r)yield*n(o)}():function*(){for(let o of r)yield*n(o)}()}Bn.single=(r,t)=>{t=t??{};let e=t.lengthEncoder??ko;return new at(e(r.byteLength),r)};var Ro=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Co=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},To=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},In=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Em=8,vm=1024*1024*4,dr;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(dr||(dr={}));var ba=r=>{let t=ee(r);return ba.bytes=gt(t),t};ba.bytes=0;function pr(r,t){let e=new at,n=dr.LENGTH,o=-1,s=t?.lengthDecoder??ba,i=t?.maxLengthLength??Em,a=t?.maxDataLength??vm;function*c(){for(;e.byteLength>0;){if(n===dr.LENGTH)try{if(o=s(e),o<0)throw new Ro("Invalid message length");if(o>a)throw new Co("Message length too long");let l=s.bytes;e.consume(l),t?.onLength!=null&&t.onLength(o),n=dr.DATA}catch(l){if(l instanceof RangeError){if(e.byteLength>i)throw new To("Message length length too long");break}throw l}if(n===dr.DATA){if(e.byteLength<o)break;let l=e.sublist(0,o);e.consume(o),t?.onData!=null&&t.onData(l),yield l,n=dr.LENGTH}}}return _o(r)?async function*(){for await(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new In("Unexpected end of input")}():function*(){for(let l of r)e.append(l),yield*c();if(e.byteLength>0)throw new In("Unexpected end of input")}()}pr.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 pr(n,{...t??{},onLength:s=>{e=s}})};var Sm=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 Bm(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}=Sm(r),f=(...g)=>{let m=e.multiArgs?g:g[0];e.filter&&!e.filter(m)||(c.push(m),e.count===c.length&&(n(),s(c)))},p=g=>{n(),i(g)};n=()=>{for(let g of a)u(g,f);for(let g of e.rejectionEvents)u(g,p)};for(let g of a)l(g,f);for(let g of e.rejectionEvents)l(g,p);e.signal&&e.signal.addEventListener("abort",()=>{p(e.signal.reason)},{once:!0}),e.resolveImmediately&&s(c)});if(o.cancel=n,typeof e.timeout=="number"){let s=fr(o,{milliseconds:e.timeout});return s.cancel=n,s}return o}function xa(r,t,e){typeof e=="function"&&(e={filter:e}),e={...e,count:1,resolveImmediately:!1};let n=Bm(r,t,e),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Ea=new Float32Array([-0]),qe=new Uint8Array(Ea.buffer);function fu(r,t,e){Ea[0]=r,t[e]=qe[0],t[e+1]=qe[1],t[e+2]=qe[2],t[e+3]=qe[3]}function hu(r,t){return qe[0]=r[t],qe[1]=r[t+1],qe[2]=r[t+2],qe[3]=r[t+3],Ea[0]}var va=new Float64Array([-0]),Dt=new Uint8Array(va.buffer);function du(r,t,e){va[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 pu(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],va[0]}var Im=BigInt(Number.MAX_SAFE_INTEGER),_m=BigInt(Number.MIN_SAFE_INTEGER),Gt=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 mr;if(t<Im&&t>_m)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>mu&&(o=0n,++n>mu&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(t){if(t===0)return mr;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):mr}},mr=new Gt(0,0);mr.toBigInt=function(){return 0n};mr.zzEncode=mr.zzDecode=function(){return this};mr.length=function(){return 1};var mu=4294967296n;function gu(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 yu(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 Aa(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 No(r,t){return(r[t-4]|r[t-3]<<8|r[t-2]<<16|r[t-1]<<24)>>>0}var Sa=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 No(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ne(this,4);return No(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ne(this,4);let t=hu(this.buf,this.pos);return this.pos+=4,t}double(){if(this.pos+8>this.len)throw ne(this,4);let t=pu(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 yu(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 Gt(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=No(this.buf,this.pos+=4),e=No(this.buf,this.pos+=4);return new Gt(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=Fi(this.buf,this.pos);return this.pos+=gt(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 Ba(r){return new Sa(r instanceof Uint8Array?r:r.subarray())}function oe(r,t,e){let n=Ba(r);return t.decode(n,void 0,e)}function Ia(r){let t=r??8192,e=t>>>1,n,o=t;return function(i){if(i<1||i>e)return vt(i);o+i>t&&(n=vt(t),o=0);let a=n.subarray(o,o+=i);return o&7&&(o=(o|7)+1),a}}var gr=class{fn;len;next;val;constructor(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}};function _a(){}var Ra=class{head;tail;len;next;constructor(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}},km=Ia();function Rm(r){return globalThis.Buffer!=null?vt(r):km(r)}var kn=class{len;head;tail;states;constructor(){this.len=0,this.head=new gr(_a,0,0),this.tail=this.head,this.states=null}_push(t,e,n){return this.tail=this.tail.next=new gr(t,e,n),this.len+=e,this}uint32(t){return this.len+=(this.tail=this.tail.next=new Ca((t=t>>>0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this}int32(t){return t<0?this._push(Lo,10,Gt.fromNumber(t)):this.uint32(t)}sint32(t){return this.uint32((t<<1^t>>31)>>>0)}uint64(t){let e=Gt.fromBigInt(t);return this._push(Lo,e.length(),e)}uint64Number(t){return this._push(Vi,gt(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=Gt.fromBigInt(t).zzEncode();return this._push(Lo,e.length(),e)}sint64Number(t){let e=Gt.fromNumber(t).zzEncode();return this._push(Lo,e.length(),e)}sint64String(t){return this.sint64(BigInt(t))}bool(t){return this._push(ka,1,t?1:0)}fixed32(t){return this._push(_n,4,t>>>0)}sfixed32(t){return this.fixed32(t)}fixed64(t){let e=Gt.fromBigInt(t);return this._push(_n,4,e.lo)._push(_n,4,e.hi)}fixed64Number(t){let e=Gt.fromNumber(t);return this._push(_n,4,e.lo)._push(_n,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(fu,4,t)}double(t){return this._push(du,8,t)}bytes(t){let e=t.length>>>0;return e===0?this._push(ka,1,0):this.uint32(e)._push(Tm,e,t)}string(t){let e=gu(t);return e!==0?this.uint32(e)._push(Aa,e,t):this._push(ka,1,0)}fork(){return this.states=new Ra(this),this.head=this.tail=new gr(_a,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new gr(_a,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=Rm(this.len),n=0;for(;t!=null;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e}};function ka(r,t,e){t[e]=r&255}function Cm(r,t,e){for(;r>127;)t[e++]=r&127|128,r>>>=7;t[e]=r}var Ca=class extends gr{next;constructor(t,e){super(Cm,t,e),this.next=void 0}};function Lo(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 _n(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 Tm(r,t,e){t.set(r,e)}globalThis.Buffer!=null&&(kn.prototype.bytes=function(r){let t=r.length>>>0;return this.uint32(t),t>0&&this._push(Nm,t,r),this},kn.prototype.string=function(r){let t=globalThis.Buffer.byteLength(r);return this.uint32(t),t>0&&this._push(Lm,t,r),this});function Nm(r,t,e){t.set(r,e)}function Lm(r,t,e){r.length<40?Aa(r,t,e):t.utf8Write!=null?t.utf8Write(r,e):t.set(Y(r),e)}function Ta(){return new kn}function se(r,t){let e=Ta();return t.encode(r,e,{lengthDelimited:!1}),e.finish()}var $r;(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"})($r||($r={}));function Do(r,t,e,n){return{name:r,type:t,encode:e,decode:n}}function yr(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 Do("enum",$r.VARINT,e,n)}function ie(r,t){return Do("message",$r.LENGTH_DELIMITED,r,t)}var Mt;(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=()=>yr(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())})(Mt||(Mt={}));var Dm=2*1024*1024,Um=30*1e3,Pm=7,Om=2,Mm=256*1024,Hm=5e3,Vm=5e3,Na=class extends Io{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 fr(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=Ge(),this.bufferedAmountLowEventTimeout=t.bufferedAmountLowEventTimeout??Um,this.maxBufferedAmount=t.maxBufferedAmount??Dm,this.maxMessageSize=(t.maxMessageSize??Mm)-Pm-Om,this.receiveFinAck=ft(),this.finAckTimeout=t.closeTimeout??Hm,this.openTimeout=t.openTimeout??Vm,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 pr(this.incomingData)){let s=n.processIncomingProtobuf(o);s!=null&&n.sourcePush(new at(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 xa(this.channel,"bufferedamountlow",{timeout:this.bufferedAmountLowEventTimeout})}catch(n){throw n instanceof Fr?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 xa(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=Mt.encode({message:n}),s=Bn.single(o);await this._sendMessage(s),t.consume(e)}}async sendReset(){await this._sendFlag(Mt.Flag.RESET)}async sendCloseWrite(t){if(await this._sendFlag(Mt.Flag.FIN)){this.log.trace("awaiting FIN_ACK");try{await Ie(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(Mt.Flag.STOP_SENDING)}processIncomingProtobuf(t){let e=Mt.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===Mt.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Mt.Flag.FIN_ACK).catch(n=>{this.log.error("error sending FIN_ACK immediately",n)})),e.flag===Mt.Flag.RESET&&this.reset(),e.flag===Mt.Flag.STOP_SENDING&&this.remoteCloseRead(),e.flag===Mt.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=Mt.encode({flag:t}),n=Bn.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 Wr(r){let{channel:t,direction:e}=r;return new Na({id:e==="inbound"?`i${t.id}`:`r${t.id}`,log:r.logger.forComponent(`libp2p:webrtc:stream:${e}:${t.id}`),...r})}var bu="/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??bu,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=Wr({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 La(this.components,{...t,peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol})}},La=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??bu,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=Wr({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),su(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=Eo();sink=vo;newStream(){let t=this.peerConnection.createDataChannel("");this.log.trace("opened outgoing datachannel with channel id %s",t.id);let e=Wr({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 wr=globalThis.RTCPeerConnection,Uo=globalThis.RTCSessionDescription,xu=globalThis.RTCIceCandidate;var Da=class{readNext;haveNext;ended;nextResult;constructor(){this.ended=!1,this.readNext=ft(),this.haveNext=ft()}[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=ft(),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=ft(),await Ie(this.readNext.promise,e?.signal,e)}};function Eu(){return new Da}var Po=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};var Ua=class extends Error{code;constructor(t,e){super(t),this.code=e}},Pa=class extends Ua{type;constructor(t){super(t,"ABORT_ERR"),this.type="aborted",this.name="AbortError"}};function vu(r,t){let e=Eu();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 at;return{read:async(i,a)=>{a?.signal?.throwIfAborted();let c,l=new Promise((u,f)=>{c=()=>{f(new Pa("Read aborted"))},a?.signal?.addEventListener("abort",c)});try{if(i==null){let{done:f,value:p}=await Promise.race([n.next(),l]);return f===!0?new at:p}for(;o.byteLength<i;){let{value:f,done:p}=await Promise.race([n.next(),l]);if(p===!0)throw new Po("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 Oo=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Mo=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ho=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Rn(r,t={}){let e=vu(r,t);t.maxDataLength!=null&&t.maxLengthLength==null&&(t.maxLengthLength=gt(t.maxDataLength));let n=t?.lengthDecoder??ee,o=t?.lengthEncoder??ge;return{read:async i=>{let a=-1,c=new at;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 Oo("Invalid message length");if(t?.maxLengthLength!=null&&c.byteLength>t.maxLengthLength)throw new Ho("message length length too long");if(a>-1)break}if(t?.maxDataLength!=null&&a>t.maxDataLength)throw new Mo("message length too long");return e.read(a,i)},write:async(i,a)=>{await e.write(new at(o(i.byteLength),i),a)},writeV:async(i,a)=>{let c=new at(...i.flatMap(l=>[o(l.byteLength),l]));await e.write(c,a)},unwrap:()=>e.unwrap()}}function Vo(r,t){let e=Rn(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 Ht;(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=()=>yr(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())})(Ht||(Ht={}));var Fo=async(r,t,e)=>{try{let n=ft();for(Km(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!==Ht.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 qt("webrtc:end-of-ice-candidates")),e.log.trace("end-of-candidates received");continue}let i=new xu(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)throw n}};function Fm(r){return An?r.iceConnectionState:r.connectionState}function Km(r,t){r[An?"oniceconnectionstatechange":"onconnectionstatechange"]=e=>{switch(Fm(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 Au({rtcConfiguration:r,dataChannel:t,signal:e,metrics:n,multiaddr:o,connectionManager:s,transportManager:i,log:a,logger:c,onProgress:l}){let{baseAddr:u}=Su(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 p=s.getConnections(ur(f)),g,m=!1;p.length===0?(l?.(new qt("webrtc:dial-relay")),g=await i.dial(u,{signal:e,onProgress:l}),m=!0):(l?.(new qt("webrtc:reuse-relay-connection")),g=p[0]);try{l?.(new qt("webrtc:open-signaling-stream"));let h=await g.newStream(Ko,{signal:e,runOnTransientConnection:!0}),d=Vo(h).pb(Ht),x=new wr(r),w=new ze({logger:c},{peerConnection:x,dataChannelOptions:t});try{let b=x.createDataChannel("init");x.onicecandidate=({candidate:B})=>{let _=JSON.stringify(B?.toJSON()??null);a.trace("initiator sending ICE candidate %o",B),d.write({type:Ht.Type.ICE_CANDIDATE,data:_},{signal:e}).catch(P=>{a.error("error sending ICE candidate",P)})},x.onicecandidateerror=B=>{a.error("initiator ICE candidate error",B)};let I=await x.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",I.sdp),l?.(new qt("webrtc:send-sdp-offer")),await d.write({type:Ht.Type.SDP_OFFER,data:I.sdp},{signal:e}),await x.setLocalDescription(I).catch(B=>{throw a.error("could not execute setLocalDescription",B),new D("Failed to set localDescription","ERR_SDP_HANDSHAKE_FAILED")}),l?.(new qt("webrtc:read-sdp-answer"));let C=await d.read({signal:e});if(C.type!==Ht.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 S=new Uo({type:"answer",sdp:C.data});return await x.setRemoteDescription(S).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 qt("webrtc:read-ice-candidates")),await Fo(x,d,{direction:"initiator",signal:e,log:a,onProgress:l}),a.trace("initiator connected, closing init channel"),b.close(),l?.(new qt("webrtc:close-signaling-stream")),a.trace("closing signaling channel"),await h.close({signal:e}),a.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:x,muxerFactory:w}}catch(b){throw a.error("outgoing signaling error",b),x.close(),h.abort(b),b}finally{x.onicecandidate=null,x.onicecandidateerror=null}}finally{if(m)try{await g.close({signal:e})}catch(h){g.abort(h)}}}var $m=U("dns4"),Wm=U("dns6"),Gm=U("dnsaddr"),br=mt(U("dns"),Gm,$m,Wm),Go=mt(U("ip4"),U("ip6")),Gr=mt(K(Go,U("tcp")),K(br,U("tcp"))),qo=K(Go,U("udp")),qm=K(qo,U("utp")),zm=K(qo,U("quic")),jm=K(qo,U("quic-v1")),Oa=mt(K(Gr,U("ws")),K(br,U("ws"))),$o=mt(K(Oa,U("p2p")),Oa),Ma=mt(K(Gr,U("wss")),K(br,U("wss")),K(Gr,U("tls"),U("ws")),K(br,U("tls"),U("ws"))),Wo=mt(K(Ma,U("p2p")),Ma),Ha=mt(K(Gr,U("http")),K(Go,U("http")),K(br,U("http"))),Va=mt(K(Gr,U("https")),K(Go,U("https")),K(br,U("https"))),Bu=K(qo,U("webrtc-direct"),U("certhash")),ku=mt(K(Bu,U("p2p")),Bu),Iu=K(jm,U("webtransport"),U("certhash"),U("certhash")),Ru=mt(K(Iu,U("p2p")),Iu),Cu=mt(K($o,U("p2p-webrtc-star"),U("p2p")),K(Wo,U("p2p-webrtc-star"),U("p2p")),K($o,U("p2p-webrtc-star")),K(Wo,U("p2p-webrtc-star"))),I2=mt(K($o,U("p2p-websocket-star"),U("p2p")),K(Wo,U("p2p-websocket-star"),U("p2p")),K($o,U("p2p-websocket-star")),K(Wo,U("p2p-websocket-star"))),Tu=mt(K(Ha,U("p2p-webrtc-direct"),U("p2p")),K(Va,U("p2p-webrtc-direct"),U("p2p")),K(Ha,U("p2p-webrtc-direct")),K(Va,U("p2p-webrtc-direct"))),xr=mt(Oa,Ma,Ha,Va,Cu,Tu,Gr,qm,zm,br,ku,Ru),_2=mt(K(xr,U("p2p-stardust"),U("p2p")),K(xr,U("p2p-stardust"))),je=mt(K(xr,U("p2p")),Cu,Tu,ku,Ru,U("p2p")),_u=mt(K(je,U("p2p-circuit"),je),K(je,U("p2p-circuit")),K(U("p2p-circuit"),je),K(xr,U("p2p-circuit")),K(U("p2p-circuit"),xr),U("p2p-circuit")),Nu=()=>mt(K(_u,Nu),_u),_e=Nu(),k2=mt(K(_e,je,_e),K(je,_e),K(_e,je),_e,je);var R2=mt(K(_e,U("webrtc"),U("p2p")),K(_e,U("webrtc")),K(xr,U("webrtc"),U("p2p")),K(xr,U("webrtc")),U("webrtc"));function Lu(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:Lu(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:Lu(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 zo=class extends so{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=>_e.matches(e)).map(e=>e.encapsulate(`/webrtc/p2p/${this.peerId}`))).flat()}async close(){this.shutdownController.abort(),this.safeDispatchEvent("close",{})}};async function Du({peerConnection:r,stream:t,signal:e,connection:n,log:o}){o.trace("new inbound signaling stream");let s=Vo(t).pb(Ht);try{r.onicecandidate=({candidate:u})=>{let f=JSON.stringify(u?.toJSON()??null);o.trace("recipient sending ICE candidate %s",f),s.write({type:Ht.Type.ICE_CANDIDATE,data:f},{signal:e}).catch(p=>{o.error("error sending ICE candidate",p)})};let a=await s.read({signal:e});if(a.type!==Ht.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 Uo({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:Ht.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 Fo(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 Ym="/webrtc",Zm="/p2p-circuit",Ko="/webrtc-signaling/0.0.1",Xm=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,oo(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"})})}[no]=!0;[Symbol.toStringTag]="@libp2p/webrtc";[Nr]=["@libp2p/transport"];[rl]=["@libp2p/identify","@libp2p/circuit-relay-v2-transport"];isStarted(){return this._started}async start(){await this.components.registrar.handle(Ko,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(Ko),this._started=!1}createListener(t){return new zo(this.components,{shutdownController:this.shutdownController})}listenFilter(t){return t.filter(zl.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 Au({rtcConfiguration:await Sn(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 hr(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??Xm),o=new wr(await Sn(this.init.rtcConfiguration)),s=new ze(this.components,{peerConnection:o,dataChannelOptions:this.init.dataChannel});try{let{remoteAddress:i}=await Du({peerConnection:o,connection:t,stream:e,signal:n,log:this.log});await e.close({signal:n});let a=new hr(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 Su(r){let t=r.toString().split(Ym+"/");if(t.length!==2)throw new D("webrtc protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);if(!t[0].includes(Zm))throw new D("p2p-circuit protocol was not present in multiaddr",Wt.ERR_INVALID_MULTIADDR);let e=re(t[0]),o=re("/"+t[1]).getPeerId();if(o==null)throw new D("destination peer id was missing",Wt.ERR_INVALID_MULTIADDR);let s=e.protos().pop();if(s===void 0)throw new D("invalid multiaddr",Wt.ERR_INVALID_MULTIADDR);return s.name!=="p2p"&&(e=e.encapsulate(`/p2p/${o}`)),{baseAddr:e,peerId:ur(o)}}var sc={};bt(sc,{Ed25519PrivateKey:()=>Ir,Ed25519PublicKey:()=>Pn,generateKeyPair:()=>ag,generateKeyPairFromSeed:()=>uf,unmarshalEd25519PrivateKey:()=>sg,unmarshalEd25519PublicKey:()=>ig});function Yt(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}function Ye(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Jm(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function qr(r,...t){if(!Jm(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 Er(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Ye(r.outputLen),Ye(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 Uu(r,t){qr(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Yo=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Yr=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),ae=(r,t)=>r<<32-t|r>>>t;var av=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Qm=async()=>{};async function Pu(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 Qm(),n+=s)}}function Ou(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=Ou(r)),qr(r),r}function Fa(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];qr(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 jr=class{clone(){return this._cloneInto()}},t0={}.toString;function Mu(r,t){if(t!==void 0&&t0.call(t)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(r,t)}function Zo(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 vr(r=32){if(Yo&&typeof Yo.getRandomValues=="function")return Yo.getRandomValues(new Uint8Array(r));throw new Error("crypto.getRandomValues must be defined")}function e0(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 Hu=(r,t,e)=>r&t^~r&e,Vu=(r,t,e)=>r&t^r&e^t&e,Zr=class extends jr{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=Yr(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=Yr(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),Uu(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;e0(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Yr(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 Xo=BigInt(4294967295),Ka=BigInt(32);function Fu(r,t=!1){return t?{h:Number(r&Xo),l:Number(r>>Ka&Xo)}:{h:Number(r>>Ka&Xo)|0,l:Number(r&Xo)|0}}function r0(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}=Fu(r[o],t);[e[o],n[o]]=[s,i]}return[e,n]}var n0=(r,t)=>BigInt(r>>>0)<<Ka|BigInt(t>>>0),o0=(r,t,e)=>r>>>e,s0=(r,t,e)=>r<<32-e|t>>>e,i0=(r,t,e)=>r>>>e|t<<32-e,a0=(r,t,e)=>r<<32-e|t>>>e,c0=(r,t,e)=>r<<64-e|t>>>e-32,l0=(r,t,e)=>r>>>e-32|t<<64-e,u0=(r,t)=>t,f0=(r,t)=>r,h0=(r,t,e)=>r<<e|t>>>32-e,d0=(r,t,e)=>t<<e|r>>>32-e,p0=(r,t,e)=>t<<e-32|r>>>64-e,m0=(r,t,e)=>r<<e-32|t>>>64-e;function g0(r,t,e,n){let o=(t>>>0)+(n>>>0);return{h:r+e+(o/2**32|0)|0,l:o|0}}var y0=(r,t,e)=>(r>>>0)+(t>>>0)+(e>>>0),w0=(r,t,e,n)=>t+e+n+(r/2**32|0)|0,b0=(r,t,e,n)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0),x0=(r,t,e,n,o)=>t+e+n+o+(r/2**32|0)|0,E0=(r,t,e,n,o)=>(r>>>0)+(t>>>0)+(e>>>0)+(n>>>0)+(o>>>0),v0=(r,t,e,n,o,s)=>t+e+n+o+s+(r/2**32|0)|0;var A0={fromBig:Fu,split:r0,toBig:n0,shrSH:o0,shrSL:s0,rotrSH:i0,rotrSL:a0,rotrBH:c0,rotrBL:l0,rotr32H:u0,rotr32L:f0,rotlSH:h0,rotlSL:d0,rotlBH:p0,rotlBL:m0,add:g0,add3L:y0,add3H:w0,add4L:b0,add4H:x0,add5H:v0,add5L:E0},z=A0;var[S0,B0]=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))),Ze=new Uint32Array(80),Xe=new Uint32Array(80),$a=class extends Zr{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:p,Gh:g,Gl:m,Hh:h,Hl:d}=this;return[t,e,n,o,s,i,a,c,l,u,f,p,g,m,h,d]}set(t,e,n,o,s,i,a,c,l,u,f,p,g,m,h,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=p|0,this.Gh=g|0,this.Gl=m|0,this.Hh=h|0,this.Hl=d|0}process(t,e){for(let b=0;b<16;b++,e+=4)Ze[b]=t.getUint32(e),Xe[b]=t.getUint32(e+=4);for(let b=16;b<80;b++){let I=Ze[b-15]|0,C=Xe[b-15]|0,S=z.rotrSH(I,C,1)^z.rotrSH(I,C,8)^z.shrSH(I,C,7),B=z.rotrSL(I,C,1)^z.rotrSL(I,C,8)^z.shrSL(I,C,7),_=Ze[b-2]|0,P=Xe[b-2]|0,N=z.rotrSH(_,P,19)^z.rotrBH(_,P,61)^z.shrSH(_,P,6),T=z.rotrSL(_,P,19)^z.rotrBL(_,P,61)^z.shrSL(_,P,6),F=z.add4L(B,T,Xe[b-7],Xe[b-16]),W=z.add4H(F,S,N,Ze[b-7],Ze[b-16]);Ze[b]=W|0,Xe[b]=F|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:p,Fh:g,Fl:m,Gh:h,Gl:d,Hh:x,Hl:w}=this;for(let b=0;b<80;b++){let I=z.rotrSH(f,p,14)^z.rotrSH(f,p,18)^z.rotrBH(f,p,41),C=z.rotrSL(f,p,14)^z.rotrSL(f,p,18)^z.rotrBL(f,p,41),S=f&g^~f&h,B=p&m^~p&d,_=z.add5L(w,C,B,B0[b],Xe[b]),P=z.add5H(_,x,I,S,S0[b],Ze[b]),N=_|0,T=z.rotrSH(n,o,28)^z.rotrBH(n,o,34)^z.rotrBH(n,o,39),F=z.rotrSL(n,o,28)^z.rotrBL(n,o,34)^z.rotrBL(n,o,39),W=n&s^n&a^s&a,R=o&i^o&c^i&c;x=h|0,w=d|0,h=g|0,d=m|0,g=f|0,m=p|0,{h:f,l:p}=z.add(l|0,u|0,P|0,N|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=z.add3L(N,F,R);n=z.add3H(E,P,T,W),o=E|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:p}=z.add(this.Eh|0,this.El|0,f|0,p|0),{h:g,l:m}=z.add(this.Fh|0,this.Fl|0,g|0,m|0),{h,l:d}=z.add(this.Gh|0,this.Gl|0,h|0,d|0),{h:x,l:w}=z.add(this.Hh|0,this.Hl|0,x|0,w|0),this.set(n,o,s,i,a,c,l,u,f,p,g,m,h,d,x,w)}roundClean(){Ze.fill(0),Xe.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 Cn=Zo(()=>new $a);var Qo={};bt(Qo,{aInRange:()=>Ct,abool:()=>le,abytes:()=>Xr,bitGet:()=>N0,bitLen:()=>T0,bitMask:()=>Nn,bitSet:()=>L0,bytesToHex:()=>Re,bytesToNumberBE:()=>Ce,bytesToNumberLE:()=>ue,concatBytes:()=>Ne,createHmacDrbg:()=>ja,ensureBytes:()=>st,equalBytes:()=>R0,hexToBytes:()=>Ar,hexToNumber:()=>za,inRange:()=>Tn,isBytes:()=>Je,memoized:()=>Sr,notImplemented:()=>U0,numberToBytesBE:()=>Qe,numberToBytesLE:()=>Te,numberToHexUnpadded:()=>Wu,numberToVarBytesBE:()=>k0,utf8ToBytes:()=>C0,validateObject:()=>Zt});var qa=BigInt(0),Jo=BigInt(1),I0=BigInt(2);function Je(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Xr(r){if(!Je(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 _0=Array.from({length:256},(r,t)=>t.toString(16).padStart(2,"0"));function Re(r){Xr(r);let t="";for(let e=0;e<r.length;e++)t+=_0[r[e]];return t}function Wu(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 ke={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Ku(r){if(r>=ke._0&&r<=ke._9)return r-ke._0;if(r>=ke._A&&r<=ke._F)return r-(ke._A-10);if(r>=ke._a&&r<=ke._f)return r-(ke._a-10)}function Ar(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=Ku(r.charCodeAt(s)),a=Ku(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(Re(r))}function ue(r){return Xr(r),za(Re(Uint8Array.from(r).reverse()))}function Qe(r,t){return Ar(r.toString(16).padStart(t*2,"0"))}function Te(r,t){return Qe(r,t).reverse()}function k0(r){return Ar(Wu(r))}function st(r,t,e){let n;if(typeof t=="string")try{n=Ar(t)}catch(s){throw new Error(`${r} must be valid hex string, got "${t}". Cause: ${s}`)}else if(Je(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 Ne(...r){let t=0;for(let n=0;n<r.length;n++){let o=r[n];Xr(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 R0(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 C0(r){if(typeof r!="string")throw new Error(`utf8ToBytes expected string, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}var Wa=r=>typeof r=="bigint"&&qa<=r;function Tn(r,t,e){return Wa(r)&&Wa(t)&&Wa(e)&&t<=r&&r<e}function Ct(r,t,e,n){if(!Tn(t,e,n))throw new Error(`expected valid ${r}: ${e} <= n < ${n}, got ${typeof t} ${t}`)}function T0(r){let t;for(t=0;r>qa;r>>=Jo,t+=1);return t}function N0(r,t){return r>>BigInt(t)&Jo}function L0(r,t,e){return r|(e?Jo:qa)<<BigInt(t)}var Nn=r=>(I0<<BigInt(r-1))-Jo,Ga=r=>new Uint8Array(r),$u=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=Ga(r),o=Ga(r),s=0,i=()=>{n.fill(1),o.fill(0),s=0},a=(...f)=>e(o,n,...f),c=(f=Ga())=>{o=a($u([0]),f),n=a(),f.length!==0&&(o=a($u([1]),f),n=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<t;){n=a();let g=n.slice();p.push(g),f+=n.length}return Ne(...p)};return(f,p)=>{i(),c(f);let g;for(;!(g=p(l()));)c();return i(),g}}var D0={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"||Je(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=D0[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 U0=()=>{throw new Error("not implemented")};function Sr(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 St=BigInt(0),ct=BigInt(1),Br=BigInt(2),P0=BigInt(3),Ya=BigInt(4),Gu=BigInt(5),qu=BigInt(8),O0=BigInt(9),M0=BigInt(16);function J(r,t){let e=r%t;return e>=St?e:t+e}function Za(r,t,e){if(e<=St||t<St)throw new Error("Expected power/modulo > 0");if(e===ct)return St;let n=ct;for(;t>St;)t&ct&&(n=n*r%e),r=r*r%e,t>>=ct;return n}function it(r,t,e){let n=r;for(;t-- >St;)n*=n,n%=e;return n}function ts(r,t){if(r===St||t<=St)throw new Error(`invert: expected positive integers, got n=${r} mod=${t}`);let e=J(r,t),n=t,o=St,s=ct,i=ct,a=St;for(;e!==St;){let l=n/e,u=n%e,f=o-i*l,p=s-a*l;n=e,e=u,o=i,s=a,i=f,a=p}if(n!==ct)throw new Error("invert: does not exist");return J(o,t)}function H0(r){let t=(r-ct)/Br,e,n,o;for(e=r-ct,n=0;e%Br===St;e/=Br,n++);for(o=Br;o<r&&Za(o,t,r)!==r-ct;o++);if(n===1){let i=(r+ct)/Ya;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+ct)/Br;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),p=a.pow(c,e);for(;!a.eql(p,a.ONE);){if(a.eql(p,a.ZERO))return a.ZERO;let g=1;for(let h=a.sqr(p);g<l&&!a.eql(h,a.ONE);g++)h=a.sqr(h);let m=a.pow(u,ct<<BigInt(l-g-1));u=a.sqr(m),f=a.mul(f,m),p=a.mul(p,u),l=g}return f}}function V0(r){if(r%Ya===P0){let t=(r+ct)/Ya;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%qu===Gu){let t=(r-Gu)/qu;return function(n,o){let s=n.mul(o,Br),i=n.pow(s,t),a=n.mul(o,i),c=n.mul(n.mul(a,Br),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%M0,H0(r)}var zu=(r,t)=>(J(r,t)&ct)===ct,F0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Xa(r){let t={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},e=F0.reduce((n,o)=>(n[o]="function",n),t);return Zt(r,e)}function K0(r,t,e){if(e<St)throw new Error("Expected power > 0");if(e===St)return r.ONE;if(e===ct)return t;let n=r.ONE,o=t;for(;e>St;)e&ct&&(n=r.mul(n,o)),o=r.sqr(o),e>>=ct;return n}function $0(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 Ja(r,t){let e=t!==void 0?t:r.toString(2).length,n=Math.ceil(e/8);return{nBitLength:e,nByteLength:n}}function es(r,t,e=!1,n={}){if(r<=St)throw new Error(`Expected Field ORDER > 0, got ${r}`);let{nBitLength:o,nByteLength:s}=Ja(r,t);if(s>2048)throw new Error("Field lengths over 2048 bytes are not supported");let i=V0(r),a=Object.freeze({ORDER:r,BITS:o,BYTES:s,MASK:Nn(o),ZERO:St,ONE:ct,create:c=>J(c,r),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return St<=c&&c<r},is0:c=>c===St,isOdd:c=>(c&ct)===ct,neg:c=>J(-c,r),eql:(c,l)=>c===l,sqr:c=>J(c*c,r),add:(c,l)=>J(c+l,r),sub:(c,l)=>J(c-l,r),mul:(c,l)=>J(c*l,r),pow:(c,l)=>K0(a,c,l),div:(c,l)=>J(c*ts(l,r),r),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ts(c,r),sqrt:n.sqrt||(c=>i(a,c)),invertBatch:c=>$0(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>e?Te(c,s):Qe(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 ju(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 Qa(r){let t=ju(r);return t+Math.ceil(t/2)}function Yu(r,t,e=!1){let n=r.length,o=ju(t),s=Qa(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=J(i,t-ct)+ct;return e?Te(a,o):Qe(a,o)}var G0=BigInt(0),tc=BigInt(1),ec=new WeakMap,Zu=new WeakMap;function rs(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>G0;)i&tc&&(a=a.add(c)),c=c.double(),i>>=tc;return a},precomputeWindow(s,i){let{windows:a,windowSize:c}=o(i),l=[],u=s,f=u;for(let p=0;p<a;p++){f=u,l.push(f);for(let g=1;g<c;g++)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,p=BigInt(2**s-1),g=2**s,m=BigInt(s);for(let h=0;h<c;h++){let d=h*l,x=Number(a&p);a>>=m,x>l&&(x-=g,a+=tc);let w=d,b=d+Math.abs(x)-1,I=h%2!==0,C=x<0;x===0?f=f.add(e(I,i[w])):u=u.add(e(C,i[b]))}return{p:u,f}},wNAFCached(s,i,a){let c=Zu.get(s)||1,l=ec.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&ec.set(s,a(l))),this.wNAF(c,l,i)},setWindowSize(s,i){n(i),Zu.set(s,i),ec.delete(s)}}}function Ln(r){return Xa(r.Fp),Zt(r,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ja(r.n,r.nBitLength),...r,p:r.Fp.ORDER})}var fe=BigInt(0),Vt=BigInt(1),ns=BigInt(2),q0=BigInt(8),z0={zip215:!0};function j0(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 Xu(r){let t=j0(r),{Fp:e,n,prehash:o,hash:s,randomBytes:i,nByteLength:a,h:c}=t,l=ns<<BigInt(a*8)-Vt,u=e.create,f=t.uvRatio||((E,y)=>{try{return{isValid:!0,value:e.sqrt(E*e.inv(y))}}catch{return{isValid:!1,value:fe}}}),p=t.adjustScalarBytes||(E=>E),g=t.domain||((E,y,A)=>{if(le("phflag",A),y.length||A)throw new Error("Contexts/pre-hash are not supported");return E});function m(E,y){Ct("coordinate "+E,y,fe,l)}function h(E){if(!(E instanceof w))throw new Error("ExtendedPoint expected")}let d=Sr((E,y)=>{let{ex:A,ey:k,ez:v}=E,L=E.is0();y==null&&(y=L?q0:e.inv(v));let M=u(A*y),V=u(k*y),$=u(v*y);if(L)return{x:fe,y:Vt};if($!==Vt)throw new Error("invZ was invalid");return{x:M,y:V}}),x=Sr(E=>{let{a:y,d:A}=t;if(E.is0())throw new Error("bad point: ZERO");let{ex:k,ey:v,ez:L,et:M}=E,V=u(k*k),$=u(v*v),q=u(L*L),Z=u(q*q),Q=u(V*y),ht=u(q*u(Q+$)),ot=u(Z+u(A*u(V*$)));if(ht!==ot)throw new Error("bad point: equation left != right (1)");let nt=u(k*v),Jt=u(L*M);if(nt!==Jt)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(y,A,k,v){this.ex=y,this.ey=A,this.ez=k,this.et=v,m("x",y),m("y",A),m("z",k),m("t",v),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof w)throw new Error("extended point not allowed");let{x:A,y:k}=y||{};return m("x",A),m("y",k),new w(A,k,Vt,u(A*k))}static normalizeZ(y){let A=e.invertBatch(y.map(k=>k.ez));return y.map((k,v)=>k.toAffine(A[v])).map(w.fromAffine)}_setWindowSize(y){C.setWindowSize(this,y)}assertValidity(){x(this)}equals(y){h(y);let{ex:A,ey:k,ez:v}=this,{ex:L,ey:M,ez:V}=y,$=u(A*V),q=u(L*v),Z=u(k*V),Q=u(M*v);return $===q&&Z===Q}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){let{a:y}=t,{ex:A,ey:k,ez:v}=this,L=u(A*A),M=u(k*k),V=u(ns*u(v*v)),$=u(y*L),q=A+k,Z=u(u(q*q)-L-M),Q=$+M,ht=Q-V,ot=$-M,nt=u(Z*ht),Jt=u(Q*ot),Bt=u(Z*ot),Qt=u(ht*Q);return new w(nt,Jt,Qt,Bt)}add(y){h(y);let{a:A,d:k}=t,{ex:v,ey:L,ez:M,et:V}=this,{ex:$,ey:q,ez:Z,et:Q}=y;if(A===BigInt(-1)){let qc=u((L-v)*(q+$)),zc=u((L+v)*(q-$)),ii=u(zc-qc);if(ii===fe)return this.double();let jc=u(M*ns*Q),Yc=u(V*ns*Z),Zc=Yc+jc,Xc=zc+qc,Jc=Yc-jc,id=u(Zc*ii),ad=u(Xc*Jc),cd=u(Zc*Jc),ld=u(ii*Xc);return new w(id,ad,ld,cd)}let ht=u(v*$),ot=u(L*q),nt=u(V*k*Q),Jt=u(M*Z),Bt=u((v+L)*($+q)-ht-ot),Qt=Jt-nt,cr=Jt+nt,pn=u(ot-A*ht),to=u(Bt*Qt),nd=u(cr*pn),od=u(Bt*pn),sd=u(Qt*cr);return new w(to,nd,sd,od)}subtract(y){return this.add(y.negate())}wNAF(y){return C.wNAFCached(this,y,w.normalizeZ)}multiply(y){let A=y;Ct("scalar",A,Vt,n);let{p:k,f:v}=this.wNAF(A);return w.normalizeZ([k,v])[0]}multiplyUnsafe(y){let A=y;return Ct("scalar",A,fe,n),A===fe?I:this.equals(I)||A===Vt?this:this.equals(b)?this.wNAF(A).p:C.unsafeLadder(this,A)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(y){return d(this,y)}clearCofactor(){let{h:y}=t;return y===Vt?this:this.multiplyUnsafe(y)}static fromHex(y,A=!1){let{d:k,a:v}=t,L=e.BYTES;y=st("pointHex",y,L),le("zip215",A);let M=y.slice(),V=y[L-1];M[L-1]=V&-129;let $=ue(M),q=A?l:e.ORDER;Ct("pointHex.y",$,fe,q);let Z=u($*$),Q=u(Z-Vt),ht=u(k*Z-v),{isValid:ot,value:nt}=f(Q,ht);if(!ot)throw new Error("Point.fromHex: invalid y coordinate");let Jt=(nt&Vt)===Vt,Bt=(V&128)!==0;if(!A&&nt===fe&&Bt)throw new Error("Point.fromHex: x=0 and x_0=1");return Bt!==Jt&&(nt=u(-nt)),w.fromAffine({x:nt,y:$})}static fromPrivateKey(y){return _(y).point}toRawBytes(){let{x:y,y:A}=this.toAffine(),k=Te(A,e.BYTES);return k[k.length-1]|=y&Vt?128:0,k}toHex(){return Re(this.toRawBytes())}}w.BASE=new w(t.Gx,t.Gy,Vt,u(t.Gx*t.Gy)),w.ZERO=new w(fe,Vt,Vt,fe);let{BASE:b,ZERO:I}=w,C=rs(w,a*8);function S(E){return J(E,n)}function B(E){return S(ue(E))}function _(E){let y=a;E=st("private key",E,y);let A=st("hashed private key",s(E),2*y),k=p(A.slice(0,y)),v=A.slice(y,2*y),L=B(k),M=b.multiply(L),V=M.toRawBytes();return{head:k,prefix:v,scalar:L,point:M,pointBytes:V}}function P(E){return _(E).pointBytes}function N(E=new Uint8Array,...y){let A=Ne(...y);return B(s(g(A,st("context",E),!!o)))}function T(E,y,A={}){E=st("message",E),o&&(E=o(E));let{prefix:k,scalar:v,pointBytes:L}=_(y),M=N(A.context,k,E),V=b.multiply(M).toRawBytes(),$=N(A.context,V,L,E),q=S(M+$*v);Ct("signature.s",q,fe,n);let Z=Ne(V,Te(q,e.BYTES));return st("result",Z,a*2)}let F=z0;function W(E,y,A,k=F){let{context:v,zip215:L}=k,M=e.BYTES;E=st("signature",E,2*M),y=st("message",y),L!==void 0&&le("zip215",L),o&&(y=o(y));let V=ue(E.slice(M,2*M)),$,q,Z;try{$=w.fromHex(A,L),q=w.fromHex(E.slice(0,M),L),Z=b.multiplyUnsafe(V)}catch{return!1}if(!L&&$.isSmallOrder())return!1;let Q=N(v,q.toRawBytes(),$.toRawBytes(),y);return q.add($.multiplyUnsafe(Q)).subtract(Z).clearCofactor().equals(w.ZERO)}return b._setWindowSize(8),{CURVE:t,getPublicKey:P,sign:T,verify:W,ExtendedPoint:w,utils:{getExtendedPublicKey:_,randomPrivateKey:()=>i(e.BYTES),precompute(E=8,y=w.BASE){return y._setWindowSize(E),y.multiply(BigInt(3)),y}}}}var Jr=BigInt(0),rc=BigInt(1);function Y0(r){return Zt(r,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...r})}function Ju(r){let t=Y0(r),{P:e}=t,n=w=>J(w,e),o=t.montgomeryBits,s=Math.ceil(o/8),i=t.nByteLength,a=t.adjustScalarBytes||(w=>w),c=t.powPminus2||(w=>Za(w,e-BigInt(2),e));function l(w,b,I){let C=n(w*(b-I));return b=n(b-C),I=n(I+C),[b,I]}let u=(t.a-BigInt(2))/BigInt(4);function f(w,b){Ct("u",w,Jr,e),Ct("scalar",b,Jr,e);let I=b,C=w,S=rc,B=Jr,_=w,P=rc,N=Jr,T;for(let W=BigInt(o-1);W>=Jr;W--){let R=I>>W&rc;N^=R,T=l(N,S,_),S=T[0],_=T[1],T=l(N,B,P),B=T[0],P=T[1],N=R;let E=S+B,y=n(E*E),A=S-B,k=n(A*A),v=y-k,L=_+P,M=_-P,V=n(M*E),$=n(L*A),q=V+$,Z=V-$;_=n(q*q),P=n(C*n(Z*Z)),S=n(y*k),B=n(v*(y+n(u*v)))}T=l(N,S,_),S=T[0],_=T[1],T=l(N,B,P),B=T[0],P=T[1];let F=c(B);return n(S*F)}function p(w){return Te(n(w),s)}function g(w){let b=st("u coordinate",w,s);return i===32&&(b[31]&=127),ue(b)}function m(w){let b=st("scalar",w),I=b.length;if(I!==s&&I!==i)throw new Error(`Expected ${s} or ${i} bytes, got ${I}`);return ue(a(b))}function h(w,b){let I=g(b),C=m(w),S=f(I,C);if(S===Jr)throw new Error("Invalid private or public key received");return p(S)}let d=p(t.Gu);function x(w){return h(w,d)}return{scalarMult:h,scalarMultBase:x,getSharedSecret:(w,b)=>h(w,b),getPublicKey:w=>x(w),utils:{randomPrivateKey:()=>t.randomBytes(t.nByteLength)},GuBytes:d}}var Dn=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Qu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),Dv=BigInt(0),Z0=BigInt(1),tf=BigInt(2),X0=BigInt(3),J0=BigInt(5),Q0=BigInt(8);function ef(r){let t=BigInt(10),e=BigInt(20),n=BigInt(40),o=BigInt(80),s=Dn,a=r*r%s*r%s,c=it(a,tf,s)*a%s,l=it(c,Z0,s)*r%s,u=it(l,J0,s)*l%s,f=it(u,t,s)*u%s,p=it(f,e,s)*f%s,g=it(p,n,s)*p%s,m=it(g,o,s)*g%s,h=it(m,o,s)*g%s,d=it(h,t,s)*u%s;return{pow_p_5_8:it(d,tf,s)*r%s,b2:a}}function rf(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function tg(r,t){let e=Dn,n=J(t*t*t,e),o=J(n*n*t,e),s=ef(r*o).pow_p_5_8,i=J(r*n*s,e),a=J(t*i*i,e),c=i,l=J(i*Qu,e),u=a===r,f=a===J(-r,e),p=a===J(-r*Qu,e);return u&&(i=c),(f||p)&&(i=l),zu(i,e)&&(i=J(-i,e)),{isValid:u||f,value:i}}var eg=es(Dn,void 0,!0),rg={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:eg,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Q0,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Cn,randomBytes:vr,adjustScalarBytes:rf,uvRatio:tg},Qr=Xu(rg);var Un=Ju({P:Dn,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:r=>{let t=Dn,{pow_p_5_8:e,b2:n}=ef(r);return J(it(e,X0,t)*n,t)},adjustScalarBytes:rf,randomBytes:vr});var tn=32,Le=64,os=32;function nf(){let r=Qr.utils.randomPrivateKey(),t=Qr.getPublicKey(r);return{privateKey:cf(r,t),publicKey:t}}function of(r){if(r.length!==os)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=Qr.getPublicKey(t);return{privateKey:cf(t,e),publicKey:e}}function sf(r,t){let e=r.subarray(0,os);return Qr.sign(t instanceof Uint8Array?t:t.subarray(),e)}function af(r,t,e){return Qr.verify(t,e instanceof Uint8Array?e:e.subarray(),r)}function cf(r,t){let e=new Uint8Array(Le);for(let n=0;n<os;n++)e[n]=r[n],e[os+n]=t[n];return e}var Pt={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 nc={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function lf(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=Pt.get();e*=8;async function c(f,p){let g=a.getRandomValues(new Uint8Array(s)),m=a.getRandomValues(new Uint8Array(n)),h={name:t,iv:m};typeof p=="string"&&(p=Y(p));let d;if(p.length===0){d=await a.subtle.importKey("jwk",nc,{name:"AES-GCM"},!0,["encrypt"]);try{let w={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(w,b,{name:t,length:e},!0,["encrypt"])}catch{d=await a.subtle.importKey("jwk",nc,{name:"AES-GCM"},!0,["encrypt"])}}else{let w={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},b=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);d=await a.subtle.deriveKey(w,b,{name:t,length:e},!0,["encrypt"])}let x=await a.subtle.encrypt(h,d,f);return yt([g,h.iv,new Uint8Array(x)])}async function l(f,p){let g=f.subarray(0,s),m=f.subarray(s,s+n),h=f.subarray(s+n),d={name:t,iv:m};typeof p=="string"&&(p=Y(p));let x;if(p.length===0)try{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},I=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);x=await a.subtle.deriveKey(b,I,{name:t,length:e},!0,["decrypt"])}catch{x=await a.subtle.importKey("jwk",nc,{name:"AES-GCM"},!0,["decrypt"])}else{let b={name:"PBKDF2",salt:g,iterations:i,hash:{name:o}},I=await a.subtle.importKey("raw",p,{name:"PBKDF2"},!1,["deriveKey"]);x=await a.subtle.deriveKey(b,I,{name:t,length:e},!0,["decrypt"])}let w=await a.subtle.decrypt(d,x,h);return new Uint8Array(w)}return{encrypt:c,decrypt:l}}async function en(r,t){let n=await lf().encrypt(r,t);return wi.encode(n)}var lt;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.Secp256k1="Secp256k1"})(lt||(lt={}));var oc;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.Secp256k1=2]="Secp256k1"})(oc||(oc={}));(function(r){r.codec=()=>yr(oc)})(lt||(lt={}));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),lt.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=lt.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),lt.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=lt.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 Pn=class{_key;constructor(t){this._key=rn(t,tn)}verify(t,e){return af(this._key,e,t)}marshal(){return this._key}get bytes(){return we.encode({Type:lt.Ed25519,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(t)?t.then(({bytes:e})=>e):t.bytes}},Ir=class{_key;_publicKey;constructor(t,e){this._key=rn(t,Le),this._publicKey=rn(e,tn)}sign(t){return sf(this._key,t)}get public(){return new Pn(this._publicKey)}marshal(){return this._key}get bytes(){return be.encode({Type:lt.Ed25519,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}async hash(){let t=kt.digest(this.bytes),e;return Yt(t)?{bytes:e}=await t:e=t.bytes,e}async id(){let t=Be.digest(this.public.bytes);return dt.encode(t.bytes).substring(1)}async export(t,e="libp2p-key"){if(e==="libp2p-key")return en(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function sg(r){if(r.length>Le){r=rn(r,Le+tn);let n=r.subarray(0,Le),o=r.subarray(Le,r.length);return new Ir(n,o)}r=rn(r,Le);let t=r.subarray(0,Le),e=r.subarray(tn);return new Ir(t,e)}function ig(r){return r=rn(r,tn),new Pn(r)}async function ag(){let{privateKey:r,publicKey:t}=nf();return new Ir(r,t)}async function uf(r){let{privateKey:t,publicKey:e}=of(r);return new Ir(t,e)}function rn(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 mc={};bt(mc,{MAX_RSA_KEY_SIZE:()=>zn,RsaPrivateKey:()=>cn,RsaPublicKey:()=>qn,fromJwk:()=>Dg,generateKeyPair:()=>Ug,unmarshalRsaPrivateKey:()=>dc,unmarshalRsaPublicKey:()=>Lg});function _r(r){if(isNaN(r)||r<=0)throw new D("random bytes length must be a Number bigger than 0","ERR_INVALID_LENGTH");return vr(r)}var or={};bt(or,{exportToPem:()=>kg,importFromPem:()=>Rg,jwkToPkcs1:()=>Sg,jwkToPkix:()=>Ig,pkcs1ToJwk:()=>Ag,pkixToJwk:()=>Bg});var is=class extends jr{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,Er(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),qr(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()}},tr=(r,t,e)=>new is(r,t).update(e).digest();tr.create=(r,t)=>new is(r,t);function cg(r,t,e,n){Er(r);let o=Mu({dkLen:32,asyncTick:10},n),{c:s,dkLen:i,asyncTick:a}=o;if(Ye(s),Ye(i),Ye(a),s<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=ce(t),l=ce(e),u=new Uint8Array(i),f=tr.create(r,c),p=f._cloneInto().update(l);return{c:s,dkLen:i,asyncTick:a,DK:u,PRF:f,PRFSalt:p}}function lg(r,t,e,n,o){return r.destroy(),t.destroy(),n&&n.destroy(),o.fill(0),e}async function ic(r,t,e,n){let{c:o,dkLen:s,asyncTick:i,DK:a,PRF:c,PRFSalt:l}=cg(r,t,e,n),u,f=new Uint8Array(4),p=Yr(f),g=new Uint8Array(c.outputLen);for(let m=1,h=0;h<s;m++,h+=c.outputLen){let d=a.subarray(h,h+c.outputLen);p.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(g),d.set(g.subarray(0,d.length)),await Pu(o-1,i,()=>{c._cloneInto(u).update(g).digestInto(g);for(let x=0;x<d.length;x++)d[x]^=g[x]})}return lg(c,l,a,u,g)}var j=gd(ff());function kr(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 er(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 ls(...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 cc(){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=kr(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,kr(s,8)-n}function hf(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=er(i,8,n),c=new Uint8Array(a);return c[0]|=128,a}let o=er(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 df(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 cA=Math.log(2);function us(){if(typeof BigInt>"u")throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function lc(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 Me(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 Mn=class{constructor(){this.items=[]}write(t){this.items.push(t)}final(){return lc(this.items)}},On=[new Uint8Array([1])],pf="0123456789";var sn="",de=new ArrayBuffer(0),uc=new Uint8Array(0),Hn="EndOfContent",gf="OCTET STRING",yf="BIT STRING";function He(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):uc}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(!Me(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:j.Convert.ToHex(this.valueHexView)}}},t.NAME="hexBlock",t}var Ue=class{constructor({blockLength:t=0,error:e=sn,warnings:n=[],valueBeforeDecode:o=uc}={}){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)}}};Ue.NAME="baseBlock";var Ut=class extends Ue{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 fs=class extends He(Ue){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):uc,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=er(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(!Me(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 p=new Uint8Array(u);for(let g=0;g<l.length;g++)p[g]=l[g];l=this.valueHexView=new Uint8Array(u)}}this.blockLength=c+1,l[c-1]=s[c]&127;let f=new Uint8Array(c);for(let p=0;p<c;p++)f[p]=l[p];l=this.valueHexView=new Uint8Array(c),l.set(f),this.blockLength<=9?this.tagNumber=kr(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}}};fs.NAME="identificationBlock";var hs=class extends Ue{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(!Me(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=kr(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=er(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}}};hs.NAME="lengthBlock";var O={},Tt=class extends Ue{constructor({name:t=sn,optional:e=!1,primitiveSchema:n,...o}={},s){super(o),this.name=t,this.optional=e,n&&(this.primitiveSchema=n),this.idBlock=new fs(o),this.lenBlock=new hs(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 Mn;e||wf(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():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 df(e,n)}};Tt.NAME="BaseBlock";function wf(r){if(r instanceof O.Constructed)for(let t of r.valueBlock.value)wf(t)&&(r.lenBlock.isIndefiniteForm=!0);return!!r.lenBlock.isIndefiniteForm}var ds=class extends Tt{constructor({value:t=sn,...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}'`}};ds.NAME="BaseStringBlock";var ps=class extends He(Ut){constructor({isHexOnly:t=!0,...e}={}){super(e),this.isHexOnly=t}};ps.NAME="PrimitiveValueBlock";var bf,ms=class extends Tt{constructor(t={}){super(t,ps),this.idBlock.isConstructed=!1}};bf=ms;O.Primitive=bf;ms.NAME="PRIMITIVE";function wg(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 js(r,t=0,e=r.length){let n=t,o=new Tt({},Ut),s=new Ue;if(!Me(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=Tt;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=O.EndOfContent;break;case 1:c=O.Boolean;break;case 2:c=O.Integer;break;case 3:c=O.BitString;break;case 4:c=O.OctetString;break;case 5:c=O.Null;break;case 6:c=O.ObjectIdentifier;break;case 10:c=O.Enumerated;break;case 12:c=O.Utf8String;break;case 13:c=O.RelativeObjectIdentifier;break;case 14:c=O.TIME;break;case 15:return o.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:o};case 16:c=O.Sequence;break;case 17:c=O.Set;break;case 18:c=O.NumericString;break;case 19:c=O.PrintableString;break;case 20:c=O.TeletexString;break;case 21:c=O.VideotexString;break;case 22:c=O.IA5String;break;case 23:c=O.UTCTime;break;case 24:c=O.GeneralizedTime;break;case 25:c=O.GraphicString;break;case 26:c=O.VisibleString;break;case 27:c=O.GeneralString;break;case 28:c=O.UniversalString;break;case 29:c=O.CharacterString;break;case 30:c=O.BmpString;break;case 31:c=O.DATE;break;case 32:c=O.TimeOfDay;break;case 33:c=O.DateTime;break;case 34:c=O.Duration;break;default:{let l=o.idBlock.isConstructed?new O.Constructed:new O.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?O.Constructed:O.Primitive}return o=wg(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 an(r){if(!r.byteLength){let t=new Tt({},Ut);return t.error="Input buffer has zero length",{offset:-1,result:t}}return js(j.BufferSourceConverter.toUint8Array(r).slice(),0,r.byteLength)}function bg(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=j.BufferSourceConverter.toUint8Array(t);if(!Me(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(;bg(this.isIndefiniteForm,n)>0;){let i=js(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===Hn)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Hn?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(t,e){let n=e||new Mn;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 xf,rr=class extends Tt{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(`
|
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} :`}};yf=er;O.Constructed=yf;er.NAME="CONSTRUCTED";var ps=class extends Ut{fromBER(t,e,n){return e}toBER(t){return de}};ps.override="EndOfContentValueBlock";var wf,ms=class extends Tt{constructor(t={}){super(t,ps),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};wf=ms;O.EndOfContent=wf;ms.NAME=Mn;var bf,rr=class extends Tt{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=rr;O.Null=bf;rr.NAME="NULL";var gs=class extends He(Ut){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 Me(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,ic.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};gs.NAME="BooleanValueBlock";var xf,ys=class extends Tt{constructor(t={}){super(t,gs),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}`}};xf=ys;O.Boolean=xf;ys.NAME="BOOLEAN";var ws=class extends He(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===Mn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==df)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}}};ws.NAME="OctetStringValueBlock";var Ef,Pe=class r extends Tt{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},ws),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=qs(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?er.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)}};Ef=Pe;O.OctetString=Ef;Pe.NAME=df;var bs=class extends He(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===Mn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==pf)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(!Me(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=qs(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}}};bs.NAME="BitStringValueBlock";var vf,nn=class extends Tt{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},bs),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 er.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)}`}}};vf=nn;O.BitString=vf;nn.NAME=pf;var Af;function yg(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 p=u;p>=0;p--,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=as(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=as(e,s)),s}function hf(r){if(r>=Pn.length)for(let t=Pn.length;t<=r;t++){let e=new Uint8Array([0]),n=Pn[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=as(e,n)),Pn.push(n)}return Pn[r]}function wg(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 Hn=class extends He(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=ic.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(lf(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=wg(hf(n),e),i="-";break;default:e=yg(e,hf(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=ff.charAt(e[c]));return a===!1&&(i+=ff.charAt(0)),i}};Af=Hn;Hn.NAME="IntegerValueBlock";Object.defineProperty(Af.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var Sf,wt=class r extends Tt{constructor(t={}){super(t,Hn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return cs(),BigInt(this.valueBlock.toString())}static fromBigInt(t){cs();let e=BigInt(t),n=new On,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()}`}};Sf=wt;O.Integer=Sf;wt.NAME="INTEGER";var Bf,xs=class extends wt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};Bf=xs;O.Enumerated=Bf;xs.NAME="ENUMERATED";var Vn=class extends He(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=j.BufferSourceConverter.toUint8Array(t);if(!Me(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=_r(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){cs();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=tr(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=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}}};Vn.NAME="sidBlock";var Es=class extends Ut{constructor({value:t=on,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Vn;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 ac(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 Vn;if(o>Number.MAX_SAFE_INTEGER){cs();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}};Es.NAME="ObjectIdentifierValueBlock";var If,he=class extends Tt{constructor(t={}){super(t,Es),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()}}};If=he;O.ObjectIdentifier=If;he.NAME="OBJECT IDENTIFIER";var Fn=class extends He(Ue){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(!Me(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=_r(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=tr(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=j.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Fn.NAME="relativeSidBlock";var vs=class extends Ut{constructor({value:t=on,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Fn;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 ac(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 Fn;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}};vs.NAME="RelativeObjectIdentifierValueBlock";var _f,As=class extends Tt{constructor(t={}){super(t,vs),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()}}};_f=As;O.RelativeObjectIdentifier=_f;As.NAME="RelativeObjectIdentifier";var kf,It=class extends er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};kf=It;O.Sequence=kf;It.NAME="SEQUENCE";var Rf,Ss=class extends er{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Rf=Ss;O.Set=Rf;Ss.NAME="SET";var Bs=class extends He(Ut){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=on}toJSON(){return{...super.toJSON(),value:this.value}}};Bs.NAME="StringValueBlock";var Is=class extends Bs{};Is.NAME="SimpleStringValueBlock";var Ot=class extends fs{constructor({...t}={}){super(t,Is)}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}};Ot.NAME="SIMPLE STRING";var _s=class extends Ot{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}};_s.NAME="Utf8StringValueBlock";var Cf,Oe=class extends _s{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Cf=Oe;O.Utf8String=Cf;Oe.NAME="UTF8String";var ks=class extends Ot{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))}};ks.NAME="BmpStringValueBlock";var Tf,Rs=class extends ks{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Tf=Rs;O.BmpString=Tf;Rs.NAME="BMPString";var Cs=class extends Ot{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=tr(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}};Cs.NAME="UniversalStringValueBlock";var Nf,Ts=class extends Cs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Nf=Ts;O.UniversalString=Nf;Ts.NAME="UniversalString";var Lf,Ns=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Lf=Ns;O.NumericString=Lf;Ns.NAME="NumericString";var Df,Ls=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Df=Ls;O.PrintableString=Df;Ls.NAME="PrintableString";var Uf,Ds=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Uf=Ds;O.TeletexString=Uf;Ds.NAME="TeletexString";var Pf,Us=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Pf=Us;O.VideotexString=Pf;Us.NAME="VideotexString";var Of,Ps=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Of=Ps;O.IA5String=Of;Ps.NAME="IA5String";var Mf,Os=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Mf=Os;O.GraphicString=Mf;Os.NAME="GraphicString";var Hf,Kn=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Hf=Kn;O.VisibleString=Hf;Kn.NAME="VisibleString";var Vf,Ms=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};Vf=Ms;O.GeneralString=Vf;Ms.NAME="GeneralString";var Ff,Hs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Ff=Hs;O.CharacterString=Ff;Hs.NAME="CharacterString";var Kf,$n=class extends Kn{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}}};Kf=$n;O.UTCTime=Kf;$n.NAME="UTCTime";var $f,Vs=class extends $n{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,p=n.indexOf("+"),g="";if(p===-1&&(p=n.indexOf("-"),f=-1),p!==-1){if(g=n.substring(p+1),n=n.substring(0,p),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(g.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,g.length===4){if(m=parseInt(g.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}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}}};$f=Vs;O.GeneralizedTime=$f;Vs.NAME="GeneralizedTime";var Wf,Fs=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};Wf=Fs;O.DATE=Wf;Fs.NAME="DATE";var Gf,Ks=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};Gf=Ks;O.TimeOfDay=Gf;Ks.NAME="TimeOfDay";var qf,$s=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};qf=$s;O.DateTime=qf;$s.NAME="DateTime";var zf,Ws=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};zf=Ws;O.Duration=zf;Ws.NAME="Duration";var jf,Gs=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};jf=Gs;O.TIME=jf;Gs.NAME="TIME";function xg(r){let{result:t}=sn(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 Eg(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(Y(r.n,"base64url"))),wt.fromBigInt(ve(Y(r.e,"base64url"))),wt.fromBigInt(ve(Y(r.d,"base64url"))),wt.fromBigInt(ve(Y(r.p,"base64url"))),wt.fromBigInt(ve(Y(r.q,"base64url"))),wt.fromBigInt(ve(Y(r.dp,"base64url"))),wt.fromBigInt(ve(Y(r.dq,"base64url"))),wt.fromBigInt(ve(Y(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function vg(r){let{result:t}=sn(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 Ag(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 rr]}),new nn({valueHex:new It({value:[wt.fromBigInt(ve(Y(r.n,"base64url"))),wt.fromBigInt(ve(Y(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 Sg=16,lc=32,uc=1e4;async function Bg(r,t){let e=Pt.get(),o=new It({value:[new wt({value:0}),new It({value:[new he({value:"1.2.840.113549.1.1.1"}),new rr]}),new Pe({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=Ir(Sg),a=await oc(Rn,t,i,{c:uc,dkLen:lc}),c=Ir(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 Pe({valueHex:i}),new wt({value:uc}),new wt({value:lc}),new It({value:[new he({value:"1.2.840.113549.2.11"}),new rr]})]}),p=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 Pe({valueHex:c})]})]})]}),m=new It({value:[p,new Pe({valueHex:u})]}).toBER(),h=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...G(h,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
7
|
-
`)}async function Ig(r,t){let e=Pt.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=Y(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:u}=_g(s),f=await oc(Rn,t,a,{c,dkLen:l}),p=await e.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),g=Wn(await e.subtle.decrypt({name:"AES-CBC",iv:i},p,u)),{result:m}=sn(g);n=Yf(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=Y(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=sn(o);n=Yf(s)}else throw new D("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return fc(n)}function _g(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=Wn(s.valueBlock.value[0].getValue()),a=uc,c=lc;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=Wn(l.valueBlock.value[1].getValue());return{cipherText:Wn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:f}}function Yf(r){return Wn(r.valueBlock.value[2].getValue())}function Wn(r){return new Uint8Array(r,0,r.byteLength)}async function Zf(r){let t=await Pt.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 Qf(t);return{privateKey:e[0],publicKey:e[1]}}async function hc(r){let e=[await Pt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await kg(r)],n=await Qf({privateKey:e[0],publicKey:e[1]});return{privateKey:n[0],publicKey:n[1]}}async function Xf(r,t){let e=await Pt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Pt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function Jf(r,t,e){let n=await Pt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Pt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function Qf(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Pt.get().subtle.exportKey("jwk",r.privateKey),Pt.get().subtle.exportKey("jwk",r.publicKey)])}async function kg(r){return Pt.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 zs(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 Y(r.n,"base64url").length*8}var qn=8192,Gn=class{_key;constructor(t){this._key=t}verify(t,e){return Jf(this._key,e,t)}marshal(){return nr.jwkToPkix(this._key)}get bytes(){return we.encode({Type:lt.RSA,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(t)?t.then(({bytes:e})=>e):t.bytes}},an=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e}genSecret(){return Ir(16)}sign(t){return Xf(this._key,t)}get public(){if(this._publicKey==null)throw new D("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new Gn(this._publicKey)}marshal(){return nr.jwkToPkcs1(this._key)}get bytes(){return be.encode({Type:lt.RSA,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(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 nr.exportToPem(this,t);if(e==="libp2p-key")return tn(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function fc(r){let t=nr.pkcs1ToJwk(r);if(zs(t)>qn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await hc(t);return new an(e.privateKey,e.publicKey)}function Cg(r){let t=nr.pkixToJwk(r);if(zs(t)>qn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new Gn(t)}async function Tg(r){if(zs(r)>qn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await hc(r);return new an(t.privateKey,t.publicKey)}async function Ng(r){if(r>qn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Zf(r);return new an(t.privateKey,t.publicKey)}var wc={};bt(wc,{Secp256k1PrivateKey:()=>jn,Secp256k1PublicKey:()=>zn,generateKeyPair:()=>Gg,unmarshalSecp256k1PrivateKey:()=>$g,unmarshalSecp256k1PublicKey:()=>Wg});var Lg=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]),or=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),sr=new Uint32Array(64),pc=class extends Yr{constructor(){super(64,32,8,!1),this.A=or[0]|0,this.B=or[1]|0,this.C=or[2]|0,this.D=or[3]|0,this.E=or[4]|0,this.F=or[5]|0,this.G=or[6]|0,this.H=or[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)sr[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let p=sr[f-15],g=sr[f-2],m=ae(p,7)^ae(p,18)^p>>>3,h=ae(g,17)^ae(g,19)^g>>>10;sr[f]=h+sr[f-7]+m+sr[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 p=ae(a,6)^ae(a,11)^ae(a,25),g=u+p+Pu(a,c,l)+Lg[f]+sr[f]|0,h=(ae(n,2)^ae(n,13)^ae(n,22))+Ou(n,o,s)|0;u=l,l=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+h|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(){sr.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var cn=jo(()=>new pc);function th(r){r.lowS!==void 0&&le("lowS",r.lowS),r.prehash!==void 0&&le("prehash",r.prehash)}function Dg(r){let t=Nn(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:Ug,hexToBytes:Pg}=Xo,kr={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(r){let{Err:t}=kr;if(r.length<2||r[0]!==2)throw new t("Invalid signature integer tag");let e=r[1],n=r.subarray(2,e+2);if(!e||n.length!==e)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:Ug(n),l:r.subarray(e+2)}},toSig(r){let{Err:t}=kr,e=typeof r=="string"?Pg(r):r;Zr(e);let n=e.length;if(n<2||e[0]!=48)throw new t("Invalid signature tag");if(e[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:o,l:s}=kr._parseInt(e.subarray(2)),{d:i,l:a}=kr._parseInt(s);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let t=l=>Number.parseInt(l[0],16)&8?"00"+l:l,e=l=>{let u=l.toString(16);return u.length&1?`0${u}`:u},n=t(e(r.s)),o=t(e(r.r)),s=n.length/2,i=o.length/2,a=e(s),c=e(i);return`30${e(i+s+4)}02${c}${o}02${a}${n}`}},ir=BigInt(0),_t=BigInt(1),TA=BigInt(2),eh=BigInt(3),NA=BigInt(4);function Og(r){let t=Dg(r),{Fp:e}=t,n=t.toBytes||((m,h,d)=>{let x=h.toAffine();return Ne(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),o=t.fromBytes||(m=>{let h=m.subarray(1),d=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:d,y:x}});function s(m){let{a:h,b:d}=t,x=e.sqr(m),w=e.mul(x,m);return e.add(e.add(w,e.mul(m,h)),d)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function i(m){return Cn(m,_t,t.n)}function a(m){let{allowedPrivateKeyLengths:h,nByteLength:d,wrapPrivateKey:x,n:w}=t;if(h&&typeof m!="bigint"){if(Xe(m)&&(m=Re(m)),typeof m!="string"||!h.includes(m.length))throw new Error("Invalid key");m=m.padStart(d*2,"0")}let b;try{b=typeof m=="bigint"?m:Ce(st("private key",m,d))}catch{throw new Error(`private key must be ${d} bytes, hex or bigint, not ${typeof m}`)}return x&&(b=J(b,w)),Ct("private key",b,_t,w),b}function c(m){if(!(m instanceof f))throw new Error("ProjectivePoint expected")}let l=Ar((m,h)=>{let{px:d,py:x,pz:w}=m;if(e.eql(w,e.ONE))return{x:d,y:x};let b=m.is0();h==null&&(h=b?e.ONE:e.inv(w));let I=e.mul(d,h),C=e.mul(x,h),S=e.mul(w,h);if(b)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:I,y:C}}),u=Ar(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:h,y:d}=m.toAffine();if(!e.isValid(h)||!e.isValid(d))throw new Error("bad point: x or y not FE");let x=e.sqr(d),w=s(h);if(!e.eql(x,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(h,d,x){if(this.px=h,this.py=d,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(d==null||!e.isValid(d))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:d,y:x}=h||{};if(!h||!e.isValid(d)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof f)throw new Error("projective point not allowed");let w=b=>e.eql(b,e.ZERO);return w(d)&&w(x)?f.ZERO:new f(d,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let d=e.invertBatch(h.map(x=>x.pz));return h.map((x,w)=>x.toAffine(d[w])).map(f.fromAffine)}static fromHex(h){let d=f.fromAffine(o(st("pointHex",h)));return d.assertValidity(),d}static fromPrivateKey(h){return f.BASE.multiply(a(h))}_setWindowSize(h){g.setWindowSize(this,h)}assertValidity(){u(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){c(h);let{px:d,py:x,pz:w}=this,{px:b,py:I,pz:C}=h,S=e.eql(e.mul(d,C),e.mul(b,w)),B=e.eql(e.mul(x,C),e.mul(I,w));return S&&B}negate(){return new f(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:d}=t,x=e.mul(d,eh),{px:w,py:b,pz:I}=this,C=e.ZERO,S=e.ZERO,B=e.ZERO,_=e.mul(w,w),P=e.mul(b,b),N=e.mul(I,I),T=e.mul(w,b);return T=e.add(T,T),B=e.mul(w,I),B=e.add(B,B),C=e.mul(h,B),S=e.mul(x,N),S=e.add(C,S),C=e.sub(P,S),S=e.add(P,S),S=e.mul(C,S),C=e.mul(T,C),B=e.mul(x,B),N=e.mul(h,N),T=e.sub(_,N),T=e.mul(h,T),T=e.add(T,B),B=e.add(_,_),_=e.add(B,_),_=e.add(_,N),_=e.mul(_,T),S=e.add(S,_),N=e.mul(b,I),N=e.add(N,N),_=e.mul(N,T),C=e.sub(C,_),B=e.mul(N,P),B=e.add(B,B),B=e.add(B,B),new f(C,S,B)}add(h){c(h);let{px:d,py:x,pz:w}=this,{px:b,py:I,pz:C}=h,S=e.ZERO,B=e.ZERO,_=e.ZERO,P=t.a,N=e.mul(t.b,eh),T=e.mul(d,b),F=e.mul(x,I),W=e.mul(w,C),R=e.add(d,x),E=e.add(b,I);R=e.mul(R,E),E=e.add(T,F),R=e.sub(R,E),E=e.add(d,w);let y=e.add(b,C);return E=e.mul(E,y),y=e.add(T,W),E=e.sub(E,y),y=e.add(x,w),S=e.add(I,C),y=e.mul(y,S),S=e.add(F,W),y=e.sub(y,S),_=e.mul(P,E),S=e.mul(N,W),_=e.add(S,_),S=e.sub(F,_),_=e.add(F,_),B=e.mul(S,_),F=e.add(T,T),F=e.add(F,T),W=e.mul(P,W),E=e.mul(N,E),F=e.add(F,W),W=e.sub(T,W),W=e.mul(P,W),E=e.add(E,W),T=e.mul(F,E),B=e.add(B,T),T=e.mul(y,E),S=e.mul(R,S),S=e.sub(S,T),T=e.mul(R,F),_=e.mul(y,_),_=e.add(_,T),new f(S,B,_)}subtract(h){return this.add(h.negate())}is0(){return this.equals(f.ZERO)}wNAF(h){return g.wNAFCached(this,h,f.normalizeZ)}multiplyUnsafe(h){Ct("scalar",h,ir,t.n);let d=f.ZERO;if(h===ir)return d;if(h===_t)return this;let{endo:x}=t;if(!x)return g.unsafeLadder(this,h);let{k1neg:w,k1:b,k2neg:I,k2:C}=x.splitScalar(h),S=d,B=d,_=this;for(;b>ir||C>ir;)b&_t&&(S=S.add(_)),C&_t&&(B=B.add(_)),_=_.double(),b>>=_t,C>>=_t;return w&&(S=S.negate()),I&&(B=B.negate()),B=new f(e.mul(B.px,x.beta),B.py,B.pz),S.add(B)}multiply(h){let{endo:d,n:x}=t;Ct("scalar",h,_t,x);let w,b;if(d){let{k1neg:I,k1:C,k2neg:S,k2:B}=d.splitScalar(h),{p:_,f:P}=this.wNAF(C),{p:N,f:T}=this.wNAF(B);_=g.constTimeNegate(I,_),N=g.constTimeNegate(S,N),N=new f(e.mul(N.px,d.beta),N.py,N.pz),w=_.add(N),b=P.add(T)}else{let{p:I,f:C}=this.wNAF(h);w=I,b=C}return f.normalizeZ([w,b])[0]}multiplyAndAddUnsafe(h,d,x){let w=f.BASE,b=(C,S)=>S===ir||S===_t||!C.equals(w)?C.multiplyUnsafe(S):C.multiply(S),I=b(this,d).add(b(h,x));return I.is0()?void 0:I}toAffine(h){return l(this,h)}isTorsionFree(){let{h,isTorsionFree:d}=t;if(h===_t)return!0;if(d)return d(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:d}=t;return h===_t?this:d?d(f,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return le("isCompressed",h),this.assertValidity(),n(f,this,h)}toHex(h=!0){return le("isCompressed",h),Re(this.toRawBytes(h))}}f.BASE=new f(t.Gx,t.Gy,e.ONE),f.ZERO=new f(e.ZERO,e.ONE,e.ZERO);let p=t.nBitLength,g=ts(f,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:i}}function Mg(r){let t=Nn(r);return Zt(t,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...t})}function rh(r){let t=Mg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(R){return J(R,n)}function a(R){return Jo(R,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Og({...t,toBytes(R,E,y){let A=E.toAffine(),k=e.toBytes(A.x),v=Ne;return le("isCompressed",y),y?v(Uint8Array.from([E.hasEvenY()?2:3]),k):v(Uint8Array.from([4]),k,e.toBytes(A.y))},fromBytes(R){let E=R.length,y=R[0],A=R.subarray(1);if(E===o&&(y===2||y===3)){let k=Ce(A);if(!Cn(k,_t,e.ORDER))throw new Error("Point is not on curve");let v=u(k),L;try{L=e.sqrt(v)}catch($){let q=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+q)}let M=(L&_t)===_t;return(y&1)===1!==M&&(L=e.neg(L)),{x:k,y:L}}else if(E===s&&y===4){let k=e.fromBytes(A.subarray(0,e.BYTES)),v=e.fromBytes(A.subarray(e.BYTES,2*e.BYTES));return{x:k,y:v}}else throw new Error(`Point of length ${E} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),p=R=>Re(Je(R,t.nByteLength));function g(R){let E=n>>_t;return R>E}function m(R){return g(R)?i(-R):R}let h=(R,E,y)=>Ce(R.slice(E,y));class d{constructor(E,y,A){this.r=E,this.s=y,this.recovery=A,this.assertValidity()}static fromCompact(E){let y=t.nByteLength;return E=st("compactSignature",E,y*2),new d(h(E,0,y),h(E,y,2*y))}static fromDER(E){let{r:y,s:A}=kr.toSig(st("DER",E));return new d(y,A)}assertValidity(){Ct("r",this.r,_t,n),Ct("s",this.s,_t,n)}addRecoveryBit(E){return new d(this.r,this.s,E)}recoverPublicKey(E){let{r:y,s:A,recovery:k}=this,v=S(st("msgHash",E));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let L=k===2||k===3?y+t.n:y;if(L>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=k&1?"03":"02",V=c.fromHex(M+p(L)),$=a(L),q=i(-v*$),Z=i(A*$),Q=c.BASE.multiplyAndAddUnsafe(V,q,Z);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return vr(this.toDERHex())}toDERHex(){return kr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return vr(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let x={isValidPrivateKey(R){try{return l(R),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let R=Xa(t.n);return qu(t.randomBytes(R),t.n)},precompute(R=8,E=c.BASE){return E._setWindowSize(R),E.multiply(BigInt(3)),E}};function w(R,E=!0){return c.fromPrivateKey(R).toRawBytes(E)}function b(R){let E=Xe(R),y=typeof R=="string",A=(E||y)&&R.length;return E?A===o||A===s:y?A===2*o||A===2*s:R instanceof c}function I(R,E,y=!0){if(b(R))throw new Error("first arg must be private key");if(!b(E))throw new Error("second arg must be public key");return c.fromHex(E).multiply(l(R)).toRawBytes(y)}let C=t.bits2int||function(R){let E=Ce(R),y=R.length*8-t.nBitLength;return y>0?E>>BigInt(y):E},S=t.bits2int_modN||function(R){return i(C(R))},B=Tn(t.nBitLength);function _(R){return Ct(`num < 2^${t.nBitLength}`,R,ir,B),Je(R,t.nByteLength)}function P(R,E,y=N){if(["recovered","canonical"].some(ot=>ot in y))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:k}=t,{lowS:v,prehash:L,extraEntropy:M}=y;v==null&&(v=!0),R=st("msgHash",R),th(y),L&&(R=st("prehashed msgHash",A(R)));let V=S(R),$=l(E),q=[_($),_(V)];if(M!=null&&M!==!1){let ot=M===!0?k(e.BYTES):M;q.push(st("extraEntropy",ot))}let Z=Ne(...q),Q=V;function ht(ot){let nt=C(ot);if(!f(nt))return;let Jt=a(nt),Bt=c.BASE.multiply(nt).toAffine(),Qt=i(Bt.x);if(Qt===ir)return;let ar=i(Jt*i(Q+Qt*$));if(ar===ir)return;let dn=(Bt.x===Qt?0:2)|Number(Bt.y&_t),Qn=ar;return v&&g(ar)&&(Qn=m(ar),dn^=1),new d(Qt,Qn,dn)}return{seed:Z,k2sig:ht}}let N={lowS:t.lowS,prehash:!1},T={lowS:t.lowS,prehash:!1};function F(R,E,y=N){let{seed:A,k2sig:k}=P(R,E,y),v=t;return qa(v.hash.outputLen,v.nByteLength,v.hmac)(A,k)}c.BASE._setWindowSize(8);function W(R,E,y,A=T){let k=R;if(E=st("msgHash",E),y=st("publicKey",y),"strict"in A)throw new Error("options.strict was renamed to lowS");th(A);let{lowS:v,prehash:L}=A,M,V;try{if(typeof k=="string"||Xe(k))try{M=d.fromDER(k)}catch(Bt){if(!(Bt instanceof kr.Err))throw Bt;M=d.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Bt,s:Qt}=k;M=new d(Bt,Qt)}else throw new Error("PARSE");V=c.fromHex(y)}catch(Bt){if(Bt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&M.hasHighS())return!1;L&&(E=t.hash(E));let{r:$,s:q}=M,Z=S(E),Q=a(q),ht=i(Z*Q),ot=i($*Q),nt=c.BASE.multiplyAndAddUnsafe(V,ht,ot)?.toAffine();return nt?i(nt.x)===$:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:I,sign:F,verify:W,ProjectivePoint:c,Signature:d,utils:x}}function Hg(r){return{hash:r,hmac:(t,...e)=>Qe(r,t,Ha(...e)),randomBytes:Er}}function nh(r,t){let e=n=>rh({...r,...Hg(n)});return Object.freeze({...e(t),create:e})}var ih=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),oh=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Vg=BigInt(1),mc=BigInt(2),sh=(r,t)=>(r+t/mc)/t;function Fg(r){let t=ih,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=it(u,e,t)*u%t,p=it(f,e,t)*u%t,g=it(p,mc,t)*l%t,m=it(g,o,t)*g%t,h=it(m,s,t)*m%t,d=it(h,a,t)*h%t,x=it(d,c,t)*d%t,w=it(x,a,t)*h%t,b=it(w,e,t)*u%t,I=it(b,i,t)*m%t,C=it(I,n,t)*l%t,S=it(C,mc,t);if(!gc.eql(gc.sqr(S),r))throw new Error("Cannot find square root");return S}var gc=Qo(ih,void 0,void 0,{sqrt:Fg}),pe=nh({a:BigInt(0),b:BigInt(7),Fp:gc,n:oh,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=oh,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Vg*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=sh(s*r,t),c=sh(-n*r,t),l=J(r-a*e-c*o,t),u=J(-a*n-c*s,t),f=l>i,p=u>i;if(f&&(l=t-l),p&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},cn),FA=BigInt(0);var KA=pe.ProjectivePoint;function ah(){return pe.utils.randomPrivateKey()}function ch(r,t){let e=kt.digest(t instanceof Uint8Array?t:t.subarray());if(Yt(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 lh(r,t,e){let n=kt.digest(e instanceof Uint8Array?e:e.subarray());if(Yt(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 uh(r){return pe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function fh(r){try{pe.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}function yc(r){try{pe.ProjectivePoint.fromHex(r)}catch(t){throw new D(String(t),"ERR_INVALID_PUBLIC_KEY")}}function hh(r){try{return pe.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}var zn=class{_key;constructor(t){yc(t),this._key=t}verify(t,e){return lh(this._key,e,t)}marshal(){return uh(this._key)}get bytes(){return we.encode({Type:lt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}async hash(){let t=kt.digest(this.bytes),e;return Yt(t)?{bytes:e}=await t:e=t.bytes,e}},jn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e??hh(t),fh(this._key),yc(this._publicKey)}sign(t){return ch(this._key,t)}get public(){return new zn(this._publicKey)}marshal(){return this._key}get bytes(){return be.encode({Type:lt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(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 tn(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function $g(r){return new jn(r)}function Wg(r){return new zn(r)}async function Gg(){let r=ah();return new jn(r)}var Rr={rsa:dc,ed25519:nc,secp256k1:wc};function dh(r){let t=Object.keys(Rr).join(" / ");return new D(`invalid or unsupported key type ${r}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function ph(r){let t=we.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case lt.RSA:return Rr.rsa.unmarshalRsaPublicKey(e);case lt.Ed25519:return Rr.ed25519.unmarshalEd25519PublicKey(e);case lt.Secp256k1:return Rr.secp256k1.unmarshalSecp256k1PublicKey(e);default:throw dh(t.Type??"unknown")}}async function bc(r){let t=be.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case lt.RSA:return Rr.rsa.unmarshalRsaPrivateKey(e);case lt.Ed25519:return Rr.ed25519.unmarshalEd25519PrivateKey(e);case lt.Secp256k1:return Rr.secp256k1.unmarshalSecp256k1PrivateKey(e);default:throw dh(t.Type??"RSA")}}function xc(){let r=ft(),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 mh(){let r=xc(),t=xc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function qg(r){return r[Symbol.asyncIterator]!=null}function zg(...r){let t=[];for(let e of r)qg(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=We({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 gh=zg;function yh(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ec(r)){let n=r;r=()=>n.source}else if(bh(r)||wh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ec(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++)Ec(e[n])&&(e[n]=Yg(e[n]));return jg(...e)}var jg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},wh=r=>r?.[Symbol.asyncIterator]!=null,bh=r=>r?.[Symbol.iterator]!=null,Ec=r=>r==null?!1:r.sink!=null&&r.source!=null,Yg=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=We({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(wh(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 gh(n,o())}return r.source};var ln=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function js(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function vc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function Ac(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Kt(r,...t){if(!Ac(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 Sc(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 xh(r,t){Kt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Ve=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Eh=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Zg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Zg)throw new Error("Non little-endian hardware is not supported");function Xg(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Ys(r){if(typeof r=="string")r=Xg(r);else if(Ac(r))r=r.slice();else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function vh(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Ah(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 Bc=(r,t)=>(Object.assign(t,r),t);function Ic(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 Nt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,_c=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=Ys(t),Kt(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],p=i[5],g=i[6],m=i[7],h=i[8],d=i[9],x=Nt(t,e+0),w=Nt(t,e+2),b=Nt(t,e+4),I=Nt(t,e+6),C=Nt(t,e+8),S=Nt(t,e+10),B=Nt(t,e+12),_=Nt(t,e+14),P=s[0]+(x&8191),N=s[1]+((x>>>13|w<<3)&8191),T=s[2]+((w>>>10|b<<6)&8191),F=s[3]+((b>>>7|I<<9)&8191),W=s[4]+((I>>>4|C<<12)&8191),R=s[5]+(C>>>1&8191),E=s[6]+((C>>>14|S<<2)&8191),y=s[7]+((S>>>11|B<<5)&8191),A=s[8]+((B>>>8|_<<8)&8191),k=s[9]+(_>>>5|o),v=0,L=v+P*a+N*(5*d)+T*(5*h)+F*(5*m)+W*(5*g);v=L>>>13,L&=8191,L+=R*(5*p)+E*(5*f)+y*(5*u)+A*(5*l)+k*(5*c),v+=L>>>13,L&=8191;let M=v+P*c+N*a+T*(5*d)+F*(5*h)+W*(5*m);v=M>>>13,M&=8191,M+=R*(5*g)+E*(5*p)+y*(5*f)+A*(5*u)+k*(5*l),v+=M>>>13,M&=8191;let V=v+P*l+N*c+T*a+F*(5*d)+W*(5*h);v=V>>>13,V&=8191,V+=R*(5*m)+E*(5*g)+y*(5*p)+A*(5*f)+k*(5*u),v+=V>>>13,V&=8191;let $=v+P*u+N*l+T*c+F*a+W*(5*d);v=$>>>13,$&=8191,$+=R*(5*h)+E*(5*m)+y*(5*g)+A*(5*p)+k*(5*f),v+=$>>>13,$&=8191;let q=v+P*f+N*u+T*l+F*c+W*a;v=q>>>13,q&=8191,q+=R*(5*d)+E*(5*h)+y*(5*m)+A*(5*g)+k*(5*p),v+=q>>>13,q&=8191;let Z=v+P*p+N*f+T*u+F*l+W*c;v=Z>>>13,Z&=8191,Z+=R*a+E*(5*d)+y*(5*h)+A*(5*m)+k*(5*g),v+=Z>>>13,Z&=8191;let Q=v+P*g+N*p+T*f+F*u+W*l;v=Q>>>13,Q&=8191,Q+=R*c+E*a+y*(5*d)+A*(5*h)+k*(5*m),v+=Q>>>13,Q&=8191;let ht=v+P*m+N*g+T*p+F*f+W*u;v=ht>>>13,ht&=8191,ht+=R*l+E*c+y*a+A*(5*d)+k*(5*h),v+=ht>>>13,ht&=8191;let ot=v+P*h+N*m+T*g+F*p+W*f;v=ot>>>13,ot&=8191,ot+=R*u+E*l+y*c+A*a+k*(5*d),v+=ot>>>13,ot&=8191;let nt=v+P*d+N*h+T*m+F*g+W*p;v=nt>>>13,nt&=8191,nt+=R*f+E*u+y*l+A*c+k*a,v+=nt>>>13,nt&=8191,v=(v<<2)+v|0,v=v+L|0,L=v&8191,v=v>>>13,M+=v,s[0]=L,s[1]=M,s[2]=V,s[3]=$,s[4]=q,s[5]=Z,s[6]=Q,s[7]=ht,s[8]=ot,s[9]=nt}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}update(t){Sc(this);let{buffer:e,blockLen:n}=this;t=Ys(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(){this.h.fill(0),this.r.fill(0),this.buffer.fill(0),this.pad.fill(0)}digestInto(t){Sc(this),xh(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 Jg(r){let t=(n,o)=>r(o).update(Ys(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Sh=Jg(r=>new _c(r));var Ih=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),Qg=Ih("expand 16-byte k"),ty=Ih("expand 32-byte k"),ey=Ve(Qg),_h=Ve(ty),xS=_h.slice();function H(r,t){return r<<t|r>>>32-t}function kc(r){return r.byteOffset%4===0}var Zs=64,ry=16,kh=2**32-1,Bh=new Uint32Array;function ny(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Zs),u=Ve(l),f=kc(o)&&kc(s),p=f?Ve(o):Bh,g=f?Ve(s):Bh;for(let m=0;m<c;i++){if(r(t,e,n,u,i,a),i>=kh)throw new Error("arx: counter overflow");let h=Math.min(Zs,c-m);if(f&&h===Zs){let d=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let x=0,w;x<ry;x++)w=d+x,g[w]=p[w]^u[x];m+=Zs;continue}for(let d=0,x;d<h;d++)x=m+d,s[x]=o[x]^l[d];m+=h}}function Rc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=vh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return js(o),js(i),vc(s),vc(e),(a,c,l,u,f=0)=>{Kt(a),Kt(c),Kt(l);let p=l.length;if(u||(u=new Uint8Array(p)),Kt(u),js(f),f<0||f>=kh)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let g=[],m=a.length,h,d;if(m===32)h=a.slice(),g.push(h),d=_h;else if(m===16&&e)h=new Uint8Array(32),h.set(a),h.set(a,16),d=ey,g.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${m}`);kc(c)||(c=c.slice(),g.push(c));let x=Ve(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(d,x,Ve(c.subarray(0,16)),x),c=c.subarray(16)}let w=16-o;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,g.push(c)}let b=Ve(c);for(ny(r,d,x,b,l,u,f,i);g.length>0;)g.pop().fill(0);return u}}function Th(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],p=t[2],g=t[3],m=t[4],h=t[5],d=t[6],x=t[7],w=o,b=e[0],I=e[1],C=e[2],S=i,B=a,_=c,P=l,N=u,T=f,F=p,W=g,R=m,E=h,y=d,A=x,k=w,v=b,L=I,M=C;for(let $=0;$<s;$+=2)S=S+N|0,k=H(k^S,16),R=R+k|0,N=H(N^R,12),S=S+N|0,k=H(k^S,8),R=R+k|0,N=H(N^R,7),B=B+T|0,v=H(v^B,16),E=E+v|0,T=H(T^E,12),B=B+T|0,v=H(v^B,8),E=E+v|0,T=H(T^E,7),_=_+F|0,L=H(L^_,16),y=y+L|0,F=H(F^y,12),_=_+F|0,L=H(L^_,8),y=y+L|0,F=H(F^y,7),P=P+W|0,M=H(M^P,16),A=A+M|0,W=H(W^A,12),P=P+W|0,M=H(M^P,8),A=A+M|0,W=H(W^A,7),S=S+T|0,M=H(M^S,16),y=y+M|0,T=H(T^y,12),S=S+T|0,M=H(M^S,8),y=y+M|0,T=H(T^y,7),B=B+F|0,k=H(k^B,16),A=A+k|0,F=H(F^A,12),B=B+F|0,k=H(k^B,8),A=A+k|0,F=H(F^A,7),_=_+W|0,v=H(v^_,16),R=R+v|0,W=H(W^R,12),_=_+W|0,v=H(v^_,8),R=R+v|0,W=H(W^R,7),P=P+N|0,L=H(L^P,16),E=E+L|0,N=H(N^E,12),P=P+N|0,L=H(L^P,8),E=E+L|0,N=H(N^E,7);let V=0;n[V++]=i+S|0,n[V++]=a+B|0,n[V++]=c+_|0,n[V++]=l+P|0,n[V++]=u+N|0,n[V++]=f+T|0,n[V++]=p+F|0,n[V++]=g+W|0,n[V++]=m+R|0,n[V++]=h+E|0,n[V++]=d+y|0,n[V++]=x+A|0,n[V++]=w+k|0,n[V++]=b+v|0,n[V++]=I+L|0,n[V++]=C+M|0}function oy(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],p=t[4],g=t[5],m=t[6],h=t[7],d=e[0],x=e[1],w=e[2],b=e[3];for(let C=0;C<20;C+=2)o=o+c|0,d=H(d^o,16),p=p+d|0,c=H(c^p,12),o=o+c|0,d=H(d^o,8),p=p+d|0,c=H(c^p,7),s=s+l|0,x=H(x^s,16),g=g+x|0,l=H(l^g,12),s=s+l|0,x=H(x^s,8),g=g+x|0,l=H(l^g,7),i=i+u|0,w=H(w^i,16),m=m+w|0,u=H(u^m,12),i=i+u|0,w=H(w^i,8),m=m+w|0,u=H(u^m,7),a=a+f|0,b=H(b^a,16),h=h+b|0,f=H(f^h,12),a=a+f|0,b=H(b^a,8),h=h+b|0,f=H(f^h,7),o=o+l|0,b=H(b^o,16),m=m+b|0,l=H(l^m,12),o=o+l|0,b=H(b^o,8),m=m+b|0,l=H(l^m,7),s=s+u|0,d=H(d^s,16),h=h+d|0,u=H(u^h,12),s=s+u|0,d=H(d^s,8),h=h+d|0,u=H(u^h,7),i=i+f|0,x=H(x^i,16),p=p+x|0,f=H(f^p,12),i=i+f|0,x=H(x^i,8),p=p+x|0,f=H(f^p,7),a=a+c|0,w=H(w^a,16),g=g+w|0,c=H(c^g,12),a=a+c|0,w=H(w^a,8),g=g+w|0,c=H(c^g,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=d,n[I++]=x,n[I++]=w,n[I++]=b}var sy=Rc(Th,{counterRight:!1,counterLength:4,allowShortKeys:!1}),iy=Rc(Th,{counterRight:!1,counterLength:8,extendNonceFn:oy,allowShortKeys:!1});var ay=new Uint8Array(16),Rh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(ay.subarray(e))},cy=new Uint8Array(32);function Ch(r,t,e,n,o){let s=r(t,e,cy),i=Sh.create(s);o&&Rh(i,o),Rh(i,n);let a=new Uint8Array(16),c=Eh(a);Ic(c,0,BigInt(o?o.length:0),!0),Ic(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return s.fill(0),l}var Nh=r=>(t,e,n)=>(Kt(t,32),Kt(e),{encrypt:(s,i)=>{let a=s.length,c=a+16;i?Kt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=Ch(r,t,e,i.subarray(0,-16),n);return i.set(l,a),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?Kt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=Ch(r,t,e,l,n);if(!Ah(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),i}}),Cc=Bc({blockSize:64,nonceLength:12,tagLength:16},Nh(sy)),IS=Bc({blockSize:64,nonceLength:24,tagLength:16},Nh(iy));function Dh(r,t,e){return xr(r),e===void 0&&(e=new Uint8Array(r.outputLen)),Qe(r,ce(e),ce(t))}var Tc=new Uint8Array([0]),Lh=new Uint8Array;function Uh(r,t,e,n=32){if(xr(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=Lh);let s=new Uint8Array(o*r.outputLen),i=Qe.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Tc[0]=l+1,a.update(l===0?Lh:c).update(e).update(Tc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Tc.fill(0),s.slice(0,n)}var Nc={hashSHA256(r){return cn(r.subarray())},getHKDF(r,t){let e=Dh(cn,t,r),o=Uh(cn,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=Dn.utils.randomPrivateKey();return{publicKey:Dn.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Dn.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return Dn.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Cc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Cc(n,t,e).decrypt(r.subarray(),o)}};var Ph=Nc;function Oh(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 un=r=>{let t=vt(2);return t[0]=r>>8,t[1]=r,t};un.bytes=2;var Yn=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)};Yn.bytes=2;function Mh(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 Lc(r,t){!t.enabled||!ln||(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 Dc(r,t){!t.enabled||!ln||(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 Hh(r,t){!t.enabled||!ln||t(r?`REMOTE_STATIC_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote static public key.")}function Uc(r,t){!t.enabled||!ln||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Pc(r,t,e){!e.enabled||!ln||(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 Xs=class r extends Error{code;constructor(t="Unexpected Peer"){super(t),this.code=r.code}static code="ERR_UNEXPECTED_PEER"},fn=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var ly=0,uy=4294967295,fy="Cipherstate has reached maximum n, a new handshake must be performed",Js=class{n;bytes;view;constructor(t=ly){this.n=t,this.bytes=Et(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>uy)throw new Error(fy)}};var Cr=Et(0),hn=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new Js(n)}hasKey(){return!!this.k}encryptWithAd(t,e){if(!this.hasKey())return e;this.n.assertValue();let n=this.crypto.encrypt(e,this.n.getBytes(),t,this.k);return this.n.increment(),n}decryptWithAd(t,e,n){if(!this.hasKey())return e;this.n.assertValue();let o=this.crypto.decrypt(e,this.n.getBytes(),t,this.k,n);return this.n.increment(),o}},Oc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Y(e,"utf-8");this.h=hy(t,n),this.ck=this.h,this.cs=new hn(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new hn(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new at(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,Cr);return[new hn(this.crypto,t),new hn(this.crypto,e)]}},Mc=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 Oc(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()}},Zn=class extends Mc{writeMessageA(t){return new at(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new at(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new at(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new fn(`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 fn(`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 fn(`handshake stage 2 validation fail: ${e.message}`)}}};function hy(r,t){if(t.length<=32){let e=Et(32);return e.set(t),e}else return r.hash(t)}var Qs;(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())})(Qs||(Qs={}));var Xn;(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),Qs.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:Et(0),identitySig:Et(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=Qs.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())})(Xn||(Xn={}));async function Hc(r,t,e){let n=await r.sign(Vh(t));return Xn.encode({identityKey:r.public.bytes,identitySig:n,extensions:e})}async function Vc(r,t,e){try{let n=Xn.decode(r);if(e){let i=e.subarray();if(!xt(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=Vh(t);if(!await ph(n.identityKey).verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new Xs(n.message)}}function Vh(r){let t=Y("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function Fh(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await Hc(o,i.publicKey,c),u=new Zn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:i});Lc(u.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await e.write(u.writeMessageA(Cr)),t.trace("Stage 0 - Initiator finished sending first message."),Dc(u.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=u.readMessageB(await e.read());t.trace("Stage 1 - Initiator received the message."),Uc(u.re,t),Hh(u.rs,t),t.trace("Initiator going to check remote's signature...");let p=await Vc(f,u.rs,a);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await e.write(u.writeMessageC(l)),t.trace("Stage 2 - Initiator sent message with signed payload.");let[g,m]=u.ss.split();return Pc(g,m,t),{payload:p,encrypt:h=>g.encryptWithAd(Cr,h),decrypt:(h,d)=>m.decryptWithAd(Cr,h,d)}}async function Kh(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await Hc(o,i.publicKey,c),u=new Zn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:i});Lc(u.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await e.read()),t.trace("Stage 0 - Responder received first message."),Uc(u.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await e.write(u.writeMessageB(l)),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Dc(u.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=u.readMessageC(await e.read());t.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Vc(f,u.rs,a),[g,m]=u.ss.split();return Pc(g,m,t),{payload:p,encrypt:h=>m.encryptWithAd(Cr,h),decrypt:(h,d)=>g.decryptWithAd(Cr,h,d)}}var Wh=16;function Gh(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 at(un(i.byteLength),i)}}}function qh(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-Wh<o)throw new Error("Invalid chunk");let i=n.sublist(o,s),a=n.subarray(o,s-Wh);try{let c=r.decrypt(i,a);t?.decryptedPackets.increment(),yield c}catch(c){throw t?.decryptErrors.increment(),c}}}}var ti=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??Ph;this.crypto=Oh(c),this.extensions=o,this.metrics=a?Mh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Et(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Tr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(t,e,n){let o=kn(e,{lengthEncoder:un,lengthDecoder:Yn,maxDataLength:65535});if(!t.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let s=await bc(t.privateKey),i=n?.publicKey,a=await this.performHandshakeInitiator(o,s,i),c=await this.createSecureConnection(o,a);return e.source=c.source,e.sink=c.sink,{conn:e,remoteExtensions:a.payload.extensions,remotePeer:await Li(a.payload.identityKey)}}async secureInbound(t,e,n){let o=kn(e,{lengthEncoder:un,lengthDecoder:Yn,maxDataLength:65535});if(!t.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let s=await bc(t.privateKey),i=n?.publicKey,a=await this.performHandshakeResponder(o,s,i),c=await this.createSecureConnection(o,a);return e.source=c.source,e.sink=c.sink,{conn:e,remoteExtensions:a.payload.extensions,remotePeer:await Li(a.payload.identityKey)}}async performHandshakeInitiator(t,e,n){let o;try{o=await Fh({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}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async performHandshakeResponder(t,e,n){let o;try{o=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}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async createSecureConnection(t,e){let[n,o]=mh(),s=t.unwrap();return await yh(n,Gh(e,this.metrics),s,i=>dr(i,{lengthDecoder:Yn}),qh(e,this.metrics),n),o}};function zh(r={}){return t=>new ti(t,r)}var Fc=Object.values(me).map(r=>r.decoder).reduce((r,t)=>r.or(t));function jh(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:py(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 da("","no fingerprint on local certificate");return n}var dy=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function py(r){return r.match(dy)?.groups?.fingerprint}function my(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function ei(r){let e=r.stringTuples().filter(n=>n[0]===Xh).map(n=>n[1])[0];if(e===void 0||e==="")throw wo(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Kc(r){return te.decode(Fc.decode(r))}function gy(r){let t=Kc(ei(r)),e=$c(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 da(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function $c(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw ql(r)}}function yy(r,t){let{host:e,port:n}=r.toOptions(),o=my(r),[s]=gy(r);return`v=0
|
6
|
+
`)}`:`${e} :`}};xf=rr;O.Constructed=xf;rr.NAME="CONSTRUCTED";var gs=class extends Ut{fromBER(t,e,n){return e}toBER(t){return de}};gs.override="EndOfContentValueBlock";var Ef,ys=class extends Tt{constructor(t={}){super(t,gs),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}};Ef=ys;O.EndOfContent=Ef;ys.NAME=Hn;var vf,nr=class extends Tt{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}`}};vf=nr;O.Null=vf;nr.NAME="NULL";var ws=class extends He(Ut){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 Me(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,cc.call(this),this.blockLength=n,e+n):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}};ws.NAME="BooleanValueBlock";var Af,bs=class extends Tt{constructor(t={}){super(t,ws),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}`}};Af=bs;O.Boolean=Af;bs.NAME="BOOLEAN";var xs=class extends He(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===Hn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(i!==gf)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}}};xs.NAME="OctetStringValueBlock";var Sf,Pe=class r extends Tt{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},xs),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=js(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?rr.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)}};Sf=Pe;O.OctetString=Sf;Pe.NAME=gf;var Es=class extends He(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===Hn){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(c!==yf)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(!Me(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=js(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}}};Es.NAME="BitStringValueBlock";var Bf,on=class extends Tt{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},Es),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 rr.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)}`}}};Bf=on;O.BitString=Bf;on.NAME=yf;var If;function xg(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 p=u;p>=0;p--,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=ls(new Uint8Array([l%10]),s);break;default:s[i-f]=l%10}}return e[0]>0&&(s=ls(e,s)),s}function mf(r){if(r>=On.length)for(let t=On.length;t<=r;t++){let e=new Uint8Array([0]),n=On[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=ls(e,n)),On.push(n)}return On[r]}function Eg(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 Vn=class extends He(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=cc.call(this)))}set valueDec(t){this._valueDec=t,this.isHexOnly=!1,this.valueHexView=new Uint8Array(hf(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=Eg(mf(n),e),i="-";break;default:e=xg(e,mf(n))}n++,o>>=1}}for(let c=0;c<e.length;c++)e[c]&&(a=!0),a&&(i+=pf.charAt(e[c]));return a===!1&&(i+=pf.charAt(0)),i}};If=Vn;Vn.NAME="IntegerValueBlock";Object.defineProperty(If.prototype,"valueHex",{set:function(r){this.valueHexView=new Uint8Array(r),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});var _f,wt=class r extends Tt{constructor(t={}){super(t,Vn),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return us(),BigInt(this.valueBlock.toString())}static fromBigInt(t){us();let e=BigInt(t),n=new Mn,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()}`}};_f=wt;O.Integer=_f;wt.NAME="INTEGER";var kf,vs=class extends wt{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}};kf=vs;O.Enumerated=kf;vs.NAME="ENUMERATED";var Fn=class extends He(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=j.BufferSourceConverter.toUint8Array(t);if(!Me(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=kr(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),e+this.blockLength)}set valueBigInt(t){us();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=er(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=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}}};Fn.NAME="sidBlock";var As=class extends Ut{constructor({value:t=sn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Fn;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 lc(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 Fn;if(o>Number.MAX_SAFE_INTEGER){us();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}};As.NAME="ObjectIdentifierValueBlock";var Rf,he=class extends Tt{constructor(t={}){super(t,As),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()}}};Rf=he;O.ObjectIdentifier=Rf;he.NAME="OBJECT IDENTIFIER";var Kn=class extends He(Ue){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(!Me(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=kr(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=er(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=j.Convert.ToHex(this.valueHexView):t=this.valueDec.toString(),t}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}};Kn.NAME="relativeSidBlock";var Ss=class extends Ut{constructor({value:t=sn,...e}={}){super(e),this.value=[],t&&this.fromString(t)}fromBER(t,e,n){let o=e;for(;n>0;){let s=new Kn;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 lc(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 Kn;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}};Ss.NAME="RelativeObjectIdentifierValueBlock";var Cf,Bs=class extends Tt{constructor(t={}){super(t,Ss),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()}}};Cf=Bs;O.RelativeObjectIdentifier=Cf;Bs.NAME="RelativeObjectIdentifier";var Tf,It=class extends rr{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}};Tf=It;O.Sequence=Tf;It.NAME="SEQUENCE";var Nf,Is=class extends rr{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Nf=Is;O.Set=Nf;Is.NAME="SET";var _s=class extends He(Ut){constructor({...t}={}){super(t),this.isHexOnly=!0,this.value=sn}toJSON(){return{...super.toJSON(),value:this.value}}};_s.NAME="StringValueBlock";var ks=class extends _s{};ks.NAME="SimpleStringValueBlock";var Ot=class extends ds{constructor({...t}={}){super(t,ks)}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}};Ot.NAME="SIMPLE STRING";var Rs=class extends Ot{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}};Rs.NAME="Utf8StringValueBlock";var Lf,Oe=class extends Rs{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}};Lf=Oe;O.Utf8String=Lf;Oe.NAME="UTF8String";var Cs=class extends Ot{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))}};Cs.NAME="BmpStringValueBlock";var Df,Ts=class extends Cs{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}};Df=Ts;O.BmpString=Df;Ts.NAME="BMPString";var Ns=class extends Ot{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=er(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}};Ns.NAME="UniversalStringValueBlock";var Uf,Ls=class extends Ns{constructor({...t}={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}};Uf=Ls;O.UniversalString=Uf;Ls.NAME="UniversalString";var Pf,Ds=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}};Pf=Ds;O.NumericString=Pf;Ds.NAME="NumericString";var Of,Us=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}};Of=Us;O.PrintableString=Of;Us.NAME="PrintableString";var Mf,Ps=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}};Mf=Ps;O.TeletexString=Mf;Ps.NAME="TeletexString";var Hf,Os=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}};Hf=Os;O.VideotexString=Hf;Os.NAME="VideotexString";var Vf,Ms=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}};Vf=Ms;O.IA5String=Vf;Ms.NAME="IA5String";var Ff,Hs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}};Ff=Hs;O.GraphicString=Ff;Hs.NAME="GraphicString";var Kf,$n=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}};Kf=$n;O.VisibleString=Kf;$n.NAME="VisibleString";var $f,Vs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}};$f=Vs;O.GeneralString=$f;Vs.NAME="GeneralString";var Wf,Fs=class extends Ot{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}};Wf=Fs;O.CharacterString=Wf;Fs.NAME="CharacterString";var Gf,Wn=class extends $n{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}}};Gf=Wn;O.UTCTime=Gf;Wn.NAME="UTCTime";var qf,Ks=class extends Wn{constructor(t={}){var e;super(t),(e=this.millisecond)!==null&&e!==void 0||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(t){super.fromDate(t),this.millisecond=t.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(t){let e=!1,n="",o="",s=0,i,a=0,c=0;if(t[t.length-1]==="Z")n=t.substring(0,t.length-1),e=!0;else{let f=new Number(t[t.length-1]);if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");n=t}if(e){if(n.indexOf("+")!==-1)throw new Error("Wrong input string for conversion");if(n.indexOf("-")!==-1)throw new Error("Wrong input string for conversion")}else{let f=1,p=n.indexOf("+"),g="";if(p===-1&&(p=n.indexOf("-"),f=-1),p!==-1){if(g=n.substring(p+1),n=n.substring(0,p),g.length!==2&&g.length!==4)throw new Error("Wrong input string for conversion");let m=parseInt(g.substring(0,2),10);if(isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");if(a=f*m,g.length===4){if(m=parseInt(g.substring(2,4),10),isNaN(m.valueOf()))throw new Error("Wrong input string for conversion");c=f*m}}}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}}};qf=Ks;O.GeneralizedTime=qf;Ks.NAME="GeneralizedTime";var zf,$s=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}};zf=$s;O.DATE=zf;$s.NAME="DATE";var jf,Ws=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}};jf=Ws;O.TimeOfDay=jf;Ws.NAME="TimeOfDay";var Yf,Gs=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}};Yf=Gs;O.DateTime=Yf;Gs.NAME="DateTime";var Zf,qs=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}};Zf=qs;O.Duration=Zf;qs.NAME="Duration";var Xf,zs=class extends Oe{constructor(t={}){super(t),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}};Xf=zs;O.TIME=Xf;zs.NAME="TIME";function Ag(r){let{result:t}=an(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 Sg(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(Y(r.n,"base64url"))),wt.fromBigInt(ve(Y(r.e,"base64url"))),wt.fromBigInt(ve(Y(r.d,"base64url"))),wt.fromBigInt(ve(Y(r.p,"base64url"))),wt.fromBigInt(ve(Y(r.q,"base64url"))),wt.fromBigInt(ve(Y(r.dp,"base64url"))),wt.fromBigInt(ve(Y(r.dq,"base64url"))),wt.fromBigInt(ve(Y(r.qi,"base64url")))]}).toBER();return new Uint8Array(e,0,e.byteLength)}function Bg(r){let{result:t}=an(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 Ig(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 nr]}),new on({valueHex:new It({value:[wt.fromBigInt(ve(Y(r.n,"base64url"))),wt.fromBigInt(ve(Y(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 _g=16,fc=32,hc=1e4;async function kg(r,t){let e=Pt.get(),o=new It({value:[new wt({value:0}),new It({value:[new he({value:"1.2.840.113549.1.1.1"}),new nr]}),new Pe({valueHex:r.marshal()})]}).toBER(),s=new Uint8Array(o,0,o.byteLength),i=_r(_g),a=await ic(Cn,t,i,{c:hc,dkLen:fc}),c=_r(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 Pe({valueHex:i}),new wt({value:hc}),new wt({value:fc}),new It({value:[new he({value:"1.2.840.113549.2.11"}),new nr]})]}),p=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 Pe({valueHex:c})]})]})]}),m=new It({value:[p,new Pe({valueHex:u})]}).toBER(),h=new Uint8Array(m,0,m.byteLength);return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...G(h,"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join(`
|
7
|
+
`)}async function Rg(r,t){let e=Pt.get(),n;if(r.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){let o=Y(r.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=an(o),{iv:i,salt:a,iterations:c,keySize:l,cipherText:u}=Cg(s),f=await ic(Cn,t,a,{c,dkLen:l}),p=await e.subtle.importKey("raw",f,"AES-CBC",!1,["decrypt"]),g=Gn(await e.subtle.decrypt({name:"AES-CBC",iv:i},p,u)),{result:m}=an(g);n=Jf(m)}else if(r.includes("-----BEGIN PRIVATE KEY-----")){let o=Y(r.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:s}=an(o);n=Jf(s)}else throw new D("Could not parse private key from PEM data","ERR_INVALID_PARAMETERS");return dc(n)}function Cg(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=Gn(s.valueBlock.value[0].getValue()),a=hc,c=fc;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=Gn(l.valueBlock.value[1].getValue());return{cipherText:Gn(r.valueBlock.value[1].getValue()),salt:i,iterations:a,keySize:c,iv:f}}function Jf(r){return Gn(r.valueBlock.value[2].getValue())}function Gn(r){return new Uint8Array(r,0,r.byteLength)}async function Qf(r){let t=await Pt.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 rh(t);return{privateKey:e[0],publicKey:e[1]}}async function pc(r){let e=[await Pt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),await Tg(r)],n=await rh({privateKey:e[0],publicKey:e[1]});return{privateKey:n[0],publicKey:n[1]}}async function th(r,t){let e=await Pt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=await Pt.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},e,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}async function eh(r,t,e){let n=await Pt.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return Pt.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,e instanceof Uint8Array?e:e.subarray())}async function rh(r){if(r.privateKey==null||r.publicKey==null)throw new D("Private and public key are required","ERR_INVALID_PARAMETERS");return Promise.all([Pt.get().subtle.exportKey("jwk",r.privateKey),Pt.get().subtle.exportKey("jwk",r.publicKey)])}async function Tg(r){return Pt.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 Ys(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 Y(r.n,"base64url").length*8}var zn=8192,qn=class{_key;constructor(t){this._key=t}verify(t,e){return eh(this._key,e,t)}marshal(){return or.jwkToPkix(this._key)}get bytes(){return we.encode({Type:lt.RSA,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(t)?t.then(({bytes:e})=>e):t.bytes}},cn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e}genSecret(){return _r(16)}sign(t){return th(this._key,t)}get public(){if(this._publicKey==null)throw new D("public key not provided","ERR_PUBKEY_NOT_PROVIDED");return new qn(this._publicKey)}marshal(){return or.jwkToPkcs1(this._key)}get bytes(){return be.encode({Type:lt.RSA,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(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 or.exportToPem(this,t);if(e==="libp2p-key")return en(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};async function dc(r){let t=or.pkcs1ToJwk(r);if(Ys(t)>zn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let e=await pc(t);return new cn(e.privateKey,e.publicKey)}function Lg(r){let t=or.pkixToJwk(r);if(Ys(t)>zn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");return new qn(t)}async function Dg(r){if(Ys(r)>zn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await pc(r);return new cn(t.privateKey,t.publicKey)}async function Ug(r){if(r>zn)throw new D("key size is too large","ERR_KEY_SIZE_TOO_LARGE");let t=await Qf(r);return new cn(t.privateKey,t.publicKey)}var xc={};bt(xc,{Secp256k1PrivateKey:()=>Yn,Secp256k1PublicKey:()=>jn,generateKeyPair:()=>jg,unmarshalSecp256k1PrivateKey:()=>qg,unmarshalSecp256k1PublicKey:()=>zg});var Pg=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]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ir=new Uint32Array(64),gc=class extends Zr{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[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)ir[f]=t.getUint32(e,!1);for(let f=16;f<64;f++){let p=ir[f-15],g=ir[f-2],m=ae(p,7)^ae(p,18)^p>>>3,h=ae(g,17)^ae(g,19)^g>>>10;ir[f]=h+ir[f-7]+m+ir[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 p=ae(a,6)^ae(a,11)^ae(a,25),g=u+p+Hu(a,c,l)+Pg[f]+ir[f]|0,h=(ae(n,2)^ae(n,13)^ae(n,22))+Vu(n,o,s)|0;u=l,l=c,c=a,a=i+g|0,i=s,s=o,o=n,n=g+h|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(){ir.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var ln=Zo(()=>new gc);function nh(r){r.lowS!==void 0&&le("lowS",r.lowS),r.prehash!==void 0&&le("prehash",r.prehash)}function Og(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:Mg,hexToBytes:Hg}=Qo,Rr={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(r){let{Err:t}=Rr;if(r.length<2||r[0]!==2)throw new t("Invalid signature integer tag");let e=r[1],n=r.subarray(2,e+2);if(!e||n.length!==e)throw new t("Invalid signature integer: wrong length");if(n[0]&128)throw new t("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new t("Invalid signature integer: unnecessary leading zero");return{d:Mg(n),l:r.subarray(e+2)}},toSig(r){let{Err:t}=Rr,e=typeof r=="string"?Hg(r):r;Xr(e);let n=e.length;if(n<2||e[0]!=48)throw new t("Invalid signature tag");if(e[1]!==n-2)throw new t("Invalid signature: incorrect length");let{d:o,l:s}=Rr._parseInt(e.subarray(2)),{d:i,l:a}=Rr._parseInt(s);if(a.length)throw new t("Invalid signature: left bytes after parsing");return{r:o,s:i}},hexFromSig(r){let t=l=>Number.parseInt(l[0],16)&8?"00"+l:l,e=l=>{let u=l.toString(16);return u.length&1?`0${u}`:u},n=t(e(r.s)),o=t(e(r.r)),s=n.length/2,i=o.length/2,a=e(s),c=e(i);return`30${e(i+s+4)}02${c}${o}02${a}${n}`}},ar=BigInt(0),_t=BigInt(1),DA=BigInt(2),oh=BigInt(3),UA=BigInt(4);function Vg(r){let t=Og(r),{Fp:e}=t,n=t.toBytes||((m,h,d)=>{let x=h.toAffine();return Ne(Uint8Array.from([4]),e.toBytes(x.x),e.toBytes(x.y))}),o=t.fromBytes||(m=>{let h=m.subarray(1),d=e.fromBytes(h.subarray(0,e.BYTES)),x=e.fromBytes(h.subarray(e.BYTES,2*e.BYTES));return{x:d,y:x}});function s(m){let{a:h,b:d}=t,x=e.sqr(m),w=e.mul(x,m);return e.add(e.add(w,e.mul(m,h)),d)}if(!e.eql(e.sqr(t.Gy),s(t.Gx)))throw new Error("bad generator point: equation left != right");function i(m){return Tn(m,_t,t.n)}function a(m){let{allowedPrivateKeyLengths:h,nByteLength:d,wrapPrivateKey:x,n:w}=t;if(h&&typeof m!="bigint"){if(Je(m)&&(m=Re(m)),typeof m!="string"||!h.includes(m.length))throw new Error("Invalid key");m=m.padStart(d*2,"0")}let b;try{b=typeof m=="bigint"?m:Ce(st("private key",m,d))}catch{throw new Error(`private key must be ${d} bytes, hex or bigint, not ${typeof m}`)}return x&&(b=J(b,w)),Ct("private key",b,_t,w),b}function c(m){if(!(m instanceof f))throw new Error("ProjectivePoint expected")}let l=Sr((m,h)=>{let{px:d,py:x,pz:w}=m;if(e.eql(w,e.ONE))return{x:d,y:x};let b=m.is0();h==null&&(h=b?e.ONE:e.inv(w));let I=e.mul(d,h),C=e.mul(x,h),S=e.mul(w,h);if(b)return{x:e.ZERO,y:e.ZERO};if(!e.eql(S,e.ONE))throw new Error("invZ was invalid");return{x:I,y:C}}),u=Sr(m=>{if(m.is0()){if(t.allowInfinityPoint&&!e.is0(m.py))return;throw new Error("bad point: ZERO")}let{x:h,y:d}=m.toAffine();if(!e.isValid(h)||!e.isValid(d))throw new Error("bad point: x or y not FE");let x=e.sqr(d),w=s(h);if(!e.eql(x,w))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class f{constructor(h,d,x){if(this.px=h,this.py=d,this.pz=x,h==null||!e.isValid(h))throw new Error("x required");if(d==null||!e.isValid(d))throw new Error("y required");if(x==null||!e.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(h){let{x:d,y:x}=h||{};if(!h||!e.isValid(d)||!e.isValid(x))throw new Error("invalid affine point");if(h instanceof f)throw new Error("projective point not allowed");let w=b=>e.eql(b,e.ZERO);return w(d)&&w(x)?f.ZERO:new f(d,x,e.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(h){let d=e.invertBatch(h.map(x=>x.pz));return h.map((x,w)=>x.toAffine(d[w])).map(f.fromAffine)}static fromHex(h){let d=f.fromAffine(o(st("pointHex",h)));return d.assertValidity(),d}static fromPrivateKey(h){return f.BASE.multiply(a(h))}_setWindowSize(h){g.setWindowSize(this,h)}assertValidity(){u(this)}hasEvenY(){let{y:h}=this.toAffine();if(e.isOdd)return!e.isOdd(h);throw new Error("Field doesn't support isOdd")}equals(h){c(h);let{px:d,py:x,pz:w}=this,{px:b,py:I,pz:C}=h,S=e.eql(e.mul(d,C),e.mul(b,w)),B=e.eql(e.mul(x,C),e.mul(I,w));return S&&B}negate(){return new f(this.px,e.neg(this.py),this.pz)}double(){let{a:h,b:d}=t,x=e.mul(d,oh),{px:w,py:b,pz:I}=this,C=e.ZERO,S=e.ZERO,B=e.ZERO,_=e.mul(w,w),P=e.mul(b,b),N=e.mul(I,I),T=e.mul(w,b);return T=e.add(T,T),B=e.mul(w,I),B=e.add(B,B),C=e.mul(h,B),S=e.mul(x,N),S=e.add(C,S),C=e.sub(P,S),S=e.add(P,S),S=e.mul(C,S),C=e.mul(T,C),B=e.mul(x,B),N=e.mul(h,N),T=e.sub(_,N),T=e.mul(h,T),T=e.add(T,B),B=e.add(_,_),_=e.add(B,_),_=e.add(_,N),_=e.mul(_,T),S=e.add(S,_),N=e.mul(b,I),N=e.add(N,N),_=e.mul(N,T),C=e.sub(C,_),B=e.mul(N,P),B=e.add(B,B),B=e.add(B,B),new f(C,S,B)}add(h){c(h);let{px:d,py:x,pz:w}=this,{px:b,py:I,pz:C}=h,S=e.ZERO,B=e.ZERO,_=e.ZERO,P=t.a,N=e.mul(t.b,oh),T=e.mul(d,b),F=e.mul(x,I),W=e.mul(w,C),R=e.add(d,x),E=e.add(b,I);R=e.mul(R,E),E=e.add(T,F),R=e.sub(R,E),E=e.add(d,w);let y=e.add(b,C);return E=e.mul(E,y),y=e.add(T,W),E=e.sub(E,y),y=e.add(x,w),S=e.add(I,C),y=e.mul(y,S),S=e.add(F,W),y=e.sub(y,S),_=e.mul(P,E),S=e.mul(N,W),_=e.add(S,_),S=e.sub(F,_),_=e.add(F,_),B=e.mul(S,_),F=e.add(T,T),F=e.add(F,T),W=e.mul(P,W),E=e.mul(N,E),F=e.add(F,W),W=e.sub(T,W),W=e.mul(P,W),E=e.add(E,W),T=e.mul(F,E),B=e.add(B,T),T=e.mul(y,E),S=e.mul(R,S),S=e.sub(S,T),T=e.mul(R,F),_=e.mul(y,_),_=e.add(_,T),new f(S,B,_)}subtract(h){return this.add(h.negate())}is0(){return this.equals(f.ZERO)}wNAF(h){return g.wNAFCached(this,h,f.normalizeZ)}multiplyUnsafe(h){Ct("scalar",h,ar,t.n);let d=f.ZERO;if(h===ar)return d;if(h===_t)return this;let{endo:x}=t;if(!x)return g.unsafeLadder(this,h);let{k1neg:w,k1:b,k2neg:I,k2:C}=x.splitScalar(h),S=d,B=d,_=this;for(;b>ar||C>ar;)b&_t&&(S=S.add(_)),C&_t&&(B=B.add(_)),_=_.double(),b>>=_t,C>>=_t;return w&&(S=S.negate()),I&&(B=B.negate()),B=new f(e.mul(B.px,x.beta),B.py,B.pz),S.add(B)}multiply(h){let{endo:d,n:x}=t;Ct("scalar",h,_t,x);let w,b;if(d){let{k1neg:I,k1:C,k2neg:S,k2:B}=d.splitScalar(h),{p:_,f:P}=this.wNAF(C),{p:N,f:T}=this.wNAF(B);_=g.constTimeNegate(I,_),N=g.constTimeNegate(S,N),N=new f(e.mul(N.px,d.beta),N.py,N.pz),w=_.add(N),b=P.add(T)}else{let{p:I,f:C}=this.wNAF(h);w=I,b=C}return f.normalizeZ([w,b])[0]}multiplyAndAddUnsafe(h,d,x){let w=f.BASE,b=(C,S)=>S===ar||S===_t||!C.equals(w)?C.multiplyUnsafe(S):C.multiply(S),I=b(this,d).add(b(h,x));return I.is0()?void 0:I}toAffine(h){return l(this,h)}isTorsionFree(){let{h,isTorsionFree:d}=t;if(h===_t)return!0;if(d)return d(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h,clearCofactor:d}=t;return h===_t?this:d?d(f,this):this.multiplyUnsafe(t.h)}toRawBytes(h=!0){return le("isCompressed",h),this.assertValidity(),n(f,this,h)}toHex(h=!0){return le("isCompressed",h),Re(this.toRawBytes(h))}}f.BASE=new f(t.Gx,t.Gy,e.ONE),f.ZERO=new f(e.ZERO,e.ONE,e.ZERO);let p=t.nBitLength,g=rs(f,t.endo?Math.ceil(p/2):p);return{CURVE:t,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:s,isWithinCurveOrder:i}}function Fg(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 sh(r){let t=Fg(r),{Fp:e,n}=t,o=e.BYTES+1,s=2*e.BYTES+1;function i(R){return J(R,n)}function a(R){return ts(R,n)}let{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:u,isWithinCurveOrder:f}=Vg({...t,toBytes(R,E,y){let A=E.toAffine(),k=e.toBytes(A.x),v=Ne;return le("isCompressed",y),y?v(Uint8Array.from([E.hasEvenY()?2:3]),k):v(Uint8Array.from([4]),k,e.toBytes(A.y))},fromBytes(R){let E=R.length,y=R[0],A=R.subarray(1);if(E===o&&(y===2||y===3)){let k=Ce(A);if(!Tn(k,_t,e.ORDER))throw new Error("Point is not on curve");let v=u(k),L;try{L=e.sqrt(v)}catch($){let q=$ instanceof Error?": "+$.message:"";throw new Error("Point is not on curve"+q)}let M=(L&_t)===_t;return(y&1)===1!==M&&(L=e.neg(L)),{x:k,y:L}}else if(E===s&&y===4){let k=e.fromBytes(A.subarray(0,e.BYTES)),v=e.fromBytes(A.subarray(e.BYTES,2*e.BYTES));return{x:k,y:v}}else throw new Error(`Point of length ${E} was invalid. Expected ${o} compressed bytes or ${s} uncompressed bytes`)}}),p=R=>Re(Qe(R,t.nByteLength));function g(R){let E=n>>_t;return R>E}function m(R){return g(R)?i(-R):R}let h=(R,E,y)=>Ce(R.slice(E,y));class d{constructor(E,y,A){this.r=E,this.s=y,this.recovery=A,this.assertValidity()}static fromCompact(E){let y=t.nByteLength;return E=st("compactSignature",E,y*2),new d(h(E,0,y),h(E,y,2*y))}static fromDER(E){let{r:y,s:A}=Rr.toSig(st("DER",E));return new d(y,A)}assertValidity(){Ct("r",this.r,_t,n),Ct("s",this.s,_t,n)}addRecoveryBit(E){return new d(this.r,this.s,E)}recoverPublicKey(E){let{r:y,s:A,recovery:k}=this,v=S(st("msgHash",E));if(k==null||![0,1,2,3].includes(k))throw new Error("recovery id invalid");let L=k===2||k===3?y+t.n:y;if(L>=e.ORDER)throw new Error("recovery id 2 or 3 invalid");let M=k&1?"03":"02",V=c.fromHex(M+p(L)),$=a(L),q=i(-v*$),Z=i(A*$),Q=c.BASE.multiplyAndAddUnsafe(V,q,Z);if(!Q)throw new Error("point at infinify");return Q.assertValidity(),Q}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new d(this.r,i(-this.s),this.recovery):this}toDERRawBytes(){return Ar(this.toDERHex())}toDERHex(){return Rr.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Ar(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let x={isValidPrivateKey(R){try{return l(R),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{let R=Qa(t.n);return Yu(t.randomBytes(R),t.n)},precompute(R=8,E=c.BASE){return E._setWindowSize(R),E.multiply(BigInt(3)),E}};function w(R,E=!0){return c.fromPrivateKey(R).toRawBytes(E)}function b(R){let E=Je(R),y=typeof R=="string",A=(E||y)&&R.length;return E?A===o||A===s:y?A===2*o||A===2*s:R instanceof c}function I(R,E,y=!0){if(b(R))throw new Error("first arg must be private key");if(!b(E))throw new Error("second arg must be public key");return c.fromHex(E).multiply(l(R)).toRawBytes(y)}let C=t.bits2int||function(R){let E=Ce(R),y=R.length*8-t.nBitLength;return y>0?E>>BigInt(y):E},S=t.bits2int_modN||function(R){return i(C(R))},B=Nn(t.nBitLength);function _(R){return Ct(`num < 2^${t.nBitLength}`,R,ar,B),Qe(R,t.nByteLength)}function P(R,E,y=N){if(["recovered","canonical"].some(ot=>ot in y))throw new Error("sign() legacy options not supported");let{hash:A,randomBytes:k}=t,{lowS:v,prehash:L,extraEntropy:M}=y;v==null&&(v=!0),R=st("msgHash",R),nh(y),L&&(R=st("prehashed msgHash",A(R)));let V=S(R),$=l(E),q=[_($),_(V)];if(M!=null&&M!==!1){let ot=M===!0?k(e.BYTES):M;q.push(st("extraEntropy",ot))}let Z=Ne(...q),Q=V;function ht(ot){let nt=C(ot);if(!f(nt))return;let Jt=a(nt),Bt=c.BASE.multiply(nt).toAffine(),Qt=i(Bt.x);if(Qt===ar)return;let cr=i(Jt*i(Q+Qt*$));if(cr===ar)return;let pn=(Bt.x===Qt?0:2)|Number(Bt.y&_t),to=cr;return v&&g(cr)&&(to=m(cr),pn^=1),new d(Qt,to,pn)}return{seed:Z,k2sig:ht}}let N={lowS:t.lowS,prehash:!1},T={lowS:t.lowS,prehash:!1};function F(R,E,y=N){let{seed:A,k2sig:k}=P(R,E,y),v=t;return ja(v.hash.outputLen,v.nByteLength,v.hmac)(A,k)}c.BASE._setWindowSize(8);function W(R,E,y,A=T){let k=R;if(E=st("msgHash",E),y=st("publicKey",y),"strict"in A)throw new Error("options.strict was renamed to lowS");nh(A);let{lowS:v,prehash:L}=A,M,V;try{if(typeof k=="string"||Je(k))try{M=d.fromDER(k)}catch(Bt){if(!(Bt instanceof Rr.Err))throw Bt;M=d.fromCompact(k)}else if(typeof k=="object"&&typeof k.r=="bigint"&&typeof k.s=="bigint"){let{r:Bt,s:Qt}=k;M=new d(Bt,Qt)}else throw new Error("PARSE");V=c.fromHex(y)}catch(Bt){if(Bt.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(v&&M.hasHighS())return!1;L&&(E=t.hash(E));let{r:$,s:q}=M,Z=S(E),Q=a(q),ht=i(Z*Q),ot=i($*Q),nt=c.BASE.multiplyAndAddUnsafe(V,ht,ot)?.toAffine();return nt?i(nt.x)===$:!1}return{CURVE:t,getPublicKey:w,getSharedSecret:I,sign:F,verify:W,ProjectivePoint:c,Signature:d,utils:x}}function Kg(r){return{hash:r,hmac:(t,...e)=>tr(r,t,Fa(...e)),randomBytes:vr}}function ih(r,t){let e=n=>sh({...r,...Kg(n)});return Object.freeze({...e(t),create:e})}var lh=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),ah=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),$g=BigInt(1),yc=BigInt(2),ch=(r,t)=>(r+t/yc)/t;function Wg(r){let t=lh,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=it(u,e,t)*u%t,p=it(f,e,t)*u%t,g=it(p,yc,t)*l%t,m=it(g,o,t)*g%t,h=it(m,s,t)*m%t,d=it(h,a,t)*h%t,x=it(d,c,t)*d%t,w=it(x,a,t)*h%t,b=it(w,e,t)*u%t,I=it(b,i,t)*m%t,C=it(I,n,t)*l%t,S=it(C,yc,t);if(!wc.eql(wc.sqr(S),r))throw new Error("Cannot find square root");return S}var wc=es(lh,void 0,void 0,{sqrt:Wg}),pe=ih({a:BigInt(0),b:BigInt(7),Fp:wc,n:ah,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:r=>{let t=ah,e=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-$g*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=e,i=BigInt("0x100000000000000000000000000000000"),a=ch(s*r,t),c=ch(-n*r,t),l=J(r-a*e-c*o,t),u=J(-a*n-c*s,t),f=l>i,p=u>i;if(f&&(l=t-l),p&&(u=t-u),l>i||u>i)throw new Error("splitScalar: Endomorphism failed, k="+r);return{k1neg:f,k1:l,k2neg:p,k2:u}}}},ln),WA=BigInt(0);var GA=pe.ProjectivePoint;function uh(){return pe.utils.randomPrivateKey()}function fh(r,t){let e=kt.digest(t instanceof Uint8Array?t:t.subarray());if(Yt(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 hh(r,t,e){let n=kt.digest(e instanceof Uint8Array?e:e.subarray());if(Yt(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 dh(r){return pe.ProjectivePoint.fromHex(r).toRawBytes(!0)}function ph(r){try{pe.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}function bc(r){try{pe.ProjectivePoint.fromHex(r)}catch(t){throw new D(String(t),"ERR_INVALID_PUBLIC_KEY")}}function mh(r){try{return pe.getPublicKey(r,!0)}catch(t){throw new D(String(t),"ERR_INVALID_PRIVATE_KEY")}}var jn=class{_key;constructor(t){bc(t),this._key=t}verify(t,e){return hh(this._key,e,t)}marshal(){return dh(this._key)}get bytes(){return we.encode({Type:lt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}async hash(){let t=kt.digest(this.bytes),e;return Yt(t)?{bytes:e}=await t:e=t.bytes,e}},Yn=class{_key;_publicKey;constructor(t,e){this._key=t,this._publicKey=e??mh(t),ph(this._key),bc(this._publicKey)}sign(t){return fh(this._key,t)}get public(){return new jn(this._publicKey)}marshal(){return this._key}get bytes(){return be.encode({Type:lt.Secp256k1,Data:this.marshal()}).subarray()}equals(t){return xt(this.bytes,t.bytes)}hash(){let t=kt.digest(this.bytes);return Yt(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 en(this.bytes,t);throw new D(`export format '${e}' is not supported`,"ERR_INVALID_EXPORT_FORMAT")}};function qg(r){return new Yn(r)}function zg(r){return new jn(r)}async function jg(){let r=uh();return new Yn(r)}var Cr={rsa:mc,ed25519:sc,secp256k1:xc};function gh(r){let t=Object.keys(Cr).join(" / ");return new D(`invalid or unsupported key type ${r}. Must be ${t}`,"ERR_UNSUPPORTED_KEY_TYPE")}function yh(r){let t=we.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case lt.RSA:return Cr.rsa.unmarshalRsaPublicKey(e);case lt.Ed25519:return Cr.ed25519.unmarshalEd25519PublicKey(e);case lt.Secp256k1:return Cr.secp256k1.unmarshalSecp256k1PublicKey(e);default:throw gh(t.Type??"unknown")}}async function Ec(r){let t=be.decode(r),e=t.Data??new Uint8Array;switch(t.Type){case lt.RSA:return Cr.rsa.unmarshalRsaPrivateKey(e);case lt.Ed25519:return Cr.ed25519.unmarshalEd25519PrivateKey(e);case lt.Secp256k1:return Cr.secp256k1.unmarshalSecp256k1PrivateKey(e);default:throw gh(t.Type??"RSA")}}function vc(){let r=ft(),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 wh(){let r=vc(),t=vc();return[{source:r.source,sink:t.sink},{source:t.source,sink:r.sink}]}function Yg(r){return r[Symbol.asyncIterator]!=null}function Zg(...r){let t=[];for(let e of r)Yg(e)||t.push(e);return t.length===r.length?function*(){for(let e of t)yield*e}():async function*(){let e=Ge({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 bh=Zg;function xh(r,...t){if(r==null)throw new Error("Empty pipeline");if(Ac(r)){let n=r;r=()=>n.source}else if(vh(r)||Eh(r)){let n=r;r=()=>n}let e=[r,...t];if(e.length>1&&Ac(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++)Ac(e[n])&&(e[n]=Jg(e[n]));return Xg(...e)}var Xg=(...r)=>{let t;for(;r.length>0;)t=r.shift()(t);return t},Eh=r=>r?.[Symbol.asyncIterator]!=null,vh=r=>r?.[Symbol.iterator]!=null,Ac=r=>r==null?!1:r.sink!=null&&r.source!=null,Jg=r=>t=>{let e=r.sink(t);if(e?.then!=null){let n=Ge({objectMode:!0});e.then(()=>{n.end()},i=>{n.end(i)});let o,s=r.source;if(Eh(s))o=async function*(){yield*s,n.end()};else if(vh(s))o=function*(){yield*s,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return bh(n,o())}return r.source};var un=!!globalThis.process?.env?.DUMP_SESSION_KEYS;function Zs(r){if(!Number.isSafeInteger(r)||r<0)throw new Error(`positive integer expected, not ${r}`)}function Sc(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function Bc(r){return r instanceof Uint8Array||r!=null&&typeof r=="object"&&r.constructor.name==="Uint8Array"}function Kt(r,...t){if(!Bc(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 Ic(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 Ah(r,t){Kt(r);let e=t.outputLen;if(r.length<e)throw new Error(`digestInto() expects output buffer of length at least ${e}`)}var Ve=r=>new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4)),Sh=r=>new DataView(r.buffer,r.byteOffset,r.byteLength),Qg=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!Qg)throw new Error("Non little-endian hardware is not supported");function ty(r){if(typeof r!="string")throw new Error(`string expected, got ${typeof r}`);return new Uint8Array(new TextEncoder().encode(r))}function Xs(r){if(typeof r=="string")r=ty(r);else if(Bc(r))r=Js(r);else throw new Error(`Uint8Array expected, got ${typeof r}`);return r}function Bh(r,t){if(t==null||typeof t!="object")throw new Error("options must be defined");return Object.assign(r,t)}function Ih(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 _c=(r,t)=>(Object.assign(t,r),t);function kc(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 Js(r){return Uint8Array.from(r)}function Fe(...r){for(let t=0;t<r.length;t++)r[t].fill(0)}var kh=r=>Uint8Array.from(r.split("").map(t=>t.charCodeAt(0))),ey=kh("expand 16-byte k"),ry=kh("expand 32-byte k"),ny=Ve(ey),Rh=Ve(ry),xS=Rh.slice();function H(r,t){return r<<t|r>>>32-t}function Rc(r){return r.byteOffset%4===0}var Qs=64,oy=16,Ch=2**32-1,_h=new Uint32Array;function sy(r,t,e,n,o,s,i,a){let c=o.length,l=new Uint8Array(Qs),u=Ve(l),f=Rc(o)&&Rc(s),p=f?Ve(o):_h,g=f?Ve(s):_h;for(let m=0;m<c;i++){if(r(t,e,n,u,i,a),i>=Ch)throw new Error("arx: counter overflow");let h=Math.min(Qs,c-m);if(f&&h===Qs){let d=m/4;if(m%4!==0)throw new Error("arx: invalid block position");for(let x=0,w;x<oy;x++)w=d+x,g[w]=p[w]^u[x];m+=Qs;continue}for(let d=0,x;d<h;d++)x=m+d,s[x]=o[x]^l[d];m+=h}}function Cc(r,t){let{allowShortKeys:e,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Bh({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof r!="function")throw new Error("core must be a function");return Zs(o),Zs(i),Sc(s),Sc(e),(a,c,l,u,f=0)=>{Kt(a),Kt(c),Kt(l);let p=l.length;if(u===void 0&&(u=new Uint8Array(p)),Kt(u),Zs(f),f<0||f>=Ch)throw new Error("arx: counter overflow");if(u.length<p)throw new Error(`arx: output (${u.length}) is shorter than data (${p})`);let g=[],m=a.length,h,d;if(m===32)g.push(h=Js(a)),d=Rh;else if(m===16&&e)h=new Uint8Array(32),h.set(a),h.set(a,16),d=ny,g.push(h);else throw new Error(`arx: invalid 32-byte key, got length=${m}`);Rc(c)||g.push(c=Js(c));let x=Ve(h);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(d,x,Ve(c.subarray(0,16)),x),c=c.subarray(16)}let w=16-o;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let I=new Uint8Array(12);I.set(c,s?0:12-c.length),c=I,g.push(c)}let b=Ve(c);return sy(r,d,x,b,l,u,f,i),Fe(...g),u}}var Nt=(r,t)=>r[t++]&255|(r[t++]&255)<<8,Tc=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=Xs(t),Kt(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],p=i[5],g=i[6],m=i[7],h=i[8],d=i[9],x=Nt(t,e+0),w=Nt(t,e+2),b=Nt(t,e+4),I=Nt(t,e+6),C=Nt(t,e+8),S=Nt(t,e+10),B=Nt(t,e+12),_=Nt(t,e+14),P=s[0]+(x&8191),N=s[1]+((x>>>13|w<<3)&8191),T=s[2]+((w>>>10|b<<6)&8191),F=s[3]+((b>>>7|I<<9)&8191),W=s[4]+((I>>>4|C<<12)&8191),R=s[5]+(C>>>1&8191),E=s[6]+((C>>>14|S<<2)&8191),y=s[7]+((S>>>11|B<<5)&8191),A=s[8]+((B>>>8|_<<8)&8191),k=s[9]+(_>>>5|o),v=0,L=v+P*a+N*(5*d)+T*(5*h)+F*(5*m)+W*(5*g);v=L>>>13,L&=8191,L+=R*(5*p)+E*(5*f)+y*(5*u)+A*(5*l)+k*(5*c),v+=L>>>13,L&=8191;let M=v+P*c+N*a+T*(5*d)+F*(5*h)+W*(5*m);v=M>>>13,M&=8191,M+=R*(5*g)+E*(5*p)+y*(5*f)+A*(5*u)+k*(5*l),v+=M>>>13,M&=8191;let V=v+P*l+N*c+T*a+F*(5*d)+W*(5*h);v=V>>>13,V&=8191,V+=R*(5*m)+E*(5*g)+y*(5*p)+A*(5*f)+k*(5*u),v+=V>>>13,V&=8191;let $=v+P*u+N*l+T*c+F*a+W*(5*d);v=$>>>13,$&=8191,$+=R*(5*h)+E*(5*m)+y*(5*g)+A*(5*p)+k*(5*f),v+=$>>>13,$&=8191;let q=v+P*f+N*u+T*l+F*c+W*a;v=q>>>13,q&=8191,q+=R*(5*d)+E*(5*h)+y*(5*m)+A*(5*g)+k*(5*p),v+=q>>>13,q&=8191;let Z=v+P*p+N*f+T*u+F*l+W*c;v=Z>>>13,Z&=8191,Z+=R*a+E*(5*d)+y*(5*h)+A*(5*m)+k*(5*g),v+=Z>>>13,Z&=8191;let Q=v+P*g+N*p+T*f+F*u+W*l;v=Q>>>13,Q&=8191,Q+=R*c+E*a+y*(5*d)+A*(5*h)+k*(5*m),v+=Q>>>13,Q&=8191;let ht=v+P*m+N*g+T*p+F*f+W*u;v=ht>>>13,ht&=8191,ht+=R*l+E*c+y*a+A*(5*d)+k*(5*h),v+=ht>>>13,ht&=8191;let ot=v+P*h+N*m+T*g+F*p+W*f;v=ot>>>13,ot&=8191,ot+=R*u+E*l+y*c+A*a+k*(5*d),v+=ot>>>13,ot&=8191;let nt=v+P*d+N*h+T*m+F*g+W*p;v=nt>>>13,nt&=8191,nt+=R*f+E*u+y*l+A*c+k*a,v+=nt>>>13,nt&=8191,v=(v<<2)+v|0,v=v+L|0,L=v&8191,v=v>>>13,M+=v,s[0]=L,s[1]=M,s[2]=V,s[3]=$,s[4]=q,s[5]=Z,s[6]=Q,s[7]=ht,s[8]=ot,s[9]=nt}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;Fe(n)}update(t){Ic(this);let{buffer:e,blockLen:n}=this;t=Xs(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(){Fe(this.h,this.r,this.buffer,this.pad)}digestInto(t){Ic(this),Ah(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 iy(r){let t=(n,o)=>r(o).update(Xs(n)).digest(),e=r(new Uint8Array(32));return t.outputLen=e.outputLen,t.blockLen=e.blockLen,t.create=n=>r(n),t}var Th=iy(r=>new Tc(r));function Dh(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],p=t[2],g=t[3],m=t[4],h=t[5],d=t[6],x=t[7],w=o,b=e[0],I=e[1],C=e[2],S=i,B=a,_=c,P=l,N=u,T=f,F=p,W=g,R=m,E=h,y=d,A=x,k=w,v=b,L=I,M=C;for(let $=0;$<s;$+=2)S=S+N|0,k=H(k^S,16),R=R+k|0,N=H(N^R,12),S=S+N|0,k=H(k^S,8),R=R+k|0,N=H(N^R,7),B=B+T|0,v=H(v^B,16),E=E+v|0,T=H(T^E,12),B=B+T|0,v=H(v^B,8),E=E+v|0,T=H(T^E,7),_=_+F|0,L=H(L^_,16),y=y+L|0,F=H(F^y,12),_=_+F|0,L=H(L^_,8),y=y+L|0,F=H(F^y,7),P=P+W|0,M=H(M^P,16),A=A+M|0,W=H(W^A,12),P=P+W|0,M=H(M^P,8),A=A+M|0,W=H(W^A,7),S=S+T|0,M=H(M^S,16),y=y+M|0,T=H(T^y,12),S=S+T|0,M=H(M^S,8),y=y+M|0,T=H(T^y,7),B=B+F|0,k=H(k^B,16),A=A+k|0,F=H(F^A,12),B=B+F|0,k=H(k^B,8),A=A+k|0,F=H(F^A,7),_=_+W|0,v=H(v^_,16),R=R+v|0,W=H(W^R,12),_=_+W|0,v=H(v^_,8),R=R+v|0,W=H(W^R,7),P=P+N|0,L=H(L^P,16),E=E+L|0,N=H(N^E,12),P=P+N|0,L=H(L^P,8),E=E+L|0,N=H(N^E,7);let V=0;n[V++]=i+S|0,n[V++]=a+B|0,n[V++]=c+_|0,n[V++]=l+P|0,n[V++]=u+N|0,n[V++]=f+T|0,n[V++]=p+F|0,n[V++]=g+W|0,n[V++]=m+R|0,n[V++]=h+E|0,n[V++]=d+y|0,n[V++]=x+A|0,n[V++]=w+k|0,n[V++]=b+v|0,n[V++]=I+L|0,n[V++]=C+M|0}function ay(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],p=t[4],g=t[5],m=t[6],h=t[7],d=e[0],x=e[1],w=e[2],b=e[3];for(let C=0;C<20;C+=2)o=o+c|0,d=H(d^o,16),p=p+d|0,c=H(c^p,12),o=o+c|0,d=H(d^o,8),p=p+d|0,c=H(c^p,7),s=s+l|0,x=H(x^s,16),g=g+x|0,l=H(l^g,12),s=s+l|0,x=H(x^s,8),g=g+x|0,l=H(l^g,7),i=i+u|0,w=H(w^i,16),m=m+w|0,u=H(u^m,12),i=i+u|0,w=H(w^i,8),m=m+w|0,u=H(u^m,7),a=a+f|0,b=H(b^a,16),h=h+b|0,f=H(f^h,12),a=a+f|0,b=H(b^a,8),h=h+b|0,f=H(f^h,7),o=o+l|0,b=H(b^o,16),m=m+b|0,l=H(l^m,12),o=o+l|0,b=H(b^o,8),m=m+b|0,l=H(l^m,7),s=s+u|0,d=H(d^s,16),h=h+d|0,u=H(u^h,12),s=s+u|0,d=H(d^s,8),h=h+d|0,u=H(u^h,7),i=i+f|0,x=H(x^i,16),p=p+x|0,f=H(f^p,12),i=i+f|0,x=H(x^i,8),p=p+x|0,f=H(f^p,7),a=a+c|0,w=H(w^a,16),g=g+w|0,c=H(c^g,12),a=a+c|0,w=H(w^a,8),g=g+w|0,c=H(c^g,7);let I=0;n[I++]=o,n[I++]=s,n[I++]=i,n[I++]=a,n[I++]=d,n[I++]=x,n[I++]=w,n[I++]=b}var cy=Cc(Dh,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ly=Cc(Dh,{counterRight:!1,counterLength:8,extendNonceFn:ay,allowShortKeys:!1});var uy=new Uint8Array(16),Nh=(r,t)=>{r.update(t);let e=t.length%16;e&&r.update(uy.subarray(e))},fy=new Uint8Array(32);function Lh(r,t,e,n,o){let s=r(t,e,fy),i=Th.create(s);o&&Nh(i,o),Nh(i,n);let a=new Uint8Array(16),c=Sh(a);kc(c,0,BigInt(o?o.length:0),!0),kc(c,8,BigInt(n.length),!0),i.update(a);let l=i.digest();return Fe(s,a),l}var Uh=r=>(t,e,n)=>(Kt(t,32),Kt(e),{encrypt(s,i){let a=s.length,c=a+16;i?Kt(i,c):i=new Uint8Array(c),r(t,e,s,i,1);let l=Lh(r,t,e,i.subarray(0,-16),n);return i.set(l,a),Fe(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?Kt(i,c):i=new Uint8Array(c);let l=s.subarray(0,-16),u=s.subarray(-16),f=Lh(r,t,e,l,n);if(!Ih(u,f))throw new Error("invalid tag");return r(t,e,l,i,1),Fe(f),i}}),Nc=_c({blockSize:64,nonceLength:12,tagLength:16},Uh(cy)),RS=_c({blockSize:64,nonceLength:24,tagLength:16},Uh(ly));function Oh(r,t,e){return Er(r),e===void 0&&(e=new Uint8Array(r.outputLen)),tr(r,ce(e),ce(t))}var Lc=new Uint8Array([0]),Ph=new Uint8Array;function Mh(r,t,e,n=32){if(Er(r),Ye(n),n>255*r.outputLen)throw new Error("Length should be <= 255*HashLen");let o=Math.ceil(n/r.outputLen);e===void 0&&(e=Ph);let s=new Uint8Array(o*r.outputLen),i=tr.create(r,t),a=i._cloneInto(),c=new Uint8Array(i.outputLen);for(let l=0;l<o;l++)Lc[0]=l+1,a.update(l===0?Ph:c).update(e).update(Lc).digestInto(c),s.set(c,r.outputLen*l),i._cloneInto(a);return i.destroy(),a.destroy(),c.fill(0),Lc.fill(0),s.slice(0,n)}var Dc={hashSHA256(r){return ln(r.subarray())},getHKDF(r,t){let e=Oh(ln,t,r),o=Mh(ln,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=Un.utils.randomPrivateKey();return{publicKey:Un.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:Un.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,t){return Un.getSharedSecret(r.subarray(),t.subarray())},chaCha20Poly1305Encrypt(r,t,e,n){return Nc(n,t,e).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,t,e,n,o){return Nc(n,t,e).decrypt(r.subarray(),o)}};var Hh=Dc;function Vh(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 fn=r=>{let t=vt(2);return t[0]=r>>8,t[1]=r,t};fn.bytes=2;var Zn=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)};Zn.bytes=2;function Fh(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 Uc(r,t){!t.enabled||!un||(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 Pc(r,t){!t.enabled||!un||(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 Kh(r,t){!t.enabled||!un||t(r?`REMOTE_STATIC_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote static public key.")}function Oc(r,t){!t.enabled||!un||t(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${G(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function Mc(r,t,e){!e.enabled||!un||(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 ti=class r extends Error{code;constructor(t="Unexpected Peer"){super(t),this.code=r.code}static code="ERR_UNEXPECTED_PEER"},hn=class r extends Error{code;constructor(t="Invalid crypto exchange"){super(t),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};var hy=0,dy=4294967295,py="Cipherstate has reached maximum n, a new handshake must be performed",ei=class{n;bytes;view;constructor(t=hy){this.n=t,this.bytes=Et(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>dy)throw new Error(py)}};var Tr=Et(0),dn=class{k;n;crypto;constructor(t,e=void 0,n=0){this.crypto=t,this.k=e,this.n=new ei(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}},Hc=class{cs;ck;h;crypto;constructor(t,e){this.crypto=t;let n=Y(e,"utf-8");this.h=my(t,n),this.ck=this.h,this.cs=new dn(t)}mixKey(t){let[e,n]=this.crypto.hkdf(this.ck,t);this.ck=e,this.cs=new dn(this.crypto,n)}mixHash(t){this.h=this.crypto.hash(new at(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,Tr);return[new dn(this.crypto,t),new dn(this.crypto,e)]}},Vc=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 Hc(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()}},Xn=class extends Vc{writeMessageA(t){return new at(this.writeE(),this.ss.encryptAndHash(t))}writeMessageB(t){let e=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new at(e,n,this.ss.encryptAndHash(t))}writeMessageC(t){let e=this.writeS();return this.writeSE(),new at(e,this.ss.encryptAndHash(t))}readMessageA(t){try{return this.readE(t),this.ss.decryptAndHash(t.sublist(32))}catch(e){throw new hn(`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 hn(`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 hn(`handshake stage 2 validation fail: ${e.message}`)}}};function my(r,t){if(t.length<=32){let e=Et(32);return e.set(t),e}else return r.hash(t)}var ri;(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())})(ri||(ri={}));var Jn;(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),ri.codec().encode(e.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(e,n)=>{let o={identityKey:Et(0),identitySig:Et(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=ri.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())})(Jn||(Jn={}));async function Fc(r,t,e){let n=await r.sign($h(t));return Jn.encode({identityKey:r.public.bytes,identitySig:n,extensions:e})}async function Kc(r,t,e){try{let n=Jn.decode(r);if(e){let i=e.subarray();if(!xt(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=$h(t);if(!await yh(n.identityKey).verify(o,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new ti(n.message)}}function $h(r){let t=Y("noise-libp2p-static-key:");return r instanceof Uint8Array?yt([t,r],t.length+r.length):(r.prepend(t),r)}async function Wh(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await Fc(o,i.publicKey,c),u=new Xn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:s,s:i});Uc(u.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await e.write(u.writeMessageA(Tr)),t.trace("Stage 0 - Initiator finished sending first message."),Pc(u.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let f=u.readMessageB(await e.read());t.trace("Stage 1 - Initiator received the message."),Oc(u.re,t),Kh(u.rs,t),t.trace("Initiator going to check remote's signature...");let p=await Kc(f,u.rs,a);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await e.write(u.writeMessageC(l)),t.trace("Stage 2 - Initiator sent message with signed payload.");let[g,m]=u.ss.split();return Mc(g,m,t),{payload:p,encrypt:h=>g.encryptWithAd(Tr,h),decrypt:(h,d)=>m.decryptWithAd(Tr,h,d)}}async function Gh(r){let{log:t,connection:e,crypto:n,privateKey:o,prologue:s,s:i,remoteIdentityKey:a,extensions:c}=r,l=await Fc(o,i.publicKey,c),u=new Xn({crypto:n,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:s,s:i});Uc(u.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),u.readMessageA(await e.read()),t.trace("Stage 0 - Responder received first message."),Oc(u.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await e.write(u.writeMessageB(l)),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Pc(u.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let f=u.readMessageC(await e.read());t.trace("Stage 2 - Responder received the message, finished handshake.");let p=await Kc(f,u.rs,a),[g,m]=u.ss.split();return Mc(g,m,t),{payload:p,encrypt:h=>m.encryptWithAd(Tr,h),decrypt:(h,d)=>g.decryptWithAd(Tr,h,d)}}var zh=16;function jh(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 at(fn(i.byteLength),i)}}}function Yh(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 ni=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??Hh;this.crypto=Vh(c),this.extensions=o,this.metrics=a?Fh(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Et(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[Nr]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(...t){let{localPeer:e,connection:n,remotePeer:o}=this.parseArgs(t),s=Rn(n,{lengthEncoder:fn,lengthDecoder:Zn,maxDataLength:65535});if(!e.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let i=await Ec(e.privateKey),a=o?.publicKey,c=await this.performHandshakeInitiator(s,i,a),l=await this.createSecureConnection(s,c);return n.source=l.source,n.sink=l.sink,{conn:n,remoteExtensions:c.payload.extensions,remotePeer:await Ui(c.payload.identityKey)}}async secureInbound(...t){let{localPeer:e,connection:n,remotePeer:o}=this.parseArgs(t),s=Rn(n,{lengthEncoder:fn,lengthDecoder:Zn,maxDataLength:65535});if(!e.privateKey)throw new D("local peerId does not contain private key","ERR_NO_PRIVATE_KEY");let i=await Ec(e.privateKey),a=o?.publicKey,c=await this.performHandshakeResponder(s,i,a),l=await this.createSecureConnection(s,c);return n.source=l.source,n.sink=l.sink,{conn:n,remoteExtensions:c.payload.extensions,remotePeer:await Ui(c.payload.identityKey)}}async performHandshakeInitiator(t,e,n){let o;try{o=await Wh({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}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async performHandshakeResponder(t,e,n){let o;try{o=await Gh({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}),this.metrics?.xxHandshakeSuccesses.increment()}catch(s){throw this.metrics?.xxHandshakeErrors.increment(),s}return o}async createSecureConnection(t,e){let[n,o]=wh(),s=t.unwrap();return await xh(n,jh(e,this.metrics),s,i=>pr(i,{lengthDecoder:Zn}),Yh(e,this.metrics),n),o}parseArgs(t){return tl(t[0])?{localPeer:t[0],connection:t[1],remotePeer:t[2]}:{localPeer:this.components.peerId,connection:t[0],remotePeer:t[1]}}};function Zh(r={}){return t=>new ni(t,r)}var $c=Object.values(me).map(r=>r.decoder).reduce((r,t)=>r.or(t));function Xh(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:yy(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 ma("","no fingerprint on local certificate");return n}var gy=/^a=fingerprint:(?:\w+-[0-9]+)\s(?<fingerprint>(:?[0-9a-fA-F]{2})+)$/m;function yy(r){return r.match(gy)?.groups?.fingerprint}function wy(r){for(let t of r.protoNames())if(t.startsWith("ip"))return t.toUpperCase();return"IP6"}function oi(r){let e=r.stringTuples().filter(n=>n[0]===td).map(n=>n[1])[0];if(e===void 0||e==="")throw xo(`Couldn't find a certhash component of multiaddr: ${r.toString()}`);return e}function Wc(r){return te.decode($c.decode(r))}function by(r){let t=Wc(oi(r)),e=Gc(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 ma(n,r.toString());return[`${e} ${o.join(":").toUpperCase()}`,n]}function Gc(r){switch(r){case 17:return"SHA-1";case 18:return"SHA-256";case 19:return"SHA-512";default:throw Yl(r)}}function xy(r,t){let{host:e,port:n}=r.toOptions(),o=wy(r),[s]=by(r);return`v=0
|
8
8
|
o=- 0 0 IN ${o} ${e}
|
9
9
|
s=-
|
10
10
|
c=IN ${o} ${e}
|
@@ -19,11 +19,11 @@ a=fingerprint:${s}
|
|
19
19
|
a=sctp-port:5000
|
20
20
|
a=max-message-size:16384
|
21
21
|
a=candidate:1467250027 1 UDP 1467250027 ${e} ${n} typ host\r
|
22
|
-
`}function
|
22
|
+
`}function Jh(r,t){return{type:"answer",sdp:xy(r,t)}}function Qh(r,t){if(r.sdp===void 0)throw vn("Can't munge a missing SDP");return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
23
23
|
a=ice-ufrag:`+t+`
|
24
24
|
`).replace(/\na=ice-pwd:[^\n]*\n/,`
|
25
25
|
a=ice-pwd:`+t+`
|
26
|
-
`),r}var
|
26
|
+
`),r}var ed=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),rd=r=>[...Array(r)].map(()=>ed.at(Math.floor(Math.random()*ed.length))).join("");var vy=1e4,x8=et("webrtc-direct").code,td=et("certhash").code,si=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"})})}[no]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[Nr]=["@libp2p/transport"];async dial(t,e){let n=await this._connect(t,e);return this.log("dialing address: %a",t),n}createListener(t){throw jl("WebRTCTransport.createListener")}listenFilter(t){return t.filter(Gl.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 xo("we need to have the remote's PeerId");let i=ur(s),a=Wc(oi(t)),c=await wr.generateCertificate({name:"ECDSA",namedCurve:"P-256",hash:Gc(a.code)}),l=new wr({...await Sn(this.init.rtcConfiguration),certificates:[c]});try{let u=new Promise((_,P)=>{let N=l.createDataChannel("",{negotiated:!0,id:0}),T=setTimeout(()=>{let F=`Data channel was never opened: state: ${N.readyState}`;this.log.error(F),this.metrics?.dialerEvents.increment({open_error:!0}),P(pa("data",F))},vy);N.onopen=F=>{clearTimeout(T),_(N)},N.onerror=F=>{clearTimeout(T);let R=`Error opening a data channel for handshaking: ${F.target?.toString()??"not specified"}`;this.log.error(R),this.metrics?.dialerEvents.increment({unknown_error:!0}),P(pa("data",R))}}),f="libp2p+webrtc+v1/"+rd(32),p=await l.createOffer(),g=Qh(p,f);await l.setLocalDescription(g);let m=Jh(t,f);await l.setRemoteDescription(m);let h=await u,d=this.components.peerId,x=this.generateNoisePrologue(l,a.code,t),w=Zh({prologueBytes:x})(this.components),b=Wr({channel:h,direction:"inbound",logger:this.components.logger,...this.init.dataChannel??{}}),I={...b,sink:b.sink.bind(b),source:async function*(){for await(let _ of b.source)for(let P of _)yield P}()},C=new hr(this.components,{peerConnection:l,remoteAddr:t,timeline:{open:Date.now()},metrics:this.metrics?.dialerEvents}),S=An?"iceconnectionstatechange":"connectionstatechange";l.addEventListener(S,()=>{switch(l.connectionState){case"failed":case"disconnected":case"closed":C.close().catch(_=>{this.log.error("error closing connection",_)}).finally(()=>{n.abort()});break;default:break}},{signal:o}),this.metrics?.dialerEvents.increment({peer_connection:!0});let B=new ze(this.components,{peerConnection:l,metrics:this.metrics?.dialerEvents,dataChannelOptions:this.init.dataChannel});return await w.secureInbound(d,I,i),await e.upgrader.upgradeOutbound(C,{skipProtection:!0,skipEncryption:!0,muxerFactory:B})}catch(u){throw l.close(),u}}generateNoisePrologue(t,e,n){if(t.getConfiguration().certificates?.length===0)throw vn("no local certificate");let o=Xh(t,{log:this.log});if(o==null)throw vn("no local fingerprint found");let s=o.trim().toLowerCase().replaceAll(":",""),i=Y(s,"hex"),a=$t(e,i),c=$c.decode(oi(n)),l=Y("libp2p-webrtc-noise:");return yt([l,a.bytes,c])}};function Ay(r){return t=>new si(t,r)}function Sy(r){return t=>new jo(t,r)}return yd(By);})();
|
27
27
|
/*! Bundled license information:
|
28
28
|
|
29
29
|
pvtsutils/build/index.js:
|