@helia/verified-fetch 3.2.1 → 3.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.min.js +5 -5
- package/dist/index.min.js.map +4 -4
- package/dist/src/plugins/plugin-handle-dag-pb.js +1 -1
- package/dist/src/plugins/plugin-handle-dag-pb.js.map +1 -1
- package/dist/src/utils/content-type-parser.d.ts.map +1 -1
- package/dist/src/utils/content-type-parser.js +3 -0
- package/dist/src/utils/content-type-parser.js.map +1 -1
- package/dist/src/utils/dir-index-html.js +1 -1
- package/dist/src/utils/dir-index-html.js.map +1 -1
- package/package.json +4 -4
- package/src/plugins/plugin-handle-dag-pb.ts +1 -1
- package/src/utils/content-type-parser.ts +3 -0
- package/src/utils/dir-index-html.ts +1 -1
package/dist/index.min.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
(function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.HeliaVerifiedFetch = factory()}(typeof self !== 'undefined' ? self : this, function () {
|
|
2
2
|
"use strict";var HeliaVerifiedFetch=(()=>{var Z$=Object.create;var fg=Object.defineProperty;var J$=Object.getOwnPropertyDescriptor;var eH=Object.getOwnPropertyNames;var tH=Object.getPrototypeOf,rH=Object.prototype.hasOwnProperty;var wt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),$t=(r,e)=>{for(var t in e)fg(r,t,{get:e[t],enumerable:!0})},OS=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of eH(e))!rH.call(r,i)&&i!==t&&fg(r,i,{get:()=>e[i],enumerable:!(n=J$(e,i))||n.enumerable});return r};var mt=(r,e,t)=>(t=r!=null?Z$(tH(r)):{},OS(e||!r||!r.__esModule?fg(t,"default",{value:r,enumerable:!0}):t,r)),nH=r=>OS(fg({},"__esModule",{value:!0}),r);var dT=wt((hde,Tx)=>{"use strict";var Yz=Object.prototype.hasOwnProperty,An="~";function Gp(){}Object.create&&(Gp.prototype=Object.create(null),new Gp().__proto__||(An=!1));function Qz(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function fT(r,e,t,n,i){if(typeof t!="function")throw new TypeError("The listener must be a function");var o=new Qz(t,n||r,i),s=An?An+e:e;return r._events[s]?r._events[s].fn?r._events[s]=[r._events[s],o]:r._events[s].push(o):(r._events[s]=o,r._eventsCount++),r}function x2(r,e){--r._eventsCount===0?r._events=new Gp:delete r._events[e]}function sn(){this._events=new Gp,this._eventsCount=0}sn.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)Yz.call(t,n)&&e.push(An?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};sn.prototype.listeners=function(e){var t=An?An+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,s=new Array(o);i<o;i++)s[i]=n[i].fn;return s};sn.prototype.listenerCount=function(e){var t=An?An+e:e,n=this._events[t];return n?n.fn?1:n.length:0};sn.prototype.emit=function(e,t,n,i,o,s){var a=An?An+e:e;if(!this._events[a])return!1;var c=this._events[a],l=arguments.length,u,f;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,o),!0;case 6:return c.fn.call(c.context,t,n,i,o,s),!0}for(f=1,u=new Array(l-1);f<l;f++)u[f-1]=arguments[f];c.fn.apply(c.context,u)}else{var d=c.length,h;for(f=0;f<d;f++)switch(c[f].once&&this.removeListener(e,c[f].fn,void 0,!0),l){case 1:c[f].fn.call(c[f].context);break;case 2:c[f].fn.call(c[f].context,t);break;case 3:c[f].fn.call(c[f].context,t,n);break;case 4:c[f].fn.call(c[f].context,t,n,i);break;default:if(!u)for(h=1,u=new Array(l-1);h<l;h++)u[h-1]=arguments[h];c[f].fn.apply(c[f].context,u)}}return!0};sn.prototype.on=function(e,t,n){return fT(this,e,t,n,!1)};sn.prototype.once=function(e,t,n){return fT(this,e,t,n,!0)};sn.prototype.removeListener=function(e,t,n,i){var o=An?An+e:e;if(!this._events[o])return this;if(!t)return x2(this,o),this;var s=this._events[o];if(s.fn)s.fn===t&&(!i||s.once)&&(!n||s.context===n)&&x2(this,o);else{for(var a=0,c=[],l=s.length;a<l;a++)(s[a].fn!==t||i&&!s[a].once||n&&s[a].context!==n)&&c.push(s[a]);c.length?this._events[o]=c.length===1?c[0]:c:x2(this,o)}return this};sn.prototype.removeAllListeners=function(e){var t;return e?(t=An?An+e:e,this._events[t]&&x2(this,t)):(this._events=new Gp,this._eventsCount=0),this};sn.prototype.off=sn.prototype.removeListener;sn.prototype.addListener=sn.prototype.on;sn.prefixed=An;sn.EventEmitter=sn;typeof Tx<"u"&&(Tx.exports=sn)});var yT=wt((Lde,gT)=>{gT.exports=function(r){if(!r)throw Error("hashlru must have a max value, of type number, greater than 0");var e=0,t=Object.create(null),n=Object.create(null);function i(o,s){t[o]=s,e++,e>=r&&(e=0,n=t,t=Object.create(null))}return{has:function(o){return t[o]!==void 0||n[o]!==void 0},remove:function(o){t[o]!==void 0&&(t[o]=void 0),n[o]!==void 0&&(n[o]=void 0)},get:function(o){var s=t[o];if(s!==void 0)return s;if((s=n[o])!==void 0)return i(o,s),s},set:function(o,s){t[o]!==void 0?t[o]=s:i(o,s)},clear:function(){t=Object.create(null),n=Object.create(null)}}}});var Sk=wt(mm=>{(function(){var r,e,t,n,i,o,s,a;a=function(c){var l,u,f,d;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,f=(c&65280)>>>8,d=c&255,[l,u,f,d].join(".")},s=function(c){var l,u,f,d,h,m;for(l=[],f=d=0;d<=3&&c.length!==0;f=++d){if(f>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}m=e(c),h=m[0],u=m[1],c=c.substring(u),l.push(h)}if(c.length!==0)throw new Error("Invalid IP");switch(l.length){case 1:if(l[0]>4294967295)throw new Error("Invalid IP");return l[0]>>>0;case 2:if(l[0]>255||l[1]>16777215)throw new Error("Invalid IP");return(l[0]<<24|l[1])>>>0;case 3:if(l[0]>255||l[1]>255||l[2]>65535)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2])>>>0;case 4:if(l[0]>255||l[1]>255||l[2]>255||l[3]>255)throw new Error("Invalid IP");return(l[0]<<24|l[1]<<16|l[2]<<8|l[3])>>>0;default:throw new Error("Invalid IP")}},t=function(c){return c.charCodeAt(0)},n=t("0"),o=t("a"),i=t("A"),e=function(c){var l,u,f,d,h;for(d=0,l=10,u="9",f=0,c.length>1&&c[f]==="0"&&(c[f+1]==="x"||c[f+1]==="X"?(f+=2,l=16):"0"<=c[f+1]&&c[f+1]<="9"&&(f++,l=8,u="7")),h=f;f<c.length;){if("0"<=c[f]&&c[f]<=u)d=d*l+(t(c[f])-n)>>>0;else if(l===16)if("a"<=c[f]&&c[f]<="f")d=d*l+(10+t(c[f])-o)>>>0;else if("A"<=c[f]&&c[f]<="F")d=d*l+(10+t(c[f])-i)>>>0;else break;else break;if(d>4294967295)throw new Error("too large");f++}if(f===h)throw new Error("empty octet");return[d,f]},r=(function(){function c(l,u){var f,d,h,m;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(m=l.split("/",2),l=m[0],u=m[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=s(u)}catch(g){throw f=g,new Error("Invalid mask: "+u)}for(d=h=32;h>=0;d=--h)if(this.maskLong===4294967295<<32-d>>>0){this.bitmask=d;break}}else if(u||u===0)this.bitmask=parseInt(u,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0);else throw new Error("Invalid mask: empty");try{this.netLong=(s(l)&this.maskLong)>>>0}catch(g){throw f=g,new Error("Invalid net address: "+l)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+u);this.size=Math.pow(2,32-this.bitmask),this.base=a(this.netLong),this.mask=a(this.maskLong),this.hostmask=a(~this.maskLong),this.first=this.bitmask<=30?a(this.netLong+1):this.base,this.last=this.bitmask<=30?a(this.netLong+this.size-2):a(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?a(this.netLong+this.size-1):void 0}return c.prototype.contains=function(l){return typeof l=="string"&&(l.indexOf("/")>0||l.split(".").length!==4)&&(l=new c(l)),l instanceof c?this.contains(l.base)&&this.contains(l.broadcast||l.last):(s(l)&this.maskLong)>>>0===(this.netLong&this.maskLong)>>>0},c.prototype.next=function(l){return l==null&&(l=1),new c(a(this.netLong+this.size*l),this.mask)},c.prototype.forEach=function(l){var u,f,d;for(d=s(this.first),f=s(this.last),u=0;d<=f;)l(a(d),d,u),u++,d++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),mm.ip2long=s,mm.long2ip=a,mm.Netmask=r}).call(mm)});var Uy=wt((g2e,V9)=>{var m2e=(function(){typeof V9<"u"&&(V9.exports=g);var r=86400,e=3200,t=146097*e/400,n=r*t,i=1e3*n,o=864e13,s=4294967296,a=1e6,c="000000000",l=Math.trunc||function(R){var _=R-R%1;return _==0&&(R<0||R===0&&1/R!=1/0)?-0:_},u=g.prototype,f=(g.fromDate=function(R){return new g(+R)},g.fromInt64BE=S(0,1,2,3,0,4),g.fromInt64LE=S(3,2,1,0,4,0),g.fromString=function(V){var _,$=new g,V=(V+="").replace(/^\s*[+\-]?\d+/,function(E){var E=+E,T=1970+(E-1970)%400;return $.year=E-T,T}).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,function(H,E,T){return E<0&&(T*=-1),_=6e4*(60*+E+ +T),""}).replace(/\.\d+$/,function(H){return $.nano=+(H+c).substr(1,9),""}).split(/\D+/);if(1<V.length?V[1]--:V[1]=0,$.time=_=Date.UTC.apply(Date,V)-(_||0),isNaN(_))throw new TypeError("Invalid Date");return w($)},g.fromTimeT=function(R){return v(R,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(R){return this.nano+=+R||0,this},u.getNano=function(){var R=w(this);return(R.time%1e3*a+ +R.nano+1e9)%1e9},u.getTimeT=function(){var _=w(this),R=Math.floor(_.time/1e3),_=_.year;return _&&(R+=_*t*r/e),R},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return x(w(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(R){var _=this,$=_.toDate(),V={H:function(){return F($.getUTCHours())},L:function(){return N($.getUTCMilliseconds(),3)},M:function(){return F($.getUTCMinutes())},N:function(){return N(_.getNano(),9)},S:function(){return F($.getUTCSeconds())},Y:function(){var H=_.getYear();return 999999<H?"+"+H:9999<H?"+"+N(H,6):0<=H?N(H,4):-999999<=H?"-"+N(-H,6):H},a:function(){return h[$.getUTCDay()]},b:function(){return d[$.getUTCMonth()]},d:function(){return F($.getUTCDate())},e:function(){return(function(H){return(9<H?"":" ")+(0|H)})($.getUTCDate())},m:function(){return F($.getUTCMonth()+1)}};return(function H(E){return E.replace(/%./g,function(T){var O=T[1],C=m[O],O=V[O];return C?H(C):O?O():T})})(R||f)},u.writeInt64BE=A(0,1,2,3,0,4),u.writeInt64LE=A(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m={"%":"%",F:"%Y-%m-%d",n:`
|
|
3
|
-
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return g;function g(R,_,$){var V=this;if(!(V instanceof g))return new g(R,_,$);V.time=+R||0,V.nano=+_||0,V.year=+$||0,w(V)}function w(R){var _,$,V,H=R.year,E=R.time,T=R.nano,C=((T<0||a<=T)&&(T-=($=Math.floor(T/a))*a,E+=$,$=1),H%e);return(E<-o||o<E||C)&&((_=l(E/i))&&(H+=_*e,E-=_*i),(V=x(E)).setUTCFullYear(C+V.getUTCFullYear()),V=(E=+V)+(_=l((H-=C)/e))*i,_&&-o<=V&&V<=o&&(H-=_*e,E=V),$=1),$&&(R.year=H,R.time=E,R.nano=T),R}function x(R){var _=new Date(0);return _.setTime(R),_}function v(H,V){H=+H||0;var $=l((V=(V|0)*s)/n)+l(H/n),V=V%n+H%n,H=l(V/n);return H&&($+=H,V-=H*n),new g(1e3*V,0,$*e)}function A(R,_,$,V,H,E){return function(C,O){var Q=w(this);C=C||new Array(8),M(C,O|=0);var U=Math.floor(Q.time/1e3),Q=Q.year*(t*r/e),j=l(Q/s)+l(U/s),Q=Q%s+U%s,U=Math.floor(Q/s);return U&&(j+=U,Q-=U*s),T(C,O+H,j),T(C,O+E,Q),C};function T(C,O,j){C[O+R]=j>>24&255,C[O+_]=j>>16&255,C[O+$]=j>>8&255,C[O+V]=255&j}}function S(R,_,$,V,H,E){return function(C,O){M(C,O|=0);var j=T(C,O+H);return v(T(C,O+E),j)};function T(C,O){return 16777216*C[O+R]+(C[O+_]<<16|C[O+$]<<8|C[O+V])}}function M(R,_){if(R=R&&R.length,R==null)throw new TypeError("Invalid Buffer");if(R<_+8)throw new RangeError("Out of range")}function F(R){return(9<R?"":"0")+(0|R)}function N(R,_){return(c+(0|R)).substr(-_)}})()});var KP=wt((H8e,VP)=>{function Ki(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}VP.exports=Ki;Ki.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ki.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ki.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Ki.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Ki.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ki.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ki.prototype.start=Ki.prototype.try;Ki.prototype.errors=function(){return this._errors};Ki.prototype.attempts=function(){return this._attempts};Ki.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(r[o]||0)+1;r[o]=s,s>=t&&(e=i,t=s)}return e}});var zP=wt(Ql=>{var UG=KP();Ql.operation=function(r){var e=Ql.timeouts(r);return new UG(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Ql.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(o,s){return o-s}),n};Ql.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};Ql.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var o=t[i],s=r[o];r[o]=function(c){var l=Ql.operation(e),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,s),r[o].options=e}}});var jP=wt((K8e,qP)=>{qP.exports=zP()});var oR=wt((bxe,iR)=>{"use strict";function aX(r){return r>=55296&&r<=56319}function cX(r){return r>=56320&&r<=57343}iR.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,o=0,s,a,c=0;c<i;c+=1){if(s=t.charCodeAt(c),a=t[c],aX(s)&&cX(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var aR=wt((vxe,sR)=>{"use strict";function lX(r){return r>=55296&&r<=56319}function uX(r){return r>=56320&&r<=57343}sR.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,o=null,s=0;s<t;s++)i=e.charCodeAt(s),uX(i)?o!=null&&lX(o)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),o=i;return n}});var lR=wt((Axe,cR)=>{"use strict";var fX=oR(),dX=aR();cR.exports=fX.bind(null,dX)});var dR=wt((Exe,fR)=>{"use strict";var hX=lR(),pX=/[\/\?<>\\:\*\|"]/g,mX=/[\x00-\x1f\x80-\x9f]/g,gX=/^\.+$/,yX=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,wX=/[\. ]+$/;function uR(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(pX,e).replace(mX,e).replace(gX,e).replace(yX,e).replace(wX,e);return hX(t,255)}fR.exports=function(r,e){var t=e&&e.replacement||"",n=uR(r,t);return t===""?n:uR(n,"")}});var la=wt(Od=>{"use strict";var bX="[object ArrayBuffer]",ca=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===bX}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),i=r.toUint8Array(t);if(n.length!==i.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==i[o])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let s of t)n+=s.byteLength;let i=new Uint8Array(n),o=0;for(let s of t){let a=this.toUint8Array(s);i.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(i,e[e.length-1]):i.buffer}},Tb="string",vX=/^[0-9a-f\s]+$/i,AX=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,EX=/^[a-zA-Z0-9-_]+$/,Y3=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n.buffer}static toString(e){let t=ca.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},zi=class{static toString(e,t=!1){let n=ca.toArrayBuffer(e),i=new DataView(n),o="";for(let s=0;s<n.byteLength;s+=2){let a=i.getUint16(s,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),i=new DataView(n);for(let o=0;o<e.length;o++)i.setUint16(o*2,e.charCodeAt(o),t);return n}},Q3=class r{static isHex(e){return typeof e===Tb&&vX.test(e)}static isBase64(e){return typeof e===Tb&&AX.test(e)}static isBase64Url(e){return typeof e===Tb&&EX.test(e)}static ToString(e,t="utf8"){let n=ca.toUint8Array(e);switch(t.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 zi.toString(n,!0);case"utf16":case"utf16be":return zi.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return zi.fromString(e,!0);case"utf16":case"utf16be":return zi.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=ca.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Y3.fromString(e);case"utf16":case"utf16be":return zi.fromString(e);case"utf16le":case"usc2":return zi.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Y3.toString(e);case"utf16":case"utf16be":return zi.toString(e);case"utf16le":case"usc2":return zi.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return n.buffer}static ToBinary(e){let t=ca.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return n}static ToHex(e){let t=ca.toUint8Array(e),n="",i=t.length;for(let o=0;o<i;o++){let s=t[o];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let i=0;i<t.length;i=i+2){let o=t.slice(i,i+2);n[i/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,t=!1){return zi.toString(e,t)}static FromUtf16String(e,t=!1){return zi.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Q3.DEFAULT_UTF8_ENCODING="utf8";function SX(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let i=arguments[n];for(let o in i)t[o]=i[o]}return t}function _X(...r){let e=r.map(i=>i.byteLength).reduce((i,o)=>i+o),t=new Uint8Array(e),n=0;return r.map(i=>new Uint8Array(i)).forEach(i=>{for(let o of i)t[n++]=o}),t.buffer}function CX(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let i=0;i<r.byteLength;i++)if(t[i]!==n[i])return!1;return!0}Od.BufferSourceConverter=ca;Od.Convert=Q3;Od.assign=SX;Od.combine=_X;Od.isEqual=CX});var $N=wt(()=>{var FN;(function(r){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:a(),n=i(r);typeof t.Reflect<"u"&&(n=i(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=r);function i(c,l){return function(u,f){Object.defineProperty(c,u,{configurable:!0,writable:!0,value:f}),l&&l(u,f)}}function o(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return o()||s()}})(function(e,t){var n=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",o=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,l=!a&&!c,u={create:a?function(){return Rw(Object.create(null))}:c?function(){return Rw({__proto__:null})}:function(){return Rw({})},has:l?function(k,B){return n.call(k,B)}:function(k,B){return B in k},get:l?function(k,B){return n.call(k,B)?k[B]:void 0}:function(k,B){return k[B]}},f=Object.getPrototypeOf(Function),d=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:W$(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:G$(),m=typeof WeakMap=="function"?WeakMap:X$(),g=i?Symbol.for("@reflect-metadata:registry"):void 0,w=z$(),x=q$(w);function v(k,B,W,re){if(q(W)){if(!Ci(k))throw new TypeError;if(!io(B))throw new TypeError;return H(k,B)}else{if(!Ci(k))throw new TypeError;if(!se(B))throw new TypeError;if(!se(re)&&!q(re)&&!Te(re))throw new TypeError;return Te(re)&&(re=void 0),W=st(W),E(k,B,W,re)}}e("decorate",v);function A(k,B){function W(re,Ee){if(!se(re))throw new TypeError;if(!q(Ee)&&!ug(Ee))throw new TypeError;Q(k,B,re,Ee)}return W}e("metadata",A);function S(k,B,W,re){if(!se(W))throw new TypeError;return q(re)||(re=st(re)),Q(k,B,W,re)}e("defineMetadata",S);function M(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),T(k,B,W)}e("hasMetadata",M);function F(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),C(k,B,W)}e("hasOwnMetadata",F);function N(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),O(k,B,W)}e("getMetadata",N);function R(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),j(k,B,W)}e("getOwnMetadata",R);function _(k,B){if(!se(k))throw new TypeError;return q(B)||(B=st(B)),U(k,B)}e("getMetadataKeys",_);function $(k,B){if(!se(k))throw new TypeError;return q(B)||(B=st(B)),Z(k,B)}e("getOwnMetadataKeys",$);function V(k,B,W){if(!se(B))throw new TypeError;if(q(W)||(W=st(W)),!se(B))throw new TypeError;q(W)||(W=st(W));var re=ap(B,W,!1);return q(re)?!1:re.OrdinaryDeleteMetadata(k,B,W)}e("deleteMetadata",V);function H(k,B){for(var W=k.length-1;W>=0;--W){var re=k[W],Ee=re(B);if(!q(Ee)&&!Te(Ee)){if(!io(Ee))throw new TypeError;B=Ee}}return B}function E(k,B,W,re){for(var Ee=k.length-1;Ee>=0;--Ee){var Jt=k[Ee],br=Jt(B,W,re);if(!q(br)&&!Te(br)){if(!se(br))throw new TypeError;re=br}}return re}function T(k,B,W){var re=C(k,B,W);if(re)return!0;var Ee=Pw(B);return Te(Ee)?!1:T(k,Ee,W)}function C(k,B,W){var re=ap(B,W,!1);return q(re)?!1:ft(re.OrdinaryHasOwnMetadata(k,B,W))}function O(k,B,W){var re=C(k,B,W);if(re)return j(k,B,W);var Ee=Pw(B);if(!Te(Ee))return O(k,Ee,W)}function j(k,B,W){var re=ap(B,W,!1);if(!q(re))return re.OrdinaryGetOwnMetadata(k,B,W)}function Q(k,B,W,re){var Ee=ap(W,re,!0);Ee.OrdinaryDefineOwnMetadata(k,B,W,re)}function U(k,B){var W=Z(k,B),re=Pw(k);if(re===null)return W;var Ee=U(re,B);if(Ee.length<=0)return W;if(W.length<=0)return Ee;for(var Jt=new h,br=[],Ve=0,ae=W;Ve<ae.length;Ve++){var ue=ae[Ve],de=Jt.has(ue);de||(Jt.add(ue),br.push(ue))}for(var ge=0,ze=Ee;ge<ze.length;ge++){var ue=ze[ge],de=Jt.has(ue);de||(Jt.add(ue),br.push(ue))}return br}function Z(k,B){var W=ap(k,B,!1);return W?W.OrdinaryOwnMetadataKeys(k,B):[]}function te(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function q(k){return k===void 0}function Te(k){return k===null}function Ne(k){return typeof k=="symbol"}function se(k){return typeof k=="object"?k!==null:typeof k=="function"}function Le(k,B){switch(te(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var W=B===3?"string":B===5?"number":"default",re=TS(k,o);if(re!==void 0){var Ee=re.call(k,W);if(se(Ee))throw new TypeError;return Ee}return Ke(k,W==="default"?"number":W)}function Ke(k,B){if(B==="string"){var W=k.toString;if(hn(W)){var re=W.call(k);if(!se(re))return re}var Ee=k.valueOf;if(hn(Ee)){var re=Ee.call(k);if(!se(re))return re}}else{var Ee=k.valueOf;if(hn(Ee)){var re=Ee.call(k);if(!se(re))return re}var Jt=k.toString;if(hn(Jt)){var re=Jt.call(k);if(!se(re))return re}}throw new TypeError}function ft(k){return!!k}function He(k){return""+k}function st(k){var B=Le(k,3);return Ne(B)?B:He(B)}function Ci(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function hn(k){return typeof k=="function"}function io(k){return typeof k=="function"}function ug(k){switch(te(k)){case 3:return!0;case 4:return!0;default:return!1}}function xf(k,B){return k===B||k!==k&&B!==B}function TS(k,B){var W=k[B];if(W!=null){if(!hn(W))throw new TypeError;return W}}function IS(k){var B=TS(k,s);if(!hn(B))throw new TypeError;var W=B.call(k);if(!se(W))throw new TypeError;return W}function kS(k){return k.value}function PS(k){var B=k.next();return B.done?!1:B}function RS(k){var B=k.return;B&&B.call(k)}function Pw(k){var B=Object.getPrototypeOf(k);if(typeof k!="function"||k===f||B!==f)return B;var W=k.prototype,re=W&&Object.getPrototypeOf(W);if(re==null||re===Object.prototype)return B;var Ee=re.constructor;return typeof Ee!="function"||Ee===k?B:Ee}function K$(){var k;!q(g)&&typeof t.Reflect<"u"&&!(g in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(k=j$(t.Reflect));var B,W,re,Ee=new m,Jt={registerProvider:br,getProvider:ae,setProvider:de};return Jt;function br(ge){if(!Object.isExtensible(Jt))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===ge:break;case q(B):B=ge;break;case B===ge:break;case q(W):W=ge;break;case W===ge:break;default:re===void 0&&(re=new h),re.add(ge);break}}function Ve(ge,ze){if(!q(B)){if(B.isProviderFor(ge,ze))return B;if(!q(W)){if(W.isProviderFor(ge,ze))return B;if(!q(re))for(var Pt=IS(re);;){var er=PS(Pt);if(!er)return;var oo=kS(er);if(oo.isProviderFor(ge,ze))return RS(Pt),oo}}}if(!q(k)&&k.isProviderFor(ge,ze))return k}function ae(ge,ze){var Pt=Ee.get(ge),er;return q(Pt)||(er=Pt.get(ze)),q(er)&&(er=Ve(ge,ze),q(er)||(q(Pt)&&(Pt=new d,Ee.set(ge,Pt)),Pt.set(ze,er))),er}function ue(ge){if(q(ge))throw new TypeError;return B===ge||W===ge||!q(re)&&re.has(ge)}function de(ge,ze,Pt){if(!ue(Pt))throw new Error("Metadata provider not registered.");var er=ae(ge,ze);if(er!==Pt){if(!q(er))return!1;var oo=Ee.get(ge);q(oo)&&(oo=new d,Ee.set(ge,oo)),oo.set(ze,Pt)}return!0}}function z$(){var k;return!q(g)&&se(t.Reflect)&&Object.isExtensible(t.Reflect)&&(k=t.Reflect[g]),q(k)&&(k=K$()),!q(g)&&se(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function q$(k){var B=new m,W={isProviderFor:function(ue,de){var ge=B.get(ue);return q(ge)?!1:ge.has(de)},OrdinaryDefineOwnMetadata:br,OrdinaryHasOwnMetadata:Ee,OrdinaryGetOwnMetadata:Jt,OrdinaryOwnMetadataKeys:Ve,OrdinaryDeleteMetadata:ae};return w.registerProvider(W),W;function re(ue,de,ge){var ze=B.get(ue),Pt=!1;if(q(ze)){if(!ge)return;ze=new d,B.set(ue,ze),Pt=!0}var er=ze.get(de);if(q(er)){if(!ge)return;if(er=new d,ze.set(de,er),!k.setProvider(ue,de,W))throw ze.delete(de),Pt&&B.delete(ue),new Error("Wrong provider for target.")}return er}function Ee(ue,de,ge){var ze=re(de,ge,!1);return q(ze)?!1:ft(ze.has(ue))}function Jt(ue,de,ge){var ze=re(de,ge,!1);if(!q(ze))return ze.get(ue)}function br(ue,de,ge,ze){var Pt=re(ge,ze,!0);Pt.set(ue,de)}function Ve(ue,de){var ge=[],ze=re(ue,de,!1);if(q(ze))return ge;for(var Pt=ze.keys(),er=IS(Pt),oo=0;;){var DS=PS(er);if(!DS)return ge.length=oo,ge;var Y$=kS(DS);try{ge[oo]=Y$}catch(Q$){try{RS(er)}finally{throw Q$}}oo++}}function ae(ue,de,ge){var ze=re(de,ge,!1);if(q(ze)||!ze.delete(ue))return!1;if(ze.size===0){var Pt=B.get(de);q(Pt)||(Pt.delete(ge),Pt.size===0&&B.delete(Pt))}return!0}}function j$(k){var B=k.defineMetadata,W=k.hasOwnMetadata,re=k.getOwnMetadata,Ee=k.getOwnMetadataKeys,Jt=k.deleteMetadata,br=new m,Ve={isProviderFor:function(ae,ue){var de=br.get(ae);return!q(de)&&de.has(ue)?!0:Ee(ae,ue).length?(q(de)&&(de=new h,br.set(ae,de)),de.add(ue),!0):!1},OrdinaryDefineOwnMetadata:B,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:re,OrdinaryOwnMetadataKeys:Ee,OrdinaryDeleteMetadata:Jt};return Ve}function ap(k,B,W){var re=w.getProvider(k,B);if(!q(re))return re;if(W){if(w.setProvider(k,B,x))return x;throw new Error("Illegal state.")}}function W$(){var k={},B=[],W=(function(){function Ve(ae,ue,de){this._index=0,this._keys=ae,this._values=ue,this._selector=de}return Ve.prototype["@@iterator"]=function(){return this},Ve.prototype[s]=function(){return this},Ve.prototype.next=function(){var ae=this._index;if(ae>=0&&ae<this._keys.length){var ue=this._selector(this._keys[ae],this._values[ae]);return ae+1>=this._keys.length?(this._index=-1,this._keys=B,this._values=B):this._index++,{value:ue,done:!1}}return{value:void 0,done:!0}},Ve.prototype.throw=function(ae){throw this._index>=0&&(this._index=-1,this._keys=B,this._values=B),ae},Ve.prototype.return=function(ae){return this._index>=0&&(this._index=-1,this._keys=B,this._values=B),{value:ae,done:!0}},Ve})(),re=(function(){function Ve(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(Ve.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Ve.prototype.has=function(ae){return this._find(ae,!1)>=0},Ve.prototype.get=function(ae){var ue=this._find(ae,!1);return ue>=0?this._values[ue]:void 0},Ve.prototype.set=function(ae,ue){var de=this._find(ae,!0);return this._values[de]=ue,this},Ve.prototype.delete=function(ae){var ue=this._find(ae,!1);if(ue>=0){for(var de=this._keys.length,ge=ue+1;ge<de;ge++)this._keys[ge-1]=this._keys[ge],this._values[ge-1]=this._values[ge];return this._keys.length--,this._values.length--,xf(ae,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},Ve.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},Ve.prototype.keys=function(){return new W(this._keys,this._values,Ee)},Ve.prototype.values=function(){return new W(this._keys,this._values,Jt)},Ve.prototype.entries=function(){return new W(this._keys,this._values,br)},Ve.prototype["@@iterator"]=function(){return this.entries()},Ve.prototype[s]=function(){return this.entries()},Ve.prototype._find=function(ae,ue){if(!xf(this._cacheKey,ae)){this._cacheIndex=-1;for(var de=0;de<this._keys.length;de++)if(xf(this._keys[de],ae)){this._cacheIndex=de;break}}return this._cacheIndex<0&&ue&&(this._cacheIndex=this._keys.length,this._keys.push(ae),this._values.push(void 0)),this._cacheIndex},Ve})();return re;function Ee(Ve,ae){return Ve}function Jt(Ve,ae){return ae}function br(Ve,ae){return[Ve,ae]}}function G$(){var k=(function(){function B(){this._map=new d}return Object.defineProperty(B.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),B.prototype.has=function(W){return this._map.has(W)},B.prototype.add=function(W){return this._map.set(W,W),this},B.prototype.delete=function(W){return this._map.delete(W)},B.prototype.clear=function(){this._map.clear()},B.prototype.keys=function(){return this._map.keys()},B.prototype.values=function(){return this._map.keys()},B.prototype.entries=function(){return this._map.entries()},B.prototype["@@iterator"]=function(){return this.keys()},B.prototype[s]=function(){return this.keys()},B})();return k}function X$(){var k=16,B=u.create(),W=re();return(function(){function ae(){this._key=re()}return ae.prototype.has=function(ue){var de=Ee(ue,!1);return de!==void 0?u.has(de,this._key):!1},ae.prototype.get=function(ue){var de=Ee(ue,!1);return de!==void 0?u.get(de,this._key):void 0},ae.prototype.set=function(ue,de){var ge=Ee(ue,!0);return ge[this._key]=de,this},ae.prototype.delete=function(ue){var de=Ee(ue,!1);return de!==void 0?delete de[this._key]:!1},ae.prototype.clear=function(){this._key=re()},ae})();function re(){var ae;do ae="@@WeakMap@@"+Ve();while(u.has(B,ae));return B[ae]=!0,ae}function Ee(ae,ue){if(!n.call(ae,W)){if(!ue)return;Object.defineProperty(ae,W,{value:u.create()})}return ae[W]}function Jt(ae,ue){for(var de=0;de<ue;++de)ae[de]=Math.random()*255|0;return ae}function br(ae){if(typeof Uint8Array=="function"){var ue=new Uint8Array(ae);return typeof crypto<"u"?crypto.getRandomValues(ue):typeof msCrypto<"u"?msCrypto.getRandomValues(ue):Jt(ue,ae),ue}return Jt(new Array(ae),ae)}function Ve(){var ae=br(k);ae[6]=ae[6]&79|64,ae[8]=ae[8]&191|128;for(var ue="",de=0;de<k;++de){var ge=ae[de];(de===4||de===6||de===8)&&(ue+="-"),ge<16&&(ue+="0"),ue+=ge.toString(16).toLowerCase()}return ue}}function Rw(k){return k.__=void 0,delete k.__,k}})})(FN||(FN={}))});var XB=wt((IKe,I5)=>{var kB,PB,RB,DB,OB,NB,BB,LB,MB,T5,zA,UB,FB,Th,$B,HB,VB,KB,zB,qB,jB,WB,GB;(function(r){var e=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:{};typeof define=="function"&&define.amd?define("tslib",["exports"],function(n){r(t(e,t(n)))}):typeof I5=="object"&&typeof I5.exports=="object"?r(t(e,t(I5.exports))):r(t(e));function t(n,i){return n!==e&&(typeof Object.create=="function"?Object.defineProperty(n,"__esModule",{value:!0}):n.__esModule=!0),function(o,s){return n[o]=i?i(o,s):s}}})(function(r){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])};kB=function(t,n){e(t,n);function i(){this.constructor=t}t.prototype=n===null?Object.create(n):(i.prototype=n.prototype,new i)},PB=Object.assign||function(t){for(var n,i=1,o=arguments.length;i<o;i++){n=arguments[i];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},RB=function(t,n){var i={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&n.indexOf(o)<0&&(i[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,o=Object.getOwnPropertySymbols(t);s<o.length;s++)n.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(t,o[s])&&(i[o[s]]=t[o[s]]);return i},DB=function(t,n,i,o){var s=arguments.length,a=s<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,i):o,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(t,n,i,o);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(a=(s<3?c(a):s>3?c(n,i,a):c(n,i))||a);return s>3&&a&&Object.defineProperty(n,i,a),a},OB=function(t,n){return function(i,o){n(i,o,t)}},NB=function(t,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,n)},BB=function(t,n,i,o){function s(a){return a instanceof i?a:new i(function(c){c(a)})}return new(i||(i=Promise))(function(a,c){function l(d){try{f(o.next(d))}catch(h){c(h)}}function u(d){try{f(o.throw(d))}catch(h){c(h)}}function f(d){d.done?a(d.value):s(d.value).then(l,u)}f((o=o.apply(t,n||[])).next())})},LB=function(t,n){var i={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},o,s,a,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(d){return u([f,d])}}function u(f){if(o)throw new TypeError("Generator is already executing.");for(;i;)try{if(o=1,s&&(a=f[0]&2?s.return:f[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,f[1])).done)return a;switch(s=0,a&&(f=[f[0]&2,a.value]),f[0]){case 0:case 1:a=f;break;case 4:return i.label++,{value:f[1],done:!1};case 5:i.label++,s=f[1],f=[0];continue;case 7:f=i.ops.pop(),i.trys.pop();continue;default:if(a=i.trys,!(a=a.length>0&&a[a.length-1])&&(f[0]===6||f[0]===2)){i=0;continue}if(f[0]===3&&(!a||f[1]>a[0]&&f[1]<a[3])){i.label=f[1];break}if(f[0]===6&&i.label<a[1]){i.label=a[1],a=f;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(f);break}a[2]&&i.ops.pop(),i.trys.pop();continue}f=n.call(t,i)}catch(d){f=[6,d],s=0}finally{o=a=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}},GB=function(t,n,i,o){o===void 0&&(o=i),t[o]=n[i]},MB=function(t,n){for(var i in t)i!=="default"&&!n.hasOwnProperty(i)&&(n[i]=t[i])},T5=function(t){var n=typeof Symbol=="function"&&Symbol.iterator,i=n&&t[n],o=0;if(i)return i.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&o>=t.length&&(t=void 0),{value:t&&t[o++],done:!t}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},zA=function(t,n){var i=typeof Symbol=="function"&&t[Symbol.iterator];if(!i)return t;var o=i.call(t),s,a=[],c;try{for(;(n===void 0||n-- >0)&&!(s=o.next()).done;)a.push(s.value)}catch(l){c={error:l}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(c)throw c.error}}return a},UB=function(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(zA(arguments[n]));return t},FB=function(){for(var t=0,n=0,i=arguments.length;n<i;n++)t+=arguments[n].length;for(var o=Array(t),s=0,n=0;n<i;n++)for(var a=arguments[n],c=0,l=a.length;c<l;c++,s++)o[s]=a[c];return o},Th=function(t){return this instanceof Th?(this.v=t,this):new Th(t)},$B=function(t,n,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=i.apply(t,n||[]),s,a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(m){o[m]&&(s[m]=function(g){return new Promise(function(w,x){a.push([m,g,w,x])>1||l(m,g)})})}function l(m,g){try{u(o[m](g))}catch(w){h(a[0][3],w)}}function u(m){m.value instanceof Th?Promise.resolve(m.value.v).then(f,d):h(a[0][2],m)}function f(m){l("next",m)}function d(m){l("throw",m)}function h(m,g){m(g),a.shift(),a.length&&l(a[0][0],a[0][1])}},HB=function(t){var n,i;return n={},o("next"),o("throw",function(s){throw s}),o("return"),n[Symbol.iterator]=function(){return this},n;function o(s,a){n[s]=t[s]?function(c){return(i=!i)?{value:Th(t[s](c)),done:s==="return"}:a?a(c):c}:a}},VB=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t[Symbol.asyncIterator],i;return n?n.call(t):(t=typeof T5=="function"?T5(t):t[Symbol.iterator](),i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i);function o(a){i[a]=t[a]&&function(c){return new Promise(function(l,u){c=t[a](c),s(l,u,c.done,c.value)})}}function s(a,c,l,u){Promise.resolve(u).then(function(f){a({value:f,done:l})},c)}},KB=function(t,n){return Object.defineProperty?Object.defineProperty(t,"raw",{value:n}):t.raw=n,t},zB=function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var i in t)Object.hasOwnProperty.call(t,i)&&(n[i]=t[i]);return n.default=t,n},qB=function(t){return t&&t.__esModule?t:{default:t}},jB=function(t,n){if(!n.has(t))throw new TypeError("attempted to get private field on non-instance");return n.get(t)},WB=function(t,n,i){if(!n.has(t))throw new TypeError("attempted to set private field on non-instance");return n.set(t,i),i},r("__extends",kB),r("__assign",PB),r("__rest",RB),r("__decorate",DB),r("__param",OB),r("__metadata",NB),r("__awaiter",BB),r("__generator",LB),r("__exportStar",MB),r("__createBinding",GB),r("__values",T5),r("__read",zA),r("__spread",UB),r("__spreadArrays",FB),r("__await",Th),r("__asyncGenerator",$B),r("__asyncDelegator",HB),r("__asyncValues",VB),r("__makeTemplateObject",KB),r("__importStar",zB),r("__importDefault",qB),r("__classPrivateFieldGet",jB),r("__classPrivateFieldSet",WB)})});var TM=wt(s8=>{"use strict";Object.defineProperty(s8,"__esModule",{value:!0});var NE=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,i)=>{this.pullQueue.push({resolve:n,reject:i})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},o8=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new NE;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:o=>i.push(o),stop:()=>i.stop(),fail:o=>i.fail(o),on:(o,s)=>{i.eventHandlers[o]=s}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};s8.EventIterator=o8;s8.default=o8});var IM=wt(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});var BE=TM();N0.EventIterator=BE.EventIterator;function wJ(r,e,t){return new BE.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}N0.subscribe=wJ;N0.default=BE.EventIterator});var cU=wt((vZe,aU)=>{aU.exports=zE;var sU=128,kJ=127,PJ=~kJ,RJ=Math.pow(2,31);function zE(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw zE.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=RJ;)e[t++]=r&255|sU,r/=128;for(;r&PJ;)e[t++]=r&255|sU,r>>>=7;return e[t]=r|0,zE.bytes=t-n+1,e}});var fU=wt((AZe,uU)=>{uU.exports=qE;var DJ=128,lU=127;function qE(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a||i>49)throw qE.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&lU)<<i:(s&lU)*Math.pow(2,i),i+=7}while(s>=DJ);return qE.bytes=o-n,t}});var hU=wt((EZe,dU)=>{var OJ=Math.pow(2,7),NJ=Math.pow(2,14),BJ=Math.pow(2,21),LJ=Math.pow(2,28),MJ=Math.pow(2,35),UJ=Math.pow(2,42),FJ=Math.pow(2,49),$J=Math.pow(2,56),HJ=Math.pow(2,63);dU.exports=function(r){return r<OJ?1:r<NJ?2:r<BJ?3:r<LJ?4:r<MJ?5:r<UJ?6:r<FJ?7:r<$J?8:r<HJ?9:10}});var S8=wt((SZe,pU)=>{pU.exports={encode:cU(),decode:fU(),encodingLength:hU()}});var OU=wt((q0,H8)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function i(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function o(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=i(h,2246822507),h^=h>>>13,h=i(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var g=[0,0,0,0];return g[3]+=h[3]+m[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=h[2]+m[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=h[1]+m[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=h[0]+m[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var g=[0,0,0,0];return g[3]+=h[3]*m[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=h[2]*m[3],g[1]+=g[2]>>>16,g[2]&=65535,g[2]+=h[3]*m[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=h[1]*m[3],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=h[2]*m[2],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=h[3]*m[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function d(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var g=h.length%4,w=h.length-g,x=m,v=0,A=3432918353,S=461845907,M=0;M<w;M=M+4)v=h[M]|h[M+1]<<8|h[M+2]<<16|h[M+3]<<24,v=i(v,A),v=o(v,15),v=i(v,S),x^=v,x=o(x,13),x=i(x,5)+3864292196;switch(v=0,g){case 3:v^=h[M+2]<<16;case 2:v^=h[M+1]<<8;case 1:v^=h[M],v=i(v,A),v=o(v,15),v=i(v,S),x^=v}return x^=h.length,x=s(x),x>>>0},t.x86.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var g=h.length%16,w=h.length-g,x=m,v=m,A=m,S=m,M=0,F=0,N=0,R=0,_=597399067,$=2869860233,V=951274213,H=2716044179,E=0;E<w;E=E+16)M=h[E]|h[E+1]<<8|h[E+2]<<16|h[E+3]<<24,F=h[E+4]|h[E+5]<<8|h[E+6]<<16|h[E+7]<<24,N=h[E+8]|h[E+9]<<8|h[E+10]<<16|h[E+11]<<24,R=h[E+12]|h[E+13]<<8|h[E+14]<<16|h[E+15]<<24,M=i(M,_),M=o(M,15),M=i(M,$),x^=M,x=o(x,19),x+=v,x=i(x,5)+1444728091,F=i(F,$),F=o(F,16),F=i(F,V),v^=F,v=o(v,17),v+=A,v=i(v,5)+197830471,N=i(N,V),N=o(N,17),N=i(N,H),A^=N,A=o(A,15),A+=S,A=i(A,5)+2530024501,R=i(R,H),R=o(R,18),R=i(R,_),S^=R,S=o(S,13),S+=x,S=i(S,5)+850148119;switch(M=0,F=0,N=0,R=0,g){case 15:R^=h[E+14]<<16;case 14:R^=h[E+13]<<8;case 13:R^=h[E+12],R=i(R,H),R=o(R,18),R=i(R,_),S^=R;case 12:N^=h[E+11]<<24;case 11:N^=h[E+10]<<16;case 10:N^=h[E+9]<<8;case 9:N^=h[E+8],N=i(N,V),N=o(N,17),N=i(N,H),A^=N;case 8:F^=h[E+7]<<24;case 7:F^=h[E+6]<<16;case 6:F^=h[E+5]<<8;case 5:F^=h[E+4],F=i(F,$),F=o(F,16),F=i(F,V),v^=F;case 4:M^=h[E+3]<<24;case 3:M^=h[E+2]<<16;case 2:M^=h[E+1]<<8;case 1:M^=h[E],M=i(M,_),M=o(M,15),M=i(M,$),x^=M}return x^=h.length,v^=h.length,A^=h.length,S^=h.length,x+=v,x+=A,x+=S,v+=x,A+=x,S+=x,x=s(x),v=s(v),A=s(A),S=s(S),x+=v,x+=A,x+=S,v+=x,A+=x,S+=x,("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)+("00000000"+(A>>>0).toString(16)).slice(-8)+("00000000"+(S>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var g=h.length%16,w=h.length-g,x=[0,m],v=[0,m],A=[0,0],S=[0,0],M=[2277735313,289559509],F=[1291169091,658871167],N=0;N<w;N=N+16)A=[h[N+4]|h[N+5]<<8|h[N+6]<<16|h[N+7]<<24,h[N]|h[N+1]<<8|h[N+2]<<16|h[N+3]<<24],S=[h[N+12]|h[N+13]<<8|h[N+14]<<16|h[N+15]<<24,h[N+8]|h[N+9]<<8|h[N+10]<<16|h[N+11]<<24],A=c(A,M),A=l(A,31),A=c(A,F),x=f(x,A),x=l(x,27),x=a(x,v),x=a(c(x,[0,5]),[0,1390208809]),S=c(S,F),S=l(S,33),S=c(S,M),v=f(v,S),v=l(v,31),v=a(v,x),v=a(c(v,[0,5]),[0,944331445]);switch(A=[0,0],S=[0,0],g){case 15:S=f(S,u([0,h[N+14]],48));case 14:S=f(S,u([0,h[N+13]],40));case 13:S=f(S,u([0,h[N+12]],32));case 12:S=f(S,u([0,h[N+11]],24));case 11:S=f(S,u([0,h[N+10]],16));case 10:S=f(S,u([0,h[N+9]],8));case 9:S=f(S,[0,h[N+8]]),S=c(S,F),S=l(S,33),S=c(S,M),v=f(v,S);case 8:A=f(A,u([0,h[N+7]],56));case 7:A=f(A,u([0,h[N+6]],48));case 6:A=f(A,u([0,h[N+5]],40));case 5:A=f(A,u([0,h[N+4]],32));case 4:A=f(A,u([0,h[N+3]],24));case 3:A=f(A,u([0,h[N+2]],16));case 2:A=f(A,u([0,h[N+1]],8));case 1:A=f(A,[0,h[N]]),A=c(A,M),A=l(A,31),A=c(A,F),x=f(x,A)}return x=f(x,[0,h.length]),v=f(v,[0,h.length]),x=a(x,v),v=a(v,x),x=d(x),v=d(v),x=a(x,v),v=a(v,x),("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)+("00000000"+(v[0]>>>0).toString(16)).slice(-8)+("00000000"+(v[1]>>>0).toString(16)).slice(-8)},typeof q0<"u"?(typeof H8<"u"&&H8.exports&&(q0=H8.exports=t),q0.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(q0)});var BU=wt((Bet,NU)=>{NU.exports=OU()});var K8=wt((Vet,MU)=>{"use strict";MU.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let i=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):i=!0,this._setInternalPos(n,e,t,i),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,i=t;for(;n<this.length;){let o=this.get(n);i=e(i,o,n),n++}return i}find(e){let t=0,n,i;for(;t<this.length&&!n;)i=this.get(t),n=e(i),t++;return n?i:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let i=this._bitArrays[n],o=e-n*7;if(!((i&1<<o)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(fee,0),c=~(4294967295<<o+1),l=LU(i&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),i=n+1;for(;!t&&this._bitArrays.length<i;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,i){let o=this._data,s=[t,n];if(i)this._sortData(),o[e]=s;else{if(o.length)if(o[o.length-1][0]>=t)o.push(s);else if(o[0][0]<=t)o.unshift(s);else{let a=Math.round(o.length/2);this._data=o.slice(0,a).concat(s).concat(o.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(dee),this._changedData=!1}bitField(){let e=[],t=8,n=0,i=0,o,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(o=s.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),u=o&l;i|=u<<8-t,o=o>>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(i),i=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(hee)}};function fee(r,e){return r+LU(e)}function LU(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function dee(r,e){return r[0]-e[0]}function hee(r){return r[1]}});var LF=wt(aS=>{aS.read=function(r,e,t,n,i){var o,s,a=i*8-n-1,c=(1<<a)-1,l=c>>1,u=-7,f=t?i-1:0,d=t?-1:1,h=r[e+f];for(f+=d,o=h&(1<<-u)-1,h>>=-u,u+=a;u>0;o=o*256+r[e+f],f+=d,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=s*256+r[e+f],f+=d,u-=8);if(o===0)o=1-l;else{if(o===c)return s?NaN:(h?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-l}return(h?-1:1)*s*Math.pow(2,o-n)};aS.write=function(r,e,t,n,i,o){var s,a,c,l=o*8-i-1,u=(1<<l)-1,f=u>>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:o-1,m=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+f>=1?e+=d/c:e+=d*Math.pow(2,1-f),e*c>=2&&(s++,c/=2),s+f>=u?(a=0,s=u):s+f>=1?(a=(e*c-1)*Math.pow(2,i),s=s+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;r[t+h]=a&255,h+=m,a/=256,i-=8);for(s=s<<i|a,l+=i;l>0;r[t+h]=s&255,h+=m,s/=256,l-=8);r[t+h-m]|=g*128}});var e$=wt((cat,JF)=>{var ip=1e3,op=ip*60,sp=op*60,yf=sp*24,ure=yf*7,fre=yf*365.25;JF.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return dre(r);if(t==="number"&&isFinite(r))return e.long?pre(r):hre(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function dre(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*fre;case"weeks":case"week":case"w":return t*ure;case"days":case"day":case"d":return t*yf;case"hours":case"hour":case"hrs":case"hr":case"h":return t*sp;case"minutes":case"minute":case"mins":case"min":case"m":return t*op;case"seconds":case"second":case"secs":case"sec":case"s":return t*ip;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function hre(r){var e=Math.abs(r);return e>=yf?Math.round(r/yf)+"d":e>=sp?Math.round(r/sp)+"h":e>=op?Math.round(r/op)+"m":e>=ip?Math.round(r/ip)+"s":r+"ms"}function pre(r){var e=Math.abs(r);return e>=yf?dw(r,e,yf,"day"):e>=sp?dw(r,e,sp,"hour"):e>=op?dw(r,e,op,"minute"):e>=ip?dw(r,e,ip,"second"):r+" ms"}function dw(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var r$=wt((lat,t$)=>{function mre(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=i,t.enabled=a,t.humanize=e$(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,h,m;function g(...w){if(!g.enabled)return;let x=g,v=Number(new Date),A=v-(f||v);x.diff=A,x.prev=f,x.curr=v,f=v,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let S=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(F,N)=>{if(F==="%%")return"%";S++;let R=t.formatters[N];if(typeof R=="function"){let _=w[S];F=R.call(x,_),w.splice(S,1),S--}return F}),t.formatArgs.call(x,w),(x.log||t.log).apply(x,w)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:w=>{d=w}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function i(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of f)d[0]==="-"?t.skips.push(d.slice(1)):t.names.push(d)}function o(u,f){let d=0,h=0,m=-1,g=0;for(;d<u.length;)if(h<f.length&&(f[h]===u[d]||f[h]==="*"))f[h]==="*"?(m=h,g=d,h++):(d++,h++);else if(m!==-1)h=m+1,g++,d=g;else return!1;for(;h<f.length&&f[h]==="*";)h++;return h===f.length}function s(){let u=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),u}function a(u){for(let f of t.skips)if(o(u,f))return!1;for(let f of t.names)if(o(u,f))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}t$.exports=mre});var n$=wt((Zn,hw)=>{Zn.formatArgs=yre;Zn.save=wre;Zn.load=xre;Zn.useColors=gre;Zn.storage=bre();Zn.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Zn.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function gre(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function yre(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+hw.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}Zn.log=console.debug||console.log||(()=>{});function wre(r){try{r?Zn.storage.setItem("debug",r):Zn.storage.removeItem("debug")}catch{}}function xre(){let r;try{r=Zn.storage.getItem("debug")||Zn.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function bre(){try{return localStorage}catch{}}hw.exports=r$()(Zn);var{formatters:vre}=hw.exports;vre.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var x$=wt((Gct,w$)=>{"use strict";w$.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306640,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var Bne={};$t(Bne,{BasePlugin:()=>kt,DagCborHtmlPreviewPlugin:()=>lg,DirIndexHtmlPlugin:()=>cg,PluginError:()=>ig,PluginFatalError:()=>Oa,createVerifiedFetch:()=>CS,dagCborHtmlPreviewPluginFactory:()=>V$,dirIndexHtmlPluginFactory:()=>U$,verifiedFetch:()=>kw});var NS=Symbol.for("@libp2p/connection");var qo=Symbol.for("@libp2p/content-routing");function BS(r){return r==null?!1:(r.type==="RSA"||r.type==="Ed25519"||r.type==="secp256k1"||r.type==="ECDSA")&&r.raw instanceof Uint8Array&&typeof r.equals=="function"&&typeof r.toMultihash=="function"&&typeof r.toCID=="function"&&typeof r.verify=="function"}var tl=Symbol.for("@libp2p/peer-discovery");var dg=Symbol.for("@libp2p/peer-id");function Ti(r){return!!r?.[dg]}var jo=Symbol.for("@libp2p/peer-routing");var Na="keep-alive";var Ba=Symbol.for("@libp2p/transport");var rl;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(rl||(rl={}));var Je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},hg=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},pg=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},K=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},_s=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},cp=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var mg=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},bf=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},La=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Wo=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},gg=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},nl=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},qe=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},vf=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Ma=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},yg=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ua=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Cs=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Me=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},wg=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Ii=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Jn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Ts=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},il=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},lp=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},xg=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Fa=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},so=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var De=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function bg(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Rr(...r){let e=[];for(let t of r)bg(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Zr(...r){let e=[];for(let t of r)bg(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var et=Symbol.for("@libp2p/service-capabilities"),ei=Symbol.for("@libp2p/service-dependencies");function Pe(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var X=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var vg=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Af=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vg(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new vg(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Dw=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ar(r={}){return iH(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function iH(r,e){e=e??{};let t=e.onEnd,n=new Af,i,o,s,a=ve(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,x)=>{o=v=>{o=null,n.push(v);try{w(r(n))}catch(A){x(A)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ve()})}},l=w=>o!=null?o(w):(n.push(w),i),u=w=>(n=new Af,o!=null?o({error:w}):(n.push({error:w}),i)),f=w=>{if(s)return i;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},d=w=>s?i:(s=!0,w!=null?u(w):l({done:!0})),h=()=>(n=new Af,d(),{done:!0}),m=w=>(d(w),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async w=>{let x=w?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let v,A;x!=null&&(v=new Promise((S,M)=>{A=()=>{M(new Dw)},x.addEventListener("abort",A)}));try{await Promise.race([a.promise,v])}finally{A!=null&&x!=null&&x?.removeEventListener("abort",A)}}},t==null)return i;let g=i;return i={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(w){return g.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return g.end(w),t!=null&&(t(w),t=void 0),i},get readableLength(){return g.readableLength},onEmpty:w=>g.onEmpty(w)},i}var ti=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Kt(r,e,t,n){let i=new ti(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((s,a)=>{function c(){Nw(t,"abort",f),Nw(r,e,l),Nw(r,o,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),s(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(i)};Ow(t,"abort",f),Ow(r,e,l),Ow(r,o,u)})}function Ow(r,e,t){r!=null&&(LS(r)?r.addEventListener(e,t):r.addListener(e,t))}function Nw(r,e,t){r!=null&&(LS(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function LS(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Is(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ag=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Eg=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Sg=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function dt(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Sg(t?.errorMessage,t?.errorCode,t?.errorName));let n,i=new Sg(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,s)=>{n=()=>{s(i)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var _g=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ve(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function oH(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Cg=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=oH(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e={}){let t=new _g(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await dt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Dr=class extends De{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Is(this.emitEmpty.bind(this),1),this.emitIdle=Is(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Eg;let n=new Cg(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await Kt(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Kt(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Kt(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=ar({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var Or=class extends Dr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function sH(r){return r[Symbol.asyncIterator]!=null}function aH(r){if(sH(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Jr=aH;function ke(r=0){return new Uint8Array(r)}function Ht(r=0){return new Uint8Array(r)}var cH=Math.pow(2,7),lH=Math.pow(2,14),uH=Math.pow(2,21),Bw=Math.pow(2,28),Lw=Math.pow(2,35),Mw=Math.pow(2,42),Uw=Math.pow(2,49),ht=128,en=127;function je(r){if(r<cH)return 1;if(r<lH)return 2;if(r<uH)return 3;if(r<Bw)return 4;if(r<Lw)return 5;if(r<Mw)return 6;if(r<Uw)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ef(r,e,t=0){switch(je(r)){case 8:e[t++]=r&255|ht,r/=128;case 7:e[t++]=r&255|ht,r/=128;case 6:e[t++]=r&255|ht,r/=128;case 5:e[t++]=r&255|ht,r/=128;case 4:e[t++]=r&255|ht,r>>>=7;case 3:e[t++]=r&255|ht,r>>>=7;case 2:e[t++]=r&255|ht,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function fH(r,e,t=0){switch(je(r)){case 8:e.set(t++,r&255|ht),r/=128;case 7:e.set(t++,r&255|ht),r/=128;case 6:e.set(t++,r&255|ht),r/=128;case 5:e.set(t++,r&255|ht),r/=128;case 4:e.set(t++,r&255|ht),r>>>=7;case 3:e.set(t++,r&255|ht),r>>>=7;case 2:e.set(t++,r&255|ht),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Fw(r,e){let t=r[e],n=0;if(n+=t&en,t<ht||(t=r[e+1],n+=(t&en)<<7,t<ht)||(t=r[e+2],n+=(t&en)<<14,t<ht)||(t=r[e+3],n+=(t&en)<<21,t<ht)||(t=r[e+4],n+=(t&en)*Bw,t<ht)||(t=r[e+5],n+=(t&en)*Lw,t<ht)||(t=r[e+6],n+=(t&en)*Mw,t<ht)||(t=r[e+7],n+=(t&en)*Uw,t<ht))return n;throw new RangeError("Could not decode varint")}function dH(r,e){let t=r.get(e),n=0;if(n+=t&en,t<ht||(t=r.get(e+1),n+=(t&en)<<7,t<ht)||(t=r.get(e+2),n+=(t&en)<<14,t<ht)||(t=r.get(e+3),n+=(t&en)<<21,t<ht)||(t=r.get(e+4),n+=(t&en)*Bw,t<ht)||(t=r.get(e+5),n+=(t&en)*Lw,t<ht)||(t=r.get(e+6),n+=(t&en)*Mw,t<ht)||(t=r.get(e+7),n+=(t&en)*Uw,t<ht))return n;throw new RangeError("Could not decode varint")}function Sr(r,e,t=0){return e==null&&(e=Ht(je(r))),e instanceof Uint8Array?Ef(r,e,t):fH(r,e,t)}function ao(r,e=0){return r instanceof Uint8Array?Fw(r,e):dH(r,e)}function Xe(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Ht(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function he(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var US=Symbol.for("@achingbrain/uint8arraylist");function MS(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function ki(r){return!!r?.[US]}var pe=class r{bufs;length;[US]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ki(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ki(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=MS(this.bufs,e);return t.buf[t.index]}set(e,t){let n=MS(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ki(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return Xe(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:Xe(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new r;return o.length=i,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(u){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ki(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f<o;f++)s[f]=-1;for(let f=0;f<i;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ht(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=ke(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=ke(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=ke(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ht(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=ke(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=ke(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=ke(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=ke(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=ke(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!he(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((i,o)=>i+o.byteLength,0)),n.length=t,n}};var Tg=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Sf=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ig=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},up=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function kg(r){return r[Symbol.asyncIterator]!=null}function FS(r,e){if(r.byteLength>e)throw new Sf("Message length too long")}var Rg=r=>{let e=je(r),t=Ht(e);return Sr(r,t),Rg.bytes=e,t};Rg.bytes=0;function Ps(r,e){e=e??{};let t=e.lengthEncoder??Rg,n=e?.maxDataLength??4194304;function*i(o){FS(o,n);let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return kg(r)?(async function*(){for await(let o of r)yield*i(o)})():(function*(){for(let o of r)yield*i(o)})()}Ps.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Rg,n=e?.maxDataLength??4194304;return FS(r,n),new pe(t(r.byteLength),r)};var ol;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ol||(ol={}));var $w=r=>{let e=ao(r);return $w.bytes=je(e),e};$w.bytes=0;function Rs(r,e){let t=new pe,n=ol.LENGTH,i=-1,o=e?.lengthDecoder??$w,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ol.LENGTH)try{if(i=o(t),i<0)throw new Tg("Invalid message length");if(i>a)throw new Sf("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=ol.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new Ig("Message length length too long");break}throw l}if(n===ol.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=ol.LENGTH}}}return kg(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new up("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new up("Unexpected end of input")})()}Rs.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Rs(n,{...e??{},onLength:o=>{t=o}})};function mH(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var _f=mH;function gH(r){return r[Symbol.asyncIterator]!=null}function yH(r,e){let t=0;if(gH(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=_f(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){yield await s;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield s;for(let c of n)yield a(c,t++)})()}var zt=yH;var Hw=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ve(),this.haveNext=ve()}[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 e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ve(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ve(),await dt(this.readNext.promise,t?.signal,t)}};function Dg(){return new Hw}function wH(r){return r[Symbol.asyncIterator]!=null}async function xH(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*bH(r){let e=new AbortController,t=Dg();xH(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*vH(r){for(let e of r)yield*e}function AH(...r){let e=[];for(let t of r)wH(t)||e.push(t);return e.length===r.length?vH(e):bH(r)}var pn=AH;function vt(r,...e){if(r==null)throw new Error("Empty pipeline");if(Vw(r)){let n=r;r=()=>n.source}else if(VS(r)||HS(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Vw(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Vw(t[n])&&(t[n]=SH(t[n]));return EH(...t)}var EH=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},HS=r=>r?.[Symbol.asyncIterator]!=null,VS=r=>r?.[Symbol.iterator]!=null,Vw=r=>r==null?!1:r.sink!=null&&r.source!=null,SH=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=ar({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let i,o=r.source;if(HS(o))i=async function*(){yield*o,n.end()};else if(VS(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return pn(n,i())}return r.source};function _H(r){return r[Symbol.asyncIterator]!=null}function CH(r,e){return _H(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var $a=CH;var fp="/ipfs/bitswap/1.2.0";var Kw=new Float32Array([-0]),Ha=new Uint8Array(Kw.buffer);function KS(r,e,t){Kw[0]=r,e[t]=Ha[0],e[t+1]=Ha[1],e[t+2]=Ha[2],e[t+3]=Ha[3]}function zS(r,e){return Ha[0]=r[e],Ha[1]=r[e+1],Ha[2]=r[e+2],Ha[3]=r[e+3],Kw[0]}var zw=new Float64Array([-0]),tn=new Uint8Array(zw.buffer);function qS(r,e,t){zw[0]=r,e[t]=tn[0],e[t+1]=tn[1],e[t+2]=tn[2],e[t+3]=tn[3],e[t+4]=tn[4],e[t+5]=tn[5],e[t+6]=tn[6],e[t+7]=tn[7]}function jS(r,e){return tn[0]=r[e],tn[1]=r[e+1],tn[2]=r[e+2],tn[3]=r[e+3],tn[4]=r[e+4],tn[5]=r[e+5],tn[6]=r[e+6],tn[7]=r[e+7],zw[0]}var TH=BigInt(Number.MAX_SAFE_INTEGER),IH=BigInt(Number.MIN_SAFE_INTEGER),ri=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return sl;if(e<TH&&e>IH)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>WS&&(i=0n,++n>WS&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return sl;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):sl}},sl=new ri(0,0);sl.toBigInt=function(){return 0n};sl.zzEncode=sl.zzDecode=function(){return this};sl.length=function(){return 1};var WS=4294967296n;function GS(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function XS(r,e,t){if(t-e<1)return"";let i,o=[],s=0,a;for(;e<t;)a=r[e++],a<128?o[s++]=a:a>191&&a<224?o[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function qw(r,e,t){let n=t,i,o;for(let s=0;s<r.length;++s)i=r.charCodeAt(s),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((o=r.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function co(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Og(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var jw=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,co(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw co(this,4);return Og(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw co(this,4);return Og(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw co(this,4);let e=zS(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw co(this,4);let e=jS(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw co(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return XS(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw co(this,e);this.pos+=e}else do if(this.pos>=this.len)throw co(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ri(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw co(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw co(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw co(this,8);let e=Og(this.buf,this.pos+=4),t=Og(this.buf,this.pos+=4);return new ri(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Fw(this.buf,this.pos);return this.pos+=je(e),e}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 Ww(r){return new jw(r instanceof Uint8Array?r:r.subarray())}function we(r,e,t){let n=Ww(r);return e.decode(n,void 0,t)}var t7={};$t(t7,{base10:()=>UH});var al={};$t(al,{coerce:()=>Pi,empty:()=>QS,equals:()=>Gw,fromHex:()=>PH,fromString:()=>Xw,isBinary:()=>RH,toHex:()=>kH,toString:()=>Yw});var QS=new Uint8Array(0);function kH(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function PH(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):QS}function Gw(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Pi(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 RH(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function Xw(r){return new TextEncoder().encode(r)}function Yw(r){return new TextDecoder().decode(r)}function DH(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}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 g=0,w=0,x=0,v=m.length;x!==v&&m[x]===0;)x++,g++;for(var A=(v-x)*u+1>>>0,S=new Uint8Array(A);x!==v;){for(var M=m[x],F=0,N=A-1;(M!==0||F<w)&&N!==-1;N--,F++)M+=256*S[N]>>>0,S[N]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");w=F,x++}for(var R=A-w;R!==A&&S[R]===0;)R++;for(var _=c.repeat(g);R<A;++R)_+=r.charAt(S[R]);return _}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var g=0;if(m[g]!==" "){for(var w=0,x=0;m[g]===c;)w++,g++;for(var v=(m.length-g)*l+1>>>0,A=new Uint8Array(v);m[g];){var S=t[m.charCodeAt(g)];if(S===255)return;for(var M=0,F=v-1;(S!==0||M<x)&&F!==-1;F--,M++)S+=a*A[F]>>>0,A[F]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");x=M,g++}if(m[g]!==" "){for(var N=v-x;N!==v&&A[N]===0;)N++;for(var R=new Uint8Array(w+(v-N)),_=w;N!==v;)R[_++]=A[N++];return R}}}function h(m){var g=d(m);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var OH=DH,NH=OH,ZS=NH;var Qw=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Zw=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return JS(this,e)}},Jw=class{decoders;constructor(e){this.decoders=e}or(e){return JS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function JS(r,e){return new Jw({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var e7=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Qw(e,t,n),this.decoder=new Zw(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Cf({name:r,prefix:e,encode:t,decode:n}){return new e7(r,e,t,n)}function Va({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=ZS(t,r);return Cf({prefix:e,name:r,encode:n,decode:o=>Pi(i(o))})}function BH(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),s=0,a=0,c=0;for(let l=0;l<i;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,s+=t,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function LH(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<<t-s]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function MH(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function qt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=MH(n);return Cf({prefix:e,name:r,encode(o){return LH(o,n,t)},decode(o){return BH(o,i,t,r)}})}var UH=Va({prefix:"9",name:"base10",alphabet:"0123456789"});var r7={};$t(r7,{base16:()=>FH,base16upper:()=>$H});var FH=qt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$H=qt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var n7={};$t(n7,{base2:()=>HH});var HH=qt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var i7={};$t(i7,{base256emoji:()=>jH});var e_=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}"),VH=e_.reduce((r,e,t)=>(r[t]=e,r),[]),KH=e_.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function zH(r){return r.reduce((e,t)=>(e+=VH[t],e),"")}function qH(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=KH[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var jH=Cf({prefix:"\u{1F680}",name:"base256emoji",encode:zH,decode:qH});var o7={};$t(o7,{base32:()=>jt,base32hex:()=>YH,base32hexpad:()=>ZH,base32hexpadupper:()=>JH,base32hexupper:()=>QH,base32pad:()=>GH,base32padupper:()=>XH,base32upper:()=>WH,base32z:()=>eV});var jt=qt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),WH=qt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),GH=qt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),XH=qt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),YH=qt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),QH=qt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZH=qt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),JH=qt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),eV=qt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var s7={};$t(s7,{base36:()=>mn,base36upper:()=>tV});var mn=Va({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tV=Va({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var a7={};$t(a7,{base58btc:()=>Ye,base58flickr:()=>rV});var Ye=Va({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rV=Va({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var c7={};$t(c7,{base64:()=>cr,base64pad:()=>nV,base64url:()=>cl,base64urlpad:()=>iV});var cr=qt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nV=qt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cl=qt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iV=qt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var l7={};$t(l7,{base8:()=>oV});var oV=qt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var u7={};$t(u7,{identity:()=>sV});var sV=Cf({prefix:"\0",name:"identity",encode:r=>Yw(r),decode:r=>Xw(r)});var Tf={};$t(Tf,{code:()=>Go,decode:()=>f7,encode:()=>uV,name:()=>lV});var aV=new TextEncoder,cV=new TextDecoder,lV="json",Go=512;function uV(r){return aV.encode(JSON.stringify(r))}function f7(r){return JSON.parse(cV.decode(r))}var Rn={};$t(Rn,{code:()=>At,decode:()=>hV,encode:()=>dV,name:()=>fV});var fV="raw",At=85;function dV(r){return Pi(r)}function hV(r){return Pi(r)}var p7={};$t(p7,{identity:()=>lr});var Et={};$t(Et,{Digest:()=>ll,create:()=>gn,decode:()=>We,equals:()=>h7,hasCode:()=>DV});var pV=n_,t_=128,mV=127,gV=~mV,yV=Math.pow(2,31);function n_(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yV;)e[t++]=r&255|t_,r/=128;for(;r&gV;)e[t++]=r&255|t_,r>>>=7;return e[t]=r|0,n_.bytes=t-n+1,e}var wV=d7,xV=128,r_=127;function d7(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw d7.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&r_)<<i:(s&r_)*Math.pow(2,i),i+=7}while(s>=xV);return d7.bytes=o-n,t}var bV=Math.pow(2,7),vV=Math.pow(2,14),AV=Math.pow(2,21),EV=Math.pow(2,28),SV=Math.pow(2,35),_V=Math.pow(2,42),CV=Math.pow(2,49),TV=Math.pow(2,56),IV=Math.pow(2,63),kV=function(r){return r<bV?1:r<vV?2:r<AV?3:r<EV?4:r<SV?5:r<_V?6:r<CV?7:r<TV?8:r<IV?9:10},PV={encode:pV,decode:wV,encodingLength:kV},RV=PV,dp=RV;function hp(r,e=0){return[dp.decode(r,e),dp.decode.bytes]}function If(r,e,t=0){return dp.encode(r,e,t),e}function kf(r){return dp.encodingLength(r)}function gn(r,e){let t=e.byteLength,n=kf(r),i=n+kf(t),o=new Uint8Array(i+t);return If(r,o,0),If(t,o,n),o.set(e,i),new ll(r,t,e,o)}function We(r){let e=Pi(r),[t,n]=hp(e),[i,o]=hp(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new ll(t,i,s,e)}function h7(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Gw(r.bytes,t.bytes)}}var ll=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};function DV(r,e){return r.code===e}var i_=0,OV="identity",o_=Pi;function NV(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return gn(i_,o_(r))}var lr={code:i_,name:OV,encode:o_,digest:NV};var g7={};$t(g7,{sha256:()=>Be,sha512:()=>Bg});var BV=20;function ul({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new m7(r,e,t,n,i)}var m7=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??BV,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?s_(n,this.code,t?.truncate):n.then(i=>s_(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function s_(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return gn(e,r)}function c_(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Be=ul({name:"sha2-256",code:18,encode:c_("SHA-256")}),Bg=ul({name:"sha2-512",code:19,encode:c_("SHA-512")});function y7(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return MV(t,w7(r),e??Ye.encoder);default:return UV(t,w7(r),e??jt.encoder)}}var l_=new WeakMap;function w7(r){let e=l_.get(r);if(e==null){let t=new Map;return l_.set(r,t),t}return e}var G=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:e,multihash:t}=this;if(e!==pp)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==FV)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:e,digest:t}=this.multihash,n=gn(e,t);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(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&h7(e.multihash,n.multihash)}toString(e){return y7(this,e)}toJSON(){return{"/":y7(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new r(n,i,o,s??u_(n,i,o.bytes))}else if(t[$V]===!0){let{version:n,multihash:i,code:o}=t,s=We(i);return r.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==pp)throw new Error(`Version 0 CID must use dag-pb (code: ${pp}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=u_(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,pp,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=Pi(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new ll(t.multihashCode,t.digestSize,o,i);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=hp(e.subarray(t));return t+=d,f},i=n(),o=pp;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),l=t+c,u=l-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,i]=LV(e,t),o=r.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return w7(o).set(n,e),o}};function LV(r,e){switch(r[0]){case"Q":{let t=e??Ye;return[Ye.prefix,t.decode(`${Ye.prefix}${r}`)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}case jt.prefix:{let t=e??jt;return[jt.prefix,t.decode(r)]}case mn.prefix:{let t=e??mn;return[mn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function MV(r,e,t){let{prefix:n}=t;if(n!==Ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function UV(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var pp=112,FV=18;function u_(r,e,t){let n=kf(r),i=n+kf(e),o=new Uint8Array(i+t.byteLength);return If(r,o,0),If(e,o,n),o.set(t,i),o}var $V=Symbol.for("@ipld/js-cid/CID");var fl={...u7,...n7,...l7,...t7,...r7,...o7,...s7,...a7,...c7,...i7},Ase={...g7,...p7};function d_(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var f_=d_("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),x7=d_("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ht(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),HV={utf8:f_,"utf-8":f_,hex:fl.base16,latin1:x7,ascii:x7,binary:x7,...fl},Lg=HV;function D(r,e="utf8"){let t=Lg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function b7(r){let e=r??8192,t=e>>>1,n,i=e;return function(s){if(s<1||s>t)return Ht(s);i+s>e&&(n=Ht(e),i=0);let a=n.subarray(i,i+=s);return(i&7)!==0&&(i=(i|7)+1),a}}var dl=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function v7(){}var E7=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},VV=b7();function KV(r){return globalThis.Buffer!=null?Ht(r):VV(r)}var gp=class{len;head;tail;states;constructor(){this.len=0,this.head=new dl(v7,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new dl(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new S7((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Mg,10,ri.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ri.fromBigInt(e);return this._push(Mg,t.length(),t)}uint64Number(e){return this._push(Ef,je(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=ri.fromBigInt(e).zzEncode();return this._push(Mg,t.length(),t)}sint64Number(e){let t=ri.fromNumber(e).zzEncode();return this._push(Mg,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(A7,1,e?1:0)}fixed32(e){return this._push(mp,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ri.fromBigInt(e);return this._push(mp,4,t.lo)._push(mp,4,t.hi)}fixed64Number(e){let t=ri.fromNumber(e);return this._push(mp,4,t.lo)._push(mp,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(KS,4,e)}double(e){return this._push(qS,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(A7,1,0):this.uint32(t)._push(qV,t,e)}string(e){let t=GS(e);return t!==0?this.uint32(t)._push(qw,t,e):this._push(A7,1,0)}fork(){return this.states=new E7(this),this.head=this.tail=new dl(v7,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 dl(v7,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=KV(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function A7(r,e,t){e[t]=r&255}function zV(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var S7=class extends dl{next;constructor(e,t){super(zV,e,t),this.next=void 0}};function Mg(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function mp(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function qV(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(gp.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(jV,e,r),this},gp.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(WV,e,r),this});function jV(r,e,t){e.set(r,t)}function WV(r,e,t){r.length<40?qw(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function _7(){return new gp}function xe(r,e){let t=_7();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Pf;(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"})(Pf||(Pf={}));function Ug(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function St(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return Ug("enum",Pf.VARINT,t,n)}function be(r,e){return Ug("message",Pf.LENGTH_DELIMITED,r,e)}var xt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},yp=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var tr;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tr||(tr={}));var C7;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(C7||(C7={}));(function(r){r.codec=()=>St(C7)})(tr||(tr={}));var Rf;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),tr.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={cid:ke(0),priority:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.priority=t.int32();break}case 3:{o.cancel=t.bool();break}case 4:{o.wantType=tr.codec().decode(t);break}case 5:{o.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Rf||(Rf={}));var Fg;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let o of t.entries)n.uint32(10),Rf.codec().encode(o,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={entries:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{if(i.limits?.entries!=null&&o.entries.length===i.limits.entries)throw new xt('Decode error - map field "entries" had too many elements');o.entries.push(Rf.codec().decode(t,t.uint32(),{limits:i.limits?.entries$}));break}case 2:{o.full=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Fg||(Fg={}));var Df;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={prefix:ke(0),data:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.prefix=t.bytes();break}case 2:{o.data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Df||(Df={}));var Ri;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Ri||(Ri={}));var $g;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})($g||($g={}));(function(r){r.codec=()=>St($g)})(Ri||(Ri={}));var Of;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&$g[t.type]!==0&&(n.uint32(16),Ri.codec().encode(t.type,n)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={cid:ke(0),type:Ri.HaveBlock},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.type=Ri.codec().decode(t);break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Of||(Of={}));var hl;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),Fg.codec().encode(t.wantlist,n)),t.blocks!=null)for(let o of t.blocks)n.uint32(26),Df.codec().encode(o,n);if(t.blockPresences!=null)for(let o of t.blockPresences)n.uint32(34),Of.codec().encode(o,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.wantlist=Fg.codec().decode(t,t.uint32(),{limits:i.limits?.wantlist});break}case 3:{if(i.limits?.blocks!=null&&o.blocks.length===i.limits.blocks)throw new xt('Decode error - map field "blocks" had too many elements');o.blocks.push(Df.codec().decode(t,t.uint32(),{limits:i.limits?.blocks$}));break}case 4:{if(i.limits?.blockPresences!=null&&o.blockPresences.length===i.limits.blockPresences)throw new xt('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Of.codec().decode(t,t.uint32(),{limits:i.limits?.blockPresences$}));break}case 5:{o.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(hl||(hl={}));function h_(r,e){for(let[t,n]of e.wantlist.entries()){let i=r.wantlist.get(t);i!=null&&(i.priority>n.priority&&(n.priority=i.priority),n.cancel=n.cancel??i.cancel,n.wantType=n.wantType??i.wantType,n.sendDontHave=n.sendDontHave??i.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var Hg=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var GV=4193648,XV=GV+16;function*p_(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],i=[...r.blocks.values()],o=0,s=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=hl.encode(l).byteLength,{added:f,hasMore:d,newSize:h}=T7(i,l.blocks,a,e,u,YV);a+=f,u=h;let m=d;({added:f,hasMore:d,newSize:h}=T7(n,l.blockPresences,s,e,u,QV)),s+=f,u=h;let g=d;if({added:f,hasMore:d,newSize:h}=T7(t,l.wantlist.entries,o,e,u,ZV),o+=f,u=h,c=!m&&!g&&!d,c||(l.wantlist.full=!1),yield hl.encode(l),c)break}}function T7(r,e,t,n,i,o){let s=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=o(l);if(u>XV)throw new Hg("Cannot send block as after encoding it is over the max message size");let f=i+u;if(f>n){a=!0;break}e.push(l),s++,i=f}return{hasMore:a,added:s,newSize:i}}function YV(r){return I7(3,Df.encode(r))}function QV(r){return I7(4,Of.encode(r))}function ZV(r){return I7(1,Rf.encode(r))}function I7(r,e){let t=je(r),n=je(e.byteLength);return t+n+e.byteLength}var Vg=class extends De{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[fp],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Or({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let i=()=>{t.status==="open"?t.abort(new Ii(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",i),await t.closeWrite(),await vt(t,s=>Rs(s,{maxDataLength:this.maxIncomingMessageSize}),async s=>{for await(let a of s)try{let c=hl.decode(a);this.log("incoming new bitswap %s message from %p on stream",t.protocol,n.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),o.removeEventListener("abort",i),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",i)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,t.id,c),t.abort(c);break}})}).catch(i=>{this.log.error("error handling incoming stream from %p",n.remotePeer,i),t.abort(i)})}async*findProviders(e,t){t?.onProgress?.(new X("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(i=>{this.log.error("could not connect to supplied provider - %e",i)}))),await Jr(zt($a(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let i=this.sendQueue.queue.find(o=>e.equals(o.options.peerId)&&o.status==="queued");if(i!=null){i.options.message=h_(i.options.message,t),await i.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let s=o?.message;if(s==null)throw new K("No message to send");this.log("sendMessage to %p",e),o?.onProgress?.(new X("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,fp,o);await a.closeRead();try{await vt(p_(s,this.maxOutgoingMessageSize),c=>Ps(c),a),await a.close(o)}catch(c){o?.onProgress?.(new X("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p",e,c),a.abort(c)}this._updateSentStats(s.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new Jn("Network isn't running");t?.onProgress?.(new X("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),Kt(this.libp2p,"peer:identify",t?.signal,{filter:i=>{if(!i.detail.peerId.equals(e))return!1;if(i.detail.protocols.includes(fp))return!0;throw new Cs(`${e} did not support ${fp}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function z(r,e="utf8"){let t=Lg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var aK=parseInt("11111",2),k7=parseInt("10000000",2),cK=parseInt("01111111",2),m_={0:wp,1:wp,2:lK,3:dK,4:hK,5:fK,6:uK,16:wp,22:wp,48:wp};function Di(r,e={offset:0}){let t=r[e.offset]&aK;if(e.offset++,m_[t]!=null)return m_[t](r,e);throw new Error("No decoder for tag "+t)}function xp(r,e){let t=0;if((r[e.offset]&k7)===k7){let n=r[e.offset]&cK,i="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)i+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(i,16)}else t=r[e.offset],e.offset++;return t}function wp(r,e){xp(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Di(r,e);if(n===null)break;t.push(n)}return t}function lK(r,e){let t=xp(r,e),n=e.offset,i=e.offset+t,o=[];for(let s=n;s<i;s++)s===n&&r[s]===0||o.push(r[s]);return e.offset+=t,Uint8Array.from(o)}function uK(r,e){let t=xp(r,e),n=e.offset+t,i=r[e.offset];e.offset++;let o=0,s=0;i<40?(o=0,s=i):i<80?(o=1,s=i-40):(o=2,s=i-80);let a=`${o}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function fK(r,e){return e.offset++,null}function dK(r,e){let t=xp(r,e),n=r[e.offset];e.offset++;let i=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return i}function hK(r,e){let t=xp(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function pK(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new pe;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Kg(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=pK(r.byteLength);return new pe(Uint8Array.from([e.byteLength|k7]),e)}function yn(r){let e=new pe,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new pe(Uint8Array.from([2]),Kg(e),e)}function bp(r){let e=Uint8Array.from([0]),t=new pe(e,r);return new pe(Uint8Array.from([3]),Kg(t),t)}function g_(r){return new pe(Uint8Array.from([4]),Kg(r),r)}function lo(r,e=48){let t=new pe;for(let n of r)t.append(n);return new pe(Uint8Array.from([e]),Kg(t),t)}var y_="1.2.840.10045.3.1.7",w_="1.3.132.0.34",x_="1.3.132.0.35";async function b_(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function v_(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let i=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}async function A_(r,e,t,n){let i=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,t.subarray());return n?.signal?.throwIfAborted(),o}var mK=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),gK=Uint8Array.from([6,5,43,129,4,0,34]),yK=Uint8Array.from([6,5,43,129,4,0,35]),E_={ext:!0,kty:"EC",crv:"P-256"},S_={ext:!0,kty:"EC",crv:"P-384"},__={ext:!0,kty:"EC",crv:"P-521"},Nf=32,Bf=48,Lf=66;function C_(r){let e=Di(r);return P7(e)}function P7(r){let e=r[1],t=z(e,"base64url"),n=r[2][1][0],i=1,o,s;if(e.byteLength===Nf)return o=z(n.subarray(i,i+Nf),"base64url"),s=z(n.subarray(i+Nf),"base64url"),new ml({...E_,key_ops:["sign"],d:t,x:o,y:s});if(e.byteLength===Bf)return o=z(n.subarray(i,i+Bf),"base64url"),s=z(n.subarray(i+Bf),"base64url"),new ml({...S_,key_ops:["sign"],d:t,x:o,y:s});if(e.byteLength===Lf)return o=z(n.subarray(i,i+Lf),"base64url"),s=z(n.subarray(i+Lf),"base64url"),new ml({...__,key_ops:["sign"],d:t,x:o,y:s});throw new K(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function R7(r){let e=Di(r);return T_(e)}function T_(r){let e=r[1][1][0],t=1,n,i;if(e.byteLength===Nf*2+1)return n=z(e.subarray(t,t+Nf),"base64url"),i=z(e.subarray(t+Nf),"base64url"),new pl({...E_,key_ops:["verify"],x:n,y:i});if(e.byteLength===Bf*2+1)return n=z(e.subarray(t,t+Bf),"base64url"),i=z(e.subarray(t+Bf),"base64url"),new pl({...S_,key_ops:["verify"],x:n,y:i});if(e.byteLength===Lf*2+1)return n=z(e.subarray(t,t+Lf),"base64url"),i=z(e.subarray(t+Lf),"base64url"),new pl({...__,key_ops:["verify"],x:n,y:i});throw new K(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function I_(r){return lo([yn(Uint8Array.from([1])),g_(D(r.d??"","base64url")),lo([P_(r.crv)],160),lo([bp(new pe(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function k_(r){return lo([yn(Uint8Array.from([1])),lo([P_(r.crv)],160),lo([bp(new pe(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function P_(r){if(r==="P-256")return mK;if(r==="P-384")return gK;if(r==="P-521")return yK;throw new K(`Invalid curve ${r}`)}async function R_(r="P-256"){let e=await b_(r);return new ml(e.privateKey)}var pl=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=k_(this.jwk)),this._raw}toMultihash(){return lr.digest(ur(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}async verify(e,t,n){return A_(this.jwk,t,e,n)}},ml=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new pl({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=I_(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}async sign(e,t){return v_(this.jwk,e,t)}};var gl=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Os(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function uo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Nr(r,...e){if(!Os(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Ns(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");uo(r.outputLen),uo(r.blockLen)}function Uf(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function O_(r,e){Nr(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function rn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function yl(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function fo(r,e){return r<<32-e|r>>>e}function zg(r,e){return r<<e|r>>>32-e>>>0}var N_=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wK=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Oi(r){if(Nr(r),N_)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=wK[r[t]];return e}var Ds={_0:48,_9:57,A:65,F:70,a:97,f:102};function D_(r){if(r>=Ds._0&&r<=Ds._9)return r-Ds._0;if(r>=Ds.A&&r<=Ds.F)return r-(Ds.A-10);if(r>=Ds.a&&r<=Ds.f)return r-(Ds.a-10)}function wl(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(N_)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let i=0,o=0;i<t;i++,o+=2){let s=D_(r.charCodeAt(o)),a=D_(r.charCodeAt(o+1));if(s===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}var xK=async()=>{};async function B_(r,e,t){let n=Date.now();for(let i=0;i<r;i++){t(i);let o=Date.now()-n;o>=0&&o<e||(await xK(),n+=o)}}function qg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ka(r){return typeof r=="string"&&(r=qg(r)),Nr(r),r}function D7(r){return typeof r=="string"&&(r=qg(r)),Nr(r),r}function wn(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];Nr(i),e+=i.length}let t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let o=r[n];t.set(o,i),i+=o.length}return t}function L_(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(r,e)}var Mf=class{};function vp(r){let e=n=>r().update(Ka(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Xo(r=32){if(gl&&typeof gl.getRandomValues=="function")return gl.getRandomValues(new Uint8Array(r));if(gl&&typeof gl.randomBytes=="function")return Uint8Array.from(gl.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function bK(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(t>>i&o),a=Number(t&o),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,a,n)}function jg(r,e,t){return r&e^~r&t}function Wg(r,e,t){return r&e^r&t^e&t}var xl=class extends Mf{constructor(e,t,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=yl(this.buffer)}update(e){Uf(this),e=Ka(e),Nr(e);let{view:t,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=yl(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Uf(this),O_(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,rn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)t[f]=0;bK(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=yl(e),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],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Bs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Br=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Gg=BigInt(4294967295),M_=BigInt(32);function vK(r,e=!1){return e?{h:Number(r&Gg),l:Number(r>>M_&Gg)}:{h:Number(r>>M_&Gg)|0,l:Number(r&Gg)|0}}function U_(r,e=!1){let t=r.length,n=new Uint32Array(t),i=new Uint32Array(t);for(let o=0;o<t;o++){let{h:s,l:a}=vK(r[o],e);[n[o],i[o]]=[s,a]}return[n,i]}var O7=(r,e,t)=>r>>>t,N7=(r,e,t)=>r<<32-t|e>>>t,bl=(r,e,t)=>r>>>t|e<<32-t,vl=(r,e,t)=>r<<32-t|e>>>t,Ap=(r,e,t)=>r<<64-t|e>>>t-32,Ep=(r,e,t)=>r>>>t-32|e<<64-t;function Yo(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}var F_=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),$_=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,H_=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),V_=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,K_=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),z_=(r,e,t,n,i,o)=>e+t+n+i+o+(r/2**32|0)|0;var EK=Uint32Array.from([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]),za=new Uint32Array(64),Xg=class extends xl{constructor(e=32){super(64,e,8,!1),this.A=Bs[0]|0,this.B=Bs[1]|0,this.C=Bs[2]|0,this.D=Bs[3]|0,this.E=Bs[4]|0,this.F=Bs[5]|0,this.G=Bs[6]|0,this.H=Bs[7]|0}get(){let{A:e,B:t,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,n,i,o,s,a,c]}set(e,t,n,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)za[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=za[f-15],h=za[f-2],m=fo(d,7)^fo(d,18)^d>>>3,g=fo(h,17)^fo(h,19)^h>>>10;za[f]=g+za[f-7]+m+za[f-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=fo(a,6)^fo(a,11)^fo(a,25),h=u+d+jg(a,c,l)+EK[f]+za[f]|0,g=(fo(n,2)^fo(n,13)^fo(n,22))+Wg(n,i,o)|0;u=l,l=c,c=a,a=s+h|0,s=o,o=i,i=n,n=h+g|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+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,i,o,s,a,c,l,u)}roundClean(){rn(za)}destroy(){this.set(0,0,0,0,0,0,0,0),rn(this.buffer)}};var q_=U_(["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))),SK=q_[0],_K=q_[1],qa=new Uint32Array(80),ja=new Uint32Array(80),Yg=class extends xl{constructor(e=64){super(128,e,16,!1),this.Ah=Br[0]|0,this.Al=Br[1]|0,this.Bh=Br[2]|0,this.Bl=Br[3]|0,this.Ch=Br[4]|0,this.Cl=Br[5]|0,this.Dh=Br[6]|0,this.Dl=Br[7]|0,this.Eh=Br[8]|0,this.El=Br[9]|0,this.Fh=Br[10]|0,this.Fl=Br[11]|0,this.Gh=Br[12]|0,this.Gl=Br[13]|0,this.Hh=Br[14]|0,this.Hl=Br[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:g,Hl:w}=this;return[e,t,n,i,o,s,a,c,l,u,f,d,h,m,g,w]}set(e,t,n,i,o,s,a,c,l,u,f,d,h,m,g,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=g|0,this.Hl=w|0}process(e,t){for(let A=0;A<16;A++,t+=4)qa[A]=e.getUint32(t),ja[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let S=qa[A-15]|0,M=ja[A-15]|0,F=bl(S,M,1)^bl(S,M,8)^O7(S,M,7),N=vl(S,M,1)^vl(S,M,8)^N7(S,M,7),R=qa[A-2]|0,_=ja[A-2]|0,$=bl(R,_,19)^Ap(R,_,61)^O7(R,_,6),V=vl(R,_,19)^Ep(R,_,61)^N7(R,_,6),H=H_(N,V,ja[A-7],ja[A-16]),E=V_(H,F,$,qa[A-7],qa[A-16]);qa[A]=E|0,ja[A]=H|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:g,Gl:w,Hh:x,Hl:v}=this;for(let A=0;A<80;A++){let S=bl(f,d,14)^bl(f,d,18)^Ap(f,d,41),M=vl(f,d,14)^vl(f,d,18)^Ep(f,d,41),F=f&h^~f&g,N=d&m^~d&w,R=K_(v,M,N,_K[A],ja[A]),_=z_(R,x,S,F,SK[A],qa[A]),$=R|0,V=bl(n,i,28)^Ap(n,i,34)^Ap(n,i,39),H=vl(n,i,28)^Ep(n,i,34)^Ep(n,i,39),E=n&o^n&a^o&a,T=i&s^i&c^s&c;x=g|0,v=w|0,g=h|0,w=m|0,h=f|0,m=d|0,{h:f,l:d}=Yo(l|0,u|0,_|0,$|0),l=a|0,u=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let C=F_($,H,T);n=$_(C,_,V,E),i=C|0}({h:n,l:i}=Yo(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=Yo(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=Yo(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Yo(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=Yo(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=Yo(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:w}=Yo(this.Gh|0,this.Gl|0,g|0,w|0),{h:x,l:v}=Yo(this.Hh|0,this.Hl|0,x|0,v|0),this.set(n,i,o,s,a,c,l,u,f,d,h,m,g,w,x,v)}roundClean(){rn(qa,ja)}destroy(){rn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Qg=vp(()=>new Xg);var Zg=vp(()=>new Yg);var M7=BigInt(0),L7=BigInt(1);function Ls(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function ii(r,e,t=""){let n=Os(r),i=r?.length,o=e!==void 0;if(!n||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return r}function Sp(r){let e=r.toString(16);return e.length&1?"0"+e:e}function j_(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?M7:BigInt("0x"+r)}function Ff(r){return j_(Oi(r))}function Ni(r){return Nr(r),j_(Oi(Uint8Array.from(r).reverse()))}function Jg(r,e){return wl(r.toString(16).padStart(e*2,"0"))}function _p(r,e){return Jg(r,e).reverse()}function at(r,e,t){let n;if(typeof e=="string")try{n=wl(e)}catch(o){throw new Error(r+" must be hex string or Uint8Array, cause: "+o)}else if(Os(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let i=n.length;if(typeof t=="number"&&i!==t)throw new Error(r+" of length "+t+" expected, got "+i);return n}function W_(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function U7(r){return Uint8Array.from(r)}var B7=r=>typeof r=="bigint"&&M7<=r;function G_(r,e,t){return B7(r)&&B7(e)&&B7(t)&&e<=r&&r<t}function Wa(r,e,t,n){if(!G_(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function e2(r){let e;for(e=0;r>M7;r>>=L7,e+=1);return e}var Ga=r=>(L7<<BigInt(r))-L7;function X_(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),i=h=>Uint8Array.of(h),o=n(r),s=n(r),a=0,c=()=>{o.fill(1),s.fill(0),a=0},l=(...h)=>t(s,o,...h),u=(h=n(0))=>{s=l(i(0),h),o=l(),h.length!==0&&(s=l(i(1),h),o=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,m=[];for(;h<e;){o=l();let g=o.slice();m.push(g),h+=o.length}return wn(...m)};return(h,m)=>{c(),u(h);let g;for(;!(g=m(f()));)u();return c(),g}}function Qo(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(i,o,s){let a=r[i];if(s&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([i,o])=>n(i,o,!1)),Object.entries(t).forEach(([i,o])=>n(i,o,!0))}var F7=()=>{throw new Error("not implemented")};function $f(r){let e=new WeakMap;return(t,...n)=>{let i=e.get(t);if(i!==void 0)return i;let o=r(t,...n);return e.set(t,o),o}}var xn=BigInt(0),_r=BigInt(1),Al=BigInt(2),Z_=BigInt(3),J_=BigInt(4),eC=BigInt(5),CK=BigInt(7),tC=BigInt(8),TK=BigInt(9),rC=BigInt(16);function Rt(r,e){let t=r%e;return t>=xn?t:e+t}function Dt(r,e,t){let n=r;for(;e-- >xn;)n*=n,n%=t;return n}function Y_(r,e){if(r===xn)throw new Error("invert: expected non-zero number");if(e<=xn)throw new Error("invert: expected positive modulus, got "+e);let t=Rt(r,e),n=e,i=xn,o=_r,s=_r,a=xn;for(;t!==xn;){let l=n/t,u=n%t,f=i-s*l,d=o-a*l;n=t,t=u,i=s,o=a,s=f,a=d}if(n!==_r)throw new Error("invert: does not exist");return Rt(i,e)}function $7(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function nC(r,e){let t=(r.ORDER+_r)/J_,n=r.pow(e,t);return $7(r,n,e),n}function IK(r,e){let t=(r.ORDER-eC)/tC,n=r.mul(e,Al),i=r.pow(n,t),o=r.mul(e,i),s=r.mul(r.mul(o,Al),i),a=r.mul(o,r.sub(s,r.ONE));return $7(r,a,e),a}function kK(r){let e=oi(r),t=iC(r),n=t(e,e.neg(e.ONE)),i=t(e,n),o=t(e,e.neg(n)),s=(r+CK)/rC;return(a,c)=>{let l=a.pow(c,s),u=a.mul(l,n),f=a.mul(l,i),d=a.mul(l,o),h=a.eql(a.sqr(u),c),m=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,m);let g=a.eql(a.sqr(u),c),w=a.cmov(l,u,g);return $7(a,w,c),w}}function iC(r){if(r<Z_)throw new Error("sqrt is not defined for small field");let e=r-_r,t=0;for(;e%Al===xn;)e/=Al,t++;let n=Al,i=oi(r);for(;Q_(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return nC;let o=i.pow(n,e),s=(e+_r)/Al;return function(c,l){if(c.is0(l))return l;if(Q_(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,o),d=c.pow(l,e),h=c.pow(l,s);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let m=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(m++,g=c.sqr(g),m===u)throw new Error("Cannot find square root");let w=_r<<BigInt(u-m-1),x=c.pow(f,w);u=m,f=c.sqr(x),d=c.mul(d,f),h=c.mul(h,x)}return h}}function PK(r){return r%J_===Z_?nC:r%tC===eC?IK:r%rC===TK?kK(r):iC(r)}var Ms=(r,e)=>(Rt(r,e)&_r)===_r,RK=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function H7(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=RK.reduce((n,i)=>(n[i]="function",n),e);return Qo(r,t),r}function DK(r,e,t){if(t<xn)throw new Error("invalid exponent, negatives unsupported");if(t===xn)return r.ONE;if(t===_r)return e;let n=r.ONE,i=e;for(;t>xn;)t&_r&&(n=r.mul(n,i)),i=r.sqr(i),t>>=_r;return n}function Cp(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((s,a,c)=>r.is0(a)?s:(n[c]=s,r.mul(s,a)),r.ONE),o=r.inv(i);return e.reduceRight((s,a,c)=>r.is0(a)?s:(n[c]=r.mul(s,n[c]),r.mul(s,a)),o),n}function Q_(r,e){let t=(r.ORDER-_r)/Al,n=r.pow(e,t),i=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function t2(r,e){e!==void 0&&uo(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function oi(r,e,t=!1,n={}){if(r<=xn)throw new Error("invalid field: expected ORDER > 0, got "+r);let i,o,s=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(i=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(s=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(o=n.sqrt);let{nBitLength:c,nByteLength:l}=t2(r,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Ga(c),ZERO:xn,ONE:_r,allowedLengths:a,create:d=>Rt(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return xn<=d&&d<r},is0:d=>d===xn,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&_r)===_r,neg:d=>Rt(-d,r),eql:(d,h)=>d===h,sqr:d=>Rt(d*d,r),add:(d,h)=>Rt(d+h,r),sub:(d,h)=>Rt(d-h,r),mul:(d,h)=>Rt(d*h,r),pow:(d,h)=>DK(f,d,h),div:(d,h)=>Rt(d*Y_(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Y_(d,r),sqrt:o||(d=>(u||(u=PK(r)),u(f,d))),toBytes:d=>t?_p(d,l):Jg(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let g=new Uint8Array(l);g.set(d,t?0:g.length-d.length),d=g}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let m=t?Ni(d):Ff(d);if(s&&(m=Rt(m,r)),!h&&!f.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:d=>Cp(f,d),cmov:(d,h,m)=>m?h:d});return Object.freeze(f)}function oC(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function V7(r){let e=oC(r);return e+Math.ceil(e/2)}function K7(r,e,t=!1){let n=r.length,i=oC(e),o=V7(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=t?Ni(r):Ff(r),a=Rt(s,e-_r)+_r;return t?_p(a,i):Jg(a,i)}var Hf=BigInt(0),El=BigInt(1);function Tp(r,e){let t=e.negate();return r?t:e}function Us(r,e){let t=Cp(r.Fp,e.map(n=>n.Z));return e.map((n,i)=>r.fromAffine(n.toAffine(t[i])))}function lC(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function z7(r,e){lC(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),i=2**r,o=Ga(r),s=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function sC(r,e,t){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=t,a=Number(r&i),c=r>>s;a>n&&(a-=o,c+=El);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}function OK(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function NK(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var q7=new WeakMap,uC=new WeakMap;function j7(r){return uC.get(r)||1}function aC(r){if(r!==Hf)throw new Error("invalid wNAF")}var Vf=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let i=e;for(;t>Hf;)t&El&&(n=n.add(i)),i=i.double(),t>>=El;return n}precomputeWindow(e,t){let{windows:n,windowSize:i}=z7(t,this.bits),o=[],s=e,a=s;for(let c=0;c<n;c++){a=s,o.push(a);for(let l=1;l<i;l++)a=a.add(s),o.push(a);s=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=z7(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=sC(n,a,s);n=c,u?o=o.add(Tp(d,t[h])):i=i.add(Tp(f,t[l]))}return aC(n),{p:i,f:o}}wNAFUnsafe(e,t,n,i=this.ZERO){let o=z7(e,this.bits);for(let s=0;s<o.windows&&n!==Hf;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=sC(n,s,o);if(n=a,!l){let f=t[c];i=i.add(u?f.negate():f)}}return aC(n),i}getPrecomputes(e,t,n){let i=q7.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(i=n(i)),q7.set(t,i))),i}cached(e,t,n){let i=j7(e);return this.wNAF(i,this.getPrecomputes(i,e,n),t)}unsafe(e,t,n,i){let o=j7(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,i)}createCache(e,t){lC(t,this.bits),uC.set(e,t),q7.delete(e)}hasCache(e){return j7(e)!==1}};function fC(r,e,t,n){let i=e,o=r.ZERO,s=r.ZERO;for(;t>Hf||n>Hf;)t&El&&(o=o.add(i)),n&El&&(s=s.add(i)),i=i.double(),t>>=El,n>>=El;return{p1:o,p2:s}}function Kf(r,e,t,n){OK(t,r),NK(n,e);let i=t.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=r.ZERO,a=e2(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ga(c),u=new Array(Number(l)+1).fill(s),f=Math.floor((e.BITS-1)/c)*c,d=s;for(let h=f;h>=0;h-=c){u.fill(s);for(let g=0;g<o;g++){let w=n[g],x=Number(w>>BigInt(h)&l);u[x]=u[x].add(t[g])}let m=s;for(let g=u.length-1,w=s;g>0;g--)w=w.add(u[g]),m=m.add(w);if(d=d.add(m),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function cC(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return H7(e),e}else return oi(r,{isLE:t})}function r2(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Hf))throw new Error(`CURVE.${c} must be positive bigint`)}let i=cC(e.p,t.Fp,n),o=cC(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var Xa=BigInt(0),Cr=BigInt(1),W7=BigInt(2),BK=BigInt(8);function LK(r,e,t,n){let i=r.sqr(t),o=r.sqr(n),s=r.add(r.mul(e.a,i),o),a=r.add(r.ONE,r.mul(e.d,r.mul(i,o)));return r.eql(s,a)}function MK(r,e={}){let t=r2("edwards",r,e,e.FpFnLE),{Fp:n,Fn:i}=t,o=t.CURVE,{h:s}=o;Qo(e,{},{uvRatio:"function"});let a=W7<<BigInt(i.BYTES*8)-Cr,c=w=>n.create(w),l=e.uvRatio||((w,x)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,x))}}catch{return{isValid:!1,value:Xa}}});if(!LK(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(w,x,v=!1){let A=v?Cr:Xa;return Wa("coordinate "+w,x,A,a),x}function f(w){if(!(w instanceof m))throw new Error("ExtendedPoint expected")}let d=$f((w,x)=>{let{X:v,Y:A,Z:S}=w,M=w.is0();x==null&&(x=M?BK:n.inv(S));let F=c(v*x),N=c(A*x),R=n.mul(S,x);if(M)return{x:Xa,y:Cr};if(R!==Cr)throw new Error("invZ was invalid");return{x:F,y:N}}),h=$f(w=>{let{a:x,d:v}=o;if(w.is0())throw new Error("bad point: ZERO");let{X:A,Y:S,Z:M,T:F}=w,N=c(A*A),R=c(S*S),_=c(M*M),$=c(_*_),V=c(N*x),H=c(_*c(V+R)),E=c($+c(v*c(N*R)));if(H!==E)throw new Error("bad point: equation left != right (1)");let T=c(A*S),C=c(M*F);if(T!==C)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(x,v,A,S){this.X=u("x",x),this.Y=u("y",v),this.Z=u("z",A,!0),this.T=u("t",S),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){if(x instanceof m)throw new Error("extended point not allowed");let{x:v,y:A}=x||{};return u("x",v),u("y",A),new m(v,A,Cr,c(v*A))}static fromBytes(x,v=!1){let A=n.BYTES,{a:S,d:M}=o;x=U7(ii(x,A,"point")),Ls(v,"zip215");let F=U7(x),N=x[A-1];F[A-1]=N&-129;let R=Ni(F),_=v?a:n.ORDER;Wa("point.y",R,Xa,_);let $=c(R*R),V=c($-Cr),H=c(M*$-S),{isValid:E,value:T}=l(V,H);if(!E)throw new Error("bad point: invalid y coordinate");let C=(T&Cr)===Cr,O=(N&128)!==0;if(!v&&T===Xa&&O)throw new Error("bad point: x=0 and x_0=1");return O!==C&&(T=c(-T)),m.fromAffine({x:T,y:R})}static fromHex(x,v=!1){return m.fromBytes(at("point",x),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,v=!0){return g.createCache(this,x),v||this.multiply(W7),this}assertValidity(){h(this)}equals(x){f(x);let{X:v,Y:A,Z:S}=this,{X:M,Y:F,Z:N}=x,R=c(v*N),_=c(M*S),$=c(A*N),V=c(F*S);return R===_&&$===V}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:x}=o,{X:v,Y:A,Z:S}=this,M=c(v*v),F=c(A*A),N=c(W7*c(S*S)),R=c(x*M),_=v+A,$=c(c(_*_)-M-F),V=R+F,H=V-N,E=R-F,T=c($*H),C=c(V*E),O=c($*E),j=c(H*V);return new m(T,C,j,O)}add(x){f(x);let{a:v,d:A}=o,{X:S,Y:M,Z:F,T:N}=this,{X:R,Y:_,Z:$,T:V}=x,H=c(S*R),E=c(M*_),T=c(N*A*V),C=c(F*$),O=c((S+M)*(R+_)-H-E),j=C-T,Q=C+T,U=c(E-v*H),Z=c(O*j),te=c(Q*U),q=c(O*U),Te=c(j*Q);return new m(Z,te,Te,q)}subtract(x){return this.add(x.negate())}multiply(x){if(!i.isValidNot0(x))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:A}=g.cached(this,x,S=>Us(m,S));return Us(m,[v,A])[0]}multiplyUnsafe(x,v=m.ZERO){if(!i.isValid(x))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return x===Xa?m.ZERO:this.is0()||x===Cr?this:g.unsafe(this,x,A=>Us(m,A),v)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return g.unsafe(this,o.n).is0()}toAffine(x){return d(this,x)}clearCofactor(){return s===Cr?this:this.multiplyUnsafe(s)}toBytes(){let{x,y:v}=this.toAffine(),A=n.toBytes(v);return A[A.length-1]|=x&Cr?128:0,A}toHex(){return Oi(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(x){return Us(m,x)}static msm(x,v){return Kf(m,i,x,v)}_setWindowSize(x){this.precompute(x)}toRawBytes(){return this.toBytes()}}m.BASE=new m(o.Gx,o.Gy,Cr,c(o.Gx*o.Gy)),m.ZERO=new m(Xa,Cr,Cr,Xa),m.Fp=n,m.Fn=i;let g=new Vf(m,i.BITS);return m.BASE.precompute(8),m}var n2=class{constructor(e){this.ep=e}static fromBytes(e){F7()}static fromHex(e){F7()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Oi(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function UK(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Qo(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:i,Fp:o,Fn:s}=r,a=t.randomBytes||Xo,c=t.adjustScalarBytes||(_=>_),l=t.domain||((_,$,V)=>{if(Ls(V,"phflag"),$.length||V)throw new Error("Contexts/pre-hash are not supported");return _});function u(_){return s.create(Ni(_))}function f(_){let $=A.secretKey;_=at("private key",_,$);let V=at("hashed private key",e(_),2*$),H=c(V.slice(0,$)),E=V.slice($,2*$),T=u(H);return{head:H,prefix:E,scalar:T}}function d(_){let{head:$,prefix:V,scalar:H}=f(_),E=i.multiply(H),T=E.toBytes();return{head:$,prefix:V,scalar:H,point:E,pointBytes:T}}function h(_){return d(_).pointBytes}function m(_=Uint8Array.of(),...$){let V=wn(...$);return u(e(l(V,at("context",_),!!n)))}function g(_,$,V={}){_=at("message",_),n&&(_=n(_));let{prefix:H,scalar:E,pointBytes:T}=d($),C=m(V.context,H,_),O=i.multiply(C).toBytes(),j=m(V.context,O,T,_),Q=s.create(C+j*E);if(!s.isValid(Q))throw new Error("sign failed: invalid s");let U=wn(O,s.toBytes(Q));return ii(U,A.signature,"result")}let w={zip215:!0};function x(_,$,V,H=w){let{context:E,zip215:T}=H,C=A.signature;_=at("signature",_,C),$=at("message",$),V=at("publicKey",V,A.publicKey),T!==void 0&&Ls(T,"zip215"),n&&($=n($));let O=C/2,j=_.subarray(0,O),Q=Ni(_.subarray(O,C)),U,Z,te;try{U=r.fromBytes(V,T),Z=r.fromBytes(j,T),te=i.multiplyUnsafe(Q)}catch{return!1}if(!T&&U.isSmallOrder())return!1;let q=m(E,Z.toBytes(),U.toBytes(),$);return Z.add(U.multiplyUnsafe(q)).subtract(te).clearCofactor().is0()}let v=o.BYTES,A={secretKey:v,publicKey:v,signature:2*v,seed:v};function S(_=a(A.seed)){return ii(_,A.seed,"seed")}function M(_){let $=R.randomSecretKey(_);return{secretKey:$,publicKey:h($)}}function F(_){return Os(_)&&_.length===s.BYTES}function N(_,$){try{return!!r.fromBytes(_,$)}catch{return!1}}let R={getExtendedPublicKey:d,randomSecretKey:S,isValidSecretKey:F,isValidPublicKey:N,toMontgomery(_){let{y:$}=r.fromBytes(_),V=A.publicKey,H=V===32;if(!H&&V!==57)throw new Error("only defined for 25519 and 448");let E=H?o.div(Cr+$,Cr-$):o.div($-Cr,$+Cr);return o.toBytes(E)},toMontgomerySecret(_){let $=A.secretKey;ii(_,$);let V=e(_.subarray(0,$));return c(V).subarray(0,$)},randomPrivateKey:S,precompute(_=8,$=r.BASE){return $.precompute(_,!1)}};return Object.freeze({keygen:M,getPublicKey:h,sign:g,verify:x,utils:R,Point:r,lengths:A})}function FK(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=oi(e.n,r.nBitLength,!0),i={Fp:t,Fn:n,uvRatio:r.uvRatio},o={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:i,hash:r.hash,eddsaOpts:o}}function $K(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function dC(r){let{CURVE:e,curveOpts:t,hash:n,eddsaOpts:i}=FK(r),o=MK(e,t),s=UK(o,n,i);return $K(r,s)}var Ip=BigInt(0),zf=BigInt(1),i2=BigInt(2);function HK(r){return Qo(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function hC(r){let e=HK(r),{P:t,type:n,adjustScalarBytes:i,powPminus2:o,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s||Xo,l=a?255:448,u=a?32:56,f=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?i2**BigInt(254):i2**BigInt(447),m=a?BigInt(8)*i2**BigInt(251)-zf:BigInt(4)*i2**BigInt(445)-zf,g=h+m+zf,w=E=>Rt(E,t),x=v(f);function v(E){return _p(w(E),u)}function A(E){let T=at("u coordinate",E,u);return a&&(T[31]&=127),w(Ni(T))}function S(E){return Ni(i(at("scalar",E,u)))}function M(E,T){let C=R(A(T),S(E));if(C===Ip)throw new Error("invalid private or public key received");return v(C)}function F(E){return M(E,x)}function N(E,T,C){let O=w(E*(T-C));return T=w(T-O),C=w(C+O),{x_2:T,x_3:C}}function R(E,T){Wa("u",E,Ip,t),Wa("scalar",T,h,g);let C=T,O=E,j=zf,Q=Ip,U=E,Z=zf,te=Ip;for(let Te=BigInt(l-1);Te>=Ip;Te--){let Ne=C>>Te&zf;te^=Ne,{x_2:j,x_3:U}=N(te,j,U),{x_2:Q,x_3:Z}=N(te,Q,Z),te=Ne;let se=j+Q,Le=w(se*se),Ke=j-Q,ft=w(Ke*Ke),He=Le-ft,st=U+Z,Ci=U-Z,hn=w(Ci*se),io=w(st*Ke),ug=hn+io,xf=hn-io;U=w(ug*ug),Z=w(O*w(xf*xf)),j=w(Le*ft),Q=w(He*(Le+w(d*He)))}({x_2:j,x_3:U}=N(te,j,U)),{x_2:Q,x_3:Z}=N(te,Q,Z);let q=o(Q);return w(j*q)}let _={secretKey:u,publicKey:u,seed:u},$=(E=c(u))=>(Nr(E,_.seed),E);function V(E){let T=$(E);return{secretKey:T,publicKey:F(T)}}return{keygen:V,getSharedSecret:(E,T)=>M(E,T),getPublicKey:E=>F(E),scalarMult:M,scalarMultBase:F,utils:{randomSecretKey:$,randomPrivateKey:$},GuBytes:x.slice(),lengths:_}}var VK=BigInt(0),$s=BigInt(1),pC=BigInt(2),KK=BigInt(3),zK=BigInt(5),qK=BigInt(8),qf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),kp={p:qf,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:qK,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yC(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),i=BigInt(80),o=qf,a=r*r%o*r%o,c=Dt(a,pC,o)*a%o,l=Dt(c,$s,o)*r%o,u=Dt(l,zK,o)*l%o,f=Dt(u,e,o)*u%o,d=Dt(f,t,o)*f%o,h=Dt(d,n,o)*d%o,m=Dt(h,i,o)*h%o,g=Dt(m,i,o)*h%o,w=Dt(g,e,o)*u%o;return{pow_p_5_8:Dt(w,pC,o)*r%o,b2:a}}function wC(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var G7=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Q7(r,e){let t=qf,n=Rt(e*e*e,t),i=Rt(n*n*e,t),o=yC(r*i).pow_p_5_8,s=Rt(r*n*o,t),a=Rt(e*s*s,t),c=s,l=Rt(s*G7,t),u=a===r,f=a===Rt(-r,t),d=a===Rt(-r*G7,t);return u&&(s=c),(f||d)&&(s=l),Ms(s,t)&&(s=Rt(-s,t)),{isValid:u||f,value:s}}var Fs=oi(kp.p,{isLE:!0}),jK=oi(kp.n,{isLE:!0}),WK={...kp,Fp:Fs,hash:Zg,adjustScalarBytes:wC,uvRatio:Q7},Bi=dC(WK);var Pp=(()=>{let r=Fs.ORDER;return hC({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=yC(e);return Rt(Dt(t,KK,r)*n,r)},adjustScalarBytes:wC})})();var X7=G7,GK=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),XK=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),YK=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),QK=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),mC=r=>Q7($s,r),ZK=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Y7=r=>Bi.Point.Fp.create(Ni(r)&ZK);function gC(r){let{d:e}=kp,t=qf,n=x=>Fs.create(x),i=n(X7*r*r),o=n((i+$s)*YK),s=BigInt(-1),a=n((s-e*i)*n(i+e)),{isValid:c,value:l}=Q7(o,a),u=n(l*r);Ms(u,t)||(u=n(-u)),c||(l=u),c||(s=i);let f=n(s*(i-$s)*QK-a),d=l*l,h=n((l+l)*a),m=n(f*GK),g=n($s-d),w=n($s+d);return new Bi.Point(n(h*w),n(g*m),n(m*w),n(h*g))}function JK(r){Nr(r,64);let e=Y7(r.subarray(0,32)),t=gC(e),n=Y7(r.subarray(32,64)),i=gC(n);return new Hs(t.add(i))}var Hs=class r extends n2{constructor(e){super(e)}static fromAffine(e){return new r(Bi.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return JK(at("ristrettoHash",e,64))}static fromBytes(e){Nr(e,32);let{a:t,d:n}=kp,i=qf,o=S=>Fs.create(S),s=Y7(e);if(!W_(Fs.toBytes(s),e)||Ms(s,i))throw new Error("invalid ristretto255 encoding 1");let a=o(s*s),c=o($s+t*a),l=o($s-t*a),u=o(c*c),f=o(l*l),d=o(t*n*u-f),{isValid:h,value:m}=mC(o(d*f)),g=o(m*l),w=o(m*g*d),x=o((s+s)*g);Ms(x,i)&&(x=o(-x));let v=o(c*w),A=o(x*v);if(!h||Ms(A,i)||v===VK)throw new Error("invalid ristretto255 encoding 2");return new r(new Bi.Point(x,v,$s,A))}static fromHex(e){return r.fromBytes(at("ristrettoHex",e,32))}static msm(e,t){return Kf(r,Bi.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:i}=this.ep,o=qf,s=w=>Fs.create(w),a=s(s(n+t)*s(n-t)),c=s(e*t),l=s(c*c),{value:u}=mC(s(a*l)),f=s(u*a),d=s(u*c),h=s(f*d*i),m;if(Ms(i*h,o)){let w=s(t*X7),x=s(e*X7);e=w,t=x,m=s(f*XK)}else m=d;Ms(e*h,o)&&(t=s(-t));let g=s((n-t)*m);return Ms(g,o)&&(g=s(-g)),Fs.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:i,Y:o}=e.ep,s=l=>Fs.create(l),a=s(t*o)===s(n*i),c=s(n*o)===s(t*i);return a||c}is0(){return this.equals(r.ZERO)}};Hs.BASE=new Hs(Bi.Point.BASE);Hs.ZERO=new Hs(Bi.Point.ZERO);Hs.Fp=Fs;Hs.Fn=jK;var Rp=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Dp=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},o2=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var xC={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new o2("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var fr=xC;var Sl=32,si=64,Z7=32;var jf,bC=(async()=>{try{return await fr.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function vC(){let r=Bi.utils.randomPrivateKey(),e=Bi.getPublicKey(r);return{privateKey:iz(r,e),publicKey:e}}async function ez(r,e){let t;r.length===si?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:z(r.subarray(32),"base64url"),d:z(t,"base64url"),ext:!0,key_ops:["sign"]},i=await fr.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),o=await fr.get().subtle.sign({name:"Ed25519"},i,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(o,0,o.byteLength)}function tz(r,e){let t=r.subarray(0,Z7);return Bi.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function AC(r,e){return jf==null&&(jf=await bC),jf?ez(r,e):tz(r,e)}async function rz(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await fr.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await fr.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function nz(r,e,t){return Bi.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function EC(r,e,t){return jf==null&&(jf=await bC),jf?rz(r,e,t):nz(r,e,t)}function iz(r,e){let t=new Uint8Array(si);for(let n=0;n<Z7;n++)t[n]=r[n],t[Z7+n]=e[n];return t}function Wf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Op=class{type="Ed25519";raw;constructor(e){this.raw=Xf(e,Sl)}toMultihash(){return lr.digest(ur(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let i=EC(this.raw,t,e);return Wf(i)?i.then(o=>(n?.signal?.throwIfAborted(),o)):i}},Gf=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Xf(e,si),this.publicKey=new Op(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=AC(this.raw,e);return Wf(n)?n.then(i=>(t?.signal?.throwIfAborted(),i)):(t?.signal?.throwIfAborted(),n)}};function J7(r){if(r.length>si){r=Xf(r,si+Sl);let n=r.subarray(0,si),i=r.subarray(si,r.length);return new Gf(n,i)}r=Xf(r,si);let e=r.subarray(0,si),t=r.subarray(Sl);return new Gf(e,t)}function ex(r){return r=Xf(r,Sl),new Op(r)}async function _C(){let{privateKey:r,publicKey:e}=vC();return new Gf(r,e)}function Xf(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new K(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var _t;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(_t||(_t={}));var tx;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(tx||(tx={}));(function(r){r.codec=()=>St(tx)})(_t||(_t={}));var Zo;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),_t.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=_t.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Zo||(Zo={}));var Np;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),_t.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=_t.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Np||(Np={}));function bn(r){if(isNaN(r)||r<=0)throw new K("random bytes length must be a Number bigger than 0");return Xo(r)}var Lp={};$t(Lp,{MAX_RSA_KEY_SIZE:()=>rx,generateRSAKeyPair:()=>fx,jwkToJWKKeyPair:()=>kC,jwkToPkcs1:()=>cz,jwkToPkix:()=>sx,jwkToRSAPrivateKey:()=>ux,pkcs1MessageToJwk:()=>ix,pkcs1MessageToRSAPrivateKey:()=>s2,pkcs1ToJwk:()=>az,pkcs1ToRSAPrivateKey:()=>ax,pkixMessageToJwk:()=>ox,pkixMessageToRSAPublicKey:()=>lx,pkixToJwk:()=>lz,pkixToRSAPublicKey:()=>cx});var Jo=Qg;var Yf=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Lp.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return G.createV1(114,this._multihash)}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,t,n){return IC(this.jwk,t,e,n)}},Bp=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Lp.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,t){return TC(this.jwk,e,t)}};var rx=8192,nx=18,oz=1062,sz=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function az(r){let e=Di(r);return ix(e)}function ix(r){return{n:z(r[1],"base64url"),e:z(r[2],"base64url"),d:z(r[3],"base64url"),p:z(r[4],"base64url"),q:z(r[5],"base64url"),dp:z(r[6],"base64url"),dq:z(r[7],"base64url"),qi:z(r[8],"base64url"),kty:"RSA"}}function cz(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 K("JWK was missing components");return lo([yn(Uint8Array.from([0])),yn(D(r.n,"base64url")),yn(D(r.e,"base64url")),yn(D(r.d,"base64url")),yn(D(r.p,"base64url")),yn(D(r.q,"base64url")),yn(D(r.dp,"base64url")),yn(D(r.dq,"base64url")),yn(D(r.qi,"base64url"))]).subarray()}function lz(r){let e=Di(r,{offset:0});return ox(e)}function ox(r){let e=Di(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function sx(r){if(r.n==null||r.e==null)throw new K("JWK was missing components");return lo([sz,bp(lo([yn(D(r.n,"base64url")),yn(D(r.e,"base64url"))]))]).subarray()}function ax(r){let e=Di(r);return s2(e)}function s2(r){let e=ix(r);return ux(e)}function cx(r,e){if(r.byteLength>=oz)throw new _s("Key size is too large");let t=Di(r,{offset:0});return lx(t,r,e)}function lx(r,e,t){let n=ox(r);if(t==null){let i=Jo(Zo.encode({Type:_t.RSA,Data:e}));t=gn(nx,i)}return new Yf(n,t)}function ux(r){if(RC(r)>rx)throw new K("Key size is too large");let e=kC(r),t=Jo(Zo.encode({Type:_t.RSA,Data:sx(e.publicKey)})),n=gn(nx,t);return new Bp(e.privateKey,new Yf(e.publicKey,n))}async function fx(r){if(r>rx)throw new K("Key size is too large");let e=await PC(r),t=Jo(Zo.encode({Type:_t.RSA,Data:sx(e.publicKey)})),n=gn(nx,t);return new Bp(e.privateKey,new Yf(e.publicKey,n))}function kC(r){if(r==null)throw new K("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function PC(r,e){let t=await fr.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await uz(t,e);return{privateKey:n[0],publicKey:n[1]}}async function TC(r,e,t){let n=await fr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let i=await fr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}async function IC(r,e,t,n){let i=await fr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await fr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),o}async function uz(r,e){if(r.privateKey==null||r.publicKey==null)throw new K("Private and public key are required");let t=await Promise.all([fr.get().subtle.exportKey("jwk",r.privateKey),fr.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function RC(r){if(r.kty!=="RSA")throw new K("invalid key type");if(r.n==null)throw new K("invalid key modulus");return D(r.n,"base64url").length*8}var a2=class extends Mf{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ns(e);let n=Ka(t);if(this.iHash=e.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 i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),rn(o)}update(e){return Uf(this),this.iHash.update(e),this}digestInto(e){Uf(this),Nr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ya=(r,e,t)=>new a2(r,e).update(t).digest();Ya.create=(r,e)=>new a2(r,e);var DC=(r,e)=>(r+(r>=0?e:-e)/OC)/e;function fz(r,e,t){let[[n,i],[o,s]]=e,a=DC(s*r,t),c=DC(-i*r,t),l=r-a*n-c*o,u=-a*i-c*s,f=l<Ks,d=u<Ks;f&&(l=-l),d&&(u=-u);let h=Ga(Math.ceil(e2(t)/2))+Zf;if(l<Ks||l>=h||u<Ks||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function hx(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function dx(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ls(t.lowS,"lowS"),Ls(t.prehash,"prehash"),t.format!==void 0&&hx(t.format),t}var px=class extends Error{constructor(e=""){super(e)}},Vs={Err:px,_tlv:{encode:(r,e)=>{let{Err:t}=Vs;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,i=Sp(n);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Sp(i.length/2|128):"";return Sp(r)+o+i+e},decode(r,e){let{Err:t}=Vs,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let c=i&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Vs;if(r<Ks)throw new e("integer: negative integers are not allowed");let t=Sp(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Vs;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ff(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Vs,i=at("signature",r),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Vs,n=e.encode(2,t.encode(r.r)),i=e.encode(2,t.encode(r.s)),o=n+i;return e.encode(48,o)}},Ks=BigInt(0),Zf=BigInt(1),OC=BigInt(2),c2=BigInt(3),dz=BigInt(4);function Qf(r,e){let{BYTES:t}=r,n;if(typeof e=="bigint")n=e;else{let i=at("private key",e);try{n=r.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function hz(r,e={}){let t=r2("weierstrass",r,e),{Fp:n,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;Qo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=BC(n,i);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(H,E,T){let{x:C,y:O}=E.toAffine(),j=n.toBytes(C);if(Ls(T,"isCompressed"),T){u();let Q=!n.isOdd(O);return wn(NC(Q),j)}else return wn(Uint8Array.of(4),j,n.toBytes(O))}function d(H){ii(H,void 0,"Point");let{publicKey:E,publicKeyUncompressed:T}=l,C=H.length,O=H[0],j=H.subarray(1);if(C===E&&(O===2||O===3)){let Q=n.fromBytes(j);if(!n.isValid(Q))throw new Error("bad point: is not on curve, wrong x");let U=g(Q),Z;try{Z=n.sqrt(U)}catch(Te){let Ne=Te instanceof Error?": "+Te.message:"";throw new Error("bad point: is not on curve, sqrt error"+Ne)}u();let te=n.isOdd(Z);return(O&1)===1!==te&&(Z=n.neg(Z)),{x:Q,y:Z}}else if(C===T&&O===4){let Q=n.BYTES,U=n.fromBytes(j.subarray(0,Q)),Z=n.fromBytes(j.subarray(Q,Q*2));if(!w(U,Z))throw new Error("bad point: is not on curve");return{x:U,y:Z}}else throw new Error(`bad point: got length ${C}, expected compressed=${E} or uncompressed=${T}`)}let h=e.toBytes||f,m=e.fromBytes||d;function g(H){let E=n.sqr(H),T=n.mul(E,H);return n.add(n.add(T,n.mul(H,o.a)),o.b)}function w(H,E){let T=n.sqr(E),C=g(H);return n.eql(T,C)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=n.mul(n.pow(o.a,c2),dz),v=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(x,v)))throw new Error("bad curve params: a or b");function A(H,E,T=!1){if(!n.isValid(E)||T&&n.is0(E))throw new Error(`bad point coordinate ${H}`);return E}function S(H){if(!(H instanceof _))throw new Error("ProjectivePoint expected")}function M(H){if(!c||!c.basises)throw new Error("no endo");return fz(H,c.basises,i.ORDER)}let F=$f((H,E)=>{let{X:T,Y:C,Z:O}=H;if(n.eql(O,n.ONE))return{x:T,y:C};let j=H.is0();E==null&&(E=j?n.ONE:n.inv(O));let Q=n.mul(T,E),U=n.mul(C,E),Z=n.mul(O,E);if(j)return{x:n.ZERO,y:n.ZERO};if(!n.eql(Z,n.ONE))throw new Error("invZ was invalid");return{x:Q,y:U}}),N=$f(H=>{if(H.is0()){if(e.allowInfinityPoint&&!n.is0(H.Y))return;throw new Error("bad point: ZERO")}let{x:E,y:T}=H.toAffine();if(!n.isValid(E)||!n.isValid(T))throw new Error("bad point: x or y not field elements");if(!w(E,T))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function R(H,E,T,C,O){return T=new _(n.mul(T.X,H),T.Y,T.Z),E=Tp(C,E),T=Tp(O,T),E.add(T)}class _{constructor(E,T,C){this.X=A("x",E),this.Y=A("y",T,!0),this.Z=A("z",C),Object.freeze(this)}static CURVE(){return o}static fromAffine(E){let{x:T,y:C}=E||{};if(!E||!n.isValid(T)||!n.isValid(C))throw new Error("invalid affine point");if(E instanceof _)throw new Error("projective point not allowed");return n.is0(T)&&n.is0(C)?_.ZERO:new _(T,C,n.ONE)}static fromBytes(E){let T=_.fromAffine(m(ii(E,void 0,"point")));return T.assertValidity(),T}static fromHex(E){return _.fromBytes(at("pointHex",E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=8,T=!0){return V.createCache(this,E),T||this.multiply(c2),this}assertValidity(){N(this)}hasEvenY(){let{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){S(E);let{X:T,Y:C,Z:O}=this,{X:j,Y:Q,Z:U}=E,Z=n.eql(n.mul(T,U),n.mul(j,O)),te=n.eql(n.mul(C,U),n.mul(Q,O));return Z&&te}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{a:E,b:T}=o,C=n.mul(T,c2),{X:O,Y:j,Z:Q}=this,U=n.ZERO,Z=n.ZERO,te=n.ZERO,q=n.mul(O,O),Te=n.mul(j,j),Ne=n.mul(Q,Q),se=n.mul(O,j);return se=n.add(se,se),te=n.mul(O,Q),te=n.add(te,te),U=n.mul(E,te),Z=n.mul(C,Ne),Z=n.add(U,Z),U=n.sub(Te,Z),Z=n.add(Te,Z),Z=n.mul(U,Z),U=n.mul(se,U),te=n.mul(C,te),Ne=n.mul(E,Ne),se=n.sub(q,Ne),se=n.mul(E,se),se=n.add(se,te),te=n.add(q,q),q=n.add(te,q),q=n.add(q,Ne),q=n.mul(q,se),Z=n.add(Z,q),Ne=n.mul(j,Q),Ne=n.add(Ne,Ne),q=n.mul(Ne,se),U=n.sub(U,q),te=n.mul(Ne,Te),te=n.add(te,te),te=n.add(te,te),new _(U,Z,te)}add(E){S(E);let{X:T,Y:C,Z:O}=this,{X:j,Y:Q,Z:U}=E,Z=n.ZERO,te=n.ZERO,q=n.ZERO,Te=o.a,Ne=n.mul(o.b,c2),se=n.mul(T,j),Le=n.mul(C,Q),Ke=n.mul(O,U),ft=n.add(T,C),He=n.add(j,Q);ft=n.mul(ft,He),He=n.add(se,Le),ft=n.sub(ft,He),He=n.add(T,O);let st=n.add(j,U);return He=n.mul(He,st),st=n.add(se,Ke),He=n.sub(He,st),st=n.add(C,O),Z=n.add(Q,U),st=n.mul(st,Z),Z=n.add(Le,Ke),st=n.sub(st,Z),q=n.mul(Te,He),Z=n.mul(Ne,Ke),q=n.add(Z,q),Z=n.sub(Le,q),q=n.add(Le,q),te=n.mul(Z,q),Le=n.add(se,se),Le=n.add(Le,se),Ke=n.mul(Te,Ke),He=n.mul(Ne,He),Le=n.add(Le,Ke),Ke=n.sub(se,Ke),Ke=n.mul(Te,Ke),He=n.add(He,Ke),se=n.mul(Le,He),te=n.add(te,se),se=n.mul(st,He),Z=n.mul(ft,Z),Z=n.sub(Z,se),se=n.mul(ft,Le),q=n.mul(st,q),q=n.add(q,se),new _(Z,te,q)}subtract(E){return this.add(E.negate())}is0(){return this.equals(_.ZERO)}multiply(E){let{endo:T}=e;if(!i.isValidNot0(E))throw new Error("invalid scalar: out of range");let C,O,j=Q=>V.cached(this,Q,U=>Us(_,U));if(T){let{k1neg:Q,k1:U,k2neg:Z,k2:te}=M(E),{p:q,f:Te}=j(U),{p:Ne,f:se}=j(te);O=Te.add(se),C=R(T.beta,q,Ne,Q,Z)}else{let{p:Q,f:U}=j(E);C=Q,O=U}return Us(_,[C,O])[0]}multiplyUnsafe(E){let{endo:T}=e,C=this;if(!i.isValid(E))throw new Error("invalid scalar: out of range");if(E===Ks||C.is0())return _.ZERO;if(E===Zf)return C;if(V.hasCache(this))return this.multiply(E);if(T){let{k1neg:O,k1:j,k2neg:Q,k2:U}=M(E),{p1:Z,p2:te}=fC(_,C,j,U);return R(T.beta,Z,te,O,Q)}else return V.unsafe(C,E)}multiplyAndAddUnsafe(E,T,C){let O=this.multiplyUnsafe(T).add(E.multiplyUnsafe(C));return O.is0()?void 0:O}toAffine(E){return F(this,E)}isTorsionFree(){let{isTorsionFree:E}=e;return s===Zf?!0:E?E(_,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:E}=e;return s===Zf?this:E?E(_,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(E=!0){return Ls(E,"isCompressed"),this.assertValidity(),h(_,this,E)}toHex(E=!0){return Oi(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(E=!0){return this.toBytes(E)}_setWindowSize(E){this.precompute(E)}static normalizeZ(E){return Us(_,E)}static msm(E,T){return Kf(_,i,E,T)}static fromPrivateKey(E){return _.BASE.multiply(Qf(i,E))}}_.BASE=new _(o.Gx,o.Gy,n.ONE),_.ZERO=new _(n.ZERO,n.ONE,n.ZERO),_.Fp=n,_.Fn=i;let $=i.BITS,V=new Vf(_,e.endo?Math.ceil($/2):$);return _.BASE.precompute(8),_}function NC(r){return Uint8Array.of(r?2:3)}function BC(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function pz(r,e={}){let{Fn:t}=r,n=e.randomBytes||Xo,i=Object.assign(BC(r.Fp,t),{seed:V7(t.ORDER)});function o(h){try{return!!Qf(t,h)}catch{return!1}}function s(h,m){let{publicKey:g,publicKeyUncompressed:w}=i;try{let x=h.length;return m===!0&&x!==g||m===!1&&x!==w?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(i.seed)){return K7(ii(h,i.seed,"seed"),t.ORDER)}function c(h,m=!0){return r.BASE.multiply(Qf(t,h)).toBytes(m)}function l(h){let m=a(h);return{secretKey:m,publicKey:c(m)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:m,publicKey:g,publicKeyUncompressed:w}=i;if(t.allowedLengths||m===g)return;let x=at("key",h).length;return x===g||x===w}function f(h,m,g=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");let w=Qf(t,h);return r.fromHex(m).multiply(w).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:r,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:h=>Qf(t,h),precompute(h=8,m=r.BASE){return m.precompute(h,!1)}},lengths:i})}function mz(r,e,t={}){Ns(e),Qo(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||Xo,i=t.hmac||((T,...C)=>Ya(e,T,wn(...C))),{Fp:o,Fn:s}=r,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=pz(r,t),m={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(T){let C=a>>Zf;return T>C}function x(T,C){if(!s.isValidNot0(C))throw new Error(`invalid signature ${T}: out of range 1..Point.Fn.ORDER`);return C}function v(T,C){hx(C);let O=h.signature,j=C==="compact"?O:C==="recovered"?O+1:void 0;return ii(T,j,`${C} signature`)}class A{constructor(C,O,j){this.r=x("r",C),this.s=x("s",O),j!=null&&(this.recovery=j),Object.freeze(this)}static fromBytes(C,O=g){v(C,O);let j;if(O==="der"){let{r:te,s:q}=Vs.toSig(ii(C));return new A(te,q)}O==="recovered"&&(j=C[0],O="compact",C=C.subarray(1));let Q=s.BYTES,U=C.subarray(0,Q),Z=C.subarray(Q,Q*2);return new A(s.fromBytes(U),s.fromBytes(Z),j)}static fromHex(C,O){return this.fromBytes(wl(C),O)}addRecoveryBit(C){return new A(this.r,this.s,C)}recoverPublicKey(C){let O=o.ORDER,{r:j,s:Q,recovery:U}=this;if(U==null||![0,1,2,3].includes(U))throw new Error("recovery id invalid");if(a*OC<O&&U>1)throw new Error("recovery id is ambiguous for h>1 curve");let te=U===2||U===3?j+a:j;if(!o.isValid(te))throw new Error("recovery id 2 or 3 invalid");let q=o.toBytes(te),Te=r.fromBytes(wn(NC((U&1)===0),q)),Ne=s.inv(te),se=M(at("msgHash",C)),Le=s.create(-se*Ne),Ke=s.create(Q*Ne),ft=r.BASE.multiplyUnsafe(Le).add(Te.multiplyUnsafe(Ke));if(ft.is0())throw new Error("point at infinify");return ft.assertValidity(),ft}hasHighS(){return w(this.s)}toBytes(C=g){if(hx(C),C==="der")return wl(Vs.hexFromSig(this));let O=s.toBytes(this.r),j=s.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return wn(Uint8Array.of(this.recovery),O,j)}return wn(O,j)}toHex(C){return Oi(this.toBytes(C))}assertValidity(){}static fromCompact(C){return A.fromBytes(at("sig",C),"compact")}static fromDER(C){return A.fromBytes(at("sig",C),"der")}normalizeS(){return this.hasHighS()?new A(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Oi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Oi(this.toBytes("compact"))}}let S=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let O=Ff(C),j=C.length*8-c;return j>0?O>>BigInt(j):O},M=t.bits2int_modN||function(C){return s.create(S(C))},F=Ga(c);function N(T){return Wa("num < 2^"+c,T,Ks,F),s.toBytes(T)}function R(T,C){return ii(T,void 0,"message"),C?ii(e(T),void 0,"prehashed message"):T}function _(T,C,O){if(["recovered","canonical"].some(Le=>Le in O))throw new Error("sign() legacy options not supported");let{lowS:j,prehash:Q,extraEntropy:U}=dx(O,m);T=R(T,Q);let Z=M(T),te=Qf(s,C),q=[N(te),N(Z)];if(U!=null&&U!==!1){let Le=U===!0?n(h.secretKey):U;q.push(at("extraEntropy",Le))}let Te=wn(...q),Ne=Z;function se(Le){let Ke=S(Le);if(!s.isValidNot0(Ke))return;let ft=s.inv(Ke),He=r.BASE.multiply(Ke).toAffine(),st=s.create(He.x);if(st===Ks)return;let Ci=s.create(ft*s.create(Ne+st*te));if(Ci===Ks)return;let hn=(He.x===st?0:2)|Number(He.y&Zf),io=Ci;return j&&w(Ci)&&(io=s.neg(Ci),hn^=1),new A(st,io,hn)}return{seed:Te,k2sig:se}}function $(T,C,O={}){T=at("message",T);let{seed:j,k2sig:Q}=_(T,C,O);return X_(e.outputLen,s.BYTES,i)(j,Q)}function V(T){let C,O=typeof T=="string"||Os(T),j=!O&&T!==null&&typeof T=="object"&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!O&&!j)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(j)C=new A(T.r,T.s);else if(O){try{C=A.fromBytes(at("sig",T),"der")}catch(Q){if(!(Q instanceof Vs.Err))throw Q}if(!C)try{C=A.fromBytes(at("sig",T),"compact")}catch{return!1}}return C||!1}function H(T,C,O,j={}){let{lowS:Q,prehash:U,format:Z}=dx(j,m);if(O=at("publicKey",O),C=R(at("message",C),U),"strict"in j)throw new Error("options.strict was renamed to lowS");let te=Z===void 0?V(T):A.fromBytes(at("sig",T),Z);if(te===!1)return!1;try{let q=r.fromBytes(O);if(Q&&te.hasHighS())return!1;let{r:Te,s:Ne}=te,se=M(C),Le=s.inv(Ne),Ke=s.create(se*Le),ft=s.create(Te*Le),He=r.BASE.multiplyUnsafe(Ke).add(q.multiplyUnsafe(ft));return He.is0()?!1:s.create(He.x)===Te}catch{return!1}}function E(T,C,O={}){let{prehash:j}=dx(O,m);return C=R(C,j),A.fromBytes(T,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:$,verify:H,recoverPublicKey:E,Signature:A,hash:e})}function gz(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=oi(e.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),o={Fp:t,Fn:i,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:o}}function yz(r){let{CURVE:e,curveOpts:t}=gz(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:n}}function wz(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,t2(t.Fn.ORDER,t.Fn.BITS))})}function LC(r){let{CURVE:e,curveOpts:t,hash:n,ecdsaOpts:i}=yz(r),o=hz(e,t),s=mz(o,n,i);return wz(r,s)}function MC(r,e){let t=n=>LC({...r,hash:n});return{...t(e),create:t}}var gx={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xz={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var UC=BigInt(2);function bz(r){let e=gx.p,t=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=Dt(u,t,e)*u%e,d=Dt(f,t,e)*u%e,h=Dt(d,UC,e)*l%e,m=Dt(h,i,e)*h%e,g=Dt(m,o,e)*m%e,w=Dt(g,a,e)*g%e,x=Dt(w,c,e)*w%e,v=Dt(x,a,e)*g%e,A=Dt(v,t,e)*u%e,S=Dt(A,s,e)*m%e,M=Dt(S,n,e)*l%e,F=Dt(M,UC,e);if(!mx.eql(mx.sqr(F),r))throw new Error("Cannot find square root");return F}var mx=oi(gx.p,{sqrt:bz}),ho=MC({...gx,Fp:mx,lowS:!0,endo:xz},Qg);var FC=32;function $C(r,e,t){let n=Be.digest(e instanceof Uint8Array?e:e.subarray());if(Wf(n))return n.then(({digest:i})=>(t?.signal?.throwIfAborted(),ho.sign(i,r).toDERRawBytes())).catch(i=>{throw i.name==="AbortError"?i:new Rp(String(i))});try{return ho.sign(n.digest,r).toDERRawBytes()}catch(i){throw new Rp(String(i))}}function HC(r,e,t,n){let i=Be.digest(t instanceof Uint8Array?t:t.subarray());if(Wf(i))return i.then(({digest:o})=>(n?.signal?.throwIfAborted(),ho.verify(e,o,r))).catch(o=>{throw o.name==="AbortError"?o:new Dp(String(o))});try{return n?.signal?.throwIfAborted(),ho.verify(e,i.digest,r)}catch(o){throw new Dp(String(o))}}var Mp=class{type="secp256k1";raw;_key;constructor(e){this._key=zC(e),this.raw=VC(this._key)}toMultihash(){return lr.digest(ur(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,t,n){return HC(this._key,t,e,n)}},Up=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=KC(e),this.publicKey=new Mp(t??qC(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,t){return $C(this.raw,e,t)}};function yx(r){return new Up(r)}function wx(r){return new Mp(r)}async function jC(){let r=vz();return new Up(r)}function VC(r){return ho.ProjectivePoint.fromHex(r).toRawBytes(!0)}function KC(r){try{return ho.getPublicKey(r,!0),r}catch(e){throw new cp(String(e))}}function zC(r){try{return ho.ProjectivePoint.fromHex(r),r}catch(e){throw new _s(String(e))}}function qC(r){try{return ho.getPublicKey(r,!0)}catch(e){throw new cp(String(e))}}function vz(){return ho.utils.randomPrivateKey()}async function Jf(r,e){if(r==="Ed25519")return _C();if(r==="secp256k1")return jC();if(r==="RSA")return fx(Az(e));if(r==="ECDSA")return R_(Ez(e));throw new so}function rr(r,e){let{Type:t,Data:n}=Zo.decode(r),i=n??new Uint8Array;switch(t){case _t.RSA:return cx(i,e);case _t.Ed25519:return ex(i);case _t.secp256k1:return wx(i);case _t.ECDSA:return R7(i);default:throw new so}}function l2(r){let{Type:e,Data:t}=Zo.decode(r.digest),n=t??new Uint8Array;switch(e){case _t.Ed25519:return ex(n);case _t.secp256k1:return wx(n);case _t.ECDSA:return R7(n);default:throw new so}}function ur(r){return Zo.encode({Type:_t[r.type],Data:r.raw})}function WC(r){let e=Np.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case _t.RSA:return ax(t);case _t.Ed25519:return J7(t);case _t.secp256k1:return yx(t);case _t.ECDSA:return C_(t);default:throw new so}}function GC(r){if(r.byteLength===si)return J7(r);if(r.byteLength===FC)return yx(r);let e=Di(r),t=e[2]?.[0];if(t===y_||t===w_||t===x_)return P7(e);if(e.length>8)return s2(e);throw new K("Could not extract private key from raw bytes")}function _l(r){return Np.encode({Type:_t[r.type],Data:r.raw})}function Az(r){return r==null?2048:parseInt(r,10)}function Ez(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new K("Unsupported curve, should be P-256, P-384 or P-521")}async function u2(r){if(r.type==="RSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};if(r.type==="ECDSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"ECDSA",namedCurve:r.jwk.crv??"P-256"},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"ECDSA",namedCurve:r.publicKey.jwk.crv??"P-256"},!0,["verify"])};throw new K("Only RSA and ECDSA keys are supported")}var XC=Symbol.for("nodejs.util.inspect.custom"),Sz=114,Fp=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[dg]=!0;toString(){return this.string==null&&(this.string=Ye.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return G.createV1(Sz,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return he(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return he(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[XC](){return`PeerId(${this.toString()})`}},$p=class extends Fp{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Hp=class extends Fp{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Vp=class extends Fp{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},_z=2336,Kp=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=lr.digest(D(this.url))}[XC](){return`PeerId(${this.url})`}[dg]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return G.createV1(_z,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var Cz=114,YC=2336;function gt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=We(Ye.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return vn(G.parse(r));if(e==null)throw new K('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=We(e.decode(r))}return dr(t)}function es(r){if(r.type==="Ed25519")return new Hp({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Vp({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new $p({multihash:r.toCID().multihash,publicKey:r});throw new so}function QC(r){return es(r.publicKey)}function dr(r){if(Iz(r))return new $p({multihash:r});if(Tz(r))try{let e=l2(r);if(e.type==="Ed25519")return new Hp({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Vp({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new Kp(new URL(t))}throw new Ua("Supplied PeerID Multihash is invalid")}function vn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Cz&&r.code!==YC)throw new yg("Supplied PeerID CID is invalid");if(r.code===YC){let e=z(r.multihash.digest);return new Kp(new URL(e))}return dr(r.multihash)}function Tz(r){return r.code===lr.code}function Iz(r){return r.code===Be.code}function Cl(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}function f2(r){let e=We(Ye.decode(`z${r}`));return dr(e)}var nn=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Cl(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Cl(this.map.values(),e=>e.key)}values(){return Cl(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ai=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Cl(this.set.entries(),e=>{let t=f2(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=f2(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Cl(this.set.values(),e=>f2(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};function xx(){return new ai}function ZC(r,e,t,n){Ns(r);let i=L_({dkLen:32,asyncTick:10},n),{c:o,dkLen:s,asyncTick:a}=i;if(uo(o),uo(s),uo(a),o<1)throw new Error("iterations (c) should be >= 1");let c=D7(e),l=D7(t),u=new Uint8Array(s),f=Ya.create(r,c),d=f._cloneInto().update(l);return{c:o,dkLen:s,asyncTick:a,DK:u,PRF:f,PRFSalt:d}}function JC(r,e,t,n,i){return r.destroy(),e.destroy(),n&&n.destroy(),rn(i),t}function eT(r,e,t,n){let{c:i,dkLen:o,DK:s,PRF:a,PRFSalt:c}=ZC(r,e,t,n),l,u=new Uint8Array(4),f=yl(u),d=new Uint8Array(a.outputLen);for(let h=1,m=0;m<o;h++,m+=a.outputLen){let g=s.subarray(m,m+a.outputLen);f.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(d),g.set(d.subarray(0,g.length));for(let w=1;w<i;w++){a._cloneInto(l).update(d).digestInto(d);for(let x=0;x<g.length;x++)g[x]^=d[x]}}return JC(a,c,s,l,d)}async function d2(r,e,t,n){let{c:i,dkLen:o,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=ZC(r,e,t,n),u,f=new Uint8Array(4),d=yl(f),h=new Uint8Array(c.outputLen);for(let m=1,g=0;g<o;m++,g+=c.outputLen){let w=a.subarray(g,g+c.outputLen);d.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(h),w.set(h.subarray(0,w.length)),await B_(i-1,s,()=>{c._cloneInto(u).update(h).digestInto(h);for(let x=0;x<w.length;x++)w[x]^=h[x]})}return JC(c,l,a,u,h)}var zp=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Qa=new Uint32Array(80),h2=class extends xl{constructor(){super(64,20,8,!1),this.A=zp[0]|0,this.B=zp[1]|0,this.C=zp[2]|0,this.D=zp[3]|0,this.E=zp[4]|0}get(){let{A:e,B:t,C:n,D:i,E:o}=this;return[e,t,n,i,o]}set(e,t,n,i,o){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0}process(e,t){for(let c=0;c<16;c++,t+=4)Qa[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Qa[c]=zg(Qa[c-3]^Qa[c-8]^Qa[c-14]^Qa[c-16],1);let{A:n,B:i,C:o,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=jg(i,o,s),u=1518500249):c<40?(l=i^o^s,u=1859775393):c<60?(l=Wg(i,o,s),u=2400959708):(l=i^o^s,u=3395469782);let f=zg(n,5)+l+a+u+Qa[c]|0;a=s,s=o,o=zg(i,30),i=n,n=f}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,i,o,s,a)}roundClean(){rn(Qa)}destroy(){this.set(0,0,0,0,0),rn(this.buffer)}},tT=vp(()=>new h2);var rT=tT;var ed=Zg;var nT={sha1:rT,"sha2-256":Jo,"sha2-512":ed};function qp(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(nT).join(" / ");throw new K(`Hash '${i}' is unknown or not supported. Must be ${a}`)}let o=nT[i],s=eT(o,r,e,{c:t,dkLen:n});return cr.encode(s).substring(1)}var bx={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},iT={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},oT=new globalThis.TextEncoder;function kz(r,e){let t=bx[e],n=iT[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Pz(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=bx[e],i=iT[e],o=r;for(;o.length>0;){let s=oT.encodeInto(o,t);o=o.slice(s.read);for(let a=0;a<s.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function vx(r,{size:e=32,utf8Buffer:t}={}){if(!bx[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Pz(r,e,t);r=oT.encode(r)}return kz(r,e)}var jp={hash:r=>Number(vx(r,{size:32})),hashV:(r,e)=>Rz(jp.hash(r,e))};function Rz(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}var Ax=64,po=class{fp;h;seed;constructor(e,t,n,i=2){if(i>Ax)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=ke(i);for(let a=0;a<s.length;a++)s[a]=o[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?he(this.fp,e.fp):!1}};function Tl(r,e){return Math.floor(Math.random()*(e-r))+r}var Il=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");let t=Tl(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dz=500,Wp=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??jp,this.seed=e.seed??Tl(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new po(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Il(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new Il(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[Tl(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Il(this.bucketSize));for(let a=0;a<Dz;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Il(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new po(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new po(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Oz={1:.5,2:.84,4:.95,8:.98};function Nz(r=.001){return r>.002?2:r>1e-5?4:8}function sT(r,e=.001){let t=Nz(e),n=Oz[t],i=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Ax);return{filterSize:i,bucketSize:t,fingerprintSize:o}}var td=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??jp,this.seed=e.seed??Tl(0,Math.pow(2,10)),this.filterSeries=[new Wp({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Wp({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function on(r,e=.001,t){return new td({...sT(r,e),...t??{}})}var p2=class{filter;constructor(e,t){this.filter=on(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function Ex(r,e=.001){return new p2(r,e)}var Sx=class extends nn{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function zs(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Sx({name:e,metrics:t}):n=new nn,n}var qs=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=cr.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=cr.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=cr.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Bz(r){let e=new Uint8Array(r.reduce((n,i)=>n+je(i),0)),t=0;for(let n of r)e=Sr(n,e,t),t+=je(n);return e}var aT=Bz;function _x(r){return aT([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var m2=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new qs,n=new Set;for(let[i,o]of this.wants.entries())try{let s=await this.blockstore.get(o.cid,e);o.wantType===tr.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(i),t.addBlock(o.cid,{data:s,prefix:_x(o.cid)})):(this.log("sending have for %c",o.cid),t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:Ri.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(i),t.addBlock(o.cid,{data:s,prefix:_x(o.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:Ri.DoNotHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((i,o)=>i+o.data.byteLength,0));for(let i of n)this.wants.delete(i)}}};var g2=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=zs({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(i=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,i)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new m2({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((i,o)=>i+o.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let i of t.wantlist.entries){let o=G.decode(i.cid),s=z(o.multihash.bytes,"base64");i.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,o),n.wants.delete(s)):(i.wantType===tr.WantHave?this.log("peer %p wanted block presence for %c",e,o):this.log("peer %p wanted block for %c",e,o),n.wants.set(s,{cid:o,priority:i.priority,wantType:i.wantType??tr.WantBlock,sendDontHave:i.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=z(e.multihash.bytes,"base64"),i=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&i.push(o);await Promise.all(i.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};function Lz(r,e){if(typeof r=="string")return Mz(r);if(typeof r=="number")return $z(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var y2=Lz;function Mz(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,i=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*315576e5;case"months":case"month":case"mo":return i*26298e5;case"weeks":case"week":case"w":return i*6048e5;case"days":case"day":case"d":return i*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return i*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return i*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return i*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Uz(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Fz(r){let e=Math.abs(r);return e>=315576e5?kl(r,e,315576e5,"year"):e>=26298e5?kl(r,e,26298e5,"month"):e>=6048e5?kl(r,e,6048e5,"week"):e>=864e5?kl(r,e,864e5,"day"):e>=36e5?kl(r,e,36e5,"hour"):e>=6e4?kl(r,e,6e4,"minute"):e>=1e3?kl(r,e,1e3,"second"):`${r} ms`}function $z(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?Fz(r):Uz(r)}function kl(r,e,t,n){let i=e>=t*1.5;return`${Math.round(r/t)} ${n}${i?"s":""}`}function Cx(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=y2,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,h,m;function g(...w){if(!g.enabled)return;let x=g,v=Number(new Date),A=v-(f||v);x.diff=A,x.prev=f,x.curr=v,f=v,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let S=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(F,N)=>{if(F==="%%")return"%";S++;let R=t.formatters[N];if(typeof R=="function"){let _=w[S];F=R.call(x,_),w.splice(S,1),S--}return F}),t.formatArgs.call(x,w),(x.log||t.log).apply(x,w)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:w=>{d=w}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function i(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var w2=Wz(),Hz=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Vz(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Kz(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+y2(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}var zz=console.debug??console.log??(()=>{});function qz(r){try{r?w2?.setItem("debug",r):w2?.removeItem("debug")}catch{}}function jz(){let r;try{r=w2?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Wz(){try{return localStorage}catch{}}function Gz(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var cT=Cx({formatArgs:Kz,save:qz,load:jz,useColors:Vz,setupFormatters:Gz,colors:Hz,storage:w2,log:zz});var Dn=cT;Dn.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);Dn.formatters.t=r=>r==null?"undefined":jt.baseEncode(r);Dn.formatters.m=r=>r==null?"undefined":cr.baseEncode(r);Dn.formatters.p=r=>r==null?"undefined":r.toString();Dn.formatters.c=r=>r==null?"undefined":r.toString();Dn.formatters.k=r=>r==null?"undefined":r.toString();Dn.formatters.a=r=>r==null?"undefined":r.toString();Dn.formatters.e=r=>r==null?"undefined":lT(r.stack)??lT(r.message)??r.toString();function Xz(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function uT(r){return{forComponent(e){return Ue(`${r}:${e}`)}}}function Za(){return{forComponent(r){return Ue(r)}}}function Ue(r){let e=Xz(`${r}:trace`);return Dn.enabled(`${r}:trace`)&&Dn.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=Dn(`${r}:trace`)),Object.assign(Dn(r),{error:Dn(`${r}:error`),trace:e,newScope:t=>Ue(`${r}:${t}`)})}function lT(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Ix=mt(dT(),1);var Xp=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},kx=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},hT=r=>globalThis.DOMException===void 0?new kx(r):new DOMException(r),pT=r=>{let e=r.reason===void 0?hT("This operation was aborted."):r.reason;return e instanceof Error?e:hT(e)};function js(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(pT(h)),a=()=>{f(pT(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Xp;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?u():i instanceof Error?f(i):(d.message=i??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},l}function Px(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Yp=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let i=Px(this.#e,n,(o,s)=>s.priority-o.priority);this.#e.splice(i,0,n)}setPriority(e,t){let n=this.#e.findIndex(o=>o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#e.splice(n,1);this.enqueue(i.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var mo=class extends Ix.default{#e;#t;#r=0;#o;#c;#l=0;#s;#n;#i;#d;#a=0;#f;#u;#h;#x=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Yp,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#o=e.intervalCap,this.#c=e.interval,this.#i=new e.queueClass,this.#d=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#h=e.throwOnTimeout===!0,this.#u=e.autoStart===!1}get#b(){return this.#t||this.#r<this.#o}get#v(){return this.#a<this.#f}#A(){this.#a--,this.#p(),this.emit("next")}#E(){this.#w(),this.#y(),this.#n=void 0}get#S(){let e=Date.now();if(this.#s===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#a:0;else return this.#n===void 0&&(this.#n=setTimeout(()=>{this.#E()},t)),!0}return!1}#p(){if(this.#i.size===0)return this.#s&&clearInterval(this.#s),this.#s=void 0,this.emit("empty"),this.#a===0&&this.emit("idle"),!1;if(!this.#u){let e=!this.#S;if(this.#b&&this.#v){let t=this.#i.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#s!==void 0||(this.#s=setInterval(()=>{this.#w()},this.#c),this.#l=Date.now()+this.#c)}#w(){this.#r===0&&this.#a===0&&this.#s&&(clearInterval(this.#s),this.#s=void 0),this.#r=this.#e?this.#a:0,this.#m()}#m(){for(;this.#p(););}get concurrency(){return this.#f}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#f=e,this.#m()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#i.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#x++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#h,...t},new Promise((n,i)=>{this.#i.enqueue(async()=>{this.#a++;try{t.signal?.throwIfAborted(),this.#r++;let o=e({signal:t.signal});t.timeout&&(o=js(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#_(t.signal)]));let s=await o;n(s),this.emit("completed",s)}catch(o){if(o instanceof Xp&&!t.throwOnTimeout){n();return}i(o),this.emit("error",o)}finally{this.#A()}},t),this.emit("add"),this.#p()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#u?(this.#u=!1,this.#m(),this):this}pause(){this.#u=!0}clear(){this.#i=new this.#d}async onEmpty(){this.#i.size!==0&&await this.#g("empty")}async onSizeLessThan(e){this.#i.size<e||await this.#g("next",()=>this.#i.size<e)}async onIdle(){this.#a===0&&this.#i.size===0||await this.#g("idle")}async#g(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#i.size}sizeBy(e){return this.#i.filter(e).length}get pending(){return this.#a}get isPaused(){return this.#u}};function b2(r){let e=[an.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Rx=60;function v2(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:an[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:an[e.type],TTL:e.TTL??e.ttl??Rx,data:e.data instanceof Uint8Array?z(e.data):e.data}))}}var Zz=4;function Dx(r,e={}){let t=new mo({concurrency:e.queryConcurrency??Zz});return async(n,i={})=>{let o=new URLSearchParams;o.set("name",n),b2(i.types).forEach(a=>{o.append("type",an[a])}),i.onProgress?.(new X("dns:query",n));let s=await t.add(async()=>{let a=await fetch(`${r}?${o}`,{headers:{accept:"application/dns-json"},signal:i?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=v2(await a.json());return i.onProgress?.(new X("dns:response",c)),c},{signal:i.signal});if(s==null)throw new Error("No DNS response received");return s}}function mT(){return[Dx("https://cloudflare-dns.com/dns-query"),Dx("https://dns.google/resolve")]}var wT=mt(yT(),1);var Ox=class{lru;constructor(e){this.lru=(0,wT.default)(e)}get(e,t){let n=!0,i=[];for(let o of t){let s=this.getAnswers(e,o);if(s.length===0){n=!1;break}i.push(...s)}if(n)return v2({answers:i})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,i=this.lru.get(n);if(i!=null){let o=i.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:an[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,i=this.lru.get(n)??[];i.push({expires:Date.now()+(t.TTL??Rx)*1e3,value:t}),this.lru.set(n,i)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function xT(r){return new Ox(r)}var Jz=1e3,A2=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=xT(e.cacheSize??Jz),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=mT())}async query(e,t={}){let n=b2(t.types),i=t.cached!==!1?this.cache.get(e,n):void 0;if(i!=null)return t.onProgress?.(new X("dns:cache",i)),i;let o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new X("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var an;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(an||(an={}));function Pl(r={}){return new A2(r)}var eq=["string","number","bigint","symbol"],tq=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function bT(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(eq.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(rq(r))return"Buffer";let t=nq(r);return t||"Object"}function rq(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function nq(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(tq.includes(e))return e}var I=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};I.uint=new I(0,"uint",!0);I.negint=new I(1,"negint",!0);I.bytes=new I(2,"bytes",!0);I.string=new I(3,"string",!0);I.array=new I(4,"array",!1);I.map=new I(5,"map",!1);I.tag=new I(6,"tag",!1);I.float=new I(7,"float",!0);I.false=new I(7,"false",!0);I.true=new I(7,"true",!0);I.null=new I(7,"null",!0);I.undefined=new I(7,"undefined",!0);I.break=new I(7,"break",!0);var Y=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var rd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",iq=new TextDecoder,oq=new TextEncoder;function E2(r){return rd&&globalThis.Buffer.isBuffer(r)}function Qp(r){return r instanceof Uint8Array?E2(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var ST=rd?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):AT(r,e,t):(r,e,t)=>t-e>64?iq.decode(r.subarray(e,t)):AT(r,e,t),S2=rd?r=>r.length>64?globalThis.Buffer.from(r):vT(r):r=>r.length>64?oq.encode(r):vT(r),ts=r=>Uint8Array.from(r),nd=rd?(r,e,t)=>E2(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_T=rd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Qp(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},CT=rd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function TT(r,e){if(E2(r)&&E2(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function vT(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function AT(r,e,t){let n=[];for(;e<t;){let i=r[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,l,u;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(u=(i&31)<<6|a&63,u>127&&(o=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(i&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(i&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(o=u))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return Nx(n)}var ET=4096;function Nx(r){let e=r.length;if(e<=ET)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=ET));return t}var sq=256,Zp=class{constructor(e=sq){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=CT(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=nd(n,0,this.cursor)}else t=_T(this.chunks,this.cursor);return e&&this.reset(),t}};var me="CBOR decode error:",Ws="CBOR encode error:",Jp=[];Jp[23]=1;Jp[24]=2;Jp[25]=3;Jp[26]=5;Jp[27]=9;function Gs(r,e,t){if(r.length-e<t)throw new Error(`${me} not enough data for type`)}var Tr=[24,256,65536,4294967296,BigInt("18446744073709551616")];function ci(r,e,t){Gs(r,e,1);let n=r[e];if(t.strict===!0&&n<Tr[0])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);return n}function li(r,e,t){Gs(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Tr[1])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);return n}function ui(r,e,t){Gs(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Tr[2])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);return n}function fi(r,e,t){Gs(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<Tr[3])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${me} integers outside of the safe integer range are not supported`)}function IT(r,e,t,n){return new Y(I.uint,ci(r,e+1,n),2)}function kT(r,e,t,n){return new Y(I.uint,li(r,e+1,n),3)}function PT(r,e,t,n){return new Y(I.uint,ui(r,e+1,n),5)}function RT(r,e,t,n){return new Y(I.uint,fi(r,e+1,n),9)}function Li(r,e){return Lr(r,0,e.value)}function Lr(r,e,t){if(t<Tr[0]){let n=Number(t);r.push([e|n])}else if(t<Tr[1]){let n=Number(t);r.push([e|24,n])}else if(t<Tr[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Tr[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Tr[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${me} encountered BigInt larger than allowable range`)}}Li.encodedSize=function(e){return Lr.encodedSize(e.value)};Lr.encodedSize=function(e){return e<Tr[0]?1:e<Tr[1]?2:e<Tr[2]?3:e<Tr[3]?5:9};Li.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function DT(r,e,t,n){return new Y(I.negint,-1-ci(r,e+1,n),2)}function OT(r,e,t,n){return new Y(I.negint,-1-li(r,e+1,n),3)}function NT(r,e,t,n){return new Y(I.negint,-1-ui(r,e+1,n),5)}var Bx=BigInt(-1),BT=BigInt(1);function LT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new Y(I.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${me} integers outside of the safe integer range are not supported`);return new Y(I.negint,Bx-BigInt(i),9)}function _2(r,e){let t=e.value,n=typeof t=="bigint"?t*Bx-BT:t*-1-1;Lr(r,e.type.majorEncoded,n)}_2.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Bx-BT:t*-1-1;return n<Tr[0]?1:n<Tr[1]?2:n<Tr[2]?3:n<Tr[3]?5:9};_2.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function em(r,e,t,n){Gs(r,e,t+n);let i=nd(r,e+t,e+t+n);return new Y(I.bytes,i,t+n)}function MT(r,e,t,n){return em(r,e,1,t)}function UT(r,e,t,n){return em(r,e,2,ci(r,e+1,n))}function FT(r,e,t,n){return em(r,e,3,li(r,e+1,n))}function $T(r,e,t,n){return em(r,e,5,ui(r,e+1,n))}function HT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer bytes lengths not supported`);return em(r,e,9,i)}function C2(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===I.string?S2(r.value):r.value),r.encodedBytes}function id(r,e){let t=C2(e);Lr(r,e.type.majorEncoded,t.length),r.push(t)}id.encodedSize=function(e){let t=C2(e);return Lr.encodedSize(t.length)+t.length};id.compareTokens=function(e,t){return cq(C2(e),C2(t))};function cq(r,e){return r.length<e.length?-1:r.length>e.length?1:TT(r,e)}function tm(r,e,t,n,i){let o=t+n;Gs(r,e,o);let s=new Y(I.string,ST(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=nd(r,e+t,e+o)),s}function VT(r,e,t,n){return tm(r,e,1,t,n)}function KT(r,e,t,n){return tm(r,e,2,ci(r,e+1,n),n)}function zT(r,e,t,n){return tm(r,e,3,li(r,e+1,n),n)}function qT(r,e,t,n){return tm(r,e,5,ui(r,e+1,n),n)}function jT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer string lengths not supported`);return tm(r,e,9,i,n)}var WT=id;function od(r,e,t,n){return new Y(I.array,n,t)}function GT(r,e,t,n){return od(r,e,1,t)}function XT(r,e,t,n){return od(r,e,2,ci(r,e+1,n))}function YT(r,e,t,n){return od(r,e,3,li(r,e+1,n))}function QT(r,e,t,n){return od(r,e,5,ui(r,e+1,n))}function ZT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer array lengths not supported`);return od(r,e,9,i)}function JT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${me} indefinite length items not allowed`);return od(r,e,1,1/0)}function T2(r,e){Lr(r,I.array.majorEncoded,e.value)}T2.compareTokens=Li.compareTokens;T2.encodedSize=function(e){return Lr.encodedSize(e.value)};function sd(r,e,t,n){return new Y(I.map,n,t)}function eI(r,e,t,n){return sd(r,e,1,t)}function tI(r,e,t,n){return sd(r,e,2,ci(r,e+1,n))}function rI(r,e,t,n){return sd(r,e,3,li(r,e+1,n))}function nI(r,e,t,n){return sd(r,e,5,ui(r,e+1,n))}function iI(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer map lengths not supported`);return sd(r,e,9,i)}function oI(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${me} indefinite length items not allowed`);return sd(r,e,1,1/0)}function I2(r,e){Lr(r,I.map.majorEncoded,e.value)}I2.compareTokens=Li.compareTokens;I2.encodedSize=function(e){return Lr.encodedSize(e.value)};function sI(r,e,t,n){return new Y(I.tag,t,1)}function aI(r,e,t,n){return new Y(I.tag,ci(r,e+1,n),2)}function cI(r,e,t,n){return new Y(I.tag,li(r,e+1,n),3)}function lI(r,e,t,n){return new Y(I.tag,ui(r,e+1,n),5)}function uI(r,e,t,n){return new Y(I.tag,fi(r,e+1,n),9)}function k2(r,e){Lr(r,I.tag.majorEncoded,e.value)}k2.compareTokens=Li.compareTokens;k2.encodedSize=function(e){return Lr.encodedSize(e.value)};var pq=20,mq=21,gq=22,yq=23;function fI(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${me} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Y(I.null,null,1):new Y(I.undefined,void 0,1)}function dI(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${me} indefinite length items not allowed`);return new Y(I.break,void 0,1)}function Lx(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${me} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${me} Infinity values are not supported`)}return new Y(I.float,r,e)}function hI(r,e,t,n){return Lx(Mx(r,e+1),3,n)}function pI(r,e,t,n){return Lx(Ux(r,e+1),5,n)}function mI(r,e,t,n){return Lx(xI(r,e+1),9,n)}function P2(r,e,t){let n=e.value;if(n===!1)r.push([I.float.majorEncoded|pq]);else if(n===!0)r.push([I.float.majorEncoded|mq]);else if(n===null)r.push([I.float.majorEncoded|gq]);else if(n===void 0)r.push([I.float.majorEncoded|yq]);else{let i,o=!1;(!t||t.float64!==!0)&&(yI(n),i=Mx(go,1),n===i||Number.isNaN(n)?(go[0]=249,r.push(go.slice(0,3)),o=!0):(wI(n),i=Ux(go,1),n===i&&(go[0]=250,r.push(go.slice(0,5)),o=!0))),o||(wq(n),i=xI(go,1),go[0]=251,r.push(go.slice(0,9)))}}P2.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){yI(n);let i=Mx(go,1);if(n===i||Number.isNaN(n))return 3;if(wI(n),i=Ux(go,1),n===i)return 5}return 9};var gI=new ArrayBuffer(9),Mi=new DataView(gI,1),go=new Uint8Array(gI,0);function yI(r){if(r===1/0)Mi.setUint16(0,31744,!1);else if(r===-1/0)Mi.setUint16(0,64512,!1);else if(Number.isNaN(r))Mi.setUint16(0,32256,!1);else{Mi.setFloat32(0,r);let e=Mi.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Mi.setUint16(0,31744,!1);else if(t===0)Mi.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Mi.setUint16(0,0):i<-14?Mi.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Mi.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function Mx(r,e){if(r.length-e<2)throw new Error(`${me} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function wI(r){Mi.setFloat32(0,r,!1)}function Ux(r,e){if(r.length-e<4)throw new Error(`${me} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function wq(r){Mi.setFloat64(0,r,!1)}function xI(r,e){if(r.length-e<8)throw new Error(`${me} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}P2.compareTokens=Li.compareTokens;function nt(r,e,t){throw new Error(`${me} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function R2(r){return()=>{throw new Error(`${me} ${r}`)}}var ie=[];for(let r=0;r<=23;r++)ie[r]=nt;ie[24]=IT;ie[25]=kT;ie[26]=PT;ie[27]=RT;ie[28]=nt;ie[29]=nt;ie[30]=nt;ie[31]=nt;for(let r=32;r<=55;r++)ie[r]=nt;ie[56]=DT;ie[57]=OT;ie[58]=NT;ie[59]=LT;ie[60]=nt;ie[61]=nt;ie[62]=nt;ie[63]=nt;for(let r=64;r<=87;r++)ie[r]=MT;ie[88]=UT;ie[89]=FT;ie[90]=$T;ie[91]=HT;ie[92]=nt;ie[93]=nt;ie[94]=nt;ie[95]=R2("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)ie[r]=VT;ie[120]=KT;ie[121]=zT;ie[122]=qT;ie[123]=jT;ie[124]=nt;ie[125]=nt;ie[126]=nt;ie[127]=R2("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)ie[r]=GT;ie[152]=XT;ie[153]=YT;ie[154]=QT;ie[155]=ZT;ie[156]=nt;ie[157]=nt;ie[158]=nt;ie[159]=JT;for(let r=160;r<=183;r++)ie[r]=eI;ie[184]=tI;ie[185]=rI;ie[186]=nI;ie[187]=iI;ie[188]=nt;ie[189]=nt;ie[190]=nt;ie[191]=oI;for(let r=192;r<=215;r++)ie[r]=sI;ie[216]=aI;ie[217]=cI;ie[218]=lI;ie[219]=uI;ie[220]=nt;ie[221]=nt;ie[222]=nt;ie[223]=nt;for(let r=224;r<=243;r++)ie[r]=R2("simple values are not supported");ie[244]=nt;ie[245]=nt;ie[246]=nt;ie[247]=fI;ie[248]=R2("simple values are not supported");ie[249]=hI;ie[250]=pI;ie[251]=mI;ie[252]=nt;ie[253]=nt;ie[254]=nt;ie[255]=dI;var yo=[];for(let r=0;r<24;r++)yo[r]=new Y(I.uint,r,1);for(let r=-1;r>=-24;r--)yo[31-r]=new Y(I.negint,r,1);yo[64]=new Y(I.bytes,new Uint8Array(0),1);yo[96]=new Y(I.string,"",1);yo[128]=new Y(I.array,0,1);yo[160]=new Y(I.map,0,1);yo[244]=new Y(I.false,!1,1);yo[245]=new Y(I.true,!0,1);yo[246]=new Y(I.null,null,1);function Fx(r){switch(r.type){case I.false:return ts([244]);case I.true:return ts([245]);case I.null:return ts([246]);case I.bytes:return r.value.length?void 0:ts([64]);case I.string:return r.value===""?ts([96]):void 0;case I.array:return r.value===0?ts([128]):void 0;case I.map:return r.value===0?ts([160]):void 0;case I.uint:return r.value<24?ts([Number(r.value)]):void 0;case I.negint:if(r.value>=-24)return ts([31-Number(r.value)])}}var bq={float64:!1,mapSorter:Aq,quickEncodeToken:Fx};function Hx(){let r=[];return r[I.uint.major]=Li,r[I.negint.major]=_2,r[I.bytes.major]=id,r[I.string.major]=WT,r[I.array.major]=T2,r[I.map.major]=I2,r[I.tag.major]=k2,r[I.float.major]=P2,r}var bI=Hx(),$x=new Zp,D2=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Ws} object contains circular references`);return new r(t,e)}},Ja={null:new Y(I.null,null),undefined:new Y(I.undefined,void 0),true:new Y(I.true,!0),false:new Y(I.false,!1),emptyArray:new Y(I.array,0),emptyMap:new Y(I.map,0)},ec={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Y(I.float,r):r>=0?new Y(I.uint,r):new Y(I.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Y(I.uint,r):new Y(I.negint,r)},Uint8Array(r,e,t,n){return new Y(I.bytes,r)},string(r,e,t,n){return new Y(I.string,r)},boolean(r,e,t,n){return r?Ja.true:Ja.false},null(r,e,t,n){return Ja.null},undefined(r,e,t,n){return Ja.undefined},ArrayBuffer(r,e,t,n){return new Y(I.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Y(I.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Ja.emptyArray,new Y(I.break)]:Ja.emptyArray;n=D2.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=rm(s,t,n);return t.addBreakTokens?[new Y(I.array,r.length),i,new Y(I.break)]:[new Y(I.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[Ja.emptyMap,new Y(I.break)]:Ja.emptyMap;n=D2.createCheck(n,r);let a=[],c=0;for(let l of o)a[c++]=[rm(l,t,n),rm(i?r.get(l):r[l],t,n)];return vq(a,t),t.addBreakTokens?[new Y(I.map,s),a,new Y(I.break)]:[new Y(I.map,s),a]}};ec.Map=ec.Object;ec.Buffer=ec.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ec[`${r}Array`]=ec.DataView;function rm(r,e={},t){let n=bT(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||ec[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=ec[n];if(!o)throw new Error(`${Ws} unsupported type: ${n}`);return o(r,n,e,t)}function vq(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Aq(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=bI[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function vI(r,e,t,n){if(Array.isArray(e))for(let i of e)vI(r,i,t,n);else t[e.type.major](r,e,n)}function Vx(r,e,t){let n=rm(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new Zp(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Qp(a.chunks[0])}}return $x.reset(),vI($x,n,e,t),$x.toBytes(!0)}function Xs(r,e){return e=Object.assign({},bq,e),Vx(r,bI,e)}var Eq={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},O2=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=yo[e];if(t===void 0){let n=ie[e];if(!n)throw new Error(`${me} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},nm=Symbol.for("DONE"),N2=Symbol.for("BREAK");function Sq(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=ad(e,t);if(o===N2){if(r.value===1/0)break;throw new Error(`${me} got unexpected break to lengthed array`)}if(o===nm)throw new Error(`${me} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function _q(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},o=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=ad(e,t);if(a===N2){if(r.value===1/0)break;throw new Error(`${me} got unexpected break to lengthed map`)}if(a===nm)throw new Error(`${me} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${me} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&o.has(a)||!n&&a in i))throw new Error(`${me} found repeat map key "${a}"`);let c=ad(e,t);if(c===nm)throw new Error(`${me} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?o.set(a,c):i[a]=c}return n?o:i}function ad(r,e){if(r.done())return nm;let t=r.next();if(t.type===I.break)return N2;if(t.type.terminal)return t.value;if(t.type===I.array)return Sq(t,r,e);if(t.type===I.map)return _q(t,r,e);if(t.type===I.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=ad(r,e);return e.tags[t.value](n)}throw new Error(`${me} tag not supported (${t.value})`)}throw new Error("unsupported")}function Kx(r,e){if(!(r instanceof Uint8Array))throw new Error(`${me} data to decode must be a Uint8Array`);e=Object.assign({},Eq,e);let t=e.tokenizer||new O2(r,e),n=ad(t,e);if(n===nm)throw new Error(`${me} did not find any content to decode`);if(n===N2)throw new Error(`${me} got unexpected break`);return[n,r.subarray(t.pos())]}function En(r,e){let[t,n]=Kx(r,e);if(n.length>0)throw new Error(`${me} too many terminals, data makes no sense`);return t}var Ys="/",AI=new TextEncoder().encode(Ys),B2=AI[0],it=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==B2)throw new Error("Invalid key")}toString(e="utf8"){return z(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ys))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=AI),this._buf[0]!==B2){let e=new Uint8Array(this._buf.byteLength+1);e.fill(B2,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===B2;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ys).slice(1)}type(){return Cq(this.baseNamespace())}name(){return Tq(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ys)||(e+=Ys),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ys):new r(e.slice(0,-1).join(Ys))}child(e){return this.toString()===Ys?e:e.toString()===Ys?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Iq(e.map(t=>t.namespaces()))])}};function Cq(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Tq(r){let e=r.split(":");return e[e.length-1]}function Iq(r){return[].concat(...r)}function L2({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*kq(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=G.asCID(n);o!=null?yield[i.join("/"),o]:typeof n=="object"&&(yield*qx(n,i))}else{let t=G.asCID(e);t!=null?yield[r.join("/"),t]:yield*qx(e,r)}}function*qx(r,e){if(r==null||r instanceof Uint8Array)return;let t=G.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*kq(o,i)}}function*Pq(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&G.asCID(n)==null&&(yield*jx(n,i))}else yield*jx(e,r)}function*jx(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&G.asCID(n)==null&&(yield*Pq(i,n))}}function Rq(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=G.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var Wx=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:L2(),bytes:L2(),value:L2(),asBlock:L2()})}links(){return qx(this.value,[])}tree(){return jx(this.value,[])}get(e="/"){return Rq(this.value,e.split("/").filter(Boolean))}};function im({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n?.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Wx({cid:e,bytes:r,value:i})}var _I="/pin/",EI="/pinned-block/",Gx=mn,SI=1;function M2(r){return r.version===0&&(r=r.toV1()),new it(`${_I}${r.toString(Gx)}`)}var U2=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=M2(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let o=new Dr({concurrency:SI});for await(let a of this.#e(e,o,{...t,depth:i}))await this.#t(a,c=>c.pinnedBy.find(l=>he(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:i,metadata:t.metadata??{}};await this.datastore.put(n,Xs(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let i=await this.getCodec(e.code),o=await this.blockstore.get(e,n),s=im({bytes:o,cid:e,codec:i});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let i=new it(`${EI}${Gx.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=En(await this.datastore.get(i,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(o)){if(o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,Xs(o),n),n.onProgress?.(new X("helia:pin:add",e))}}async*rm(e,t={}){let n=M2(e),i=await this.datastore.get(n,t),o=En(i);await this.datastore.delete(n,t);let s=new Dr({concurrency:SI});for await(let a of this.#e(e,s,{...t,depth:o.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>he(l,e.bytes)),!0),{...t,depth:o.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_I+(e.cid!=null?`${e.cid.toString(mn)}`:"")},e)){let i=G.parse(t.toString().substring(5),mn),o=En(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new it(`${EI}${Gx.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=M2(e),i=await this.datastore.get(n,t);return En(i)}async setMetadata(e,t,n){let i=M2(e),o=await this.datastore.get(i,n),s=En(o);s.metadata=t??{},await this.datastore.put(i,Xs(s),n)}};var F2=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Dl=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},$2=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},H2=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var Dq=5,V2=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Dq,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await Rr(...this.routers)}async stop(){await Zr(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Dl("No content routers available");let n=new Or({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let i of pn(n.toGenerator(),...Ol(this.routers,"findProviders").map(o=>o.findProviders(e,t))))if(i!=null){if(i.multiaddrs.length===0){if(n.find(i.id)!=null)continue;n.add(async()=>{try{let o=await this.findPeer(i.id,t);return o.multiaddrs.length===0?null:o}catch(o){return this.log.error("could not load multiaddrs for peer %p",i.id,o),null}},{peerId:i.id,signal:t.signal}).catch(o=>{this.log.error("could not load multiaddrs for peer %p",i.id,o)})}yield i}}async provide(e,t={}){if(this.routers.length===0)throw new Dl("No content routers available");await Promise.all(Ol(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Ol(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Ol(this.routers,"put").map(async i=>{await i.put(e,t,n)}))}async get(e,t){return Promise.any(Ol(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Dl("No peer routers available");let n=this,i=pn(...Ol(this.routers,"findPeer").map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let o of i)if(o!=null)return o;throw new qe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Dl("No peer routers available");for await(let n of pn(...Ol(this.routers,"getClosestPeers").map(i=>i.getClosestPeers(e,t))))n!=null&&(yield n)}};function Ol(r,e){return r.filter(t=>t[e]!=null)}var K2=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var z2=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ti)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Oq(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var q2=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Oq(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ti),this.cleanup())}async join(e={}){let t=new z2(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await dt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Xx(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var om=class extends De{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Xx(this.emitEmpty.bind(this),1),this.emitIdle=Xx(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new K2;let n=new q2(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ti)}),this.clear()}async onEmpty(e){this.size!==0&&await Kt(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Kt(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Kt(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=ar({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new ti("Queue aborted"))};this.addEventListener("success",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var j2="lock:worker:request-read",W2="lock:worker:abort-read-request",G2="lock:worker:release-read",X2="lock:master:grant-read",Y2="lock:master:error-read",Q2="lock:worker:request-write",Z2="lock:worker:abort-write-request",J2="lock:worker:release-write",ey="lock:master:grant-write",ty="lock:master:error-write",ry="lock:worker:finalize",ny="mortice",CI={singleProcess:!1};var Yx=(r,e,t,n,i,o,s,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===i&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:s,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===ry&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var TI=(r=10)=>Math.random().toString().substring(2,r+2);var iy=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(ny)}readLock(e){return this.sendRequest(j2,W2,X2,Y2,G2,e)}writeLock(e){return this.sendRequest(Q2,Z2,ey,ty,J2,e)}finalize(){this.channel.postMessage({type:ry,name:this.name}),this.channel.close()}async sendRequest(e,t,n,i,o,s){s?.signal?.throwIfAborted();let a=TI();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===i)){this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var II=r=>{if(r=Object.assign({},CI,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(ny),n=new De;return t.addEventListener("message",Yx(n,t,"requestReadLock","abortReadLockRequest",j2,W2,Y2,G2,X2)),t.addEventListener("message",Yx(n,t,"requestWriteLock","abortWriteLockRequest",Q2,Z2,ty,J2,ey)),n}return new iy(r.name)};var Nl=new Map,sm;function kI(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Nq(r){if(sm==null&&(sm=II(r),!kI(sm))){let e=sm;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=Nl.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=Nl.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,i=Nl.get(n);i?.finalize()})}return sm}async function Qx(r,e){let t,n,i=new Promise((s,a)=>{t=s,n=a}),o=()=>{n(new ti)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",o),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),i}var PI=(r,e)=>{let t=Nl.get(r);if(t!=null)return t;let n=Nq(e);if(kI(n))return t=n,Nl.set(r,t),t;let i=new om({concurrency:1}),o;return t={async readLock(s){if(o!=null)return Qx(o,s);o=new om({concurrency:e.concurrency,autoStart:!1});let a=o,c=Qx(o,s);return i.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(s){return o=null,Qx(i,s)},finalize:()=>{Nl.delete(r)},queue:i},Nl.set(r,t),e.autoFinalize===!0&&i.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Bq={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function am(r){let e=Object.assign({},Bq,r);return PI(e.name,e)}var oy=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=am({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Rr(this.child),this.started=!0}async stop(){await Zr(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new Error("CID was pinned");yield o}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Zx=new it("/version"),RI=1;async function DI(r){if(!await r.has(Zx)){await r.put(Zx,D(`${RI}`));return}let e=await r.get(Zx),t=z(e);if(parseInt(t,10)!==RI)throw new Error("Unknown datastore version, a datastore migration may be required")}var Qs={};$t(Qs,{code:()=>Mr,decode:()=>rs,decodeOptions:()=>Vq,encode:()=>cd,encodeOptions:()=>$q,name:()=>Kq,toByteView:()=>NI});var OI=42;function NI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Lq(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=G.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new Y(I.tag,OI),new Y(I.bytes,t)]}function Mq(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Uq(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function Fq(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Jx={float64:!0,typeEncoders:{Map:Fq,Object:Lq,undefined:Mq,number:Uq}},$q={...Jx,typeEncoders:{...Jx.typeEncoders}};function Hq(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return G.decode(r.subarray(1))}var sy={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};sy.tags[OI]=Hq;var Vq={...sy,tags:sy.tags.slice()},Kq="dag-cbor",Mr=113,cd=r=>Xs(r,Jx),rs=r=>En(NI(r),sy);var Bl={};$t(Bl,{code:()=>xo,decode:()=>ud,encode:()=>cy,format:()=>ej,name:()=>Jq,parse:()=>rj,stringify:()=>ej});var e9=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===I.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===I.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[I.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[I.negint.major](e,t){this[I.uint.major](e,t)}[I.bytes.major](e,t){throw new Error(`${Ws} unsupported type: Uint8Array`)}[I.string.major](e,t){this.prefix(e);let n=S2(JSON.stringify(t.value));e.push(n.length>32?Qp(n):n)}[I.array.major](e,t){this.prefix(e),this.inRecursive.push({type:I.array,elements:0}),e.push([91])}[I.map.major](e,t){this.prefix(e),this.inRecursive.push({type:I.map,elements:0}),e.push([123])}[I.tag.major](e,t){}[I.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===I.array)e.push([93]);else if(s.type===I.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Ws} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};function zq(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Ws} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==I.string||n.type!==I.string)throw new Error(`${Ws} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Ws} unexpected duplicate map keys, this is not supported`)}var qq={addBreakTokens:!0,mapSorter:zq};function cm(r,e){return e=Object.assign({},qq,e),Vx(r,new e9,e)}var ld=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${me} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${me} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,i=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new Y(I.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${me} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${me} unexpected token at position ${this._pos}`);n=!0,this._pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new Y(I.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new Y(s>=0?I.uint:I.negint,s,this._pos-e):new Y(s>=0?I.uint:I.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${me} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new Y(I.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${me} unexpected end of unicode escape sequence at position ${this._pos}`);let o=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${me} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${me} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(o&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(o&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let o=this.ch(),s;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${me} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${me} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new Y(I.string,Nx(t),this._pos-e);default:if(o<32)throw new Error(`${me} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}throw new Error(`${me} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new Y(I.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new Y(I.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new Y(I.null,null,4);case 102:return this.expect([102,97,108,115,101]),new Y(I.false,!1,5);case 116:return this.expect([116,114,117,101]),new Y(I.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${me} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${me} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${me} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${me} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${me} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function t9(r,e){return e=Object.assign({tokenizer:new ld(r,e)},e),En(r,e)}function Wq(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Gq(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=G.asCID(r);if(!e)return null;let t=e.toString();return[new Y(I.map,1/0,1),new Y(I.string,"/",1),new Y(I.string,t,t.length),new Y(I.break,void 0,1)]}function ay(r){let e=cr.encode(r).slice(1);return[new Y(I.map,1/0,1),new Y(I.string,"/",1),new Y(I.map,1/0,1),new Y(I.string,"bytes",5),new Y(I.string,e,e.length),new Y(I.break,void 0,1),new Y(I.break,void 0,1)]}function wo(r){return ay(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function Xq(r){return ay(new Uint8Array(r))}function Yq(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Qq(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Zq={typeEncoders:{Object:Gq,Buffer:ay,Uint8Array:ay,Int8Array:wo,Uint16Array:wo,Int16Array:wo,Uint32Array:wo,Int32Array:wo,Float32Array:wo,Float64Array:wo,Uint8ClampedArray:wo,BigInt64Array:wo,BigUint64Array:wo,DataView:wo,ArrayBuffer:Xq,undefined:Yq,number:Qq}},r9=class extends ld{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===I.map){let t=this._next();if(t.type===I.string&&t.value==="/"){let n=this._next();if(n.type===I.string){if(this._next().type!==I.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new Y(I.tag,42,0)}if(n.type===I.map){let i=this._next();if(i.type===I.string&&i.value==="bytes"){let o=this._next();if(o.type===I.string){for(let a=0;a<2;a++)if(this._next().type!==I.break)throw new Error("Invalid encoded Bytes form");let s=cr.decode(`m${o.value}`);return new Y(I.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},n9={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};n9.tags[42]=G.parse;var Jq="dag-json",xo=297,cy=r=>cm(r,Zq),ud=r=>{let e=Wq(r),t=Object.assign(n9,{tokenizer:new r9(e,n9)});return t9(e,t)},ej=r=>tj.decode(cy(r));var tj=new TextDecoder,rj=r=>ud(nj.encode(r)),nj=new TextEncoder;var ir={};$t(ir,{code:()=>tt,createLink:()=>zI,createNode:()=>KI,decode:()=>nr,encode:()=>Qe,name:()=>pj,prepare:()=>Wt,validate:()=>s9});var ij=new TextDecoder;function i9(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function ly(r,e){let t;[t,e]=i9(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function BI(r,e){let t;return[t,e]=i9(r,e),[t&7,t>>3,e]}function oj(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=BI(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=ly(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=ly(r,n),e.Name=ij.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=i9(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function LI(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=BI(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=ly(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=ly(r,t),n.push(oj(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var UI=new TextEncoder,MI=2**32,sj=2**31;function aj(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=lm(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=UI.encode(r.Name);t-=n.length,e.set(n,t),t=lm(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=lm(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function FI(r){let e=lj(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=lm(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=aj(r.Links[i],t.subarray(0,n));n-=o,n=lm(t,n,o)-1,t[n]=18}return t}function cj(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+fd(t)}if(typeof r.Name=="string"){let t=UI.encode(r.Name).length;e+=1+t+fd(t)}return typeof r.Tsize=="number"&&(e+=1+fd(r.Tsize)),e}function lj(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+fd(t)}if(r.Links)for(let t of r.Links){let n=cj(t);e+=1+n+fd(n)}return e}function lm(r,e,t){e-=fd(t);let n=e;for(;t>=sj;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function fd(r){return r%2===0&&r++,Math.floor((uj(r)+6)/7)}function uj(r){let e=0;return r>=MI&&(r=Math.floor(r/MI),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+fj[r]}var fj=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var dj=["Data","Links"],hj=["Hash","Name","Tsize"],o9=new TextEncoder;function HI(r,e){if(r===e)return 0;let t=r.Name?o9.encode(r.Name):[],n=e.Name?o9.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s<a;++s)if(t[s]!==n[s]){i=t[s],o=n[s];break}return i<o?-1:o<i?1:0}function $I(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function VI(r){if(typeof r.asCID=="object"){let t=G.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=G.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=G.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=G.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Wt(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=o9.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(VI),e.Links.sort(HI);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function s9(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!$I(r,dj))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!$I(t,hj))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&HI(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function KI(r,e=[]){return Wt({Data:r,Links:e})}function zI(r,e,t){return VI({Hash:t,Name:r,Tsize:e})}function qI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var pj="dag-pb",tt=112;function Qe(r){s9(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),FI(e)}function nr(r){let e=qI(r),t=LI(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=G.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}function dd(r){return r?.then!=null}function jI(r=[],e){let t={[tt]:ir,[At]:Rn,[Mr]:Qs,[xo]:Bl,[Go]:Tf};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);dd(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new H2(`Could not load codec for ${n}`)}}function WI(r=[],e){let t={[Be.code]:Be,[Bg.code]:Bg,[lr.code]:lr};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);dd(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new $2(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Ui=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Zs=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var uy=0,fy=class extends Zs{child;constructor(e){super(),this.child=e}put(e,t,n){return e.multihash.code===uy||this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}get(e,t){if(e.multihash.code===uy)return t?.signal?.throwIfAborted(),e.multihash.digest;if(this.child==null)throw t?.signal?.throwIfAborted(),new Ui;return this.child.get(e,t)}has(e,t){return e.multihash.code===uy?(t?.signal?.throwIfAborted(),!0):this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===uy){t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}getAll(e){return this.child!=null?this.child.getAll(e):(e?.signal?.throwIfAborted(),[])}};function mj(r){return r[Symbol.asyncIterator]!=null}function gj(r,e){let t=0;if(mj(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=_f(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield i);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield i);for(let c of n)a(c,t++)&&(yield c)})()}var di=gj;function yj(r){return r[Symbol.asyncIterator]!=null}function GI(r){return r?.then!=null}function wj(r,e){let t=0;if(yj(r))return(async function*(){for await(let c of r){let l=e(c,t++);GI(l)&&await l,yield c}})();let n=_f(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();if(typeof e(i,t++)?.then=="function")return(async function*(){yield i;for(let c of n){let l=e(c,t++);GI(l)&&await l,yield c}})();let a=e;return(function*(){yield i;for(let c of n)a(c,t++),yield c})()}var Ll=wj;var dy=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new fy(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new X("blocks:put:duplicate",e)),e):(n.onProgress?.(new X("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,t,n))),n.onProgress?.(new X("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=di(e,async({cid:o})=>{let s=await this.child.has(o,t);return s&&t.onProgress?.(new X("blocks:put-many:duplicate",o)),!s}),i=Ll(n,async({cid:o,block:s})=>{t.onProgress?.(new X("blocks:put-many:providers:notify",o)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(o,s,t)))});t.onProgress?.(new X("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new X("blocks:get:providers:get",e));let i=await XI(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new X("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new X("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,i,t))),i}return t.onProgress?.(new X("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new X("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Ll(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let i=await this.getHasher(n.multihash.code);t.onProgress?.(new X("blocks:get-many:providers:get",n));let o=await XI(n,this.components.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new X("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new X("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new X("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new X("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new X("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},hy=class extends dy{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await Rr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Zr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(i=>i.createSession==null?i:i.createSession(t));return new a9({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},a9=class extends dy{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let i=Pe([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:i})}finally{i.clear()}}async*putMany(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Pe([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function xj(r){return typeof r.retrieve=="function"}var bj=(r,e)=>{if(e==null)throw new K(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,i=e.digest(t);if(dd(i)?n=await i:n=i,!he(n.digest,r.multihash.digest))throw new Ua("Hash of downloaded block did not match multihash from passed CID")}};async function XI(r,e,t,n){let i=bj(r,t),o=new AbortController,s=Pe([o.signal,n.signal]);o.signal;let a=[];for(let c of e)xj(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await i(f),l=!0}});return l||await i(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{o.abort(),s.clear()}}var Ml=class extends De{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=on(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=cr.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i;let o=ve();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",e)}let s=!1,a=new Dr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{s=!0,o.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(s||t.signal?.aborted===!0){this.log.trace("session idle, found block");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c",e,u),o.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,u)});let l=()=>{o.reject(new Je(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await o.promise}finally{this.removeEventListener("provider",c),t.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let i=ve(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;o<t&&this.initialProviders.length>0;){let s=this.initialProviders.pop();if(s==null)break;let a=await this.convertToProvider(s,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<t)throw new F2(`Found ${o} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),i.reject(s)}),i.promise}};var py=class{libp2p;blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??Za(),this.log=this.logger.forComponent("helia"),this.getHasher=WI(e.hashers,e.loadHasher),this.getCodec=jI(e.codecs,e.loadCodec),this.dns=e.dns??Pl(),this.metrics=e.metrics,this.libp2p=e.libp2p;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new V2(t,{routers:(e.routers??[]).flatMap(i=>{let o=[i];return i[qo]!=null&&o.push(i[qo]),i[jo]!=null&&o.push(i[jo]),o}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new hy(t);this.pins=new U2(e.datastore,n,this.getCodec),this.blockstore=new oy(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(i=>i(t))}async start(){await DI(this.datastore),await Rr(this.blockstore,this.datastore,this.routing,this.libp2p)}async stop(){await Zr(this.blockstore,this.datastore,this.routing,this.libp2p)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();this.log("gc start"),await Jr(i.deleteMany((async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new X("helia:gc:deleted",o))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new X("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};var c9=class extends Ml{wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let i=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,i.has?"has":"does not have",e),i.has&&i.block!=null)return i.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}async convertToProvider(e,t){return Ti(e)?e:(await this.libp2p.dial(e,t)).remotePeer}};function YI(r,e){return new c9(r,e)}var my=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var l9=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function hr(r){let{name:e,metrics:t}=r,n;return t!=null?n=new l9({name:e,metrics:t}):n=new Map,n}function Ej(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=ao(r);e.push(t),r=r.slice(je(t))}return e}var QI=Ej;var gy=class extends De{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),this.peers=zs({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=hr({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(i=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,i)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(i=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,i)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=z(e.multihash.bytes,"base64"),i=this.wants.get(n);i==null&&(i={cid:e,priority:t.priority??1,wantType:t.wantType??tr.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,i)),i.wantType===tr.WantHave&&t.wantType===tr.WantBlock&&(i.wantType=tr.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===tr.WantBlock?(await Kt(this,"block",t?.signal,{filter:a=>he(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Kt(this,"presence",t?.signal,{filter:s=>he(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),i.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=ve(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,i=new qs;for(let[o,s]of this.wants.entries())t.has(o)||s.cancel||(n.add(o),i.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(i.wantlist.size!==0)try{await this.network.sendMessage(e,i);for(let o of n)t.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=z(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let i=new qs;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:tr.WantHave,priority:1}),await this.network.sendMessage(t,i),(await Kt(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&he(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:tr.WantBlock})}async wantSessionBlock(e,t,n={}){let i=new qs;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:tr.WantBlock,priority:1}),await this.network.sendMessage(t,i),(await Kt(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&he(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=z(e.multihash.bytes,"base64"),i=this.wants.get(n);i!=null&&(i.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let i of t.blocks){if(i.prefix==null||i.data==null)continue;let o=QI(i.prefix),s=o[0],a=o[1],c=o[2],l=c===Be.code?Be:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(i.data);u.then!=null&&(u=await u);let f=G.create(s===0?0:1,a,u);this.log("received block from %p for %c",e,f),this.safeDispatchEvent("block",{detail:{sender:e,cid:f,block:i.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:f,has:!0,block:i.data}});let d=z(f.multihash.bytes,"base64"),h=this.wants.get(d);h!=null&&(h.cancel=!0,n=!0)}for(let{cid:i,type:o}of t.blockPresences){let s=G.decode(i);this.log("received %s from %p for %c",o,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:o===Ri.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new qs(!0);for(let[i,o]of this.wants.entries())o.cancel||(t.add(i),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:tr.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(i){this.log.error("error sending full wantlist to new peer %p",e,i)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var yy=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new my(e),this.network=new Vg(e,t),this.peerWantLists=new g2({...e,network:this.network},t),this.wantList=new gy({...e,network:this.network},t)}createSession(e={}){return YI({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,i=Pe([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:i}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,o)});try{let o=await this.wantList.wantBlock(e,{...t,signal:i});return t.onProgress?.(new X("bitswap:want-block:received",{cid:e,sender:o.sender})),o.block}finally{n.abort(),i.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var ZI=(r,e={})=>new yy(r,e);var u9=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=ZI(e,{hashLoader:{getHasher:async i=>n(i)},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,i,o)=>{await this.bitswap.notify(n,i,o)},retrieve:async(n,i)=>t.retrieve(n,i)}}};function um(r={}){return e=>new u9(e,r)}var Ur=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Js=class extends Error{static name="ValidationError";name="ValidationError"},fm=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},wy=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var xy=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*i)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let i=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[i]=s[0],t[i+1]=s[1],t[i+2]=s[2],t[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];t[i]=o>>8,t[i+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var JI=45,Sj=15,hd=new xy;function by(r){if(!(r.length>Sj))return hd.new(r).parseWith(()=>hd.readIPv4Addr())}function vy(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>JI))return hd.new(r).parseWith(()=>hd.readIPv6Addr())}function pd(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>JI)return;let t=hd.new(r).parseWith(()=>hd.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function bo(r){return!!by(r)}function Ay(r){return!!vy(r)}function d9(r){return e=>z(e,r)}function h9(r){return e=>D(e,r)}function md(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ul(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function ek(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ul(n);return Xe([t,i],t.length+i.length)}function tk(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=jt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ul(n);return Xe([t,i],t.length+i.length)}function p9(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),i=md(t);return`${n}:${i}`}var m9=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let i=parseInt(t,10);if(isNaN(i)||i<0||i>255)throw new Ur("Invalid byte value in IP address");e[n]=i}),e},rk=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=bo(t[n]),s;o&&(s=m9(t[n]),t[n]=z(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,z(s.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Ur("Invalid byte value in IP address");i[e++]=o>>8&255,i[e++]=o&255}return i},nk=function(r){if(r.byteLength!==4)throw new Ur("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ik=function(r){if(r.byteLength!==16)throw new Ur("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let i=r[n],o=r[n+1],s=`${i.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ur(`Invalid IPv6 address "${t}"`)}};function ok(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ur(`Invalid IPv6 address "${r}"`)}}var f9=Object.values(fl).map(r=>r.decoder),_j=(function(){let r=f9[0].or(f9[1]);return f9.slice(2).forEach(e=>r=r.or(e)),r})();function sk(r){return _j.decode(r)}function ak(r){return e=>r.encoder.encode(e)}function Cj(r){if(parseInt(r).toString()!==r)throw new Js("Value must be an integer")}function Tj(r){if(r<0)throw new Js("Value must be a positive integer, or zero")}function Ij(r){return e=>{if(e>r)throw new Js(`Value must be smaller than or equal to ${r}`)}}function kj(...r){return e=>{for(let t of r)t(e)}}var dm=kj(Cj,Tj,Ij(65535));var Ir=-1,g9=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new wy(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},On=new g9,zj=[{code:4,name:"ip4",size:32,valueToBytes:m9,bytesToValue:nk,validate:r=>{if(!bo(r))throw new Js(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:273,name:"udp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:33,name:"dccp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:41,name:"ip6",size:128,valueToBytes:rk,bytesToValue:ik,stringToValue:ok,validate:r=>{if(!Ay(r))throw new Js(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Ir},{code:43,name:"ipcidr",size:8,bytesToValue:d9("base10"),valueToBytes:h9("base10")},{code:53,name:"dns",size:Ir,resolvable:!0},{code:54,name:"dns4",size:Ir,resolvable:!0},{code:55,name:"dns6",size:Ir,resolvable:!0},{code:56,name:"dnsaddr",size:Ir,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ir,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Ir,bytesToValue:d9("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?h9("base58btc")(r):G.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:p9,valueToBytes:ek},{code:445,name:"onion3",size:296,bytesToValue:p9,valueToBytes:tk},{code:446,name:"garlic64",size:Ir},{code:447,name:"garlic32",size:Ir},{code:448,name:"tls"},{code:449,name:"sni",size:Ir},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ir,bytesToValue:ak(cl),valueToBytes:sk},{code:480,name:"http"},{code:481,name:"http-path",size:Ir,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Ir}];zj.forEach(r=>{On.addProtocol(r)});function ck(r){let e=[],t=0;for(;t<r.length;){let n=ao(r,t),i=On.getProtocol(n),o=je(n),s=qj(i,r,t+o),a=0;s>0&&i.size===Ir&&(a=je(s));let c=o+a+s,l={code:n,name:i.name,bytes:r.subarray(t,t+c)};if(s>0){let u=t+o+a,f=r.subarray(u,u+s);l.value=i.bytesToValue?.(f)??z(f)}e.push(l),t+=c}return e}function lk(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let i=On.getProtocol(n.code),o=je(n.code),s,a=0,c=0;n.value!=null&&(s=i.valueToBytes?.(n.value)??D(n.value),a=s.byteLength,i.size===Ir&&(c=je(a)));let l=new Uint8Array(o+c+a),u=0;Ef(n.code,l,u),u+=o,s!=null&&(i.size===Ir&&(Ef(a,l,u),u+=c),l.set(s,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Xe(t,e)}function uk(r){if(r.charAt(0)!=="/")throw new Ur('String multiaddr must start with "/"');let e=[],t="protocol",n="",i="";for(let o=1;o<r.length;o++){let s=r.charAt(o);s!=="/"&&(t==="protocol"?i+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(s==="/"||a){let c=On.getProtocol(i);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",i="",t="protocol";continue}else if(a)throw new Ur(`Component ${i} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ur(`Component ${i} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",i="",t="protocol"}}}if(i!==""&&n!=="")throw new Ur("Incomplete multiaddr");return e}function fk(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=On.getProtocol(e.code);if(t==null)throw new Ur(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function qj(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ao(e,t)}var jj=Symbol.for("nodejs.util.inspect.custom"),C9=Symbol.for("@multiformats/multiaddr"),Wj=[53,54,55,56],_9=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function Gj(r){if(r==null&&(r="/"),rc(r))return r.getComponents();if(r instanceof Uint8Array)return ck(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),uk(r);if(Array.isArray(r))return r;throw new Ur("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Cy=class r{[C9]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Gj(e),t.validate!==!1&&Xj(this)}get bytes(){return this.#r==null&&(this.#r=lk(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=fk(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),Wj.includes(a)&&(t="tcp",i=443,n=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",i=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=On.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=On.getProtocol(e),i=[e];return t!=null&&i.push(n.valueToBytes?.(t)??D(t)),i})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new fm(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,i),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:i})=>{n===421&&e.push([n,i]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?z(Ye.decode(`z${n}`),"base58btc"):z(G.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(On.getProtocol(e.code).path)return e.value??null;return null}equals(e){return he(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=dk.get(t.name);if(n==null)throw new _9(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>oe(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[jj](){return`Multiaddr(${this.toString()})`}};function Xj(r){r.getComponents().forEach(e=>{let t=On.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function hk(r,e,t){let n=0;for(let i of r)if(!(n<e)){if(n>t)break;if(i!==255)return!1;n++}return!0}function pk(r,e,t,n){let i=0;for(let o of r)if(!(i<t)){if(i>n)break;if(o!==e[i])return!1;i++}return!0}function T9(r){switch(r.length){case $l:return r.join(".");case Hl:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function mk(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let i=t+1;i<r.length;i++)if(r[i]!=0)return-1;break}return e}function gk(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var $l=4,Hl=16,j0e=parseInt("0xFFFF",16),Yj=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function pm(r,e){e.length===Hl&&r.length===$l&&hk(e,0,11)&&(e=e.slice(12)),e.length===$l&&r.length===Hl&&pk(r,Yj,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=r[i]&e[i];return n}function yk(r,e){if(typeof e=="string"&&(e=pd(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function I9(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=$l,i=by(e);if(i==null&&(n=Hl,i=vy(e),i==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=k9(o,8*n);return{network:pm(i,s),mask:s}}function k9(r,e){if(e!==8*$l&&e!==8*Hl)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let i=0;i<t;i++){if(r>=8){n[i]=255,r-=8;continue}n[i]=255-(255>>r),r=0}return n}var Vl=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=I9(e));else{let n=pd(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n.length*8){let o=pd(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=k9(i,8*n.length);this.network=pm(n,this.mask)}}contains(e){return yk({network:this.network,mask:this.mask},e)}toString(){let e=mk(this.mask),t=e!==-1?String(e):gk(this.mask);return T9(this.network)+"/"+t}};function wk(r,e){return new Vl(r).contains(e)}function P9(r){let e,t;if(r.getComponents().forEach(n=>{(n.name==="ip4"||n.name==="ip6")&&(t=n.value),n.name==="ipcidr"&&(e=n.value)}),e==null||t==null)throw new Error("Invalid multiaddr");return new Vl(t,e)}var dk=new Map;function rc(r){return!!r?.[C9]}function oe(r){return new Cy(r)}function Hi(r){let e=On.getProtocol(r);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}var Qj=[6,53,56,54,55];function xk(r){return Ak("sni",r)?.value}function bk(r){let e=Ak("tcp",r)?.value;return e==null?"":`:${e}`}function Ak(r,e){return e.find(t=>t.name===r)}function vk(r){return r.some(({code:e})=>e===448)}function Ao(r,e){let t=Ek[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var Ek={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Ao(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Ao(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ao(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ao(t,e)}`},http:(r,e)=>{let t=vk(e),n=xk(e),i=bk(e);if(t&&n!=null)return`https://${n}${i}`;let o=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Ao(s,e);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ao(t,e),i=decodeURIComponent(r.value??"");return`${n}${i}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ao(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ao(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ao(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=vk(e),n=xk(e),i=bk(e);if(t&&n!=null)return`wss://${n}${i}`;let o=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Ao(s,e);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ao(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function wd(r,e){let n=oe(r).getComponents(),i=n.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let o=Ek[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let s=o(i,n)??"";return e?.assumeHttp!==!1&&Qj.includes(i.code)&&(s=s.replace(/^.*:\/\//,""),i.value==="443"?s=`https://${s}`:s=`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}var _k=mt(Sk(),1),Zj=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Jj=Zj.map(r=>new _k.Netmask(r));function R9(r){for(let e of Jj)if(e.contains(r))return!0;return!1}function eW(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function tW(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),i=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return R9(i)}function rW(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function nW(r){let e=r.split(":"),t=e[e.length-1];return R9(t)}function iW(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Sn(r){if(bo(r))return R9(r);if(eW(r))return tW(r);if(rW(r))return nW(r);if(Ay(r))return iW(r)}var yt=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Ie=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),rt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),cn=(...r)=>({match:e=>{let t;for(let n of r){let i=n.match(e);i!==!1&&(t==null||i.length<t.length)&&(t=i)}return t??!1}}),ot=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function pt(...r){function e(i){if(i==null)return!1;let o=i.getComponents();for(let s of r){let a=s.match(o);if(a===!1)return!1;o=a}return o}function t(i){return e(i)!==!1}function n(i){let o=e(i);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var oW=Ie(421),Ck=pt(oW),Iy=Ie(54),ky=Ie(55),Py=Ie(56),O9=Ie(53),Nge=pt(Iy,rt(Ie(421))),Bge=pt(ky,rt(Ie(421))),Lge=pt(Py,rt(Ie(421))),gm=pt(cn(O9,Py,Iy,ky),rt(Ie(421))),Tk=ot(Ie(4),rt(Ie(43))),Ik=ot(rt(Ie(42)),Ie(41),rt(Ie(43))),N9=cn(Tk,Ik),Kl=cn(N9,O9,Iy,ky,Py),kk=pt(cn(N9,ot(cn(O9,Py,Iy,ky),rt(Ie(421))))),B9=pt(Tk),L9=pt(Ik),Pk=pt(N9),M9=ot(Kl,Ie(6)),ym=ot(Kl,Ie(273)),zl=pt(ot(M9,rt(Ie(421)))),Mge=pt(ym),U9=ot(ym,yt(460),rt(Ie(421))),Ry=ot(ym,yt(461),rt(Ie(421))),sW=cn(U9,Ry),Uge=pt(U9),Rk=pt(Ry),D9=cn(Kl,M9,ym,U9,Ry),Dk=cn(ot(D9,yt(477),rt(Ie(421)))),na=pt(Dk),Ok=cn(ot(D9,yt(478),rt(Ie(421))),ot(D9,yt(448),rt(Ie(449)),yt(477),rt(Ie(421)))),ql=pt(Ok),Nk=ot(ym,yt(280),rt(Ie(466)),rt(Ie(466)),rt(Ie(421))),wm=pt(Nk),Bk=ot(Ry,yt(465),rt(Ie(466)),rt(Ie(466)),rt(Ie(421))),F9=pt(Bk),Ty=cn(Dk,Ok,ot(M9,rt(Ie(421))),ot(sW,rt(Ie(421))),ot(Kl,rt(Ie(421))),Nk,Bk,Ie(421)),Dy=pt(Ty),aW=ot(Ty,yt(290),Ie(421)),Nn=pt(aW),cW=cn(ot(Ty,yt(290),yt(281),rt(Ie(421))),ot(Ty,yt(281),rt(Ie(421))),ot(yt(281),rt(Ie(421)))),xm=pt(cW),lW=cn(ot(Kl,Ie(6),yt(480),rt(Ie(421))),ot(Kl,yt(480),rt(Ie(421)))),Lk=pt(lW),uW=ot(Kl,cn(ot(Ie(6,"443"),yt(480)),ot(Ie(6),yt(443)),ot(Ie(6),yt(448),yt(480)),ot(yt(448),yt(480)),yt(448),yt(443)),rt(Ie(421))),Mk=pt(uW),fW=cn(ot(Ie(777),rt(Ie(421)))),Fge=pt(fW),dW=cn(ot(Ie(400),rt(Ie(421)))),$ge=pt(dW);function $9(r,e,t){return r.filter(n=>{if(Mk.matches(n)||e&&Lk.matches(n))return t||gm.matches(n)?!0:Sn(n.toOptions().host)===!1;if(!e&&t){let{host:i}=n.toOptions();if(i==="127.0.0.1"||i==="localhost"||i.endsWith(".localhost"))return!0}return!1})}async function*Oy(r,e,t,n,i,o={}){for await(let s of e.findProviders(r,o)){let a=$9(s.multiaddrs,n,i);if(a.length===0)continue;let c=wd(a[0]);yield new xd(c,{logger:t,transformRequestInit:o.transformRequestInit})}}async function Uk(r,e,t){let{signal:n,log:i}=t??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>e)throw i?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(l=>{i?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let s=r.body?.getReader();if(s==null)throw new Error("Response body is not readable");let a=new pe;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await s.read();if(c)break;if(a.append(l),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{s.cancel().catch(c=>{i?.error("error cancelling reader - %e",c)}).finally(()=>{s.releaseLock()})}return a.subarray()}var xd=class{url;#e=0;#t=0;#r=0;#o=0;#c=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return cr.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=Fk}={}){let i=new URL(this.url.toString());if(i.pathname=`/ipfs/${e.toString()}`,i.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),s=new AbortController,a=()=>{s.abort()};t?.addEventListener("abort",a);try{let c=this.#c.get(o);if(c==null){this.#e++;let l={signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(i.toString(),u).then(async f=>{if(this.log("GET %s %d",i,f.status),!f.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);let d=await Uk(f,n,{signal:s.signal,log:this.log});return this.#o++,d}),this.#c.set(o,c)}return await c}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",a),this.#c.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#o/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#o,pendingResponses:this.#c.size}}};var H9=class extends Ml{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Ny,this.allowLocal=t.allowLocal??By,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let i=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(i),i}async*findNewProviders(e,t={}){yield*Oy(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t){if(Ti(e))return;let n=$9(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let i=wd(n[0]);return new xd(i,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function $k(r,e){return new H9(r,e)}var Ly=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Ny,this.allowLocal=t.allowLocal??By,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let i of Oy(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,i.url);try{let o=await i.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,i.url);try{await t.validateFn?.(o)}catch(s){this.log.error("failed to validate block for %c from %s",e,i.url,s);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s",e,i.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${i.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,i.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return $k({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Ny=!1,By=!1,Fk=2097152;function bm(r={}){return e=>new Ly(e,r)}async function*My(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var jk=mt(Uy(),1);var Fy=class extends Error{static name="SignatureCreationError";constructor(e="Record signature creation failed"){super(e),this.name="SignatureCreationError"}},Eo=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},$y=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},jl=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},Hy=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},vm=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},Vy=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Am=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var Fr;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),(function(i){i.codec=()=>St(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=be((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.value!=null&&(o.uint32(10),o.bytes(i.value)),i.signatureV1!=null&&(o.uint32(18),o.bytes(i.signatureV1)),i.validityType!=null&&(o.uint32(24),r.ValidityType.codec().encode(i.validityType,o)),i.validity!=null&&(o.uint32(34),o.bytes(i.validity)),i.sequence!=null&&(o.uint32(40),o.uint64(i.sequence)),i.ttl!=null&&(o.uint32(48),o.uint64(i.ttl)),i.pubKey!=null&&(o.uint32(58),o.bytes(i.pubKey)),i.signatureV2!=null&&(o.uint32(66),o.bytes(i.signatureV2)),i.data!=null&&(o.uint32(74),o.bytes(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o,s={})=>{let a={},c=o==null?i.len:i.pos+o;for(;i.pos<c;){let l=i.uint32();switch(l>>>3){case 1:{a.value=i.bytes();break}case 2:{a.signatureV1=i.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(i);break}case 4:{a.validity=i.bytes();break}case 5:{a.sequence=i.uint64();break}case 6:{a.ttl=i.uint64();break}case 7:{a.pubKey=i.bytes();break}case 8:{a.signatureV2=i.bytes();break}case 9:{a.data=i.bytes();break}default:{i.skipType(l&7);break}}}return a})),n),r.encode=i=>xe(i,r.codec()),r.decode=(i,o)=>we(i,r.codec(),o)})(Fr||(Fr={}));var hW=Ue("ipns:utils"),Hk=D("/ipns/"),pW=114,mW=0,gW=18;function Em(r){let e;if(r.pubKey!=null)try{e=rr(r.pubKey)}catch(t){throw hW.error(t),t}if(e!=null)return e}function Vk(r,e,t){let n=D(e);return Xe([r,t,n])}function zy(r){let e=D("ipns-signature:");return Xe([e,r])}function nc(r){return"signatureV1"in r?Fr.encode({value:D(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:D(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Fr.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function Bn(r){let e=Fr.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new Eo("Missing data or signatureV2");let t=zk(e.data),n=yW(t.Value),i=z(t.Validity);if(e.value!=null&&e.signatureV1!=null)return wW(e),{value:n,validityType:Fr.ValidityType.EOL,validity:i,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Fr.ValidityType.EOL,validity:i,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function ia(r){return Xe([Hk,r.bytes])}function bd(r){let e=We(r.slice(Hk.length));if(!Ky(e,mW)&&!Ky(e,gW))throw new Ua("Multihash in IPNS key was not identity or sha2-256");return e}function Kk(r,e,t,n,i){let o;if(e===Fr.ValidityType.EOL)o=0;else throw new jl("The validity type is unsupported");return Xs({Value:r,Validity:t,ValidityType:o,Sequence:n,TTL:i})}function zk(r){let e=En(r);if(e.ValidityType===0)e.ValidityType=Fr.ValidityType.EOL;else throw new jl("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function yW(r){let e=z(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${G.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${G.parse(e).toV1().toString()}`}catch{}throw new vm("Value must be a valid content path starting with /")}function qk(r){if(r!=null){let e=vW(r);if(e!=null)return e.code===pW?`/ipns/${e.toString(mn)}`:`/ipfs/${e.toV1().toString()}`;if(xW(r))return`/ipns/${mn.encode(r.bytes)}`;let t=r.toString().trim();if(t.startsWith("/")&&t.length>1)return t}throw new vm("Value must be a valid content path starting with /")}function wW(r){if(r.data==null)throw new Vy("Record data is missing");let e=zk(r.data);if(!he(e.Value,r.value??new Uint8Array(0)))throw new Eo('Field "value" did not match between protobuf and CBOR');if(!he(e.Validity,r.validity??new Uint8Array(0)))throw new Eo('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new Eo('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new Eo('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new Eo('Field "ttl" did not match between protobuf and CBOR')}function xW(r){return r.bytes instanceof Uint8Array}function bW(r){return typeof r?.toCID=="function"}function vW(r){if(bW(r))return r.toCID();try{return G.parse(r)}catch{}return G.asCID(r)}function Ky(r,e){return r.code===e}var AW=Ue("ipns"),Wk=300*1e9,EW="/ipns/",U2e=EW.length,Gk={v1Compatible:!0,ttlNs:Wk};async function Xk(r,e,t,n,i=Gk){let o=new jk.default(Date.now()+Number(n)),s=Fr.ValidityType.EOL,a=BigInt(i.ttlNs??Wk);return SW(r,e,t,s,o.toString(),a,i)}var SW=async(r,e,t,n,i,o,s=Gk)=>{t=BigInt(t);let a=D(i),c=qk(e),l=D(c),u=Kk(l,n,a,t,o),f=zy(u),d=await r.sign(f),h;if(r.type==="RSA"&&(h=ur(r.publicKey)),s.v1Compatible===!0){let m=await _W(r,l,n,a),g={value:c,signatureV1:m,validity:i,validityType:n,sequence:t,ttl:o,signatureV2:d,data:u};return h!=null&&(g.pubKey=h),g}else{let m={value:c,validity:i,validityType:n,sequence:t,ttl:o,signatureV2:d,data:u};return h!=null&&(m.pubKey=h),m}},_W=async(r,e,t,n)=>{try{let i=Vk(e,t,n);return await r.sign(i)}catch(i){throw AW.error("record signature creation failed",i),new Fy("Record signature creation failed")}};var Yk=mt(Uy(),1);var qy=Ue("ipns:validator"),CW=1024*10;async function TW(r,e){let t=Bn(e),n;try{let i=zy(t.data);n=await r.verify(i,t.signatureV2)}catch{n=!1}if(!n)throw qy.error("record signature verification failed"),new Eo("Record signature verification failed");if(t.validityType===Fr.ValidityType.EOL){if(Yk.default.fromString(t.validity).toDate().getTime()<Date.now())throw qy.error("record has expired"),new $y("record has expired")}else if(t.validityType!=null)throw qy.error("the validity type is unsupported"),new jl("The validity type is unsupported");qy("ipns record for %s is valid",t.value)}async function ic(r,e){if(e.byteLength>CW)throw new Hy("The record is too large");let t=bd(r),n;Ky(t,0)&&(n=l2(t));let i=Bn(e),o=Em(i)??n;if(o==null)throw new Am("Could not extract public key from IPNS record or routing key");let s=ia(o.toMultihash());if(!he(s,r))throw new Am("Embedded public key did not match routing key");await TW(o,e)}var jy=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Sm(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),i="";for await(let o of r){if(typeof o=="string"&&(o=new TextEncoder().encode(o)),ki(o)&&(o=o.subarray()),i+=n.decode(o,{stream:!0}),i.length>(e?.maxMessageLength??i.length))throw new jy("Incoming message too long");let s=i.split(t);i=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}i+=n.decode(),i!==""&&(yield JSON.parse(i))}var vd=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},So=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function IW(r){return r[Symbol.asyncIterator]!=null}function kW(r){if(IW(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Ad=kW;var Qk=D("/ipns/");function Zk(r){return he(r.subarray(0,Qk.byteLength),Qk)}var Wy=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*zt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Zk(e))return;let i=bd(e),o=G.createV1(114,i),s=Bn(t);await this.client.putIPNS(o,s,n)}async get(e,t){if(!Zk(e))throw new qe("Not found");let n=bd(e),i=G.createV1(114,n);try{let o=await this.client.getIPNS(i,t);return nc(o)}catch(o){throw o.name==="BadResponseError"?new qe("Not found"):o}}},Gy=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await Ad(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new qe("Not found")}async*getClosestPeers(e,t={}){}};var $r=Ue("delegated-routing-v1-http-api-client"),Xy={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Yy=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new mo({concurrency:t.concurrentRequests??Xy.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Xy.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new Wy(this),this.peerRouting=new Gy(this),this.cacheName=t.cacheName??Xy.cacheName,this.cacheTTL=t.cacheTTL??Xy.cacheTTL}get[qo](){return this.contentRouting}get[jo](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&$r("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){$r("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),i=Pe([this.shutDownController.signal,n,t.signal]);let o=ve(),s=ve();this.httpQueue.add(async()=>(o.resolve(),s.promise));try{await o.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:i},l=await this.#r(a.toString(),c);if(l==null)throw new So("No response received");if(!l.ok)throw l.status===404?new qe("No matching records found"):l.status===422?new vd("Request does not conform to schema or semantic constraints"):new So(`Unexpected status code: ${l.status}`);if(l.body==null)throw new So("Routing response had no body");let u=l.headers.get("Content-Type");if(u==null)throw new So("No Content-Type header received");if(u?.startsWith("application/json")){let f=await l.json();for(let d of f.Providers){let h=this.#e(d);h!=null&&(yield h)}}else if(u.includes("application/x-ndjson"))for await(let f of Sm(My(l.body))){let d=this.#e(f);d!=null&&(yield d)}else throw new So(`Unsupported Content-Type: ${u}`)}finally{i.clear(),s.resolve(),$r("getProviders finished: %c",e)}}async*getPeers(e,t={}){$r("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),i=Pe([this.shutDownController.signal,n,t.signal]);let o=ve(),s=ve();this.httpQueue.add(async()=>(o.resolve(),s.promise));try{await o.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:i},l=await this.#r(a.toString(),c);if(l.status===404)throw new qe("No matching records found");if(l.status===422)throw new vd("Request does not conform to schema or semantic constraints");if(l.body==null)throw new So("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Peers){let h=this.#e(d);h!=null&&(yield h)}}else for await(let f of Sm(My(l.body))){let d=this.#e(f);d!=null&&(yield d)}}catch(a){$r.error("getPeers errored:",a)}finally{i.clear(),s.resolve(),$r("getPeers finished: %c",e)}}async getIPNS(e,t={}){$r("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),i=Pe([this.shutDownController.signal,n,t.signal]);let o=ve(),s=ve();this.httpQueue.add(async()=>(o.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await o.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:i},l=await this.#r(a,c);if($r("getIPNS GET %s %d",a,l.status),l.status===404)throw new qe("No matching records found");if(l.status===422)throw new vd("Request does not conform to schema or semantic constraints");if(l.body==null)throw new So("GET ipns response had no body");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await ic(ia(e.multihash),f),Bn(f)}catch(c){throw $r.error("getIPNS GET %s error:",a,c),c}finally{i.clear(),s.resolve(),$r("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){$r("putIPNS starts: %c",e);let i=AbortSignal.timeout(this.timeout),o=Pe([this.shutDownController.signal,i,n.signal]);let s=ve(),a=ve();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let l=nc(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:o},f=await this.#r(c,u);if($r("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new So("PUT ipns response had status other than 200")}catch(l){throw $r.error("putIPNS PUT %s error:",c,l.stack),l}finally{o.clear(),a.resolve(),$r("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(oe)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:gt(e.ID),Addrs:n,Protocols:t}}catch(t){$r.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let i=t?.join(",")??this.filterAddrs?.join(",")??"";i!==""&&e.searchParams.set("filter-addrs",i)}if(n!=null||this.filterProtocols!=null){let i=n?.join(",")??this.filterProtocols?.join(",")??"";i!==""&&e.searchParams.set("filter-protocols",i)}}async#r(e,t){let n=t.method??"GET",i=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return $r("returning cached response for %s",i),c;await this.cache?.delete(e)}}let o=this.inFlightRequests.get(i);if(o!=null){let c=await o;return $r("deduplicating outgoing request for %s",i),c.clone()}let s=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let f=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,f)}return c}).finally(()=>{this.inFlightRequests.delete(i)});return this.inFlightRequests.set(i,s),await s}};function Qy(r,e={}){return new Yy(new URL(r),e)}function K9(){return{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var Jk="[a-fA-F\\d:]",oc=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Jk})|(?<=${Jk})(?=\\s|$))`:"",_o="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",mr="[a-fA-F\\d]{1,4}",Zy=`
|
|
3
|
+
`,R:"%H:%M",T:"%H:%M:%S",t:" ",X:"%T",Z:"GMT",z:"+0000"};return g;function g(R,_,$){var V=this;if(!(V instanceof g))return new g(R,_,$);V.time=+R||0,V.nano=+_||0,V.year=+$||0,w(V)}function w(R){var _,$,V,H=R.year,E=R.time,T=R.nano,C=((T<0||a<=T)&&(T-=($=Math.floor(T/a))*a,E+=$,$=1),H%e);return(E<-o||o<E||C)&&((_=l(E/i))&&(H+=_*e,E-=_*i),(V=x(E)).setUTCFullYear(C+V.getUTCFullYear()),V=(E=+V)+(_=l((H-=C)/e))*i,_&&-o<=V&&V<=o&&(H-=_*e,E=V),$=1),$&&(R.year=H,R.time=E,R.nano=T),R}function x(R){var _=new Date(0);return _.setTime(R),_}function v(H,V){H=+H||0;var $=l((V=(V|0)*s)/n)+l(H/n),V=V%n+H%n,H=l(V/n);return H&&($+=H,V-=H*n),new g(1e3*V,0,$*e)}function A(R,_,$,V,H,E){return function(C,O){var Q=w(this);C=C||new Array(8),M(C,O|=0);var U=Math.floor(Q.time/1e3),Q=Q.year*(t*r/e),j=l(Q/s)+l(U/s),Q=Q%s+U%s,U=Math.floor(Q/s);return U&&(j+=U,Q-=U*s),T(C,O+H,j),T(C,O+E,Q),C};function T(C,O,j){C[O+R]=j>>24&255,C[O+_]=j>>16&255,C[O+$]=j>>8&255,C[O+V]=255&j}}function S(R,_,$,V,H,E){return function(C,O){M(C,O|=0);var j=T(C,O+H);return v(T(C,O+E),j)};function T(C,O){return 16777216*C[O+R]+(C[O+_]<<16|C[O+$]<<8|C[O+V])}}function M(R,_){if(R=R&&R.length,R==null)throw new TypeError("Invalid Buffer");if(R<_+8)throw new RangeError("Out of range")}function F(R){return(9<R?"":"0")+(0|R)}function N(R,_){return(c+(0|R)).substr(-_)}})()});var KP=wt((H8e,VP)=>{function Ki(r,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(r)),this._timeouts=r,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}VP.exports=Ki;Ki.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};Ki.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};Ki.prototype.retry=function(r){if(this._timeout&&clearTimeout(this._timeout),!r)return!1;var e=new Date().getTime();if(r&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(r),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(r);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var n=this;return this._timer=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},t),this._options.unref&&this._timer.unref(),!0};Ki.prototype.attempt=function(r,e){this._fn=r,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};Ki.prototype.try=function(r){console.log("Using RetryOperation.try() is deprecated"),this.attempt(r)};Ki.prototype.start=function(r){console.log("Using RetryOperation.start() is deprecated"),this.attempt(r)};Ki.prototype.start=Ki.prototype.try;Ki.prototype.errors=function(){return this._errors};Ki.prototype.attempts=function(){return this._attempts};Ki.prototype.mainError=function(){if(this._errors.length===0)return null;for(var r={},e=null,t=0,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,s=(r[o]||0)+1;r[o]=s,s>=t&&(e=i,t=s)}return e}});var zP=wt(Ql=>{var UG=KP();Ql.operation=function(r){var e=Ql.timeouts(r);return new UG(e,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})};Ql.timeouts=function(r){if(r instanceof Array)return[].concat(r);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in r)e[t]=r[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<e.retries;i++)n.push(this.createTimeout(i,e));return r&&r.forever&&!n.length&&n.push(this.createTimeout(i,e)),n.sort(function(o,s){return o-s}),n};Ql.createTimeout=function(r,e){var t=e.randomize?Math.random()+1:1,n=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,r));return n=Math.min(n,e.maxTimeout),n};Ql.wrap=function(r,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var n in r)typeof r[n]=="function"&&t.push(n)}for(var i=0;i<t.length;i++){var o=t[i],s=r[o];r[o]=function(c){var l=Ql.operation(e),u=Array.prototype.slice.call(arguments,1),f=u.pop();u.push(function(d){l.retry(d)||(d&&(arguments[0]=l.mainError()),f.apply(this,arguments))}),l.attempt(function(){c.apply(r,u)})}.bind(r,s),r[o].options=e}}});var jP=wt((K8e,qP)=>{qP.exports=zP()});var oR=wt((bxe,iR)=>{"use strict";function aX(r){return r>=55296&&r<=56319}function cX(r){return r>=56320&&r<=57343}iR.exports=function(e,t,n){if(typeof t!="string")throw new Error("Input must be string");for(var i=t.length,o=0,s,a,c=0;c<i;c+=1){if(s=t.charCodeAt(c),a=t[c],aX(s)&&cX(t.charCodeAt(c+1))&&(c+=1,a+=t[c]),o+=e(a),o===n)return t.slice(0,c+1);if(o>n)return t.slice(0,c-a.length+1)}return t}});var aR=wt((vxe,sR)=>{"use strict";function lX(r){return r>=55296&&r<=56319}function uX(r){return r>=56320&&r<=57343}sR.exports=function(e){if(typeof e!="string")throw new Error("Input must be string");for(var t=e.length,n=0,i=null,o=null,s=0;s<t;s++)i=e.charCodeAt(s),uX(i)?o!=null&&lX(o)?n+=1:n+=3:i<=127?n+=1:i>=128&&i<=2047?n+=2:i>=2048&&i<=65535&&(n+=3),o=i;return n}});var lR=wt((Axe,cR)=>{"use strict";var fX=oR(),dX=aR();cR.exports=fX.bind(null,dX)});var dR=wt((Exe,fR)=>{"use strict";var hX=lR(),pX=/[\/\?<>\\:\*\|"]/g,mX=/[\x00-\x1f\x80-\x9f]/g,gX=/^\.+$/,yX=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,wX=/[\. ]+$/;function uR(r,e){if(typeof r!="string")throw new Error("Input must be string");var t=r.replace(pX,e).replace(mX,e).replace(gX,e).replace(yX,e).replace(wX,e);return hX(t,255)}fR.exports=function(r,e){var t=e&&e.replacement||"",n=uR(r,t);return t===""?n:uR(n,"")}});var la=wt(Od=>{"use strict";var bX="[object ArrayBuffer]",ca=class r{static isArrayBuffer(e){return Object.prototype.toString.call(e)===bX}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||e.byteOffset===0&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,t){let n=r.toUint8Array(e),i=r.toUint8Array(t);if(n.length!==i.byteLength)return!1;for(let o=0;o<n.length;o++)if(n[o]!==i[o])return!1;return!0}static concat(...e){let t;Array.isArray(e[0])&&!(e[1]instanceof Function)||Array.isArray(e[0])&&e[1]instanceof Function?t=e[0]:e[e.length-1]instanceof Function?t=e.slice(0,e.length-1):t=e;let n=0;for(let s of t)n+=s.byteLength;let i=new Uint8Array(n),o=0;for(let s of t){let a=this.toUint8Array(s);i.set(a,o),o+=a.length}return e[e.length-1]instanceof Function?this.toView(i,e[e.length-1]):i.buffer}},Tb="string",vX=/^[0-9a-f\s]+$/i,AX=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,EX=/^[a-zA-Z0-9-_]+$/,Y3=class{static fromString(e){let t=unescape(encodeURIComponent(e)),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);return n.buffer}static toString(e){let t=ca.toUint8Array(e),n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return decodeURIComponent(escape(n))}},zi=class{static toString(e,t=!1){let n=ca.toArrayBuffer(e),i=new DataView(n),o="";for(let s=0;s<n.byteLength;s+=2){let a=i.getUint16(s,t);o+=String.fromCharCode(a)}return o}static fromString(e,t=!1){let n=new ArrayBuffer(e.length*2),i=new DataView(n);for(let o=0;o<e.length;o++)i.setUint16(o*2,e.charCodeAt(o),t);return n}},Q3=class r{static isHex(e){return typeof e===Tb&&vX.test(e)}static isBase64(e){return typeof e===Tb&&AX.test(e)}static isBase64Url(e){return typeof e===Tb&&EX.test(e)}static ToString(e,t="utf8"){let n=ca.toUint8Array(e);switch(t.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 zi.toString(n,!0);case"utf16":case"utf16be":return zi.toString(n);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromString(e,t="utf8"){if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return zi.fromString(e,!0);case"utf16":case"utf16be":return zi.fromString(e);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToBase64(e){let t=ca.toUint8Array(e);if(typeof btoa<"u"){let n=this.ToString(t,"binary");return btoa(n)}else return Buffer.from(t).toString("base64")}static FromBase64(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return typeof atob<"u"?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.FromBinary(e);case"utf8":return Y3.fromString(e);case"utf16":case"utf16be":return zi.fromString(e);case"utf16le":case"usc2":return zi.fromString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static ToUtf8String(e,t=r.DEFAULT_UTF8_ENCODING){switch(t){case"ascii":return this.ToBinary(e);case"utf8":return Y3.toString(e);case"utf16":case"utf16be":return zi.toString(e);case"utf16le":case"usc2":return zi.toString(e,!0);default:throw new Error(`Unknown type of encoding '${t}'`)}}static FromBinary(e){let t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return n.buffer}static ToBinary(e){let t=ca.toUint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return n}static ToHex(e){let t=ca.toUint8Array(e),n="",i=t.length;for(let o=0;o<i;o++){let s=t[o];s<16&&(n+="0"),n+=s.toString(16)}return n}static FromHex(e){let t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!r.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t=`0${t}`);let n=new Uint8Array(t.length/2);for(let i=0;i<t.length;i=i+2){let o=t.slice(i,i+2);n[i/2]=parseInt(o,16)}return n.buffer}static ToUtf16String(e,t=!1){return zi.toString(e,t)}static FromUtf16String(e,t=!1){return zi.fromString(e,t)}static Base64Padding(e){let t=4-e.length%4;if(t<4)for(let n=0;n<t;n++)e+="=";return e}static formatString(e){return e?.replace(/[\n\r\t ]/g,"")||""}};Q3.DEFAULT_UTF8_ENCODING="utf8";function SX(r,...e){let t=arguments[0];for(let n=1;n<arguments.length;n++){let i=arguments[n];for(let o in i)t[o]=i[o]}return t}function _X(...r){let e=r.map(i=>i.byteLength).reduce((i,o)=>i+o),t=new Uint8Array(e),n=0;return r.map(i=>new Uint8Array(i)).forEach(i=>{for(let o of i)t[n++]=o}),t.buffer}function CX(r,e){if(!(r&&e)||r.byteLength!==e.byteLength)return!1;let t=new Uint8Array(r),n=new Uint8Array(e);for(let i=0;i<r.byteLength;i++)if(t[i]!==n[i])return!1;return!0}Od.BufferSourceConverter=ca;Od.Convert=Q3;Od.assign=SX;Od.combine=_X;Od.isEqual=CX});var $N=wt(()=>{var FN;(function(r){(function(e){var t=typeof globalThis=="object"||typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:a(),n=i(r);typeof t.Reflect<"u"&&(n=i(t.Reflect,n)),e(n,t),typeof t.Reflect>"u"&&(t.Reflect=r);function i(c,l){return function(u,f){Object.defineProperty(c,u,{configurable:!0,writable:!0,value:f}),l&&l(u,f)}}function o(){try{return Function("return this;")()}catch{}}function s(){try{return(0,eval)("(function() { return this; })()")}catch{}}function a(){return o()||s()}})(function(e,t){var n=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",o=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",s=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",a=typeof Object.create=="function",c={__proto__:[]}instanceof Array,l=!a&&!c,u={create:a?function(){return Rw(Object.create(null))}:c?function(){return Rw({__proto__:null})}:function(){return Rw({})},has:l?function(k,B){return n.call(k,B)}:function(k,B){return B in k},get:l?function(k,B){return n.call(k,B)?k[B]:void 0}:function(k,B){return k[B]}},f=Object.getPrototypeOf(Function),d=typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:W$(),h=typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:G$(),m=typeof WeakMap=="function"?WeakMap:X$(),g=i?Symbol.for("@reflect-metadata:registry"):void 0,w=z$(),x=q$(w);function v(k,B,W,re){if(q(W)){if(!Ci(k))throw new TypeError;if(!io(B))throw new TypeError;return H(k,B)}else{if(!Ci(k))throw new TypeError;if(!se(B))throw new TypeError;if(!se(re)&&!q(re)&&!Te(re))throw new TypeError;return Te(re)&&(re=void 0),W=st(W),E(k,B,W,re)}}e("decorate",v);function A(k,B){function W(re,Ee){if(!se(re))throw new TypeError;if(!q(Ee)&&!ug(Ee))throw new TypeError;Q(k,B,re,Ee)}return W}e("metadata",A);function S(k,B,W,re){if(!se(W))throw new TypeError;return q(re)||(re=st(re)),Q(k,B,W,re)}e("defineMetadata",S);function M(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),T(k,B,W)}e("hasMetadata",M);function F(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),C(k,B,W)}e("hasOwnMetadata",F);function N(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),O(k,B,W)}e("getMetadata",N);function R(k,B,W){if(!se(B))throw new TypeError;return q(W)||(W=st(W)),j(k,B,W)}e("getOwnMetadata",R);function _(k,B){if(!se(k))throw new TypeError;return q(B)||(B=st(B)),U(k,B)}e("getMetadataKeys",_);function $(k,B){if(!se(k))throw new TypeError;return q(B)||(B=st(B)),Z(k,B)}e("getOwnMetadataKeys",$);function V(k,B,W){if(!se(B))throw new TypeError;if(q(W)||(W=st(W)),!se(B))throw new TypeError;q(W)||(W=st(W));var re=ap(B,W,!1);return q(re)?!1:re.OrdinaryDeleteMetadata(k,B,W)}e("deleteMetadata",V);function H(k,B){for(var W=k.length-1;W>=0;--W){var re=k[W],Ee=re(B);if(!q(Ee)&&!Te(Ee)){if(!io(Ee))throw new TypeError;B=Ee}}return B}function E(k,B,W,re){for(var Ee=k.length-1;Ee>=0;--Ee){var Jt=k[Ee],br=Jt(B,W,re);if(!q(br)&&!Te(br)){if(!se(br))throw new TypeError;re=br}}return re}function T(k,B,W){var re=C(k,B,W);if(re)return!0;var Ee=Pw(B);return Te(Ee)?!1:T(k,Ee,W)}function C(k,B,W){var re=ap(B,W,!1);return q(re)?!1:ft(re.OrdinaryHasOwnMetadata(k,B,W))}function O(k,B,W){var re=C(k,B,W);if(re)return j(k,B,W);var Ee=Pw(B);if(!Te(Ee))return O(k,Ee,W)}function j(k,B,W){var re=ap(B,W,!1);if(!q(re))return re.OrdinaryGetOwnMetadata(k,B,W)}function Q(k,B,W,re){var Ee=ap(W,re,!0);Ee.OrdinaryDefineOwnMetadata(k,B,W,re)}function U(k,B){var W=Z(k,B),re=Pw(k);if(re===null)return W;var Ee=U(re,B);if(Ee.length<=0)return W;if(W.length<=0)return Ee;for(var Jt=new h,br=[],Ve=0,ae=W;Ve<ae.length;Ve++){var ue=ae[Ve],de=Jt.has(ue);de||(Jt.add(ue),br.push(ue))}for(var ge=0,ze=Ee;ge<ze.length;ge++){var ue=ze[ge],de=Jt.has(ue);de||(Jt.add(ue),br.push(ue))}return br}function Z(k,B){var W=ap(k,B,!1);return W?W.OrdinaryOwnMetadataKeys(k,B):[]}function te(k){if(k===null)return 1;switch(typeof k){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return k===null?1:6;default:return 6}}function q(k){return k===void 0}function Te(k){return k===null}function Ne(k){return typeof k=="symbol"}function se(k){return typeof k=="object"?k!==null:typeof k=="function"}function Le(k,B){switch(te(k)){case 0:return k;case 1:return k;case 2:return k;case 3:return k;case 4:return k;case 5:return k}var W=B===3?"string":B===5?"number":"default",re=TS(k,o);if(re!==void 0){var Ee=re.call(k,W);if(se(Ee))throw new TypeError;return Ee}return Ke(k,W==="default"?"number":W)}function Ke(k,B){if(B==="string"){var W=k.toString;if(hn(W)){var re=W.call(k);if(!se(re))return re}var Ee=k.valueOf;if(hn(Ee)){var re=Ee.call(k);if(!se(re))return re}}else{var Ee=k.valueOf;if(hn(Ee)){var re=Ee.call(k);if(!se(re))return re}var Jt=k.toString;if(hn(Jt)){var re=Jt.call(k);if(!se(re))return re}}throw new TypeError}function ft(k){return!!k}function He(k){return""+k}function st(k){var B=Le(k,3);return Ne(B)?B:He(B)}function Ci(k){return Array.isArray?Array.isArray(k):k instanceof Object?k instanceof Array:Object.prototype.toString.call(k)==="[object Array]"}function hn(k){return typeof k=="function"}function io(k){return typeof k=="function"}function ug(k){switch(te(k)){case 3:return!0;case 4:return!0;default:return!1}}function xf(k,B){return k===B||k!==k&&B!==B}function TS(k,B){var W=k[B];if(W!=null){if(!hn(W))throw new TypeError;return W}}function IS(k){var B=TS(k,s);if(!hn(B))throw new TypeError;var W=B.call(k);if(!se(W))throw new TypeError;return W}function kS(k){return k.value}function PS(k){var B=k.next();return B.done?!1:B}function RS(k){var B=k.return;B&&B.call(k)}function Pw(k){var B=Object.getPrototypeOf(k);if(typeof k!="function"||k===f||B!==f)return B;var W=k.prototype,re=W&&Object.getPrototypeOf(W);if(re==null||re===Object.prototype)return B;var Ee=re.constructor;return typeof Ee!="function"||Ee===k?B:Ee}function K$(){var k;!q(g)&&typeof t.Reflect<"u"&&!(g in t.Reflect)&&typeof t.Reflect.defineMetadata=="function"&&(k=j$(t.Reflect));var B,W,re,Ee=new m,Jt={registerProvider:br,getProvider:ae,setProvider:de};return Jt;function br(ge){if(!Object.isExtensible(Jt))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case k===ge:break;case q(B):B=ge;break;case B===ge:break;case q(W):W=ge;break;case W===ge:break;default:re===void 0&&(re=new h),re.add(ge);break}}function Ve(ge,ze){if(!q(B)){if(B.isProviderFor(ge,ze))return B;if(!q(W)){if(W.isProviderFor(ge,ze))return B;if(!q(re))for(var Pt=IS(re);;){var er=PS(Pt);if(!er)return;var oo=kS(er);if(oo.isProviderFor(ge,ze))return RS(Pt),oo}}}if(!q(k)&&k.isProviderFor(ge,ze))return k}function ae(ge,ze){var Pt=Ee.get(ge),er;return q(Pt)||(er=Pt.get(ze)),q(er)&&(er=Ve(ge,ze),q(er)||(q(Pt)&&(Pt=new d,Ee.set(ge,Pt)),Pt.set(ze,er))),er}function ue(ge){if(q(ge))throw new TypeError;return B===ge||W===ge||!q(re)&&re.has(ge)}function de(ge,ze,Pt){if(!ue(Pt))throw new Error("Metadata provider not registered.");var er=ae(ge,ze);if(er!==Pt){if(!q(er))return!1;var oo=Ee.get(ge);q(oo)&&(oo=new d,Ee.set(ge,oo)),oo.set(ze,Pt)}return!0}}function z$(){var k;return!q(g)&&se(t.Reflect)&&Object.isExtensible(t.Reflect)&&(k=t.Reflect[g]),q(k)&&(k=K$()),!q(g)&&se(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,g,{enumerable:!1,configurable:!1,writable:!1,value:k}),k}function q$(k){var B=new m,W={isProviderFor:function(ue,de){var ge=B.get(ue);return q(ge)?!1:ge.has(de)},OrdinaryDefineOwnMetadata:br,OrdinaryHasOwnMetadata:Ee,OrdinaryGetOwnMetadata:Jt,OrdinaryOwnMetadataKeys:Ve,OrdinaryDeleteMetadata:ae};return w.registerProvider(W),W;function re(ue,de,ge){var ze=B.get(ue),Pt=!1;if(q(ze)){if(!ge)return;ze=new d,B.set(ue,ze),Pt=!0}var er=ze.get(de);if(q(er)){if(!ge)return;if(er=new d,ze.set(de,er),!k.setProvider(ue,de,W))throw ze.delete(de),Pt&&B.delete(ue),new Error("Wrong provider for target.")}return er}function Ee(ue,de,ge){var ze=re(de,ge,!1);return q(ze)?!1:ft(ze.has(ue))}function Jt(ue,de,ge){var ze=re(de,ge,!1);if(!q(ze))return ze.get(ue)}function br(ue,de,ge,ze){var Pt=re(ge,ze,!0);Pt.set(ue,de)}function Ve(ue,de){var ge=[],ze=re(ue,de,!1);if(q(ze))return ge;for(var Pt=ze.keys(),er=IS(Pt),oo=0;;){var DS=PS(er);if(!DS)return ge.length=oo,ge;var Y$=kS(DS);try{ge[oo]=Y$}catch(Q$){try{RS(er)}finally{throw Q$}}oo++}}function ae(ue,de,ge){var ze=re(de,ge,!1);if(q(ze)||!ze.delete(ue))return!1;if(ze.size===0){var Pt=B.get(de);q(Pt)||(Pt.delete(ge),Pt.size===0&&B.delete(Pt))}return!0}}function j$(k){var B=k.defineMetadata,W=k.hasOwnMetadata,re=k.getOwnMetadata,Ee=k.getOwnMetadataKeys,Jt=k.deleteMetadata,br=new m,Ve={isProviderFor:function(ae,ue){var de=br.get(ae);return!q(de)&&de.has(ue)?!0:Ee(ae,ue).length?(q(de)&&(de=new h,br.set(ae,de)),de.add(ue),!0):!1},OrdinaryDefineOwnMetadata:B,OrdinaryHasOwnMetadata:W,OrdinaryGetOwnMetadata:re,OrdinaryOwnMetadataKeys:Ee,OrdinaryDeleteMetadata:Jt};return Ve}function ap(k,B,W){var re=w.getProvider(k,B);if(!q(re))return re;if(W){if(w.setProvider(k,B,x))return x;throw new Error("Illegal state.")}}function W$(){var k={},B=[],W=(function(){function Ve(ae,ue,de){this._index=0,this._keys=ae,this._values=ue,this._selector=de}return Ve.prototype["@@iterator"]=function(){return this},Ve.prototype[s]=function(){return this},Ve.prototype.next=function(){var ae=this._index;if(ae>=0&&ae<this._keys.length){var ue=this._selector(this._keys[ae],this._values[ae]);return ae+1>=this._keys.length?(this._index=-1,this._keys=B,this._values=B):this._index++,{value:ue,done:!1}}return{value:void 0,done:!0}},Ve.prototype.throw=function(ae){throw this._index>=0&&(this._index=-1,this._keys=B,this._values=B),ae},Ve.prototype.return=function(ae){return this._index>=0&&(this._index=-1,this._keys=B,this._values=B),{value:ae,done:!0}},Ve})(),re=(function(){function Ve(){this._keys=[],this._values=[],this._cacheKey=k,this._cacheIndex=-2}return Object.defineProperty(Ve.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Ve.prototype.has=function(ae){return this._find(ae,!1)>=0},Ve.prototype.get=function(ae){var ue=this._find(ae,!1);return ue>=0?this._values[ue]:void 0},Ve.prototype.set=function(ae,ue){var de=this._find(ae,!0);return this._values[de]=ue,this},Ve.prototype.delete=function(ae){var ue=this._find(ae,!1);if(ue>=0){for(var de=this._keys.length,ge=ue+1;ge<de;ge++)this._keys[ge-1]=this._keys[ge],this._values[ge-1]=this._values[ge];return this._keys.length--,this._values.length--,xf(ae,this._cacheKey)&&(this._cacheKey=k,this._cacheIndex=-2),!0}return!1},Ve.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=k,this._cacheIndex=-2},Ve.prototype.keys=function(){return new W(this._keys,this._values,Ee)},Ve.prototype.values=function(){return new W(this._keys,this._values,Jt)},Ve.prototype.entries=function(){return new W(this._keys,this._values,br)},Ve.prototype["@@iterator"]=function(){return this.entries()},Ve.prototype[s]=function(){return this.entries()},Ve.prototype._find=function(ae,ue){if(!xf(this._cacheKey,ae)){this._cacheIndex=-1;for(var de=0;de<this._keys.length;de++)if(xf(this._keys[de],ae)){this._cacheIndex=de;break}}return this._cacheIndex<0&&ue&&(this._cacheIndex=this._keys.length,this._keys.push(ae),this._values.push(void 0)),this._cacheIndex},Ve})();return re;function Ee(Ve,ae){return Ve}function Jt(Ve,ae){return ae}function br(Ve,ae){return[Ve,ae]}}function G$(){var k=(function(){function B(){this._map=new d}return Object.defineProperty(B.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),B.prototype.has=function(W){return this._map.has(W)},B.prototype.add=function(W){return this._map.set(W,W),this},B.prototype.delete=function(W){return this._map.delete(W)},B.prototype.clear=function(){this._map.clear()},B.prototype.keys=function(){return this._map.keys()},B.prototype.values=function(){return this._map.keys()},B.prototype.entries=function(){return this._map.entries()},B.prototype["@@iterator"]=function(){return this.keys()},B.prototype[s]=function(){return this.keys()},B})();return k}function X$(){var k=16,B=u.create(),W=re();return(function(){function ae(){this._key=re()}return ae.prototype.has=function(ue){var de=Ee(ue,!1);return de!==void 0?u.has(de,this._key):!1},ae.prototype.get=function(ue){var de=Ee(ue,!1);return de!==void 0?u.get(de,this._key):void 0},ae.prototype.set=function(ue,de){var ge=Ee(ue,!0);return ge[this._key]=de,this},ae.prototype.delete=function(ue){var de=Ee(ue,!1);return de!==void 0?delete de[this._key]:!1},ae.prototype.clear=function(){this._key=re()},ae})();function re(){var ae;do ae="@@WeakMap@@"+Ve();while(u.has(B,ae));return B[ae]=!0,ae}function Ee(ae,ue){if(!n.call(ae,W)){if(!ue)return;Object.defineProperty(ae,W,{value:u.create()})}return ae[W]}function Jt(ae,ue){for(var de=0;de<ue;++de)ae[de]=Math.random()*255|0;return ae}function br(ae){if(typeof Uint8Array=="function"){var ue=new Uint8Array(ae);return typeof crypto<"u"?crypto.getRandomValues(ue):typeof msCrypto<"u"?msCrypto.getRandomValues(ue):Jt(ue,ae),ue}return Jt(new Array(ae),ae)}function Ve(){var ae=br(k);ae[6]=ae[6]&79|64,ae[8]=ae[8]&191|128;for(var ue="",de=0;de<k;++de){var ge=ae[de];(de===4||de===6||de===8)&&(ue+="-"),ge<16&&(ue+="0"),ue+=ge.toString(16).toLowerCase()}return ue}}function Rw(k){return k.__=void 0,delete k.__,k}})})(FN||(FN={}))});var XB=wt((IKe,I5)=>{var kB,PB,RB,DB,OB,NB,BB,LB,MB,T5,zA,UB,FB,Th,$B,HB,VB,KB,zB,qB,jB,WB,GB;(function(r){var e=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof this=="object"?this:{};typeof define=="function"&&define.amd?define("tslib",["exports"],function(n){r(t(e,t(n)))}):typeof I5=="object"&&typeof I5.exports=="object"?r(t(e,t(I5.exports))):r(t(e));function t(n,i){return n!==e&&(typeof Object.create=="function"?Object.defineProperty(n,"__esModule",{value:!0}):n.__esModule=!0),function(o,s){return n[o]=i?i(o,s):s}}})(function(r){var e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)n.hasOwnProperty(i)&&(t[i]=n[i])};kB=function(t,n){e(t,n);function i(){this.constructor=t}t.prototype=n===null?Object.create(n):(i.prototype=n.prototype,new i)},PB=Object.assign||function(t){for(var n,i=1,o=arguments.length;i<o;i++){n=arguments[i];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},RB=function(t,n){var i={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&n.indexOf(o)<0&&(i[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,o=Object.getOwnPropertySymbols(t);s<o.length;s++)n.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(t,o[s])&&(i[o[s]]=t[o[s]]);return i},DB=function(t,n,i,o){var s=arguments.length,a=s<3?n:o===null?o=Object.getOwnPropertyDescriptor(n,i):o,c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")a=Reflect.decorate(t,n,i,o);else for(var l=t.length-1;l>=0;l--)(c=t[l])&&(a=(s<3?c(a):s>3?c(n,i,a):c(n,i))||a);return s>3&&a&&Object.defineProperty(n,i,a),a},OB=function(t,n){return function(i,o){n(i,o,t)}},NB=function(t,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,n)},BB=function(t,n,i,o){function s(a){return a instanceof i?a:new i(function(c){c(a)})}return new(i||(i=Promise))(function(a,c){function l(d){try{f(o.next(d))}catch(h){c(h)}}function u(d){try{f(o.throw(d))}catch(h){c(h)}}function f(d){d.done?a(d.value):s(d.value).then(l,u)}f((o=o.apply(t,n||[])).next())})},LB=function(t,n){var i={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},o,s,a,c;return c={next:l(0),throw:l(1),return:l(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function l(f){return function(d){return u([f,d])}}function u(f){if(o)throw new TypeError("Generator is already executing.");for(;i;)try{if(o=1,s&&(a=f[0]&2?s.return:f[0]?s.throw||((a=s.return)&&a.call(s),0):s.next)&&!(a=a.call(s,f[1])).done)return a;switch(s=0,a&&(f=[f[0]&2,a.value]),f[0]){case 0:case 1:a=f;break;case 4:return i.label++,{value:f[1],done:!1};case 5:i.label++,s=f[1],f=[0];continue;case 7:f=i.ops.pop(),i.trys.pop();continue;default:if(a=i.trys,!(a=a.length>0&&a[a.length-1])&&(f[0]===6||f[0]===2)){i=0;continue}if(f[0]===3&&(!a||f[1]>a[0]&&f[1]<a[3])){i.label=f[1];break}if(f[0]===6&&i.label<a[1]){i.label=a[1],a=f;break}if(a&&i.label<a[2]){i.label=a[2],i.ops.push(f);break}a[2]&&i.ops.pop(),i.trys.pop();continue}f=n.call(t,i)}catch(d){f=[6,d],s=0}finally{o=a=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}},GB=function(t,n,i,o){o===void 0&&(o=i),t[o]=n[i]},MB=function(t,n){for(var i in t)i!=="default"&&!n.hasOwnProperty(i)&&(n[i]=t[i])},T5=function(t){var n=typeof Symbol=="function"&&Symbol.iterator,i=n&&t[n],o=0;if(i)return i.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&o>=t.length&&(t=void 0),{value:t&&t[o++],done:!t}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")},zA=function(t,n){var i=typeof Symbol=="function"&&t[Symbol.iterator];if(!i)return t;var o=i.call(t),s,a=[],c;try{for(;(n===void 0||n-- >0)&&!(s=o.next()).done;)a.push(s.value)}catch(l){c={error:l}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(c)throw c.error}}return a},UB=function(){for(var t=[],n=0;n<arguments.length;n++)t=t.concat(zA(arguments[n]));return t},FB=function(){for(var t=0,n=0,i=arguments.length;n<i;n++)t+=arguments[n].length;for(var o=Array(t),s=0,n=0;n<i;n++)for(var a=arguments[n],c=0,l=a.length;c<l;c++,s++)o[s]=a[c];return o},Th=function(t){return this instanceof Th?(this.v=t,this):new Th(t)},$B=function(t,n,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=i.apply(t,n||[]),s,a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(m){o[m]&&(s[m]=function(g){return new Promise(function(w,x){a.push([m,g,w,x])>1||l(m,g)})})}function l(m,g){try{u(o[m](g))}catch(w){h(a[0][3],w)}}function u(m){m.value instanceof Th?Promise.resolve(m.value.v).then(f,d):h(a[0][2],m)}function f(m){l("next",m)}function d(m){l("throw",m)}function h(m,g){m(g),a.shift(),a.length&&l(a[0][0],a[0][1])}},HB=function(t){var n,i;return n={},o("next"),o("throw",function(s){throw s}),o("return"),n[Symbol.iterator]=function(){return this},n;function o(s,a){n[s]=t[s]?function(c){return(i=!i)?{value:Th(t[s](c)),done:s==="return"}:a?a(c):c}:a}},VB=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t[Symbol.asyncIterator],i;return n?n.call(t):(t=typeof T5=="function"?T5(t):t[Symbol.iterator](),i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i);function o(a){i[a]=t[a]&&function(c){return new Promise(function(l,u){c=t[a](c),s(l,u,c.done,c.value)})}}function s(a,c,l,u){Promise.resolve(u).then(function(f){a({value:f,done:l})},c)}},KB=function(t,n){return Object.defineProperty?Object.defineProperty(t,"raw",{value:n}):t.raw=n,t},zB=function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var i in t)Object.hasOwnProperty.call(t,i)&&(n[i]=t[i]);return n.default=t,n},qB=function(t){return t&&t.__esModule?t:{default:t}},jB=function(t,n){if(!n.has(t))throw new TypeError("attempted to get private field on non-instance");return n.get(t)},WB=function(t,n,i){if(!n.has(t))throw new TypeError("attempted to set private field on non-instance");return n.set(t,i),i},r("__extends",kB),r("__assign",PB),r("__rest",RB),r("__decorate",DB),r("__param",OB),r("__metadata",NB),r("__awaiter",BB),r("__generator",LB),r("__exportStar",MB),r("__createBinding",GB),r("__values",T5),r("__read",zA),r("__spread",UB),r("__spreadArrays",FB),r("__await",Th),r("__asyncGenerator",$B),r("__asyncDelegator",HB),r("__asyncValues",VB),r("__makeTemplateObject",KB),r("__importStar",zB),r("__importDefault",qB),r("__classPrivateFieldGet",jB),r("__classPrivateFieldSet",WB)})});var TM=wt(s8=>{"use strict";Object.defineProperty(s8,"__esModule",{value:!0});var NE=class{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(this.isStopped)return;let t={value:e,done:!1};if(this.pullQueue.length){let n=this.pullQueue.shift();n&&n.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),this.highWaterMark!==void 0&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console&&console.warn(`EventIterator queue reached ${this.pushQueue.length} items`))}stop(){if(!this.isStopped){this.isStopped=!0,this.remove();for(let e of this.pullQueue)e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(let t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{let t=Promise.reject(e);t.catch(()=>{}),this.pushQueue.push(t)}}remove(){Promise.resolve().then(()=>{this.removeCallback&&this.removeCallback()})}[Symbol.asyncIterator](){return{next:e=>{let t=this.pushQueue.shift();return t?(this.lowWaterMark!==void 0&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise((n,i)=>{this.pullQueue.push({resolve:n,reject:i})})},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}},o8=class{constructor(e,{highWaterMark:t=100,lowWaterMark:n=1}={}){let i=new NE;i.highWaterMark=t,i.lowWaterMark=n,i.removeCallback=e({push:o=>i.push(o),stop:()=>i.stop(),fail:o=>i.fail(o),on:(o,s)=>{i.eventHandlers[o]=s}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}};s8.EventIterator=o8;s8.default=o8});var IM=wt(N0=>{"use strict";Object.defineProperty(N0,"__esModule",{value:!0});var BE=TM();N0.EventIterator=BE.EventIterator;function wJ(r,e,t){return new BE.EventIterator(({push:n})=>(this.addEventListener(r,n,e),()=>this.removeEventListener(r,n,e)),t)}N0.subscribe=wJ;N0.default=BE.EventIterator});var cU=wt((vZe,aU)=>{aU.exports=zE;var sU=128,kJ=127,PJ=~kJ,RJ=Math.pow(2,31);function zE(r,e,t){if(Number.MAX_SAFE_INTEGER&&r>Number.MAX_SAFE_INTEGER)throw zE.bytes=0,new RangeError("Could not encode varint");e=e||[],t=t||0;for(var n=t;r>=RJ;)e[t++]=r&255|sU,r/=128;for(;r&PJ;)e[t++]=r&255|sU,r>>>=7;return e[t]=r|0,zE.bytes=t-n+1,e}});var fU=wt((AZe,uU)=>{uU.exports=qE;var DJ=128,lU=127;function qE(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a||i>49)throw qE.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&lU)<<i:(s&lU)*Math.pow(2,i),i+=7}while(s>=DJ);return qE.bytes=o-n,t}});var hU=wt((EZe,dU)=>{var OJ=Math.pow(2,7),NJ=Math.pow(2,14),BJ=Math.pow(2,21),LJ=Math.pow(2,28),MJ=Math.pow(2,35),UJ=Math.pow(2,42),FJ=Math.pow(2,49),$J=Math.pow(2,56),HJ=Math.pow(2,63);dU.exports=function(r){return r<OJ?1:r<NJ?2:r<BJ?3:r<LJ?4:r<MJ?5:r<UJ?6:r<FJ?7:r<$J?8:r<HJ?9:10}});var S8=wt((SZe,pU)=>{pU.exports={encode:cU(),decode:fU(),encodingLength:hU()}});var OU=wt((q0,H8)=>{(function(r,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function n(h){if(!Array.isArray(h)&&!ArrayBuffer.isView(h))return!1;for(var m=0;m<h.length;m++)if(!Number.isInteger(h[m])||h[m]<0||h[m]>255)return!1;return!0}function i(h,m){return(h&65535)*m+(((h>>>16)*m&65535)<<16)}function o(h,m){return h<<m|h>>>32-m}function s(h){return h^=h>>>16,h=i(h,2246822507),h^=h>>>13,h=i(h,3266489909),h^=h>>>16,h}function a(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var g=[0,0,0,0];return g[3]+=h[3]+m[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=h[2]+m[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=h[1]+m[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=h[0]+m[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function c(h,m){h=[h[0]>>>16,h[0]&65535,h[1]>>>16,h[1]&65535],m=[m[0]>>>16,m[0]&65535,m[1]>>>16,m[1]&65535];var g=[0,0,0,0];return g[3]+=h[3]*m[3],g[2]+=g[3]>>>16,g[3]&=65535,g[2]+=h[2]*m[3],g[1]+=g[2]>>>16,g[2]&=65535,g[2]+=h[3]*m[2],g[1]+=g[2]>>>16,g[2]&=65535,g[1]+=h[1]*m[3],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=h[2]*m[2],g[0]+=g[1]>>>16,g[1]&=65535,g[1]+=h[3]*m[1],g[0]+=g[1]>>>16,g[1]&=65535,g[0]+=h[0]*m[3]+h[1]*m[2]+h[2]*m[1]+h[3]*m[0],g[0]&=65535,[g[0]<<16|g[1],g[2]<<16|g[3]]}function l(h,m){return m%=64,m===32?[h[1],h[0]]:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m|h[0]>>>32-m]:(m-=32,[h[1]<<m|h[0]>>>32-m,h[0]<<m|h[1]>>>32-m])}function u(h,m){return m%=64,m===0?h:m<32?[h[0]<<m|h[1]>>>32-m,h[1]<<m]:[h[1]<<m-32,0]}function f(h,m){return[h[0]^m[0],h[1]^m[1]]}function d(h){return h=f(h,[0,h[0]>>>1]),h=c(h,[4283543511,3981806797]),h=f(h,[0,h[0]>>>1]),h=c(h,[3301882366,444984403]),h=f(h,[0,h[0]>>>1]),h}t.x86.hash32=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var g=h.length%4,w=h.length-g,x=m,v=0,A=3432918353,S=461845907,M=0;M<w;M=M+4)v=h[M]|h[M+1]<<8|h[M+2]<<16|h[M+3]<<24,v=i(v,A),v=o(v,15),v=i(v,S),x^=v,x=o(x,13),x=i(x,5)+3864292196;switch(v=0,g){case 3:v^=h[M+2]<<16;case 2:v^=h[M+1]<<8;case 1:v^=h[M],v=i(v,A),v=o(v,15),v=i(v,S),x^=v}return x^=h.length,x=s(x),x>>>0},t.x86.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var g=h.length%16,w=h.length-g,x=m,v=m,A=m,S=m,M=0,F=0,N=0,R=0,_=597399067,$=2869860233,V=951274213,H=2716044179,E=0;E<w;E=E+16)M=h[E]|h[E+1]<<8|h[E+2]<<16|h[E+3]<<24,F=h[E+4]|h[E+5]<<8|h[E+6]<<16|h[E+7]<<24,N=h[E+8]|h[E+9]<<8|h[E+10]<<16|h[E+11]<<24,R=h[E+12]|h[E+13]<<8|h[E+14]<<16|h[E+15]<<24,M=i(M,_),M=o(M,15),M=i(M,$),x^=M,x=o(x,19),x+=v,x=i(x,5)+1444728091,F=i(F,$),F=o(F,16),F=i(F,V),v^=F,v=o(v,17),v+=A,v=i(v,5)+197830471,N=i(N,V),N=o(N,17),N=i(N,H),A^=N,A=o(A,15),A+=S,A=i(A,5)+2530024501,R=i(R,H),R=o(R,18),R=i(R,_),S^=R,S=o(S,13),S+=x,S=i(S,5)+850148119;switch(M=0,F=0,N=0,R=0,g){case 15:R^=h[E+14]<<16;case 14:R^=h[E+13]<<8;case 13:R^=h[E+12],R=i(R,H),R=o(R,18),R=i(R,_),S^=R;case 12:N^=h[E+11]<<24;case 11:N^=h[E+10]<<16;case 10:N^=h[E+9]<<8;case 9:N^=h[E+8],N=i(N,V),N=o(N,17),N=i(N,H),A^=N;case 8:F^=h[E+7]<<24;case 7:F^=h[E+6]<<16;case 6:F^=h[E+5]<<8;case 5:F^=h[E+4],F=i(F,$),F=o(F,16),F=i(F,V),v^=F;case 4:M^=h[E+3]<<24;case 3:M^=h[E+2]<<16;case 2:M^=h[E+1]<<8;case 1:M^=h[E],M=i(M,_),M=o(M,15),M=i(M,$),x^=M}return x^=h.length,v^=h.length,A^=h.length,S^=h.length,x+=v,x+=A,x+=S,v+=x,A+=x,S+=x,x=s(x),v=s(v),A=s(A),S=s(S),x+=v,x+=A,x+=S,v+=x,A+=x,S+=x,("00000000"+(x>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)+("00000000"+(A>>>0).toString(16)).slice(-8)+("00000000"+(S>>>0).toString(16)).slice(-8)},t.x64.hash128=function(h,m){if(t.inputValidation&&!n(h))return e;m=m||0;for(var g=h.length%16,w=h.length-g,x=[0,m],v=[0,m],A=[0,0],S=[0,0],M=[2277735313,289559509],F=[1291169091,658871167],N=0;N<w;N=N+16)A=[h[N+4]|h[N+5]<<8|h[N+6]<<16|h[N+7]<<24,h[N]|h[N+1]<<8|h[N+2]<<16|h[N+3]<<24],S=[h[N+12]|h[N+13]<<8|h[N+14]<<16|h[N+15]<<24,h[N+8]|h[N+9]<<8|h[N+10]<<16|h[N+11]<<24],A=c(A,M),A=l(A,31),A=c(A,F),x=f(x,A),x=l(x,27),x=a(x,v),x=a(c(x,[0,5]),[0,1390208809]),S=c(S,F),S=l(S,33),S=c(S,M),v=f(v,S),v=l(v,31),v=a(v,x),v=a(c(v,[0,5]),[0,944331445]);switch(A=[0,0],S=[0,0],g){case 15:S=f(S,u([0,h[N+14]],48));case 14:S=f(S,u([0,h[N+13]],40));case 13:S=f(S,u([0,h[N+12]],32));case 12:S=f(S,u([0,h[N+11]],24));case 11:S=f(S,u([0,h[N+10]],16));case 10:S=f(S,u([0,h[N+9]],8));case 9:S=f(S,[0,h[N+8]]),S=c(S,F),S=l(S,33),S=c(S,M),v=f(v,S);case 8:A=f(A,u([0,h[N+7]],56));case 7:A=f(A,u([0,h[N+6]],48));case 6:A=f(A,u([0,h[N+5]],40));case 5:A=f(A,u([0,h[N+4]],32));case 4:A=f(A,u([0,h[N+3]],24));case 3:A=f(A,u([0,h[N+2]],16));case 2:A=f(A,u([0,h[N+1]],8));case 1:A=f(A,[0,h[N]]),A=c(A,M),A=l(A,31),A=c(A,F),x=f(x,A)}return x=f(x,[0,h.length]),v=f(v,[0,h.length]),x=a(x,v),v=a(v,x),x=d(x),v=d(v),x=a(x,v),v=a(v,x),("00000000"+(x[0]>>>0).toString(16)).slice(-8)+("00000000"+(x[1]>>>0).toString(16)).slice(-8)+("00000000"+(v[0]>>>0).toString(16)).slice(-8)+("00000000"+(v[1]>>>0).toString(16)).slice(-8)},typeof q0<"u"?(typeof H8<"u"&&H8.exports&&(q0=H8.exports=t),q0.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=r.murmurHash3,t.noConflict=function(){return r.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},r.murmurHash3=t)})(q0)});var BU=wt((Bet,NU)=>{NU.exports=OU()});var K8=wt((Vet,MU)=>{"use strict";MU.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let i=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):i=!0,this._setInternalPos(n,e,t,i),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,i=t;for(;n<this.length;){let o=this.get(n);i=e(i,o,n),n++}return i}find(e){let t=0,n,i;for(;t<this.length&&!n;)i=this.get(t),n=e(i),t++;return n?i:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let i=this._bitArrays[n],o=e-n*7;if(!((i&1<<o)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(fee,0),c=~(4294967295<<o+1),l=LU(i&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),i=n+1;for(;!t&&this._bitArrays.length<i;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,i){let o=this._data,s=[t,n];if(i)this._sortData(),o[e]=s;else{if(o.length)if(o[o.length-1][0]>=t)o.push(s);else if(o[0][0]<=t)o.unshift(s);else{let a=Math.round(o.length/2);this._data=o.slice(0,a).concat(s).concat(o.slice(a))}else this._data.push(s);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(dee),this._changedData=!1}bitField(){let e=[],t=8,n=0,i=0,o,s=this._bitArrays.slice();for(;s.length||n;){n===0&&(o=s.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),u=o&l;i|=u<<8-t,o=o>>>c,n-=c,t-=c,(!t||!n&&!s.length)&&(e.push(i),i=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(hee)}};function fee(r,e){return r+LU(e)}function LU(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function dee(r,e){return r[0]-e[0]}function hee(r){return r[1]}});var LF=wt(aS=>{aS.read=function(r,e,t,n,i){var o,s,a=i*8-n-1,c=(1<<a)-1,l=c>>1,u=-7,f=t?i-1:0,d=t?-1:1,h=r[e+f];for(f+=d,o=h&(1<<-u)-1,h>>=-u,u+=a;u>0;o=o*256+r[e+f],f+=d,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=s*256+r[e+f],f+=d,u-=8);if(o===0)o=1-l;else{if(o===c)return s?NaN:(h?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-l}return(h?-1:1)*s*Math.pow(2,o-n)};aS.write=function(r,e,t,n,i,o){var s,a,c,l=o*8-i-1,u=(1<<l)-1,f=u>>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:o-1,m=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-s))<1&&(s--,c*=2),s+f>=1?e+=d/c:e+=d*Math.pow(2,1-f),e*c>=2&&(s++,c/=2),s+f>=u?(a=0,s=u):s+f>=1?(a=(e*c-1)*Math.pow(2,i),s=s+f):(a=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;r[t+h]=a&255,h+=m,a/=256,i-=8);for(s=s<<i|a,l+=i;l>0;r[t+h]=s&255,h+=m,s/=256,l-=8);r[t+h-m]|=g*128}});var e$=wt((cat,JF)=>{var ip=1e3,op=ip*60,sp=op*60,yf=sp*24,ure=yf*7,fre=yf*365.25;JF.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return dre(r);if(t==="number"&&isFinite(r))return e.long?pre(r):hre(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function dre(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*fre;case"weeks":case"week":case"w":return t*ure;case"days":case"day":case"d":return t*yf;case"hours":case"hour":case"hrs":case"hr":case"h":return t*sp;case"minutes":case"minute":case"mins":case"min":case"m":return t*op;case"seconds":case"second":case"secs":case"sec":case"s":return t*ip;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function hre(r){var e=Math.abs(r);return e>=yf?Math.round(r/yf)+"d":e>=sp?Math.round(r/sp)+"h":e>=op?Math.round(r/op)+"m":e>=ip?Math.round(r/ip)+"s":r+"ms"}function pre(r){var e=Math.abs(r);return e>=yf?dw(r,e,yf,"day"):e>=sp?dw(r,e,sp,"hour"):e>=op?dw(r,e,op,"minute"):e>=ip?dw(r,e,ip,"second"):r+" ms"}function dw(r,e,t,n){var i=e>=t*1.5;return Math.round(r/t)+" "+n+(i?"s":"")}});var r$=wt((lat,t$)=>{function mre(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=i,t.enabled=a,t.humanize=e$(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,h,m;function g(...w){if(!g.enabled)return;let x=g,v=Number(new Date),A=v-(f||v);x.diff=A,x.prev=f,x.curr=v,f=v,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let S=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(F,N)=>{if(F==="%%")return"%";S++;let R=t.formatters[N];if(typeof R=="function"){let _=w[S];F=R.call(x,_),w.splice(S,1),S--}return F}),t.formatArgs.call(x,w),(x.log||t.log).apply(x,w)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:w=>{d=w}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function i(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of f)d[0]==="-"?t.skips.push(d.slice(1)):t.names.push(d)}function o(u,f){let d=0,h=0,m=-1,g=0;for(;d<u.length;)if(h<f.length&&(f[h]===u[d]||f[h]==="*"))f[h]==="*"?(m=h,g=d,h++):(d++,h++);else if(m!==-1)h=m+1,g++,d=g;else return!1;for(;h<f.length&&f[h]==="*";)h++;return h===f.length}function s(){let u=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),u}function a(u){for(let f of t.skips)if(o(u,f))return!1;for(let f of t.names)if(o(u,f))return!0;return!1}function c(u){return u instanceof Error?u.stack||u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}t$.exports=mre});var n$=wt((Zn,hw)=>{Zn.formatArgs=yre;Zn.save=wre;Zn.load=xre;Zn.useColors=gre;Zn.storage=bre();Zn.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Zn.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function gre(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function yre(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+hw.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}Zn.log=console.debug||console.log||(()=>{});function wre(r){try{r?Zn.storage.setItem("debug",r):Zn.storage.removeItem("debug")}catch{}}function xre(){let r;try{r=Zn.storage.getItem("debug")||Zn.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function bre(){try{return localStorage}catch{}}hw.exports=r$()(Zn);var{formatters:vre}=hw.exports;vre.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var x$=wt((Gct,w$)=>{"use strict";w$.exports={RTLD_LAZY:1,RTLD_NOW:2,RTLD_GLOBAL:256,RTLD_LOCAL:0,RTLD_DEEPBIND:8,E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOPNOTSUPP:95,EOVERFLOW:75,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18,PRIORITY_LOW:19,PRIORITY_BELOW_NORMAL:10,PRIORITY_NORMAL:0,PRIORITY_ABOVE_NORMAL:-7,PRIORITY_HIGH:-14,PRIORITY_HIGHEST:-20,SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGILL:4,SIGTRAP:5,SIGABRT:6,SIGIOT:6,SIGBUS:7,SIGFPE:8,SIGKILL:9,SIGUSR1:10,SIGSEGV:11,SIGUSR2:12,SIGPIPE:13,SIGALRM:14,SIGTERM:15,SIGCHLD:17,SIGSTKFLT:16,SIGCONT:18,SIGSTOP:19,SIGTSTP:20,SIGTTIN:21,SIGTTOU:22,SIGURG:23,SIGXCPU:24,SIGXFSZ:25,SIGVTALRM:26,SIGPROF:27,SIGWINCH:28,SIGIO:29,SIGPOLL:29,SIGPWR:30,SIGSYS:31,UV_FS_SYMLINK_DIR:1,UV_FS_SYMLINK_JUNCTION:2,O_RDONLY:0,O_WRONLY:1,O_RDWR:2,UV_DIRENT_UNKNOWN:0,UV_DIRENT_FILE:1,UV_DIRENT_DIR:2,UV_DIRENT_LINK:3,UV_DIRENT_FIFO:4,UV_DIRENT_SOCKET:5,UV_DIRENT_CHAR:6,UV_DIRENT_BLOCK:7,S_IFMT:61440,S_IFREG:32768,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960,S_IFSOCK:49152,O_CREAT:64,O_EXCL:128,UV_FS_O_FILEMAP:0,O_NOCTTY:256,O_TRUNC:512,O_APPEND:1024,O_DIRECTORY:65536,O_NOATIME:262144,O_NOFOLLOW:131072,O_SYNC:1052672,O_DSYNC:4096,O_DIRECT:16384,O_NONBLOCK:2048,S_IRWXU:448,S_IRUSR:256,S_IWUSR:128,S_IXUSR:64,S_IRWXG:56,S_IRGRP:32,S_IWGRP:16,S_IXGRP:8,S_IRWXO:7,S_IROTH:4,S_IWOTH:2,S_IXOTH:1,F_OK:0,R_OK:4,W_OK:2,X_OK:1,UV_FS_COPYFILE_EXCL:1,COPYFILE_EXCL:1,UV_FS_COPYFILE_FICLONE:2,COPYFILE_FICLONE:2,UV_FS_COPYFILE_FICLONE_FORCE:4,COPYFILE_FICLONE_FORCE:4,OPENSSL_VERSION_NUMBER:805306640,SSL_OP_ALL:2147485776,SSL_OP_ALLOW_NO_DHE_KEX:1024,SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION:262144,SSL_OP_CIPHER_SERVER_PREFERENCE:4194304,SSL_OP_CISCO_ANYCONNECT:32768,SSL_OP_COOKIE_EXCHANGE:8192,SSL_OP_CRYPTOPRO_TLSEXT_BUG:2147483648,SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:2048,SSL_OP_LEGACY_SERVER_CONNECT:4,SSL_OP_NO_COMPRESSION:131072,SSL_OP_NO_ENCRYPT_THEN_MAC:524288,SSL_OP_NO_QUERY_MTU:4096,SSL_OP_NO_RENEGOTIATION:1073741824,SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION:65536,SSL_OP_NO_SSLv2:0,SSL_OP_NO_SSLv3:33554432,SSL_OP_NO_TICKET:16384,SSL_OP_NO_TLSv1:67108864,SSL_OP_NO_TLSv1_1:268435456,SSL_OP_NO_TLSv1_2:134217728,SSL_OP_NO_TLSv1_3:536870912,SSL_OP_PRIORITIZE_CHACHA:2097152,SSL_OP_TLS_ROLLBACK_BUG:8388608,ENGINE_METHOD_RSA:1,ENGINE_METHOD_DSA:2,ENGINE_METHOD_DH:4,ENGINE_METHOD_RAND:8,ENGINE_METHOD_EC:2048,ENGINE_METHOD_CIPHERS:64,ENGINE_METHOD_DIGESTS:128,ENGINE_METHOD_PKEY_METHS:512,ENGINE_METHOD_PKEY_ASN1_METHS:1024,ENGINE_METHOD_ALL:65535,ENGINE_METHOD_NONE:0,DH_CHECK_P_NOT_SAFE_PRIME:2,DH_CHECK_P_NOT_PRIME:1,DH_UNABLE_TO_CHECK_GENERATOR:4,DH_NOT_SUITABLE_GENERATOR:8,RSA_PKCS1_PADDING:1,RSA_NO_PADDING:3,RSA_PKCS1_OAEP_PADDING:4,RSA_X931_PADDING:5,RSA_PKCS1_PSS_PADDING:6,RSA_PSS_SALTLEN_DIGEST:-1,RSA_PSS_SALTLEN_MAX_SIGN:-2,RSA_PSS_SALTLEN_AUTO:-2,defaultCoreCipherList:"TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",TLS1_VERSION:769,TLS1_1_VERSION:770,TLS1_2_VERSION:771,TLS1_3_VERSION:772,POINT_CONVERSION_COMPRESSED:2,POINT_CONVERSION_UNCOMPRESSED:4,POINT_CONVERSION_HYBRID:6}});var Bne={};$t(Bne,{BasePlugin:()=>kt,DagCborHtmlPreviewPlugin:()=>lg,DirIndexHtmlPlugin:()=>cg,PluginError:()=>ig,PluginFatalError:()=>Oa,createVerifiedFetch:()=>CS,dagCborHtmlPreviewPluginFactory:()=>V$,dirIndexHtmlPluginFactory:()=>U$,verifiedFetch:()=>kw});var NS=Symbol.for("@libp2p/connection");var qo=Symbol.for("@libp2p/content-routing");function BS(r){return r==null?!1:(r.type==="RSA"||r.type==="Ed25519"||r.type==="secp256k1"||r.type==="ECDSA")&&r.raw instanceof Uint8Array&&typeof r.equals=="function"&&typeof r.toMultihash=="function"&&typeof r.toCID=="function"&&typeof r.verify=="function"}var tl=Symbol.for("@libp2p/peer-discovery");var dg=Symbol.for("@libp2p/peer-id");function Ti(r){return!!r?.[dg]}var jo=Symbol.for("@libp2p/peer-routing");var Na="keep-alive";var Ba=Symbol.for("@libp2p/transport");var rl;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(rl||(rl={}));var Je=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},hg=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},pg=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},K=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},_s=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},cp=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}};var mg=class extends Error{static name="ConnectionClosingError";constructor(e="The connection is closing"){super(e),this.name="ConnectionClosingError"}},bf=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},La=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}},Wo=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},gg=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},nl=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},qe=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},vf=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},Ma=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},yg=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},Ua=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},Cs=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Me=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},wg=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},Ii=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},Jn=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}};var Ts=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},il=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}},lp=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},xg=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Fa=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},so=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var De=class extends EventTarget{#e=new Map;constructor(){super()}listenerCount(e){let t=this.#e.get(e);return t==null?0:t.length}addEventListener(e,t,n){super.addEventListener(e,t,n);let i=this.#e.get(e);i==null&&(i=[],this.#e.set(e,i)),i.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let i=this.#e.get(e);i!=null&&(i=i.filter(({callback:o})=>o!==t),this.#e.set(e,i))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:i})=>!i),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};function bg(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function Rr(...r){let e=[];for(let t of r)bg(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStart!=null&&await t.beforeStart()})),await Promise.all(e.map(async t=>{await t.start()})),await Promise.all(e.map(async t=>{t.afterStart!=null&&await t.afterStart()}))}async function Zr(...r){let e=[];for(let t of r)bg(t)&&e.push(t);await Promise.all(e.map(async t=>{t.beforeStop!=null&&await t.beforeStop()})),await Promise.all(e.map(async t=>{await t.stop()})),await Promise.all(e.map(async t=>{t.afterStop!=null&&await t.afterStop()}))}var et=Symbol.for("@libp2p/service-capabilities"),ei=Symbol.for("@libp2p/service-dependencies");function Pe(r){let e=new globalThis.AbortController;function t(){e.abort();for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}for(let o of r){if(o?.aborted===!0){t();break}o?.addEventListener!=null&&o.addEventListener("abort",t)}function n(){for(let o of r)o?.removeEventListener!=null&&o.removeEventListener("abort",t)}let i=e.signal;return i.clear=n,i}var X=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function ve(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var vg=class{buffer;mask;top;btm;next;constructor(e){if(!(e>0)||(e-1&e)!==0)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(e),this.mask=e-1,this.top=0,this.btm=0,this.next=null}push(e){return this.buffer[this.top]!==void 0?!1:(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){let e=this.buffer[this.btm];if(e!==void 0)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return this.buffer[this.btm]===void 0}},Af=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new vg(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return e?.byteLength!=null?e.byteLength:1}push(e){if(e?.value!=null&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){let t=this.head;this.head=t.next=new vg(2*this.head.buffer.length),this.head.push(e)}}shift(){let e=this.tail.shift();if(e===void 0&&this.tail.next!=null){let t=this.tail.next;this.tail.next=null,this.tail=t,e=this.tail.shift()}return e?.value!=null&&(this.size-=this.calculateSize(e.value)),e}isEmpty(){return this.head.isEmpty()}};var Dw=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function ar(r={}){return iH(t=>{let n=t.shift();if(n==null)return{done:!0};if(n.error!=null)throw n.error;return{done:n.done===!0,value:n.value}},r)}function iH(r,e){e=e??{};let t=e.onEnd,n=new Af,i,o,s,a=ve(),c=async()=>{try{return n.isEmpty()?s?{done:!0}:await new Promise((w,x)=>{o=v=>{o=null,n.push(v);try{w(r(n))}catch(A){x(A)}return i}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=ve()})}},l=w=>o!=null?o(w):(n.push(w),i),u=w=>(n=new Af,o!=null?o({error:w}):(n.push({error:w}),i)),f=w=>{if(s)return i;if(e?.objectMode!==!0&&w?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:w})},d=w=>s?i:(s=!0,w!=null?u(w):l({done:!0})),h=()=>(n=new Af,d(),{done:!0}),m=w=>(d(w),{done:!0});if(i={[Symbol.asyncIterator](){return this},next:c,return:h,throw:m,push:f,end:d,get readableLength(){return n.size},onEmpty:async w=>{let x=w?.signal;if(x?.throwIfAborted(),n.isEmpty())return;let v,A;x!=null&&(v=new Promise((S,M)=>{A=()=>{M(new Dw)},x.addEventListener("abort",A)}));try{await Promise.race([a.promise,v])}finally{A!=null&&x!=null&&x?.removeEventListener("abort",A)}}},t==null)return i;let g=i;return i={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(w){return g.throw(w),t!=null&&(t(w),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:f,end(w){return g.end(w),t!=null&&(t(w),t=void 0),i},get readableLength(){return g.readableLength},onEmpty:w=>g.onEmpty(w)},i}var ti=class extends Error{static name="AbortError";name="AbortError";constructor(e="The operation was aborted",...t){super(e,...t)}};async function Kt(r,e,t,n){let i=new ti(n?.errorMessage);n?.errorCode!=null&&(i.code=n.errorCode);let o=n?.errorEvent??"error";return t?.aborted===!0?Promise.reject(i):new Promise((s,a)=>{function c(){Nw(t,"abort",f),Nw(r,e,l),Nw(r,o,u)}let l=d=>{try{if(n?.filter?.(d)===!1)return}catch(h){c(),a(h);return}c(),s(d)},u=d=>{if(c(),d instanceof Error){a(d);return}a(d.detail??n?.error??new Error(`The "${n?.errorEvent}" event was emitted but the event had no '.detail' field. Pass an 'error' option to race-event to change this message.`))},f=()=>{c(),a(i)};Ow(t,"abort",f),Ow(r,e,l),Ow(r,o,u)})}function Ow(r,e,t){r!=null&&(LS(r)?r.addEventListener(e,t):r.addListener(e,t))}function Nw(r,e,t){r!=null&&(LS(r)?r.removeEventListener(e,t):r.removeListener(e,t))}function LS(r){return typeof r.addEventListener=="function"&&typeof r.removeEventListener=="function"}function Is(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var Ag=class extends Error{remainingPoints;msBeforeNext;consumedPoints;isFirstInDuration;constructor(e="Rate limit exceeded",t){super(e),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}},Eg=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var Sg=class extends Error{type;code;constructor(e,t,n){super(e??"The operation was aborted"),this.type="aborted",this.name=n??"AbortError",this.code=t??"ABORT_ERR"}};async function dt(r,e,t){if(e==null)return r;if(e.aborted)return r.catch(()=>{}),Promise.reject(new Sg(t?.errorMessage,t?.errorCode,t?.errorName));let n,i=new Sg(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([r,new Promise((o,s)=>{n=()=>{s(i)},e.addEventListener("abort",n)})])}finally{n!=null&&e.removeEventListener("abort",n)}}var _g=class{deferred;signal;constructor(e){this.signal=e,this.deferred=ve(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Je)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function oH(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var Cg=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=oH(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new Je),this.cleanup())}async join(e={}){let t=new _g(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await dt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};var Dr=class extends De{concurrency;maxSize;queue;pending;sort;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,e.metricName!=null&&e.metrics?.registerMetricGroup(e.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}),this.sort=e.sort,this.queue=[],this.emitEmpty=Is(this.emitEmpty.bind(this),1),this.emitIdle=Is(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new Eg;let n=new Cg(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("completed",{detail:i}),this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Je)}),this.clear()}async onEmpty(e){this.size!==0&&await Kt(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Kt(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Kt(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=ar({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new Je("Queue aborted"))};this.addEventListener("completed",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var Or=class extends Dr{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function sH(r){return r[Symbol.asyncIterator]!=null}function aH(r){if(sH(r))return(async()=>{for await(let e of r);})();for(let e of r);}var Jr=aH;function ke(r=0){return new Uint8Array(r)}function Ht(r=0){return new Uint8Array(r)}var cH=Math.pow(2,7),lH=Math.pow(2,14),uH=Math.pow(2,21),Bw=Math.pow(2,28),Lw=Math.pow(2,35),Mw=Math.pow(2,42),Uw=Math.pow(2,49),ht=128,en=127;function je(r){if(r<cH)return 1;if(r<lH)return 2;if(r<uH)return 3;if(r<Bw)return 4;if(r<Lw)return 5;if(r<Mw)return 6;if(r<Uw)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ef(r,e,t=0){switch(je(r)){case 8:e[t++]=r&255|ht,r/=128;case 7:e[t++]=r&255|ht,r/=128;case 6:e[t++]=r&255|ht,r/=128;case 5:e[t++]=r&255|ht,r/=128;case 4:e[t++]=r&255|ht,r>>>=7;case 3:e[t++]=r&255|ht,r>>>=7;case 2:e[t++]=r&255|ht,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function fH(r,e,t=0){switch(je(r)){case 8:e.set(t++,r&255|ht),r/=128;case 7:e.set(t++,r&255|ht),r/=128;case 6:e.set(t++,r&255|ht),r/=128;case 5:e.set(t++,r&255|ht),r/=128;case 4:e.set(t++,r&255|ht),r>>>=7;case 3:e.set(t++,r&255|ht),r>>>=7;case 2:e.set(t++,r&255|ht),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function Fw(r,e){let t=r[e],n=0;if(n+=t&en,t<ht||(t=r[e+1],n+=(t&en)<<7,t<ht)||(t=r[e+2],n+=(t&en)<<14,t<ht)||(t=r[e+3],n+=(t&en)<<21,t<ht)||(t=r[e+4],n+=(t&en)*Bw,t<ht)||(t=r[e+5],n+=(t&en)*Lw,t<ht)||(t=r[e+6],n+=(t&en)*Mw,t<ht)||(t=r[e+7],n+=(t&en)*Uw,t<ht))return n;throw new RangeError("Could not decode varint")}function dH(r,e){let t=r.get(e),n=0;if(n+=t&en,t<ht||(t=r.get(e+1),n+=(t&en)<<7,t<ht)||(t=r.get(e+2),n+=(t&en)<<14,t<ht)||(t=r.get(e+3),n+=(t&en)<<21,t<ht)||(t=r.get(e+4),n+=(t&en)*Bw,t<ht)||(t=r.get(e+5),n+=(t&en)*Lw,t<ht)||(t=r.get(e+6),n+=(t&en)*Mw,t<ht)||(t=r.get(e+7),n+=(t&en)*Uw,t<ht))return n;throw new RangeError("Could not decode varint")}function Sr(r,e,t=0){return e==null&&(e=Ht(je(r))),e instanceof Uint8Array?Ef(r,e,t):fH(r,e,t)}function ao(r,e=0){return r instanceof Uint8Array?Fw(r,e):dH(r,e)}function Xe(r,e){e==null&&(e=r.reduce((i,o)=>i+o.length,0));let t=Ht(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}function he(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var US=Symbol.for("@achingbrain/uint8arraylist");function MS(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function ki(r){return!!r?.[US]}var pe=class r{bufs;length;[US]=!0;constructor(...e){this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ki(n))t+=n.byteLength,this.bufs.push(...n.bufs);else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ki(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=MS(this.bufs,e);return t.buf[t.index]}set(e,t){let n=MS(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ki(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return Xe(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:Xe(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),o=new r;return o.length=i,o.bufs=[...n],o}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:this.bufs,length:this.length};let n=[],i=0;for(let o=0;o<this.bufs.length;o++){let s=this.bufs[o],a=i,c=a+s.byteLength;if(i=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(s);break}let f=e-a;n.push(s.subarray(f,f+(t-e)));break}if(l){if(e===0){n.push(s);continue}n.push(s.subarray(e-a));continue}if(u){if(t===c){n.push(s);break}n.push(s.subarray(0,t-a));break}n.push(s)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ki(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let o=256,s=new Int32Array(o);for(let f=0;f<o;f++)s[f]=-1;for(let f=0;f<i;f++)s[n[f]]=f;let a=s,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let f=t;f<=c;f+=u){u=0;for(let d=l;d>=0;d--){let h=this.get(f+d);if(n[d]!==h){u=Math.max(1,d-a[h]);break}}if(u===0)return f}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=Ht(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=ke(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=ke(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=ke(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=Ht(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=ke(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=ke(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=ke(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=ke(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=ke(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!he(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((i,o)=>i+o.byteLength,0)),n.length=t,n}};var Tg=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},Sf=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},Ig=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},up=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function kg(r){return r[Symbol.asyncIterator]!=null}function FS(r,e){if(r.byteLength>e)throw new Sf("Message length too long")}var Rg=r=>{let e=je(r),t=Ht(e);return Sr(r,t),Rg.bytes=e,t};Rg.bytes=0;function Ps(r,e){e=e??{};let t=e.lengthEncoder??Rg,n=e?.maxDataLength??4194304;function*i(o){FS(o,n);let s=t(o.byteLength);s instanceof Uint8Array?yield s:yield*s,o instanceof Uint8Array?yield o:yield*o}return kg(r)?(async function*(){for await(let o of r)yield*i(o)})():(function*(){for(let o of r)yield*i(o)})()}Ps.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??Rg,n=e?.maxDataLength??4194304;return FS(r,n),new pe(t(r.byteLength),r)};var ol;(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(ol||(ol={}));var $w=r=>{let e=ao(r);return $w.bytes=je(e),e};$w.bytes=0;function Rs(r,e){let t=new pe,n=ol.LENGTH,i=-1,o=e?.lengthDecoder??$w,s=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===ol.LENGTH)try{if(i=o(t),i<0)throw new Tg("Invalid message length");if(i>a)throw new Sf("Message length too long");let l=o.bytes;t.consume(l),e?.onLength!=null&&e.onLength(i),n=ol.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>s)throw new Ig("Message length length too long");break}throw l}if(n===ol.DATA){if(t.byteLength<i)break;let l=t.sublist(0,i);t.consume(i),e?.onData!=null&&e.onData(l),yield l,n=ol.LENGTH}}}return kg(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new up("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new up("Unexpected end of input")})()}Rs.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:o,value:s}=await r.next(t);if(o===!0)return;s!=null&&(yield s)}catch(o){if(o.code==="ERR_UNDER_READ")return{done:!0,value:null};throw o}finally{t=1}})();return Rs(n,{...e??{},onLength:o=>{t=o}})};function mH(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:i=>{n.push(i)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var _f=mH;function gH(r){return r[Symbol.asyncIterator]!=null}function yH(r,e){let t=0;if(gH(r))return(async function*(){for await(let c of r)yield e(c,t++)})();let n=_f(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){yield await s;for(let c of n)yield e(c,t++)})();let a=e;return(function*(){yield s;for(let c of n)yield a(c,t++)})()}var zt=yH;var Hw=class{readNext;haveNext;ended;nextResult;error;constructor(){this.ended=!1,this.readNext=ve(),this.haveNext=ve()}[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 e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=ve(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=ve(),await dt(this.readNext.promise,t?.signal,t)}};function Dg(){return new Hw}function wH(r){return r[Symbol.asyncIterator]!=null}async function xH(r,e,t){try{await Promise.all(r.map(async n=>{for await(let i of n)await e.push(i,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*bH(r){let e=new AbortController,t=Dg();xH(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*vH(r){for(let e of r)yield*e}function AH(...r){let e=[];for(let t of r)wH(t)||e.push(t);return e.length===r.length?vH(e):bH(r)}var pn=AH;function vt(r,...e){if(r==null)throw new Error("Empty pipeline");if(Vw(r)){let n=r;r=()=>n.source}else if(VS(r)||HS(r)){let n=r;r=()=>n}let t=[r,...e];if(t.length>1&&Vw(t[t.length-1])&&(t[t.length-1]=t[t.length-1].sink),t.length>2)for(let n=1;n<t.length-1;n++)Vw(t[n])&&(t[n]=SH(t[n]));return EH(...t)}var EH=(...r)=>{let e;for(;r.length>0;)e=r.shift()(e);return e},HS=r=>r?.[Symbol.asyncIterator]!=null,VS=r=>r?.[Symbol.iterator]!=null,Vw=r=>r==null?!1:r.sink!=null&&r.source!=null,SH=r=>e=>{let t=r.sink(e);if(t?.then!=null){let n=ar({objectMode:!0});t.then(()=>{n.end()},s=>{n.end(s)});let i,o=r.source;if(HS(o))i=async function*(){yield*o,n.end()};else if(VS(o))i=function*(){yield*o,n.end()};else throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");return pn(n,i())}return r.source};function _H(r){return r[Symbol.asyncIterator]!=null}function CH(r,e){return _H(r)?(async function*(){let t=0;if(!(e<1)){for await(let n of r)if(yield n,t++,t===e)return}})():(function*(){let t=0;if(!(e<1)){for(let n of r)if(yield n,t++,t===e)return}})()}var $a=CH;var fp="/ipfs/bitswap/1.2.0";var Kw=new Float32Array([-0]),Ha=new Uint8Array(Kw.buffer);function KS(r,e,t){Kw[0]=r,e[t]=Ha[0],e[t+1]=Ha[1],e[t+2]=Ha[2],e[t+3]=Ha[3]}function zS(r,e){return Ha[0]=r[e],Ha[1]=r[e+1],Ha[2]=r[e+2],Ha[3]=r[e+3],Kw[0]}var zw=new Float64Array([-0]),tn=new Uint8Array(zw.buffer);function qS(r,e,t){zw[0]=r,e[t]=tn[0],e[t+1]=tn[1],e[t+2]=tn[2],e[t+3]=tn[3],e[t+4]=tn[4],e[t+5]=tn[5],e[t+6]=tn[6],e[t+7]=tn[7]}function jS(r,e){return tn[0]=r[e],tn[1]=r[e+1],tn[2]=r[e+2],tn[3]=r[e+3],tn[4]=r[e+4],tn[5]=r[e+5],tn[6]=r[e+6],tn[7]=r[e+7],zw[0]}var TH=BigInt(Number.MAX_SAFE_INTEGER),IH=BigInt(Number.MIN_SAFE_INTEGER),ri=class r{lo;hi;constructor(e,t){this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return sl;if(e<TH&&e>IH)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>WS&&(i=0n,++n>WS&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return sl;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):sl}},sl=new ri(0,0);sl.toBigInt=function(){return 0n};sl.zzEncode=sl.zzDecode=function(){return this};sl.length=function(){return 1};var WS=4294967296n;function GS(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function XS(r,e,t){if(t-e<1)return"";let i,o=[],s=0,a;for(;e<t;)a=r[e++],a<128?o[s++]=a:a>191&&a<224?o[s++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,o[s++]=55296+(a>>10),o[s++]=56320+(a&1023)):o[s++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,s>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i!=null?(s>0&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))}function qw(r,e,t){let n=t,i,o;for(let s=0;s<r.length;++s)i=r.charCodeAt(s),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((o=r.charCodeAt(s+1))&64512)===56320?(i=65536+((i&1023)<<10)+(o&1023),++s,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}function co(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Og(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var jw=class{buf;pos;len;_slice=Uint8Array.prototype.subarray;constructor(e){this.buf=e,this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,co(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw co(this,4);return Og(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw co(this,4);return Og(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw co(this,4);let e=zS(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw co(this,4);let e=jS(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw co(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return XS(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw co(this,e);this.pos+=e}else do if(this.pos>=this.len)throw co(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ri(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw co(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw co(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw co(this,8);let e=Og(this.buf,this.pos+=4),t=Og(this.buf,this.pos+=4);return new ri(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=Fw(this.buf,this.pos);return this.pos+=je(e),e}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 Ww(r){return new jw(r instanceof Uint8Array?r:r.subarray())}function we(r,e,t){let n=Ww(r);return e.decode(n,void 0,t)}var t7={};$t(t7,{base10:()=>UH});var al={};$t(al,{coerce:()=>Pi,empty:()=>QS,equals:()=>Gw,fromHex:()=>PH,fromString:()=>Xw,isBinary:()=>RH,toHex:()=>kH,toString:()=>Yw});var QS=new Uint8Array(0);function kH(r){return r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function PH(r){let e=r.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):QS}function Gw(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Pi(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 RH(r){return r instanceof ArrayBuffer||ArrayBuffer.isView(r)}function Xw(r){return new TextEncoder().encode(r)}function Yw(r){return new TextDecoder().decode(r)}function DH(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var o=r.charAt(i),s=o.charCodeAt(0);if(t[s]!==255)throw new TypeError(o+" is ambiguous");t[s]=i}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 g=0,w=0,x=0,v=m.length;x!==v&&m[x]===0;)x++,g++;for(var A=(v-x)*u+1>>>0,S=new Uint8Array(A);x!==v;){for(var M=m[x],F=0,N=A-1;(M!==0||F<w)&&N!==-1;N--,F++)M+=256*S[N]>>>0,S[N]=M%a>>>0,M=M/a>>>0;if(M!==0)throw new Error("Non-zero carry");w=F,x++}for(var R=A-w;R!==A&&S[R]===0;)R++;for(var _=c.repeat(g);R<A;++R)_+=r.charAt(S[R]);return _}function d(m){if(typeof m!="string")throw new TypeError("Expected String");if(m.length===0)return new Uint8Array;var g=0;if(m[g]!==" "){for(var w=0,x=0;m[g]===c;)w++,g++;for(var v=(m.length-g)*l+1>>>0,A=new Uint8Array(v);m[g];){var S=t[m.charCodeAt(g)];if(S===255)return;for(var M=0,F=v-1;(S!==0||M<x)&&F!==-1;F--,M++)S+=a*A[F]>>>0,A[F]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");x=M,g++}if(m[g]!==" "){for(var N=v-x;N!==v&&A[N]===0;)N++;for(var R=new Uint8Array(w+(v-N)),_=w;N!==v;)R[_++]=A[N++];return R}}}function h(m){var g=d(m);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var OH=DH,NH=OH,ZS=NH;var Qw=class{name;prefix;baseEncode;constructor(e,t,n){this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Zw=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return JS(this,e)}},Jw=class{decoders;constructor(e){this.decoders=e}or(e){return JS(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function JS(r,e){return new Jw({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var e7=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,i){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new Qw(e,t,n),this.decoder=new Zw(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Cf({name:r,prefix:e,encode:t,decode:n}){return new e7(r,e,t,n)}function Va({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=ZS(t,r);return Cf({prefix:e,name:r,encode:n,decode:o=>Pi(i(o))})}function BH(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let o=new Uint8Array(i*t/8|0),s=0,a=0,c=0;for(let l=0;l<i;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,s+=t,s>=8&&(s-=8,o[c++]=255&a>>s)}if(s>=t||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return o}function LH(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,o="",s=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],s+=8;s>t;)s-=t,o+=e[i&a>>s];if(s!==0&&(o+=e[i&a<<t-s]),n)for(;(o.length*t&7)!==0;)o+="=";return o}function MH(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function qt({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=MH(n);return Cf({prefix:e,name:r,encode(o){return LH(o,n,t)},decode(o){return BH(o,i,t,r)}})}var UH=Va({prefix:"9",name:"base10",alphabet:"0123456789"});var r7={};$t(r7,{base16:()=>FH,base16upper:()=>$H});var FH=qt({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$H=qt({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var n7={};$t(n7,{base2:()=>HH});var HH=qt({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var i7={};$t(i7,{base256emoji:()=>jH});var e_=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}"),VH=e_.reduce((r,e,t)=>(r[t]=e,r),[]),KH=e_.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function zH(r){return r.reduce((e,t)=>(e+=VH[t],e),"")}function qH(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=KH[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var jH=Cf({prefix:"\u{1F680}",name:"base256emoji",encode:zH,decode:qH});var o7={};$t(o7,{base32:()=>jt,base32hex:()=>YH,base32hexpad:()=>ZH,base32hexpadupper:()=>JH,base32hexupper:()=>QH,base32pad:()=>GH,base32padupper:()=>XH,base32upper:()=>WH,base32z:()=>eV});var jt=qt({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),WH=qt({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),GH=qt({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),XH=qt({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),YH=qt({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),QH=qt({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZH=qt({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),JH=qt({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),eV=qt({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var s7={};$t(s7,{base36:()=>mn,base36upper:()=>tV});var mn=Va({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),tV=Va({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var a7={};$t(a7,{base58btc:()=>Ye,base58flickr:()=>rV});var Ye=Va({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),rV=Va({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var c7={};$t(c7,{base64:()=>cr,base64pad:()=>nV,base64url:()=>cl,base64urlpad:()=>iV});var cr=qt({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nV=qt({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cl=qt({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iV=qt({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var l7={};$t(l7,{base8:()=>oV});var oV=qt({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var u7={};$t(u7,{identity:()=>sV});var sV=Cf({prefix:"\0",name:"identity",encode:r=>Yw(r),decode:r=>Xw(r)});var Tf={};$t(Tf,{code:()=>Go,decode:()=>f7,encode:()=>uV,name:()=>lV});var aV=new TextEncoder,cV=new TextDecoder,lV="json",Go=512;function uV(r){return aV.encode(JSON.stringify(r))}function f7(r){return JSON.parse(cV.decode(r))}var Rn={};$t(Rn,{code:()=>At,decode:()=>hV,encode:()=>dV,name:()=>fV});var fV="raw",At=85;function dV(r){return Pi(r)}function hV(r){return Pi(r)}var p7={};$t(p7,{identity:()=>lr});var Et={};$t(Et,{Digest:()=>ll,create:()=>gn,decode:()=>We,equals:()=>h7,hasCode:()=>DV});var pV=n_,t_=128,mV=127,gV=~mV,yV=Math.pow(2,31);function n_(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yV;)e[t++]=r&255|t_,r/=128;for(;r&gV;)e[t++]=r&255|t_,r>>>=7;return e[t]=r|0,n_.bytes=t-n+1,e}var wV=d7,xV=128,r_=127;function d7(r,n){var t=0,n=n||0,i=0,o=n,s,a=r.length;do{if(o>=a)throw d7.bytes=0,new RangeError("Could not decode varint");s=r[o++],t+=i<28?(s&r_)<<i:(s&r_)*Math.pow(2,i),i+=7}while(s>=xV);return d7.bytes=o-n,t}var bV=Math.pow(2,7),vV=Math.pow(2,14),AV=Math.pow(2,21),EV=Math.pow(2,28),SV=Math.pow(2,35),_V=Math.pow(2,42),CV=Math.pow(2,49),TV=Math.pow(2,56),IV=Math.pow(2,63),kV=function(r){return r<bV?1:r<vV?2:r<AV?3:r<EV?4:r<SV?5:r<_V?6:r<CV?7:r<TV?8:r<IV?9:10},PV={encode:pV,decode:wV,encodingLength:kV},RV=PV,dp=RV;function hp(r,e=0){return[dp.decode(r,e),dp.decode.bytes]}function If(r,e,t=0){return dp.encode(r,e,t),e}function kf(r){return dp.encodingLength(r)}function gn(r,e){let t=e.byteLength,n=kf(r),i=n+kf(t),o=new Uint8Array(i+t);return If(r,o,0),If(t,o,n),o.set(e,i),new ll(r,t,e,o)}function We(r){let e=Pi(r),[t,n]=hp(e),[i,o]=hp(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new ll(t,i,s,e)}function h7(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Gw(r.bytes,t.bytes)}}var ll=class{code;size;digest;bytes;constructor(e,t,n,i){this.code=e,this.size=t,this.digest=n,this.bytes=i}};function DV(r,e){return r.code===e}var i_=0,OV="identity",o_=Pi;function NV(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return gn(i_,o_(r))}var lr={code:i_,name:OV,encode:o_,digest:NV};var g7={};$t(g7,{sha256:()=>Be,sha512:()=>Bg});var BV=20;function ul({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new m7(r,e,t,n,i)}var m7=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,i,o){this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??BV,this.maxDigestLength=o}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?s_(n,this.code,t?.truncate):n.then(i=>s_(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function s_(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return gn(e,r)}function c_(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Be=ul({name:"sha2-256",code:18,encode:c_("SHA-256")}),Bg=ul({name:"sha2-512",code:19,encode:c_("SHA-512")});function y7(r,e){let{bytes:t,version:n}=r;switch(n){case 0:return MV(t,w7(r),e??Ye.encoder);default:return UV(t,w7(r),e??jt.encoder)}}var l_=new WeakMap;function w7(r){let e=l_.get(r);if(e==null){let t=new Map;return l_.set(r,t),t}return e}var G=class r{code;version;multihash;bytes;"/";constructor(e,t,n,i){this.code=t,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}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:e,multihash:t}=this;if(e!==pp)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==FV)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}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:e,digest:t}=this.multihash,n=gn(e,t);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(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&h7(e.multihash,n.multihash)}toString(e){return y7(this,e)}toJSON(){return{"/":y7(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:o,bytes:s}=t;return new r(n,i,o,s??u_(n,i,o.bytes))}else if(t[$V]===!0){let{version:n,multihash:i,code:o}=t,s=We(i);return r.create(n,o,s)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==pp)throw new Error(`Version 0 CID must use dag-pb (code: ${pp}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=u_(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,pp,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=Pi(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let o=i.subarray(t.multihashSize-t.digestSize),s=new ll(t.multihashCode,t.digestSize,o,i);return[t.version===0?r.createV0(s):r.createV1(t.codec,s),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[f,d]=hp(e.subarray(t));return t+=d,f},i=n(),o=pp;if(i===18?(i=0,t=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=t,a=n(),c=n(),l=t+c,u=l-s;return{version:i,codec:o,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,i]=LV(e,t),o=r.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return w7(o).set(n,e),o}};function LV(r,e){switch(r[0]){case"Q":{let t=e??Ye;return[Ye.prefix,t.decode(`${Ye.prefix}${r}`)]}case Ye.prefix:{let t=e??Ye;return[Ye.prefix,t.decode(r)]}case jt.prefix:{let t=e??jt;return[jt.prefix,t.decode(r)]}case mn.prefix:{let t=e??mn;return[mn.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function MV(r,e,t){let{prefix:n}=t;if(n!==Ye.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let o=t.encode(r).slice(1);return e.set(n,o),o}else return i}function UV(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let o=t.encode(r);return e.set(n,o),o}else return i}var pp=112,FV=18;function u_(r,e,t){let n=kf(r),i=n+kf(e),o=new Uint8Array(i+t.byteLength);return If(r,o,0),If(e,o,n),o.set(t,i),o}var $V=Symbol.for("@ipld/js-cid/CID");var fl={...u7,...n7,...l7,...t7,...r7,...o7,...s7,...a7,...c7,...i7},Ase={...g7,...p7};function d_(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var f_=d_("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),x7=d_("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=Ht(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),HV={utf8:f_,"utf-8":f_,hex:fl.base16,latin1:x7,ascii:x7,binary:x7,...fl},Lg=HV;function D(r,e="utf8"){let t=Lg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function b7(r){let e=r??8192,t=e>>>1,n,i=e;return function(s){if(s<1||s>t)return Ht(s);i+s>e&&(n=Ht(e),i=0);let a=n.subarray(i,i+=s);return(i&7)!==0&&(i=(i|7)+1),a}}var dl=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function v7(){}var E7=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},VV=b7();function KV(r){return globalThis.Buffer!=null?Ht(r):VV(r)}var gp=class{len;head;tail;states;constructor(){this.len=0,this.head=new dl(v7,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new dl(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new S7((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Mg,10,ri.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ri.fromBigInt(e);return this._push(Mg,t.length(),t)}uint64Number(e){return this._push(Ef,je(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=ri.fromBigInt(e).zzEncode();return this._push(Mg,t.length(),t)}sint64Number(e){let t=ri.fromNumber(e).zzEncode();return this._push(Mg,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(A7,1,e?1:0)}fixed32(e){return this._push(mp,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ri.fromBigInt(e);return this._push(mp,4,t.lo)._push(mp,4,t.hi)}fixed64Number(e){let t=ri.fromNumber(e);return this._push(mp,4,t.lo)._push(mp,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(KS,4,e)}double(e){return this._push(qS,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(A7,1,0):this.uint32(t)._push(qV,t,e)}string(e){let t=GS(e);return t!==0?this.uint32(t)._push(qw,t,e):this._push(A7,1,0)}fork(){return this.states=new E7(this),this.head=this.tail=new dl(v7,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 dl(v7,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=KV(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function A7(r,e,t){e[t]=r&255}function zV(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var S7=class extends dl{next;constructor(e,t){super(zV,e,t),this.next=void 0}};function Mg(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function mp(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function qV(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(gp.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(jV,e,r),this},gp.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(WV,e,r),this});function jV(r,e,t){e.set(r,t)}function WV(r,e,t){r.length<40?qw(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(D(r),t)}function _7(){return new gp}function xe(r,e){let t=_7();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Pf;(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"})(Pf||(Pf={}));function Ug(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function St(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,s){let a=e(o);s.int32(a)},n=function(o){let s=o.int32();return e(s)};return Ug("enum",Pf.VARINT,t,n)}function be(r,e){return Ug("message",Pf.LENGTH_DELIMITED,r,e)}var xt=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},yp=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"};var tr;(function(r){r.WantBlock="WantBlock",r.WantHave="WantHave"})(tr||(tr={}));var C7;(function(r){r[r.WantBlock=0]="WantBlock",r[r.WantHave=1]="WantHave"})(C7||(C7={}));(function(r){r.codec=()=>St(C7)})(tr||(tr={}));var Rf;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.priority!=null&&t.priority!==0&&(n.uint32(16),n.int32(t.priority)),t.cancel!=null&&(n.uint32(24),n.bool(t.cancel)),t.wantType!=null&&(n.uint32(32),tr.codec().encode(t.wantType,n)),t.sendDontHave!=null&&(n.uint32(40),n.bool(t.sendDontHave)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={cid:ke(0),priority:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.priority=t.int32();break}case 3:{o.cancel=t.bool();break}case 4:{o.wantType=tr.codec().decode(t);break}case 5:{o.sendDontHave=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Rf||(Rf={}));var Fg;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.entries!=null)for(let o of t.entries)n.uint32(10),Rf.codec().encode(o,n);t.full!=null&&(n.uint32(16),n.bool(t.full)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={entries:[]},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{if(i.limits?.entries!=null&&o.entries.length===i.limits.entries)throw new xt('Decode error - map field "entries" had too many elements');o.entries.push(Rf.codec().decode(t,t.uint32(),{limits:i.limits?.entries$}));break}case 2:{o.full=t.bool();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Fg||(Fg={}));var Df;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.prefix!=null&&t.prefix.byteLength>0&&(n.uint32(10),n.bytes(t.prefix)),t.data!=null&&t.data.byteLength>0&&(n.uint32(18),n.bytes(t.data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={prefix:ke(0),data:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.prefix=t.bytes();break}case 2:{o.data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Df||(Df={}));var Ri;(function(r){r.HaveBlock="HaveBlock",r.DoNotHaveBlock="DoNotHaveBlock"})(Ri||(Ri={}));var $g;(function(r){r[r.HaveBlock=0]="HaveBlock",r[r.DoNotHaveBlock=1]="DoNotHaveBlock"})($g||($g={}));(function(r){r.codec=()=>St($g)})(Ri||(Ri={}));var Of;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.cid!=null&&t.cid.byteLength>0&&(n.uint32(10),n.bytes(t.cid)),t.type!=null&&$g[t.type]!==0&&(n.uint32(16),Ri.codec().encode(t.type,n)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={cid:ke(0),type:Ri.HaveBlock},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.cid=t.bytes();break}case 2:{o.type=Ri.codec().decode(t);break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Of||(Of={}));var hl;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{if(i.lengthDelimited!==!1&&n.fork(),t.wantlist!=null&&(n.uint32(10),Fg.codec().encode(t.wantlist,n)),t.blocks!=null)for(let o of t.blocks)n.uint32(26),Df.codec().encode(o,n);if(t.blockPresences!=null)for(let o of t.blockPresences)n.uint32(34),Of.codec().encode(o,n);t.pendingBytes!=null&&t.pendingBytes!==0&&(n.uint32(40),n.int32(t.pendingBytes)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={blocks:[],blockPresences:[],pendingBytes:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.wantlist=Fg.codec().decode(t,t.uint32(),{limits:i.limits?.wantlist});break}case 3:{if(i.limits?.blocks!=null&&o.blocks.length===i.limits.blocks)throw new xt('Decode error - map field "blocks" had too many elements');o.blocks.push(Df.codec().decode(t,t.uint32(),{limits:i.limits?.blocks$}));break}case 4:{if(i.limits?.blockPresences!=null&&o.blockPresences.length===i.limits.blockPresences)throw new xt('Decode error - map field "blockPresences" had too many elements');o.blockPresences.push(Of.codec().decode(t,t.uint32(),{limits:i.limits?.blockPresences$}));break}case 5:{o.pendingBytes=t.int32();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(hl||(hl={}));function h_(r,e){for(let[t,n]of e.wantlist.entries()){let i=r.wantlist.get(t);i!=null&&(i.priority>n.priority&&(n.priority=i.priority),n.cancel=n.cancel??i.cancel,n.wantType=n.wantType??i.wantType,n.sendDontHave=n.sendDontHave??i.sendDontHave),r.wantlist.set(t,n)}for(let[t,n]of e.blockPresences.entries())r.blockPresences.set(t,n);for(let[t,n]of e.blocks.entries())r.blocks.set(t,n);return e.full&&!r.full&&(r.full=!0),r}var Hg=class extends Error{static name="BlockTooLargeError";constructor(e="Block too large"){super(e),this.name="BlockTooLargeError"}};var GV=4193648,XV=GV+16;function*p_(r,e){let t=[...r.wantlist.values()],n=[...r.blockPresences.values()],i=[...r.blocks.values()],o=0,s=0,a=0,c=!1;for(;;){let l={wantlist:{full:r.full??!1,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},u=hl.encode(l).byteLength,{added:f,hasMore:d,newSize:h}=T7(i,l.blocks,a,e,u,YV);a+=f,u=h;let m=d;({added:f,hasMore:d,newSize:h}=T7(n,l.blockPresences,s,e,u,QV)),s+=f,u=h;let g=d;if({added:f,hasMore:d,newSize:h}=T7(t,l.wantlist.entries,o,e,u,ZV),o+=f,u=h,c=!m&&!g&&!d,c||(l.wantlist.full=!1),yield hl.encode(l),c)break}}function T7(r,e,t,n,i,o){let s=0,a=!1;for(let c=t;c<r.length;c++){let l=r[c],u=o(l);if(u>XV)throw new Hg("Cannot send block as after encoding it is over the max message size");let f=i+u;if(f>n){a=!0;break}e.push(l),s++,i=f}return{hasMore:a,added:s,newSize:i}}function YV(r){return I7(3,Df.encode(r))}function QV(r){return I7(4,Of.encode(r))}function ZV(r){return I7(1,Rf.encode(r))}function I7(r,e){let t=je(r),n=je(e.byteLength);return t+n+e.byteLength}var Vg=class extends De{log;libp2p;routing;protocols;running;maxInboundStreams;maxOutboundStreams;messageReceiveTimeout;registrarIds;metrics;sendQueue;runOnLimitedConnections;maxOutgoingMessageSize;maxIncomingMessageSize;constructor(e,t={}){super(),this.log=e.logger.forComponent("helia:bitswap:network"),this.libp2p=e.libp2p,this.routing=e.routing,this.protocols=t.protocols??[fp],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=t.maxInboundStreams??1024,this.maxOutboundStreams=t.maxOutboundStreams??1024,this.messageReceiveTimeout=t.messageReceiveTimeout??5e3,this.runOnLimitedConnections=t.runOnLimitedConnections??!1,this.maxIncomingMessageSize=t.maxIncomingMessageSize??4194304,this.maxOutgoingMessageSize=t.maxOutgoingMessageSize??t.maxIncomingMessageSize??4194304,this.metrics={blocksSent:e.metrics?.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:e.metrics?.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new Or({concurrency:t.messageSendConcurrency??50,metrics:e.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",n=>{this.log.error("error sending wantlist to peer",n.detail)})}async start(){if(this.running)return;this.running=!0,await this.libp2p.handle(this.protocols,this._onStream,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnections});let e={onConnect:t=>{this.safeDispatchEvent("peer:connected",{detail:t})},onDisconnect:t=>{this.safeDispatchEvent("peer:disconnected",{detail:t})}};this.registrarIds=[];for(let t of this.protocols)this.registrarIds.push(await this.libp2p.register(t,e));this.libp2p.getConnections().forEach(t=>{this.safeDispatchEvent("peer:connected",{detail:t.remotePeer})})}async stop(){if(this.running=!1,await this.libp2p.unhandle(this.protocols),this.registrarIds!=null){for(let e of this.registrarIds)this.libp2p.unregister(e);this.registrarIds=[]}}_onStream(e){if(!this.running)return;let{stream:t,connection:n}=e;Promise.resolve().then(async()=>{this.log("incoming new bitswap %s stream from %p",t.protocol,n.remotePeer);let i=()=>{t.status==="open"?t.abort(new Ii(`Incoming Bitswap stream timed out after ${this.messageReceiveTimeout}ms`)):this.log("stream aborted with status %s",t.status)},o=AbortSignal.timeout(this.messageReceiveTimeout);o.addEventListener("abort",i),await t.closeWrite(),await vt(t,s=>Rs(s,{maxDataLength:this.maxIncomingMessageSize}),async s=>{for await(let a of s)try{let c=hl.decode(a);this.log("incoming new bitswap %s message from %p on stream",t.protocol,n.remotePeer,t.id),this.safeDispatchEvent("bitswap:message",{detail:{peer:n.remotePeer,message:c}}),o.removeEventListener("abort",i),o=AbortSignal.timeout(this.messageReceiveTimeout),o.addEventListener("abort",i)}catch(c){this.log.error("error reading incoming bitswap message from %p on stream",n.remotePeer,t.id,c),t.abort(c);break}})}).catch(i=>{this.log.error("error handling incoming stream from %p",n.remotePeer,i),t.abort(i)})}async*findProviders(e,t){t?.onProgress?.(new X("bitswap:network:find-providers",e));for await(let n of this.routing.findProviders(e,t))await this.libp2p.isDialable(n.multiaddrs,{runOnLimitedConnection:this.runOnLimitedConnections})&&(yield n)}async findAndConnect(e,t){t?.providers!=null&&await Promise.all(t.providers.map(async n=>this.connectTo(n).catch(i=>{this.log.error("could not connect to supplied provider - %e",i)}))),await Jr(zt($a(this.findProviders(e,t),t?.maxProviders??3),async n=>this.connectTo(n.id,t))).catch(n=>{this.log.error(n)})}async sendMessage(e,t,n){if(!this.running)throw new Error("network isn't running");let i=this.sendQueue.queue.find(o=>e.equals(o.options.peerId)&&o.status==="queued");if(i!=null){i.options.message=h_(i.options.message,t),await i.join({signal:n?.signal});return}await this.sendQueue.add(async o=>{let s=o?.message;if(s==null)throw new K("No message to send");this.log("sendMessage to %p",e),o?.onProgress?.(new X("bitswap:network:send-wantlist",e));let a=await this.libp2p.dialProtocol(e,fp,o);await a.closeRead();try{await vt(p_(s,this.maxOutgoingMessageSize),c=>Ps(c),a),await a.close(o)}catch(c){o?.onProgress?.(new X("bitswap:network:send-wantlist:error",{peer:e,error:c})),this.log.error("error sending message to %p",e,c),a.abort(c)}this._updateSentStats(s.blocks)},{peerId:e,signal:n?.signal,message:t})}async connectTo(e,t){if(!this.running)throw new Jn("Network isn't running");t?.onProgress?.(new X("bitswap:network:dial",e));let[n]=await Promise.all([this.libp2p.dial(e,t),Kt(this.libp2p,"peer:identify",t?.signal,{filter:i=>{if(!i.detail.peerId.equals(e))return!1;if(i.detail.protocols.includes(fp))return!0;throw new Cs(`${e} did not support ${fp}`)}})]);return n}_updateSentStats(e){let t=0;for(let n of e.values())t+=n.data.byteLength;this.metrics.dataSent?.increment(t),this.metrics.blocksSent?.increment(e.size)}};function z(r,e="utf8"){let t=Lg[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var aK=parseInt("11111",2),k7=parseInt("10000000",2),cK=parseInt("01111111",2),m_={0:wp,1:wp,2:lK,3:dK,4:hK,5:fK,6:uK,16:wp,22:wp,48:wp};function Di(r,e={offset:0}){let t=r[e.offset]&aK;if(e.offset++,m_[t]!=null)return m_[t](r,e);throw new Error("No decoder for tag "+t)}function xp(r,e){let t=0;if((r[e.offset]&k7)===k7){let n=r[e.offset]&cK,i="0x";e.offset++;for(let o=0;o<n;o++,e.offset++)i+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(i,16)}else t=r[e.offset],e.offset++;return t}function wp(r,e){xp(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=Di(r,e);if(n===null)break;t.push(n)}return t}function lK(r,e){let t=xp(r,e),n=e.offset,i=e.offset+t,o=[];for(let s=n;s<i;s++)s===n&&r[s]===0||o.push(r[s]);return e.offset+=t,Uint8Array.from(o)}function uK(r,e){let t=xp(r,e),n=e.offset+t,i=r[e.offset];e.offset++;let o=0,s=0;i<40?(o=0,s=i):i<80?(o=1,s=i-40):(o=2,s=i-80);let a=`${o}.${s}`,c=[];for(;e.offset<n;){let l=r[e.offset];if(e.offset++,c.push(l&127),l<128){c.reverse();let u=0;for(let f=0;f<c.length;f++)u+=c[f]<<f*7;a+=`.${u}`,c=[]}}return a}function fK(r,e){return e.offset++,null}function dK(r,e){let t=xp(r,e),n=r[e.offset];e.offset++;let i=r.subarray(e.offset,e.offset+t-1);if(e.offset+=t,n!==0)throw new Error("Unused bits in bit string is unimplemented");return i}function hK(r,e){let t=xp(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function pK(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new pe;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function Kg(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=pK(r.byteLength);return new pe(Uint8Array.from([e.byteLength|k7]),e)}function yn(r){let e=new pe,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new pe(Uint8Array.from([2]),Kg(e),e)}function bp(r){let e=Uint8Array.from([0]),t=new pe(e,r);return new pe(Uint8Array.from([3]),Kg(t),t)}function g_(r){return new pe(Uint8Array.from([4]),Kg(r),r)}function lo(r,e=48){let t=new pe;for(let n of r)t.append(n);return new pe(Uint8Array.from([e]),Kg(t),t)}var y_="1.2.840.10045.3.1.7",w_="1.3.132.0.34",x_="1.3.132.0.35";async function b_(r="P-256"){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:r},!0,["sign","verify"]);return{publicKey:await crypto.subtle.exportKey("jwk",e.publicKey),privateKey:await crypto.subtle.exportKey("jwk",e.privateKey)}}async function v_(r,e,t){let n=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["sign"]);t?.signal?.throwIfAborted();let i=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}async function A_(r,e,t,n){let i=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let o=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,e,t.subarray());return n?.signal?.throwIfAborted(),o}var mK=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),gK=Uint8Array.from([6,5,43,129,4,0,34]),yK=Uint8Array.from([6,5,43,129,4,0,35]),E_={ext:!0,kty:"EC",crv:"P-256"},S_={ext:!0,kty:"EC",crv:"P-384"},__={ext:!0,kty:"EC",crv:"P-521"},Nf=32,Bf=48,Lf=66;function C_(r){let e=Di(r);return P7(e)}function P7(r){let e=r[1],t=z(e,"base64url"),n=r[2][1][0],i=1,o,s;if(e.byteLength===Nf)return o=z(n.subarray(i,i+Nf),"base64url"),s=z(n.subarray(i+Nf),"base64url"),new ml({...E_,key_ops:["sign"],d:t,x:o,y:s});if(e.byteLength===Bf)return o=z(n.subarray(i,i+Bf),"base64url"),s=z(n.subarray(i+Bf),"base64url"),new ml({...S_,key_ops:["sign"],d:t,x:o,y:s});if(e.byteLength===Lf)return o=z(n.subarray(i,i+Lf),"base64url"),s=z(n.subarray(i+Lf),"base64url"),new ml({...__,key_ops:["sign"],d:t,x:o,y:s});throw new K(`Private key length was wrong length, got ${e.byteLength}, expected 32, 48 or 66`)}function R7(r){let e=Di(r);return T_(e)}function T_(r){let e=r[1][1][0],t=1,n,i;if(e.byteLength===Nf*2+1)return n=z(e.subarray(t,t+Nf),"base64url"),i=z(e.subarray(t+Nf),"base64url"),new pl({...E_,key_ops:["verify"],x:n,y:i});if(e.byteLength===Bf*2+1)return n=z(e.subarray(t,t+Bf),"base64url"),i=z(e.subarray(t+Bf),"base64url"),new pl({...S_,key_ops:["verify"],x:n,y:i});if(e.byteLength===Lf*2+1)return n=z(e.subarray(t,t+Lf),"base64url"),i=z(e.subarray(t+Lf),"base64url"),new pl({...__,key_ops:["verify"],x:n,y:i});throw new K(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function I_(r){return lo([yn(Uint8Array.from([1])),g_(D(r.d??"","base64url")),lo([P_(r.crv)],160),lo([bp(new pe(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function k_(r){return lo([yn(Uint8Array.from([1])),lo([P_(r.crv)],160),lo([bp(new pe(Uint8Array.from([4]),D(r.x??"","base64url"),D(r.y??"","base64url")))],161)]).subarray()}function P_(r){if(r==="P-256")return mK;if(r==="P-384")return gK;if(r==="P-521")return yK;throw new K(`Invalid curve ${r}`)}async function R_(r="P-256"){let e=await b_(r);return new ml(e.privateKey)}var pl=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=k_(this.jwk)),this._raw}toMultihash(){return lr.digest(ur(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}async verify(e,t,n){return A_(this.jwk,t,e,n)}},ml=class{type="ECDSA";jwk;publicKey;_raw;constructor(e){this.jwk=e,this.publicKey=new pl({crv:e.crv,ext:e.ext,key_ops:["verify"],kty:"EC",x:e.x,y:e.y})}get raw(){return this._raw==null&&(this._raw=I_(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}async sign(e,t){return v_(this.jwk,e,t)}};var gl=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Os(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function uo(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function Nr(r,...e){if(!Os(r))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(r.length))throw new Error("Uint8Array expected of length "+e+", got length="+r.length)}function Ns(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");uo(r.outputLen),uo(r.blockLen)}function Uf(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function O_(r,e){Nr(r);let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function rn(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function yl(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function fo(r,e){return r<<32-e|r>>>e}function zg(r,e){return r<<e|r>>>32-e>>>0}var N_=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",wK=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Oi(r){if(Nr(r),N_)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=wK[r[t]];return e}var Ds={_0:48,_9:57,A:65,F:70,a:97,f:102};function D_(r){if(r>=Ds._0&&r<=Ds._9)return r-Ds._0;if(r>=Ds.A&&r<=Ds.F)return r-(Ds.A-10);if(r>=Ds.a&&r<=Ds.f)return r-(Ds.a-10)}function wl(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(N_)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let i=0,o=0;i<t;i++,o+=2){let s=D_(r.charCodeAt(o)),a=D_(r.charCodeAt(o+1));if(s===void 0||a===void 0){let c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}n[i]=s*16+a}return n}var xK=async()=>{};async function B_(r,e,t){let n=Date.now();for(let i=0;i<r;i++){t(i);let o=Date.now()-n;o>=0&&o<e||(await xK(),n+=o)}}function qg(r){if(typeof r!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(r))}function Ka(r){return typeof r=="string"&&(r=qg(r)),Nr(r),r}function D7(r){return typeof r=="string"&&(r=qg(r)),Nr(r),r}function wn(...r){let e=0;for(let n=0;n<r.length;n++){let i=r[n];Nr(i),e+=i.length}let t=new Uint8Array(e);for(let n=0,i=0;n<r.length;n++){let o=r[n];t.set(o,i),i+=o.length}return t}function L_(r,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(r,e)}var Mf=class{};function vp(r){let e=n=>r().update(Ka(n)).digest(),t=r();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>r(),e}function Xo(r=32){if(gl&&typeof gl.getRandomValues=="function")return gl.getRandomValues(new Uint8Array(r));if(gl&&typeof gl.randomBytes=="function")return Uint8Array.from(gl.randomBytes(r));throw new Error("crypto.getRandomValues must be defined")}function bK(r,e,t,n){if(typeof r.setBigUint64=="function")return r.setBigUint64(e,t,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(t>>i&o),a=Number(t&o),c=n?4:0,l=n?0:4;r.setUint32(e+c,s,n),r.setUint32(e+l,a,n)}function jg(r,e,t){return r&e^~r&t}function Wg(r,e,t){return r&e^r&t^e&t}var xl=class extends Mf{constructor(e,t,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=yl(this.buffer)}update(e){Uf(this),e=Ka(e),Nr(e);let{view:t,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let c=yl(e);for(;i<=o-s;s+=i)this.process(c,s);continue}n.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Uf(this),O_(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,rn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)t[f]=0;bK(n,i-8,BigInt(this.length*8),o),this.process(n,0);let a=yl(e),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],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:n,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Bs=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Br=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Gg=BigInt(4294967295),M_=BigInt(32);function vK(r,e=!1){return e?{h:Number(r&Gg),l:Number(r>>M_&Gg)}:{h:Number(r>>M_&Gg)|0,l:Number(r&Gg)|0}}function U_(r,e=!1){let t=r.length,n=new Uint32Array(t),i=new Uint32Array(t);for(let o=0;o<t;o++){let{h:s,l:a}=vK(r[o],e);[n[o],i[o]]=[s,a]}return[n,i]}var O7=(r,e,t)=>r>>>t,N7=(r,e,t)=>r<<32-t|e>>>t,bl=(r,e,t)=>r>>>t|e<<32-t,vl=(r,e,t)=>r<<32-t|e>>>t,Ap=(r,e,t)=>r<<64-t|e>>>t-32,Ep=(r,e,t)=>r>>>t-32|e<<64-t;function Yo(r,e,t,n){let i=(e>>>0)+(n>>>0);return{h:r+t+(i/2**32|0)|0,l:i|0}}var F_=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),$_=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,H_=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),V_=(r,e,t,n,i)=>e+t+n+i+(r/2**32|0)|0,K_=(r,e,t,n,i)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(i>>>0),z_=(r,e,t,n,i,o)=>e+t+n+i+o+(r/2**32|0)|0;var EK=Uint32Array.from([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]),za=new Uint32Array(64),Xg=class extends xl{constructor(e=32){super(64,e,8,!1),this.A=Bs[0]|0,this.B=Bs[1]|0,this.C=Bs[2]|0,this.D=Bs[3]|0,this.E=Bs[4]|0,this.F=Bs[5]|0,this.G=Bs[6]|0,this.H=Bs[7]|0}get(){let{A:e,B:t,C:n,D:i,E:o,F:s,G:a,H:c}=this;return[e,t,n,i,o,s,a,c]}set(e,t,n,i,o,s,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)za[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){let d=za[f-15],h=za[f-2],m=fo(d,7)^fo(d,18)^d>>>3,g=fo(h,17)^fo(h,19)^h>>>10;za[f]=g+za[f-7]+m+za[f-16]|0}let{A:n,B:i,C:o,D:s,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){let d=fo(a,6)^fo(a,11)^fo(a,25),h=u+d+jg(a,c,l)+EK[f]+za[f]|0,g=(fo(n,2)^fo(n,13)^fo(n,22))+Wg(n,i,o)|0;u=l,l=c,c=a,a=s+h|0,s=o,o=i,i=n,n=h+g|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+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,i,o,s,a,c,l,u)}roundClean(){rn(za)}destroy(){this.set(0,0,0,0,0,0,0,0),rn(this.buffer)}};var q_=U_(["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))),SK=q_[0],_K=q_[1],qa=new Uint32Array(80),ja=new Uint32Array(80),Yg=class extends xl{constructor(e=64){super(128,e,16,!1),this.Ah=Br[0]|0,this.Al=Br[1]|0,this.Bh=Br[2]|0,this.Bl=Br[3]|0,this.Ch=Br[4]|0,this.Cl=Br[5]|0,this.Dh=Br[6]|0,this.Dl=Br[7]|0,this.Eh=Br[8]|0,this.El=Br[9]|0,this.Fh=Br[10]|0,this.Fl=Br[11]|0,this.Gh=Br[12]|0,this.Gl=Br[13]|0,this.Hh=Br[14]|0,this.Hl=Br[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:i,Ch:o,Cl:s,Dh:a,Dl:c,Eh:l,El:u,Fh:f,Fl:d,Gh:h,Gl:m,Hh:g,Hl:w}=this;return[e,t,n,i,o,s,a,c,l,u,f,d,h,m,g,w]}set(e,t,n,i,o,s,a,c,l,u,f,d,h,m,g,w){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=f|0,this.Fl=d|0,this.Gh=h|0,this.Gl=m|0,this.Hh=g|0,this.Hl=w|0}process(e,t){for(let A=0;A<16;A++,t+=4)qa[A]=e.getUint32(t),ja[A]=e.getUint32(t+=4);for(let A=16;A<80;A++){let S=qa[A-15]|0,M=ja[A-15]|0,F=bl(S,M,1)^bl(S,M,8)^O7(S,M,7),N=vl(S,M,1)^vl(S,M,8)^N7(S,M,7),R=qa[A-2]|0,_=ja[A-2]|0,$=bl(R,_,19)^Ap(R,_,61)^O7(R,_,6),V=vl(R,_,19)^Ep(R,_,61)^N7(R,_,6),H=H_(N,V,ja[A-7],ja[A-16]),E=V_(H,F,$,qa[A-7],qa[A-16]);qa[A]=E|0,ja[A]=H|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:a,Cl:c,Dh:l,Dl:u,Eh:f,El:d,Fh:h,Fl:m,Gh:g,Gl:w,Hh:x,Hl:v}=this;for(let A=0;A<80;A++){let S=bl(f,d,14)^bl(f,d,18)^Ap(f,d,41),M=vl(f,d,14)^vl(f,d,18)^Ep(f,d,41),F=f&h^~f&g,N=d&m^~d&w,R=K_(v,M,N,_K[A],ja[A]),_=z_(R,x,S,F,SK[A],qa[A]),$=R|0,V=bl(n,i,28)^Ap(n,i,34)^Ap(n,i,39),H=vl(n,i,28)^Ep(n,i,34)^Ep(n,i,39),E=n&o^n&a^o&a,T=i&s^i&c^s&c;x=g|0,v=w|0,g=h|0,w=m|0,h=f|0,m=d|0,{h:f,l:d}=Yo(l|0,u|0,_|0,$|0),l=a|0,u=c|0,a=o|0,c=s|0,o=n|0,s=i|0;let C=F_($,H,T);n=$_(C,_,V,E),i=C|0}({h:n,l:i}=Yo(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=Yo(this.Bh|0,this.Bl|0,o|0,s|0),{h:a,l:c}=Yo(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Yo(this.Dh|0,this.Dl|0,l|0,u|0),{h:f,l:d}=Yo(this.Eh|0,this.El|0,f|0,d|0),{h,l:m}=Yo(this.Fh|0,this.Fl|0,h|0,m|0),{h:g,l:w}=Yo(this.Gh|0,this.Gl|0,g|0,w|0),{h:x,l:v}=Yo(this.Hh|0,this.Hl|0,x|0,v|0),this.set(n,i,o,s,a,c,l,u,f,d,h,m,g,w,x,v)}roundClean(){rn(qa,ja)}destroy(){rn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Qg=vp(()=>new Xg);var Zg=vp(()=>new Yg);var M7=BigInt(0),L7=BigInt(1);function Ls(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}"`;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function ii(r,e,t=""){let n=Os(r),i=r?.length,o=e!==void 0;if(!n||o&&i!==e){let s=t&&`"${t}" `,a=o?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return r}function Sp(r){let e=r.toString(16);return e.length&1?"0"+e:e}function j_(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?M7:BigInt("0x"+r)}function Ff(r){return j_(Oi(r))}function Ni(r){return Nr(r),j_(Oi(Uint8Array.from(r).reverse()))}function Jg(r,e){return wl(r.toString(16).padStart(e*2,"0"))}function _p(r,e){return Jg(r,e).reverse()}function at(r,e,t){let n;if(typeof e=="string")try{n=wl(e)}catch(o){throw new Error(r+" must be hex string or Uint8Array, cause: "+o)}else if(Os(e))n=Uint8Array.from(e);else throw new Error(r+" must be hex string or Uint8Array");let i=n.length;if(typeof t=="number"&&i!==t)throw new Error(r+" of length "+t+" expected, got "+i);return n}function W_(r,e){if(r.length!==e.length)return!1;let t=0;for(let n=0;n<r.length;n++)t|=r[n]^e[n];return t===0}function U7(r){return Uint8Array.from(r)}var B7=r=>typeof r=="bigint"&&M7<=r;function G_(r,e,t){return B7(r)&&B7(e)&&B7(t)&&e<=r&&r<t}function Wa(r,e,t,n){if(!G_(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function e2(r){let e;for(e=0;r>M7;r>>=L7,e+=1);return e}var Ga=r=>(L7<<BigInt(r))-L7;function X_(r,e,t){if(typeof r!="number"||r<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let n=h=>new Uint8Array(h),i=h=>Uint8Array.of(h),o=n(r),s=n(r),a=0,c=()=>{o.fill(1),s.fill(0),a=0},l=(...h)=>t(s,o,...h),u=(h=n(0))=>{s=l(i(0),h),o=l(),h.length!==0&&(s=l(i(1),h),o=l())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0,m=[];for(;h<e;){o=l();let g=o.slice();m.push(g),h+=o.length}return wn(...m)};return(h,m)=>{c(),u(h);let g;for(;!(g=m(f()));)u();return c(),g}}function Qo(r,e,t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(i,o,s){let a=r[i];if(s&&a===void 0)return;let c=typeof a;if(c!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}Object.entries(e).forEach(([i,o])=>n(i,o,!1)),Object.entries(t).forEach(([i,o])=>n(i,o,!0))}var F7=()=>{throw new Error("not implemented")};function $f(r){let e=new WeakMap;return(t,...n)=>{let i=e.get(t);if(i!==void 0)return i;let o=r(t,...n);return e.set(t,o),o}}var xn=BigInt(0),_r=BigInt(1),Al=BigInt(2),Z_=BigInt(3),J_=BigInt(4),eC=BigInt(5),CK=BigInt(7),tC=BigInt(8),TK=BigInt(9),rC=BigInt(16);function Rt(r,e){let t=r%e;return t>=xn?t:e+t}function Dt(r,e,t){let n=r;for(;e-- >xn;)n*=n,n%=t;return n}function Y_(r,e){if(r===xn)throw new Error("invert: expected non-zero number");if(e<=xn)throw new Error("invert: expected positive modulus, got "+e);let t=Rt(r,e),n=e,i=xn,o=_r,s=_r,a=xn;for(;t!==xn;){let l=n/t,u=n%t,f=i-s*l,d=o-a*l;n=t,t=u,i=s,o=a,s=f,a=d}if(n!==_r)throw new Error("invert: does not exist");return Rt(i,e)}function $7(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function nC(r,e){let t=(r.ORDER+_r)/J_,n=r.pow(e,t);return $7(r,n,e),n}function IK(r,e){let t=(r.ORDER-eC)/tC,n=r.mul(e,Al),i=r.pow(n,t),o=r.mul(e,i),s=r.mul(r.mul(o,Al),i),a=r.mul(o,r.sub(s,r.ONE));return $7(r,a,e),a}function kK(r){let e=oi(r),t=iC(r),n=t(e,e.neg(e.ONE)),i=t(e,n),o=t(e,e.neg(n)),s=(r+CK)/rC;return(a,c)=>{let l=a.pow(c,s),u=a.mul(l,n),f=a.mul(l,i),d=a.mul(l,o),h=a.eql(a.sqr(u),c),m=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(d,f,m);let g=a.eql(a.sqr(u),c),w=a.cmov(l,u,g);return $7(a,w,c),w}}function iC(r){if(r<Z_)throw new Error("sqrt is not defined for small field");let e=r-_r,t=0;for(;e%Al===xn;)e/=Al,t++;let n=Al,i=oi(r);for(;Q_(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return nC;let o=i.pow(n,e),s=(e+_r)/Al;return function(c,l){if(c.is0(l))return l;if(Q_(c,l)!==1)throw new Error("Cannot find square root");let u=t,f=c.mul(c.ONE,o),d=c.pow(l,e),h=c.pow(l,s);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let m=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(m++,g=c.sqr(g),m===u)throw new Error("Cannot find square root");let w=_r<<BigInt(u-m-1),x=c.pow(f,w);u=m,f=c.sqr(x),d=c.mul(d,f),h=c.mul(h,x)}return h}}function PK(r){return r%J_===Z_?nC:r%tC===eC?IK:r%rC===TK?kK(r):iC(r)}var Ms=(r,e)=>(Rt(r,e)&_r)===_r,RK=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function H7(r){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=RK.reduce((n,i)=>(n[i]="function",n),e);return Qo(r,t),r}function DK(r,e,t){if(t<xn)throw new Error("invalid exponent, negatives unsupported");if(t===xn)return r.ONE;if(t===_r)return e;let n=r.ONE,i=e;for(;t>xn;)t&_r&&(n=r.mul(n,i)),i=r.sqr(i),t>>=_r;return n}function Cp(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),i=e.reduce((s,a,c)=>r.is0(a)?s:(n[c]=s,r.mul(s,a)),r.ONE),o=r.inv(i);return e.reduceRight((s,a,c)=>r.is0(a)?s:(n[c]=r.mul(s,n[c]),r.mul(s,a)),o),n}function Q_(r,e){let t=(r.ORDER-_r)/Al,n=r.pow(e,t),i=r.eql(n,r.ONE),o=r.eql(n,r.ZERO),s=r.eql(n,r.neg(r.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function t2(r,e){e!==void 0&&uo(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function oi(r,e,t=!1,n={}){if(r<=xn)throw new Error("invalid field: expected ORDER > 0, got "+r);let i,o,s=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let d=e;d.BITS&&(i=d.BITS),d.sqrt&&(o=d.sqrt),typeof d.isLE=="boolean"&&(t=d.isLE),typeof d.modFromBytes=="boolean"&&(s=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(o=n.sqrt);let{nBitLength:c,nByteLength:l}=t2(r,i);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u,f=Object.freeze({ORDER:r,isLE:t,BITS:c,BYTES:l,MASK:Ga(c),ZERO:xn,ONE:_r,allowedLengths:a,create:d=>Rt(d,r),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return xn<=d&&d<r},is0:d=>d===xn,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&_r)===_r,neg:d=>Rt(-d,r),eql:(d,h)=>d===h,sqr:d=>Rt(d*d,r),add:(d,h)=>Rt(d+h,r),sub:(d,h)=>Rt(d-h,r),mul:(d,h)=>Rt(d*h,r),pow:(d,h)=>DK(f,d,h),div:(d,h)=>Rt(d*Y_(h,r),r),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Y_(d,r),sqrt:o||(d=>(u||(u=PK(r)),u(f,d))),toBytes:d=>t?_p(d,l):Jg(d,l),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);let g=new Uint8Array(l);g.set(d,t?0:g.length-d.length),d=g}if(d.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+d.length);let m=t?Ni(d):Ff(d);if(s&&(m=Rt(m,r)),!h&&!f.isValid(m))throw new Error("invalid field element: outside of range 0..ORDER");return m},invertBatch:d=>Cp(f,d),cmov:(d,h,m)=>m?h:d});return Object.freeze(f)}function oC(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function V7(r){let e=oC(r);return e+Math.ceil(e/2)}function K7(r,e,t=!1){let n=r.length,i=oC(e),o=V7(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=t?Ni(r):Ff(r),a=Rt(s,e-_r)+_r;return t?_p(a,i):Jg(a,i)}var Hf=BigInt(0),El=BigInt(1);function Tp(r,e){let t=e.negate();return r?t:e}function Us(r,e){let t=Cp(r.Fp,e.map(n=>n.Z));return e.map((n,i)=>r.fromAffine(n.toAffine(t[i])))}function lC(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function z7(r,e){lC(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),i=2**r,o=Ga(r),s=BigInt(r);return{windows:t,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function sC(r,e,t){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=t,a=Number(r&i),c=r>>s;a>n&&(a-=o,c+=El);let l=e*n,u=l+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:d,isNegF:h,offsetF:l}}function OK(r,e){if(!Array.isArray(r))throw new Error("array expected");r.forEach((t,n)=>{if(!(t instanceof e))throw new Error("invalid point at index "+n)})}function NK(r,e){if(!Array.isArray(r))throw new Error("array of scalars expected");r.forEach((t,n)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+n)})}var q7=new WeakMap,uC=new WeakMap;function j7(r){return uC.get(r)||1}function aC(r){if(r!==Hf)throw new Error("invalid wNAF")}var Vf=class{constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,n=this.ZERO){let i=e;for(;t>Hf;)t&El&&(n=n.add(i)),i=i.double(),t>>=El;return n}precomputeWindow(e,t){let{windows:n,windowSize:i}=z7(t,this.bits),o=[],s=e,a=s;for(let c=0;c<n;c++){a=s,o.push(a);for(let l=1;l<i;l++)a=a.add(s),o.push(a);s=a.double()}return o}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=z7(e,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:d,offsetF:h}=sC(n,a,s);n=c,u?o=o.add(Tp(d,t[h])):i=i.add(Tp(f,t[l]))}return aC(n),{p:i,f:o}}wNAFUnsafe(e,t,n,i=this.ZERO){let o=z7(e,this.bits);for(let s=0;s<o.windows&&n!==Hf;s++){let{nextN:a,offset:c,isZero:l,isNeg:u}=sC(n,s,o);if(n=a,!l){let f=t[c];i=i.add(u?f.negate():f)}}return aC(n),i}getPrecomputes(e,t,n){let i=q7.get(t);return i||(i=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(i=n(i)),q7.set(t,i))),i}cached(e,t,n){let i=j7(e);return this.wNAF(i,this.getPrecomputes(i,e,n),t)}unsafe(e,t,n,i){let o=j7(e);return o===1?this._unsafeLadder(e,t,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),t,i)}createCache(e,t){lC(t,this.bits),uC.set(e,t),q7.delete(e)}hasCache(e){return j7(e)!==1}};function fC(r,e,t,n){let i=e,o=r.ZERO,s=r.ZERO;for(;t>Hf||n>Hf;)t&El&&(o=o.add(i)),n&El&&(s=s.add(i)),i=i.double(),t>>=El,n>>=El;return{p1:o,p2:s}}function Kf(r,e,t,n){OK(t,r),NK(n,e);let i=t.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=r.ZERO,a=e2(BigInt(i)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ga(c),u=new Array(Number(l)+1).fill(s),f=Math.floor((e.BITS-1)/c)*c,d=s;for(let h=f;h>=0;h-=c){u.fill(s);for(let g=0;g<o;g++){let w=n[g],x=Number(w>>BigInt(h)&l);u[x]=u[x].add(t[g])}let m=s;for(let g=u.length-1,w=s;g>0;g--)w=w.add(u[g]),m=m.add(w);if(d=d.add(m),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function cC(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return H7(e),e}else return oi(r,{isLE:t})}function r2(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let c of["p","n","h"]){let l=e[c];if(!(typeof l=="bigint"&&l>Hf))throw new Error(`CURVE.${c} must be positive bigint`)}let i=cC(e.p,t.Fp,n),o=cC(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var Xa=BigInt(0),Cr=BigInt(1),W7=BigInt(2),BK=BigInt(8);function LK(r,e,t,n){let i=r.sqr(t),o=r.sqr(n),s=r.add(r.mul(e.a,i),o),a=r.add(r.ONE,r.mul(e.d,r.mul(i,o)));return r.eql(s,a)}function MK(r,e={}){let t=r2("edwards",r,e,e.FpFnLE),{Fp:n,Fn:i}=t,o=t.CURVE,{h:s}=o;Qo(e,{},{uvRatio:"function"});let a=W7<<BigInt(i.BYTES*8)-Cr,c=w=>n.create(w),l=e.uvRatio||((w,x)=>{try{return{isValid:!0,value:n.sqrt(n.div(w,x))}}catch{return{isValid:!1,value:Xa}}});if(!LK(n,o,o.Gx,o.Gy))throw new Error("bad curve params: generator point");function u(w,x,v=!1){let A=v?Cr:Xa;return Wa("coordinate "+w,x,A,a),x}function f(w){if(!(w instanceof m))throw new Error("ExtendedPoint expected")}let d=$f((w,x)=>{let{X:v,Y:A,Z:S}=w,M=w.is0();x==null&&(x=M?BK:n.inv(S));let F=c(v*x),N=c(A*x),R=n.mul(S,x);if(M)return{x:Xa,y:Cr};if(R!==Cr)throw new Error("invZ was invalid");return{x:F,y:N}}),h=$f(w=>{let{a:x,d:v}=o;if(w.is0())throw new Error("bad point: ZERO");let{X:A,Y:S,Z:M,T:F}=w,N=c(A*A),R=c(S*S),_=c(M*M),$=c(_*_),V=c(N*x),H=c(_*c(V+R)),E=c($+c(v*c(N*R)));if(H!==E)throw new Error("bad point: equation left != right (1)");let T=c(A*S),C=c(M*F);if(T!==C)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(x,v,A,S){this.X=u("x",x),this.Y=u("y",v),this.Z=u("z",A,!0),this.T=u("t",S),Object.freeze(this)}static CURVE(){return o}static fromAffine(x){if(x instanceof m)throw new Error("extended point not allowed");let{x:v,y:A}=x||{};return u("x",v),u("y",A),new m(v,A,Cr,c(v*A))}static fromBytes(x,v=!1){let A=n.BYTES,{a:S,d:M}=o;x=U7(ii(x,A,"point")),Ls(v,"zip215");let F=U7(x),N=x[A-1];F[A-1]=N&-129;let R=Ni(F),_=v?a:n.ORDER;Wa("point.y",R,Xa,_);let $=c(R*R),V=c($-Cr),H=c(M*$-S),{isValid:E,value:T}=l(V,H);if(!E)throw new Error("bad point: invalid y coordinate");let C=(T&Cr)===Cr,O=(N&128)!==0;if(!v&&T===Xa&&O)throw new Error("bad point: x=0 and x_0=1");return O!==C&&(T=c(-T)),m.fromAffine({x:T,y:R})}static fromHex(x,v=!1){return m.fromBytes(at("point",x),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,v=!0){return g.createCache(this,x),v||this.multiply(W7),this}assertValidity(){h(this)}equals(x){f(x);let{X:v,Y:A,Z:S}=this,{X:M,Y:F,Z:N}=x,R=c(v*N),_=c(M*S),$=c(A*N),V=c(F*S);return R===_&&$===V}is0(){return this.equals(m.ZERO)}negate(){return new m(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:x}=o,{X:v,Y:A,Z:S}=this,M=c(v*v),F=c(A*A),N=c(W7*c(S*S)),R=c(x*M),_=v+A,$=c(c(_*_)-M-F),V=R+F,H=V-N,E=R-F,T=c($*H),C=c(V*E),O=c($*E),j=c(H*V);return new m(T,C,j,O)}add(x){f(x);let{a:v,d:A}=o,{X:S,Y:M,Z:F,T:N}=this,{X:R,Y:_,Z:$,T:V}=x,H=c(S*R),E=c(M*_),T=c(N*A*V),C=c(F*$),O=c((S+M)*(R+_)-H-E),j=C-T,Q=C+T,U=c(E-v*H),Z=c(O*j),te=c(Q*U),q=c(O*U),Te=c(j*Q);return new m(Z,te,Te,q)}subtract(x){return this.add(x.negate())}multiply(x){if(!i.isValidNot0(x))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:A}=g.cached(this,x,S=>Us(m,S));return Us(m,[v,A])[0]}multiplyUnsafe(x,v=m.ZERO){if(!i.isValid(x))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return x===Xa?m.ZERO:this.is0()||x===Cr?this:g.unsafe(this,x,A=>Us(m,A),v)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return g.unsafe(this,o.n).is0()}toAffine(x){return d(this,x)}clearCofactor(){return s===Cr?this:this.multiplyUnsafe(s)}toBytes(){let{x,y:v}=this.toAffine(),A=n.toBytes(v);return A[A.length-1]|=x&Cr?128:0,A}toHex(){return Oi(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(x){return Us(m,x)}static msm(x,v){return Kf(m,i,x,v)}_setWindowSize(x){this.precompute(x)}toRawBytes(){return this.toBytes()}}m.BASE=new m(o.Gx,o.Gy,Cr,c(o.Gx*o.Gy)),m.ZERO=new m(Xa,Cr,Cr,Xa),m.Fp=n,m.Fn=i;let g=new Vf(m,i.BITS);return m.BASE.precompute(8),m}var n2=class{constructor(e){this.ep=e}static fromBytes(e){F7()}static fromHex(e){F7()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return Oi(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,t){return this.init(this.ep.precompute(e,t))}toRawBytes(){return this.toBytes()}};function UK(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Qo(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:i,Fp:o,Fn:s}=r,a=t.randomBytes||Xo,c=t.adjustScalarBytes||(_=>_),l=t.domain||((_,$,V)=>{if(Ls(V,"phflag"),$.length||V)throw new Error("Contexts/pre-hash are not supported");return _});function u(_){return s.create(Ni(_))}function f(_){let $=A.secretKey;_=at("private key",_,$);let V=at("hashed private key",e(_),2*$),H=c(V.slice(0,$)),E=V.slice($,2*$),T=u(H);return{head:H,prefix:E,scalar:T}}function d(_){let{head:$,prefix:V,scalar:H}=f(_),E=i.multiply(H),T=E.toBytes();return{head:$,prefix:V,scalar:H,point:E,pointBytes:T}}function h(_){return d(_).pointBytes}function m(_=Uint8Array.of(),...$){let V=wn(...$);return u(e(l(V,at("context",_),!!n)))}function g(_,$,V={}){_=at("message",_),n&&(_=n(_));let{prefix:H,scalar:E,pointBytes:T}=d($),C=m(V.context,H,_),O=i.multiply(C).toBytes(),j=m(V.context,O,T,_),Q=s.create(C+j*E);if(!s.isValid(Q))throw new Error("sign failed: invalid s");let U=wn(O,s.toBytes(Q));return ii(U,A.signature,"result")}let w={zip215:!0};function x(_,$,V,H=w){let{context:E,zip215:T}=H,C=A.signature;_=at("signature",_,C),$=at("message",$),V=at("publicKey",V,A.publicKey),T!==void 0&&Ls(T,"zip215"),n&&($=n($));let O=C/2,j=_.subarray(0,O),Q=Ni(_.subarray(O,C)),U,Z,te;try{U=r.fromBytes(V,T),Z=r.fromBytes(j,T),te=i.multiplyUnsafe(Q)}catch{return!1}if(!T&&U.isSmallOrder())return!1;let q=m(E,Z.toBytes(),U.toBytes(),$);return Z.add(U.multiplyUnsafe(q)).subtract(te).clearCofactor().is0()}let v=o.BYTES,A={secretKey:v,publicKey:v,signature:2*v,seed:v};function S(_=a(A.seed)){return ii(_,A.seed,"seed")}function M(_){let $=R.randomSecretKey(_);return{secretKey:$,publicKey:h($)}}function F(_){return Os(_)&&_.length===s.BYTES}function N(_,$){try{return!!r.fromBytes(_,$)}catch{return!1}}let R={getExtendedPublicKey:d,randomSecretKey:S,isValidSecretKey:F,isValidPublicKey:N,toMontgomery(_){let{y:$}=r.fromBytes(_),V=A.publicKey,H=V===32;if(!H&&V!==57)throw new Error("only defined for 25519 and 448");let E=H?o.div(Cr+$,Cr-$):o.div($-Cr,$+Cr);return o.toBytes(E)},toMontgomerySecret(_){let $=A.secretKey;ii(_,$);let V=e(_.subarray(0,$));return c(V).subarray(0,$)},randomPrivateKey:S,precompute(_=8,$=r.BASE){return $.precompute(_,!1)}};return Object.freeze({keygen:M,getPublicKey:h,sign:g,verify:x,utils:R,Point:r,lengths:A})}function FK(r){let e={a:r.a,d:r.d,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=oi(e.n,r.nBitLength,!0),i={Fp:t,Fn:n,uvRatio:r.uvRatio},o={randomBytes:r.randomBytes,adjustScalarBytes:r.adjustScalarBytes,domain:r.domain,prehash:r.prehash,mapToCurve:r.mapToCurve};return{CURVE:e,curveOpts:i,hash:r.hash,eddsaOpts:o}}function $K(r,e){let t=e.Point;return Object.assign({},e,{ExtendedPoint:t,CURVE:r,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function dC(r){let{CURVE:e,curveOpts:t,hash:n,eddsaOpts:i}=FK(r),o=MK(e,t),s=UK(o,n,i);return $K(r,s)}var Ip=BigInt(0),zf=BigInt(1),i2=BigInt(2);function HK(r){return Qo(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function hC(r){let e=HK(r),{P:t,type:n,adjustScalarBytes:i,powPminus2:o,randomBytes:s}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=s||Xo,l=a?255:448,u=a?32:56,f=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?i2**BigInt(254):i2**BigInt(447),m=a?BigInt(8)*i2**BigInt(251)-zf:BigInt(4)*i2**BigInt(445)-zf,g=h+m+zf,w=E=>Rt(E,t),x=v(f);function v(E){return _p(w(E),u)}function A(E){let T=at("u coordinate",E,u);return a&&(T[31]&=127),w(Ni(T))}function S(E){return Ni(i(at("scalar",E,u)))}function M(E,T){let C=R(A(T),S(E));if(C===Ip)throw new Error("invalid private or public key received");return v(C)}function F(E){return M(E,x)}function N(E,T,C){let O=w(E*(T-C));return T=w(T-O),C=w(C+O),{x_2:T,x_3:C}}function R(E,T){Wa("u",E,Ip,t),Wa("scalar",T,h,g);let C=T,O=E,j=zf,Q=Ip,U=E,Z=zf,te=Ip;for(let Te=BigInt(l-1);Te>=Ip;Te--){let Ne=C>>Te&zf;te^=Ne,{x_2:j,x_3:U}=N(te,j,U),{x_2:Q,x_3:Z}=N(te,Q,Z),te=Ne;let se=j+Q,Le=w(se*se),Ke=j-Q,ft=w(Ke*Ke),He=Le-ft,st=U+Z,Ci=U-Z,hn=w(Ci*se),io=w(st*Ke),ug=hn+io,xf=hn-io;U=w(ug*ug),Z=w(O*w(xf*xf)),j=w(Le*ft),Q=w(He*(Le+w(d*He)))}({x_2:j,x_3:U}=N(te,j,U)),{x_2:Q,x_3:Z}=N(te,Q,Z);let q=o(Q);return w(j*q)}let _={secretKey:u,publicKey:u,seed:u},$=(E=c(u))=>(Nr(E,_.seed),E);function V(E){let T=$(E);return{secretKey:T,publicKey:F(T)}}return{keygen:V,getSharedSecret:(E,T)=>M(E,T),getPublicKey:E=>F(E),scalarMult:M,scalarMultBase:F,utils:{randomSecretKey:$,randomPrivateKey:$},GuBytes:x.slice(),lengths:_}}var VK=BigInt(0),$s=BigInt(1),pC=BigInt(2),KK=BigInt(3),zK=BigInt(5),qK=BigInt(8),qf=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),kp={p:qf,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:qK,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function yC(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),i=BigInt(80),o=qf,a=r*r%o*r%o,c=Dt(a,pC,o)*a%o,l=Dt(c,$s,o)*r%o,u=Dt(l,zK,o)*l%o,f=Dt(u,e,o)*u%o,d=Dt(f,t,o)*f%o,h=Dt(d,n,o)*d%o,m=Dt(h,i,o)*h%o,g=Dt(m,i,o)*h%o,w=Dt(g,e,o)*u%o;return{pow_p_5_8:Dt(w,pC,o)*r%o,b2:a}}function wC(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var G7=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Q7(r,e){let t=qf,n=Rt(e*e*e,t),i=Rt(n*n*e,t),o=yC(r*i).pow_p_5_8,s=Rt(r*n*o,t),a=Rt(e*s*s,t),c=s,l=Rt(s*G7,t),u=a===r,f=a===Rt(-r,t),d=a===Rt(-r*G7,t);return u&&(s=c),(f||d)&&(s=l),Ms(s,t)&&(s=Rt(-s,t)),{isValid:u||f,value:s}}var Fs=oi(kp.p,{isLE:!0}),jK=oi(kp.n,{isLE:!0}),WK={...kp,Fp:Fs,hash:Zg,adjustScalarBytes:wC,uvRatio:Q7},Bi=dC(WK);var Pp=(()=>{let r=Fs.ORDER;return hC({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=yC(e);return Rt(Dt(t,KK,r)*n,r)},adjustScalarBytes:wC})})();var X7=G7,GK=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),XK=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),YK=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),QK=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),mC=r=>Q7($s,r),ZK=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Y7=r=>Bi.Point.Fp.create(Ni(r)&ZK);function gC(r){let{d:e}=kp,t=qf,n=x=>Fs.create(x),i=n(X7*r*r),o=n((i+$s)*YK),s=BigInt(-1),a=n((s-e*i)*n(i+e)),{isValid:c,value:l}=Q7(o,a),u=n(l*r);Ms(u,t)||(u=n(-u)),c||(l=u),c||(s=i);let f=n(s*(i-$s)*QK-a),d=l*l,h=n((l+l)*a),m=n(f*GK),g=n($s-d),w=n($s+d);return new Bi.Point(n(h*w),n(g*m),n(m*w),n(h*g))}function JK(r){Nr(r,64);let e=Y7(r.subarray(0,32)),t=gC(e),n=Y7(r.subarray(32,64)),i=gC(n);return new Hs(t.add(i))}var Hs=class r extends n2{constructor(e){super(e)}static fromAffine(e){return new r(Bi.Point.fromAffine(e))}assertSame(e){if(!(e instanceof r))throw new Error("RistrettoPoint expected")}init(e){return new r(e)}static hashToCurve(e){return JK(at("ristrettoHash",e,64))}static fromBytes(e){Nr(e,32);let{a:t,d:n}=kp,i=qf,o=S=>Fs.create(S),s=Y7(e);if(!W_(Fs.toBytes(s),e)||Ms(s,i))throw new Error("invalid ristretto255 encoding 1");let a=o(s*s),c=o($s+t*a),l=o($s-t*a),u=o(c*c),f=o(l*l),d=o(t*n*u-f),{isValid:h,value:m}=mC(o(d*f)),g=o(m*l),w=o(m*g*d),x=o((s+s)*g);Ms(x,i)&&(x=o(-x));let v=o(c*w),A=o(x*v);if(!h||Ms(A,i)||v===VK)throw new Error("invalid ristretto255 encoding 2");return new r(new Bi.Point(x,v,$s,A))}static fromHex(e){return r.fromBytes(at("ristrettoHex",e,32))}static msm(e,t){return Kf(r,Bi.Point.Fn,e,t)}toBytes(){let{X:e,Y:t,Z:n,T:i}=this.ep,o=qf,s=w=>Fs.create(w),a=s(s(n+t)*s(n-t)),c=s(e*t),l=s(c*c),{value:u}=mC(s(a*l)),f=s(u*a),d=s(u*c),h=s(f*d*i),m;if(Ms(i*h,o)){let w=s(t*X7),x=s(e*X7);e=w,t=x,m=s(f*XK)}else m=d;Ms(e*h,o)&&(t=s(-t));let g=s((n-t)*m);return Ms(g,o)&&(g=s(-g)),Fs.toBytes(g)}equals(e){this.assertSame(e);let{X:t,Y:n}=this.ep,{X:i,Y:o}=e.ep,s=l=>Fs.create(l),a=s(t*o)===s(n*i),c=s(n*o)===s(t*i);return a||c}is0(){return this.equals(r.ZERO)}};Hs.BASE=new Hs(Bi.Point.BASE);Hs.ZERO=new Hs(Bi.Point.ZERO);Hs.Fp=Fs;Hs.Fn=jK;var Rp=class extends Error{constructor(e="An error occurred while signing a message"){super(e),this.name="SigningError"}},Dp=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},o2=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var xC={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new o2("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};var fr=xC;var Sl=32,si=64,Z7=32;var jf,bC=(async()=>{try{return await fr.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();function vC(){let r=Bi.utils.randomPrivateKey(),e=Bi.getPublicKey(r);return{privateKey:iz(r,e),publicKey:e}}async function ez(r,e){let t;r.length===si?t=r.subarray(0,32):t=r;let n={crv:"Ed25519",kty:"OKP",x:z(r.subarray(32),"base64url"),d:z(t,"base64url"),ext:!0,key_ops:["sign"]},i=await fr.get().subtle.importKey("jwk",n,{name:"Ed25519"},!0,["sign"]),o=await fr.get().subtle.sign({name:"Ed25519"},i,e instanceof Uint8Array?e:e.subarray());return new Uint8Array(o,0,o.byteLength)}function tz(r,e){let t=r.subarray(0,Z7);return Bi.sign(e instanceof Uint8Array?e:e.subarray(),t)}async function AC(r,e){return jf==null&&(jf=await bC),jf?ez(r,e):tz(r,e)}async function rz(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await fr.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await fr.get().subtle.verify({name:"Ed25519"},n,e,t instanceof Uint8Array?t:t.subarray())}throw new TypeError("WebCrypto does not support SharedArrayBuffer for Ed25519 keys")}function nz(r,e,t){return Bi.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function EC(r,e,t){return jf==null&&(jf=await bC),jf?rz(r,e,t):nz(r,e,t)}function iz(r,e){let t=new Uint8Array(si);for(let n=0;n<Z7;n++)t[n]=r[n],t[Z7+n]=e[n];return t}function Wf(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var Op=class{type="Ed25519";raw;constructor(e){this.raw=Xf(e,Sl)}toMultihash(){return lr.digest(ur(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let i=EC(this.raw,t,e);return Wf(i)?i.then(o=>(n?.signal?.throwIfAborted(),o)):i}},Gf=class{type="Ed25519";raw;publicKey;constructor(e,t){this.raw=Xf(e,si),this.publicKey=new Op(t)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,t){t?.signal?.throwIfAborted();let n=AC(this.raw,e);return Wf(n)?n.then(i=>(t?.signal?.throwIfAborted(),i)):(t?.signal?.throwIfAborted(),n)}};function J7(r){if(r.length>si){r=Xf(r,si+Sl);let n=r.subarray(0,si),i=r.subarray(si,r.length);return new Gf(n,i)}r=Xf(r,si);let e=r.subarray(0,si),t=r.subarray(Sl);return new Gf(e,t)}function ex(r){return r=Xf(r,Sl),new Op(r)}async function _C(){let{privateKey:r,publicKey:e}=vC();return new Gf(r,e)}function Xf(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new K(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var _t;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(_t||(_t={}));var tx;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(tx||(tx={}));(function(r){r.codec=()=>St(tx)})(_t||(_t={}));var Zo;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),_t.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=_t.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Zo||(Zo={}));var Np;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),_t.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.Type=_t.codec().decode(t);break}case 2:{o.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Np||(Np={}));function bn(r){if(isNaN(r)||r<=0)throw new K("random bytes length must be a Number bigger than 0");return Xo(r)}var Lp={};$t(Lp,{MAX_RSA_KEY_SIZE:()=>rx,generateRSAKeyPair:()=>fx,jwkToJWKKeyPair:()=>kC,jwkToPkcs1:()=>cz,jwkToPkix:()=>sx,jwkToRSAPrivateKey:()=>ux,pkcs1MessageToJwk:()=>ix,pkcs1MessageToRSAPrivateKey:()=>s2,pkcs1ToJwk:()=>az,pkcs1ToRSAPrivateKey:()=>ax,pkixMessageToJwk:()=>ox,pkixMessageToRSAPublicKey:()=>lx,pkixToJwk:()=>lz,pkixToRSAPublicKey:()=>cx});var Jo=Qg;var Yf=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=Lp.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return G.createV1(114,this._multihash)}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,t,n){return IC(this.jwk,t,e,n)}},Bp=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=Lp.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,t){return TC(this.jwk,e,t)}};var rx=8192,nx=18,oz=1062,sz=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function az(r){let e=Di(r);return ix(e)}function ix(r){return{n:z(r[1],"base64url"),e:z(r[2],"base64url"),d:z(r[3],"base64url"),p:z(r[4],"base64url"),q:z(r[5],"base64url"),dp:z(r[6],"base64url"),dq:z(r[7],"base64url"),qi:z(r[8],"base64url"),kty:"RSA"}}function cz(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 K("JWK was missing components");return lo([yn(Uint8Array.from([0])),yn(D(r.n,"base64url")),yn(D(r.e,"base64url")),yn(D(r.d,"base64url")),yn(D(r.p,"base64url")),yn(D(r.q,"base64url")),yn(D(r.dp,"base64url")),yn(D(r.dq,"base64url")),yn(D(r.qi,"base64url"))]).subarray()}function lz(r){let e=Di(r,{offset:0});return ox(e)}function ox(r){let e=Di(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function sx(r){if(r.n==null||r.e==null)throw new K("JWK was missing components");return lo([sz,bp(lo([yn(D(r.n,"base64url")),yn(D(r.e,"base64url"))]))]).subarray()}function ax(r){let e=Di(r);return s2(e)}function s2(r){let e=ix(r);return ux(e)}function cx(r,e){if(r.byteLength>=oz)throw new _s("Key size is too large");let t=Di(r,{offset:0});return lx(t,r,e)}function lx(r,e,t){let n=ox(r);if(t==null){let i=Jo(Zo.encode({Type:_t.RSA,Data:e}));t=gn(nx,i)}return new Yf(n,t)}function ux(r){if(RC(r)>rx)throw new K("Key size is too large");let e=kC(r),t=Jo(Zo.encode({Type:_t.RSA,Data:sx(e.publicKey)})),n=gn(nx,t);return new Bp(e.privateKey,new Yf(e.publicKey,n))}async function fx(r){if(r>rx)throw new K("Key size is too large");let e=await PC(r),t=Jo(Zo.encode({Type:_t.RSA,Data:sx(e.publicKey)})),n=gn(nx,t);return new Bp(e.privateKey,new Yf(e.publicKey,n))}function kC(r){if(r==null)throw new K("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function PC(r,e){let t=await fr.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:r,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]);e?.signal?.throwIfAborted();let n=await uz(t,e);return{privateKey:n[0],publicKey:n[1]}}async function TC(r,e,t){let n=await fr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let i=await fr.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(i,0,i.byteLength)}async function IC(r,e,t,n){let i=await fr.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let o=await fr.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},i,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),o}async function uz(r,e){if(r.privateKey==null||r.publicKey==null)throw new K("Private and public key are required");let t=await Promise.all([fr.get().subtle.exportKey("jwk",r.privateKey),fr.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function RC(r){if(r.kty!=="RSA")throw new K("invalid key type");if(r.n==null)throw new K("invalid key modulus");return D(r.n,"base64url").length*8}var a2=class extends Mf{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,Ns(e);let n=Ka(t);if(this.iHash=e.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 i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),rn(o)}update(e){return Uf(this),this.iHash.update(e),this}digestInto(e){Uf(this),Nr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ya=(r,e,t)=>new a2(r,e).update(t).digest();Ya.create=(r,e)=>new a2(r,e);var DC=(r,e)=>(r+(r>=0?e:-e)/OC)/e;function fz(r,e,t){let[[n,i],[o,s]]=e,a=DC(s*r,t),c=DC(-i*r,t),l=r-a*n-c*o,u=-a*i-c*s,f=l<Ks,d=u<Ks;f&&(l=-l),d&&(u=-u);let h=Ga(Math.ceil(e2(t)/2))+Zf;if(l<Ks||l>=h||u<Ks||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:d,k2:u}}function hx(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function dx(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ls(t.lowS,"lowS"),Ls(t.prehash,"prehash"),t.format!==void 0&&hx(t.format),t}var px=class extends Error{constructor(e=""){super(e)}},Vs={Err:px,_tlv:{encode:(r,e)=>{let{Err:t}=Vs;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,i=Sp(n);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=n>127?Sp(i.length/2|128):"";return Sp(r)+o+i+e},decode(r,e){let{Err:t}=Vs,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let c=i&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");let l=e.subarray(n,n+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of l)s=s<<8|u;if(n+=c,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+s)}}},_int:{encode(r){let{Err:e}=Vs;if(r<Ks)throw new e("integer: negative integers are not allowed");let t=Sp(r);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(r){let{Err:e}=Vs;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ff(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Vs,i=at("signature",r),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,o),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Vs,n=e.encode(2,t.encode(r.r)),i=e.encode(2,t.encode(r.s)),o=n+i;return e.encode(48,o)}},Ks=BigInt(0),Zf=BigInt(1),OC=BigInt(2),c2=BigInt(3),dz=BigInt(4);function Qf(r,e){let{BYTES:t}=r,n;if(typeof e=="bigint")n=e;else{let i=at("private key",e);try{n=r.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${t}, got ${typeof e}`)}}if(!r.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function hz(r,e={}){let t=r2("weierstrass",r,e),{Fp:n,Fn:i}=t,o=t.CURVE,{h:s,n:a}=o;Qo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=BC(n,i);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(H,E,T){let{x:C,y:O}=E.toAffine(),j=n.toBytes(C);if(Ls(T,"isCompressed"),T){u();let Q=!n.isOdd(O);return wn(NC(Q),j)}else return wn(Uint8Array.of(4),j,n.toBytes(O))}function d(H){ii(H,void 0,"Point");let{publicKey:E,publicKeyUncompressed:T}=l,C=H.length,O=H[0],j=H.subarray(1);if(C===E&&(O===2||O===3)){let Q=n.fromBytes(j);if(!n.isValid(Q))throw new Error("bad point: is not on curve, wrong x");let U=g(Q),Z;try{Z=n.sqrt(U)}catch(Te){let Ne=Te instanceof Error?": "+Te.message:"";throw new Error("bad point: is not on curve, sqrt error"+Ne)}u();let te=n.isOdd(Z);return(O&1)===1!==te&&(Z=n.neg(Z)),{x:Q,y:Z}}else if(C===T&&O===4){let Q=n.BYTES,U=n.fromBytes(j.subarray(0,Q)),Z=n.fromBytes(j.subarray(Q,Q*2));if(!w(U,Z))throw new Error("bad point: is not on curve");return{x:U,y:Z}}else throw new Error(`bad point: got length ${C}, expected compressed=${E} or uncompressed=${T}`)}let h=e.toBytes||f,m=e.fromBytes||d;function g(H){let E=n.sqr(H),T=n.mul(E,H);return n.add(n.add(T,n.mul(H,o.a)),o.b)}function w(H,E){let T=n.sqr(E),C=g(H);return n.eql(T,C)}if(!w(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let x=n.mul(n.pow(o.a,c2),dz),v=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(x,v)))throw new Error("bad curve params: a or b");function A(H,E,T=!1){if(!n.isValid(E)||T&&n.is0(E))throw new Error(`bad point coordinate ${H}`);return E}function S(H){if(!(H instanceof _))throw new Error("ProjectivePoint expected")}function M(H){if(!c||!c.basises)throw new Error("no endo");return fz(H,c.basises,i.ORDER)}let F=$f((H,E)=>{let{X:T,Y:C,Z:O}=H;if(n.eql(O,n.ONE))return{x:T,y:C};let j=H.is0();E==null&&(E=j?n.ONE:n.inv(O));let Q=n.mul(T,E),U=n.mul(C,E),Z=n.mul(O,E);if(j)return{x:n.ZERO,y:n.ZERO};if(!n.eql(Z,n.ONE))throw new Error("invZ was invalid");return{x:Q,y:U}}),N=$f(H=>{if(H.is0()){if(e.allowInfinityPoint&&!n.is0(H.Y))return;throw new Error("bad point: ZERO")}let{x:E,y:T}=H.toAffine();if(!n.isValid(E)||!n.isValid(T))throw new Error("bad point: x or y not field elements");if(!w(E,T))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function R(H,E,T,C,O){return T=new _(n.mul(T.X,H),T.Y,T.Z),E=Tp(C,E),T=Tp(O,T),E.add(T)}class _{constructor(E,T,C){this.X=A("x",E),this.Y=A("y",T,!0),this.Z=A("z",C),Object.freeze(this)}static CURVE(){return o}static fromAffine(E){let{x:T,y:C}=E||{};if(!E||!n.isValid(T)||!n.isValid(C))throw new Error("invalid affine point");if(E instanceof _)throw new Error("projective point not allowed");return n.is0(T)&&n.is0(C)?_.ZERO:new _(T,C,n.ONE)}static fromBytes(E){let T=_.fromAffine(m(ii(E,void 0,"point")));return T.assertValidity(),T}static fromHex(E){return _.fromBytes(at("pointHex",E))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(E=8,T=!0){return V.createCache(this,E),T||this.multiply(c2),this}assertValidity(){N(this)}hasEvenY(){let{y:E}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(E)}equals(E){S(E);let{X:T,Y:C,Z:O}=this,{X:j,Y:Q,Z:U}=E,Z=n.eql(n.mul(T,U),n.mul(j,O)),te=n.eql(n.mul(C,U),n.mul(Q,O));return Z&&te}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{a:E,b:T}=o,C=n.mul(T,c2),{X:O,Y:j,Z:Q}=this,U=n.ZERO,Z=n.ZERO,te=n.ZERO,q=n.mul(O,O),Te=n.mul(j,j),Ne=n.mul(Q,Q),se=n.mul(O,j);return se=n.add(se,se),te=n.mul(O,Q),te=n.add(te,te),U=n.mul(E,te),Z=n.mul(C,Ne),Z=n.add(U,Z),U=n.sub(Te,Z),Z=n.add(Te,Z),Z=n.mul(U,Z),U=n.mul(se,U),te=n.mul(C,te),Ne=n.mul(E,Ne),se=n.sub(q,Ne),se=n.mul(E,se),se=n.add(se,te),te=n.add(q,q),q=n.add(te,q),q=n.add(q,Ne),q=n.mul(q,se),Z=n.add(Z,q),Ne=n.mul(j,Q),Ne=n.add(Ne,Ne),q=n.mul(Ne,se),U=n.sub(U,q),te=n.mul(Ne,Te),te=n.add(te,te),te=n.add(te,te),new _(U,Z,te)}add(E){S(E);let{X:T,Y:C,Z:O}=this,{X:j,Y:Q,Z:U}=E,Z=n.ZERO,te=n.ZERO,q=n.ZERO,Te=o.a,Ne=n.mul(o.b,c2),se=n.mul(T,j),Le=n.mul(C,Q),Ke=n.mul(O,U),ft=n.add(T,C),He=n.add(j,Q);ft=n.mul(ft,He),He=n.add(se,Le),ft=n.sub(ft,He),He=n.add(T,O);let st=n.add(j,U);return He=n.mul(He,st),st=n.add(se,Ke),He=n.sub(He,st),st=n.add(C,O),Z=n.add(Q,U),st=n.mul(st,Z),Z=n.add(Le,Ke),st=n.sub(st,Z),q=n.mul(Te,He),Z=n.mul(Ne,Ke),q=n.add(Z,q),Z=n.sub(Le,q),q=n.add(Le,q),te=n.mul(Z,q),Le=n.add(se,se),Le=n.add(Le,se),Ke=n.mul(Te,Ke),He=n.mul(Ne,He),Le=n.add(Le,Ke),Ke=n.sub(se,Ke),Ke=n.mul(Te,Ke),He=n.add(He,Ke),se=n.mul(Le,He),te=n.add(te,se),se=n.mul(st,He),Z=n.mul(ft,Z),Z=n.sub(Z,se),se=n.mul(ft,Le),q=n.mul(st,q),q=n.add(q,se),new _(Z,te,q)}subtract(E){return this.add(E.negate())}is0(){return this.equals(_.ZERO)}multiply(E){let{endo:T}=e;if(!i.isValidNot0(E))throw new Error("invalid scalar: out of range");let C,O,j=Q=>V.cached(this,Q,U=>Us(_,U));if(T){let{k1neg:Q,k1:U,k2neg:Z,k2:te}=M(E),{p:q,f:Te}=j(U),{p:Ne,f:se}=j(te);O=Te.add(se),C=R(T.beta,q,Ne,Q,Z)}else{let{p:Q,f:U}=j(E);C=Q,O=U}return Us(_,[C,O])[0]}multiplyUnsafe(E){let{endo:T}=e,C=this;if(!i.isValid(E))throw new Error("invalid scalar: out of range");if(E===Ks||C.is0())return _.ZERO;if(E===Zf)return C;if(V.hasCache(this))return this.multiply(E);if(T){let{k1neg:O,k1:j,k2neg:Q,k2:U}=M(E),{p1:Z,p2:te}=fC(_,C,j,U);return R(T.beta,Z,te,O,Q)}else return V.unsafe(C,E)}multiplyAndAddUnsafe(E,T,C){let O=this.multiplyUnsafe(T).add(E.multiplyUnsafe(C));return O.is0()?void 0:O}toAffine(E){return F(this,E)}isTorsionFree(){let{isTorsionFree:E}=e;return s===Zf?!0:E?E(_,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:E}=e;return s===Zf?this:E?E(_,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(E=!0){return Ls(E,"isCompressed"),this.assertValidity(),h(_,this,E)}toHex(E=!0){return Oi(this.toBytes(E))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(E=!0){return this.toBytes(E)}_setWindowSize(E){this.precompute(E)}static normalizeZ(E){return Us(_,E)}static msm(E,T){return Kf(_,i,E,T)}static fromPrivateKey(E){return _.BASE.multiply(Qf(i,E))}}_.BASE=new _(o.Gx,o.Gy,n.ONE),_.ZERO=new _(n.ZERO,n.ONE,n.ZERO),_.Fp=n,_.Fn=i;let $=i.BITS,V=new Vf(_,e.endo?Math.ceil($/2):$);return _.BASE.precompute(8),_}function NC(r){return Uint8Array.of(r?2:3)}function BC(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function pz(r,e={}){let{Fn:t}=r,n=e.randomBytes||Xo,i=Object.assign(BC(r.Fp,t),{seed:V7(t.ORDER)});function o(h){try{return!!Qf(t,h)}catch{return!1}}function s(h,m){let{publicKey:g,publicKeyUncompressed:w}=i;try{let x=h.length;return m===!0&&x!==g||m===!1&&x!==w?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=n(i.seed)){return K7(ii(h,i.seed,"seed"),t.ORDER)}function c(h,m=!0){return r.BASE.multiply(Qf(t,h)).toBytes(m)}function l(h){let m=a(h);return{secretKey:m,publicKey:c(m)}}function u(h){if(typeof h=="bigint")return!1;if(h instanceof r)return!0;let{secretKey:m,publicKey:g,publicKeyUncompressed:w}=i;if(t.allowedLengths||m===g)return;let x=at("key",h).length;return x===g||x===w}function f(h,m,g=!0){if(u(h)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");let w=Qf(t,h);return r.fromHex(m).multiply(w).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:l,Point:r,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:a,isValidPrivateKey:o,randomPrivateKey:a,normPrivateKeyToScalar:h=>Qf(t,h),precompute(h=8,m=r.BASE){return m.precompute(h,!1)}},lengths:i})}function mz(r,e,t={}){Ns(e),Qo(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=t.randomBytes||Xo,i=t.hmac||((T,...C)=>Ya(e,T,wn(...C))),{Fp:o,Fn:s}=r,{ORDER:a,BITS:c}=s,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h}=pz(r,t),m={prehash:!1,lowS:typeof t.lowS=="boolean"?t.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(T){let C=a>>Zf;return T>C}function x(T,C){if(!s.isValidNot0(C))throw new Error(`invalid signature ${T}: out of range 1..Point.Fn.ORDER`);return C}function v(T,C){hx(C);let O=h.signature,j=C==="compact"?O:C==="recovered"?O+1:void 0;return ii(T,j,`${C} signature`)}class A{constructor(C,O,j){this.r=x("r",C),this.s=x("s",O),j!=null&&(this.recovery=j),Object.freeze(this)}static fromBytes(C,O=g){v(C,O);let j;if(O==="der"){let{r:te,s:q}=Vs.toSig(ii(C));return new A(te,q)}O==="recovered"&&(j=C[0],O="compact",C=C.subarray(1));let Q=s.BYTES,U=C.subarray(0,Q),Z=C.subarray(Q,Q*2);return new A(s.fromBytes(U),s.fromBytes(Z),j)}static fromHex(C,O){return this.fromBytes(wl(C),O)}addRecoveryBit(C){return new A(this.r,this.s,C)}recoverPublicKey(C){let O=o.ORDER,{r:j,s:Q,recovery:U}=this;if(U==null||![0,1,2,3].includes(U))throw new Error("recovery id invalid");if(a*OC<O&&U>1)throw new Error("recovery id is ambiguous for h>1 curve");let te=U===2||U===3?j+a:j;if(!o.isValid(te))throw new Error("recovery id 2 or 3 invalid");let q=o.toBytes(te),Te=r.fromBytes(wn(NC((U&1)===0),q)),Ne=s.inv(te),se=M(at("msgHash",C)),Le=s.create(-se*Ne),Ke=s.create(Q*Ne),ft=r.BASE.multiplyUnsafe(Le).add(Te.multiplyUnsafe(Ke));if(ft.is0())throw new Error("point at infinify");return ft.assertValidity(),ft}hasHighS(){return w(this.s)}toBytes(C=g){if(hx(C),C==="der")return wl(Vs.hexFromSig(this));let O=s.toBytes(this.r),j=s.toBytes(this.s);if(C==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return wn(Uint8Array.of(this.recovery),O,j)}return wn(O,j)}toHex(C){return Oi(this.toBytes(C))}assertValidity(){}static fromCompact(C){return A.fromBytes(at("sig",C),"compact")}static fromDER(C){return A.fromBytes(at("sig",C),"der")}normalizeS(){return this.hasHighS()?new A(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Oi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Oi(this.toBytes("compact"))}}let S=t.bits2int||function(C){if(C.length>8192)throw new Error("input is too large");let O=Ff(C),j=C.length*8-c;return j>0?O>>BigInt(j):O},M=t.bits2int_modN||function(C){return s.create(S(C))},F=Ga(c);function N(T){return Wa("num < 2^"+c,T,Ks,F),s.toBytes(T)}function R(T,C){return ii(T,void 0,"message"),C?ii(e(T),void 0,"prehashed message"):T}function _(T,C,O){if(["recovered","canonical"].some(Le=>Le in O))throw new Error("sign() legacy options not supported");let{lowS:j,prehash:Q,extraEntropy:U}=dx(O,m);T=R(T,Q);let Z=M(T),te=Qf(s,C),q=[N(te),N(Z)];if(U!=null&&U!==!1){let Le=U===!0?n(h.secretKey):U;q.push(at("extraEntropy",Le))}let Te=wn(...q),Ne=Z;function se(Le){let Ke=S(Le);if(!s.isValidNot0(Ke))return;let ft=s.inv(Ke),He=r.BASE.multiply(Ke).toAffine(),st=s.create(He.x);if(st===Ks)return;let Ci=s.create(ft*s.create(Ne+st*te));if(Ci===Ks)return;let hn=(He.x===st?0:2)|Number(He.y&Zf),io=Ci;return j&&w(Ci)&&(io=s.neg(Ci),hn^=1),new A(st,io,hn)}return{seed:Te,k2sig:se}}function $(T,C,O={}){T=at("message",T);let{seed:j,k2sig:Q}=_(T,C,O);return X_(e.outputLen,s.BYTES,i)(j,Q)}function V(T){let C,O=typeof T=="string"||Os(T),j=!O&&T!==null&&typeof T=="object"&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!O&&!j)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(j)C=new A(T.r,T.s);else if(O){try{C=A.fromBytes(at("sig",T),"der")}catch(Q){if(!(Q instanceof Vs.Err))throw Q}if(!C)try{C=A.fromBytes(at("sig",T),"compact")}catch{return!1}}return C||!1}function H(T,C,O,j={}){let{lowS:Q,prehash:U,format:Z}=dx(j,m);if(O=at("publicKey",O),C=R(at("message",C),U),"strict"in j)throw new Error("options.strict was renamed to lowS");let te=Z===void 0?V(T):A.fromBytes(at("sig",T),Z);if(te===!1)return!1;try{let q=r.fromBytes(O);if(Q&&te.hasHighS())return!1;let{r:Te,s:Ne}=te,se=M(C),Le=s.inv(Ne),Ke=s.create(se*Le),ft=s.create(Te*Le),He=r.BASE.multiplyUnsafe(Ke).add(q.multiplyUnsafe(ft));return He.is0()?!1:s.create(He.x)===Te}catch{return!1}}function E(T,C,O={}){let{prehash:j}=dx(O,m);return C=R(C,j),A.fromBytes(T,"recovered").recoverPublicKey(C).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:d,lengths:h,Point:r,sign:$,verify:H,recoverPublicKey:E,Signature:A,hash:e})}function gz(r){let e={a:r.a,b:r.b,p:r.Fp.ORDER,n:r.n,h:r.h,Gx:r.Gx,Gy:r.Gy},t=r.Fp,n=r.allowedPrivateKeyLengths?Array.from(new Set(r.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=oi(e.n,{BITS:r.nBitLength,allowedLengths:n,modFromBytes:r.wrapPrivateKey}),o={Fp:t,Fn:i,allowInfinityPoint:r.allowInfinityPoint,endo:r.endo,isTorsionFree:r.isTorsionFree,clearCofactor:r.clearCofactor,fromBytes:r.fromBytes,toBytes:r.toBytes};return{CURVE:e,curveOpts:o}}function yz(r){let{CURVE:e,curveOpts:t}=gz(r),n={hmac:r.hmac,randomBytes:r.randomBytes,lowS:r.lowS,bits2int:r.bits2int,bits2int_modN:r.bits2int_modN};return{CURVE:e,curveOpts:t,hash:r.hash,ecdsaOpts:n}}function wz(r,e){let t=e.Point;return Object.assign({},e,{ProjectivePoint:t,CURVE:Object.assign({},r,t2(t.Fn.ORDER,t.Fn.BITS))})}function LC(r){let{CURVE:e,curveOpts:t,hash:n,ecdsaOpts:i}=yz(r),o=hz(e,t),s=mz(o,n,i);return wz(r,s)}function MC(r,e){let t=n=>LC({...r,hash:n});return{...t(e),create:t}}var gx={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xz={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var UC=BigInt(2);function bz(r){let e=gx.p,t=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=Dt(u,t,e)*u%e,d=Dt(f,t,e)*u%e,h=Dt(d,UC,e)*l%e,m=Dt(h,i,e)*h%e,g=Dt(m,o,e)*m%e,w=Dt(g,a,e)*g%e,x=Dt(w,c,e)*w%e,v=Dt(x,a,e)*g%e,A=Dt(v,t,e)*u%e,S=Dt(A,s,e)*m%e,M=Dt(S,n,e)*l%e,F=Dt(M,UC,e);if(!mx.eql(mx.sqr(F),r))throw new Error("Cannot find square root");return F}var mx=oi(gx.p,{sqrt:bz}),ho=MC({...gx,Fp:mx,lowS:!0,endo:xz},Qg);var FC=32;function $C(r,e,t){let n=Be.digest(e instanceof Uint8Array?e:e.subarray());if(Wf(n))return n.then(({digest:i})=>(t?.signal?.throwIfAborted(),ho.sign(i,r).toDERRawBytes())).catch(i=>{throw i.name==="AbortError"?i:new Rp(String(i))});try{return ho.sign(n.digest,r).toDERRawBytes()}catch(i){throw new Rp(String(i))}}function HC(r,e,t,n){let i=Be.digest(t instanceof Uint8Array?t:t.subarray());if(Wf(i))return i.then(({digest:o})=>(n?.signal?.throwIfAborted(),ho.verify(e,o,r))).catch(o=>{throw o.name==="AbortError"?o:new Dp(String(o))});try{return n?.signal?.throwIfAborted(),ho.verify(e,i.digest,r)}catch(o){throw new Dp(String(o))}}var Mp=class{type="secp256k1";raw;_key;constructor(e){this._key=zC(e),this.raw=VC(this._key)}toMultihash(){return lr.digest(ur(this))}toCID(){return G.createV1(114,this.toMultihash())}toString(){return Ye.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}verify(e,t,n){return HC(this._key,t,e,n)}},Up=class{type="secp256k1";raw;publicKey;constructor(e,t){this.raw=KC(e),this.publicKey=new Mp(t??qC(e))}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:he(this.raw,e.raw)}sign(e,t){return $C(this.raw,e,t)}};function yx(r){return new Up(r)}function wx(r){return new Mp(r)}async function jC(){let r=vz();return new Up(r)}function VC(r){return ho.ProjectivePoint.fromHex(r).toRawBytes(!0)}function KC(r){try{return ho.getPublicKey(r,!0),r}catch(e){throw new cp(String(e))}}function zC(r){try{return ho.ProjectivePoint.fromHex(r),r}catch(e){throw new _s(String(e))}}function qC(r){try{return ho.getPublicKey(r,!0)}catch(e){throw new cp(String(e))}}function vz(){return ho.utils.randomPrivateKey()}async function Jf(r,e){if(r==="Ed25519")return _C();if(r==="secp256k1")return jC();if(r==="RSA")return fx(Az(e));if(r==="ECDSA")return R_(Ez(e));throw new so}function rr(r,e){let{Type:t,Data:n}=Zo.decode(r),i=n??new Uint8Array;switch(t){case _t.RSA:return cx(i,e);case _t.Ed25519:return ex(i);case _t.secp256k1:return wx(i);case _t.ECDSA:return R7(i);default:throw new so}}function l2(r){let{Type:e,Data:t}=Zo.decode(r.digest),n=t??new Uint8Array;switch(e){case _t.Ed25519:return ex(n);case _t.secp256k1:return wx(n);case _t.ECDSA:return R7(n);default:throw new so}}function ur(r){return Zo.encode({Type:_t[r.type],Data:r.raw})}function WC(r){let e=Np.decode(r),t=e.Data??new Uint8Array;switch(e.Type){case _t.RSA:return ax(t);case _t.Ed25519:return J7(t);case _t.secp256k1:return yx(t);case _t.ECDSA:return C_(t);default:throw new so}}function GC(r){if(r.byteLength===si)return J7(r);if(r.byteLength===FC)return yx(r);let e=Di(r),t=e[2]?.[0];if(t===y_||t===w_||t===x_)return P7(e);if(e.length>8)return s2(e);throw new K("Could not extract private key from raw bytes")}function _l(r){return Np.encode({Type:_t[r.type],Data:r.raw})}function Az(r){return r==null?2048:parseInt(r,10)}function Ez(r){if(r==="P-256"||r==null)return"P-256";if(r==="P-384")return"P-384";if(r==="P-521")return"P-521";throw new K("Unsupported curve, should be P-256, P-384 or P-521")}async function u2(r){if(r.type==="RSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};if(r.type==="ECDSA")return{privateKey:await crypto.subtle.importKey("jwk",r.jwk,{name:"ECDSA",namedCurve:r.jwk.crv??"P-256"},!0,["sign"]),publicKey:await crypto.subtle.importKey("jwk",r.publicKey.jwk,{name:"ECDSA",namedCurve:r.publicKey.jwk.crv??"P-256"},!0,["verify"])};throw new K("Only RSA and ECDSA keys are supported")}var XC=Symbol.for("nodejs.util.inspect.custom"),Sz=114,Fp=class{type;multihash;publicKey;string;constructor(e){this.type=e.type,this.multihash=e.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return`PeerId(${this.toString()})`}[dg]=!0;toString(){return this.string==null&&(this.string=Ye.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return G.createV1(Sz,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return he(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return he(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[XC](){return`PeerId(${this.toString()})`}},$p=class extends Fp{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},Hp=class extends Fp{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},Vp=class extends Fp{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},_z=2336,Kp=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=lr.digest(D(this.url))}[XC](){return`PeerId(${this.url})`}[dg]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return G.createV1(_z,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};var Cz=114,YC=2336;function gt(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=We(Ye.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return vn(G.parse(r));if(e==null)throw new K('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=We(e.decode(r))}return dr(t)}function es(r){if(r.type==="Ed25519")return new Hp({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new Vp({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new $p({multihash:r.toCID().multihash,publicKey:r});throw new so}function QC(r){return es(r.publicKey)}function dr(r){if(Iz(r))return new $p({multihash:r});if(Tz(r))try{let e=l2(r);if(e.type==="Ed25519")return new Hp({multihash:r,publicKey:e});if(e.type==="secp256k1")return new Vp({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new Kp(new URL(t))}throw new Ua("Supplied PeerID Multihash is invalid")}function vn(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==Cz&&r.code!==YC)throw new yg("Supplied PeerID CID is invalid");if(r.code===YC){let e=z(r.multihash.digest);return new Kp(new URL(e))}return dr(r.multihash)}function Tz(r){return r.code===lr.code}function Iz(r){return r.code===Be.code}function Cl(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),i=n.value;return n.done===!0||i==null?{done:!0,value:void 0}:{done:!1,value:e(i)}}};return t}function f2(r){let e=We(Ye.decode(`z${r}`));return dr(e)}var nn=class{map;constructor(e){if(this.map=new Map,e!=null)for(let[t,n]of e.entries())this.map.set(t.toString(),{key:t,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return Cl(this.map.entries(),e=>[e[1].key,e[1].value])}forEach(e){this.map.forEach((t,n)=>{e(t.value,t.key,this)})}get(e){return this.map.get(e.toString())?.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return Cl(this.map.values(),e=>e.key)}values(){return Cl(this.map.values(),e=>e.value)}get size(){return this.map.size}};var ai=class r{set;constructor(e){if(this.set=new Set,e!=null)for(let t of e)this.set.add(t.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return Cl(this.set.entries(),e=>{let t=f2(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=f2(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return Cl(this.set.values(),e=>f2(e))}intersection(e){let t=new r;for(let n of e)this.has(n)&&t.add(n);return t}difference(e){let t=new r;for(let n of this)e.has(n)||t.add(n);return t}union(e){let t=new r;for(let n of e)t.add(n);for(let n of this)t.add(n);return t}};function xx(){return new ai}function ZC(r,e,t,n){Ns(r);let i=L_({dkLen:32,asyncTick:10},n),{c:o,dkLen:s,asyncTick:a}=i;if(uo(o),uo(s),uo(a),o<1)throw new Error("iterations (c) should be >= 1");let c=D7(e),l=D7(t),u=new Uint8Array(s),f=Ya.create(r,c),d=f._cloneInto().update(l);return{c:o,dkLen:s,asyncTick:a,DK:u,PRF:f,PRFSalt:d}}function JC(r,e,t,n,i){return r.destroy(),e.destroy(),n&&n.destroy(),rn(i),t}function eT(r,e,t,n){let{c:i,dkLen:o,DK:s,PRF:a,PRFSalt:c}=ZC(r,e,t,n),l,u=new Uint8Array(4),f=yl(u),d=new Uint8Array(a.outputLen);for(let h=1,m=0;m<o;h++,m+=a.outputLen){let g=s.subarray(m,m+a.outputLen);f.setInt32(0,h,!1),(l=c._cloneInto(l)).update(u).digestInto(d),g.set(d.subarray(0,g.length));for(let w=1;w<i;w++){a._cloneInto(l).update(d).digestInto(d);for(let x=0;x<g.length;x++)g[x]^=d[x]}}return JC(a,c,s,l,d)}async function d2(r,e,t,n){let{c:i,dkLen:o,asyncTick:s,DK:a,PRF:c,PRFSalt:l}=ZC(r,e,t,n),u,f=new Uint8Array(4),d=yl(f),h=new Uint8Array(c.outputLen);for(let m=1,g=0;g<o;m++,g+=c.outputLen){let w=a.subarray(g,g+c.outputLen);d.setInt32(0,m,!1),(u=l._cloneInto(u)).update(f).digestInto(h),w.set(h.subarray(0,w.length)),await B_(i-1,s,()=>{c._cloneInto(u).update(h).digestInto(h);for(let x=0;x<w.length;x++)w[x]^=h[x]})}return JC(c,l,a,u,h)}var zp=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Qa=new Uint32Array(80),h2=class extends xl{constructor(){super(64,20,8,!1),this.A=zp[0]|0,this.B=zp[1]|0,this.C=zp[2]|0,this.D=zp[3]|0,this.E=zp[4]|0}get(){let{A:e,B:t,C:n,D:i,E:o}=this;return[e,t,n,i,o]}set(e,t,n,i,o){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=o|0}process(e,t){for(let c=0;c<16;c++,t+=4)Qa[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)Qa[c]=zg(Qa[c-3]^Qa[c-8]^Qa[c-14]^Qa[c-16],1);let{A:n,B:i,C:o,D:s,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=jg(i,o,s),u=1518500249):c<40?(l=i^o^s,u=1859775393):c<60?(l=Wg(i,o,s),u=2400959708):(l=i^o^s,u=3395469782);let f=zg(n,5)+l+a+u+Qa[c]|0;a=s,s=o,o=zg(i,30),i=n,n=f}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,this.set(n,i,o,s,a)}roundClean(){rn(Qa)}destroy(){this.set(0,0,0,0,0),rn(this.buffer)}},tT=vp(()=>new h2);var rT=tT;var ed=Zg;var nT={sha1:rT,"sha2-256":Jo,"sha2-512":ed};function qp(r,e,t,n,i){if(i!=="sha1"&&i!=="sha2-256"&&i!=="sha2-512"){let a=Object.keys(nT).join(" / ");throw new K(`Hash '${i}' is unknown or not supported. Must be ${a}`)}let o=nT[i],s=eT(o,r,e,{c:t,dkLen:n});return cr.encode(s).substring(1)}var bx={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},iT={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},oT=new globalThis.TextEncoder;function kz(r,e){let t=bx[e],n=iT[e];for(let i=0;i<r.length;i++)n^=BigInt(r[i]),n=BigInt.asUintN(e,n*t);return n}function Pz(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=bx[e],i=iT[e],o=r;for(;o.length>0;){let s=oT.encodeInto(o,t);o=o.slice(s.read);for(let a=0;a<s.written;a++)i^=BigInt(t[a]),i=BigInt.asUintN(e,i*n)}return i}function vx(r,{size:e=32,utf8Buffer:t}={}){if(!bx[e])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if(typeof r=="string"){if(t)return Pz(r,e,t);r=oT.encode(r)}return kz(r,e)}var jp={hash:r=>Number(vx(r,{size:32})),hashV:(r,e)=>Rz(jp.hash(r,e))};function Rz(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),D(e,"base16")}var Ax=64,po=class{fp;h;seed;constructor(e,t,n,i=2){if(i>Ax)throw new TypeError("Invalid Fingerprint Size");let o=t.hashV(e,n),s=ke(i);for(let a=0;a<s.length;a++)s[a]=o[a];s.length===0&&(s[0]=7),this.fp=s,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?he(this.fp,e.fp):!1}};function Tl(r,e){return Math.floor(Math.random()*(e-r))+r}var Il=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");for(let t=0;t<this.contents.length;t++)if(this.contents[t]==null)return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");let t=Tl(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof po))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Dz=500,Wp=class{bucketSize;filterSize;fingerprintSize;buckets;count;hash;seed;constructor(e){this.filterSize=e.filterSize,this.bucketSize=e.bucketSize??4,this.fingerprintSize=e.fingerprintSize??2,this.count=0,this.buckets=[],this.hash=e.hash??jp,this.seed=e.seed??Tl(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=D(e));let t=new po(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Il(this.bucketSize)),this.buckets[i]==null&&(this.buckets[i]=new Il(this.bucketSize)),this.buckets[n].add(t)||this.buckets[i].add(t))return this.count++,!0;let o=[n,i],s=o[Tl(0,o.length-1)];this.buckets[s]==null&&(this.buckets[s]=new Il(this.bucketSize));for(let a=0;a<Dz;a++){let c=this.buckets[s].swap(t);if(c!=null&&(s=(s^c.hash())%this.filterSize,this.buckets[s]==null&&(this.buckets[s]=new Il(this.bucketSize)),this.buckets[s].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=D(e));let t=new po(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.has(t)??!1;if(i)return i;let o=(n^t.hash())%this.filterSize;return this.buckets[o]?.has(t)??!1}remove(e){typeof e=="string"&&(e=D(e));let t=new po(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,i=this.buckets[n]?.remove(t)??!1;if(i)return this.count--,i;let o=(n^t.hash())%this.filterSize,s=this.buckets[o]?.remove(t)??!1;return s&&this.count--,s}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Oz={1:.5,2:.84,4:.95,8:.98};function Nz(r=.001){return r>.002?2:r>1e-5?4:8}function sT(r,e=.001){let t=Nz(e),n=Oz[t],i=Math.round(r/n),o=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),Ax);return{filterSize:i,bucketSize:t,fingerprintSize:o}}var td=class{filterSize;bucketSize;fingerprintSize;scale;filterSeries;hash;seed;constructor(e){this.bucketSize=e.bucketSize??4,this.filterSize=e.filterSize??(1<<18)/this.bucketSize,this.fingerprintSize=e.fingerprintSize??2,this.scale=e.scale??2,this.hash=e.hash??jp,this.seed=e.seed??Tl(0,Math.pow(2,10)),this.filterSeries=[new Wp({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=D(e)),this.has(e))return!0;let t=this.filterSeries.find(n=>n.reliable);if(t==null){let n=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new Wp({filterSize:n,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){typeof e=="string"&&(e=D(e));for(let t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce((e,t)=>e+t.count,0)}};function on(r,e=.001,t){return new td({...sT(r,e),...t??{}})}var p2=class{filter;constructor(e,t){this.filter=on(e,t)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){this.filter.remove?.(e.toMultihash().bytes)}};function Ex(r,e=.001){return new p2(r,e)}var Sx=class extends nn{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function zs(r){let{name:e,metrics:t}=r,n;return t!=null?n=new Sx({name:e,metrics:t}):n=new nn,n}var qs=class{full;pendingBytes;wantlist;blocks;blockPresences;constructor(e=!1,t=0){this.full=e,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){let n=cr.encode(e.multihash.bytes);this.wantlist.set(n,t)}addBlockPresence(e,t){let n=cr.encode(e.multihash.bytes);this.blockPresences.set(n,t)}addBlock(e,t){let n=cr.encode(e.multihash.bytes);this.blocks.set(n,t)}};function Bz(r){let e=new Uint8Array(r.reduce((n,i)=>n+je(i),0)),t=0;for(let n of r)e=Sr(n,e,t),t+=je(n);return e}var aT=Bz;function _x(r){return aT([r.version,r.code,r.multihash.code,r.multihash.digest.byteLength])}var m2=class{peerId;blockstore;network;wants;exchangeCount;bytesSent;bytesReceived;lastExchange;maxSizeReplaceHasWithBlock;log;constructor(e,t){this.peerId=e.peerId,this.blockstore=e.blockstore,this.network=e.network,this.wants=new Map,this.log=e.logger.forComponent(`helia:bitswap:ledger:${e.peerId}`),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock??1024}sentBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=new Date().getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}async sendBlocksToPeer(e){let t=new qs,n=new Set;for(let[i,o]of this.wants.entries())try{let s=await this.blockstore.get(o.cid,e);o.wantType===tr.WantHave?s.byteLength<this.maxSizeReplaceHasWithBlock?(this.log("sending have and block for %c",o.cid),n.add(i),t.addBlock(o.cid,{data:s,prefix:_x(o.cid)})):(this.log("sending have for %c",o.cid),t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:Ri.HaveBlock})):(this.log("sending block for %c",o.cid),n.add(i),t.addBlock(o.cid,{data:s,prefix:_x(o.cid)}))}catch(s){if(s.name!=="NotFoundError")throw s;if(this.log("do not have block for %c",o.cid),!o.sendDontHave||o.sentDoNotHave===!0)continue;o.sentDoNotHave=!0,t.addBlockPresence(o.cid,{cid:o.cid.bytes,type:Ri.DoNotHaveBlock})}if(t.blocks.size>0||t.blockPresences.size>0){this.log("sending message"),await this.network.sendMessage(this.peerId,t,e),this.log("sent message"),this.sentBytes([...t.blocks.values()].reduce((i,o)=>i+o.data.byteLength,0));for(let i of n)this.wants.delete(i)}}};var g2=class{blockstore;network;ledgerMap;maxSizeReplaceHasWithBlock;log;logger;constructor(e,t={}){this.blockstore=e.blockstore,this.network=e.network,this.maxSizeReplaceHasWithBlock=t.maxSizeReplaceHasWithBlock,this.log=e.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=e.logger,this.ledgerMap=zs({name:"helia_bitswap_ledger_map",metrics:e.metrics}),this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(i=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,i)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}ledgerForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){let t=this.ledgerMap.get(e);if(t!=null)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map(e=>e.peerId)}async receiveMessage(e,t){let n=this.ledgerMap.get(e);if(n==null&&(n=new m2({peerId:e,blockstore:this.blockstore,network:this.network,logger:this.logger},{maxSizeReplaceHasWithBlock:this.maxSizeReplaceHasWithBlock}),this.ledgerMap.set(e,n)),n.receivedBytes(t.blocks?.reduce((i,o)=>i+o.data.byteLength,0)??0),t.wantlist!=null){t.wantlist.full===!0&&n.wants.clear();for(let i of t.wantlist.entries){let o=G.decode(i.cid),s=z(o.multihash.bytes,"base64");i.cancel===!0?(this.log("peer %p cancelled want of block for %c",e,o),n.wants.delete(s)):(i.wantType===tr.WantHave?this.log("peer %p wanted block presence for %c",e,o):this.log("peer %p wanted block for %c",e,o),n.wants.set(s,{cid:o,priority:i.priority,wantType:i.wantType??tr.WantBlock,sendDontHave:i.sendDontHave??!1}))}}this.log("send blocks to peer"),await n.sendBlocksToPeer()}async receivedBlock(e,t){let n=z(e.multihash.bytes,"base64"),i=[];for(let o of this.ledgerMap.values())o.wants.has(n)&&i.push(o);await Promise.all(i.map(async o=>o.sendBlocksToPeer(t)))}peerDisconnected(e){this.ledgerMap.delete(e)}};function Lz(r,e){if(typeof r=="string")return Mz(r);if(typeof r=="number")return $z(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}var y2=Lz;function Mz(r){if(typeof r!="string"||r.length===0||r.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,i=parseFloat(t),o=n.toLowerCase();switch(o){case"years":case"year":case"yrs":case"yr":case"y":return i*315576e5;case"months":case"month":case"mo":return i*26298e5;case"weeks":case"week":case"w":return i*6048e5;case"days":case"day":case"d":return i*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return i*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return i*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return i*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:throw Error(`Unknown unit "${o}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Uz(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Fz(r){let e=Math.abs(r);return e>=315576e5?kl(r,e,315576e5,"year"):e>=26298e5?kl(r,e,26298e5,"month"):e>=6048e5?kl(r,e,6048e5,"week"):e>=864e5?kl(r,e,864e5,"day"):e>=36e5?kl(r,e,36e5,"hour"):e>=6e4?kl(r,e,6e4,"minute"):e>=1e3?kl(r,e,1e3,"second"):`${r} ms`}function $z(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?Fz(r):Uz(r)}function kl(r,e,t,n){let i=e>=t*1.5;return`${Math.round(r/t)} ${n}${i?"s":""}`}function Cx(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=i,t.enabled=s,t.humanize=y2,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let f=0;for(let d=0;d<u.length;d++)f=(f<<5)-f+u.charCodeAt(d),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(u){let f,d=null,h,m;function g(...w){if(!g.enabled)return;let x=g,v=Number(new Date),A=v-(f||v);x.diff=A,x.prev=f,x.curr=v,f=v,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let S=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(F,N)=>{if(F==="%%")return"%";S++;let R=t.formatters[N];if(typeof R=="function"){let _=w[S];F=R.call(x,_),w.splice(S,1),S--}return F}),t.formatArgs.call(x,w),(x.log||t.log).apply(x,w)}return g.namespace=u,g.useColors=t.useColors(),g.color=t.selectColor(u),g.extend=n,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==t.namespaces&&(h=t.namespaces,m=t.enabled(u)),m),set:w=>{d=w}}),typeof t.init=="function"&&t.init(g),g}function n(u,f){let d=t(this.namespace+(typeof f>"u"?":":f)+u);return d.log=this.log,d}function i(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let f,d=(typeof u=="string"?u:"").split(/[\s,]+/),h=d.length;for(f=0;f<h;f++)d[f]&&(u=d[f].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function o(){let u=[...t.names.map(a),...t.skips.map(a).map(f=>"-"+f)].join(",");return t.enable(""),u}function s(u){if(u[u.length-1]==="*")return!0;let f,d;for(f=0,d=t.skips.length;f<d;f++)if(t.skips[f].test(u))return!1;for(f=0,d=t.names.length;f<d;f++)if(t.names[f].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var w2=Wz(),Hz=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Vz(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Kz(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+y2(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(t++,i==="%c"&&(n=t))}),r.splice(n,0,e)}var zz=console.debug??console.log??(()=>{});function qz(r){try{r?w2?.setItem("debug",r):w2?.removeItem("debug")}catch{}}function jz(){let r;try{r=w2?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Wz(){try{return localStorage}catch{}}function Gz(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var cT=Cx({formatArgs:Kz,save:qz,load:jz,useColors:Vz,setupFormatters:Gz,colors:Hz,storage:w2,log:zz});var Dn=cT;Dn.formatters.b=r=>r==null?"undefined":Ye.baseEncode(r);Dn.formatters.t=r=>r==null?"undefined":jt.baseEncode(r);Dn.formatters.m=r=>r==null?"undefined":cr.baseEncode(r);Dn.formatters.p=r=>r==null?"undefined":r.toString();Dn.formatters.c=r=>r==null?"undefined":r.toString();Dn.formatters.k=r=>r==null?"undefined":r.toString();Dn.formatters.a=r=>r==null?"undefined":r.toString();Dn.formatters.e=r=>r==null?"undefined":lT(r.stack)??lT(r.message)??r.toString();function Xz(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e}function uT(r){return{forComponent(e){return Ue(`${r}:${e}`)}}}function Za(){return{forComponent(r){return Ue(r)}}}function Ue(r){let e=Xz(`${r}:trace`);return Dn.enabled(`${r}:trace`)&&Dn.names.map(t=>t.toString()).find(t=>t.includes(":trace"))!=null&&(e=Dn(`${r}:trace`)),Object.assign(Dn(r),{error:Dn(`${r}:error`),trace:e,newScope:t=>Ue(`${r}:${t}`)})}function lT(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Ix=mt(dT(),1);var Xp=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},kx=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}},hT=r=>globalThis.DOMException===void 0?new kx(r):new DOMException(r),pT=r=>{let e=r.reason===void 0?hT("This operation was aborted."):r.reason;return e instanceof Error?e:hT(e)};function js(r,e){let{milliseconds:t,fallback:n,message:i,customTimers:o={setTimeout,clearTimeout}}=e,s,a,l=new Promise((u,f)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:h}=e;h.aborted&&f(pT(h)),a=()=>{f(pT(h))},h.addEventListener("abort",a,{once:!0})}if(t===Number.POSITIVE_INFINITY){r.then(u,f);return}let d=new Xp;s=o.setTimeout.call(void 0,()=>{if(n){try{u(n())}catch(h){f(h)}return}typeof r.cancel=="function"&&r.cancel(),i===!1?u():i instanceof Error?f(i):(d.message=i??`Promise timed out after ${t} milliseconds`,f(d))},t),(async()=>{try{u(await r)}catch(h){f(h)}})()}).finally(()=>{l.clear(),a&&e.signal&&e.signal.removeEventListener("abort",a)});return l.clear=()=>{o.clearTimeout.call(void 0,s),s=void 0},l}function Px(r,e,t){let n=0,i=r.length;for(;i>0;){let o=Math.trunc(i/2),s=n+o;t(r[s],e)<=0?(n=++s,i-=o+1):i=o}return n}var Yp=class{#e=[];enqueue(e,t){t={priority:0,...t};let n={priority:t.priority,id:t.id,run:e};if(this.size===0||this.#e[this.size-1].priority>=t.priority){this.#e.push(n);return}let i=Px(this.#e,n,(o,s)=>s.priority-o.priority);this.#e.splice(i,0,n)}setPriority(e,t){let n=this.#e.findIndex(o=>o.id===e);if(n===-1)throw new ReferenceError(`No promise function with the id "${e}" exists in the queue.`);let[i]=this.#e.splice(n,1);this.enqueue(i.run,{priority:t,id:e})}dequeue(){return this.#e.shift()?.run}filter(e){return this.#e.filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return this.#e.length}};var mo=class extends Ix.default{#e;#t;#r=0;#s;#c;#l=0;#o;#n;#i;#h;#a=0;#f;#u;#d;#x=1n;timeout;constructor(e){if(super(),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Yp,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${e.intervalCap?.toString()??""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${e.interval?.toString()??""}\` (${typeof e.interval})`);this.#e=e.carryoverConcurrencyCount,this.#t=e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,this.#s=e.intervalCap,this.#c=e.interval,this.#i=new e.queueClass,this.#h=e.queueClass,this.concurrency=e.concurrency,this.timeout=e.timeout,this.#d=e.throwOnTimeout===!0,this.#u=e.autoStart===!1}get#b(){return this.#t||this.#r<this.#s}get#v(){return this.#a<this.#f}#A(){this.#a--,this.#p(),this.emit("next")}#E(){this.#w(),this.#y(),this.#n=void 0}get#S(){let e=Date.now();if(this.#o===void 0){let t=this.#l-e;if(t<0)this.#r=this.#e?this.#a:0;else return this.#n===void 0&&(this.#n=setTimeout(()=>{this.#E()},t)),!0}return!1}#p(){if(this.#i.size===0)return this.#o&&clearInterval(this.#o),this.#o=void 0,this.emit("empty"),this.#a===0&&this.emit("idle"),!1;if(!this.#u){let e=!this.#S;if(this.#b&&this.#v){let t=this.#i.dequeue();return t?(this.emit("active"),t(),e&&this.#y(),!0):!1}}return!1}#y(){this.#t||this.#o!==void 0||(this.#o=setInterval(()=>{this.#w()},this.#c),this.#l=Date.now()+this.#c)}#w(){this.#r===0&&this.#a===0&&this.#o&&(clearInterval(this.#o),this.#o=void 0),this.#r=this.#e?this.#a:0,this.#m()}#m(){for(;this.#p(););}get concurrency(){return this.#f}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this.#f=e,this.#m()}async#_(e){return new Promise((t,n)=>{e.addEventListener("abort",()=>{n(e.reason)},{once:!0})})}setPriority(e,t){this.#i.setPriority(e,t)}async add(e,t={}){return t.id??=(this.#x++).toString(),t={timeout:this.timeout,throwOnTimeout:this.#d,...t},new Promise((n,i)=>{this.#i.enqueue(async()=>{this.#a++;try{t.signal?.throwIfAborted(),this.#r++;let o=e({signal:t.signal});t.timeout&&(o=js(Promise.resolve(o),{milliseconds:t.timeout})),t.signal&&(o=Promise.race([o,this.#_(t.signal)]));let s=await o;n(s),this.emit("completed",s)}catch(o){if(o instanceof Xp&&!t.throwOnTimeout){n();return}i(o),this.emit("error",o)}finally{this.#A()}},t),this.emit("add"),this.#p()})}async addAll(e,t){return Promise.all(e.map(async n=>this.add(n,t)))}start(){return this.#u?(this.#u=!1,this.#m(),this):this}pause(){this.#u=!0}clear(){this.#i=new this.#h}async onEmpty(){this.#i.size!==0&&await this.#g("empty")}async onSizeLessThan(e){this.#i.size<e||await this.#g("next",()=>this.#i.size<e)}async onIdle(){this.#a===0&&this.#i.size===0||await this.#g("idle")}async#g(e,t){return new Promise(n=>{let i=()=>{t&&!t()||(this.off(e,i),n())};this.on(e,i)})}get size(){return this.#i.size}sizeBy(e){return this.#i.filter(e).length}get pending(){return this.#a}get isPaused(){return this.#u}};function b2(r){let e=[an.A];return r==null?e:Array.isArray(r)?r.length===0?e:r:[r]}var Rx=60;function v2(r){return{Status:r.Status??0,TC:r.TC??r.flag_tc??!1,RD:r.RD??r.flag_rd??!1,RA:r.RA??r.flag_ra??!1,AD:r.AD??r.flag_ad??!1,CD:r.CD??r.flag_cd??!1,Question:(r.Question??r.questions??[]).map(e=>({name:e.name,type:an[e.type]})),Answer:(r.Answer??r.answers??[]).map(e=>({name:e.name,type:an[e.type],TTL:e.TTL??e.ttl??Rx,data:e.data instanceof Uint8Array?z(e.data):e.data}))}}var Zz=4;function Dx(r,e={}){let t=new mo({concurrency:e.queryConcurrency??Zz});return async(n,i={})=>{let o=new URLSearchParams;o.set("name",n),b2(i.types).forEach(a=>{o.append("type",an[a])}),i.onProgress?.(new X("dns:query",n));let s=await t.add(async()=>{let a=await fetch(`${r}?${o}`,{headers:{accept:"application/dns-json"},signal:i?.signal});if(a.status!==200)throw new Error(`Unexpected HTTP status: ${a.status} - ${a.statusText}`);let c=v2(await a.json());return i.onProgress?.(new X("dns:response",c)),c},{signal:i.signal});if(s==null)throw new Error("No DNS response received");return s}}function mT(){return[Dx("https://cloudflare-dns.com/dns-query"),Dx("https://dns.google/resolve")]}var wT=mt(yT(),1);var Ox=class{lru;constructor(e){this.lru=(0,wT.default)(e)}get(e,t){let n=!0,i=[];for(let o of t){let s=this.getAnswers(e,o);if(s.length===0){n=!1;break}i.push(...s)}if(n)return v2({answers:i})}getAnswers(e,t){let n=`${e.toLowerCase()}-${t}`,i=this.lru.get(n);if(i!=null){let o=i.filter(s=>s.expires>Date.now()).map(({expires:s,value:a})=>({...a,TTL:Math.round((s-Date.now())/1e3),type:an[a.type]}));return o.length===0&&this.lru.remove(n),o}return[]}add(e,t){let n=`${e.toLowerCase()}-${t.type}`,i=this.lru.get(n)??[];i.push({expires:Date.now()+(t.TTL??Rx)*1e3,value:t}),this.lru.set(n,i)}remove(e,t){let n=`${e.toLowerCase()}-${t}`;this.lru.remove(n)}clear(){this.lru.clear()}};function xT(r){return new Ox(r)}var Jz=1e3,A2=class{resolvers;cache;constructor(e){this.resolvers={},this.cache=xT(e.cacheSize??Jz),Object.entries(e.resolvers??{}).forEach(([t,n])=>{Array.isArray(n)||(n=[n]),t.endsWith(".")||(t=`${t}.`),this.resolvers[t]=n}),this.resolvers["."]==null&&(this.resolvers["."]=mT())}async query(e,t={}){let n=b2(t.types),i=t.cached!==!1?this.cache.get(e,n):void 0;if(i!=null)return t.onProgress?.(new X("dns:cache",i)),i;let o=`${e.split(".").pop()}.`,s=(this.resolvers[o]??this.resolvers["."]).sort(()=>Math.random()>.5?-1:1),a=[];for(let c of s){if(t.signal?.aborted===!0)break;try{let l=await c(e,{...t,types:n});for(let u of l.Answer)this.cache.add(e,u);return l}catch(l){a.push(l),t.onProgress?.(new X("dns:error",l))}}throw a.length===1?a[0]:new AggregateError(a,`DNS lookup of ${e} ${n} failed`)}};var an;(function(r){r[r.A=1]="A",r[r.CNAME=5]="CNAME",r[r.TXT=16]="TXT",r[r.AAAA=28]="AAAA"})(an||(an={}));function Pl(r={}){return new A2(r)}var eq=["string","number","bigint","symbol"],tq=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function bT(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(eq.includes(e))return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(rq(r))return"Buffer";let t=nq(r);return t||"Object"}function rq(r){return r&&r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer.call(null,r)}function nq(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(tq.includes(e))return e}var I=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}};I.uint=new I(0,"uint",!0);I.negint=new I(1,"negint",!0);I.bytes=new I(2,"bytes",!0);I.string=new I(3,"string",!0);I.array=new I(4,"array",!1);I.map=new I(5,"map",!1);I.tag=new I(6,"tag",!1);I.float=new I(7,"float",!0);I.false=new I(7,"false",!0);I.true=new I(7,"true",!0);I.null=new I(7,"null",!0);I.undefined=new I(7,"undefined",!0);I.break=new I(7,"break",!0);var Y=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var rd=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",iq=new TextDecoder,oq=new TextEncoder;function E2(r){return rd&&globalThis.Buffer.isBuffer(r)}function Qp(r){return r instanceof Uint8Array?E2(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}var ST=rd?(r,e,t)=>t-e>64?globalThis.Buffer.from(r.subarray(e,t)).toString("utf8"):AT(r,e,t):(r,e,t)=>t-e>64?iq.decode(r.subarray(e,t)):AT(r,e,t),S2=rd?r=>r.length>64?globalThis.Buffer.from(r):vT(r):r=>r.length>64?oq.encode(r):vT(r),ts=r=>Uint8Array.from(r),nd=rd?(r,e,t)=>E2(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),_T=rd?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Qp(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let i of r)n+i.length>t.length&&(i=i.subarray(0,t.length-n)),t.set(i,n),n+=i.length;return t},CT=rd?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r);function TT(r,e){if(E2(r)&&E2(e))return r.compare(e);for(let t=0;t<r.length;t++)if(r[t]!==e[t])return r[t]<e[t]?-1:1;return 0}function vT(r){let e=[],t=0;for(let n=0;n<r.length;n++){let i=r.charCodeAt(n);i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(i=65536+((i&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128)}return e}function AT(r,e,t){let n=[];for(;e<t;){let i=r[e],o=null,s=i>239?4:i>223?3:i>191?2:1;if(e+s<=t){let a,c,l,u;switch(s){case 1:i<128&&(o=i);break;case 2:a=r[e+1],(a&192)===128&&(u=(i&31)<<6|a&63,u>127&&(o=u));break;case 3:a=r[e+1],c=r[e+2],(a&192)===128&&(c&192)===128&&(u=(i&15)<<12|(a&63)<<6|c&63,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:a=r[e+1],c=r[e+2],l=r[e+3],(a&192)===128&&(c&192)===128&&(l&192)===128&&(u=(i&15)<<18|(a&63)<<12|(c&63)<<6|l&63,u>65535&&u<1114112&&(o=u))}}o===null?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|o&1023),n.push(o),e+=s}return Nx(n)}var ET=4096;function Nx(r){let e=r.length;if(e<=ET)return String.fromCharCode.apply(String,r);let t="",n=0;for(;n<e;)t+=String.fromCharCode.apply(String,r.slice(n,n+=ET));return t}var sq=256,Zp=class{constructor(e=sq){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let i=t.length-(this.maxCursor-this.cursor)-1;t.set(e,i)}else{if(t){let i=t.length-(this.maxCursor-this.cursor)-1;i<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,i),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=CT(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=nd(n,0,this.cursor)}else t=_T(this.chunks,this.cursor);return e&&this.reset(),t}};var me="CBOR decode error:",Ws="CBOR encode error:",Jp=[];Jp[23]=1;Jp[24]=2;Jp[25]=3;Jp[26]=5;Jp[27]=9;function Gs(r,e,t){if(r.length-e<t)throw new Error(`${me} not enough data for type`)}var Tr=[24,256,65536,4294967296,BigInt("18446744073709551616")];function ci(r,e,t){Gs(r,e,1);let n=r[e];if(t.strict===!0&&n<Tr[0])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);return n}function li(r,e,t){Gs(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<Tr[1])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);return n}function ui(r,e,t){Gs(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<Tr[2])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);return n}function fi(r,e,t){Gs(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],i=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(t.strict===!0&&o<Tr[3])throw new Error(`${me} integer encoded in more bytes than necessary (strict decode)`);if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(t.allowBigInt===!0)return o;throw new Error(`${me} integers outside of the safe integer range are not supported`)}function IT(r,e,t,n){return new Y(I.uint,ci(r,e+1,n),2)}function kT(r,e,t,n){return new Y(I.uint,li(r,e+1,n),3)}function PT(r,e,t,n){return new Y(I.uint,ui(r,e+1,n),5)}function RT(r,e,t,n){return new Y(I.uint,fi(r,e+1,n),9)}function Li(r,e){return Lr(r,0,e.value)}function Lr(r,e,t){if(t<Tr[0]){let n=Number(t);r.push([e|n])}else if(t<Tr[1]){let n=Number(t);r.push([e|24,n])}else if(t<Tr[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<Tr[3]){let n=Number(t);r.push([e|26,n>>>24&255,n>>>16&255,n>>>8&255,n&255])}else{let n=BigInt(t);if(n<Tr[4]){let i=[e|27,0,0,0,0,0,0,0],o=Number(n&BigInt(4294967295)),s=Number(n>>BigInt(32)&BigInt(4294967295));i[8]=o&255,o=o>>8,i[7]=o&255,o=o>>8,i[6]=o&255,o=o>>8,i[5]=o&255,i[4]=s&255,s=s>>8,i[3]=s&255,s=s>>8,i[2]=s&255,s=s>>8,i[1]=s&255,r.push(i)}else throw new Error(`${me} encountered BigInt larger than allowable range`)}}Li.encodedSize=function(e){return Lr.encodedSize(e.value)};Lr.encodedSize=function(e){return e<Tr[0]?1:e<Tr[1]?2:e<Tr[2]?3:e<Tr[3]?5:9};Li.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};function DT(r,e,t,n){return new Y(I.negint,-1-ci(r,e+1,n),2)}function OT(r,e,t,n){return new Y(I.negint,-1-li(r,e+1,n),3)}function NT(r,e,t,n){return new Y(I.negint,-1-ui(r,e+1,n),5)}var Bx=BigInt(-1),BT=BigInt(1);function LT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i!="bigint"){let o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new Y(I.negint,o,9)}if(n.allowBigInt!==!0)throw new Error(`${me} integers outside of the safe integer range are not supported`);return new Y(I.negint,Bx-BigInt(i),9)}function _2(r,e){let t=e.value,n=typeof t=="bigint"?t*Bx-BT:t*-1-1;Lr(r,e.type.majorEncoded,n)}_2.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*Bx-BT:t*-1-1;return n<Tr[0]?1:n<Tr[1]?2:n<Tr[2]?3:n<Tr[3]?5:9};_2.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function em(r,e,t,n){Gs(r,e,t+n);let i=nd(r,e+t,e+t+n);return new Y(I.bytes,i,t+n)}function MT(r,e,t,n){return em(r,e,1,t)}function UT(r,e,t,n){return em(r,e,2,ci(r,e+1,n))}function FT(r,e,t,n){return em(r,e,3,li(r,e+1,n))}function $T(r,e,t,n){return em(r,e,5,ui(r,e+1,n))}function HT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer bytes lengths not supported`);return em(r,e,9,i)}function C2(r){return r.encodedBytes===void 0&&(r.encodedBytes=r.type===I.string?S2(r.value):r.value),r.encodedBytes}function id(r,e){let t=C2(e);Lr(r,e.type.majorEncoded,t.length),r.push(t)}id.encodedSize=function(e){let t=C2(e);return Lr.encodedSize(t.length)+t.length};id.compareTokens=function(e,t){return cq(C2(e),C2(t))};function cq(r,e){return r.length<e.length?-1:r.length>e.length?1:TT(r,e)}function tm(r,e,t,n,i){let o=t+n;Gs(r,e,o);let s=new Y(I.string,ST(r,e+t,e+o),o);return i.retainStringBytes===!0&&(s.byteValue=nd(r,e+t,e+o)),s}function VT(r,e,t,n){return tm(r,e,1,t,n)}function KT(r,e,t,n){return tm(r,e,2,ci(r,e+1,n),n)}function zT(r,e,t,n){return tm(r,e,3,li(r,e+1,n),n)}function qT(r,e,t,n){return tm(r,e,5,ui(r,e+1,n),n)}function jT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer string lengths not supported`);return tm(r,e,9,i,n)}var WT=id;function od(r,e,t,n){return new Y(I.array,n,t)}function GT(r,e,t,n){return od(r,e,1,t)}function XT(r,e,t,n){return od(r,e,2,ci(r,e+1,n))}function YT(r,e,t,n){return od(r,e,3,li(r,e+1,n))}function QT(r,e,t,n){return od(r,e,5,ui(r,e+1,n))}function ZT(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer array lengths not supported`);return od(r,e,9,i)}function JT(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${me} indefinite length items not allowed`);return od(r,e,1,1/0)}function T2(r,e){Lr(r,I.array.majorEncoded,e.value)}T2.compareTokens=Li.compareTokens;T2.encodedSize=function(e){return Lr.encodedSize(e.value)};function sd(r,e,t,n){return new Y(I.map,n,t)}function eI(r,e,t,n){return sd(r,e,1,t)}function tI(r,e,t,n){return sd(r,e,2,ci(r,e+1,n))}function rI(r,e,t,n){return sd(r,e,3,li(r,e+1,n))}function nI(r,e,t,n){return sd(r,e,5,ui(r,e+1,n))}function iI(r,e,t,n){let i=fi(r,e+1,n);if(typeof i=="bigint")throw new Error(`${me} 64-bit integer map lengths not supported`);return sd(r,e,9,i)}function oI(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${me} indefinite length items not allowed`);return sd(r,e,1,1/0)}function I2(r,e){Lr(r,I.map.majorEncoded,e.value)}I2.compareTokens=Li.compareTokens;I2.encodedSize=function(e){return Lr.encodedSize(e.value)};function sI(r,e,t,n){return new Y(I.tag,t,1)}function aI(r,e,t,n){return new Y(I.tag,ci(r,e+1,n),2)}function cI(r,e,t,n){return new Y(I.tag,li(r,e+1,n),3)}function lI(r,e,t,n){return new Y(I.tag,ui(r,e+1,n),5)}function uI(r,e,t,n){return new Y(I.tag,fi(r,e+1,n),9)}function k2(r,e){Lr(r,I.tag.majorEncoded,e.value)}k2.compareTokens=Li.compareTokens;k2.encodedSize=function(e){return Lr.encodedSize(e.value)};var pq=20,mq=21,gq=22,yq=23;function fI(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${me} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new Y(I.null,null,1):new Y(I.undefined,void 0,1)}function dI(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${me} indefinite length items not allowed`);return new Y(I.break,void 0,1)}function Lx(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${me} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${me} Infinity values are not supported`)}return new Y(I.float,r,e)}function hI(r,e,t,n){return Lx(Mx(r,e+1),3,n)}function pI(r,e,t,n){return Lx(Ux(r,e+1),5,n)}function mI(r,e,t,n){return Lx(xI(r,e+1),9,n)}function P2(r,e,t){let n=e.value;if(n===!1)r.push([I.float.majorEncoded|pq]);else if(n===!0)r.push([I.float.majorEncoded|mq]);else if(n===null)r.push([I.float.majorEncoded|gq]);else if(n===void 0)r.push([I.float.majorEncoded|yq]);else{let i,o=!1;(!t||t.float64!==!0)&&(yI(n),i=Mx(go,1),n===i||Number.isNaN(n)?(go[0]=249,r.push(go.slice(0,3)),o=!0):(wI(n),i=Ux(go,1),n===i&&(go[0]=250,r.push(go.slice(0,5)),o=!0))),o||(wq(n),i=xI(go,1),go[0]=251,r.push(go.slice(0,9)))}}P2.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n===null||n===void 0)return 1;if(!t||t.float64!==!0){yI(n);let i=Mx(go,1);if(n===i||Number.isNaN(n))return 3;if(wI(n),i=Ux(go,1),n===i)return 5}return 9};var gI=new ArrayBuffer(9),Mi=new DataView(gI,1),go=new Uint8Array(gI,0);function yI(r){if(r===1/0)Mi.setUint16(0,31744,!1);else if(r===-1/0)Mi.setUint16(0,64512,!1);else if(Number.isNaN(r))Mi.setUint16(0,32256,!1);else{Mi.setFloat32(0,r);let e=Mi.getUint32(0),t=(e&2139095040)>>23,n=e&8388607;if(t===255)Mi.setUint16(0,31744,!1);else if(t===0)Mi.setUint16(0,(r&2147483648)>>16|n>>13,!1);else{let i=t-127;i<-24?Mi.setUint16(0,0):i<-14?Mi.setUint16(0,(e&2147483648)>>16|1<<24+i,!1):Mi.setUint16(0,(e&2147483648)>>16|i+15<<10|n>>13,!1)}}}function Mx(r,e){if(r.length-e<2)throw new Error(`${me} not enough data for float16`);let t=(r[e]<<8)+r[e+1];if(t===31744)return 1/0;if(t===64512)return-1/0;if(t===32256)return NaN;let n=t>>10&31,i=t&1023,o;return n===0?o=i*2**-24:n!==31?o=(i+1024)*2**(n-25):o=i===0?1/0:NaN,t&32768?-o:o}function wI(r){Mi.setFloat32(0,r,!1)}function Ux(r,e){if(r.length-e<4)throw new Error(`${me} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function wq(r){Mi.setFloat64(0,r,!1)}function xI(r,e){if(r.length-e<8)throw new Error(`${me} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}P2.compareTokens=Li.compareTokens;function nt(r,e,t){throw new Error(`${me} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function R2(r){return()=>{throw new Error(`${me} ${r}`)}}var ie=[];for(let r=0;r<=23;r++)ie[r]=nt;ie[24]=IT;ie[25]=kT;ie[26]=PT;ie[27]=RT;ie[28]=nt;ie[29]=nt;ie[30]=nt;ie[31]=nt;for(let r=32;r<=55;r++)ie[r]=nt;ie[56]=DT;ie[57]=OT;ie[58]=NT;ie[59]=LT;ie[60]=nt;ie[61]=nt;ie[62]=nt;ie[63]=nt;for(let r=64;r<=87;r++)ie[r]=MT;ie[88]=UT;ie[89]=FT;ie[90]=$T;ie[91]=HT;ie[92]=nt;ie[93]=nt;ie[94]=nt;ie[95]=R2("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)ie[r]=VT;ie[120]=KT;ie[121]=zT;ie[122]=qT;ie[123]=jT;ie[124]=nt;ie[125]=nt;ie[126]=nt;ie[127]=R2("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)ie[r]=GT;ie[152]=XT;ie[153]=YT;ie[154]=QT;ie[155]=ZT;ie[156]=nt;ie[157]=nt;ie[158]=nt;ie[159]=JT;for(let r=160;r<=183;r++)ie[r]=eI;ie[184]=tI;ie[185]=rI;ie[186]=nI;ie[187]=iI;ie[188]=nt;ie[189]=nt;ie[190]=nt;ie[191]=oI;for(let r=192;r<=215;r++)ie[r]=sI;ie[216]=aI;ie[217]=cI;ie[218]=lI;ie[219]=uI;ie[220]=nt;ie[221]=nt;ie[222]=nt;ie[223]=nt;for(let r=224;r<=243;r++)ie[r]=R2("simple values are not supported");ie[244]=nt;ie[245]=nt;ie[246]=nt;ie[247]=fI;ie[248]=R2("simple values are not supported");ie[249]=hI;ie[250]=pI;ie[251]=mI;ie[252]=nt;ie[253]=nt;ie[254]=nt;ie[255]=dI;var yo=[];for(let r=0;r<24;r++)yo[r]=new Y(I.uint,r,1);for(let r=-1;r>=-24;r--)yo[31-r]=new Y(I.negint,r,1);yo[64]=new Y(I.bytes,new Uint8Array(0),1);yo[96]=new Y(I.string,"",1);yo[128]=new Y(I.array,0,1);yo[160]=new Y(I.map,0,1);yo[244]=new Y(I.false,!1,1);yo[245]=new Y(I.true,!0,1);yo[246]=new Y(I.null,null,1);function Fx(r){switch(r.type){case I.false:return ts([244]);case I.true:return ts([245]);case I.null:return ts([246]);case I.bytes:return r.value.length?void 0:ts([64]);case I.string:return r.value===""?ts([96]):void 0;case I.array:return r.value===0?ts([128]):void 0;case I.map:return r.value===0?ts([160]):void 0;case I.uint:return r.value<24?ts([Number(r.value)]):void 0;case I.negint:if(r.value>=-24)return ts([31-Number(r.value)])}}var bq={float64:!1,mapSorter:Aq,quickEncodeToken:Fx};function Hx(){let r=[];return r[I.uint.major]=Li,r[I.negint.major]=_2,r[I.bytes.major]=id,r[I.string.major]=WT,r[I.array.major]=T2,r[I.map.major]=I2,r[I.tag.major]=k2,r[I.float.major]=P2,r}var bI=Hx(),$x=new Zp,D2=class r{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error(`${Ws} object contains circular references`);return new r(t,e)}},Ja={null:new Y(I.null,null),undefined:new Y(I.undefined,void 0),true:new Y(I.true,!0),false:new Y(I.false,!1),emptyArray:new Y(I.array,0),emptyMap:new Y(I.map,0)},ec={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new Y(I.float,r):r>=0?new Y(I.uint,r):new Y(I.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new Y(I.uint,r):new Y(I.negint,r)},Uint8Array(r,e,t,n){return new Y(I.bytes,r)},string(r,e,t,n){return new Y(I.string,r)},boolean(r,e,t,n){return r?Ja.true:Ja.false},null(r,e,t,n){return Ja.null},undefined(r,e,t,n){return Ja.undefined},ArrayBuffer(r,e,t,n){return new Y(I.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new Y(I.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[Ja.emptyArray,new Y(I.break)]:Ja.emptyArray;n=D2.createCheck(n,r);let i=[],o=0;for(let s of r)i[o++]=rm(s,t,n);return t.addBreakTokens?[new Y(I.array,r.length),i,new Y(I.break)]:[new Y(I.array,r.length),i]},Object(r,e,t,n){let i=e!=="Object",o=i?r.keys():Object.keys(r),s=i?r.size:o.length;if(!s)return t.addBreakTokens===!0?[Ja.emptyMap,new Y(I.break)]:Ja.emptyMap;n=D2.createCheck(n,r);let a=[],c=0;for(let l of o)a[c++]=[rm(l,t,n),rm(i?r.get(l):r[l],t,n)];return vq(a,t),t.addBreakTokens?[new Y(I.map,s),a,new Y(I.break)]:[new Y(I.map,s),a]}};ec.Map=ec.Object;ec.Buffer=ec.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))ec[`${r}Array`]=ec.DataView;function rm(r,e={},t){let n=bT(r),i=e&&e.typeEncoders&&e.typeEncoders[n]||ec[n];if(typeof i=="function"){let s=i(r,n,e,t);if(s!=null)return s}let o=ec[n];if(!o)throw new Error(`${Ws} unsupported type: ${n}`);return o(r,n,e,t)}function vq(r,e){e.mapSorter&&r.sort(e.mapSorter)}function Aq(r,e){let t=Array.isArray(r[0])?r[0][0]:r[0],n=Array.isArray(e[0])?e[0][0]:e[0];if(t.type!==n.type)return t.type.compare(n.type);let i=t.type.major,o=bI[i].compareTokens(t,n);return o===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),o}function vI(r,e,t,n){if(Array.isArray(e))for(let i of e)vI(r,i,t,n);else t[e.type.major](r,e,n)}function Vx(r,e,t){let n=rm(r,t);if(!Array.isArray(n)&&t.quickEncodeToken){let i=t.quickEncodeToken(n);if(i)return i;let o=e[n.type.major];if(o.encodedSize){let s=o.encodedSize(n,t),a=new Zp(s);if(o(a,n,t),a.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${n} was wrong`);return Qp(a.chunks[0])}}return $x.reset(),vI($x,n,e,t),$x.toBytes(!0)}function Xs(r,e){return e=Object.assign({},bq,e),Vx(r,bI,e)}var Eq={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},O2=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=yo[e];if(t===void 0){let n=ie[e];if(!n)throw new Error(`${me} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,"0")})`);let i=e&31;t=n(this.data,this._pos,i,this.options)}return this._pos+=t.encodedLength,t}},nm=Symbol.for("DONE"),N2=Symbol.for("BREAK");function Sq(r,e,t){let n=[];for(let i=0;i<r.value;i++){let o=ad(e,t);if(o===N2){if(r.value===1/0)break;throw new Error(`${me} got unexpected break to lengthed array`)}if(o===nm)throw new Error(`${me} found array but not enough entries (got ${i}, expected ${r.value})`);n[i]=o}return n}function _q(r,e,t){let n=t.useMaps===!0,i=n?void 0:{},o=n?new Map:void 0;for(let s=0;s<r.value;s++){let a=ad(e,t);if(a===N2){if(r.value===1/0)break;throw new Error(`${me} got unexpected break to lengthed map`)}if(a===nm)throw new Error(`${me} found map but not enough entries (got ${s} [no key], expected ${r.value})`);if(n!==!0&&typeof a!="string")throw new Error(`${me} non-string keys not supported (got ${typeof a})`);if(t.rejectDuplicateMapKeys===!0&&(n&&o.has(a)||!n&&a in i))throw new Error(`${me} found repeat map key "${a}"`);let c=ad(e,t);if(c===nm)throw new Error(`${me} found map but not enough entries (got ${s} [no value], expected ${r.value})`);n?o.set(a,c):i[a]=c}return n?o:i}function ad(r,e){if(r.done())return nm;let t=r.next();if(t.type===I.break)return N2;if(t.type.terminal)return t.value;if(t.type===I.array)return Sq(t,r,e);if(t.type===I.map)return _q(t,r,e);if(t.type===I.tag){if(e.tags&&typeof e.tags[t.value]=="function"){let n=ad(r,e);return e.tags[t.value](n)}throw new Error(`${me} tag not supported (${t.value})`)}throw new Error("unsupported")}function Kx(r,e){if(!(r instanceof Uint8Array))throw new Error(`${me} data to decode must be a Uint8Array`);e=Object.assign({},Eq,e);let t=e.tokenizer||new O2(r,e),n=ad(t,e);if(n===nm)throw new Error(`${me} did not find any content to decode`);if(n===N2)throw new Error(`${me} got unexpected break`);return[n,r.subarray(t.pos())]}function En(r,e){let[t,n]=Kx(r,e);if(n.length>0)throw new Error(`${me} too many terminals, data makes no sense`);return t}var Ys="/",AI=new TextEncoder().encode(Ys),B2=AI[0],it=class r{_buf;constructor(e,t){if(typeof e=="string")this._buf=D(e);else if(e instanceof Uint8Array)this._buf=e;else throw new Error("Invalid key, should be String of Uint8Array");if(t==null&&(t=!0),t&&this.clean(),this._buf.byteLength===0||this._buf[0]!==B2)throw new Error("Invalid key")}toString(e="utf8"){return z(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return`Key(${this.toString()})`}static withNamespaces(e){return new r(e.join(Ys))}static random(){return new r(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||typeof e=="string"?new r(e):typeof e.uint8Array=="function"?new r(e.uint8Array()):null}clean(){if((this._buf==null||this._buf.byteLength===0)&&(this._buf=AI),this._buf[0]!==B2){let e=new Uint8Array(this._buf.byteLength+1);e.fill(B2,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===B2;)this._buf=this._buf.subarray(0,-1)}less(e){let t=this.list(),n=e.list();for(let i=0;i<t.length;i++){if(n.length<i+1)return!1;let o=t[i],s=n[i];if(o<s)return!0;if(o>s)return!1}return t.length<n.length}reverse(){return r.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){let e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Ys).slice(1)}type(){return Cq(this.baseNamespace())}name(){return Tq(this.baseNamespace())}instance(e){return new r(this.toString()+":"+e)}path(){let e=this.parent().toString();return e.endsWith(Ys)||(e+=Ys),e+=this.type(),new r(e)}parent(){let e=this.list();return e.length===1?new r(Ys):new r(e.slice(0,-1).join(Ys))}child(e){return this.toString()===Ys?e:e.toString()===Ys?this:new r(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()===this.toString()?!1:e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()===this.toString()?!1:this.toString().startsWith(e.toString())}isTopLevel(){return this.list().length===1}concat(...e){return r.withNamespaces([...this.namespaces(),...Iq(e.map(t=>t.namespaces()))])}};function Cq(r){let e=r.split(":");return e.length<2?"":e.slice(0,-1).join(":")}function Tq(r){let e=r.split(":");return e[e.length-1]}function Iq(r){return[].concat(...r)}function L2({enumerable:r=!0,configurable:e=!1}={}){return{enumerable:r,configurable:e,writable:!1}}function*kq(r,e){if(e!=null&&typeof e=="object")if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t],o=G.asCID(n);o!=null?yield[i.join("/"),o]:typeof n=="object"&&(yield*qx(n,i))}else{let t=G.asCID(e);t!=null?yield[r.join("/"),t]:yield*qx(e,r)}}function*qx(r,e){if(r==null||r instanceof Uint8Array)return;let t=G.asCID(r);t!=null&&(yield[e.join("/"),t]);for(let[n,i]of Object.entries(r)){let o=[...e,n];yield*kq(o,i)}}function*Pq(r,e){if(Array.isArray(e))for(let[t,n]of e.entries()){let i=[...r,t];yield i.join("/"),typeof n=="object"&&G.asCID(n)==null&&(yield*jx(n,i))}else yield*jx(e,r)}function*jx(r,e){if(!(r==null||typeof r!="object"))for(let[t,n]of Object.entries(r)){let i=[...e,t];yield i.join("/"),n!=null&&!(n instanceof Uint8Array)&&typeof n=="object"&&G.asCID(n)==null&&(yield*Pq(i,n))}}function Rq(r,e){let t=r;for(let[n,i]of e.entries()){if(t=t[i],t==null)throw new Error(`Object has no property at ${e.slice(0,n+1).map(s=>`[${JSON.stringify(s)}]`).join("")}`);let o=G.asCID(t);if(o!=null)return{value:o,remaining:e.slice(n+1).join("/")}}return{value:t}}var Wx=class{cid;bytes;value;asBlock;constructor({cid:e,bytes:t,value:n}){if(e==null||t==null||typeof n>"u")throw new Error("Missing required argument");this.cid=e,this.bytes=t,this.value=n,this.asBlock=this,Object.defineProperties(this,{cid:L2(),bytes:L2(),value:L2(),asBlock:L2()})}links(){return qx(this.value,[])}tree(){return jx(this.value,[])}get(e="/"){return Rq(this.value,e.split("/").filter(Boolean))}};function im({bytes:r,cid:e,value:t,codec:n}){let i=t!==void 0?t:n?.decode(r);if(i===void 0)throw new Error('Missing required argument, must either provide "value" or "codec"');return new Wx({cid:e,bytes:r,value:i})}var _I="/pin/",EI="/pinned-block/",Gx=mn,SI=1;function M2(r){return r.version===0&&(r=r.toV1()),new it(`${_I}${r.toString(Gx)}`)}var U2=class{datastore;blockstore;getCodec;constructor(e,t,n){this.datastore=e,this.blockstore=t,this.getCodec=n}async*add(e,t={}){let n=M2(e);if(await this.datastore.has(n))throw new Error("Already pinned");let i=Math.round(t.depth??1/0);if(i<0)throw new Error("Depth must be greater than or equal to 0");let o=new Dr({concurrency:SI});for await(let a of this.#e(e,o,{...t,depth:i}))await this.#t(a,c=>c.pinnedBy.find(l=>he(l,e.bytes))!=null?!1:(c.pinCount++,c.pinnedBy.push(e.bytes),!0),t),yield a;let s={depth:i,metadata:t.metadata??{}};await this.datastore.put(n,Xs(s),t)}async*#e(e,t,n){if(n.depth===-1)return;let i=await this.getCodec(e.code),o=await this.blockstore.get(e,n),s=im({bytes:o,cid:e,codec:i});yield e;for(let[,a]of s.links())yield*await t.add(async()=>this.#e(a,t,{...n,depth:n.depth-1}))}async#t(e,t,n){let i=new it(`${EI}${Gx.encode(e.multihash.bytes)}`),o={pinCount:0,pinnedBy:[]};try{o=En(await this.datastore.get(i,n))}catch(a){if(a.name!=="NotFoundError")throw a}if(t(o)){if(o.pinCount===0&&await this.datastore.has(i)){await this.datastore.delete(i);return}await this.datastore.put(i,Xs(o),n),n.onProgress?.(new X("helia:pin:add",e))}}async*rm(e,t={}){let n=M2(e),i=await this.datastore.get(n,t),o=En(i);await this.datastore.delete(n,t);let s=new Dr({concurrency:SI});for await(let a of this.#e(e,s,{...t,depth:o.depth}))await this.#t(a,c=>(c.pinCount--,c.pinnedBy=c.pinnedBy.filter(l=>he(l,e.bytes)),!0),{...t,depth:o.depth}),yield a}async*ls(e={}){for await(let{key:t,value:n}of this.datastore.query({prefix:_I+(e.cid!=null?`${e.cid.toString(mn)}`:"")},e)){let i=G.parse(t.toString().substring(5),mn),o=En(n);yield{cid:i,...o}}}async isPinned(e,t={}){let n=new it(`${EI}${Gx.encode(e.multihash.bytes)}`);return this.datastore.has(n,t)}async get(e,t){let n=M2(e),i=await this.datastore.get(n,t);return En(i)}async setMetadata(e,t,n){let i=M2(e),o=await this.datastore.get(i,n),s=En(o);s.metadata=t??{},await this.datastore.put(i,Xs(s),n)}};var F2=class extends Error{static name="InsufficientProvidersError";constructor(e="Insufficient providers found"){super(e),this.name="InsufficientProvidersError"}},Dl=class extends Error{static name="NoRoutersAvailableError";constructor(e="No routers available"){super(e),this.name="NoRoutersAvailableError"}},$2=class extends Error{static name="UnknownHashAlgorithmError";constructor(e="Unknown hash algorithm"){super(e),this.name="UnknownHashAlgorithmError"}},H2=class extends Error{static name="UnknownCodecError";constructor(e="Unknown codec"){super(e),this.name="UnknownCodecError"}};var Dq=5,V2=class{log;routers;providerLookupConcurrency;constructor(e,t){this.log=e.logger.forComponent("helia:routing"),this.routers=t.routers??[],this.providerLookupConcurrency=t.providerLookupConcurrency??Dq,this.findProviders=e.metrics?.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1})??this.findProviders,this.provide=e.metrics?.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1})??this.cancelReprovide,this.put=e.metrics?.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2})??this.put,this.get=e.metrics?.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1})??this.get,this.findPeer=e.metrics?.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1})??this.getClosestPeers}async start(){await Rr(...this.routers)}async stop(){await Zr(...this.routers)}async*findProviders(e,t={}){if(this.routers.length===0)throw new Dl("No content routers available");let n=new Or({concurrency:this.providerLookupConcurrency});n.addEventListener("error",()=>{});for await(let i of pn(n.toGenerator(),...Ol(this.routers,"findProviders").map(o=>o.findProviders(e,t))))if(i!=null){if(i.multiaddrs.length===0){if(n.find(i.id)!=null)continue;n.add(async()=>{try{let o=await this.findPeer(i.id,t);return o.multiaddrs.length===0?null:o}catch(o){return this.log.error("could not load multiaddrs for peer %p",i.id,o),null}},{peerId:i.id,signal:t.signal}).catch(o=>{this.log.error("could not load multiaddrs for peer %p",i.id,o)})}yield i}}async provide(e,t={}){if(this.routers.length===0)throw new Dl("No content routers available");await Promise.all(Ol(this.routers,"provide").map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){await Promise.all(Ol(this.routers,"cancelReprovide").map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){await Promise.all(Ol(this.routers,"put").map(async i=>{await i.put(e,t,n)}))}async get(e,t){return Promise.any(Ol(this.routers,"get").map(async n=>n.get(e,t)))}async findPeer(e,t){if(this.routers.length===0)throw new Dl("No peer routers available");let n=this,i=pn(...Ol(this.routers,"findPeer").map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let o of i)if(o!=null)return o;throw new qe("Could not find peer in routing")}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Dl("No peer routers available");for await(let n of pn(...Ol(this.routers,"getClosestPeers").map(i=>i.getClosestPeers(e,t))))n!=null&&(yield n)}};function Ol(r,e){return r.filter(t=>t[e]!=null)}var K2=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}};var z2=class{deferred;signal;constructor(e){this.signal=e,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new ti)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function Oq(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var q2=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=Oq(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){this.recipients.reduce((t,n)=>t&&n.signal?.aborted===!0,!0)&&(this.controller.abort(new ti),this.cleanup())}async join(e={}){let t=new z2(e.signal);return this.recipients.push(t),e.signal?.addEventListener("abort",this.onAbort),t.deferred.promise}async run(){this.status="running",this.timeline.started=Date.now();try{this.controller.signal.throwIfAborted();let e=await dt(this.fn({...this.options??{},signal:this.controller.signal}),this.controller.signal);this.recipients.forEach(t=>{t.deferred.resolve(e)}),this.status="complete"}catch(e){this.recipients.forEach(t=>{t.deferred.reject(e)}),this.status="errored"}finally{this.timeline.finished=Date.now(),this.cleanup()}}cleanup(){this.recipients.forEach(e=>{e.cleanup(),e.signal?.removeEventListener("abort",this.onAbort)})}};function Xx(r,e){let t,n=function(){let i=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(i,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var om=class extends De{concurrency;maxSize;queue;pending;sort;autoStart;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=e.autoStart??!0,this.sort=e.sort,this.queue=[],this.emitEmpty=Xx(this.emitEmpty.bind(this),1),this.emitIdle=Xx(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(this.size===0)return this.emitEmpty(),this.running===0&&this.emitIdle(),!1;if(this.pending<this.concurrency){let e;for(let t of this.queue)if(t.status==="queued"){e=t;break}return e==null?!1:(this.safeDispatchEvent("active"),this.pending++,e.run().finally(()=>{for(let t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()}),!0)}return!1}enqueue(e){this.queue.push(e),this.sort!=null&&this.queue.sort(this.sort)}start(){this.autoStart===!1&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}async add(e,t){if(t?.signal?.throwIfAborted(),this.size===this.maxSize)throw new K2;let n=new q2(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.autoStart&&this.tryToStartAnother(),n.join(t).then(i=>(this.safeDispatchEvent("success",{detail:{job:n,result:i}}),i)).catch(i=>{if(n.status==="queued"){for(let o=0;o<this.queue.length;o++)if(this.queue[o]===n){this.queue.splice(o,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:i}}),i})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new ti)}),this.clear()}async onEmpty(e){this.size!==0&&await Kt(this,"empty",e?.signal)}async onSizeLessThan(e,t){this.size<e||await Kt(this,"next",t?.signal,{filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Kt(this,"idle",e?.signal)}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}async*toGenerator(e){e?.signal?.throwIfAborted();let t=ar({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},i=c=>{c.detail!=null&&t.push(c.detail.result)},o=c=>{n(c.detail.error)},s=()=>{n()},a=()=>{n(new ti("Queue aborted"))};this.addEventListener("success",i),this.addEventListener("failure",o),this.addEventListener("idle",s),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("success",i),this.removeEventListener("failure",o),this.removeEventListener("idle",s),e?.signal?.removeEventListener("abort",a),n()}}};var j2="lock:worker:request-read",W2="lock:worker:abort-read-request",G2="lock:worker:release-read",X2="lock:master:grant-read",Y2="lock:master:error-read",Q2="lock:worker:request-write",Z2="lock:worker:abort-write-request",J2="lock:worker:release-write",ey="lock:master:grant-write",ty="lock:master:error-write",ry="lock:worker:finalize",ny="mortice",CI={singleProcess:!1};var Yx=(r,e,t,n,i,o,s,a,c)=>l=>{if(l.data==null)return;let u={type:l.data.type,name:l.data.name,identifier:l.data.identifier};u.type===i&&r.safeDispatchEvent(t,{detail:{name:u.name,identifier:u.identifier,handler:async()=>{e.postMessage({type:c,name:u.name,identifier:u.identifier}),await new Promise(f=>{let d=h=>{if(h?.data==null)return;let m={type:h.data.type,name:h.data.name,identifier:h.data.identifier};m.type===a&&m.identifier===u.identifier&&(e.removeEventListener("message",d),f())};e.addEventListener("message",d)})},onError:f=>{e.postMessage({type:s,name:u.name,identifier:u.identifier,error:{message:f.message,name:f.name,stack:f.stack}})}}}),u.type===o&&r.safeDispatchEvent(n,{detail:{name:u.name,identifier:u.identifier}}),u.type===ry&&r.safeDispatchEvent("finalizeRequest",{detail:{name:u.name}})};var TI=(r=10)=>Math.random().toString().substring(2,r+2);var iy=class{name;channel;constructor(e){this.name=e,this.channel=new BroadcastChannel(ny)}readLock(e){return this.sendRequest(j2,W2,X2,Y2,G2,e)}writeLock(e){return this.sendRequest(Q2,Z2,ey,ty,J2,e)}finalize(){this.channel.postMessage({type:ry,name:this.name}),this.channel.close()}async sendRequest(e,t,n,i,o,s){s?.signal?.throwIfAborted();let a=TI();return this.channel.postMessage({type:e,identifier:a,name:this.name}),new Promise((c,l)=>{let u=()=>{this.channel.postMessage({type:t,identifier:a,name:this.name})};s?.signal?.addEventListener("abort",u,{once:!0});let f=d=>{if(d.data?.identifier===a&&(d.data?.type===n&&(this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",u),c(()=>{this.channel.postMessage({type:o,identifier:a,name:this.name})})),d.data.type===i)){this.channel.removeEventListener("message",f),s?.signal?.removeEventListener("abort",u);let h=new Error;d.data.error!=null&&(h.message=d.data.error.message,h.name=d.data.error.name,h.stack=d.data.error.stack),l(h)}};this.channel.addEventListener("message",f)})}};var II=r=>{if(r=Object.assign({},CI,r),!!globalThis.document||r.singleProcess){let t=new BroadcastChannel(ny),n=new De;return t.addEventListener("message",Yx(n,t,"requestReadLock","abortReadLockRequest",j2,W2,Y2,G2,X2)),t.addEventListener("message",Yx(n,t,"requestWriteLock","abortWriteLockRequest",Q2,Z2,ty,J2,ey)),n}return new iy(r.name)};var Nl=new Map,sm;function kI(r){return typeof r?.readLock=="function"&&typeof r?.writeLock=="function"}function Nq(r){if(sm==null&&(sm=II(r),!kI(sm))){let e=sm;e.addEventListener("requestReadLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=Nl.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortReadLockRequest",a),o.readLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortReadLockRequest",a)})}),e.addEventListener("requestWriteLock",t=>{let n=t.detail.name,i=t.detail.identifier,o=Nl.get(n);if(o==null)return;let s=new AbortController,a=c=>{c.detail.name!==n||c.detail.identifier!==i||s.abort()};e.addEventListener("abortWriteLockRequest",a),o.writeLock({signal:s.signal}).then(async c=>{await t.detail.handler().finally(()=>{c()})}).catch(c=>{t.detail.onError(c)}).finally(()=>{e.removeEventListener("abortWriteLockRequest",a)})}),e.addEventListener("finalizeRequest",t=>{let n=t.detail.name,i=Nl.get(n);i?.finalize()})}return sm}async function Qx(r,e){let t,n,i=new Promise((s,a)=>{t=s,n=a}),o=()=>{n(new ti)};return e?.signal?.addEventListener("abort",o,{once:!0}),r.add(async()=>{await new Promise(s=>{t(()=>{e?.signal?.removeEventListener("abort",o),s()})})},{signal:e?.signal}).catch(s=>{n(s)}),i}var PI=(r,e)=>{let t=Nl.get(r);if(t!=null)return t;let n=Nq(e);if(kI(n))return t=n,Nl.set(r,t),t;let i=new om({concurrency:1}),o;return t={async readLock(s){if(o!=null)return Qx(o,s);o=new om({concurrency:e.concurrency,autoStart:!1});let a=o,c=Qx(o,s);return i.add(async()=>{a.start(),await a.onIdle().then(()=>{o===a&&(o=null)})}),c},async writeLock(s){return o=null,Qx(i,s)},finalize:()=>{Nl.delete(r)},queue:i},Nl.set(r,t),e.autoFinalize===!0&&i.addEventListener("idle",()=>{t.finalize()},{once:!0}),t};var Bq={name:"lock",concurrency:1/0,singleProcess:!1,autoFinalize:!1};function am(r){let e=Object.assign({},Bq,r);return PI(e.name,e)}var oy=class{lock;child;pins;started;constructor(e,t,n={}){this.child=e,this.pins=t,this.lock=am({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}async start(){await Rr(this.child),this.started=!0}async stop(){await Zr(this.child),this.started=!1}unwrap(){return this.child}async put(e,t,n={}){n?.signal?.throwIfAborted();let i=await this.lock.readLock();try{return await this.child.put(e,t,n)}finally{i()}}async*putMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.putMany(e,t)}finally{n()}}async get(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.get(e,t)}finally{n()}}async*getMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{yield*this.child.getMany(e,t)}finally{n()}}async delete(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{if(await this.pins.isPinned(e))throw new Error("CID was pinned");await this.child.delete(e,t)}finally{n()}}async*deleteMany(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.writeLock();try{let i=this;yield*this.child.deleteMany((async function*(){for await(let o of e){if(await i.pins.isPinned(o))throw new Error("CID was pinned");yield o}})(),t)}finally{n()}}async has(e,t={}){t?.signal?.throwIfAborted();let n=await this.lock.readLock();try{return await this.child.has(e,t)}finally{n()}}async*getAll(e={}){e?.signal?.throwIfAborted();let t=await this.lock.readLock();try{yield*this.child.getAll(e)}finally{t()}}createSession(e,t){return t?.signal?.throwIfAborted(),this.child.createSession(e,t)}};var Zx=new it("/version"),RI=1;async function DI(r){if(!await r.has(Zx)){await r.put(Zx,D(`${RI}`));return}let e=await r.get(Zx),t=z(e);if(parseInt(t,10)!==RI)throw new Error("Unknown datastore version, a datastore migration may be required")}var Qs={};$t(Qs,{code:()=>Mr,decode:()=>rs,decodeOptions:()=>Vq,encode:()=>cd,encodeOptions:()=>$q,name:()=>Kq,toByteView:()=>NI});var OI=42;function NI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Lq(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=G.asCID(r);if(!e)return null;let t=new Uint8Array(e.bytes.byteLength+1);return t.set(e.bytes,1),[new Y(I.tag,OI),new Y(I.bytes,t)]}function Mq(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Uq(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function Fq(r){for(let e of r.keys())if(typeof e!="string"||e.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Jx={float64:!0,typeEncoders:{Map:Fq,Object:Lq,undefined:Mq,number:Uq}},$q={...Jx,typeEncoders:{...Jx.typeEncoders}};function Hq(r){if(r[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return G.decode(r.subarray(1))}var sy={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};sy.tags[OI]=Hq;var Vq={...sy,tags:sy.tags.slice()},Kq="dag-cbor",Mr=113,cd=r=>Xs(r,Jx),rs=r=>En(NI(r),sy);var Bl={};$t(Bl,{code:()=>xo,decode:()=>ud,encode:()=>cy,format:()=>ej,name:()=>Jq,parse:()=>rj,stringify:()=>ej});var e9=class extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){let t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===I.array&&(t.elements++,t.elements!==1&&e.push([44])),t.type===I.map&&(t.elements++,t.elements!==1&&(t.elements%2===1?e.push([44]):e.push([58]))))}[I.uint.major](e,t){this.prefix(e);let n=String(t.value),i=[];for(let o=0;o<n.length;o++)i[o]=n.charCodeAt(o);e.push(i)}[I.negint.major](e,t){this[I.uint.major](e,t)}[I.bytes.major](e,t){throw new Error(`${Ws} unsupported type: Uint8Array`)}[I.string.major](e,t){this.prefix(e);let n=S2(JSON.stringify(t.value));e.push(n.length>32?Qp(n):n)}[I.array.major](e,t){this.prefix(e),this.inRecursive.push({type:I.array,elements:0}),e.push([91])}[I.map.major](e,t){this.prefix(e),this.inRecursive.push({type:I.map,elements:0}),e.push([123])}[I.tag.major](e,t){}[I.float.major](e,t){if(t.type.name==="break"){let s=this.inRecursive.pop();if(s){if(s.type===I.array)e.push([93]);else if(s.type===I.map)e.push([125]);else throw new Error("Unexpected recursive type; this should not happen!");return}throw new Error("Unexpected break; this should not happen!")}if(t.value===void 0)throw new Error(`${Ws} unsupported type: undefined`);if(this.prefix(e),t.type.name==="true"){e.push([116,114,117,101]);return}else if(t.type.name==="false"){e.push([102,97,108,115,101]);return}else if(t.type.name==="null"){e.push([110,117,108,108]);return}let n=String(t.value),i=[],o=!1;for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s),!o&&(i[s]===46||i[s]===101||i[s]===69)&&(o=!0);o||(i.push(46),i.push(48)),e.push(i)}};function zq(r,e){if(Array.isArray(r[0])||Array.isArray(e[0]))throw new Error(`${Ws} complex map keys are not supported`);let t=r[0],n=e[0];if(t.type!==I.string||n.type!==I.string)throw new Error(`${Ws} non-string map keys are not supported`);if(t<n)return-1;if(t>n)return 1;throw new Error(`${Ws} unexpected duplicate map keys, this is not supported`)}var qq={addBreakTokens:!0,mapSorter:zq};function cm(r,e){return e=Object.assign({},qq,e),Vx(r,new e9,e)}var ld=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){let e=this.ch();for(;e===32||e===9||e===13||e===10;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error(`${me} unexpected end of input at position ${this._pos}`);for(let t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error(`${me} unexpected token at position ${this._pos}, expected to find '${String.fromCharCode(...e)}'`)}parseNumber(){let e=this._pos,t=!1,n=!1,i=a=>{for(;!this.done();){let c=this.ch();if(a.includes(c))this._pos++;else break}};if(this.ch()===45&&(t=!0,this._pos++),this.ch()===48)if(this._pos++,this.ch()===46)this._pos++,n=!0;else return new Y(I.uint,0,this._pos-e);if(i([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error(`${me} unexpected token at position ${this._pos}`);if(!this.done()&&this.ch()===46){if(n)throw new Error(`${me} unexpected token at position ${this._pos}`);n=!0,this._pos++,i([48,49,50,51,52,53,54,55,56,57])}!this.done()&&(this.ch()===101||this.ch()===69)&&(n=!0,this._pos++,!this.done()&&(this.ch()===43||this.ch()===45)&&this._pos++,i([48,49,50,51,52,53,54,55,56,57]));let o=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),s=parseFloat(o);return n?new Y(I.float,s,this._pos-e):this.options.allowBigInt!==!0||Number.isSafeInteger(s)?new Y(s>=0?I.uint:I.negint,s,this._pos-e):new Y(s>=0?I.uint:I.negint,BigInt(o),this._pos-e)}parseString(){if(this.ch()!==34)throw new Error(`${me} unexpected character at position ${this._pos}; this shouldn't happen`);this._pos++;for(let o=this._pos,s=0;o<this.data.length&&s<65536;o++,s++){let a=this.data[o];if(a===92||a<32||a>=128)break;if(a===34){let c=String.fromCharCode.apply(null,this.data.subarray(this._pos,o));return this._pos=o+1,new Y(I.string,c,s)}}let e=this._pos,t=[],n=()=>{if(this._pos+4>=this.data.length)throw new Error(`${me} unexpected end of unicode escape sequence at position ${this._pos}`);let o=0;for(let s=0;s<4;s++){let a=this.ch();if(a>=48&&a<=57)a-=48;else if(a>=97&&a<=102)a=a-97+10;else if(a>=65&&a<=70)a=a-65+10;else throw new Error(`${me} unexpected unicode escape character at position ${this._pos}`);o=o*16+a,this._pos++}return o},i=()=>{let o=this.ch(),s=null,a=o>239?4:o>223?3:o>191?2:1;if(this._pos+a>this.data.length)throw new Error(`${me} unexpected unicode sequence at position ${this._pos}`);let c,l,u,f;switch(a){case 1:o<128&&(s=o);break;case 2:c=this.data[this._pos+1],(c&192)===128&&(f=(o&31)<<6|c&63,f>127&&(s=f));break;case 3:c=this.data[this._pos+1],l=this.data[this._pos+2],(c&192)===128&&(l&192)===128&&(f=(o&15)<<12|(c&63)<<6|l&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:c=this.data[this._pos+1],l=this.data[this._pos+2],u=this.data[this._pos+3],(c&192)===128&&(l&192)===128&&(u&192)===128&&(f=(o&15)<<18|(c&63)<<12|(l&63)<<6|u&63,f>65535&&f<1114112&&(s=f))}s===null?(s=65533,a=1):s>65535&&(s-=65536,t.push(s>>>10&1023|55296),s=56320|s&1023),t.push(s),this._pos+=a};for(;!this.done();){let o=this.ch(),s;switch(o){case 92:if(this._pos++,this.done())throw new Error(`${me} unexpected string termination at position ${this._pos}`);switch(s=this.ch(),this._pos++,s){case 34:case 39:case 92:case 47:t.push(s);break;case 98:t.push(8);break;case 116:t.push(9);break;case 110:t.push(10);break;case 102:t.push(12);break;case 114:t.push(13);break;case 117:t.push(n());break;default:throw new Error(`${me} unexpected string escape character at position ${this._pos}`)}break;case 34:return this._pos++,new Y(I.string,Nx(t),this._pos-e);default:if(o<32)throw new Error(`${me} invalid control character at position ${this._pos}`);o<128?(t.push(o),this._pos++):i()}}throw new Error(`${me} unexpected end of string at position ${this._pos}`)}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new Y(I.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new Y(I.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new Y(I.null,null,4);case 102:return this.expect([102,97,108,115,101]),new Y(I.false,!1,5);case 116:return this.expect([116,114,117,101]),new Y(I.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error(`${me} unexpected character at position ${this._pos}`)}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":{if(this.modeStack.pop(),this.ch()===93)return this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${me} unexpected character at position ${this._pos}, was expecting array delimiter but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue()}case"array-start":return this.modeStack.pop(),this.ch()===93?(this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(this.ch()===125)return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1);if(this.ch()!==44)throw new Error(`${me} unexpected character at position ${this._pos}, was expecting object delimiter but found '${String.fromCharCode(this.ch())}'`);this._pos++,this.skipWhitespace();case"obj-start":{if(this.modeStack.pop(),this.ch()===125)return this._pos++,this.skipWhitespace(),new Y(I.break,void 0,1);let e=this.parseString();if(this.skipWhitespace(),this.ch()!==58)throw new Error(`${me} unexpected character at position ${this._pos}, was expecting key/value delimiter ':' but found '${String.fromCharCode(this.ch())}'`);return this._pos++,this.modeStack.push("obj-value"),e}case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error(`${me} unexpected parse state at position ${this._pos}; this shouldn't happen`)}}};function t9(r,e){return e=Object.assign({tokenizer:new ld(r,e)},e),En(r,e)}function Wq(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}function Gq(r){if(r.asCID!==r&&r["/"]!==r.bytes)return null;let e=G.asCID(r);if(!e)return null;let t=e.toString();return[new Y(I.map,1/0,1),new Y(I.string,"/",1),new Y(I.string,t,t.length),new Y(I.break,void 0,1)]}function ay(r){let e=cr.encode(r).slice(1);return[new Y(I.map,1/0,1),new Y(I.string,"/",1),new Y(I.map,1/0,1),new Y(I.string,"bytes",5),new Y(I.string,e,e.length),new Y(I.break,void 0,1),new Y(I.break,void 0,1)]}function wo(r){return ay(new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}function Xq(r){return ay(new Uint8Array(r))}function Yq(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Qq(r){if(Number.isNaN(r))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(r===1/0||r===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}var Zq={typeEncoders:{Object:Gq,Buffer:ay,Uint8Array:ay,Int8Array:wo,Uint16Array:wo,Int16Array:wo,Uint32Array:wo,Int32Array:wo,Float32Array:wo,Float64Array:wo,Uint8ClampedArray:wo,BigInt64Array:wo,BigUint64Array:wo,DataView:wo,ArrayBuffer:Xq,undefined:Yq,number:Qq}},r9=class extends ld{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return this.tokenBuffer.length===0&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){let e=this._next();if(e.type===I.map){let t=this._next();if(t.type===I.string&&t.value==="/"){let n=this._next();if(n.type===I.string){if(this._next().type!==I.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(n),new Y(I.tag,42,0)}if(n.type===I.map){let i=this._next();if(i.type===I.string&&i.value==="bytes"){let o=this._next();if(o.type===I.string){for(let a=0;a<2;a++)if(this._next().type!==I.break)throw new Error("Invalid encoded Bytes form");let s=cr.decode(`m${o.value}`);return new Y(I.bytes,s,o.value.length)}this.tokenBuffer.push(o)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(t)}return e}},n9={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};n9.tags[42]=G.parse;var Jq="dag-json",xo=297,cy=r=>cm(r,Zq),ud=r=>{let e=Wq(r),t=Object.assign(n9,{tokenizer:new r9(e,n9)});return t9(e,t)},ej=r=>tj.decode(cy(r));var tj=new TextDecoder,rj=r=>ud(nj.encode(r)),nj=new TextEncoder;var ir={};$t(ir,{code:()=>tt,createLink:()=>zI,createNode:()=>KI,decode:()=>nr,encode:()=>Qe,name:()=>pj,prepare:()=>Wt,validate:()=>s9});var ij=new TextDecoder;function i9(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function ly(r,e){let t;[t,e]=i9(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function BI(r,e){let t;return[t,e]=i9(r,e),[t&7,t>>3,e]}function oj(r){let e={},t=r.length,n=0;for(;n<t;){let i,o;if([i,o,n]=BI(r,n),o===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=ly(r,n)}else if(o===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let s;[s,n]=ly(r,n),e.Name=ij.decode(s)}else if(o===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=i9(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${o}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function LI(r){let e=r.length,t=0,n,i=!1,o;for(;t<e;){let a,c;if([a,c,t]=BI(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,t]=ly(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=ly(r,t),n.push(oj(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let s={};return o&&(s.Data=o),s.Links=n||[],s}var UI=new TextEncoder,MI=2**32,sj=2**31;function aj(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=lm(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=UI.encode(r.Name);t-=n.length,e.set(n,t),t=lm(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=lm(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function FI(r){let e=lj(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=lm(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let o=aj(r.Links[i],t.subarray(0,n));n-=o,n=lm(t,n,o)-1,t[n]=18}return t}function cj(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+fd(t)}if(typeof r.Name=="string"){let t=UI.encode(r.Name).length;e+=1+t+fd(t)}return typeof r.Tsize=="number"&&(e+=1+fd(r.Tsize)),e}function lj(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+fd(t)}if(r.Links)for(let t of r.Links){let n=cj(t);e+=1+n+fd(n)}return e}function lm(r,e,t){e-=fd(t);let n=e;for(;t>=sj;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function fd(r){return r%2===0&&r++,Math.floor((uj(r)+6)/7)}function uj(r){let e=0;return r>=MI&&(r=Math.floor(r/MI),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+fj[r]}var fj=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];var dj=["Data","Links"],hj=["Hash","Name","Tsize"],o9=new TextEncoder;function HI(r,e){if(r===e)return 0;let t=r.Name?o9.encode(r.Name):[],n=e.Name?o9.encode(e.Name):[],i=t.length,o=n.length;for(let s=0,a=Math.min(i,o);s<a;++s)if(t[s]!==n[s]){i=t[s],o=n[s];break}return i<o?-1:o<i?1:0}function $I(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function VI(r){if(typeof r.asCID=="object"){let t=G.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=G.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=G.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=G.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function Wt(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=o9.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(VI),e.Links.sort(HI);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function s9(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!$I(r,dj))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!$I(t,hj))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&HI(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function KI(r,e=[]){return Wt({Data:r,Links:e})}function zI(r,e,t){return VI({Hash:t,Name:r,Tsize:e})}function qI(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var pj="dag-pb",tt=112;function Qe(r){s9(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),FI(e)}function nr(r){let e=qI(r),t=LI(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let o={};try{o.Hash=G.decode(i.Hash)}catch{}if(!o.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(o.Name=i.Name),i.Tsize!==void 0&&(o.Tsize=i.Tsize),o})),n}function dd(r){return r?.then!=null}function jI(r=[],e){let t={[tt]:ir,[At]:Rn,[Mr]:Qs,[xo]:Bl,[Go]:Tf};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);dd(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new H2(`Could not load codec for ${n}`)}}function WI(r=[],e){let t={[Be.code]:Be,[Bg.code]:Bg,[lr.code]:lr};return r.forEach(n=>{t[n.code]=n}),async n=>{let i=t[n];if(i==null&&e!=null){let o=e(n);dd(o)?i=await o:i=o,t[i.code]=i}if(i!=null)return i;throw new $2(`No hasher configured for multihash code 0x${n.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`)}}var Ui=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not Found"){super(e)}};var Zs=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,block:i}of e)await this.put(n,i,t),yield n}get(e,t){return Promise.reject(new Error(".get is not implemented"))}async*getMany(e,t){for await(let n of e)yield{cid:n,block:await this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}};var uy=0,fy=class extends Zs{child;constructor(e){super(),this.child=e}put(e,t,n){return e.multihash.code===uy||this.child==null?(n?.signal?.throwIfAborted(),e):this.child.put(e,t,n)}get(e,t){if(e.multihash.code===uy)return t?.signal?.throwIfAborted(),e.multihash.digest;if(this.child==null)throw t?.signal?.throwIfAborted(),new Ui;return this.child.get(e,t)}has(e,t){return e.multihash.code===uy?(t?.signal?.throwIfAborted(),!0):this.child==null?(t?.signal?.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){if(e.code===uy){t?.signal?.throwIfAborted();return}if(this.child!=null)return this.child.delete(e,t)}getAll(e){return this.child!=null?this.child.getAll(e):(e?.signal?.throwIfAborted(),[])}};function mj(r){return r[Symbol.asyncIterator]!=null}function gj(r,e){let t=0;if(mj(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=_f(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();let s=e(i,t++);if(typeof s.then=="function")return(async function*(){await s&&(yield i);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){s===!0&&(yield i);for(let c of n)a(c,t++)&&(yield c)})()}var di=gj;function yj(r){return r[Symbol.asyncIterator]!=null}function GI(r){return r?.then!=null}function wj(r,e){let t=0;if(yj(r))return(async function*(){for await(let c of r){let l=e(c,t++);GI(l)&&await l,yield c}})();let n=_f(r),{value:i,done:o}=n.next();if(o===!0)return(function*(){})();if(typeof e(i,t++)?.then=="function")return(async function*(){yield i;for(let c of n){let l=e(c,t++);GI(l)&&await l,yield c}})();let a=e;return(function*(){yield i;for(let c of n)a(c,t++),yield c})()}var Ll=wj;var dy=class{child;getHasher;log;logger;components;constructor(e){this.log=e.logger.forComponent("helia:networked-storage"),this.logger=e.logger,this.components=e,this.child=new fy(e.blockstore),this.getHasher=e.getHasher}async put(e,t,n={}){return await this.child.has(e,n)?(n.onProgress?.(new X("blocks:put:duplicate",e)),e):(n.onProgress?.(new X("blocks:put:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async i=>i.announce?.(e,t,n))),n.onProgress?.(new X("blocks:put:blockstore:put",e)),this.child.put(e,t,n))}async*putMany(e,t={}){let n=di(e,async({cid:o})=>{let s=await this.child.has(o,t);return s&&t.onProgress?.(new X("blocks:put-many:duplicate",o)),!s}),i=Ll(n,async({cid:o,block:s})=>{t.onProgress?.(new X("blocks:put-many:providers:notify",o)),await Promise.all(this.components.blockBrokers.map(async a=>a.announce?.(o,s,t)))});t.onProgress?.(new X("blocks:put-many:blockstore:put-many")),yield*this.child.putMany(i,t)}async get(e,t={}){if(t.offline!==!0&&!await this.child.has(e,t)){let n=await this.getHasher(e.multihash.code);t.onProgress?.(new X("blocks:get:providers:get",e));let i=await XI(e,this.components.blockBrokers,n,{...t,log:this.log});return t.onProgress?.(new X("blocks:get:blockstore:put",e)),await this.child.put(e,i,t),t.onProgress?.(new X("blocks:get:providers:notify",e)),await Promise.all(this.components.blockBrokers.map(async o=>o.announce?.(e,i,t))),i}return t.onProgress?.(new X("blocks:get:blockstore:get",e)),this.child.get(e,t)}async*getMany(e,t={}){t.onProgress?.(new X("blocks:get-many:blockstore:get-many")),yield*this.child.getMany(Ll(e,async n=>{if(t.offline!==!0&&!await this.child.has(n,t)){let i=await this.getHasher(n.multihash.code);t.onProgress?.(new X("blocks:get-many:providers:get",n));let o=await XI(n,this.components.blockBrokers,i,{...t,log:this.log});t.onProgress?.(new X("blocks:get-many:blockstore:put",n)),await this.child.put(n,o,t),t.onProgress?.(new X("blocks:get-many:providers:notify",n)),await Promise.all(this.components.blockBrokers.map(async s=>s.announce?.(n,o,t)))}}))}async delete(e,t={}){t.onProgress?.(new X("blocks:delete:blockstore:delete",e)),await this.child.delete(e,t)}async*deleteMany(e,t={}){t.onProgress?.(new X("blocks:delete-many:blockstore:delete-many")),yield*this.child.deleteMany((async function*(){for await(let n of e)yield n})(),t)}async has(e,t={}){return this.child.has(e,t)}async*getAll(e={}){e.onProgress?.(new X("blocks:get-all:blockstore:get-many")),yield*this.child.getAll(e)}},hy=class extends dy{started;constructor(e){super(e),this.started=!1}isStarted(){return this.started}async start(){await Rr(this.child,...this.components.blockBrokers),this.started=!0}async stop(){await Zr(this.child,...this.components.blockBrokers),this.started=!1}unwrap(){return this.child}createSession(e,t){let n=this.components.blockBrokers.map(i=>i.createSession==null?i:i.createSession(t));return new a9({blockstore:this.child,blockBrokers:n,getHasher:this.getHasher,logger:this.logger},{root:e})}},a9=class extends dy{closeController;constructor(e,t){super(e),this.closeController=new AbortController,this.closeController.signal,this.log=e.logger.forComponent(`helia:session-storage:${t.root}`)}close(){this.closeController.abort()}async put(e,t,n={}){let i=Pe([this.closeController.signal,n.signal]);try{return await super.put(e,t,{...n,signal:i})}finally{i.clear()}}async*putMany(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{yield*super.putMany(e,{...t,signal:n})}finally{n.clear()}}async get(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{return await super.get(e,{...t,signal:n})}finally{n.clear()}}async*getMany(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{yield*super.getMany(e,{...t,signal:n})}finally{n.clear()}}async delete(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{await super.delete(e,{...t,signal:n})}finally{n.clear()}}async*deleteMany(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{yield*super.deleteMany(e,{...t,signal:n})}finally{n.clear()}}async has(e,t={}){let n=Pe([this.closeController.signal,t.signal]);try{return await super.has(e,{...t,signal:n})}finally{n.clear()}}async*getAll(e={}){let t=Pe([this.closeController.signal,e.signal]);try{yield*super.getAll({...e,signal:t})}finally{t.clear()}}};function xj(r){return typeof r.retrieve=="function"}var bj=(r,e)=>{if(e==null)throw new K(`No hasher configured for multihash code 0x${r.multihash.code.toString(16)}, please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv`);return async t=>{let n,i=e.digest(t);if(dd(i)?n=await i:n=i,!he(n.digest,r.multihash.digest))throw new Ua("Hash of downloaded block did not match multihash from passed CID")}};async function XI(r,e,t,n){let i=bj(r,t),o=new AbortController,s=Pe([o.signal,n.signal]);o.signal;let a=[];for(let c of e)xj(c)&&a.push(c);try{return await Promise.any(a.map(async c=>{try{let l=!1,u=await c.retrieve(r,{...n,signal:s,validateFn:async f=>{await i(f),l=!0}});return l||await i(u),u}catch(l){throw n.log.error("could not retrieve verified block for %c",r,l),l}}))}finally{o.abort(),s.clear()}}var Ml=class extends De{initialPeerSearchComplete;requests;name;log;logger;minProviders;maxProviders;providers;evictionFilter;initialProviders;constructor(e,t){super(),this.name=t.name,this.logger=e.logger,this.log=e.logger.forComponent(this.name),this.requests=new Map,this.minProviders=t.minProviders??1,this.maxProviders=t.maxProviders??5,this.providers=[],this.evictionFilter=on(this.maxProviders),this.initialProviders=t.providers??[]}async retrieve(e,t={}){let n=cr.encode(e.multihash.bytes),i=this.requests.get(n);if(i!=null)return this.log("join existing request for %c",e),i;let o=ve();if(this.requests.set(n,o.promise),this.providers.length===0){let u=!1;this.initialPeerSearchComplete==null&&(u=!0,this.log=this.logger.forComponent(`${this.name}:${e}`),this.initialPeerSearchComplete=this.findProviders(e,this.minProviders,t)),await this.initialPeerSearchComplete,u&&this.log("found initial session peers for %c",e)}let s=!1,a=new Dr({concurrency:this.maxProviders});a.addEventListener("error",()=>{}),a.addEventListener("failure",u=>{this.log.error("error querying provider %o, evicting from session",u.detail.job.options.provider,u.detail.error),this.evict(u.detail.job.options.provider)}),a.addEventListener("success",u=>{s=!0,o.resolve(u.detail.result)}),a.addEventListener("idle",()=>{if(s||t.signal?.aborted===!0){this.log.trace("session idle, found block");return}Promise.resolve().then(async()=>{this.log("no session peers had block for for %c, finding new providers",e);for(let u=0;u<this.minProviders&&this.providers.length!==0;u++){let f=this.providers[Math.floor(Math.random()*this.providers.length)];this.evict(f)}await this.findProviders(e,this.minProviders,t),this.log("found new providers re-retrieving %c",e),this.requests.delete(n),o.resolve(await this.retrieve(e,t))}).catch(u=>{this.log.error("could not find new providers for %c",e,u),o.reject(u)})});let c=u=>{a.add(async()=>this.queryProvider(e,u.detail,t),{provider:u.detail}).catch(f=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,f)})};this.addEventListener("provider",c),Promise.all([...this.providers].map(async u=>a.add(async()=>this.queryProvider(e,u,t),{provider:u}))).catch(u=>{t.signal?.aborted!==!0&&this.log.error("error retrieving session block for %c",e,u)});let l=()=>{o.reject(new Je(t.signal?.reason??"Session aborted")),a.abort()};t.signal?.addEventListener("abort",l);try{return await o.promise}finally{this.removeEventListener("provider",c),t.signal?.removeEventListener("abort",l),a.clear(),this.requests.delete(n)}}evict(e){this.evictionFilter.add(this.toEvictionKey(e));let t=this.providers.findIndex(n=>this.equals(n,e));t!==-1&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return!!(this.providers.find(t=>this.equals(t,e))!=null||this.isEvicted(e))}async findProviders(e,t,n){let i=ve(),o=0;return Promise.resolve().then(async()=>{if(this.log("finding %d-%d new provider(s) for %c",t,this.maxProviders,e),this.initialProviders.length>0)for(;o<t&&this.initialProviders.length>0;){let s=this.initialProviders.pop();if(s==null)break;let a=await this.convertToProvider(s,n);if(n.signal?.aborted===!0)break;if(a!=null&&!this.hasProvider(a)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(a),this.safeDispatchEvent("provider",{detail:a}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(o<this.maxProviders)for await(let s of this.findNewProviders(e,n)){if(o===this.maxProviders||n.signal?.aborted===!0)break;if(!this.hasProvider(s)&&(this.log("found %d/%d new providers",o,this.maxProviders),this.providers.push(s),this.safeDispatchEvent("provider",{detail:s}),o++,o===t&&(this.log("session is ready"),i.resolve()),this.providers.length===this.maxProviders)){this.log("found max session peers",o);break}}if(this.log("found %d/%d new session peers",o,this.maxProviders),o<t)throw new F2(`Found ${o} of ${t} ${this.name} providers for ${e}`)}).catch(s=>{this.log.error("error searching routing for potential session peers for %c",e,s.errors??s),i.reject(s)}),i.promise}};var py=class{libp2p;blockstore;datastore;pins;logger;routing;getCodec;getHasher;dns;metrics;log;constructor(e){this.logger=e.logger??Za(),this.log=this.logger.forComponent("helia"),this.getHasher=WI(e.hashers,e.loadHasher),this.getCodec=jI(e.codecs,e.loadCodec),this.dns=e.dns??Pl(),this.metrics=e.metrics,this.libp2p=e.libp2p;let t={blockstore:e.blockstore,datastore:e.datastore,logger:this.logger,libp2p:this.libp2p,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics,...e.components??{}};this.routing=t.routing=new V2(t,{routers:(e.routers??[]).flatMap(i=>{let o=[i];return i[qo]!=null&&o.push(i[qo]),i[jo]!=null&&o.push(i[jo]),o}),providerLookupConcurrency:e.providerLookupConcurrency});let n=new hy(t);this.pins=new U2(e.datastore,n,this.getCodec),this.blockstore=new oy(n,this.pins,{holdGcLock:e.holdGcLock??!0}),this.datastore=e.datastore,t.blockBrokers=e.blockBrokers.map(i=>i(t))}async start(){await DI(this.datastore),await Rr(this.blockstore,this.datastore,this.routing,this.libp2p)}async stop(){await Zr(this.blockstore,this.datastore,this.routing,this.libp2p)}async gc(e={}){let t=await this.blockstore.lock.writeLock();try{let n=this,i=this.blockstore.unwrap();this.log("gc start"),await Jr(i.deleteMany((async function*(){for await(let{cid:o}of i.getAll())try{if(await n.pins.isPinned(o,e))continue;yield o,e.onProgress?.(new X("helia:gc:deleted",o))}catch(s){n.log.error("Error during gc",s),e.onProgress?.(new X("helia:gc:error",s))}})()))}finally{t()}this.log("gc finished")}};var c9=class extends Ml{wantList;network;libp2p;constructor(e,t){super(e,{...t,name:"helia:bitswap:session"}),this.wantList=e.wantList,this.network=e.network,this.libp2p=e.libp2p}async queryProvider(e,t,n){this.log("sending WANT-BLOCK for %c to %p",e,t);let i=await this.wantList.wantSessionBlock(e,t,n);if(this.log("%p %s %c",t,i.has?"has":"does not have",e),i.has&&i.block!=null)return i.block;throw new Error("Provider did not have block")}async*findNewProviders(e,t={}){for await(let n of this.network.findProviders(e,t))yield n.id}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}async convertToProvider(e,t){return Ti(e)?e:(await this.libp2p.dial(e,t)).remotePeer}};function YI(r,e){return new c9(r,e)}var my=class{blocksReceived;duplicateBlocksReceived;dataReceived;duplicateDataReceived;constructor(e){this.blocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=e.metrics?.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=e.metrics?.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.blocksReceived?.increment(n)}updateDuplicateBlocksReceived(e=1,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateBlocksReceived?.increment(n)}updateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.dataReceived?.increment(n)}updateDuplicateDataReceived(e,t){let n={global:e};t!=null&&(n[t.toString()]=e),this.duplicateDataReceived?.increment(n)}};var l9=class extends Map{metric;constructor(e){super();let{name:t,metrics:n}=e;this.metric=n.registerMetric(t),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){let t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}};function hr(r){let{name:e,metrics:t}=r,n;return t!=null?n=new l9({name:e,metrics:t}):n=new Map,n}function Ej(r){if(!(r instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");let e=[];for(;r.length>0;){let t=ao(r);e.push(t),r=r.slice(je(t))}return e}var QI=Ej;var gy=class extends De{peers;wants;network;log;sendMessagesDelay;sendMessagesTimeout;hashLoader;sendingMessages;constructor(e,t={}){super(),this.peers=zs({name:"helia_bitswap_peers",metrics:e.metrics}),this.wants=hr({name:"helia_bitswap_wantlist",metrics:e.metrics}),this.network=e.network,this.sendMessagesDelay=t.sendMessagesDelay??10,this.log=e.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=t.hashLoader,this.network.addEventListener("bitswap:message",n=>{this.receiveMessage(n.detail.peer,n.detail.message).catch(i=>{this.log.error("error receiving bitswap message from %p",n.detail.peer,i)})}),this.network.addEventListener("peer:connected",n=>{this.peerConnected(n.detail).catch(i=>{this.log.error("error processing newly connected bitswap peer %p",n.detail,i)})}),this.network.addEventListener("peer:disconnected",n=>{this.peerDisconnected(n.detail)})}async addEntry(e,t){let n=z(e.multihash.bytes,"base64"),i=this.wants.get(n);i==null&&(i={cid:e,priority:t.priority??1,wantType:t.wantType??tr.WantBlock,cancel:!1,sendDontHave:!0},this.wants.set(n,i)),i.wantType===tr.WantHave&&t.wantType===tr.WantBlock&&(i.wantType=tr.WantBlock),await this.sendMessagesDebounced();try{return t.wantType===tr.WantBlock?(await Kt(this,"block",t?.signal,{filter:a=>he(e.multihash.digest,a.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail:(await Kt(this,"presence",t?.signal,{filter:s=>he(e.multihash.digest,s.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{t.signal?.aborted===!0&&(this.log("want for %c was aborted, cancelling want",e),i.cancel=!0,await this.sendMessagesDebounced())}}async sendMessagesDebounced(){await this.sendingMessages?.promise,clearTimeout(this.sendMessagesTimeout),this.sendMessagesTimeout=setTimeout(()=>{this.sendMessages().catch(e=>{this.log("error sending messages to peers",e)})},this.sendMessagesDelay)}async sendMessages(){this.sendingMessages=ve(),await Promise.all([...this.peers.entries()].map(async([e,t])=>{let n=new Set,i=new qs;for(let[o,s]of this.wants.entries())t.has(o)||s.cancel||(n.add(o),i.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}));if(i.wantlist.size!==0)try{await this.network.sendMessage(e,i);for(let o of n)t.add(o)}catch(o){this.log.error("error sending full wantlist to new peer",o)}})).catch(e=>{this.log.error("error sending messages",e)});for(let[e,t]of this.wants)if(t.cancel){this.wants.delete(e);for(let n of this.peers.values())n.delete(e)}this.sendingMessages.resolve()}has(e){let t=z(e.multihash.bytes,"base64");return this.wants.has(t)}async wantSessionPresence(e,t,n={}){let i=new qs;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:tr.WantHave,priority:1}),await this.network.sendMessage(t,i),(await Kt(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&he(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async wantBlock(e,t={}){return this.addEntry(e,{...t,wantType:tr.WantBlock})}async wantSessionBlock(e,t,n={}){let i=new qs;return i.addWantlistEntry(e,{cid:e.bytes,sendDontHave:!0,wantType:tr.WantBlock,priority:1}),await this.network.sendMessage(t,i),(await Kt(this,"presence",n.signal,{filter:s=>t.equals(s.detail.sender)&&he(e.multihash.digest,s.detail.cid.multihash.digest)})).detail}async receivedBlock(e,t){let n=z(e.multihash.bytes,"base64"),i=this.wants.get(n);i!=null&&(i.cancel=!0,await this.sendMessagesDebounced())}async receiveMessage(e,t){this.log("received message from %p with %d blocks",e,t.blocks.length);let n=!1;for(let i of t.blocks){if(i.prefix==null||i.data==null)continue;let o=QI(i.prefix),s=o[0],a=o[1],c=o[2],l=c===Be.code?Be:await this.hashLoader?.getHasher(c);if(l==null){this.log.error("unknown hash algorithm",c);continue}let u=l.digest(i.data);u.then!=null&&(u=await u);let f=G.create(s===0?0:1,a,u);this.log("received block from %p for %c",e,f),this.safeDispatchEvent("block",{detail:{sender:e,cid:f,block:i.data}}),this.safeDispatchEvent("presence",{detail:{sender:e,cid:f,has:!0,block:i.data}});let d=z(f.multihash.bytes,"base64"),h=this.wants.get(d);h!=null&&(h.cancel=!0,n=!0)}for(let{cid:i,type:o}of t.blockPresences){let s=G.decode(i);this.log("received %s from %p for %c",o,e,s),this.safeDispatchEvent("presence",{detail:{sender:e,cid:s,has:o===Ri.HaveBlock}})}n&&await this.sendMessagesDebounced()}async peerConnected(e){let t=new Set,n=new qs(!0);for(let[i,o]of this.wants.entries())o.cancel||(t.add(i),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:tr.WantBlock,cancel:!1,sendDontHave:!1}));if(n.wantlist.size===0){this.peers.set(e,t);return}try{await this.network.sendMessage(e,n),this.peers.set(e,t)}catch(i){this.log.error("error sending full wantlist to new peer %p",e,i)}}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}};var yy=class{log;logger;stats;network;blockstore;peerWantLists;wantList;libp2p;constructor(e,t={}){this.logger=e.logger,this.log=e.logger.forComponent("helia:bitswap"),this.blockstore=e.blockstore,this.libp2p=e.libp2p,this.stats=new my(e),this.network=new Vg(e,t),this.peerWantLists=new g2({...e,network:this.network},t),this.wantList=new gy({...e,network:this.network},t)}createSession(e={}){return YI({wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},e)}async want(e,t={}){let n=new AbortController,i=Pe([n.signal,t.signal]);n.signal,this.network.findAndConnect(e,{...t,signal:i}).catch(o=>{n.signal.aborted||this.log.error("error during finding and connect for cid %c",e,o)});try{let o=await this.wantList.wantBlock(e,{...t,signal:i});return t.onProgress?.(new X("bitswap:want-block:received",{cid:e,sender:o.sender})),o.block}finally{n.abort(),i.clear()}}async notify(e,t,n={}){await Promise.all([this.peerWantLists.receivedBlock(e,n),this.wantList.receivedBlock(e,n)])}getWantlist(){return[...this.wantList.wants.values()].filter(e=>!e.cancel).map(e=>({cid:e.cid,priority:e.priority,wantType:e.wantType}))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}async start(){this.wantList.start(),await this.network.start()}async stop(){this.wantList.stop(),await this.network.stop()}};var ZI=(r,e={})=>new yy(r,e);var u9=class{bitswap;started;constructor(e,t={}){let{getHasher:n}=e;this.bitswap=ZI(e,{hashLoader:{getHasher:async i=>n(i)},...t}),this.started=!1}isStarted(){return this.started}async start(){await this.bitswap.start(),this.started=!0}async stop(){await this.bitswap.stop(),this.started=!1}async announce(e,t,n){await this.bitswap.notify(e,t,n)}async retrieve(e,t={}){return this.bitswap.want(e,t)}createSession(e){let t=this.bitswap.createSession(e);return{announce:async(n,i,o)=>{await this.bitswap.notify(n,i,o)},retrieve:async(n,i)=>t.retrieve(n,i)}}};function um(r={}){return e=>new u9(e,r)}var Ur=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Js=class extends Error{static name="ValidationError";name="ValidationError"},fm=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},wy=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var xy=class{index=0;input="";new(e){return this.index=0,this.input=e,this}readAtomically(e){let t=this.index,n=e();return n===void 0&&(this.index=t),n}parseWith(e){let t=e();if(this.index===this.input.length)return t}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(e){return this.readAtomically(()=>{let t=this.readChar();if(t===e)return t})}readSeparator(e,t,n){return this.readAtomically(()=>{if(!(t>0&&this.readGivenChar(e)===void 0))return n()})}readNumber(e,t,n,i){return this.readAtomically(()=>{let o=0,s=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*i)-1;for(;;){let u=this.readAtomically(()=>{let f=this.readChar();if(f===void 0)return;let d=Number.parseInt(f,e);if(!Number.isNaN(d))return d});if(u===void 0)break;if(o*=e,o+=u,o>l||(s+=1,t!==void 0&&s>t))return}if(s!==0)return!n&&c&&s>1?void 0:o})}readIPv4Addr(){return this.readAtomically(()=>{let e=new Uint8Array(4);for(let t=0;t<e.length;t++){let n=this.readSeparator(".",t,()=>this.readNumber(10,3,!1,1));if(n===void 0)return;e[t]=n}return e})}readIPv6Addr(){let e=t=>{for(let n=0;n<t.length/2;n++){let i=n*2;if(n<t.length-3){let s=this.readSeparator(":",n,()=>this.readIPv4Addr());if(s!==void 0)return t[i]=s[0],t[i+1]=s[1],t[i+2]=s[2],t[i+3]=s[3],[i+4,!0]}let o=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(o===void 0)return[i,!1];t[i]=o>>8,t[i+1]=o&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,i]=e(t);if(n===16)return t;if(i||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let o=new Uint8Array(14),s=16-(n+2),[a]=e(o.subarray(0,s));return t.set(o.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var JI=45,Sj=15,hd=new xy;function by(r){if(!(r.length>Sj))return hd.new(r).parseWith(()=>hd.readIPv4Addr())}function vy(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>JI))return hd.new(r).parseWith(()=>hd.readIPv6Addr())}function pd(r,e=!1){if(r.includes("%")&&(r=r.split("%")[0]),r.length>JI)return;let t=hd.new(r).parseWith(()=>hd.readIPAddr());if(t)return e&&t.length===4?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,t[0],t[1],t[2],t[3]]):t}function bo(r){return!!by(r)}function Ay(r){return!!vy(r)}function d9(r){return e=>z(e,r)}function h9(r){return e=>D(e,r)}function md(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ul(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function ek(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==16)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion address.`);let t=D(e[0],"base32"),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ul(n);return Xe([t,i],t.length+i.length)}function tk(r){let e=r.split(":");if(e.length!==2)throw new Error(`failed to parse onion addr: ["'${e.join('", "')}'"]' does not contain a port number`);if(e[0].length!==56)throw new Error(`failed to parse onion addr: ${e[0]} not a Tor onion3 address.`);let t=jt.decode(`b${e[0]}`),n=parseInt(e[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");let i=Ul(n);return Xe([t,i],t.length+i.length)}function p9(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),i=md(t);return`${n}:${i}`}var m9=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let i=parseInt(t,10);if(isNaN(i)||i<0||i>255)throw new Ur("Invalid byte value in IP address");e[n]=i}),e},rk=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let o=bo(t[n]),s;o&&(s=m9(t[n]),t[n]=z(s.subarray(0,2),"base16")),s!=null&&++n<8&&t.splice(n,0,z(s.subarray(2,4),"base16"))}if(t[0]==="")for(;t.length<8;)t.unshift("0");else if(t[t.length-1]==="")for(;t.length<8;)t.push("0");else if(t.length<8){for(n=0;n<t.length&&t[n]!=="";n++);let o=[n,1];for(n=9-t.length;n>0;n--)o.push("0");t.splice.apply(t,o)}let i=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let o=parseInt(t[n],16);if(isNaN(o)||o<0||o>65535)throw new Ur("Invalid byte value in IP address");i[e++]=o>>8&255,i[e++]=o&255}return i},nk=function(r){if(r.byteLength!==4)throw new Ur("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},ik=function(r){if(r.byteLength!==16)throw new Ur("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let i=r[n],o=r[n+1],s=`${i.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`;e.push(s)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Ur(`Invalid IPv6 address "${t}"`)}};function ok(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Ur(`Invalid IPv6 address "${r}"`)}}var f9=Object.values(fl).map(r=>r.decoder),_j=(function(){let r=f9[0].or(f9[1]);return f9.slice(2).forEach(e=>r=r.or(e)),r})();function sk(r){return _j.decode(r)}function ak(r){return e=>r.encoder.encode(e)}function Cj(r){if(parseInt(r).toString()!==r)throw new Js("Value must be an integer")}function Tj(r){if(r<0)throw new Js("Value must be a positive integer, or zero")}function Ij(r){return e=>{if(e>r)throw new Js(`Value must be smaller than or equal to ${r}`)}}function kj(...r){return e=>{for(let t of r)t(e)}}var dm=kj(Cj,Tj,Ij(65535));var Ir=-1,g9=class{protocolsByCode=new Map;protocolsByName=new Map;getProtocol(e){let t;if(typeof e=="string"?t=this.protocolsByName.get(e):t=this.protocolsByCode.get(e),t==null)throw new wy(`Protocol ${e} was unknown`);return t}addProtocol(e){this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),e.aliases?.forEach(t=>{this.protocolsByName.set(t,e)})}removeProtocol(e){let t=this.protocolsByCode.get(e);t!=null&&(this.protocolsByCode.delete(t.code),this.protocolsByName.delete(t.name),t.aliases?.forEach(n=>{this.protocolsByName.delete(n)}))}},On=new g9,zj=[{code:4,name:"ip4",size:32,valueToBytes:m9,bytesToValue:nk,validate:r=>{if(!bo(r))throw new Js(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:273,name:"udp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:33,name:"dccp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:41,name:"ip6",size:128,valueToBytes:rk,bytesToValue:ik,stringToValue:ok,validate:r=>{if(!Ay(r))throw new Js(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:Ir},{code:43,name:"ipcidr",size:8,bytesToValue:d9("base10"),valueToBytes:h9("base10")},{code:53,name:"dns",size:Ir,resolvable:!0},{code:54,name:"dns4",size:Ir,resolvable:!0},{code:55,name:"dns6",size:Ir,resolvable:!0},{code:56,name:"dnsaddr",size:Ir,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Ul,bytesToValue:md,validate:dm},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ir,path:!0,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:Ir,bytesToValue:d9("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?h9("base58btc")(r):G.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:p9,valueToBytes:ek},{code:445,name:"onion3",size:296,bytesToValue:p9,valueToBytes:tk},{code:446,name:"garlic64",size:Ir},{code:447,name:"garlic32",size:Ir},{code:448,name:"tls"},{code:449,name:"sni",size:Ir},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ir,bytesToValue:ak(cl),valueToBytes:sk},{code:480,name:"http"},{code:481,name:"http-path",size:Ir,stringToValue:r=>`/${decodeURIComponent(r)}`,valueToString:r=>encodeURIComponent(r.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Ir}];zj.forEach(r=>{On.addProtocol(r)});function ck(r){let e=[],t=0;for(;t<r.length;){let n=ao(r,t),i=On.getProtocol(n),o=je(n),s=qj(i,r,t+o),a=0;s>0&&i.size===Ir&&(a=je(s));let c=o+a+s,l={code:n,name:i.name,bytes:r.subarray(t,t+c)};if(s>0){let u=t+o+a,f=r.subarray(u,u+s);l.value=i.bytesToValue?.(f)??z(f)}e.push(l),t+=c}return e}function lk(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let i=On.getProtocol(n.code),o=je(n.code),s,a=0,c=0;n.value!=null&&(s=i.valueToBytes?.(n.value)??D(n.value),a=s.byteLength,i.size===Ir&&(c=je(a)));let l=new Uint8Array(o+c+a),u=0;Ef(n.code,l,u),u+=o,s!=null&&(i.size===Ir&&(Ef(a,l,u),u+=c),l.set(s,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Xe(t,e)}function uk(r){if(r.charAt(0)!=="/")throw new Ur('String multiaddr must start with "/"');let e=[],t="protocol",n="",i="";for(let o=1;o<r.length;o++){let s=r.charAt(o);s!=="/"&&(t==="protocol"?i+=r.charAt(o):n+=r.charAt(o));let a=o===r.length-1;if(s==="/"||a){let c=On.getProtocol(i);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",i="",t="protocol";continue}else if(a)throw new Ur(`Component ${i} was missing value`);t="value"}else if(t==="value"){let l={code:c.code,name:c.name};if(c.size!=null&&c.size!==0){if(n==="")throw new Ur(`Component ${i} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",i="",t="protocol"}}}if(i!==""&&n!=="")throw new Ur("Incomplete multiaddr");return e}function fk(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=On.getProtocol(e.code);if(t==null)throw new Ur(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function qj(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ao(e,t)}var jj=Symbol.for("nodejs.util.inspect.custom"),C9=Symbol.for("@multiformats/multiaddr"),Wj=[53,54,55,56],_9=class extends Error{constructor(e="No available resolver"){super(e),this.name="NoAvailableResolverError"}};function Gj(r){if(r==null&&(r="/"),rc(r))return r.getComponents();if(r instanceof Uint8Array)return ck(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),uk(r);if(Array.isArray(r))return r;throw new Ur("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Cy=class r{[C9]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Gj(e),t.validate!==!1&&Xj(this)}get bytes(){return this.#r==null&&(this.#r=lk(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=fk(this.#e)),this.#t}toJSON(){return this.toString()}toOptions(){let e,t,n,i,o="";for(let{code:a,name:c,value:l}of this.#e)a===42&&(o=`%${l??""}`),Wj.includes(a)&&(t="tcp",i=443,n=`${l??""}${o}`,e=a===55?6:4),(a===6||a===273)&&(t=c==="tcp"?"tcp":"udp",i=parseInt(l??"")),(a===4||a===41)&&(t="tcp",n=`${l??""}${o}`,e=a===41?6:4);if(e==null||t==null||n==null||i==null)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:e,host:n,transport:t,port:i}}getComponents(){return[...this.#e]}protos(){return this.#e.map(({code:e,value:t})=>{let n=On.getProtocol(e);return{code:e,size:n.size??0,name:n.name,resolvable:!!n.resolvable,path:!!n.path}})}protoCodes(){return this.#e.map(({code:e})=>e)}protoNames(){return this.#e.map(({name:e})=>e)}tuples(){return this.#e.map(({code:e,value:t})=>{if(t==null)return[e];let n=On.getProtocol(e),i=[e];return t!=null&&i.push(n.valueToBytes?.(t)??D(t)),i})}stringTuples(){return this.#e.map(({code:e,value:t})=>t==null?[e]:[e,t])}encapsulate(e){let t=new r(e);return new r([...this.#e,...t.getComponents()],{validate:!1})}decapsulate(e){let t=e.toString(),n=this.toString(),i=n.lastIndexOf(t);if(i<0)throw new fm(`Address ${this.toString()} does not contain subaddress: ${e.toString()}`);return new r(n.slice(0,i),{validate:!1})}decapsulateCode(e){let t;for(let n=this.#e.length-1;n>-1;n--)if(this.#e[n].code===e){t=n;break}return new r(this.#e.slice(0,t),{validate:!1})}getPeerId(){try{let e=[];this.#e.forEach(({code:n,value:i})=>{n===421&&e.push([n,i]),n===290&&(e=[])});let t=e.pop();if(t?.[1]!=null){let n=t[1];return n[0]==="Q"||n[0]==="1"?z(Ye.decode(`z${n}`),"base58btc"):z(G.parse(n).multihash.bytes,"base58btc")}return null}catch{return null}}getPath(){for(let e of this.#e)if(On.getProtocol(e.code).path)return e.value??null;return null}equals(e){return he(this.bytes,e.bytes)}async resolve(e){let t=this.protos().find(o=>o.resolvable);if(t==null)return[this];let n=dk.get(t.name);if(n==null)throw new _9(`no available resolver for ${t.name}`);return(await n(this,e)).map(o=>oe(o))}nodeAddress(){let e=this.toOptions();if(e.transport!=="tcp"&&e.transport!=="udp")throw new Error(`multiaddr must have a valid format - no protocol with name: "${e.transport}". Must have a valid transport protocol: "{tcp, udp}"`);return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return!(this.#e.length!==2||this.#e[0].code!==4&&this.#e[0].code!==41||this.#e[1].code!==6&&this.#e[1].code!==273)}[jj](){return`Multiaddr(${this.toString()})`}};function Xj(r){r.getComponents().forEach(e=>{let t=On.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function hk(r,e,t){let n=0;for(let i of r)if(!(n<e)){if(n>t)break;if(i!==255)return!1;n++}return!0}function pk(r,e,t,n){let i=0;for(let o of r)if(!(i<t)){if(i>n)break;if(o!==e[i])return!1;i++}return!0}function T9(r){switch(r.length){case $l:return r.join(".");case Hl:{let e=[];for(let t=0;t<r.length;t++)t%2===0&&e.push(r[t].toString(16).padStart(2,"0")+r[t+1].toString(16).padStart(2,"0"));return e.join(":")}default:throw new Error("Invalid ip length")}}function mk(r){let e=0;for(let[t,n]of r.entries()){if(n===255){e+=8;continue}for(;(n&128)!=0;)e++,n=n<<1;if((n&128)!=0)return-1;for(let i=t+1;i<r.length;i++)if(r[i]!=0)return-1;break}return e}function gk(r){let e="0x";for(let t of r)e+=(t>>4).toString(16)+(t&15).toString(16);return e}var $l=4,Hl=16,j0e=parseInt("0xFFFF",16),Yj=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function pm(r,e){e.length===Hl&&r.length===$l&&hk(e,0,11)&&(e=e.slice(12)),e.length===$l&&r.length===Hl&&pk(r,Yj,0,11)&&(r=r.slice(12));let t=r.length;if(t!=e.length)throw new Error("Failed to mask ip");let n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=r[i]&e[i];return n}function yk(r,e){if(typeof e=="string"&&(e=pd(e)),e==null)throw new Error("Invalid ip");if(e.length!==r.network.length)return!1;for(let t=0;t<e.length;t++)if((r.network[t]&r.mask[t])!==(e[t]&r.mask[t]))return!1;return!0}function I9(r){let[e,t]=r.split("/");if(!e||!t)throw new Error("Failed to parse given CIDR: "+r);let n=$l,i=by(e);if(i==null&&(n=Hl,i=vy(e),i==null))throw new Error("Failed to parse given CIDR: "+r);let o=parseInt(t,10);if(Number.isNaN(o)||String(o).length!==t.length||o<0||o>n*8)throw new Error("Failed to parse given CIDR: "+r);let s=k9(o,8*n);return{network:pm(i,s),mask:s}}function k9(r,e){if(e!==8*$l&&e!==8*Hl)throw new Error("Invalid CIDR mask");if(r<0||r>e)throw new Error("Invalid CIDR mask");let t=e/8,n=new Uint8Array(t);for(let i=0;i<t;i++){if(r>=8){n[i]=255,r-=8;continue}n[i]=255-(255>>r),r=0}return n}var Vl=class{constructor(e,t){if(t==null)({network:this.network,mask:this.mask}=I9(e));else{let n=pd(e);if(n==null)throw new Error("Failed to parse network");t=String(t);let i=parseInt(t,10);if(Number.isNaN(i)||String(i).length!==t.length||i<0||i>n.length*8){let o=pd(t);if(o==null)throw new Error("Failed to parse mask");this.mask=o}else this.mask=k9(i,8*n.length);this.network=pm(n,this.mask)}}contains(e){return yk({network:this.network,mask:this.mask},e)}toString(){let e=mk(this.mask),t=e!==-1?String(e):gk(this.mask);return T9(this.network)+"/"+t}};function wk(r,e){return new Vl(r).contains(e)}function P9(r){let e,t;if(r.getComponents().forEach(n=>{(n.name==="ip4"||n.name==="ip6")&&(t=n.value),n.name==="ipcidr"&&(e=n.value)}),e==null||t==null)throw new Error("Invalid multiaddr");return new Vl(t,e)}var dk=new Map;function rc(r){return!!r?.[C9]}function oe(r){return new Cy(r)}function Hi(r){let e=On.getProtocol(r);return{code:e.code,size:e.size??0,name:e.name,resolvable:!!e.resolvable,path:!!e.path}}var Qj=[6,53,56,54,55];function xk(r){return Ak("sni",r)?.value}function bk(r){let e=Ak("tcp",r)?.value;return e==null?"":`:${e}`}function Ak(r,e){return e.find(t=>t.name===r)}function vk(r){return r.some(({code:e})=>e===448)}function Ao(r,e){let t=Ek[r.name];if(t==null)throw new Error(`Can't interpret protocol ${r.name}`);let n=t(r,e);return r.code===41?`[${n}]`:n}var Ek={ip4:(r,e)=>r.value,ip6:(r,e)=>e.length===0?r.value:`[${r.value}]`,tcp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`tcp://${Ao(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${Ao(t,e)}:${r.value}`},dnsaddr:(r,e)=>r.value,dns4:(r,e)=>r.value,dns6:(r,e)=>r.value,dns:(r,e)=>r.value,ipfs:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ao(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${Ao(t,e)}`},http:(r,e)=>{let t=vk(e),n=xk(e),i=bk(e);if(t&&n!=null)return`https://${n}${i}`;let o=t?"https://":"http://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Ao(s,e);return a=a?.replace("tcp://",""),`${o}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ao(t,e),i=decodeURIComponent(r.value??"");return`${n}${i}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ao(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return Ao(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ao(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=vk(e),n=xk(e),i=bk(e);if(t&&n!=null)return`wss://${n}${i}`;let o=t?"wss://":"ws://",s=e.pop();if(s==null)throw new Error("Unexpected end of multiaddr");let a=Ao(s,e);return a=a?.replace("tcp://",""),`${o}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=Ao(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function wd(r,e){let n=oe(r).getComponents(),i=n.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let o=Ek[i.name];if(o==null)throw new Error(`No interpreter found for ${i.name}`);let s=o(i,n)??"";return e?.assumeHttp!==!1&&Qj.includes(i.code)&&(s=s.replace(/^.*:\/\//,""),i.value==="443"?s=`https://${s}`:s=`http://${s}`),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString(),s.endsWith("/")&&(s=s.substring(0,s.length-1))),s}var _k=mt(Sk(),1),Zj=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"],Jj=Zj.map(r=>new _k.Netmask(r));function R9(r){for(let e of Jj)if(e.contains(r))return!0;return!1}function eW(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function tW(r){let e=r.split(":");if(e.length<2)return!1;let t=e[e.length-1].padStart(4,"0"),n=e[e.length-2].padStart(4,"0"),i=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return R9(i)}function rW(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function nW(r){let e=r.split(":"),t=e[e.length-1];return R9(t)}function iW(r){return/^::$/.test(r)||/^::1$/.test(r)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(r)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(r)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(r)||/^ff([0-9a-fA-F]{2,2}):/i.test(r)}function Sn(r){if(bo(r))return R9(r);if(eW(r))return tW(r);if(rW(r))return nW(r);if(Ay(r))return iW(r)}var yt=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Ie=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),rt=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),cn=(...r)=>({match:e=>{let t;for(let n of r){let i=n.match(e);i!==!1&&(t==null||i.length<t.length)&&(t=i)}return t??!1}}),ot=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function pt(...r){function e(i){if(i==null)return!1;let o=i.getComponents();for(let s of r){let a=s.match(o);if(a===!1)return!1;o=a}return o}function t(i){return e(i)!==!1}function n(i){let o=e(i);return o===!1?!1:o.length===0}return{matchers:r,matches:t,exactMatch:n}}var oW=Ie(421),Ck=pt(oW),Iy=Ie(54),ky=Ie(55),Py=Ie(56),O9=Ie(53),Nge=pt(Iy,rt(Ie(421))),Bge=pt(ky,rt(Ie(421))),Lge=pt(Py,rt(Ie(421))),gm=pt(cn(O9,Py,Iy,ky),rt(Ie(421))),Tk=ot(Ie(4),rt(Ie(43))),Ik=ot(rt(Ie(42)),Ie(41),rt(Ie(43))),N9=cn(Tk,Ik),Kl=cn(N9,O9,Iy,ky,Py),kk=pt(cn(N9,ot(cn(O9,Py,Iy,ky),rt(Ie(421))))),B9=pt(Tk),L9=pt(Ik),Pk=pt(N9),M9=ot(Kl,Ie(6)),ym=ot(Kl,Ie(273)),zl=pt(ot(M9,rt(Ie(421)))),Mge=pt(ym),U9=ot(ym,yt(460),rt(Ie(421))),Ry=ot(ym,yt(461),rt(Ie(421))),sW=cn(U9,Ry),Uge=pt(U9),Rk=pt(Ry),D9=cn(Kl,M9,ym,U9,Ry),Dk=cn(ot(D9,yt(477),rt(Ie(421)))),na=pt(Dk),Ok=cn(ot(D9,yt(478),rt(Ie(421))),ot(D9,yt(448),rt(Ie(449)),yt(477),rt(Ie(421)))),ql=pt(Ok),Nk=ot(ym,yt(280),rt(Ie(466)),rt(Ie(466)),rt(Ie(421))),wm=pt(Nk),Bk=ot(Ry,yt(465),rt(Ie(466)),rt(Ie(466)),rt(Ie(421))),F9=pt(Bk),Ty=cn(Dk,Ok,ot(M9,rt(Ie(421))),ot(sW,rt(Ie(421))),ot(Kl,rt(Ie(421))),Nk,Bk,Ie(421)),Dy=pt(Ty),aW=ot(Ty,yt(290),Ie(421)),Nn=pt(aW),cW=cn(ot(Ty,yt(290),yt(281),rt(Ie(421))),ot(Ty,yt(281),rt(Ie(421))),ot(yt(281),rt(Ie(421)))),xm=pt(cW),lW=cn(ot(Kl,Ie(6),yt(480),rt(Ie(421))),ot(Kl,yt(480),rt(Ie(421)))),Lk=pt(lW),uW=ot(Kl,cn(ot(Ie(6,"443"),yt(480)),ot(Ie(6),yt(443)),ot(Ie(6),yt(448),yt(480)),ot(yt(448),yt(480)),yt(448),yt(443)),rt(Ie(421))),Mk=pt(uW),fW=cn(ot(Ie(777),rt(Ie(421)))),Fge=pt(fW),dW=cn(ot(Ie(400),rt(Ie(421)))),$ge=pt(dW);function $9(r,e,t){return r.filter(n=>{if(Mk.matches(n)||e&&Lk.matches(n))return t||gm.matches(n)?!0:Sn(n.toOptions().host)===!1;if(!e&&t){let{host:i}=n.toOptions();if(i==="127.0.0.1"||i==="localhost"||i.endsWith(".localhost"))return!0}return!1})}async function*Oy(r,e,t,n,i,o={}){for await(let s of e.findProviders(r,o)){let a=$9(s.multiaddrs,n,i);if(a.length===0)continue;let c=wd(a[0]);yield new xd(c,{logger:t,transformRequestInit:o.transformRequestInit})}}async function Uk(r,e,t){let{signal:n,log:i}=t??{},o=r.headers.get("content-length");if(o!=null){let c=parseInt(o,10);if(c>e)throw i?.error("content-length header (%d) is greater than the limit (%d)",c,e),r.body!=null&&await r.body.cancel().catch(l=>{i?.error("error cancelling response body after content-length check - %e",l)}),new Error(`Content-Length header (${c}) is greater than the limit (${e}).`)}let s=r.body?.getReader();if(s==null)throw new Error("Response body is not readable");let a=new pe;try{for(;;){if(n?.aborted===!0)throw new Error("Response body read was aborted.");let{done:c,value:l}=await s.read();if(c)break;if(a.append(l),a.byteLength>e)throw new Error(`Response body is greater than the limit (${e}), received ${a.byteLength} bytes.`)}}finally{s.cancel().catch(c=>{i?.error("error cancelling reader - %e",c)}).finally(()=>{s.releaseLock()})}return a.subarray()}var xd=class{url;#e=0;#t=0;#r=0;#s=0;#c=new Map;log;transformRequestInit;constructor(e,{logger:t,transformRequestInit:n}){this.url=e instanceof URL?e:new URL(e),this.transformRequestInit=n,this.log=t.forComponent(`helia:trustless-gateway-block-broker:${this.url.hostname}`)}#l(e){let t=e.multihash.bytes;return cr.encode(t)}async getRawBlock(e,{signal:t,maxSize:n=Fk}={}){let i=new URL(this.url.toString());if(i.pathname=`/ipfs/${e.toString()}`,i.search="?format=raw",t?.aborted===!0)throw new Error(`Signal to fetch raw block for CID ${e} from gateway ${this.url} was aborted prior to fetch`);let o=this.#l(e),s=new AbortController,a=()=>{s.abort()};t?.addEventListener("abort",a);try{let c=this.#c.get(o);if(c==null){this.#e++;let l={signal:s.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},u=this.transformRequestInit!=null?await this.transformRequestInit(l):l;c=fetch(i.toString(),u).then(async f=>{if(this.log("GET %s %d",i,f.status),!f.ok)throw this.#t++,new Error(`unable to fetch raw block for CID ${e} from gateway ${this.url}`);let d=await Uk(f,n,{signal:s.signal,log:this.log});return this.#s++,d}),this.#c.set(o,c)}return await c}catch{throw t?.aborted===!0?new Error(`fetching raw block for CID ${e} from gateway ${this.url} was aborted`):(this.#t++,new Error(`unable to fetch raw block for CID ${e}`))}finally{t?.removeEventListener("abort",a),this.#c.delete(o)}}reliability(){return this.#e===0?1:this.#r>0?-1/0:this.#s/(this.#e+this.#t*3)}incrementInvalidBlocks(){this.#r++}getStats(){return{attempts:this.#e,errors:this.#t,invalidBlocks:this.#r,successes:this.#s,pendingResponses:this.#c.size}}};var H9=class extends Ml{routing;allowInsecure;allowLocal;transformRequestInit;constructor(e,t){super(e,{...t,name:"helia:trustless-gateway:session"}),this.routing=e.routing,this.allowInsecure=t.allowInsecure??Ny,this.allowLocal=t.allowLocal??By,this.transformRequestInit=t.transformRequestInit}async queryProvider(e,t,n){this.log("fetching BLOCK for %c from %s",e,t.url);let i=await t.getRawBlock(e,n);return this.log.trace("got block for %c from %s",e,t.url),await n.validateFn?.(i),i}async*findNewProviders(e,t={}){yield*Oy(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}async convertToProvider(e,t){if(Ti(e))return;let n=$9(Array.isArray(e)?e:[e],this.allowInsecure,this.allowLocal);if(n.length===0)return;let i=wd(n[0]);return new xd(i,{logger:this.logger,transformRequestInit:this.transformRequestInit})}};function $k(r,e){return new H9(r,e)}var Ly=class{allowInsecure;allowLocal;transformRequestInit;routing;log;logger;constructor(e,t={}){this.log=e.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=e.logger,this.routing=e.routing,this.allowInsecure=t.allowInsecure??Ny,this.allowLocal=t.allowLocal??By,this.transformRequestInit=t.transformRequestInit}async retrieve(e,t={}){let n=[];for await(let i of Oy(e,this.routing,this.logger,this.allowInsecure,this.allowLocal,{...t,transformRequestInit:this.transformRequestInit})){this.log("getting block for %c from %s",e,i.url);try{let o=await i.getRawBlock(e,t);this.log.trace("got block for %c from %s",e,i.url);try{await t.validateFn?.(o)}catch(s){this.log.error("failed to validate block for %c from %s",e,i.url,s);continue}return o}catch(o){if(this.log.error("failed to get block for %c from %s",e,i.url,o),o instanceof Error?n.push(o):n.push(new Error(`Unable to fetch raw block for CID ${e} from gateway ${i.url}`)),t.signal?.aborted===!0){this.log.trace("request aborted while fetching raw block for CID %c from gateway %s",e,i.url);break}}}throw n.length>0?new AggregateError(n,`Unable to fetch raw block for CID ${e} from any gateway`):new Error(`Unable to fetch raw block for CID ${e} from any gateway`)}createSession(e={}){return $k({logger:this.logger,routing:this.routing},{...e,allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit})}};var Ny=!1,By=!1,Fk=2097152;function bm(r={}){return e=>new Ly(e,r)}async function*My(r,e={}){let t=r.getReader();try{for(;;){let n=await t.read();if(n.done)return;yield n.value}}finally{e.preventCancel!==!0&&await t.cancel(),t.releaseLock()}}var jk=mt(Uy(),1);var Fy=class extends Error{static name="SignatureCreationError";constructor(e="Record signature creation failed"){super(e),this.name="SignatureCreationError"}},Eo=class extends Error{static name="SignatureVerificationError";constructor(e="Record signature verification failed"){super(e),this.name="SignatureVerificationError"}},$y=class extends Error{static name="RecordExpiredError";constructor(e="Record has expired"){super(e),this.name="RecordExpiredError"}},jl=class extends Error{static name="UnsupportedValidityError";constructor(e="The validity type is unsupported"){super(e),this.name="UnsupportedValidityError"}},Hy=class extends Error{static name="RecordTooLargeError";constructor(e="The record is too large"){super(e),this.name="RecordTooLargeError"}},vm=class extends Error{static name="InvalidValueError";constructor(e="Value must be a valid content path starting with /"){super(e),this.name="InvalidValueError"}},Vy=class extends Error{static name="InvalidRecordDataError";constructor(e="Invalid record data"){super(e),this.name="InvalidRecordDataError"}},Am=class extends Error{static name="InvalidEmbeddedPublicKeyError";constructor(e="Invalid embedded public key"){super(e),this.name="InvalidEmbeddedPublicKeyError"}};var Fr;(function(r){let e;(function(i){i.EOL="EOL"})(e=r.ValidityType||(r.ValidityType={}));let t;(function(i){i[i.EOL=0]="EOL"})(t||(t={})),(function(i){i.codec=()=>St(t)})(e=r.ValidityType||(r.ValidityType={}));let n;r.codec=()=>(n==null&&(n=be((i,o,s={})=>{s.lengthDelimited!==!1&&o.fork(),i.value!=null&&(o.uint32(10),o.bytes(i.value)),i.signatureV1!=null&&(o.uint32(18),o.bytes(i.signatureV1)),i.validityType!=null&&(o.uint32(24),r.ValidityType.codec().encode(i.validityType,o)),i.validity!=null&&(o.uint32(34),o.bytes(i.validity)),i.sequence!=null&&(o.uint32(40),o.uint64(i.sequence)),i.ttl!=null&&(o.uint32(48),o.uint64(i.ttl)),i.pubKey!=null&&(o.uint32(58),o.bytes(i.pubKey)),i.signatureV2!=null&&(o.uint32(66),o.bytes(i.signatureV2)),i.data!=null&&(o.uint32(74),o.bytes(i.data)),s.lengthDelimited!==!1&&o.ldelim()},(i,o,s={})=>{let a={},c=o==null?i.len:i.pos+o;for(;i.pos<c;){let l=i.uint32();switch(l>>>3){case 1:{a.value=i.bytes();break}case 2:{a.signatureV1=i.bytes();break}case 3:{a.validityType=r.ValidityType.codec().decode(i);break}case 4:{a.validity=i.bytes();break}case 5:{a.sequence=i.uint64();break}case 6:{a.ttl=i.uint64();break}case 7:{a.pubKey=i.bytes();break}case 8:{a.signatureV2=i.bytes();break}case 9:{a.data=i.bytes();break}default:{i.skipType(l&7);break}}}return a})),n),r.encode=i=>xe(i,r.codec()),r.decode=(i,o)=>we(i,r.codec(),o)})(Fr||(Fr={}));var hW=Ue("ipns:utils"),Hk=D("/ipns/"),pW=114,mW=0,gW=18;function Em(r){let e;if(r.pubKey!=null)try{e=rr(r.pubKey)}catch(t){throw hW.error(t),t}if(e!=null)return e}function Vk(r,e,t){let n=D(e);return Xe([r,t,n])}function zy(r){let e=D("ipns-signature:");return Xe([e,r])}function nc(r){return"signatureV1"in r?Fr.encode({value:D(r.value),signatureV1:r.signatureV1,validityType:r.validityType,validity:D(r.validity),sequence:r.sequence,ttl:r.ttl,pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data}):Fr.encode({pubKey:r.pubKey,signatureV2:r.signatureV2,data:r.data})}function Bn(r){let e=Fr.decode(r);if(e.sequence!=null&&(e.sequence=BigInt(e.sequence)),e.ttl!=null&&(e.ttl=BigInt(e.ttl)),e.signatureV2==null||e.data==null)throw new Eo("Missing data or signatureV2");let t=zk(e.data),n=yW(t.Value),i=z(t.Validity);if(e.value!=null&&e.signatureV1!=null)return wW(e),{value:n,validityType:Fr.ValidityType.EOL,validity:i,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV1:e.signatureV1,signatureV2:e.signatureV2,data:e.data};if(e.signatureV2!=null)return{value:n,validityType:Fr.ValidityType.EOL,validity:i,sequence:t.Sequence,ttl:t.TTL,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function ia(r){return Xe([Hk,r.bytes])}function bd(r){let e=We(r.slice(Hk.length));if(!Ky(e,mW)&&!Ky(e,gW))throw new Ua("Multihash in IPNS key was not identity or sha2-256");return e}function Kk(r,e,t,n,i){let o;if(e===Fr.ValidityType.EOL)o=0;else throw new jl("The validity type is unsupported");return Xs({Value:r,Validity:t,ValidityType:o,Sequence:n,TTL:i})}function zk(r){let e=En(r);if(e.ValidityType===0)e.ValidityType=Fr.ValidityType.EOL;else throw new jl("The validity type is unsupported");return Number.isInteger(e.Sequence)&&(e.Sequence=BigInt(e.Sequence)),Number.isInteger(e.TTL)&&(e.TTL=BigInt(e.TTL)),e}function yW(r){let e=z(r).trim();if(e.startsWith("/"))return e;try{return`/ipfs/${G.decode(r).toV1().toString()}`}catch{}try{return`/ipfs/${G.parse(e).toV1().toString()}`}catch{}throw new vm("Value must be a valid content path starting with /")}function qk(r){if(r!=null){let e=vW(r);if(e!=null)return e.code===pW?`/ipns/${e.toString(mn)}`:`/ipfs/${e.toV1().toString()}`;if(xW(r))return`/ipns/${mn.encode(r.bytes)}`;let t=r.toString().trim();if(t.startsWith("/")&&t.length>1)return t}throw new vm("Value must be a valid content path starting with /")}function wW(r){if(r.data==null)throw new Vy("Record data is missing");let e=zk(r.data);if(!he(e.Value,r.value??new Uint8Array(0)))throw new Eo('Field "value" did not match between protobuf and CBOR');if(!he(e.Validity,r.validity??new Uint8Array(0)))throw new Eo('Field "validity" did not match between protobuf and CBOR');if(e.ValidityType!==r.validityType)throw new Eo('Field "validityType" did not match between protobuf and CBOR');if(e.Sequence!==r.sequence)throw new Eo('Field "sequence" did not match between protobuf and CBOR');if(e.TTL!==r.ttl)throw new Eo('Field "ttl" did not match between protobuf and CBOR')}function xW(r){return r.bytes instanceof Uint8Array}function bW(r){return typeof r?.toCID=="function"}function vW(r){if(bW(r))return r.toCID();try{return G.parse(r)}catch{}return G.asCID(r)}function Ky(r,e){return r.code===e}var AW=Ue("ipns"),Wk=300*1e9,EW="/ipns/",U2e=EW.length,Gk={v1Compatible:!0,ttlNs:Wk};async function Xk(r,e,t,n,i=Gk){let o=new jk.default(Date.now()+Number(n)),s=Fr.ValidityType.EOL,a=BigInt(i.ttlNs??Wk);return SW(r,e,t,s,o.toString(),a,i)}var SW=async(r,e,t,n,i,o,s=Gk)=>{t=BigInt(t);let a=D(i),c=qk(e),l=D(c),u=Kk(l,n,a,t,o),f=zy(u),d=await r.sign(f),h;if(r.type==="RSA"&&(h=ur(r.publicKey)),s.v1Compatible===!0){let m=await _W(r,l,n,a),g={value:c,signatureV1:m,validity:i,validityType:n,sequence:t,ttl:o,signatureV2:d,data:u};return h!=null&&(g.pubKey=h),g}else{let m={value:c,validity:i,validityType:n,sequence:t,ttl:o,signatureV2:d,data:u};return h!=null&&(m.pubKey=h),m}},_W=async(r,e,t,n)=>{try{let i=Vk(e,t,n);return await r.sign(i)}catch(i){throw AW.error("record signature creation failed",i),new Fy("Record signature creation failed")}};var Yk=mt(Uy(),1);var qy=Ue("ipns:validator"),CW=1024*10;async function TW(r,e){let t=Bn(e),n;try{let i=zy(t.data);n=await r.verify(i,t.signatureV2)}catch{n=!1}if(!n)throw qy.error("record signature verification failed"),new Eo("Record signature verification failed");if(t.validityType===Fr.ValidityType.EOL){if(Yk.default.fromString(t.validity).toDate().getTime()<Date.now())throw qy.error("record has expired"),new $y("record has expired")}else if(t.validityType!=null)throw qy.error("the validity type is unsupported"),new jl("The validity type is unsupported");qy("ipns record for %s is valid",t.value)}async function ic(r,e){if(e.byteLength>CW)throw new Hy("The record is too large");let t=bd(r),n;Ky(t,0)&&(n=l2(t));let i=Bn(e),o=Em(i)??n;if(o==null)throw new Am("Could not extract public key from IPNS record or routing key");let s=ia(o.toMultihash());if(!he(s,r))throw new Am("Embedded public key did not match routing key");await TW(o,e)}var jy=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MESSAGE_LENGTH"};async function*Sm(r,e={}){let t=/\r?\n/,n=new TextDecoder("utf8"),i="";for await(let o of r){if(typeof o=="string"&&(o=new TextEncoder().encode(o)),ki(o)&&(o=o.subarray()),i+=n.decode(o,{stream:!0}),i.length>(e?.maxMessageLength??i.length))throw new jy("Incoming message too long");let s=i.split(t);i=s.pop()??"";for(let a=0;a<s.length;a++)yield JSON.parse(s[a])}i+=n.decode(),i!==""&&(yield JSON.parse(i))}var vd=class extends Error{static name="InvalidRequestError";constructor(e="Invalid request"){super(e),this.name="InvalidRequestError"}},So=class extends Error{static name="BadResponseError";constructor(e="Bad response"){super(e),this.name="BadResponseError"}};function IW(r){return r[Symbol.asyncIterator]!=null}function kW(r){if(IW(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Ad=kW;var Qk=D("/ipns/");function Zk(r){return he(r.subarray(0,Qk.byteLength),Qk)}var Wy=class{client;constructor(e){this.client=e}async*findProviders(e,t={}){yield*zt(this.client.getProviders(e,t),n=>({id:n.ID,multiaddrs:n.Addrs??[]}))}async provide(){}async cancelReprovide(){}async put(e,t,n){if(!Zk(e))return;let i=bd(e),o=G.createV1(114,i),s=Bn(t);await this.client.putIPNS(o,s,n)}async get(e,t){if(!Zk(e))throw new qe("Not found");let n=bd(e),i=G.createV1(114,n);try{let o=await this.client.getIPNS(i,t);return nc(o)}catch(o){throw o.name==="BadResponseError"?new qe("Not found"):o}}},Gy=class{client;constructor(e){this.client=e}async findPeer(e,t={}){let n=await Ad(this.client.getPeers(e,t));if(n!=null)return{id:n.ID,multiaddrs:n.Addrs??[]};throw new qe("Not found")}async*getClosestPeers(e,t={}){}};var $r=Ue("delegated-routing-v1-http-api-client"),Xy={concurrentRequests:4,timeout:3e4,cacheTTL:300*1e3,cacheName:"delegated-routing-v1-cache"},Yy=class{started;httpQueue;shutDownController;clientUrl;timeout;contentRouting;peerRouting;filterAddrs;filterProtocols;inFlightRequests;cacheName;cache;cacheTTL;constructor(e,t={}){this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new mo({concurrency:t.concurrentRequests??Xy.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=e instanceof URL?e:new URL(e),this.timeout=t.timeout??Xy.timeout,this.filterAddrs=t.filterAddrs,this.filterProtocols=t.filterProtocols,this.contentRouting=new Wy(this),this.peerRouting=new Gy(this),this.cacheName=t.cacheName??Xy.cacheName,this.cacheTTL=t.cacheTTL??Xy.cacheTTL}get[qo](){return this.contentRouting}get[jo](){return this.peerRouting}isStarted(){return this.started}async start(){this.started||(this.started=!0,this.cacheTTL>0&&(this.cache=await globalThis.caches?.open(this.cacheName),this.cache!=null&&$r("cache enabled with ttl %d",this.cacheTTL)))}async stop(){this.httpQueue.clear(),this.shutDownController.abort(),await globalThis.caches?.delete(this.cacheName),this.started=!1}async*getProviders(e,t={}){$r("getProviders starts: %c",e);let n=AbortSignal.timeout(this.timeout),i=Pe([this.shutDownController.signal,n,t.signal]);let o=ve(),s=ve();this.httpQueue.add(async()=>(o.resolve(),s.promise));try{await o.promise;let a=new URL(`${this.clientUrl}routing/v1/providers/${e.toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:i},l=await this.#r(a.toString(),c);if(l==null)throw new So("No response received");if(!l.ok)throw l.status===404?new qe("No matching records found"):l.status===422?new vd("Request does not conform to schema or semantic constraints"):new So(`Unexpected status code: ${l.status}`);if(l.body==null)throw new So("Routing response had no body");let u=l.headers.get("Content-Type");if(u==null)throw new So("No Content-Type header received");if(u?.startsWith("application/json")){let f=await l.json();for(let d of f.Providers){let h=this.#e(d);h!=null&&(yield h)}}else if(u.includes("application/x-ndjson"))for await(let f of Sm(My(l.body))){let d=this.#e(f);d!=null&&(yield d)}else throw new So(`Unsupported Content-Type: ${u}`)}finally{i.clear(),s.resolve(),$r("getProviders finished: %c",e)}}async*getPeers(e,t={}){$r("getPeers starts: %c",e);let n=AbortSignal.timeout(this.timeout),i=Pe([this.shutDownController.signal,n,t.signal]);let o=ve(),s=ve();this.httpQueue.add(async()=>(o.resolve(),s.promise));try{await o.promise;let a=new URL(`${this.clientUrl}routing/v1/peers/${e.toCID().toString()}`);this.#t(a,t.filterAddrs,t.filterProtocols);let c={headers:{Accept:"application/x-ndjson"},signal:i},l=await this.#r(a.toString(),c);if(l.status===404)throw new qe("No matching records found");if(l.status===422)throw new vd("Request does not conform to schema or semantic constraints");if(l.body==null)throw new So("Routing response had no body");if(l.headers.get("Content-Type")==="application/json"){let f=await l.json();for(let d of f.Peers){let h=this.#e(d);h!=null&&(yield h)}}else for await(let f of Sm(My(l.body))){let d=this.#e(f);d!=null&&(yield d)}}catch(a){$r.error("getPeers errored:",a)}finally{i.clear(),s.resolve(),$r("getPeers finished: %c",e)}}async getIPNS(e,t={}){$r("getIPNS starts: %s",e);let n=AbortSignal.timeout(this.timeout),i=Pe([this.shutDownController.signal,n,t.signal]);let o=ve(),s=ve();this.httpQueue.add(async()=>(o.resolve(),s.promise));let a=`${this.clientUrl}routing/v1/ipns/${e}`;try{await o.promise;let c={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:i},l=await this.#r(a,c);if($r("getIPNS GET %s %d",a,l.status),l.status===404)throw new qe("No matching records found");if(l.status===422)throw new vd("Request does not conform to schema or semantic constraints");if(l.body==null)throw new So("GET ipns response had no body");let u=await l.arrayBuffer(),f=new Uint8Array(u,0,u.byteLength);return t.validate!==!1&&await ic(ia(e.multihash),f),Bn(f)}catch(c){throw $r.error("getIPNS GET %s error:",a,c),c}finally{i.clear(),s.resolve(),$r("getIPNS finished: %s",e)}}async putIPNS(e,t,n={}){$r("putIPNS starts: %c",e);let i=AbortSignal.timeout(this.timeout),o=Pe([this.shutDownController.signal,i,n.signal]);let s=ve(),a=ve();this.httpQueue.add(async()=>(s.resolve(),a.promise));let c=`${this.clientUrl}routing/v1/ipns/${e}`;try{await s.promise;let l=nc(t),u={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:l,signal:o},f=await this.#r(c,u);if($r("putIPNS PUT %s %d",c,f.status),f.status!==200)throw new So("PUT ipns response had status other than 200")}catch(l){throw $r.error("putIPNS PUT %s error:",c,l.stack),l}finally{o.clear(),a.resolve(),$r("putIPNS finished: %c",e)}}#e(e){try{let t=[],n=e.Addrs?.map(oe)??[];return e.Protocols!=null&&t.push(...e.Protocols),e.Protocol!=null&&(t.push(e.Protocol),delete e.Protocol),{...e,Schema:"peer",ID:gt(e.ID),Addrs:n,Protocols:t}}catch(t){$r.error("could not conform record to peer schema",t)}}#t(e,t,n){if(t!=null||this.filterAddrs!=null){let i=t?.join(",")??this.filterAddrs?.join(",")??"";i!==""&&e.searchParams.set("filter-addrs",i)}if(n!=null||this.filterProtocols!=null){let i=n?.join(",")??this.filterProtocols?.join(",")??"";i!==""&&e.searchParams.set("filter-protocols",i)}}async#r(e,t){let n=t.method??"GET",i=`${n}-${e}`;if(n==="GET"){let c=await this.cache?.match(e);if(c!=null){if(parseInt(c.headers.get("x-cache-expires")??"0",10)>Date.now())return $r("returning cached response for %s",i),c;await this.cache?.delete(e)}}let o=this.inFlightRequests.get(i);if(o!=null){let c=await o;return $r("deduplicating outgoing request for %s",i),c.clone()}let s=fetch(e,t).then(async c=>{if(this.cache!=null&&c.ok&&n==="GET"){let l=Date.now()+this.cacheTTL,u=new Headers(c.headers);u.set("x-cache-expires",l.toString());let f=new Response(c.clone().body,{status:c.status,statusText:c.statusText,headers:u});await this.cache.put(e,f)}return c}).finally(()=>{this.inFlightRequests.delete(i)});return this.inFlightRequests.set(i,s),await s}};function Qy(r,e={}){return new Yy(new URL(r),e)}function K9(){return{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}}var Jk="[a-fA-F\\d:]",oc=r=>r&&r.includeBoundaries?`(?:(?<=\\s|^)(?=${Jk})|(?<=${Jk})(?=\\s|$))`:"",_o="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",mr="[a-fA-F\\d]{1,4}",Zy=`
|
|
4
4
|
(?:
|
|
5
5
|
(?:${mr}:){7}(?:${mr}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8
|
|
6
6
|
(?:${mr}:){6}(?:${_o}|:${mr}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
(?:${mr}:){1}(?:(?::${mr}){0,4}:${_o}|(?::${mr}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4
|
|
12
12
|
(?::(?:(?::${mr}){0,5}:${_o}|(?::${mr}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4
|
|
13
13
|
)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1
|
|
14
|
-
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),PW=new RegExp(`(?:^${_o}$)|(?:^${Zy}$)`),RW=new RegExp(`^${_o}$`),DW=new RegExp(`^${Zy}$`),z9=r=>r&&r.exact?PW:new RegExp(`(?:${oc(r)}${_o}${oc(r)})|(?:${oc(r)}${Zy}${oc(r)})`,"g");z9.v4=r=>r&&r.exact?RW:new RegExp(`${oc(r)}${_o}${oc(r)}`,"g");z9.v6=r=>r&&r.exact?DW:new RegExp(`${oc(r)}${Zy}${oc(r)}`,"g");var q9=z9;function j9(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function eP(){return!1}var{toString:OW}=Object.prototype;function W9(r){return OW.call(r)==="[object RegExp]"}var tP={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function G9(r,e={}){if(!W9(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(tP).map(i=>(typeof e[i]=="boolean"?e[i]:r[i])?tP[i]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function X9(r,e,{timeout:t}={}){try{return j9(()=>G9(r).test(e),{timeout:t})()}catch(n){if(eP(n))return!1;throw n}}var NW=15,BW=45,rP={timeout:400};function Y9(r){return r.length>BW?!1:X9(q9.v6({exact:!0}),r,rP)}function nP(r){return r.length>NW?!1:X9(q9.v4({exact:!0}),r,rP)}var iP={http:"80",https:"443",ws:"80",wss:"443"},LW=["http","https","ws","wss"];function oP(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:i,port:o,path:s}=MW(r),a=[UW(i,t),FW(o,n),$W(n)];s!=null&&a.push(HW(s));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return oe(c)}function MW(r){let[e]=r.split(":");LW.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:i,pathname:o,search:s}=new URL(r);if(i==null||i===""){let c=VW(e);c!=null&&(i=c),c==null&&t==="http:"&&(i="80")}let a;return o!=null&&o!==""&&o!=="/"&&(o.startsWith("/")&&(o=o.substring(1)),a=o),s!=null&&s!==""&&(a=a??"",a+=s),{scheme:e,hostname:n,port:i,path:a}}function UW(r,e){if(!(r==null||r==="")){if(nP(r))return["ip4",r];if(Y9(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Y9(t))return["ip6",t]}return[e,r]}}function FW(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function $W(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function HW(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function VW(r){if(!(r==null||r===""||iP[r]==null))return iP[r]}var KW=["https://trustless-gateway.link","https://4everland.io"],zW=2336;function qW(r){return r=r.toString(),{id:vn(G.createV1(zW,lr.digest(D(r)))),multiaddrs:[oP(r)]}}var Q9=class{gateways;shuffle;constructor(e={}){this.gateways=(e.gateways??KW).map(t=>qW(t)),this.shuffle=e.shuffle??!0}async*findProviders(e,t){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function _m(r={}){return new Q9(r)}var Z9=class{libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*this.libp2p.contentRouting.findProviders(e,t)}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return this.libp2p.contentRouting.get(e,t)}async findPeer(e,t){return this.libp2p.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t){yield*this.libp2p.peerRouting.getClosestPeers(e,t)}};function Cm(r){return new Z9(r)}var Tm=class extends Zs{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(jt.encode(e.multihash.bytes),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(jt.encode(e.multihash.bytes));if(n==null)throw new Ui;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(jt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(jt.encode(e.multihash.bytes))}async*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:G.createV1(At,We(jt.decode(t))),block:n},e?.signal?.throwIfAborted()}};var v3e=Ue("blockstore:core:tiered");var sP="SHARDING";function WW(r){return r[Symbol.asyncIterator]!=null}function GW(r){if(WW(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var oa=GW;function XW(r){return r[Symbol.asyncIterator]!=null}function YW(r,e){return XW(r)?(async function*(){yield*(await oa(r)).sort(e)})():(function*(){yield*oa(r).sort(e)})()}var Jy=YW;var sa=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:i}of e)await this.put(n,i,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await Jr(this.putMany(e,n)),e=[],await Jr(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let i=e.prefix;n=di(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>di(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Jy(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=di(n,()=>i++>=o)}return e.limit!=null&&(n=$a(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=di(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>di(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Jy(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=di(n,()=>o++>=i)}return e.limit!=null&&(n=$a(n,e.limit)),n}};var Wl=class extends sa{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Ui;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,i]of this.data.entries())yield{key:new it(n),value:i},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new it(n),t?.signal?.throwIfAborted()}};var e4e=new it(sP);var p4e=Ue("datastore:core:tiered");function Ed(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:lP}=Object.prototype,{propertyIsEnumerable:QW}=Object,Sd=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},ZW=void 0,cP={concatArrays:!1,ignoreUndefined:!1},e3=r=>{let e=[];for(let t in r)lP.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)QW.call(r,n)&&e.push(n)}return e};function _d(r){return Array.isArray(r)?JW(r):Ed(r)?eG(r):r}function JW(r){let e=r.slice(0,0);return e3(r).forEach(t=>{Sd(e,t,_d(r[t]))}),e}function eG(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return e3(r).forEach(t=>{Sd(e,t,_d(r[t]))}),e}var uP=(r,e,t,n)=>(t.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in r&&r[i]!==Object.getPrototypeOf(r)?Sd(r,i,J9(r[i],e[i],n)):Sd(r,i,_d(e[i])))}),r),tG=(r,e,t)=>{let n=r.slice(0,0),i=0;return[r,e].forEach(o=>{let s=[];for(let a=0;a<o.length;a++)lP.call(o,a)&&(s.push(String(a)),o===r?Sd(n,i++,o[a]):Sd(n,i++,_d(o[a])));n=uP(n,o,e3(o).filter(a=>!s.includes(a)),t)}),n};function J9(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?tG(r,e,t):!Ed(e)||!Ed(r)?_d(e):uP(r,e,e3(e),t)}function Gt(...r){let e=J9(_d(cP),this!==ZW&&this||{},cP),t={_:{}};for(let n of r)if(n!==void 0){if(!Ed(n))throw new TypeError("`"+n+"` is not an Option Object");t=J9(t,{_:n},e)}return t._}var eb=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[an.TXT]}),s=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(s!=null&&!l.includes(s)||a.push(oe(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Pl()),this.dns)}},Gl=new eb;var rG={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Gl}},transportManager:{faultTolerance:rl.FATAL_ALL}};async function fP(r){let e=Gt(rG,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new K("Private network is enforced, but no protector was provided");return e}var Im;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={publicKey:ke(0),payloadType:ke(0),payload:ke(0),signature:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Im||(Im={}));var t3=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var pi=class r{static createFromProtobuf=e=>{let t=Im.decode(e),n=rr(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let i=e.domain,o=e.codec,s=e.marshal(),a=dP(i,o,s),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t,n)=>{let i=r.createFromProtobuf(e);if(!await i.validate(t,n))throw new t3("Envelope signature is not valid for the given domain");return i};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:i,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=i,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Im.encode({publicKey:ur(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:he(this.marshal(),e.marshal())}async validate(e,t){let n=dP(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},dP=(r,e,t)=>{let n=D(r),i=Sr(n.byteLength),o=Sr(e.length),s=Sr(t.length);return new pe(i,n,o,e,s,t)};function hP(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var pP="libp2p-peer-record",mP=Uint8Array.from([3,1]);var km;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=be((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={multiaddr:ke(0)},l=s==null?o.len:o.pos+s;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),i),n.encode=o=>xe(o,n.codec()),n.decode=(o,s)=>we(o,n.codec(),s)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=be((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(s,i);o.lengthDelimited!==!1&&i.ldelim()},(n,i,o={})=>{let s={peerId:ke(0),seq:0n,addresses:[]},a=i==null?n.len:n.pos+i;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{s.peerId=n.bytes();break}case 2:{s.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&s.addresses.length===o.limits.addresses)throw new xt('Decode error - map field "addresses" had too many elements');s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return s})),t),r.encode=n=>xe(n,r.codec()),r.decode=(n,i)=>we(n,r.codec(),i)})(km||(km={}));var _n=class r{static createFromProtobuf=e=>{let t=km.decode(e),n=dr(We(t.peerId)),i=(t.addresses??[]).map(s=>oe(s.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:i,seqNumber:o})};static DOMAIN=pP;static CODEC=mP;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=km.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!hP(this.multiaddrs,e.multiaddrs))}};var aa;(function(r){let e;(function(i){let o;i.codec=()=>(o==null&&(o=be((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:"",value:ke(0)},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{l.key=s.string();break}case 2:{l.value=s.bytes();break}default:{s.skipType(f&7);break}}}return l})),o),i.encode=s=>xe(s,i.codec()),i.decode=(s,a)=>we(s,i.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(i){let o;i.codec=()=>(o==null&&(o=be((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),n3.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:""},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{l.key=s.string();break}case 2:{l.value=n3.codec().decode(s,s.uint32(),{limits:c.limits?.value});break}default:{s.skipType(f&7);break}}}return l})),o),i.encode=s=>xe(s,i.codec()),i.decode=(s,a)=>we(s,i.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=be((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.addresses!=null)for(let a of i.addresses)o.uint32(10),r3.codec().encode(a,o);if(i.protocols!=null)for(let a of i.protocols)o.uint32(18),o.string(a);if(i.publicKey!=null&&(o.uint32(34),o.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);i.updated!=null&&(o.uint32(64),o.uint64Number(i.updated)),s.lengthDelimited!==!1&&o.ldelim()},(i,o,s={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?i.len:i.pos+o;for(;i.pos<c;){let l=i.uint32();switch(l>>>3){case 1:{if(s.limits?.addresses!=null&&a.addresses.length===s.limits.addresses)throw new xt('Decode error - map field "addresses" had too many elements');a.addresses.push(r3.codec().decode(i,i.uint32(),{limits:s.limits?.addresses$}));break}case 2:{if(s.limits?.protocols!=null&&a.protocols.length===s.limits.protocols)throw new xt('Decode error - map field "protocols" had too many elements');a.protocols.push(i.string());break}case 4:{a.publicKey=i.bytes();break}case 5:{a.peerRecordEnvelope=i.bytes();break}case 6:{if(s.limits?.metadata!=null&&a.metadata.size===s.limits.metadata)throw new yp('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(i,i.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(s.limits?.tags!=null&&a.tags.size===s.limits.tags)throw new yp('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(i,i.uint32(),{limits:{value:s.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=i.uint64Number();break}default:{i.skipType(l&7);break}}}return a})),n),r.encode=i=>xe(i,r.codec()),r.decode=(i,o)=>we(i,r.codec(),o)})(aa||(aa={}));var r3;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={multiaddr:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}case 3:{o.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(r3||(r3={}));var n3;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(n3||(n3={}));function nG(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=rr(e.publicKey,t);return es(n)}function gP(r,e,t){let n=aa.decode(e);return Cd(r,n,t)}function Cd(r,e,t){let n=new Map,i=BigInt(Date.now());for(let[o,s]of e.tags.entries())s.expiry!=null&&s.expiry<i||n.set(o,s);return{...e,id:nG(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:s})=>({multiaddr:oe(o),isCertified:s??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function yP(r,e){return iG(r.addresses,e.addresses)&&oG(r.protocols,e.protocols)&&sG(r.publicKey,e.publicKey)&&aG(r.peerRecordEnvelope,e.peerRecordEnvelope)&&cG(r.metadata,e.metadata)&&lG(r.tags,e.tags)}function iG(r,e){return xP(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!he(t.multiaddr,n.multiaddr)))}function oG(r,e){return xP(r,e,(t,n)=>t===n)}function sG(r,e){return wP(r,e)}function aG(r,e){return wP(r,e)}function cG(r,e){return bP(r,e,(t,n)=>he(t,n))}function lG(r,e){return bP(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function wP(r,e){return r==null&&e==null?!0:r!=null&&e!=null?he(r,e):!1}function xP(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function bP(r,e,t){if(r.size!==e.size)return!1;for(let[n,i]of r.entries()){let o=e.get(n);if(o==null||!t(i,o))return!1}return!0}var tb="/peers/";function Pm(r){if(!Ti(r)||r.type==null)throw new K("Invalid PeerId");let e=r.toCID().toString();return new it(`${tb}${e}`)}async function vP(r,e,t,n,i){let o=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=oe(s.multiaddr)),!rc(s.multiaddr))throw new K("Multiaddr was invalid");if(!await e(r,s.multiaddr,i))continue;let a=s.isCertified??!1,c=s.multiaddr.toString(),l=o.get(c);l!=null?s.isCertified=l.isCertified||a:o.set(c,{multiaddr:s.multiaddr,isCertified:a})}return[...o.values()].sort((s,a)=>s.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:s,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate(oe(`/p2p/${r}`))),{isCertified:s,multiaddr:a.bytes}})}async function o3(r,e,t,n){if(e==null)throw new K("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new K("publicKey bytes do not match peer id publicKey bytes");let i=n.existingPeer?.peer;if(i!=null&&!r.equals(i.id))throw new K("peer id did not match existing peer id");let o=i?.addresses??[],s=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,l=i?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=i3(d,{validate:AP})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=i3(d,{validate:EP,map:SP})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,m]of d)m==null?a.delete(h):a.set(h,m);a=i3([...a.entries()],{validate:AP})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[m,g]of d)g==null?h.delete(m):h.set(m,g);c=i3([...h.entries()],{validate:EP,map:SP})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;i?.id.publicKey!=null?u=ur(i.id.publicKey):e.publicKey!=null?u=ur(e.publicKey):r.publicKey!=null&&(u=ur(r.publicKey));let f={addresses:await vP(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...s.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>he(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function i3(r,e){let t=new Map;for(let[n,i]of r)i!=null&&e.validate(n,i);for(let[n,i]of r.sort(([o],[s])=>o.localeCompare(s)))i!=null&&t.set(n,e.map?.(n,i)??i);return t}function AP(r,e){if(typeof r!="string")throw new K("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new K("Metadata value must be a Uint8Array")}function EP(r,e){if(typeof r!="string")throw new K("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new K("Tag value must be an integer");if(e.value<0||e.value>100)throw new K("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new K("Tag ttl must be an integer");if(e.ttl<0)throw new K("Tag ttl must be between greater than 0")}}function SP(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function _P(r){let e=r.toString().split("/")[2],t=G.parse(e,jt);return vn(t)}function rb(r,e,t){let n=_P(r);return gP(n,e,t)}function uG(r,e){return{prefix:tb,filters:(r.filters??[]).map(t=>({key:n,value:i})=>t(rb(n,i,e))),orders:(r.orders??[]).map(t=>(n,i)=>t(rb(n.key,n.value,e),rb(i.key,i.value,e)))}}var s3=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=zs({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:am({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let i=await n.lock.readLock(t);return()=>{i(),this.maybeRemoveLock(e,n)}}catch(i){throw this.maybeRemoveLock(e,n),i}}async getWriteLock(e,t){let n=this.getLock(e);try{let i=await n.lock.writeLock(t);return()=>{i(),this.maybeRemoveLock(e,n)}}catch(i){throw this.maybeRemoveLock(e,n),i}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Pm(e),t)}async load(e,t){let n=Pm(e),i=await this.datastore.get(n,t),o=aa.decode(i);if(this.#r(e,o))throw await this.datastore.delete(n,t),new qe;return Cd(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let i=await this.#e(e,n),o=await o3(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,i)}async patch(e,t,n){let i=await this.#e(e,n),o=await o3(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,i)}async merge(e,t,n){let i=await this.#e(e,n),o=await o3(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,i)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(uG(e??{},this.maxAddressAge),e)){let i=_P(t);if(i.equals(this.peerId))continue;let o=aa.decode(n);if(this.#r(i,o)){await this.datastore.delete(t,e);continue}yield Cd(i,o,this.peerId.equals(i)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Pm(e),i=await this.datastore.get(n,t),o=aa.decode(i);if(this.#r(e,o))throw await this.datastore.delete(n,t),new qe;return{peerPB:o,peer:Cd(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,i){t.updated=Date.now();let o=aa.encode(t);return await this.datastore.put(Pm(e),o,i),{peer:Cd(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!yP(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,i=Date.now()-this.maxAddressAge,o=t.addresses.filter(s=>s.observed!=null&&s.observed>i);return n&&o.length===0}};var nb=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new s3(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return oa(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:i})=>i)}}async save(e,t,n){let i=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{i?.()}}async patch(e,t,n){let i=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{i?.()}}async merge(e,t,n){let i=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{i?.()}}async consumePeerRecord(e,t,n){let i=Ti(t)?t:Ti(t?.expectedPeer)?t.expectedPeer:void 0,o=Ti(t)||t===void 0?n:t,s=await pi.openAndCertify(e,_n.DOMAIN,o),a=vn(s.publicKey.toCID());if(i?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",i,a),!1;let c=_n.createFromProtobuf(s.payload),l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=pi.createFromProtobuf(l.peerRecordEnvelope),f=_n.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function CP(r,e={}){return new nb(r,e)}var TP=864e13;var fG=448,ib=449,dG=53,hG=54,pG=55,mG=56,a3=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=hr({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let i=Sn(n)===!0;this.mappings.set(n,{domain:e,verified:i,expires:i?TP-Date.now():0,lastVerified:i?TP-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[i,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",i,o.domain),this.mappings.delete(i),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr.stringTuples(),s=o[0][1];if(s!=null)for(let[a,c]of this.mappings.entries()){if(s!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:oe(`/${o.map(u=>[Hi(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===fG&&e[n+1]?.[0]!==ib)return e.splice(n+1,0,[ib,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),i=!1;for(let[o,s]of this.mappings.entries())s.domain===n&&(this.log("marking %s to %s DNS mapping as verified",o,s.domain),i=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return i}unconfirm(e,t){let n=this.findHost(e),i=!1;for(let[o,s]of this.mappings.entries())s.domain===n&&(this.log("removing verification of %s to %s DNS mapping",o,s.domain),i=i||s.verified,s.verified=!1,s.expires=Date.now()+t);return i}findHost(e){for(let t of e.stringTuples())if(t[0]===ib||t[0]===dG||t[0]===hG||t[0]===pG||t[0]===mG)return t[1]}};var ob=4,sb=41,ab=6,gG=273,c3=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=hr({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let i of n)if(i.externalIp===t[0][1])return!0;return!1}add(e,t,n,i=t,o="tcp"){let s=`${e}-${t}-${o}`,a=this.mappings.get(s)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:i,externalFamily:bo(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(s,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",i=t[1][0]===ab?"tcp":"udp",o=parseInt(t[1][1]??"0"),s=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===o&&u.protocol===i&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,o,i),s=s||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return s}getAll(e){let t=[];for(let{multiaddr:n}of e){let i=n.stringTuples(),o;if((i[0][0]===ob||i[0][0]===sb)&&i[1][0]===ab?o=`${i[0][1]}-${i[1][1]}-tcp`:(i[0][0]===ob||i[0][0]===sb)&&i[1][0]===gG&&(o=`${i[0][1]}-${i[1][1]}-udp`),o==null)continue;let s=this.mappings.get(o);if(s!=null)for(let a of s)i[0][0]=a.externalFamily===4?ob:sb,i[0][1]=a.externalIp,i[1][1]=`${a.externalPort}`,t.push({multiaddr:oe(`/${i.map(c=>[Hi(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let i=e.stringTuples()[0][1],o=!1;for(let s of this.mappings.values())for(let a of s)a.externalIp===i&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=e.stringTuples(),i=n[0][1]??"",o=n[1][0]===ab?"tcp":"udp",s=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===i&&u.externalPort===s&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,i,s,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function IP(r){try{for(let{code:e,value:t}of r.getComponents())if(e!==42&&t!=null){if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}}catch{}return!1}function l3(r){try{for(let{code:e}of r.getComponents())if(e!==42)return e===4||e===41}catch{}return!1}function Vi(r){try{if(!l3(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:Sn(e)??!1}catch{}return!0}var yG={maxObservedAddresses:10},u3=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=hr({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??yG.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Vi(e)||IP(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:oe(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),i=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,i),o}};var wG=[4,41,53,54,55,56];function cb(r){try{for(let{code:e}of r.getComponents())if(e!==42)return wG.includes(e)}catch{}return!1}var xG={maxObservedAddresses:10},f3=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=hr({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??xG.maxObservedAddresses}get(e,t){if(Vi(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),i=this.addresses.get(n);return i==null&&(i={verified:!cb(e),expires:0},this.addresses.set(n,i)),{multiaddr:e,verified:i.verified,type:"transport",expires:i.expires,lastVerified:i.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),i=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.addresses.set(n,i),o}unconfirm(e,t){let n=this.toKey(e),i=this.addresses.get(n)??{verified:!1,expires:0},o=i.verified;return i.verified=!1,i.expires=Date.now()+t,this.addresses.set(n,i),o}toKey(e){if(cb(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var kP=6e4,PP={maxObservedAddresses:10,addressVerificationTTL:kP*10,addressVerificationRetry:kP*5},bG=r=>r;function lb(r,e){let t=r.getPeerId();return t!=null&>(t).equals(e)&&(r=r.decapsulate(oe(`/p2p/${e.toString()}`))),r}var d3=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:i=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.appendAnnounce=new Set(o.map(s=>s.toString())),this.observed=new u3(e,t),this.dnsMappings=new a3(e,t),this.ipMappings=new c3(e,t),this.transportAddresses=new f3(e,t),this.announceFilter=t.announceFilter??bG,this.observedAddressFilter=on(1024),this.addressVerificationTTL=t.addressVerificationTTL??PP.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??PP.addressVerificationRetry,this._updatePeerStoreAddresses=Is(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>oe(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>oe(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>oe(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=lb(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=lb(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=lb(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let i=n.multiaddr.toString();return e.has(i)?!1:(e.add(i),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let i=oe(n);return i.getComponents().pop()?.value===this.components.peerId.toString()?i:i.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(i=>{i.updateAnnounceAddrs(e)}),e.map(i=>({multiaddr:i,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(i=>this.transportAddresses.get(i,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(i=>{i.updateAnnounceAddrs(n)}),t=t.concat(n.map(i=>({multiaddr:i,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(oe(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,i=t,o="tcp"){this.ipMappings.add(e,t,n,i,o),this.observed.removePrefixed(`/ip${bo(n)?4:6}/${n}/${o}/${i}`)}removePublicAddressMapping(e,t,n,i=t,o="tcp"){this.ipMappings.remove(oe(`/ip${bo(n)?4:6}/${n}/${o}/${i}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||Sn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),i=[o=>na.exactMatch(o)||ql.exactMatch(o),o=>zl.exactMatch(o),o=>Rk.exactMatch(o)];for(let o of i){if(!o(e))continue;let s=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(u)).length>0);if(s.length!==1)continue;let a=s[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};var RP;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(RP||(RP={}));var h3=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},p3=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Td=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Rm=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},m3=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},g3=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},y3=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Dm=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},w3=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},x3=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},b3=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},v3=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},A3=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Xl=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Yl=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},E3=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},S3=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var ub=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Za())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>bg(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},AG=["metrics","connectionProtector","dns"],EG=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function DP(r={}){let e=new ub(r);return new Proxy(e,{get(n,i,o){if(typeof i=="string"&&!EG.includes(i)){let s=e.components[i];if(s==null&&!AG.includes(i))throw new h3(`${i} not set`);return s}return Reflect.get(n,i,o)},set(n,i,o){return typeof i=="string"?e.components[i]=o:Reflect.set(n,i,o),!0}})}function OP(r){let e={};for(let t of Object.values(r.components))for(let n of SG(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of _G(t))if(e[n]!==!0)throw new p3(`Service "${CG(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function SG(r){return Array.isArray(r?.[et])?r[et]:[]}function _G(r){return Array.isArray(r?.[ei])?r[ei]:[]}function CG(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var TG=4,IG=41;function NP(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(na.matches(e))return!1;let t=e.stringTuples();return t[0][0]===TG||t[0][0]===IG?!!Sn(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var BP=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},kG=new WeakMap;function PG({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:i}={})=>{if(i?.aborted)return Promise.reject(BP());let o,s,a,c=r??clearTimeout,l=()=>{c(o),a(BP())},u=()=>{i&&i.removeEventListener("abort",l)},f=new Promise((d,h)=>{s=()=>{u(),d(n)},a=h,o=(e??setTimeout)(s,t)});return i&&i.addEventListener("abort",l,{once:!0}),kG.set(f,()=>{c(o),o=null,s()}),f}}var RG=PG(),_3=RG;var Id=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new fb}async consume(e,t=1,n={}){let i=this.getKey(e),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,t,o);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(i,s.consumedPoints,this.blockDuration)),new Ag("Rate limit exceeded",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let a=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=s.consumedPoints*this.execEvenlyMinDelayMs),await _3(a)}return s}penalty(e,t=1,n={}){let i=this.getKey(e),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,t,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){let i=this.getKey(e),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,-t,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){let n=t*1e3,i=this.points+1;return this.memoryStorage.set(this.getKey(e),i,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:i,isFirstInDuration:!1}}set(e,t,n=0){let i=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:i===0?-1:i,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},fb=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let i=this.storage.get(e);if(i!=null){let o=i.expiresAt!=null?i.expiresAt.getTime()-new Date().getTime():-1;return i.expiresAt==null||o>0?(i.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:i.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let i=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let s={value:t,expiresAt:i>0?new Date(Date.now()+i):void 0};return this.storage.set(e,s),i>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},i),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:i===0?-1:i,consumedPoints:s.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function C3(r){if(Ti(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getPeerId();t=n==null?void 0:gt(n),e.forEach(i=>{if(!rc(i))throw new Ma("Invalid multiaddr");let o=i.getPeerId();if(o==null){if(t!=null)throw new K("Multiaddrs must all have the same peer id or have no peer id")}else{let s=gt(o);if(t?.equals(s)!==!0)throw new K("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Ck.exactMatch(n)),{peerId:t,multiaddrs:e}}var DG=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function LP(r,e){let t=r?.streams?.map(i=>i.protocol)??[],n=e?.closableProtocols??DG;if(!(t.filter(i=>i!=null&&!n.includes(i)).length>0))try{await r?.close(e)}catch(i){r?.abort(i)}}function Om(r){try{let e;typeof r=="string"?e=oe(r):e=r;let t=new Set([...e.getComponents().map(n=>n.name)]);if(!t.has("ipcidr")){let i=t.has("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(i)}return P9(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var T3=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Om(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let i=new nn;for(let c of e){let l=c.remotePeer;if(!i.has(l)){i.set(l,0);try{let u=await this.peerStore.get(l);i.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,i),s=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===s)break;await Promise.all(a.map(async c=>{await LP(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,i)=>{let o=n.timeline.open,s=i.timeline.open;return o<s?1:o>s?-1:0}).sort((n,i)=>n.direction==="outbound"&&i.direction==="inbound"?1:n.direction==="inbound"&&i.direction==="outbound"?-1:0).sort((n,i)=>n.streams.length>i.streams.length?1:n.streams.length<i.streams.length?-1:0).sort((n,i)=>{let o=t.get(n.remotePeer)??0,s=t.get(i.remotePeer)??0;return o>s?1:o<s?-1:0})}};var MP="last-dial-failure",UP="last-dial-success";var FP=100,I3=50;var k3=class extends Dr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function $P(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function db(r){if(!l3(r))return!1;let{address:e}=r.nodeAddress();return $P(e)}function OG(r,e){let t=zl.exactMatch(r.multiaddr),n=zl.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let i=ql.exactMatch(r.multiaddr),o=ql.exactMatch(e.multiaddr);if(i&&!o)return-1;if(!i&&o)return 1;let s=na.exactMatch(r.multiaddr),a=na.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=xm.exactMatch(r.multiaddr),l=xm.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=wm.exactMatch(r.multiaddr),f=wm.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=F9.exactMatch(r.multiaddr),h=F9.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function NG(r,e){let t=db(r.multiaddr),n=db(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function BG(r,e){let t=Vi(r.multiaddr),n=Vi(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function LG(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function MG(r,e){let t=Nn.exactMatch(r.multiaddr),n=Nn.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function HP(r){return r.sort(OG).sort(LG).sort(MG).sort(BG).sort(NG)}async function hb(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new S3("Max recursive depth reached");let i=!1,o=[];for(let s of Object.values(e))if(s.canResolve(r)){i=!0;let a=await s.resolve(r,t);for(let c of a)o.push(...await hb(c,e,{...t,depth:n+1}))}return i===!1&&o.push(r),o}var Nm={maxParallelDials:I3,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Gl}},P3=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Nm.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Nm.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Nm.dialTimeout,this.connections=t.connections??new nn,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Nm.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new k3({concurrency:t.maxParallelDials??Nm.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Je.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:i}=C3(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0||a.limits!=null?!1:a.remotePeer.equals(n)?!0:i.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new X("dial-queue:already-connected")),o;let s=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of i)if(c.has(l.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let a of i)s.options.multiaddrs.add(a.toString());return t.onProgress?.(new X("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ts("Dial queue is full");return this.log("creating dial target for %p",n,i.map(a=>a.toString())),t.onProgress?.(new X("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new X("dial-queue:start-dial"));let c=Pe([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:t.priority??yb,multiaddrs:new Set(i.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,i=e.multiaddrs,o=new Set,s=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);s||i.size>0;){c++,s=!1;let u=[],f=new Set(e.multiaddrs);i.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(o.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new X("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Ts("Peer had more than maxPeerAddrsToDial");a++;try{let m=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(m.remotePeer,{multiaddrs:[m.remoteAddr],metadata:{[UP]:D(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return m}catch(m){if(this.log.error("dial failed to %a",h.multiaddr,m),o.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[MP]:D(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(t.aborted)throw new Ii(m.message);l.push(m)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let i=[...t].map(f=>({multiaddr:oe(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Ts("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Dm("The dial request is blocked by gater.allowDialPeer");if(i.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);i.push(...f.addresses),this.log("loaded multiaddrs for %p",e,i.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(i.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,i.map(({multiaddr:d})=>d.toString())),i.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let o=(await Promise.all(i.map(async f=>{let d=await hb(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let s=o.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of s){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new b3("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?HP(l):l.sort(this.addressSorter);if(u.length===0)throw new Dm("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(i=>i.toString())),t);return t.runOnLimitedConnection===!1?n.find(i=>!Nn.matches(i.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var GP=mt(jP(),1);var FG=Object.prototype.toString,$G=r=>FG.call(r)==="[object Error]",HG=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function wb(r){return r&&$G(r)&&r.name==="TypeError"&&typeof r.message=="string"?r.message==="Load failed"?r.stack===void 0:HG.has(r.message):!1}var xb=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},WP=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function bb(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let i=GP.default.operation(e),o=()=>{i.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let s=()=>{e.signal?.removeEventListener("abort",o),i.stop()};i.attempt(async a=>{try{let c=await r(a);s(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof xb)throw c.originalError;if(c instanceof TypeError&&!wb(c))throw c;if(WP(c,a,e),await e.shouldRetry(c)||(i.stop(),n(c)),await e.onFailedAttempt(c),!i.retry(c))throw i.mainError()}catch(l){WP(l,a,e),s(),n(l)}}})})}var R3=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Or({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(i=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,i)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);XP(t)&&(this.queue.has(e)||this.queue.add(async n=>{await bb(async i=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,i,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let i={};[...t.tags.keys()].forEach(o=>{o.startsWith(Na)&&(i[o]=void 0)}),await this.peerStore.merge(e,{tags:i}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>XP(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function XP(r){for(let e of r.tags.keys())if(e.startsWith(Na))return!0;return!1}var yb=50,vb={maxConnections:FP,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},D3=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??vb.maxConnections,this.maxConnections<1)throw new K("Connection Manager maxConnections must be greater than 0");this.connections=new nn,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Om(n)),this.deny=(t.deny??[]).map(n=>Om(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??vb.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Id({points:t.inboundConnectionThreshold??vb.inboundConnectionThreshold,duration:1}),this.connectionPruner=new T3({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>oe(n))}),this.dialQueue=new P3(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??I3,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Gl},connections:this.connections}),this.reconnectQueue=new R3({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);t[n]=i[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Rr(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Zr(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(i){this.log.error(i)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new K("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,i=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),i&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Jn("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=C3(e);if(this.peerId.equals(n))throw new vf("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p as %a",n,a.remoteAddr),t.onProgress?.(new X("dial-queue:already-connected")),a}let i=await this.dialQueue.dial(e,{...t,priority:t.priority??yb});if(i.status!=="open")throw new bf("Remote closed connection during opening");let o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)if(a.id===i.id&&(s=!0),t.force!==!0&&a.id!==i.id&&a.remoteAddr.equals(i.remoteAddr))return i.abort(new Ma("Duplicate multiaddr connection")),a;return s||o.push(i),i}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(t)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>i.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>i.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>oe(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var kd=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),i=e-this.movingAverage,o=n*i;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+i*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*i}else this.movingAverage=e;this.previousTime=t}};var zG=1.2,qG=2,jG=5e3,WG=6e4,GG=5e3,Co=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??GG;this.success=new kd(t),this.failure=new kd(t),this.next=new kd(t),this.failureMultiplier=e.failureMultiplier??qG,this.timeoutMultiplier=e.timeoutMultiplier??zG,this.minTimeout=e.minTimeout??jG,this.maxTimeout=e.maxTimeout??WG,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),i=Pe([e.signal,n]);return i.start=Date.now(),i.timeout=t,i}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var O3=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Zl(r,e){let t=Dg();r.sink(t).catch(async s=>{await t.end(s)}),r.sink=async s=>{for await(let a of s)await t.push(a);await t.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 i=new pe;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await dt(n.next(),s?.signal);return c===!0?null:l}for(;i.byteLength<s.bytes;){let{value:c,done:l}=await dt(n.next(),s?.signal);if(l===!0)throw new O3("unexpected end of input");i.append(c)}let a=i.sublist(0,s.bytes);return i.consume(s.bytes),a},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await t.push(s,a):await t.push(s.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let s=r.source;r.source=(async function*(){e?.yieldBytes===!1?yield i:yield*i,yield*s})()}return r}}}var XG=1e4,YG="1.0.0",QG="ping",ZG="ipfs",YP=32,JG=!0,N3=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??ZG}/${QG}/${YG}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??XG,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??JG,this.timeout=new Co({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[et]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),i=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=Zl(i);t=Date.now(),await Promise.all([o.write(bn(YP),{signal:n}),o.read({bytes:YP,signal:n})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var B3=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,cid:n.toString()}),getAttributesFromYieldedValue:(n,i)=>({...i,providers:[...Array.isArray(i.providers)?i.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Td("No content routers available");let n=this,i=new ai;for await(let o of pn(...n.routers.filter(s=>s.findProviders instanceof Function).map(s=>s.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!i.has(o.id)&&(i.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Td("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Td("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Jn;await Promise.all(this.routers.filter(i=>i.put instanceof Function).map(async i=>{await i.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Jn;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var L3=globalThis.CustomEvent??Event;async function*Cn(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,o=[],s=ve(),a=ve(),c=!1,l,u=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(o.length===t&&(s=ve(),await s.promise),u)break;let g={done:!1};o.push(g),m().then(w=>{g.done=!0,g.ok=!0,g.value=w,i.dispatchEvent(new L3("task-complete"))},w=>{g.done=!0,g.err=w,i.dispatchEvent(new L3("task-complete"))})}c=!0,i.dispatchEvent(new L3("task-complete"))}catch(m){l=m,i.dispatchEvent(new L3("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(m=>m.done)}function*d(){for(;o.length>0&&o[0].done;){let m=o[0];if(o.shift(),m.ok)yield m.value;else throw u=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;f();)for(let m=0;m<o.length;m++)if(o[m].done){let g=o[m];if(o.splice(m,1),m--,g.ok)yield g.value;else throw u=!0,s.resolve(),g.err;s.resolve()}}for(;;){if(f()||(a=ve(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&o.length===0)break}}var M3=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,key:z(n,"base36")}),getAttributesFromYieldedValue:(n,i)=>({...i,peers:[...Array.isArray(i.peers)?i.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Rm("No peer routers available");if(e.toString()===this.peerId.toString())throw new m3("Should not try to find self");let n=this,i=pn(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let o of i)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new qe}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Rm("No peer routers available");let n=this,i=on(1024);for await(let o of Cn((async function*(){let s=pn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of s)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!i.has(o.id.toMultihash().bytes)&&(i.add(o.id.toMultihash().bytes),yield o))}};var U3=class extends De{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Pe([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ve(),yield(await Kt(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Pe([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let i=bn(32),o=Date.now();for await(let s of this.peerRouting.getClosestPeers(i,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await dt(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",i,this.walkers,n)}catch(i){this.log.error("random walk errored",i),this.safeDispatchEvent("walk:error",{detail:i})}this.log("no walkers left, ended walk")}).catch(i=>{this.log.error("random walk errored",i)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Ab=32,Eb=64,F3=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,i]of this.topologies)t[n]=i.size;return t}}),this.handlers=hr({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g3(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new y3(`Handler already registered for protocol ${e}`);let i=Gt.bind({ignoreUndefined:!0})({maxInboundStreams:Ab,maxOutboundStreams:Eb},n);this.handlers.set(e,{handler:t,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(i=>{this.handlers.delete(i)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new K("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,n).then(i=>{for(let o of i.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.filter?.has(t)!==!1&&(a.filter?.remove(t),a.onDisconnect?.(t))}}).catch(i=>{i.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,i)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of i){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,i=e.detail.peerId;for(let o of t){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(i)!==!0&&(a.filter?.add(i),a.onConnect?.(i,n))}}};var $3=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=hr({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=hr({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??rl.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new K("Transport must have a valid tag");if(this.transports.has(t))throw new K(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new E3(`No transport available for address ${String(e)}`);return t?.onProgress?.(new X("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Jn("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new w3)});let n=[];for(let[o,s]of this.transports.entries()){let a=s.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=s.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),B9.matches(c)?t.ipv4.attempts++:L9.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),B9.matches(c)&&t.ipv4.success++,L9.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,f),t.errors.set(c.toString(),f),f}))}}let i=await Promise.allSettled(n);if(!(i.length>0&&i.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===rl.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new x3(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
14
|
+
`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),PW=new RegExp(`(?:^${_o}$)|(?:^${Zy}$)`),RW=new RegExp(`^${_o}$`),DW=new RegExp(`^${Zy}$`),z9=r=>r&&r.exact?PW:new RegExp(`(?:${oc(r)}${_o}${oc(r)})|(?:${oc(r)}${Zy}${oc(r)})`,"g");z9.v4=r=>r&&r.exact?RW:new RegExp(`${oc(r)}${_o}${oc(r)}`,"g");z9.v6=r=>r&&r.exact?DW:new RegExp(`${oc(r)}${Zy}${oc(r)}`,"g");var q9=z9;function j9(r){let e=(...t)=>r(...t);return Object.defineProperty(e,"name",{value:`functionTimeout(${r.name||"<anonymous>"})`,configurable:!0}),e}function eP(){return!1}var{toString:OW}=Object.prototype;function W9(r){return OW.call(r)==="[object RegExp]"}var tP={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function G9(r,e={}){if(!W9(r))throw new TypeError("Expected a RegExp instance");let t=Object.keys(tP).map(i=>(typeof e[i]=="boolean"?e[i]:r[i])?tP[i]:"").join(""),n=new RegExp(e.source||r.source,t);return n.lastIndex=typeof e.lastIndex=="number"?e.lastIndex:r.lastIndex,n}function X9(r,e,{timeout:t}={}){try{return j9(()=>G9(r).test(e),{timeout:t})()}catch(n){if(eP(n))return!1;throw n}}var NW=15,BW=45,rP={timeout:400};function Y9(r){return r.length>BW?!1:X9(q9.v6({exact:!0}),r,rP)}function nP(r){return r.length>NW?!1:X9(q9.v4({exact:!0}),r,rP)}var iP={http:"80",https:"443",ws:"80",wss:"443"},LW=["http","https","ws","wss"];function oP(r,e){e=e??{};let t=e.defaultDnsType??"dns",{scheme:n,hostname:i,port:o,path:s}=MW(r),a=[UW(i,t),FW(o,n),$W(n)];s!=null&&a.push(HW(s));let c="/"+a.filter(l=>!!l).reduce((l,u)=>l.concat(u),[]).join("/");return oe(c)}function MW(r){let[e]=r.split(":");LW.includes(e)||(r="http"+r.substring(e.length));let{protocol:t,hostname:n,port:i,pathname:o,search:s}=new URL(r);if(i==null||i===""){let c=VW(e);c!=null&&(i=c),c==null&&t==="http:"&&(i="80")}let a;return o!=null&&o!==""&&o!=="/"&&(o.startsWith("/")&&(o=o.substring(1)),a=o),s!=null&&s!==""&&(a=a??"",a+=s),{scheme:e,hostname:n,port:i,path:a}}function UW(r,e){if(!(r==null||r==="")){if(nP(r))return["ip4",r];if(Y9(r))return["ip6",r];if(r[0]==="["){let t=r.substring(1,r.length-1);if(Y9(t))return["ip6",t]}return[e,r]}}function FW(r,e){if(!(r==null||r===""))return e==="udp"?["udp",r]:["tcp",r]}function $W(r){if(r.match(/^tcp$|^udp$/)==null)return r==="https"?["/tls/http"]:r==="wss"?["/tls/ws"]:[r]}function HW(r){if(!(r==null||r===""))return["http-path",encodeURIComponent(r)]}function VW(r){if(!(r==null||r===""||iP[r]==null))return iP[r]}var KW=["https://trustless-gateway.link","https://4everland.io"],zW=2336;function qW(r){return r=r.toString(),{id:vn(G.createV1(zW,lr.digest(D(r)))),multiaddrs:[oP(r)]}}var Q9=class{gateways;shuffle;constructor(e={}){this.gateways=(e.gateways??KW).map(t=>qW(t)),this.shuffle=e.shuffle??!0}async*findProviders(e,t){yield*(this.shuffle?this.gateways.toSorted(()=>Math.random()>.5?1:-1):this.gateways).map(n=>({...n,protocols:["transport-ipfs-gateway-http"]}))}};function _m(r={}){return new Q9(r)}var Z9=class{libp2p;constructor(e){this.libp2p=e}async provide(e,t){await this.libp2p.contentRouting.provide(e,t)}async cancelReprovide(e,t){await this.libp2p.contentRouting.cancelReprovide(e,t)}async*findProviders(e,t){yield*this.libp2p.contentRouting.findProviders(e,t)}async put(e,t,n){await this.libp2p.contentRouting.put(e,t,n)}async get(e,t){return this.libp2p.contentRouting.get(e,t)}async findPeer(e,t){return this.libp2p.peerRouting.findPeer(e,t)}async*getClosestPeers(e,t){yield*this.libp2p.peerRouting.getClosestPeers(e,t)}};function Cm(r){return new Z9(r)}var Tm=class extends Zs{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(jt.encode(e.multihash.bytes),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(jt.encode(e.multihash.bytes));if(n==null)throw new Ui;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(jt.encode(e.multihash.bytes))}async delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(jt.encode(e.multihash.bytes))}async*getAll(e){e?.signal?.throwIfAborted();for(let[t,n]of this.data.entries())yield{cid:G.createV1(At,We(jt.decode(t))),block:n},e?.signal?.throwIfAborted()}};var v3e=Ue("blockstore:core:tiered");var sP="SHARDING";function WW(r){return r[Symbol.asyncIterator]!=null}function GW(r){if(WW(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var oa=GW;function XW(r){return r[Symbol.asyncIterator]!=null}function YW(r,e){return XW(r)?(async function*(){yield*(await oa(r)).sort(e)})():(function*(){yield*oa(r).sort(e)})()}var Jy=YW;var sa=class{put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*putMany(e,t={}){for await(let{key:n,value:i}of e)await this.put(n,i,t),yield n}async*getMany(e,t={}){for await(let n of e)yield{key:n,value:await this.get(n,t)}}async*deleteMany(e,t={}){for await(let n of e)await this.delete(n,t),yield n}batch(){let e=[],t=[];return{put(n,i){e.push({key:n,value:i})},delete(n){t.push(n)},commit:async n=>{await Jr(this.putMany(e,n)),e=[],await Jr(this.deleteMany(t,n)),t=[]}}}async*_all(e,t){throw new Error("._all is not implemented")}async*_allKeys(e,t){throw new Error("._allKeys is not implemented")}query(e,t){let n=this._all(e,t);if(e.prefix!=null){let i=e.prefix;n=di(n,o=>o.key.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>di(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Jy(i,o),n)),e.offset!=null){let i=0,o=e.offset;n=di(n,()=>i++>=o)}return e.limit!=null&&(n=$a(n,e.limit)),n}queryKeys(e,t){let n=this._allKeys(e,t);if(e.prefix!=null){let i=e.prefix;n=di(n,o=>o.toString().startsWith(i))}if(Array.isArray(e.filters)&&(n=e.filters.reduce((i,o)=>di(i,o),n)),Array.isArray(e.orders)&&(n=e.orders.reduce((i,o)=>Jy(i,o),n)),e.offset!=null){let i=e.offset,o=0;n=di(n,()=>o++>=i)}return e.limit!=null&&(n=$a(n,e.limit)),n}};var Wl=class extends sa{data;constructor(){super(),this.data=new Map}put(e,t,n){return n?.signal?.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){t?.signal?.throwIfAborted();let n=this.data.get(e.toString());if(n==null)throw new Ui;return n}has(e,t){return t?.signal?.throwIfAborted(),this.data.has(e.toString())}delete(e,t){t?.signal?.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){t?.signal?.throwIfAborted();for(let[n,i]of this.data.entries())yield{key:new it(n),value:i},t?.signal?.throwIfAborted()}*_allKeys(e,t){t?.signal?.throwIfAborted();for(let n of this.data.keys())yield new it(n),t?.signal?.throwIfAborted()}};var e4e=new it(sP);var p4e=Ue("datastore:core:tiered");function Ed(r){if(typeof r!="object"||r===null)return!1;let e=Object.getPrototypeOf(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in r)&&!(Symbol.iterator in r)}var{hasOwnProperty:lP}=Object.prototype,{propertyIsEnumerable:QW}=Object,Sd=(r,e,t)=>{Object.defineProperty(r,e,{value:t,writable:!0,enumerable:!0,configurable:!0})},ZW=void 0,cP={concatArrays:!1,ignoreUndefined:!1},e3=r=>{let e=[];for(let t in r)lP.call(r,t)&&e.push(t);if(Object.getOwnPropertySymbols){let t=Object.getOwnPropertySymbols(r);for(let n of t)QW.call(r,n)&&e.push(n)}return e};function _d(r){return Array.isArray(r)?JW(r):Ed(r)?eG(r):r}function JW(r){let e=r.slice(0,0);return e3(r).forEach(t=>{Sd(e,t,_d(r[t]))}),e}function eG(r){let e=Object.getPrototypeOf(r)===null?Object.create(null):{};return e3(r).forEach(t=>{Sd(e,t,_d(r[t]))}),e}var uP=(r,e,t,n)=>(t.forEach(i=>{typeof e[i]>"u"&&n.ignoreUndefined||(i in r&&r[i]!==Object.getPrototypeOf(r)?Sd(r,i,J9(r[i],e[i],n)):Sd(r,i,_d(e[i])))}),r),tG=(r,e,t)=>{let n=r.slice(0,0),i=0;return[r,e].forEach(o=>{let s=[];for(let a=0;a<o.length;a++)lP.call(o,a)&&(s.push(String(a)),o===r?Sd(n,i++,o[a]):Sd(n,i++,_d(o[a])));n=uP(n,o,e3(o).filter(a=>!s.includes(a)),t)}),n};function J9(r,e,t){return t.concatArrays&&Array.isArray(r)&&Array.isArray(e)?tG(r,e,t):!Ed(e)||!Ed(r)?_d(e):uP(r,e,e3(e),t)}function Gt(...r){let e=J9(_d(cP),this!==ZW&&this||{},cP),t={_:{}};for(let n of r)if(n!==void 0){if(!Ed(n))throw new TypeError("`"+n+"` is not an Option Object");t=J9(t,{_:n},e)}return t._}var eb=class{dns;canResolve(e){return e.getComponents().some(({name:t})=>t==="dnsaddr")}async resolve(e,t){let n=e.getComponents().find(c=>c.name==="dnsaddr")?.value;if(n==null)return[e];let o=await this.getDNS(t).query(`_dnsaddr.${n}`,{signal:t?.signal,types:[an.TXT]}),s=e.getComponents().find(c=>c.name==="p2p")?.value,a=[];for(let c of o.Answer){let l=c.data.replace(/["']/g,"").trim().split("=")[1];l!=null&&(s!=null&&!l.includes(s)||a.push(oe(l)))}return a}getDNS(e){return e.dns!=null?e.dns:(this.dns==null&&(this.dns=Pl()),this.dns)}},Gl=new eb;var rG={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:r=>r},connectionManager:{resolvers:{dnsaddr:Gl}},transportManager:{faultTolerance:rl.FATAL_ALL}};async function fP(r){let e=Gt(rG,r);if(e.connectionProtector===null&&globalThis.process?.env?.LIBP2P_FORCE_PNET!=null)throw new K("Private network is enforced, but no protector was provided");return e}var Im;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.publicKey!=null&&t.publicKey.byteLength>0&&(n.uint32(10),n.bytes(t.publicKey)),t.payloadType!=null&&t.payloadType.byteLength>0&&(n.uint32(18),n.bytes(t.payloadType)),t.payload!=null&&t.payload.byteLength>0&&(n.uint32(26),n.bytes(t.payload)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={publicKey:ke(0),payloadType:ke(0),payload:ke(0),signature:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.publicKey=t.bytes();break}case 2:{o.payloadType=t.bytes();break}case 3:{o.payload=t.bytes();break}case 5:{o.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(Im||(Im={}));var t3=class extends Error{constructor(e="Invalid signature"){super(e),this.name="InvalidSignatureError"}};var pi=class r{static createFromProtobuf=e=>{let t=Im.decode(e),n=rr(t.publicKey);return new r({publicKey:n,payloadType:t.payloadType,payload:t.payload,signature:t.signature})};static seal=async(e,t,n)=>{if(t==null)throw new Error("Missing private key");let i=e.domain,o=e.codec,s=e.marshal(),a=dP(i,o,s),c=await t.sign(a.subarray(),n);return new r({publicKey:t.publicKey,payloadType:o,payload:s,signature:c})};static openAndCertify=async(e,t,n)=>{let i=r.createFromProtobuf(e);if(!await i.validate(t,n))throw new t3("Envelope signature is not valid for the given domain");return i};publicKey;payloadType;payload;signature;marshaled;constructor(e){let{publicKey:t,payloadType:n,payload:i,signature:o}=e;this.publicKey=t,this.payloadType=n,this.payload=i,this.signature=o}marshal(){return this.marshaled==null&&(this.marshaled=Im.encode({publicKey:ur(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return e==null?!1:he(this.marshal(),e.marshal())}async validate(e,t){let n=dP(e,this.payloadType,this.payload);return this.publicKey.verify(n.subarray(),this.signature,t)}},dP=(r,e,t)=>{let n=D(r),i=Sr(n.byteLength),o=Sr(e.length),s=Sr(t.length);return new pe(i,n,o,e,s,t)};function hP(r,e){let t=(n,i)=>n.toString().localeCompare(i.toString());return r.length!==e.length?!1:(e.sort(t),r.sort(t).every((n,i)=>e[i].equals(n)))}var pP="libp2p-peer-record",mP=Uint8Array.from([3,1]);var km;(function(r){let e;(function(n){let i;n.codec=()=>(i==null&&(i=be((o,s,a={})=>{a.lengthDelimited!==!1&&s.fork(),o.multiaddr!=null&&o.multiaddr.byteLength>0&&(s.uint32(10),s.bytes(o.multiaddr)),a.lengthDelimited!==!1&&s.ldelim()},(o,s,a={})=>{let c={multiaddr:ke(0)},l=s==null?o.len:o.pos+s;for(;o.pos<l;){let u=o.uint32();switch(u>>>3){case 1:{c.multiaddr=o.bytes();break}default:{o.skipType(u&7);break}}}return c})),i),n.encode=o=>xe(o,n.codec()),n.decode=(o,s)=>we(o,n.codec(),s)})(e=r.AddressInfo||(r.AddressInfo={}));let t;r.codec=()=>(t==null&&(t=be((n,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),n.peerId!=null&&n.peerId.byteLength>0&&(i.uint32(10),i.bytes(n.peerId)),n.seq!=null&&n.seq!==0n&&(i.uint32(16),i.uint64(n.seq)),n.addresses!=null)for(let s of n.addresses)i.uint32(26),r.AddressInfo.codec().encode(s,i);o.lengthDelimited!==!1&&i.ldelim()},(n,i,o={})=>{let s={peerId:ke(0),seq:0n,addresses:[]},a=i==null?n.len:n.pos+i;for(;n.pos<a;){let c=n.uint32();switch(c>>>3){case 1:{s.peerId=n.bytes();break}case 2:{s.seq=n.uint64();break}case 3:{if(o.limits?.addresses!=null&&s.addresses.length===o.limits.addresses)throw new xt('Decode error - map field "addresses" had too many elements');s.addresses.push(r.AddressInfo.codec().decode(n,n.uint32(),{limits:o.limits?.addresses$}));break}default:{n.skipType(c&7);break}}}return s})),t),r.encode=n=>xe(n,r.codec()),r.decode=(n,i)=>we(n,r.codec(),i)})(km||(km={}));var _n=class r{static createFromProtobuf=e=>{let t=km.decode(e),n=dr(We(t.peerId)),i=(t.addresses??[]).map(s=>oe(s.multiaddr)),o=t.seq;return new r({peerId:n,multiaddrs:i,seqNumber:o})};static DOMAIN=pP;static CODEC=mP;peerId;multiaddrs;seqNumber;domain=r.DOMAIN;codec=r.CODEC;marshaled;constructor(e){let{peerId:t,multiaddrs:n,seqNumber:i}=e;this.peerId=t,this.multiaddrs=n??[],this.seqNumber=i??BigInt(Date.now())}marshal(){return this.marshaled==null&&(this.marshaled=km.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map(e=>({multiaddr:e.bytes}))})),this.marshaled}equals(e){return!(!(e instanceof r)||!this.peerId.equals(e.peerId)||this.seqNumber!==e.seqNumber||!hP(this.multiaddrs,e.multiaddrs))}};var aa;(function(r){let e;(function(i){let o;i.codec=()=>(o==null&&(o=be((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&s.value.byteLength>0&&(a.uint32(18),a.bytes(s.value)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:"",value:ke(0)},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{l.key=s.string();break}case 2:{l.value=s.bytes();break}default:{s.skipType(f&7);break}}}return l})),o),i.encode=s=>xe(s,i.codec()),i.decode=(s,a)=>we(s,i.codec(),a)})(e=r.Peer$metadataEntry||(r.Peer$metadataEntry={}));let t;(function(i){let o;i.codec=()=>(o==null&&(o=be((s,a,c={})=>{c.lengthDelimited!==!1&&a.fork(),s.key!=null&&s.key!==""&&(a.uint32(10),a.string(s.key)),s.value!=null&&(a.uint32(18),n3.codec().encode(s.value,a)),c.lengthDelimited!==!1&&a.ldelim()},(s,a,c={})=>{let l={key:""},u=a==null?s.len:s.pos+a;for(;s.pos<u;){let f=s.uint32();switch(f>>>3){case 1:{l.key=s.string();break}case 2:{l.value=n3.codec().decode(s,s.uint32(),{limits:c.limits?.value});break}default:{s.skipType(f&7);break}}}return l})),o),i.encode=s=>xe(s,i.codec()),i.decode=(s,a)=>we(s,i.codec(),a)})(t=r.Peer$tagsEntry||(r.Peer$tagsEntry={}));let n;r.codec=()=>(n==null&&(n=be((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.addresses!=null)for(let a of i.addresses)o.uint32(10),r3.codec().encode(a,o);if(i.protocols!=null)for(let a of i.protocols)o.uint32(18),o.string(a);if(i.publicKey!=null&&(o.uint32(34),o.bytes(i.publicKey)),i.peerRecordEnvelope!=null&&(o.uint32(42),o.bytes(i.peerRecordEnvelope)),i.metadata!=null&&i.metadata.size!==0)for(let[a,c]of i.metadata.entries())o.uint32(50),r.Peer$metadataEntry.codec().encode({key:a,value:c},o);if(i.tags!=null&&i.tags.size!==0)for(let[a,c]of i.tags.entries())o.uint32(58),r.Peer$tagsEntry.codec().encode({key:a,value:c},o);i.updated!=null&&(o.uint32(64),o.uint64Number(i.updated)),s.lengthDelimited!==!1&&o.ldelim()},(i,o,s={})=>{let a={addresses:[],protocols:[],metadata:new Map,tags:new Map},c=o==null?i.len:i.pos+o;for(;i.pos<c;){let l=i.uint32();switch(l>>>3){case 1:{if(s.limits?.addresses!=null&&a.addresses.length===s.limits.addresses)throw new xt('Decode error - map field "addresses" had too many elements');a.addresses.push(r3.codec().decode(i,i.uint32(),{limits:s.limits?.addresses$}));break}case 2:{if(s.limits?.protocols!=null&&a.protocols.length===s.limits.protocols)throw new xt('Decode error - map field "protocols" had too many elements');a.protocols.push(i.string());break}case 4:{a.publicKey=i.bytes();break}case 5:{a.peerRecordEnvelope=i.bytes();break}case 6:{if(s.limits?.metadata!=null&&a.metadata.size===s.limits.metadata)throw new yp('Decode error - map field "metadata" had too many elements');let u=r.Peer$metadataEntry.codec().decode(i,i.uint32());a.metadata.set(u.key,u.value);break}case 7:{if(s.limits?.tags!=null&&a.tags.size===s.limits.tags)throw new yp('Decode error - map field "tags" had too many elements');let u=r.Peer$tagsEntry.codec().decode(i,i.uint32(),{limits:{value:s.limits?.tags$value}});a.tags.set(u.key,u.value);break}case 8:{a.updated=i.uint64Number();break}default:{i.skipType(l&7);break}}}return a})),n),r.encode=i=>xe(i,r.codec()),r.decode=(i,o)=>we(i,r.codec(),o)})(aa||(aa={}));var r3;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.multiaddr!=null&&t.multiaddr.byteLength>0&&(n.uint32(10),n.bytes(t.multiaddr)),t.isCertified!=null&&(n.uint32(16),n.bool(t.isCertified)),t.observed!=null&&(n.uint32(24),n.uint64Number(t.observed)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={multiaddr:ke(0)},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.multiaddr=t.bytes();break}case 2:{o.isCertified=t.bool();break}case 3:{o.observed=t.uint64Number();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(r3||(r3={}));var n3;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.value!=null&&t.value!==0&&(n.uint32(8),n.uint32(t.value)),t.expiry!=null&&(n.uint32(16),n.uint64(t.expiry)),i.lengthDelimited!==!1&&n.ldelim()},(t,n,i={})=>{let o={value:0},s=n==null?t.len:t.pos+n;for(;t.pos<s;){let a=t.uint32();switch(a>>>3){case 1:{o.value=t.uint32();break}case 2:{o.expiry=t.uint64();break}default:{t.skipType(a&7);break}}}return o})),e),r.encode=t=>xe(t,r.codec()),r.decode=(t,n)=>we(t,r.codec(),n)})(n3||(n3={}));function nG(r,e){if(r.publicKey!=null||e.publicKey==null)return r;let t;r.type==="RSA"&&(t=r.toMultihash());let n=rr(e.publicKey,t);return es(n)}function gP(r,e,t){let n=aa.decode(e);return Cd(r,n,t)}function Cd(r,e,t){let n=new Map,i=BigInt(Date.now());for(let[o,s]of e.tags.entries())s.expiry!=null&&s.expiry<i||n.set(o,s);return{...e,id:nG(r,e),addresses:e.addresses.filter(({observed:o})=>o!=null&&o>Date.now()-t).map(({multiaddr:o,isCertified:s})=>({multiaddr:oe(o),isCertified:s??!1})),metadata:e.metadata,peerRecordEnvelope:e.peerRecordEnvelope??void 0,tags:n}}function yP(r,e){return iG(r.addresses,e.addresses)&&oG(r.protocols,e.protocols)&&sG(r.publicKey,e.publicKey)&&aG(r.peerRecordEnvelope,e.peerRecordEnvelope)&&cG(r.metadata,e.metadata)&&lG(r.tags,e.tags)}function iG(r,e){return xP(r,e,(t,n)=>!(t.isCertified!==n.isCertified||!he(t.multiaddr,n.multiaddr)))}function oG(r,e){return xP(r,e,(t,n)=>t===n)}function sG(r,e){return wP(r,e)}function aG(r,e){return wP(r,e)}function cG(r,e){return bP(r,e,(t,n)=>he(t,n))}function lG(r,e){return bP(r,e,(t,n)=>t.value===n.value&&t.expiry===n.expiry)}function wP(r,e){return r==null&&e==null?!0:r!=null&&e!=null?he(r,e):!1}function xP(r,e,t){if(r.length!==e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function bP(r,e,t){if(r.size!==e.size)return!1;for(let[n,i]of r.entries()){let o=e.get(n);if(o==null||!t(i,o))return!1}return!0}var tb="/peers/";function Pm(r){if(!Ti(r)||r.type==null)throw new K("Invalid PeerId");let e=r.toCID().toString();return new it(`${tb}${e}`)}async function vP(r,e,t,n,i){let o=new Map;for(let s of t){if(s==null)continue;if(s.multiaddr instanceof Uint8Array&&(s.multiaddr=oe(s.multiaddr)),!rc(s.multiaddr))throw new K("Multiaddr was invalid");if(!await e(r,s.multiaddr,i))continue;let a=s.isCertified??!1,c=s.multiaddr.toString(),l=o.get(c);l!=null?s.isCertified=l.isCertified||a:o.set(c,{multiaddr:s.multiaddr,isCertified:a})}return[...o.values()].sort((s,a)=>s.multiaddr.toString().localeCompare(a.multiaddr.toString())).map(({isCertified:s,multiaddr:a})=>{let c=a.getPeerId();return r.equals(c)&&(a=a.decapsulate(oe(`/p2p/${r}`))),{isCertified:s,multiaddr:a.bytes}})}async function o3(r,e,t,n){if(e==null)throw new K("Invalid PeerData");if(e.publicKey!=null&&r.publicKey!=null&&!e.publicKey.equals(r.publicKey))throw new K("publicKey bytes do not match peer id publicKey bytes");let i=n.existingPeer?.peer;if(i!=null&&!r.equals(i.id))throw new K("peer id did not match existing peer id");let o=i?.addresses??[],s=new Set(i?.protocols??[]),a=i?.metadata??new Map,c=i?.tags??new Map,l=i?.peerRecordEnvelope;if(t==="patch"){if((e.multiaddrs!=null||e.addresses!=null)&&(o=[],e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses)),e.protocols!=null&&(s=new Set(e.protocols)),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);a=i3(d,{validate:AP})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags);c=i3(d,{validate:EP,map:SP})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}if(t==="merge"){if(e.multiaddrs!=null&&o.push(...e.multiaddrs.map(d=>({isCertified:!1,multiaddr:d}))),e.addresses!=null&&o.push(...e.addresses),e.protocols!=null&&(s=new Set([...s,...e.protocols])),e.metadata!=null){let d=e.metadata instanceof Map?[...e.metadata.entries()]:Object.entries(e.metadata);for(let[h,m]of d)m==null?a.delete(h):a.set(h,m);a=i3([...a.entries()],{validate:AP})}if(e.tags!=null){let d=e.tags instanceof Map?[...e.tags.entries()]:Object.entries(e.tags),h=new Map(c);for(let[m,g]of d)g==null?h.delete(m):h.set(m,g);c=i3([...h.entries()],{validate:EP,map:SP})}e.peerRecordEnvelope!=null&&(l=e.peerRecordEnvelope)}let u;i?.id.publicKey!=null?u=ur(i.id.publicKey):e.publicKey!=null?u=ur(e.publicKey):r.publicKey!=null&&(u=ur(r.publicKey));let f={addresses:await vP(r,n.addressFilter??(async()=>!0),o,n.existingPeer?.peerPB.addresses,n),protocols:[...s.values()].sort((d,h)=>d.localeCompare(h)),metadata:a,tags:c,publicKey:u,peerRecordEnvelope:l};return f.addresses.forEach(d=>{d.observed=n.existingPeer?.peerPB.addresses?.find(h=>he(h.multiaddr,h.multiaddr))?.observed??Date.now()}),r.type!=="RSA"&&delete f.publicKey,f}function i3(r,e){let t=new Map;for(let[n,i]of r)i!=null&&e.validate(n,i);for(let[n,i]of r.sort(([o],[s])=>o.localeCompare(s)))i!=null&&t.set(n,e.map?.(n,i)??i);return t}function AP(r,e){if(typeof r!="string")throw new K("Metadata key must be a string");if(!(e instanceof Uint8Array))throw new K("Metadata value must be a Uint8Array")}function EP(r,e){if(typeof r!="string")throw new K("Tag name must be a string");if(e.value!=null){if(parseInt(`${e.value}`,10)!==e.value)throw new K("Tag value must be an integer");if(e.value<0||e.value>100)throw new K("Tag value must be between 0-100")}if(e.ttl!=null){if(parseInt(`${e.ttl}`,10)!==e.ttl)throw new K("Tag ttl must be an integer");if(e.ttl<0)throw new K("Tag ttl must be between greater than 0")}}function SP(r,e){let t;e.expiry!=null&&(t=e.expiry),e.ttl!=null&&(t=BigInt(Date.now()+Number(e.ttl)));let n={value:e.value??0};return t!=null&&(n.expiry=t),n}function _P(r){let e=r.toString().split("/")[2],t=G.parse(e,jt);return vn(t)}function rb(r,e,t){let n=_P(r);return gP(n,e,t)}function uG(r,e){return{prefix:tb,filters:(r.filters??[]).map(t=>({key:n,value:i})=>t(rb(n,i,e))),orders:(r.orders??[]).map(t=>(n,i)=>t(rb(n.key,n.value,e),rb(i.key,i.value,e)))}}var s3=class{peerId;datastore;locks;addressFilter;log;maxAddressAge;maxPeerAge;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.peerId=e.peerId,this.datastore=e.datastore,this.addressFilter=t.addressFilter,this.locks=zs({name:"libp2p_peer_store_locks",metrics:e.metrics}),this.maxAddressAge=t.maxAddressAge??36e5,this.maxPeerAge=t.maxPeerAge??216e5}getLock(e){let t=this.locks.get(e);return t==null&&(t={refs:0,lock:am({name:e.toString(),singleProcess:!0})},this.locks.set(e,t)),t.refs++,t}maybeRemoveLock(e,t){t.refs--,t.refs===0&&(t.lock.finalize(),this.locks.delete(e))}async getReadLock(e,t){let n=this.getLock(e);try{let i=await n.lock.readLock(t);return()=>{i(),this.maybeRemoveLock(e,n)}}catch(i){throw this.maybeRemoveLock(e,n),i}}async getWriteLock(e,t){let n=this.getLock(e);try{let i=await n.lock.writeLock(t);return()=>{i(),this.maybeRemoveLock(e,n)}}catch(i){throw this.maybeRemoveLock(e,n),i}}async has(e,t){try{return await this.load(e,t),!0}catch(n){if(n.name!=="NotFoundError")throw n}return!1}async delete(e,t){this.peerId.equals(e)||await this.datastore.delete(Pm(e),t)}async load(e,t){let n=Pm(e),i=await this.datastore.get(n,t),o=aa.decode(i);if(this.#r(e,o))throw await this.datastore.delete(n,t),new qe;return Cd(e,o,this.peerId.equals(e)?1/0:this.maxAddressAge)}async save(e,t,n){let i=await this.#e(e,n),o=await o3(e,t,"patch",{...n,addressFilter:this.addressFilter});return this.#t(e,o,i)}async patch(e,t,n){let i=await this.#e(e,n),o=await o3(e,t,"patch",{...n,addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,i)}async merge(e,t,n){let i=await this.#e(e,n),o=await o3(e,t,"merge",{addressFilter:this.addressFilter,existingPeer:i});return this.#t(e,o,i)}async*all(e){for await(let{key:t,value:n}of this.datastore.query(uG(e??{},this.maxAddressAge),e)){let i=_P(t);if(i.equals(this.peerId))continue;let o=aa.decode(n);if(this.#r(i,o)){await this.datastore.delete(t,e);continue}yield Cd(i,o,this.peerId.equals(i)?1/0:this.maxAddressAge)}}async#e(e,t){try{let n=Pm(e),i=await this.datastore.get(n,t),o=aa.decode(i);if(this.#r(e,o))throw await this.datastore.delete(n,t),new qe;return{peerPB:o,peer:Cd(e,o,this.maxAddressAge)}}catch(n){n.name!=="NotFoundError"&&this.log.error("invalid peer data found in peer store - %e",n)}}async#t(e,t,n,i){t.updated=Date.now();let o=aa.encode(t);return await this.datastore.put(Pm(e),o,i),{peer:Cd(e,t,this.maxAddressAge),previous:n?.peer,updated:n==null||!yP(t,n.peerPB)}}#r(e,t){if(t.updated==null)return!0;if(this.peerId.equals(e))return!1;let n=t.updated<Date.now()-this.maxPeerAge,i=Date.now()-this.maxAddressAge,o=t.addresses.filter(s=>s.observed!=null&&s.observed>i);return n&&o.length===0}};var nb=class{store;events;peerId;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-store"),this.events=e.events,this.peerId=e.peerId,this.store=new s3(e,t)}[Symbol.toStringTag]="@libp2p/peer-store";async forEach(e,t){for await(let n of this.store.all(t))e(n)}async all(e){return oa(this.store.all(e))}async delete(e,t){let n=await this.store.getReadLock(e,t);try{await this.store.delete(e,t)}finally{n()}}async has(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.has(e,t)}finally{this.log.trace("has release read lock"),n?.()}}async get(e,t){let n=await this.store.getReadLock(e,t);try{return await this.store.load(e,t)}finally{n?.()}}async getInfo(e,t){let n=await this.get(e,t);return{id:n.id,multiaddrs:n.addresses.map(({multiaddr:i})=>i)}}async save(e,t,n){let i=await this.store.getWriteLock(e,n);try{let o=await this.store.save(e,t,n);return this.#e(e,o),o.peer}finally{i?.()}}async patch(e,t,n){let i=await this.store.getWriteLock(e,n);try{let o=await this.store.patch(e,t,n);return this.#e(e,o),o.peer}finally{i?.()}}async merge(e,t,n){let i=await this.store.getWriteLock(e,n);try{let o=await this.store.merge(e,t,n);return this.#e(e,o),o.peer}finally{i?.()}}async consumePeerRecord(e,t,n){let i=Ti(t)?t:Ti(t?.expectedPeer)?t.expectedPeer:void 0,o=Ti(t)||t===void 0?n:t,s=await pi.openAndCertify(e,_n.DOMAIN,o),a=vn(s.publicKey.toCID());if(i?.equals(a)===!1)return this.log("envelope peer id was not the expected peer id - expected: %p received: %p",i,a),!1;let c=_n.createFromProtobuf(s.payload),l;try{l=await this.get(a,o)}catch(u){if(u.name!=="NotFoundError")throw u}if(l?.peerRecordEnvelope!=null){let u=pi.createFromProtobuf(l.peerRecordEnvelope),f=_n.createFromProtobuf(u.payload);if(f.seqNumber>=c.seqNumber)return this.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,c.seqNumber),!1}return await this.patch(c.peerId,{peerRecordEnvelope:e,addresses:c.multiaddrs.map(u=>({isCertified:!0,multiaddr:u}))},o),!0}#e(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}};function CP(r,e={}){return new nb(r,e)}var TP=864e13;var fG=448,ib=449,dG=53,hG=54,pG=55,mG=56,a3=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=hr({name:"libp2p_address_manager_dns_mappings",metrics:e.metrics})}has(e){let t=this.findHost(e);for(let n of this.mappings.values())if(n.domain===t)return!0;return!1}add(e,t){t.forEach(n=>{this.log("add DNS mapping %s to %s",n,e);let i=Sn(n)===!0;this.mappings.set(n,{domain:e,verified:i,expires:i?TP-Date.now():0,lastVerified:i?TP-Date.now():void 0})})}remove(e){let t=this.findHost(e),n=!1;for(let[i,o]of this.mappings.entries())o.domain===t&&(this.log("removing %s to %s DNS mapping %e",i,o.domain),this.mappings.delete(i),n=n||o.verified);return n}getAll(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n].multiaddr.stringTuples(),s=o[0][1];if(s!=null)for(let[a,c]of this.mappings.entries()){if(s!==a)continue;this.maybeAddSNITuple(o,c.domain)&&(e.splice(n,1),n--,t.push({multiaddr:oe(`/${o.map(u=>[Hi(u[0]).name,u[1]].join("/")).join("/")}`),verified:c.verified,type:"dns-mapping",expires:c.expires,lastVerified:c.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(let n=0;n<e.length;n++)if(e[n][0]===fG&&e[n+1]?.[0]!==ib)return e.splice(n+1,0,[ib,t]),!0;return!1}confirm(e,t){let n=this.findHost(e),i=!1;for(let[o,s]of this.mappings.entries())s.domain===n&&(this.log("marking %s to %s DNS mapping as verified",o,s.domain),i=s.verified,s.verified=!0,s.expires=Date.now()+t,s.lastVerified=Date.now());return i}unconfirm(e,t){let n=this.findHost(e),i=!1;for(let[o,s]of this.mappings.entries())s.domain===n&&(this.log("removing verification of %s to %s DNS mapping",o,s.domain),i=i||s.verified,s.verified=!1,s.expires=Date.now()+t);return i}findHost(e){for(let t of e.stringTuples())if(t[0]===ib||t[0]===dG||t[0]===hG||t[0]===pG||t[0]===mG)return t[1]}};var ob=4,sb=41,ab=6,gG=273,c3=class{log;mappings;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=hr({name:"libp2p_address_manager_ip_mappings",metrics:e.metrics})}has(e){let t=e.stringTuples();for(let n of this.mappings.values())for(let i of n)if(i.externalIp===t[0][1])return!0;return!1}add(e,t,n,i=t,o="tcp"){let s=`${e}-${t}-${o}`,a=this.mappings.get(s)??[],c={internalIp:e,internalPort:t,externalIp:n,externalPort:i,externalFamily:bo(n)?4:6,protocol:o,verified:!1,expires:0};a.push(c),this.mappings.set(s,a)}remove(e){let t=e.stringTuples(),n=t[0][1]??"",i=t[1][0]===ab?"tcp":"udp",o=parseInt(t[1][1]??"0"),s=!1;for(let[a,c]of this.mappings.entries()){for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===n&&u.externalPort===o&&u.protocol===i&&(this.log("removing %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,n,o,i),s=s||u.verified,c.splice(l,1),l--)}c.length===0&&this.mappings.delete(a)}return s}getAll(e){let t=[];for(let{multiaddr:n}of e){let i=n.stringTuples(),o;if((i[0][0]===ob||i[0][0]===sb)&&i[1][0]===ab?o=`${i[0][1]}-${i[1][1]}-tcp`:(i[0][0]===ob||i[0][0]===sb)&&i[1][0]===gG&&(o=`${i[0][1]}-${i[1][1]}-udp`),o==null)continue;let s=this.mappings.get(o);if(s!=null)for(let a of s)i[0][0]=a.externalFamily===4?ob:sb,i[0][1]=a.externalIp,i[1][1]=`${a.externalPort}`,t.push({multiaddr:oe(`/${i.map(c=>[Hi(c[0]).name,c[1]].join("/")).join("/")}`),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}return t}confirm(e,t){let i=e.stringTuples()[0][1],o=!1;for(let s of this.mappings.values())for(let a of s)a.externalIp===i&&(this.log("marking %s to %s IP mapping as verified",a.internalIp,a.externalIp),o=a.verified,a.verified=!0,a.expires=Date.now()+t,a.lastVerified=Date.now());return o}unconfirm(e,t){let n=e.stringTuples(),i=n[0][1]??"",o=n[1][0]===ab?"tcp":"udp",s=parseInt(n[1][1]??"0"),a=!1;for(let c of this.mappings.values())for(let l=0;l<c.length;l++){let u=c[l];u.externalIp===i&&u.externalPort===s&&u.protocol===o&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",u.externalIp,u.externalPort,i,s,o),a=a||u.verified,u.verified=!1,u.expires=Date.now()+t)}return a}};function IP(r){try{for(let{code:e,value:t}of r.getComponents())if(e!==42&&t!=null){if(e===4)return t.startsWith("169.254.");if(e===41)return t.toLowerCase().startsWith("fe80")}}catch{}return!1}function l3(r){try{for(let{code:e}of r.getComponents())if(e!==42)return e===4||e===41}catch{}return!1}function Vi(r){try{if(!l3(r))return!1;let[[,e]]=r.stringTuples();return e==null?!1:Sn(e)??!1}catch{}return!0}var yG={maxObservedAddresses:10},u3=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=hr({name:"libp2p_address_manager_observed_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??yG.maxObservedAddresses}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(let t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(Vi(e)||IP(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map(([e,t])=>({multiaddr:oe(e),verified:t.verified,type:"observed",expires:t.expires,lastVerified:t.lastVerified}))}remove(e){let t=this.addresses.get(e.toString())?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),t}confirm(e,t){let n=e.toString(),i=this.addresses.get(n)??{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,i),o}};var wG=[4,41,53,54,55,56];function cb(r){try{for(let{code:e}of r.getComponents())if(e!==42)return wG.includes(e)}catch{}return!1}var xG={maxObservedAddresses:10},f3=class{log;addresses;maxObservedAddresses;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=hr({name:"libp2p_address_manager_transport_addresses",metrics:e.metrics}),this.maxObservedAddresses=t.maxObservedAddresses??xG.maxObservedAddresses}get(e,t){if(Vi(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};let n=this.toKey(e),i=this.addresses.get(n);return i==null&&(i={verified:!cb(e),expires:0},this.addresses.set(n,i)),{multiaddr:e,verified:i.verified,type:"transport",expires:i.expires,lastVerified:i.lastVerified}}has(e){let t=this.toKey(e);return this.addresses.has(t)}remove(e){let t=this.toKey(e),n=this.addresses.get(t)?.verified??!1;return this.log("removing observed address %a",e),this.addresses.delete(t),n}confirm(e,t){let n=this.toKey(e),i=this.addresses.get(n)??{verified:!1,expires:0,lastVerified:0},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.addresses.set(n,i),o}unconfirm(e,t){let n=this.toKey(e),i=this.addresses.get(n)??{verified:!1,expires:0},o=i.verified;return i.verified=!1,i.expires=Date.now()+t,this.addresses.set(n,i),o}toKey(e){if(cb(e)){let t=e.toOptions();return`${t.host}-${t.port}-${t.transport}`}return e.toString()}};var kP=6e4,PP={maxObservedAddresses:10,addressVerificationTTL:kP*10,addressVerificationRetry:kP*5},bG=r=>r;function lb(r,e){let t=r.getPeerId();return t!=null&>(t).equals(e)&&(r=r.decapsulate(oe(`/p2p/${e.toString()}`))),r}var d3=class{log;components;listen;announce;appendAnnounce;announceFilter;observed;dnsMappings;ipMappings;transportAddresses;observedAddressFilter;addressVerificationTTL;addressVerificationRetry;constructor(e,t={}){let{listen:n=[],announce:i=[],appendAnnounce:o=[]}=t;this.components=e,this.log=e.logger.forComponent("libp2p:address-manager"),this.listen=n.map(s=>s.toString()),this.announce=new Set(i.map(s=>s.toString())),this.appendAnnounce=new Set(o.map(s=>s.toString())),this.observed=new u3(e,t),this.dnsMappings=new a3(e,t),this.ipMappings=new c3(e,t),this.transportAddresses=new f3(e,t),this.announceFilter=t.announceFilter??bG,this.observedAddressFilter=on(1024),this.addressVerificationTTL=t.addressVerificationTTL??PP.addressVerificationTTL,this.addressVerificationRetry=t.addressVerificationRetry??PP.addressVerificationRetry,this._updatePeerStoreAddresses=Is(this._updatePeerStoreAddresses.bind(this),1e3),e.events.addEventListener("transport:listening",()=>{this._updatePeerStoreAddresses()}),e.events.addEventListener("transport:close",()=>{this._updatePeerStoreAddresses()})}[Symbol.toStringTag]="@libp2p/address-manager";_updatePeerStoreAddresses(){let e=this.getAddresses().map(t=>t.getPeerId()===this.components.peerId.toString()?t.decapsulate(`/p2p/${this.components.peerId.toString()}`):t);this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch(t=>{this.log.error("error updating addresses",t)})}getListenAddrs(){return Array.from(this.listen).map(e=>oe(e))}getAnnounceAddrs(){return Array.from(this.announce).map(e=>oe(e))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map(e=>oe(e))}getObservedAddrs(){return this.observed.getAll().map(e=>e.multiaddr)}addObservedAddr(e){let t=e.stringTuples(),n=`${t[0][1]}:${t[1][1]}`;this.observedAddressFilter.has(n)||(this.observedAddressFilter.add(n),e=lb(e,this.components.peerId),!this.ipMappings.has(e)&&(this.dnsMappings.has(e)||this.observed.add(e)))}confirmObservedAddr(e,t){e=lb(e,this.components.peerId);let n=!0;(t?.type==="transport"||this.transportAddresses.has(e))&&!this.transportAddresses.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="dns-mapping"||this.dnsMappings.has(e))&&!this.dnsMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="ip-mapping"||this.ipMappings.has(e))&&!this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1),(t?.type==="observed"||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,t?.ttl??this.addressVerificationTTL),n=!1):!this.observed.confirm(e,t?.ttl??this.addressVerificationTTL)&&n&&(n=!1)),n||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){e=lb(e,this.components.peerId);let n=!1;this.observed.has(e)&&!this.observed.remove(e)&&n&&(n=!1),this.transportAddresses.has(e)&&!this.transportAddresses.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.dnsMappings.has(e)&&!this.dnsMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),this.ipMappings.has(e)&&!this.ipMappings.unconfirm(e,t?.ttl??this.addressVerificationRetry)&&n&&(n=!1),n&&this._updatePeerStoreAddresses()}getAddresses(){let e=new Set,t=this.getAddressesWithMetadata().filter(n=>{if(!n.verified)return!1;let i=n.multiaddr.toString();return e.has(i)?!1:(e.add(i),!0)}).map(n=>n.multiaddr);return this.announceFilter(t.map(n=>{let i=oe(n);return i.getComponents().pop()?.value===this.components.peerId.toString()?i:i.encapsulate(`/p2p/${this.components.peerId.toString()}`)}))}getAddressesWithMetadata(){let e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach(i=>{i.updateAnnounceAddrs(e)}),e.map(i=>({multiaddr:i,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}));let t=[];t=t.concat(this.components.transportManager.getAddrs().map(i=>this.transportAddresses.get(i,this.addressVerificationTTL)));let n=this.getAppendAnnounceAddrs();return n.length>0&&(this.components.transportManager.getListeners().forEach(i=>{i.updateAnnounceAddrs(n)}),t=t.concat(n.map(i=>({multiaddr:i,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})))),t=t.concat(this.observed.getAll()),t=t.concat(this.ipMappings.getAll(t)),t=t.concat(this.dnsMappings.getAll(t)),t}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(oe(`/dns/${e}`))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,n,i=t,o="tcp"){this.ipMappings.add(e,t,n,i,o),this.observed.removePrefixed(`/ip${bo(n)?4:6}/${n}/${o}/${i}`)}removePublicAddressMapping(e,t,n,i=t,o="tcp"){this.ipMappings.remove(oe(`/ip${bo(n)?4:6}/${n}/${o}/${i}`))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){if(this.ipMappings.has(e))return!1;let t=e.toOptions();if(t.family===6||t.host==="127.0.0.1"||Sn(t.host)===!0)return!1;let n=this.components.transportManager.getListeners(),i=[o=>na.exactMatch(o)||ql.exactMatch(o),o=>zl.exactMatch(o),o=>Rk.exactMatch(o)];for(let o of i){if(!o(e))continue;let s=n.filter(l=>l.getAddrs().filter(u=>u.toOptions().family===4&&o(u)).length>0);if(s.length!==1)continue;let a=s[0].getAddrs().filter(l=>l.toOptions().host!=="127.0.0.1").pop();if(a==null)continue;let c=a.toOptions();return this.observed.remove(e),this.ipMappings.add(c.host,c.port,t.host,t.port,t.transport),!0}return!1}};var RP;(function(r){r.NOT_STARTED_YET="The libp2p node is not started yet",r.NOT_FOUND="Not found"})(RP||(RP={}));var h3=class extends Error{constructor(e="Missing service"){super(e),this.name="MissingServiceError"}},p3=class extends Error{constructor(e="Unmet service dependencies"){super(e),this.name="UnmetServiceDependenciesError"}},Td=class extends Error{constructor(e="No content routers available"){super(e),this.name="NoContentRoutersError"}},Rm=class extends Error{constructor(e="No peer routers available"){super(e),this.name="NoPeerRoutersError"}},m3=class extends Error{constructor(e="Should not try to find self"){super(e),this.name="QueriedForSelfError"}},g3=class extends Error{constructor(e="Unhandled protocol error"){super(e),this.name="UnhandledProtocolError"}},y3=class extends Error{constructor(e="Duplicate protocol handler error"){super(e),this.name="DuplicateProtocolHandlerError"}},Dm=class extends Error{constructor(e="Dial denied error"){super(e),this.name="DialDeniedError"}},w3=class extends Error{constructor(e="No transport was configured to listen on this address"){super(e),this.name="UnsupportedListenAddressError"}},x3=class extends Error{constructor(e="Configured listen addresses could not be listened on"){super(e),this.name="UnsupportedListenAddressesError"}},b3=class extends Error{constructor(e="No valid addresses"){super(e),this.name="NoValidAddressesError"}},v3=class extends Error{constructor(e="Connection intercepted"){super(e),this.name="ConnectionInterceptedError"}},A3=class extends Error{constructor(e="Connection denied"){super(e),this.name="ConnectionDeniedError"}},Xl=class extends Error{constructor(e="Stream is not multiplexed"){super(e),this.name="MuxerUnavailableError"}},Yl=class extends Error{constructor(e="Encryption failed"){super(e),this.name="EncryptionFailedError"}},E3=class extends Error{constructor(e="Transport unavailable"){super(e),this.name="TransportUnavailableError"}},S3=class extends Error{constructor(e="Max recursive depth reached"){super(e),this.name="RecursionLimitError"}};var ub=class{components={};_started=!1;constructor(e={}){this.components={};for(let[t,n]of Object.entries(e))this.components[t]=n;this.components.logger==null&&(this.components.logger=Za())}isStarted(){return this._started}async _invokeStartableMethod(e){await Promise.all(Object.values(this.components).filter(t=>bg(t)).map(async t=>{await t[e]?.()}))}async beforeStart(){await this._invokeStartableMethod("beforeStart")}async start(){await this._invokeStartableMethod("start"),this._started=!0}async afterStart(){await this._invokeStartableMethod("afterStart")}async beforeStop(){await this._invokeStartableMethod("beforeStop")}async stop(){await this._invokeStartableMethod("stop"),this._started=!1}async afterStop(){await this._invokeStartableMethod("afterStop")}},AG=["metrics","connectionProtector","dns"],EG=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function DP(r={}){let e=new ub(r);return new Proxy(e,{get(n,i,o){if(typeof i=="string"&&!EG.includes(i)){let s=e.components[i];if(s==null&&!AG.includes(i))throw new h3(`${i} not set`);return s}return Reflect.get(n,i,o)},set(n,i,o){return typeof i=="string"?e.components[i]=o:Reflect.set(n,i,o),!0}})}function OP(r){let e={};for(let t of Object.values(r.components))for(let n of SG(t))e[n]=!0;for(let t of Object.values(r.components))for(let n of _G(t))if(e[n]!==!0)throw new p3(`Service "${CG(t)}" required capability "${n}" but it was not provided by any component, you may need to add additional configuration when creating your node.`)}function SG(r){return Array.isArray(r?.[et])?r[et]:[]}function _G(r){return Array.isArray(r?.[ei])?r[ei]:[]}function CG(r){return r?.[Symbol.toStringTag]??r?.toString()??"unknown"}var TG=4,IG=41;function NP(r={}){return{denyDialPeer:async()=>!1,denyDialMultiaddr:async e=>{if(na.matches(e))return!1;let t=e.stringTuples();return t[0][0]===TG||t[0][0]===IG?!!Sn(`${t[0][1]}`):!1},denyInboundConnection:async()=>!1,denyOutboundConnection:async()=>!1,denyInboundEncryptedConnection:async()=>!1,denyOutboundEncryptedConnection:async()=>!1,denyInboundUpgradedConnection:async()=>!1,denyOutboundUpgradedConnection:async()=>!1,filterMultiaddrForPeer:async()=>!0,...r}}var BP=()=>{let r=new Error("Delay aborted");return r.name="AbortError",r},kG=new WeakMap;function PG({clearTimeout:r,setTimeout:e}={}){return(t,{value:n,signal:i}={})=>{if(i?.aborted)return Promise.reject(BP());let o,s,a,c=r??clearTimeout,l=()=>{c(o),a(BP())},u=()=>{i&&i.removeEventListener("abort",l)},f=new Promise((d,h)=>{s=()=>{u(),d(n)},a=h,o=(e??setTimeout)(s,t)});return i&&i.addEventListener("abort",l,{once:!0}),kG.set(f,()=>{c(o),o=null,s()}),f}}var RG=PG(),_3=RG;var Id=class{memoryStorage;points;duration;blockDuration;execEvenly;execEvenlyMinDelayMs;keyPrefix;constructor(e={}){this.points=e.points??4,this.duration=e.duration??1,this.blockDuration=e.blockDuration??0,this.execEvenly=e.execEvenly??!1,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs??this.duration*1e3/this.points,this.keyPrefix=e.keyPrefix??"rlflx",this.memoryStorage=new fb}async consume(e,t=1,n={}){let i=this.getKey(e),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,t,o);if(s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.consumedPoints>this.points)throw this.blockDuration>0&&s.consumedPoints<=this.points+t&&(s=this.memoryStorage.set(i,s.consumedPoints,this.blockDuration)),new Ag("Rate limit exceeded",s);if(this.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){let a=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));a<this.execEvenlyMinDelayMs&&(a=s.consumedPoints*this.execEvenlyMinDelayMs),await _3(a)}return s}penalty(e,t=1,n={}){let i=this.getKey(e),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,t,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}reward(e,t=1,n={}){let i=this.getKey(e),o=this._getKeySecDuration(n),s=this.memoryStorage.incrby(i,-t,o);return s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s}block(e,t){let n=t*1e3,i=this.points+1;return this.memoryStorage.set(this.getKey(e),i,t),{remainingPoints:0,msBeforeNext:n===0?-1:n,consumedPoints:i,isFirstInDuration:!1}}set(e,t,n=0){let i=(n>=0?n:this.duration)*1e3;return this.memoryStorage.set(this.getKey(e),t,n),{remainingPoints:0,msBeforeNext:i===0?-1:i,consumedPoints:t,isFirstInDuration:!1}}get(e){let t=this.memoryStorage.get(this.getKey(e));return t!=null&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return e?.customDuration!=null&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}},fb=class{storage;constructor(){this.storage=new Map}incrby(e,t,n){let i=this.storage.get(e);if(i!=null){let o=i.expiresAt!=null?i.expiresAt.getTime()-new Date().getTime():-1;return i.expiresAt==null||o>0?(i.value+=t,{remainingPoints:0,msBeforeNext:o,consumedPoints:i.value,isFirstInDuration:!1}):this.set(e,t,n)}return this.set(e,t,n)}set(e,t,n){let i=n*1e3,o=this.storage.get(e);o!=null&&clearTimeout(o.timeoutId);let s={value:t,expiresAt:i>0?new Date(Date.now()+i):void 0};return this.storage.set(e,s),i>0&&(s.timeoutId=setTimeout(()=>{this.storage.delete(e)},i),s.timeoutId.unref!=null&&s.timeoutId.unref()),{remainingPoints:0,msBeforeNext:i===0?-1:i,consumedPoints:s.value,isFirstInDuration:!0}}get(e){let t=this.storage.get(e);if(t!=null)return{remainingPoints:0,msBeforeNext:t.expiresAt!=null?t.expiresAt.getTime()-new Date().getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){let t=this.storage.get(e);return t!=null?(t.timeoutId!=null&&clearTimeout(t.timeoutId),this.storage.delete(e),!0):!1}};function C3(r){if(Ti(r))return{peerId:r,multiaddrs:[]};let e=Array.isArray(r)?r:[r],t;if(e.length>0){let n=e[0].getPeerId();t=n==null?void 0:gt(n),e.forEach(i=>{if(!rc(i))throw new Ma("Invalid multiaddr");let o=i.getPeerId();if(o==null){if(t!=null)throw new K("Multiaddrs must all have the same peer id or have no peer id")}else{let s=gt(o);if(t?.equals(s)!==!0)throw new K("Multiaddrs must all have the same peer id or have no peer id")}})}return e=e.filter(n=>!Ck.exactMatch(n)),{peerId:t,multiaddrs:e}}var DG=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];async function LP(r,e){let t=r?.streams?.map(i=>i.protocol)??[],n=e?.closableProtocols??DG;if(!(t.filter(i=>i!=null&&!n.includes(i)).length>0))try{await r?.close(e)}catch(i){r?.abort(i)}}function Om(r){try{let e;typeof r=="string"?e=oe(r):e=r;let t=new Set([...e.getComponents().map(n=>n.name)]);if(!t.has("ipcidr")){let i=t.has("ip6")?"/ipcidr/128":"/ipcidr/32";e=e.encapsulate(i)}return P9(e)}catch{throw new Error(`Can't convert to IpNet, Invalid multiaddr format: ${r}`)}}var T3=class{connectionManager;peerStore;allow;events;log;constructor(e,t={}){this.allow=(t.allow??[]).map(n=>Om(n)),this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch(e=>{this.log.error("error while pruning connections %e",e)})}async _maybePruneConnections(){let e=this.connectionManager.getConnections(),t=e.length,n=this.connectionManager.getMaxConnections();if(this.log("checking max connections limit %d/%d",t,n),t<=n)return;let i=new nn;for(let c of e){let l=c.remotePeer;if(!i.has(l)){i.set(l,0);try{let u=await this.peerStore.get(l);i.set(l,[...u.tags.values()].reduce((f,d)=>f+d.value,0))}catch(u){u.name!=="NotFoundError"&&this.log.error("error loading peer tags",u)}}}let o=this.sortConnections(e,i),s=Math.max(t-n,0),a=[];for(let c of o)if(this.log("too many connections open - closing a connection to %p",c.remotePeer),this.allow.some(u=>u.contains(c.remoteAddr.nodeAddress().address))||a.push(c),a.length===s)break;await Promise.all(a.map(async c=>{await LP(c,{signal:AbortSignal.timeout(1e3)})})),this.events.safeDispatchEvent("connection:prune",{detail:a})}sortConnections(e,t){return e.sort((n,i)=>{let o=n.timeline.open,s=i.timeline.open;return o<s?1:o>s?-1:0}).sort((n,i)=>n.direction==="outbound"&&i.direction==="inbound"?1:n.direction==="inbound"&&i.direction==="outbound"?-1:0).sort((n,i)=>n.streams.length>i.streams.length?1:n.streams.length<i.streams.length?-1:0).sort((n,i)=>{let o=t.get(n.remotePeer)??0,s=t.get(i.remotePeer)??0;return o>s?1:o<s?-1:0})}};var MP="last-dial-failure",UP="last-dial-success";var FP=100,I3=50;var k3=class extends Dr{constructor(e={}){super({...e,sort:(t,n)=>t.options.priority>n.options.priority?-1:t.options.priority<n.options.priority?1:0})}};function $P(r){return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(r)||/^::1$/.test(r)}function db(r){if(!l3(r))return!1;let{address:e}=r.nodeAddress();return $P(e)}function OG(r,e){let t=zl.exactMatch(r.multiaddr),n=zl.exactMatch(e.multiaddr);if(t&&!n)return-1;if(!t&&n)return 1;let i=ql.exactMatch(r.multiaddr),o=ql.exactMatch(e.multiaddr);if(i&&!o)return-1;if(!i&&o)return 1;let s=na.exactMatch(r.multiaddr),a=na.exactMatch(e.multiaddr);if(s&&!a)return-1;if(!s&&a)return 1;let c=xm.exactMatch(r.multiaddr),l=xm.exactMatch(e.multiaddr);if(c&&!l)return-1;if(!c&&l)return 1;let u=wm.exactMatch(r.multiaddr),f=wm.exactMatch(e.multiaddr);if(u&&!f)return-1;if(!u&&f)return 1;let d=F9.exactMatch(r.multiaddr),h=F9.exactMatch(e.multiaddr);return d&&!h?-1:!d&&h?1:0}function NG(r,e){let t=db(r.multiaddr),n=db(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function BG(r,e){let t=Vi(r.multiaddr),n=Vi(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function LG(r,e){return r.isCertified&&!e.isCertified?-1:!r.isCertified&&e.isCertified?1:0}function MG(r,e){let t=Nn.exactMatch(r.multiaddr),n=Nn.exactMatch(e.multiaddr);return t&&!n?1:!t&&n?-1:0}function HP(r){return r.sort(OG).sort(LG).sort(MG).sort(BG).sort(NG)}async function hb(r,e,t){let n=t.depth??0;if(n>(t.maxRecursiveDepth??32))throw new S3("Max recursive depth reached");let i=!1,o=[];for(let s of Object.values(e))if(s.canResolve(r)){i=!0;let a=await s.resolve(r,t);for(let c of a)o.push(...await hb(c,e,{...t,depth:n+1}))}return i===!1&&o.push(r),o}var Nm={maxParallelDials:I3,maxDialQueueLength:500,maxPeerAddrsToDial:25,dialTimeout:1e4,resolvers:{dnsaddr:Gl}},P3=class{queue;components;addressSorter;maxPeerAddrsToDial;maxDialQueueLength;dialTimeout;shutDownController;connections;log;resolvers;constructor(e,t={}){this.addressSorter=t.addressSorter,this.maxPeerAddrsToDial=t.maxPeerAddrsToDial??Nm.maxPeerAddrsToDial,this.maxDialQueueLength=t.maxDialQueueLength??Nm.maxDialQueueLength,this.dialTimeout=t.dialTimeout??Nm.dialTimeout,this.connections=t.connections??new nn,this.log=e.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=e,this.resolvers=t.resolvers??Nm.resolvers,this.shutDownController=new AbortController,this.shutDownController.signal,this.queue=new k3({concurrency:t.maxParallelDials??Nm.maxParallelDials,metricName:"libp2p_dial_queue",metrics:e.metrics}),this.queue.addEventListener("failure",n=>{n.detail?.error.name!==Je.name&&this.log.error("error in dial queue - %e",n.detail)})}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}async dial(e,t={}){let{peerId:n,multiaddrs:i}=C3(e),o=Array.from(this.connections.values()).flat().find(a=>t.force===!0||a.limits!=null?!1:a.remotePeer.equals(n)?!0:i.find(c=>c.equals(a.remoteAddr)));if(o?.status==="open")return this.log("already connected to %a",o.remoteAddr),t.onProgress?.(new X("dial-queue:already-connected")),o;let s=this.queue.queue.find(a=>{if(n?.equals(a.options.peerId)===!0)return!0;let c=a.options.multiaddrs;if(c==null)return!1;for(let l of i)if(c.has(l.toString()))return!0;return!1});if(s!=null){this.log("joining existing dial target for %p",n);for(let a of i)s.options.multiaddrs.add(a.toString());return t.onProgress?.(new X("dial-queue:already-in-dial-queue")),s.join(t)}if(this.queue.size>=this.maxDialQueueLength)throw new Ts("Dial queue is full");return this.log("creating dial target for %p",n,i.map(a=>a.toString())),t.onProgress?.(new X("dial-queue:add-to-dial-queue")),this.queue.add(async a=>{a.onProgress?.(new X("dial-queue:start-dial"));let c=Pe([this.shutDownController.signal,a.signal]);try{return await this.dialPeer(a,c)}finally{c.clear()}},{peerId:n,priority:t.priority??yb,multiaddrs:new Set(i.map(a=>a.toString())),signal:t.signal??AbortSignal.timeout(this.dialTimeout),onProgress:t.onProgress})}async dialPeer(e,t){let n=e.peerId,i=e.multiaddrs,o=new Set,s=e.multiaddrs.size===0,a=0,c=0,l=[];for(this.log("starting dial to %p",n);s||i.size>0;){c++,s=!1;let u=[],f=new Set(e.multiaddrs);i.clear(),this.log("calculating addrs to dial %p from %s",n,[...f]);let d=await this.calculateMultiaddrs(n,f,{...e,signal:t});for(let h of d){if(o.has(h.multiaddr.toString())){this.log.trace("skipping previously failed multiaddr %a while dialing %p",h.multiaddr,n);continue}u.push(h)}this.log("%s dial to %p with %s",c===1?"starting":"continuing",n,u.map(h=>h.multiaddr.toString())),e?.onProgress?.(new X("dial-queue:calculated-addresses",u));for(let h of u){if(a===this.maxPeerAddrsToDial)throw this.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",a,e.peerId),new Ts("Peer had more than maxPeerAddrsToDial");a++;try{let m=await this.components.transportManager.dial(h.multiaddr,{...e,signal:t});this.log("dial to %a succeeded",h.multiaddr);try{await this.components.peerStore.merge(m.remotePeer,{multiaddrs:[m.remoteAddr],metadata:{[UP]:D(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}return m}catch(m){if(this.log.error("dial failed to %a",h.multiaddr,m),o.add(h.multiaddr.toString()),n!=null)try{await this.components.peerStore.merge(n,{metadata:{[MP]:D(Date.now().toString())}})}catch(g){this.log.error("could not update last dial failure key for %p",n,g)}if(t.aborted)throw new Ii(m.message);l.push(m)}}}throw l.length===1?l[0]:new AggregateError(l,"All multiaddr dials failed")}async calculateMultiaddrs(e,t=new Set,n={}){let i=[...t].map(f=>({multiaddr:oe(f),isCertified:!1}));if(e!=null){if(this.components.peerId.equals(e))throw new Ts("Tried to dial self");if(await this.components.connectionGater.denyDialPeer?.(e)===!0)throw new Dm("The dial request is blocked by gater.allowDialPeer");if(i.length===0){this.log("loading multiaddrs for %p",e);try{let f=await this.components.peerStore.get(e);i.push(...f.addresses),this.log("loaded multiaddrs for %p",e,i.map(({multiaddr:d})=>d.toString()))}catch(f){if(f.name!=="NotFoundError")throw f}}if(i.length===0){this.log("looking up multiaddrs for %p in the peer routing",e);try{let f=await this.components.peerRouting.findPeer(e,n);this.log("found multiaddrs for %p in the peer routing",e,i.map(({multiaddr:d})=>d.toString())),i.push(...f.multiaddrs.map(d=>({multiaddr:d,isCertified:!1})))}catch(f){f.name==="NoPeerRoutersError"?this.log("no peer routers configured",e):this.log.error("looking up multiaddrs for %p in the peer routing failed - %e",e,f)}}}let o=(await Promise.all(i.map(async f=>{let d=await hb(f.multiaddr,this.resolvers,{dns:this.components.dns,log:this.log,...n});return d.length===1&&d[0].equals(f.multiaddr)?f:d.map(h=>({multiaddr:h,isCertified:!1}))}))).flat();if(e!=null){let f=`/p2p/${e.toString()}`;o=o.map(d=>d.multiaddr.getComponents().pop()?.name!=="p2p"?{multiaddr:d.multiaddr.encapsulate(f),isCertified:d.isCertified}:d)}let s=o.filter(f=>{if(this.components.transportManager.dialTransportForMultiaddr(f.multiaddr)==null)return!1;let d=f.multiaddr.getPeerId();return e!=null&&d!=null?e.equals(d):!0}),a=new Map;for(let f of s){let d=f.multiaddr.toString(),h=a.get(d);if(h!=null){h.isCertified=h.isCertified||f.isCertified||!1;continue}a.set(d,f)}let c=[...a.values()];if(c.length===0)throw new b3("The dial request has no valid addresses");let l=[];for(let f of c)this.components.connectionGater.denyDialMultiaddr!=null&&await this.components.connectionGater.denyDialMultiaddr(f.multiaddr)||l.push(f);let u=this.addressSorter==null?HP(l):l.sort(this.addressSorter);if(u.length===0)throw new Dm("The connection gater denied all addresses in the dial request");return this.log.trace("addresses for %p before filtering",e??"unknown peer",o.map(({multiaddr:f})=>f.toString())),this.log.trace("addresses for %p after filtering",e??"unknown peer",u.map(({multiaddr:f})=>f.toString())),u}async isDialable(e,t={}){Array.isArray(e)||(e=[e]);try{let n=await this.calculateMultiaddrs(void 0,new Set(e.map(i=>i.toString())),t);return t.runOnLimitedConnection===!1?n.find(i=>!Nn.matches(i.multiaddr))!=null:!0}catch(n){this.log.trace("error calculating if multiaddr(s) were dialable",n)}return!1}};var GP=mt(jP(),1);var FG=Object.prototype.toString,$G=r=>FG.call(r)==="[object Error]",HG=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred."]);function wb(r){if(!(r&&$G(r)&&r.name==="TypeError"&&typeof r.message=="string"))return!1;let{message:t,stack:n}=r;return t==="Load failed"?n===void 0||"__sentry_captured__"in r:t.startsWith("error sending request for url")?!0:HG.has(t)}var xb=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},WP=(r,e,t)=>{let n=t.retries-(e-1);return r.attemptNumber=e,r.retriesLeft=n,r};async function bb(r,e){return new Promise((t,n)=>{e={...e},e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.retries??=10;let i=GP.default.operation(e),o=()=>{i.stop(),n(e.signal?.reason)};e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",o,{once:!0});let s=()=>{e.signal?.removeEventListener("abort",o),i.stop()};i.attempt(async a=>{try{let c=await r(a);s(),t(c)}catch(c){try{if(!(c instanceof Error))throw new TypeError(`Non-error was thrown: "${c}". You should only throw errors.`);if(c instanceof xb)throw c.originalError;if(c instanceof TypeError&&!wb(c))throw c;if(WP(c,a,e),await e.shouldRetry(c)||(i.stop(),n(c)),await e.onFailedAttempt(c),!i.retry(c))throw i.mainError()}catch(l){WP(l,a,e),s(),n(l)}}})})}var R3=class{log;queue;started;peerStore;retries;retryInterval;backoffFactor;connectionManager;events;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=e.peerStore,this.connectionManager=e.connectionManager,this.queue=new Or({concurrency:t.maxParallelReconnects??5,metricName:"libp2p_reconnect_queue",metrics:e.metrics}),this.started=!1,this.retries=t.retries??5,this.backoffFactor=t.backoffFactor,this.retryInterval=t.retryInterval,this.events=e.events,e.events.addEventListener("peer:disconnect",n=>{this.maybeReconnect(n.detail).catch(i=>{this.log.error("failed to maybe reconnect to %p - %e",n.detail,i)})})}async maybeReconnect(e){if(!this.started)return;let t=await this.peerStore.get(e);XP(t)&&(this.queue.has(e)||this.queue.add(async n=>{await bb(async i=>{if(this.started)try{await this.connectionManager.openConnection(e,{signal:n?.signal})}catch(o){throw this.log("reconnecting to %p attempt %d of %d failed - %e",e,i,this.retries,o),o}},{signal:n?.signal,retries:this.retries,factor:this.backoffFactor,minTimeout:this.retryInterval})},{peerId:e}).catch(async n=>{this.log.error("failed to reconnect to %p - %e",e,n);let i={};[...t.tags.keys()].forEach(o=>{o.startsWith(Na)&&(i[o]=void 0)}),await this.peerStore.merge(e,{tags:i}),this.events.safeDispatchEvent("peer:reconnect-failure",{detail:e})}).catch(async n=>{this.log.error("failed to remove keep-alive tag from %p - %e",e,n)}))}start(){this.started=!0}async afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>XP(t)]});await Promise.all(e.map(async t=>{await this.connectionManager.openConnection(t.id).catch(n=>{this.log.error(n)})}))}).catch(e=>{this.log.error(e)})}stop(){this.started=!1,this.queue.abort()}};function XP(r){for(let e of r.tags.keys())if(e.startsWith(Na))return!0;return!1}var yb=50,vb={maxConnections:FP,inboundConnectionThreshold:5,maxIncomingPendingConnections:10},D3=class{started;connections;allow;deny;maxIncomingPendingConnections;incomingPendingConnections;outboundPendingConnections;maxConnections;dialQueue;reconnectQueue;connectionPruner;inboundConnectionRateLimiter;peerStore;metrics;events;log;peerId;constructor(e,t={}){if(this.maxConnections=t.maxConnections??vb.maxConnections,this.maxConnections<1)throw new K("Connection Manager maxConnections must be greater than 0");this.connections=new nn,this.started=!1,this.peerId=e.peerId,this.peerStore=e.peerStore,this.metrics=e.metrics,this.events=e.events,this.log=e.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(t.allow??[]).map(n=>Om(n)),this.deny=(t.deny??[]).map(n=>Om(n)),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=t.maxIncomingPendingConnections??vb.maxIncomingPendingConnections,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new Id({points:t.inboundConnectionThreshold??vb.inboundConnectionThreshold,duration:1}),this.connectionPruner=new T3({connectionManager:this,peerStore:e.peerStore,events:e.events,logger:e.logger},{allow:t.allow?.map(n=>oe(n))}),this.dialQueue=new P3(e,{addressSorter:t.addressSorter,maxParallelDials:t.maxParallelDials??I3,maxDialQueueLength:t.maxDialQueueLength??500,maxPeerAddrsToDial:t.maxPeerAddrsToDial??25,dialTimeout:t.dialTimeout??1e4,resolvers:t.resolvers??{dnsaddr:Gl},connections:this.connections}),this.reconnectQueue=new R3({events:e.events,peerStore:e.peerStore,logger:e.logger,connectionManager:this},{retries:t.reconnectRetries,retryInterval:t.reconnectRetryInterval,backoffFactor:t.reconnectBackoffFactor,maxParallelReconnects:t.maxParallelReconnects})}[Symbol.toStringTag]="@libp2p/connection-manager";async start(){this.metrics?.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{let e={inbound:0,"inbound pending":this.incomingPendingConnections,outbound:0,"outbound pending":this.outboundPendingConnections};for(let t of this.connections.values())for(let n of t)e[n.direction]++;return e}}),this.metrics?.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{let e={};for(let t of this.connections.values())for(let n of t)for(let i of n.streams){let o=`${i.direction} ${i.protocol??"unnegotiated"}`;e[o]=(e[o]??0)+1}return e}}),this.metrics?.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{let e={};for(let n of this.connections.values())for(let i of n){let o={};for(let s of i.streams){let a=`${s.direction} ${s.protocol??"unnegotiated"}`;o[a]=(o[a]??0)+1}for(let[s,a]of Object.entries(o))e[s]=e[s]??[],e[s].push(a)}let t={};for(let[n,i]of Object.entries(e)){i=i.sort((s,a)=>s-a);let o=Math.floor(i.length*.9);t[n]=i[o]}return t}}),this.events.addEventListener("connection:open",this.onConnect),this.events.addEventListener("connection:close",this.onDisconnect),await Rr(this.dialQueue,this.reconnectQueue,this.connectionPruner),this.started=!0,this.log("started")}async stop(){this.events.removeEventListener("connection:open",this.onConnect),this.events.removeEventListener("connection:close",this.onDisconnect),await Zr(this.reconnectQueue,this.dialQueue,this.connectionPruner);let e=[];for(let t of this.connections.values())for(let n of t)e.push((async()=>{try{await n.close()}catch(i){this.log.error(i)}})());this.log("closing %d connections",e.length),await Promise.all(e),this.connections.clear(),this.log("stopped")}getMaxConnections(){return this.maxConnections}setMaxConnections(e){if(this.maxConnections<1)throw new K("Connection Manager maxConnections must be greater than 0");let t=!1;e<this.maxConnections&&(t=!0),this.maxConnections=e,t&&this.connectionPruner.maybePruneConnections()}onConnect(e){this._onConnect(e).catch(t=>{this.log.error(t)})}async _onConnect(e){let{detail:t}=e;if(!this.started){await t.close();return}if(t.status!=="open")return;let n=t.remotePeer,i=!this.connections.has(n),o=this.connections.get(n)??[];o.push(t),this.connections.set(n,o),n.publicKey!=null&&n.type==="RSA"&&await this.peerStore.patch(n,{publicKey:n.publicKey}),i&&this.events.safeDispatchEvent("peer:connect",{detail:t.remotePeer})}onDisconnect(e){let{detail:t}=e,n=t.remotePeer,o=(this.connections.get(n)??[]).filter(s=>s.id!==t.id);this.connections.set(n,o),o.length===0&&(this.log.trace("peer %p disconnected, removing connection map entry",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:t.remotePeer}))}getConnections(e){if(e!=null)return this.connections.get(e)??[];let t=[];for(let n of this.connections.values())t=t.concat(n);return t}getConnectionsMap(){return this.connections}async openConnection(e,t={}){if(!this.started)throw new Jn("Not started");this.outboundPendingConnections++;try{t.signal?.throwIfAborted();let{peerId:n}=C3(e);if(this.peerId.equals(n))throw new vf("Can not dial self");if(n!=null&&t.force!==!0){this.log("dial %p",n);let a=this.getConnections(n).find(c=>c.limits==null);if(a!=null)return this.log("had an existing non-limited connection to %p as %a",n,a.remoteAddr),t.onProgress?.(new X("dial-queue:already-connected")),a}let i=await this.dialQueue.dial(e,{...t,priority:t.priority??yb});if(i.status!=="open")throw new bf("Remote closed connection during opening");let o=this.connections.get(i.remotePeer);o==null&&(o=[],this.connections.set(i.remotePeer,o));let s=!1;for(let a of o)if(a.id===i.id&&(s=!0),t.force!==!0&&a.id!==i.id&&a.remoteAddr.equals(i.remoteAddr))return i.abort(new Ma("Duplicate multiaddr connection")),a;return s||o.push(i),i}finally{this.outboundPendingConnections--}}async closeConnections(e,t={}){let n=this.connections.get(e)??[];await Promise.all(n.map(async i=>{try{await i.close(t)}catch(o){i.abort(o)}}))}async acceptIncomingConnection(e){if(this.deny.some(i=>i.contains(e.remoteAddr.nodeAddress().address)))return this.log("connection from %a refused - connection remote address was in deny list",e.remoteAddr),!1;if(this.allow.some(i=>i.contains(e.remoteAddr.nodeAddress().address)))return this.incomingPendingConnections++,!0;if(this.incomingPendingConnections===this.maxIncomingPendingConnections)return this.log("connection from %a refused - incomingPendingConnections exceeded by host",e.remoteAddr),!1;if(e.remoteAddr.isThinWaistAddress()){let i=e.remoteAddr.nodeAddress().address;try{await this.inboundConnectionRateLimiter.consume(i,1)}catch{return this.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",e.remoteAddr,i),!1}}return this.getConnections().length<this.maxConnections?(this.incomingPendingConnections++,!0):(this.log("connection from %a refused - maxConnections exceeded",e.remoteAddr),!1)}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){let e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map(t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map(n=>oe(n))}))}async isDialable(e,t={}){return this.dialQueue.isDialable(e,t)}};var kd=class{movingAverage;variance;deviation;forecast;timeSpan;previousTime;constructor(e){this.timeSpan=e,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e,t=Date.now()){if(this.previousTime!=null){let n=this.alpha(t,this.previousTime),i=e-this.movingAverage,o=n*i;this.movingAverage=n*e+(1-n)*this.movingAverage,this.variance=(1-n)*(this.variance+i*o),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+n*i}else this.movingAverage=e;this.previousTime=t}};var zG=1.2,qG=2,jG=5e3,WG=6e4,GG=5e3,Co=class{success;failure;next;metric;timeoutMultiplier;failureMultiplier;minTimeout;maxTimeout;constructor(e={}){let t=e.interval??GG;this.success=new kd(t),this.failure=new kd(t),this.next=new kd(t),this.failureMultiplier=e.failureMultiplier??qG,this.timeoutMultiplier=e.timeoutMultiplier??zG,this.minTimeout=e.minTimeout??jG,this.maxTimeout=e.maxTimeout??WG,e.metricName!=null&&(this.metric=e.metrics?.registerMetricGroup(e.metricName))}getTimeoutSignal(e={}){let t=Math.round(this.next.movingAverage*(e.timeoutFactor??this.timeoutMultiplier));t<this.minTimeout&&(t=this.minTimeout),t>this.maxTimeout&&(t=this.maxTimeout);let n=AbortSignal.timeout(t),i=Pe([e.signal,n]);return i.start=Date.now(),i.timeout=t,i}cleanUp(e){let t=Date.now()-e.start;e.aborted?(this.failure.push(t),this.next.push(t*this.failureMultiplier),this.metric?.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:t})):(this.success.push(t),this.next.push(t),this.metric?.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:t}))}};var O3=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"};function Zl(r,e){let t=Dg();r.sink(t).catch(async s=>{await t.end(s)}),r.sink=async s=>{for await(let a of s)await t.push(a);await t.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 i=new pe;return{read:async s=>{if(s?.signal?.throwIfAborted(),s?.bytes==null){let{done:c,value:l}=await dt(n.next(),s?.signal);return c===!0?null:l}for(;i.byteLength<s.bytes;){let{value:c,done:l}=await dt(n.next(),s?.signal);if(l===!0)throw new O3("unexpected end of input");i.append(c)}let a=i.sublist(0,s.bytes);return i.consume(s.bytes),a},write:async(s,a)=>{a?.signal?.throwIfAborted(),s instanceof Uint8Array?await t.push(s,a):await t.push(s.subarray(),a)},unwrap:()=>{if(i.byteLength>0){let s=r.source;r.source=(async function*(){e?.yieldBytes===!1?yield i:yield*i,yield*s})()}return r}}}var XG=1e4,YG="1.0.0",QG="ping",ZG="ipfs",YP=32,JG=!0,N3=class{protocol;components;log;heartbeatInterval;pingIntervalMs;abortController;timeout;abortConnectionOnPingFailure;constructor(e,t={}){this.components=e,this.protocol=`/${t.protocolPrefix??ZG}/${QG}/${YG}`,this.log=e.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=t.pingInterval??XG,this.abortConnectionOnPingFailure=t.abortConnectionOnPingFailure??JG,this.timeout=new Co({...t.pingTimeout??{},metrics:e.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"})}[Symbol.toStringTag]="@libp2p/connection-monitor";[et]=["@libp2p/connection-monitor"];start(){this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval(()=>{this.components.connectionManager.getConnections().forEach(e=>{Promise.resolve().then(async()=>{let t=Date.now();try{let n=this.timeout.getTimeoutSignal({signal:this.abortController?.signal}),i=await e.newStream(this.protocol,{signal:n,runOnLimitedConnection:!0}),o=Zl(i);t=Date.now(),await Promise.all([o.write(bn(YP),{signal:n}),o.read({bytes:YP,signal:n})]),e.rtt=Date.now()-t,await o.unwrap().close({signal:n})}catch(n){if(n.name!=="UnsupportedProtocolError")throw n;e.rtt=(Date.now()-t)/2}}).catch(t=>{this.log.error("error during heartbeat",t),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),e.abort(t)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")})})},this.pingIntervalMs)}stop(){this.abortController?.abort(),this.heartbeatInterval!=null&&clearInterval(this.heartbeatInterval)}};var B3=class{routers;started;components;constructor(e,t){this.routers=t.routers??[],this.started=!1,this.components=e,this.findProviders=e.metrics?.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,cid:n.toString()}),getAttributesFromYieldedValue:(n,i)=>({...i,providers:[...Array.isArray(i.providers)?i.providers:[],n.id.toString()]})})??this.findProviders,this.provide=e.metrics?.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,cid:n.toString()})})??this.provide,this.cancelReprovide=e.metrics?.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,cid:n.toString()})})??this.cancelReprovide,this.put=e.metrics?.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.put,this.get=e.metrics?.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:([n])=>({key:z(n,"base36")})})??this.get}[Symbol.toStringTag]="@libp2p/content-routing";isStarted(){return this.started}async start(){this.started=!0}async stop(){this.started=!1}async*findProviders(e,t={}){if(this.routers.length===0)throw new Td("No content routers available");let n=this,i=new ai;for await(let o of pn(...n.routers.filter(s=>s.findProviders instanceof Function).map(s=>s.findProviders(e,t))))o!=null&&(o.multiaddrs.length>0&&await this.components.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!i.has(o.id)&&(i.add(o.id),yield o))}async provide(e,t={}){if(this.routers.length===0)throw new Td("No content routers available");await Promise.all(this.routers.filter(n=>n.provide instanceof Function).map(async n=>{await n.provide(e,t)}))}async cancelReprovide(e,t={}){if(this.routers.length===0)throw new Td("No content routers available");await Promise.all(this.routers.filter(n=>n.cancelReprovide instanceof Function).map(async n=>{await n.cancelReprovide(e,t)}))}async put(e,t,n){if(!this.isStarted())throw new Jn;await Promise.all(this.routers.filter(i=>i.put instanceof Function).map(async i=>{await i.put(e,t,n)}))}async get(e,t){if(!this.isStarted())throw new Jn;return Promise.any(this.routers.filter(n=>n.get instanceof Function).map(async n=>n.get(e,t)))}};var L3=globalThis.CustomEvent??Event;async function*Cn(r,e={}){let t=e.concurrency??1/0;t<1&&(t=1/0);let n=e.ordered??!1,i=new EventTarget,o=[],s=ve(),a=ve(),c=!1,l,u=!1;i.addEventListener("task-complete",()=>{a.resolve()}),Promise.resolve().then(async()=>{try{for await(let m of r){if(o.length===t&&(s=ve(),await s.promise),u)break;let g={done:!1};o.push(g),m().then(w=>{g.done=!0,g.ok=!0,g.value=w,i.dispatchEvent(new L3("task-complete"))},w=>{g.done=!0,g.err=w,i.dispatchEvent(new L3("task-complete"))})}c=!0,i.dispatchEvent(new L3("task-complete"))}catch(m){l=m,i.dispatchEvent(new L3("task-complete"))}});function f(){return n?o[0]?.done:!!o.find(m=>m.done)}function*d(){for(;o.length>0&&o[0].done;){let m=o[0];if(o.shift(),m.ok)yield m.value;else throw u=!0,s.resolve(),m.err;s.resolve()}}function*h(){for(;f();)for(let m=0;m<o.length;m++)if(o[m].done){let g=o[m];if(o.splice(m,1),m--,g.ok)yield g.value;else throw u=!0,s.resolve(),g.err;s.resolve()}}for(;;){if(f()||(a=ve(),await a.promise),l!=null||(n?yield*d():yield*h(),l!=null))throw l;if(c&&o.length===0)break}}var M3=class{log;peerId;peerStore;routers;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:peer-routing"),this.peerId=e.peerId,this.peerStore=e.peerStore,this.routers=t.routers??[],this.findPeer=e.metrics?.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,peer:n.toString()})})??this.findPeer,this.getClosestPeers=e.metrics?.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:([n],i)=>({...i,key:z(n,"base36")}),getAttributesFromYieldedValue:(n,i)=>({...i,peers:[...Array.isArray(i.peers)?i.peers:[],n.id.toString()]})})??this.getClosestPeers}[Symbol.toStringTag]="@libp2p/peer-routing";async findPeer(e,t){if(this.routers.length===0)throw new Rm("No peer routers available");if(e.toString()===this.peerId.toString())throw new m3("Should not try to find self");let n=this,i=pn(...this.routers.filter(o=>o.findPeer instanceof Function).map(o=>(async function*(){try{yield await o.findPeer(e,t)}catch(s){n.log.error(s)}})()));for await(let o of i)if(o!=null)return o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),o;throw new qe}async*getClosestPeers(e,t={}){if(this.routers.length===0)throw new Rm("No peer routers available");let n=this,i=on(1024);for await(let o of Cn((async function*(){let s=pn(...n.routers.filter(a=>a.getClosestPeers instanceof Function).map(a=>a.getClosestPeers(e,t)));for await(let a of s)yield async()=>{if(a.multiaddrs.length===0)try{a=await n.findPeer(a.id,{...t,useCache:!1})}catch(c){n.log.error("could not find peer multiaddrs",c);return}return a}})()))o!=null&&(o.multiaddrs.length>0&&await this.peerStore.merge(o.id,{multiaddrs:o.multiaddrs},t),!i.has(o.id.toMultihash().bytes)&&(i.add(o.id.toMultihash().bytes),yield o))}};var U3=class extends De{peerRouting;log;walking;walkers;shutdownController;walkController;needNext;constructor(e){super(),this.log=e.logger.forComponent("libp2p:random-walk"),this.peerRouting=e.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}[Symbol.toStringTag]="@libp2p/random-walk";start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}async*walk(e){this.walking||this.startWalk(),this.walkers++;let t=Pe([this.shutdownController.signal,e?.signal]);try{for(;;)this.needNext?.resolve(),this.needNext=ve(),yield(await Kt(this,"walk:peer",t,{errorEvent:"walk:error"})).detail}finally{t.clear(),this.walkers--,this.walkers===0&&(this.walkController?.abort(),this.walkController=void 0)}}startWalk(){this.walking=!0,this.walkController=new AbortController,this.walkController.signal;let e=Pe([this.walkController.signal,this.shutdownController.signal]);let t=Date.now(),n=0;Promise.resolve().then(async()=>{for(this.log("start walk");this.walkers>0;)try{let i=bn(32),o=Date.now();for await(let s of this.peerRouting.getClosestPeers(i,{signal:e}))e.aborted&&this.log("aborting walk"),e.throwIfAborted(),this.log("found peer %p after %dms for %d walkers",s.id,Date.now()-o,this.walkers),n++,this.safeDispatchEvent("walk:peer",{detail:s}),this.walkers===1&&this.needNext!=null&&(this.log("wait for need next"),await dt(this.needNext.promise,e)),o=Date.now();this.log("walk iteration for %b and %d walkers finished, found %d peers",i,this.walkers,n)}catch(i){this.log.error("random walk errored",i),this.safeDispatchEvent("walk:error",{detail:i})}this.log("no walkers left, ended walk")}).catch(i=>{this.log.error("random walk errored",i)}).finally(()=>{this.log("finished walk, found %d peers after %dms",n,Date.now()-t),this.walking=!1})}};var Ab=32,Eb=64,F3=class{log;topologies;handlers;components;constructor(e){this.components=e,this.log=e.logger.forComponent("libp2p:registrar"),this.topologies=new Map,e.metrics?.registerMetricGroup("libp2p_registrar_topologies",{calculate:()=>{let t={};for(let[n,i]of this.topologies)t[n]=i.size;return t}}),this.handlers=hr({name:"libp2p_registrar_protocol_handlers",metrics:e.metrics}),this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}[Symbol.toStringTag]="@libp2p/registrar";getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){let t=this.handlers.get(e);if(t==null)throw new g3(`No handler registered for protocol ${e}`);return t}getTopologies(e){let t=this.topologies.get(e);return t==null?[]:[...t.values()]}async handle(e,t,n){if(this.handlers.has(e)&&n?.force!==!0)throw new y3(`Handler already registered for protocol ${e}`);let i=Gt.bind({ignoreUndefined:!0})({maxInboundStreams:Ab,maxOutboundStreams:Eb},n);this.handlers.set(e,{handler:t,options:i}),await this.components.peerStore.merge(this.components.peerId,{protocols:[e]},n)}async unhandle(e,t){(Array.isArray(e)?e:[e]).forEach(i=>{this.handlers.delete(i)}),await this.components.peerStore.patch(this.components.peerId,{protocols:this.getProtocols()},t)}async register(e,t){if(t==null)throw new K("invalid topology");let n=`${(Math.random()*1e9).toString(36)}${Date.now()}`,i=this.topologies.get(e);return i==null&&(i=new Map,this.topologies.set(e,i)),i.set(n,t),n}unregister(e){for(let[t,n]of this.topologies.entries())n.has(e)&&(n.delete(e),n.size===0&&this.topologies.delete(t))}_onDisconnect(e){let t=e.detail,n={signal:AbortSignal.timeout(5e3)};this.components.peerStore.get(t,n).then(i=>{for(let o of i.protocols){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.filter?.has(t)!==!1&&(a.filter?.remove(t),a.onDisconnect?.(t))}}).catch(i=>{i.name!=="NotFoundError"&&this.log.error("could not inform topologies of disconnecting peer %p",t,i)})}_onPeerUpdate(e){let{peer:t,previous:n}=e.detail,i=(n?.protocols??[]).filter(o=>!t.protocols.includes(o));for(let o of i){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())a.filter?.has(t.id)!==!1&&(a.filter?.remove(t.id),a.onDisconnect?.(t.id))}}_onPeerIdentify(e){let t=e.detail.protocols,n=e.detail.connection,i=e.detail.peerId;for(let o of t){let s=this.topologies.get(o);if(s!=null)for(let a of s.values())n.limits!=null&&a.notifyOnLimitedConnection!==!0||a.filter?.has(i)!==!0&&(a.filter?.add(i),a.onConnect?.(i,n))}}};var $3=class{log;components;transports;listeners;faultTolerance;started;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:transports"),this.components=e,this.started=!1,this.transports=hr({name:"libp2p_transport_manager_transports",metrics:this.components.metrics}),this.listeners=hr({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=t.faultTolerance??rl.FATAL_ALL}[Symbol.toStringTag]="@libp2p/transport-manager";add(e){let t=e[Symbol.toStringTag];if(t==null)throw new K("Transport must have a valid tag");if(this.transports.has(t))throw new K(`There is already a transport with the tag ${t}`);this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}async afterStart(){let e=this.components.addressManager.getListenAddrs();await this.listen(e)}async stop(){let e=[];for(let[t,n]of this.listeners)for(this.log("closing listeners for %s",t);n.length>0;){let i=n.pop();i!=null&&e.push(i.close())}await Promise.all(e),this.log("all listeners closed");for(let t of this.listeners.keys())this.listeners.set(t,[]);this.started=!1}async dial(e,t){let n=this.dialTransportForMultiaddr(e);if(n==null)throw new E3(`No transport available for address ${String(e)}`);return t?.onProgress?.(new X("transport-manager:selected-transport",n[Symbol.toStringTag])),n.dial(e,{...t,upgrader:this.components.upgrader})}getAddrs(){let e=[];for(let t of this.listeners.values())for(let n of t)e=[...e,...n.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(let t of this.transports.values())if(t.dialFilter([e]).length>0)return t}listenTransportForMultiaddr(e){for(let t of this.transports.values())if(t.listenFilter([e]).length>0)return t}async listen(e){if(!this.isStarted())throw new Jn("Not started");if(e==null||e.length===0){this.log("no addresses were provided for listening, this node is dial only");return}let t={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};e.forEach(o=>{t.errors.set(o.toString(),new w3)});let n=[];for(let[o,s]of this.transports.entries()){let a=s.listenFilter(e);for(let c of a){this.log("creating listener for %s on %a",o,c);let l=s.createListener({upgrader:this.components.upgrader}),u=this.listeners.get(o)??[];u==null&&(u=[],this.listeners.set(o,u)),u.push(l),l.addEventListener("listening",()=>{this.components.events.safeDispatchEvent("transport:listening",{detail:l})}),l.addEventListener("close",()=>{let f=u.findIndex(d=>d===l);u.splice(f,1),this.components.events.safeDispatchEvent("transport:close",{detail:l})}),B9.matches(c)?t.ipv4.attempts++:L9.matches(c)&&t.ipv6.attempts++,n.push(l.listen(c).then(()=>{t.errors.delete(c.toString()),B9.matches(c)&&t.ipv4.success++,L9.matches(c)&&t.ipv6.success++},f=>{throw this.log.error("transport %s could not listen on address %a - %e",o,c,f),t.errors.set(c.toString(),f),f}))}}let i=await Promise.allSettled(n);if(!(i.length>0&&i.every(o=>o.status==="fulfilled"))){if(this.ipv6Unsupported(t)){this.log("all IPv4 addresses succeed but all IPv6 failed");return}if(this.faultTolerance===rl.NO_FATAL){this.log("failed to listen on any address but fault tolerance allows this");return}throw new x3(`Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set \`transportManager.faultTolerance\` to NO_FATAL:
|
|
15
15
|
${[...t.errors.entries()].map(([o,s])=>`
|
|
16
16
|
${o}: ${`${s.stack??s}`.split(`
|
|
17
17
|
`).join(`
|
|
@@ -79,7 +79,7 @@ a=end-of-candidates
|
|
|
79
79
|
`;return r.sdp=r.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,`
|
|
80
80
|
a=ice-ufrag:`+e+t).replace(/\na=ice-pwd:[^\n]*\n/,`
|
|
81
81
|
a=ice-pwd:`+e+t),r}var OE=D("libp2p-webrtc-noise:");function bM(r,e,t){let n=r.trim().toLowerCase().replaceAll(":",""),i=D(n,"hex"),o=gn(Be.code,i),s=PE.decode(RE(e)),a=OE.byteLength+o.bytes.byteLength+s.byteLength;return t==="server"?Xe([OE,s,o.bytes],a):Xe([OE,o.bytes,s],a)}var gJ=m1?"iceconnectionstatechange":"connectionstatechange";async function vM(r,e,t){let n=r.createDataChannel("",{negotiated:!0,id:0});try{if(t.role==="client"){t.log.trace("client creating local offer");let f=await r.createOffer();t.log.trace("client created local offer %s",f.sdp);let d=DE(f,e);t.log.trace("client setting local offer %s",d.sdp),await r.setLocalDescription(d);let h=yM(t.remoteAddr,e);t.log.trace("client setting server description %s",h.sdp),await r.setRemoteDescription(h)}else{let f=wM(t.remoteAddr,e);t.log.trace("server setting client %s %s",f.type,f.sdp),await r.setRemoteDescription(f),t.log.trace("server creating local answer");let d=await r.createAnswer();t.log.trace("server created local answer");let h=DE(d,e);t.log.trace("server setting local description %s",d.sdp),await r.setLocalDescription(h)}if(n.readyState!=="open"&&(t.log.trace("%s wait for handshake channel to open, starting status %s",t.role,n.readyState),await Kt(n,"open",t.signal)),t.log.trace("%s handshake channel opened",t.role),t.role==="server"){let f=r.remoteFingerprint()?.value??"";t.remoteAddr=t.remoteAddr.encapsulate(gM(f))}let i=mM(r.localDescription?.sdp);if(i==null)throw new Ac("Could not get fingerprint from local description sdp");t.log.trace("%s performing noise handshake",t.role);let o=bM(i,t.remoteAddr,t.role),s=C4({prologueBytes:o})(t),a=th({channel:n,direction:"outbound",handshake:!0,log:t.log,...t.dataChannel??{}}),c=new _u(t,{peerConnection:r,remoteAddr:t.remoteAddr,timeline:{open:Date.now()},metrics:t.events});r.addEventListener(gJ,()=>{switch(r.connectionState){case"failed":case"disconnected":case"closed":c.close().catch(f=>{t.log.error("error closing connection",f),c.abort(f)});break;default:break}}),t.events?.increment({peer_connection:!0});let l=new vc(t,{peerConnection:r,metrics:t.events,dataChannelOptions:t.dataChannel});if(t.role==="client")return t.log.trace("%s secure inbound",t.role),await s.secureInbound(a,{remotePeer:t.remotePeerId,signal:t.signal,skipStreamMuxerNegotiation:!0}),t.log.trace("%s upgrade outbound",t.role),await t.upgrader.upgradeOutbound(c,{skipProtection:!0,skipEncryption:!0,muxerFactory:l,signal:t.signal});t.log.trace("%s secure outbound",t.role);let u=await s.secureOutbound(a,{remotePeer:t.remotePeerId,signal:t.signal,skipStreamMuxerNegotiation:!0});c.remoteAddr=c.remoteAddr.encapsulate(`/p2p/${u.remotePeer}`),t.log.trace("%s upgrade inbound",t.role),await t.upgrader.upgradeInbound(c,{skipProtection:!0,skipEncryption:!0,muxerFactory:l,signal:t.signal})}catch(i){throw n.close(),i}}async function AM(r,e,t,n){n==null&&(n=await RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));let i=typeof t=="function"?await t():t;return new RTCPeerConnection({...i??{},certificates:[n]})}async function EM(r){let e=await u2(r),t=await crypto.subtle.exportKey("pkcs8",e.privateKey);return["-----BEGIN PRIVATE KEY-----",...z(new Uint8Array(t),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join(`
|
|
82
|
-
`)}var n8=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new De,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new K("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Ba]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[et]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,i=e.getPeerId();i!=null&&(n=gt(i));let o=ON(),s=await AM("client",o,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await vM(s,o,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey})}catch(a){throw s.close(),a}}createListener(e){if(this.certificate==null)throw new Jn;return new r8(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(wm.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(yJ(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:i}=await this.loadOrCreateCertificate(t,e);return{privateKey:await EM(t),pem:n,certhash:i}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??SN,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new qe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await Jf("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,i=new it(this.init.certificateDatastoreKey??EN),o=await u2(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new qe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(i,o)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(i,o)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??Uv)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:cl.encode((await Be.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),i=new Fh(n),o=i.notAfter.getTime()-(this.init.certificateRenewalThreshold??Uv);if(Date.now()>o)throw this.log("stored TLS certificate has expired"),new qe;this.log("loaded certificate, expires in %d ms",o);let s=await i.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!he(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new qe;return this.log("loaded certificate, expiry time is %o",o),i}async createCertificate(e,t){let n=new Date,i=new Date(Date.now()+(this.init.certificateLifespan??_N));n.setMilliseconds(0),i.setMilliseconds(0);let o=await t8.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:i,keys:t,extensions:[new Lh(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,D(o.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),o}getKeychain(){try{return this.components.keychain}catch{}}};function yJ(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function i8(r){return e=>new n8(e,r)}function SM(r){return e=>new Q6(e,r)}var _M=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",o)}function i(){n(),e()}function o(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",o)})};var CM=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await _M(r)}catch(o){if(o.message==="socket closed")break;throw o}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,o)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:s});o(a)}}),setTimeout(()=>{r.close()})})});var PM=mt(IM(),1);function kM(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var RM=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((o,s)=>{if(n){o();return}if(i!=null){s(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(o)},l=u=>{a(()=>{s(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=(async function*(){let o=new PM.EventIterator(({push:s,stop:a,fail:c})=>{let l=f=>{let d=null;typeof f.data=="string"&&(d=D(f.data)),kM(f.data)&&(d=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(d=f.data),d!=null&&s(d)},u=f=>{c(f.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of o)yield kM(s)?new Uint8Array(s):s})(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",o=>{n||(i=o.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var DM=(r,e)=>{e=e??{};let t=RM(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,i=parseInt(s.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:CM(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var OM=WebSocket;var xJ={"http:":"ws:","https:":"wss:"},NM="ws:",BM=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??NM}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??NM,i=e.host,o=e.port!=null&&i?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${i}${o}${r}`}let t=new URL(r);for(let[n,i]of Object.entries(xJ))t.protocol===n&&(t.protocol=i);return t};function LM(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=BM(r,t),i=new OM(n.toString(),e.websocket);return DM(i,e)}function MM(r){return r.filter(e=>ql.exactMatch(e)||na.exactMatch(e))}function UM(){throw new Error("WebSocket Servers can not be created in the browser!")}function FM(r,e,t){let n=t.metrics,i=t.metricPrefix??"",o={log:t.logger.forComponent("libp2p:websockets:connection"),async sink(c){try{await r.sink((async function*(){for await(let l of c)l instanceof Uint8Array?yield l:yield l.subarray()})())}catch(l){l.type!=="aborted"&&o.log.error(l)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(c={}){let l=Date.now();if(c.signal==null){let f=AbortSignal.timeout(500);c={...c,signal:f}}let u=()=>{let{host:f,port:d}=o.remoteAddr.toOptions();o.log("timeout closing stream to %s:%s after %dms, destroying it manually",f,d,Date.now()-l),this.abort(new Je("Socket close timeout"))};c.signal?.addEventListener("abort",u);try{await r.close()}catch(f){o.log.error("error closing WebSocket gracefully - %e",f),this.abort(f)}finally{c.signal?.removeEventListener("abort",u),o.timeline.close=Date.now()}},abort(c){o.log.error("destroying WebSocket after error - %e",c),r.destroy(),o.timeline.close=Date.now(),n?.increment({[`${i}error`]:!0})}},s=!1,a=r.socket.close.bind(r.socket);return r.socket.close=(...c)=>(s=!0,a(...c)),r.socket.addEventListener("close",c=>{if(o.log('closed %s, code %d, reason "%s", wasClean %s',s?"locally":"by remote",c.code,c.reason,c.wasClean),!c.wasClean){o.abort(new La(`${s?"Local":"Remote"} did not close WebSocket cleanly`));return}n?.increment({[`${i}close`]:!0}),o.timeline.close=Date.now()},{once:!0}),o}var LE=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ba]=!0;[Symbol.toStringTag]="@libp2p/websockets";[et]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=FM(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i,t);return this.log("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let i=ve(),o=LM(wd(e),this.init);o.socket.addEventListener("error",()=>{let s=new La(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),i.reject(s)});try{t.onProgress?.(new X("websockets:open-connection")),await dt(Promise.race([o.connected(),i.promise]),t.signal)}catch(s){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),o.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return UM({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):MM(e)}dialFilter(e){return this.listenFilter(e)}};function a8(r={}){return e=>new LE(e,r)}var ME=mt(Uy(),1);function c8(r,e){let t=e.map((n,i)=>({record:Bn(n),index:i}));return t.sort((n,i)=>{let o=n.record.sequence,s=i.record.sequence;if(o>s)return-1;if(o<s)return 1;if(n.record.validityType===Fr.ValidityType.EOL&&i.record.validityType===Fr.ValidityType.EOL){let a=ME.default.fromString(n.record.validity).toDate(),c=ME.default.fromString(i.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var $M="5.5.1",HM="helia";var VM={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function B0(r={}){let e=`${HM}/${$M} ${W3()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[yv(),SM(),i8(),a8()],connectionEncrypters:[C4()],streamMuxers:[FD(),lN()],peerDiscovery:[tO(VM)],services:{autoNAT:zD(),dcutr:mO(),delegatedRouting:()=>Qy("https://delegated-ipfs.dev",K9()),dht:rN({clientMode:!0,validators:{ipns:ic},selectors:{ipns:c8}}),identify:vO(),identifyPush:AO(),keychain:y4(r.keychain),ping:hN()}}}async function KM(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await Mb(r.datastore,r.keychain));let t=B0(e);return t.datastore=t.datastore??r.datastore,await G3({...t,...e,start:!1})}async function zM(r={}){let e=r.datastore??new Wl,t=r.blockstore??new Tm,n;return nR(r.libp2p)?n=r.libp2p:n=await KM({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[bm(),um()],routers:r.routers??[Cm(n),_m()],metrics:n.metrics}}async function qM(r={}){let e=await zM(r),t=new py(e);return e.start!==!1&&await t.start(),t}function jM(){let r=B0();r.start=!1,r.addresses={listen:[]},r.transports=[i8(),a8()],r.peerDiscovery=[];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var l8=class extends Error{static name="DNSLinkNotFoundError";constructor(e="DNSLink not found"){super(e),this.name="DNSLinkNotFoundError"}},u8=class extends Error{static name="RecordsFailedValidationError";constructor(e="Records failed validation"){super(e),this.name="RecordsFailedValidationError"}},f8=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(e="Unsupported multibase prefix"){super(e),this.name="UnsupportedMultibasePrefixError"}},d8=class extends Error{static name="UnsupportedMultihashCodecError";constructor(e="Unsupported multihash codec"){super(e),this.name="UnsupportedMultihashCodecError"}},h8=class extends Error{static name="InvalidValueError";constructor(e="Invalid value"){super(e),this.name="InvalidValueError"}};var vJ=32;async function WM(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=((await t.query(r,{...i,types:[an.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,d,...h]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${G.parse(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{let m;return d.charAt(0)==="1"||d.charAt(0)==="Q"?m=gt(d):m=vn(G.parse(d)),{value:`/ipns/${m}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await p8(d,e-1,t,n,i)}else{if(f==="dnslink")return await p8(d,e-1,t,n,i);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=((await t.query(r,{...i,types:[an.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await p8(l.data,e-1,t,n,i)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new l8(`No DNSLink records found for domain: ${r}`)}async function p8(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await WM(r,e,t,n,i)}catch(o){if(o.code!=="ENOTFOUND"&&o.code!=="ENODATA"&&o.name!=="DNSLinkNotFoundError"&&o.name!=="NotFoundError")throw o;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,WM(r,e,t,n,i)}}async function GM(r,e,t,n={}){return p8(r,n.maxRecursiveDepth??vJ,e,t,n)}var UE=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(i){throw n.onProgress?.(new X("ipns:routing:helia:error",i)),i}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){throw t.onProgress?.(new X("ipns:routing:helia:error",n)),n}}};function XM(r){return new UE(r)}function m8(r){return new it("/dht/record/"+z(r,"base32"),!1)}function YM(r){return{async put(e,t,n={}){try{let i=m8(e);try{let s=await r.get(i),a=Mt.deserialize(s);if(he(a.value,t))return}catch(s){if(s.name!=="NotFoundError")throw s}let o=new Mt(e,t,new Date);n.onProgress?.(new X("ipns:routing:datastore:put")),await r.put(i,o.serialize(),n)}catch(i){throw n.onProgress?.(new X("ipns:routing:datastore:error",i)),i}},async get(e,t={}){try{let n=m8(e);t.onProgress?.(new X("ipns:routing:datastore:get"));let i=await r.get(n,t),o=Mt.deserialize(i);return{record:o.value,created:o.timeReceived}}catch(n){throw t.onProgress?.(new X("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=m8(e);return r.has(n,t)},async delete(e,t){let n=m8(e);return r.delete(n,t)}}}var FE="/ipns/";function $E(r,e){return r.code===e}var Ia=Ue("helia:ipns"),JM=60*1e3,eU=60*JM,SJ=48*eU,HE=23*eU,QM=BigInt(JM)*5000000n,ZM={[mn.prefix]:mn,[Ye.prefix]:Ye},VE=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[XM(e.routing),...t],this.localStore=YM(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let i=1n,o=ia(e.publicKey.toMultihash());if(await this.localStore.has(o,n)){let{record:l}=await this.localStore.get(o,n);i=Bn(l).sequence+1n}let s=n.ttl!=null?BigInt(n.ttl)*1000000n:QM,a=await Xk(e,t,i,n.lifetime??SJ,{...n,ttlNs:s}),c=nc(a);return await this.localStore.put(o,c,n),n.offline!==!0&&await Promise.all(this.routers.map(async l=>{await l.put(o,c,n)})),a}catch(i){throw n.onProgress?.(new X("ipns:publish:error",i)),i}}async resolve(e,t={}){let n=BS(e)?e.toMultihash():e,i=ia(n),o=await this.#t(i,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await GM(e,this.dns,this.log,t);return{...await this.#e(n.value,t),answer:n.answer}}republish(e={}){if(this.timeout!=null)throw new Error("Republish is already running");e.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function t(){let n=Date.now();e.onProgress?.(new X("ipns:republish:start"));let o=Date.now()-n,s=HE-o;s<0&&(s=e.interval??HE),setTimeout(()=>{t().catch(a=>{Ia.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Ia.error("error republishing",n)})},e.interval??HE)}async#e(e,t={}){let n=e.split("/");try{let i=n[1];if(i==="ipns"){let o=n[2],s=o.substring(0,1),a;if(s==="1"||s==="Q")a=Ye.decode(`z${o}`);else if(ZM[s]!=null)a=ZM[s].decode(o);else throw new f8(`Unsupported multibase prefix "${s}"`);let c;try{c=We(a)}catch{c=G.decode(a).multihash}if(!$E(c,0)&&!$E(c,18))throw new d8(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,t),u=n.slice(3).join("/");return{cid:l,path:u}}else if(i==="ipfs"){let o=G.parse(n[2]),s=n.slice(3).join("/");return{cid:o,path:s}}}catch(i){Ia.error("error parsing ipfs path",i)}throw Ia.error("invalid ipfs path %s",e),new h8("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Ia("record is present in the cache"),t.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await ic(e,a),this.log("record was valid");let l=Bn(a),u=Number((l.ttl??QM)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(e,t)}else Ia("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new qe("Record was not present in the cache or has expired");Ia("did not have record locally");let o=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(e,{...t,validate:!1})}catch(l){Ia.error("error finding IPNS record",l);return}try{await ic(e,c),n.push(c)}catch(l){o++,Ia.error("error finding IPNS record",l)}})),n.length===0)throw o>0?new u8(`${o>1?`${o} records`:"Record"} found for routing key ${o>1?"were":"was"} invalid`):new qe("Could not find record for routing key");let s=n[c8(e,n)];return await this.localStore.put(e,s,t),Bn(s)}async republishRecord(e,t,n={}){let i;try{if(i=Em(t)?.toMultihash(),i==null)if(typeof e=="string"){e.startsWith(FE)&&(e=e.slice(FE.length));try{i=gt(e).toMultihash()}catch(a){throw new Error(`Invalid string key: ${a.message}`)}}else i=e;if(i==null)throw new Error("No public key multihash found to determine the routing key");let o=ia(i),s=nc(t);await ic(o,s),await this.localStore.put(o,s,n),n.offline!==!0&&await Promise.all(this.routers.map(async a=>{await a.put(o,s,n)}))}catch(o){throw n.onProgress?.(new X("ipns:republish:error",{key:i,record:t,err:o})),o}}};function tU(r,{routers:e=[]}={}){return new VE(r,e)}var sf=class extends Map{#e=0;#t=new Map;#r=new Map;#o;#c;#l;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#o=e.maxSize,this.#c=e.maxAge||Number.POSITIVE_INFINITY,this.#l=e.onEviction}get __oldCache(){return this.#r}#s(e){if(typeof this.#l=="function")for(let[t,n]of e)this.#l(t,n.value)}#n(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#l=="function"&&this.#l(e,t.value),this.delete(e)):!1}#i(e,t){if(this.#n(e,t)===!1)return t.value}#d(e,t){return t.expiry?this.#i(e,t):t.value}#a(e,t){let n=t.get(e);return this.#d(e,n)}#f(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#o&&(this.#e=0,this.#s(this.#r),this.#r=this.#t,this.#t=new Map)}#u(e,t){this.#r.delete(e),this.#f(e,t)}*#h(){for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#n(t,n)===!1&&(yield e)}for(let e of this.#t){let[t,n]=e;this.#n(t,n)===!1&&(yield e)}}get(e){if(this.#t.has(e)){let t=this.#t.get(e);return this.#d(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#n(e,t)===!1)return this.#u(e,t),t.value}}set(e,t,{maxAge:n=this.#c}={}){let i=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#t.has(e)?this.#t.set(e,{value:t,expiry:i}):this.#f(e,{value:t,expiry:i}),this}has(e){return this.#t.has(e)?!this.#n(e,this.#t.get(e)):this.#r.has(e)?!this.#n(e,this.#r.get(e)):!1}peek(e){if(this.#t.has(e))return this.#a(e,this.#t);if(this.#r.has(e))return this.#a(e,this.#r)}expiresIn(e){let t=this.#t.get(e)??this.#r.get(e);if(t)return t.expiry?t.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#r.delete(e)||t}clear(){this.#t.clear(),this.#r.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#h()],n=t.length-e;n<0?(this.#t=new Map(t),this.#r=new Map,this.#e=t.length):(n>0&&this.#s(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#o=e}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#t){let[t,n]=e;this.#n(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#n(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#n(i,o)===!1&&(yield[i,o.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#t.has(i)||this.#n(i,o)===!1&&(yield[i,o.value])}}*entriesAscending(){for(let[e,t]of this.#h())yield[e,t.value]}get size(){if(!this.#e)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#o)}get maxSize(){return this.#o}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,i]of this.entriesAscending())e.call(t,i,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};function af(r,e={}){let t=Kd(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(i){try{let{value:o,done:s}=await t.next();if(this._cancelled)return;if(s===!0){i.close();return}i.enqueue(o)}catch(o){i.error(o)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Pr=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},g8=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},y8=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function rU(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([i])=>i.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function nU(r,e,t){if((r??0)>(e??1/0))throw new Pr("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new Pr("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new Pr("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Pr("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function iU({ttl:r,protocol:e,response:t}){if(t.headers.has("cache-control"))return;let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function w8({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new Pr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new Pr("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let i=t-1;return`bytes ${i-e+1}-${i}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function x8(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",L0(e))}function L0(r){return r.map(e=>e.toV1().toString()).join(",")}function _J(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function CJ(r){if(!r.startsWith("bytes="))throw new Pr("Invalid range request");let t=r.substring(6).split(",").map(i=>i.trim()),n=[];for(let i of t){let o=i.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(o?.groups==null)throw new Pr(`Invalid range specification: ${i}`);let{start:s,end:a}=o.groups;n.push({start:s??null,end:a??null})}if(n.length===0)throw new Pr("No valid ranges found");return{ranges:n}}var b8=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;multiPartBoundary;requestRanges=[];byteRanges=[];isMultiRangeRequest=!1;_isValidRangeRequest=!1;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=rU(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{ranges:n}=CJ(this.rangeRequestHeader);this.isMultiRangeRequest=n.length>1,this.requestRanges=n.map(i=>({start:i.start!=null?parseInt(i.start):null,end:i.end!=null?parseInt(i.end):null})),this.multiPartBoundary=`multipart_byteranges_${Math.floor(Math.random()*1e9)}`}catch(n){this.log.error("error parsing range request header - %e",n),this.requestRanges=[]}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1}getByteRanges(){return this.byteRanges}setBody(e,t="application/octet-stream"){typeof e=="function"?this._body=this.createRangeStream(e,t):(this._body=e,this.setFileSize(this._fileSize??_J(e))),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(e){let t=this._body;if(t==null)return this.log.trace("body is null"),t;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),t;if(this.isMultiRangeRequest)return this._body instanceof ReadableStream?this._body:af(this.getMultipartBody(e));if(this.byteRanges.length>0){let n=this.byteRanges[0];return t instanceof ReadableStream?t:((n.start!=null||n.end!=null)&&this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",n.start,n.end,n.size),this.getSlicedBody(t,n))}return this.log.error("returning unmodified body for valid range request"),t}getSlicedBody(e,t){let n=t.start??0,i;return t.end!=null&&t.start!=null?i=t.end-t.start+1:i=void 0,this.log.trace("slicing body with offset=%o and length=%o",n,i),typeof e=="string"||e instanceof Blob||e instanceof ArrayBuffer||e instanceof Uint8Array?e.slice(n,i!==void 0?n+i:void 0):e}setFileSize(e){this._fileSize=e!=null?Number(e):null,this._isValidRangeRequest=!1,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(e,t){return!(e!=null&&(e<0||this._fileSize!=null&&e>=this._fileSize||t!=null&&e>t))}isValidByteEnd(e,t){if(t!=null){if(t<0)return this.log.trace("invalid range request, byteEnd is less than 0"),!1;if(this._fileSize!=null&&t>=this._fileSize)return this.log.trace("invalid range request, byteEnd is greater than fileSize"),!1;if(e!=null&&t<e)return this.log.trace("invalid range request, byteEnd is less than byteStart"),!1}return!0}isValidByteRange(e){return this.log.trace("validating byte range: %o",e),e.start!=null&&!this.isValidByteStart(e.start,e.end)?(this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1):e.end!=null&&!this.isValidByteEnd(e.start,e.end)?(this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1):!0}get isValidRangeRequest(){return this._isValidRangeRequest?!0:this.isRangeRequest?this.byteRanges.length===0?(this.log.trace("invalid range request, no valid ranges"),!1):this.byteRanges.every(t=>this.isValidByteRange(t))?(this._isValidRangeRequest=!0,!0):(this.log.trace("invalid range request, not all ranges are valid"),!1):!1}getLength(e){if(!this.isValidRangeRequest){this.log.error("cannot get length for invalid range request");return}if(!(this.isMultiRangeRequest&&e==null))return e??=this.byteRanges[0],this.log.trace("getting length for range: %o",e),e.end!=null&&e.start!=null?e.end-e.start+1:e.end!=null?e.end+1:e.size}setOffsetDetails(){if(this.requestRanges.length===0){this.log.trace("no request ranges defined");return}try{this.byteRanges=this.requestRanges.map(e=>{let{start:t,end:n,byteSize:i}=nU(e.start??void 0,e.end??void 0,this._fileSize??void 0);return{start:t,end:n,size:i}}),this.log.trace("set byte ranges: %o",this.byteRanges)}catch(e){this.log.error("error setting offset details: %o",e),this.byteRanges=[]}}async convertToUint8Array(e){if(typeof e=="string")return new TextEncoder().encode(e);if("arrayBuffer"in e&&typeof e.arrayBuffer=="function"){let t=await e.arrayBuffer();return new Uint8Array(t)}if("byteLength"in e&&!("buffer"in e))return new Uint8Array(e);if("buffer"in e&&"byteLength"in e&&"byteOffset"in e)return e;throw new Error("Unsupported content type for multipart response")}async*getMultipartBody(e="application/octet-stream"){let t=this._body;if(t instanceof ReadableStream)return t;if(t===null)throw new Error("Cannot create multipart body from null");let n=new TextEncoder;for(let i of this.byteRanges){if(i.start===void 0||i.end===void 0)continue;let o=`\r
|
|
82
|
+
`)}var n8=class{log;metrics;components;init;certificate;privateKey;emitter;renewCertificateTask;constructor(e,t={}){if(this.log=e.logger.forComponent("libp2p:webrtc-direct"),this.components=e,this.init=t,this.emitter=new De,t.certificateLifespan!=null&&t.certificateRenewalThreshold!=null&&t.certificateRenewalThreshold>=t.certificateLifespan)throw new K("Certificate renewal threshold must be less than certificate lifespan");e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}[Ba]=!0;[Symbol.toStringTag]="@libp2p/webrtc-direct";[et]=["@libp2p/transport"];async start(){this.certificate=await this.getCertificate()}async stop(){this.renewCertificateTask!=null&&clearTimeout(this.renewCertificateTask),this.certificate=void 0}async dial(e,t){this.log("dial %a",e),t.signal.throwIfAborted();let n,i=e.getPeerId();i!=null&&(n=gt(i));let o=ON(),s=await AM("client",o,typeof this.init.rtcConfiguration=="function"?await this.init.rtcConfiguration():this.init.rtcConfiguration??{});try{return await vM(s,o,{role:"client",log:this.log,logger:this.components.logger,metrics:this.components.metrics,events:this.metrics?.dialerEvents,signal:t.signal,remoteAddr:e,dataChannel:this.init.dataChannel,upgrader:t.upgrader,peerId:this.components.peerId,remotePeerId:n,privateKey:this.components.privateKey})}catch(a){throw s.close(),a}}createListener(e){if(this.certificate==null)throw new Jn;return new r8(this.components,{...this.init,...e,certificate:this.certificate,emitter:this.emitter})}listenFilter(e){return e.filter(wm.exactMatch)}dialFilter(e){return this.listenFilter(e)}async getCertificate(e){if(yJ(this.init.certificate))return this.log("using provided TLS certificate"),this.init.certificate;let t=await this.loadOrCreatePrivateKey(),{pem:n,certhash:i}=await this.loadOrCreateCertificate(t,e);return{privateKey:await EM(t),pem:n,certhash:i}}async loadOrCreatePrivateKey(){if(this.privateKey!=null)return this.privateKey;let e=this.init.certificateKeychainName??SN,t=this.getKeychain();try{if(t==null)throw this.log("no keychain configured - not checking for stored private key"),new qe;this.log.trace("checking for stored private key"),this.privateKey=await t.exportKey(e)}catch(n){if(n.name!=="NotFoundError")throw n;this.log.trace("generating private key"),this.privateKey=await Jf("ECDSA","P-256"),t!=null?(this.log.trace("storing private key"),await t.importKey(e,this.privateKey)):this.log("no keychain configured - not storing private key")}return this.privateKey}async loadOrCreateCertificate(e,t){if(this.certificate!=null&&t!==!0)return this.certificate;let n,i=new it(this.init.certificateDatastoreKey??EN),o=await u2(e);try{if(t===!0)throw this.log.trace("forcing renewal of TLS certificate"),new qe;this.log.trace("checking for stored TLS certificate"),n=await this.loadCertificate(i,o)}catch(a){if(a.name!=="NotFoundError")throw a;this.log.trace("generating new TLS certificate"),n=await this.createCertificate(i,o)}let s=n.notAfter.getTime()-(this.init.certificateRenewalThreshold??Uv)-Date.now();return s<0&&(s=100),this.log("will renew TLS certificate after %d ms",s),this.renewCertificateTask=setTimeout(()=>{this.log("renewing TLS certificate"),this.getCertificate(!0).then(a=>{this.certificate=a,this.emitter.safeDispatchEvent("certificate:renew",{detail:a})}).catch(a=>{this.log.error("could not renew certificate - %e",a)})},s),{pem:n.toString("pem"),certhash:cl.encode((await Be.digest(new Uint8Array(n.rawData))).bytes)}}async loadCertificate(e,t){let n=await this.components.datastore.get(e),i=new Fh(n),o=i.notAfter.getTime()-(this.init.certificateRenewalThreshold??Uv);if(Date.now()>o)throw this.log("stored TLS certificate has expired"),new qe;this.log("loaded certificate, expires in %d ms",o);let s=await i.publicKey.export(crypto),a=await crypto.subtle.exportKey("raw",s),c=await crypto.subtle.exportKey("raw",t.publicKey);if(!he(new Uint8Array(a,0,a.byteLength),new Uint8Array(c,0,c.byteLength)))throw this.log("stored TLS certificate public key did not match public key from private key"),new qe;return this.log("loaded certificate, expiry time is %o",o),i}async createCertificate(e,t){let n=new Date,i=new Date(Date.now()+(this.init.certificateLifespan??_N));n.setMilliseconds(0),i.setMilliseconds(0);let o=await t8.createSelfSigned({serialNumber:(BigInt(Math.random().toString().replace(".",""))*100000n).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:n,notAfter:i,keys:t,extensions:[new Lh(!1,void 0,!0)]},crypto);return this.getKeychain()!=null?(this.log.trace("storing TLS certificate"),await this.components.datastore.put(e,D(o.toString("pem")))):this.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),o}getKeychain(){try{return this.components.keychain}catch{}}};function yJ(r){return r==null?!1:typeof r.privateKey=="string"&&typeof r.pem=="string"&&typeof r.certhash=="string"}function i8(r){return e=>new n8(e,r)}function SM(r){return e=>new Q6(e,r)}var _M=async r=>{if(r.readyState>=2)throw new Error("socket closed");r.readyState!==1&&await new Promise((e,t)=>{function n(){r.removeEventListener("open",i),r.removeEventListener("error",o)}function i(){n(),e()}function o(s){n(),t(s.error??new Error(`connect ECONNREFUSED ${r.url}`))}r.addEventListener("open",i),r.addEventListener("error",o)})};var CM=(r,e)=>(e=e??{},e.closeOnEnd=e.closeOnEnd!==!1,async n=>{for await(let i of n){try{await _M(r)}catch(o){if(o.message==="socket closed")break;throw o}if(r.readyState===r.CLOSING||r.readyState===r.CLOSED)break;r.send(i)}e.closeOnEnd!=null&&r.readyState<=1&&await new Promise((i,o)=>{r.addEventListener("close",s=>{if(s.wasClean||s.code===1006)i();else{let a=Object.assign(new Error("ws error"),{event:s});o(a)}}),setTimeout(()=>{r.close()})})});var PM=mt(IM(),1);function kM(r){return r instanceof ArrayBuffer||r?.constructor?.name==="ArrayBuffer"&&typeof r?.byteLength=="number"}var RM=r=>{r.binaryType="arraybuffer";let e=async()=>{await new Promise((o,s)=>{if(n){o();return}if(i!=null){s(i);return}let a=u=>{r.removeEventListener("open",c),r.removeEventListener("error",l),u()},c=()=>{a(o)},l=u=>{a(()=>{s(u.error??new Error(`connect ECONNREFUSED ${r.url}`))})};r.addEventListener("open",c),r.addEventListener("error",l)})},t=(async function*(){let o=new PM.EventIterator(({push:s,stop:a,fail:c})=>{let l=f=>{let d=null;typeof f.data=="string"&&(d=D(f.data)),kM(f.data)&&(d=new Uint8Array(f.data)),f.data instanceof Uint8Array&&(d=f.data),d!=null&&s(d)},u=f=>{c(f.error??new Error("Socket error"))};return r.addEventListener("message",l),r.addEventListener("error",u),r.addEventListener("close",a),()=>{r.removeEventListener("message",l),r.removeEventListener("error",u),r.removeEventListener("close",a)}},{highWaterMark:1/0});await e();for await(let s of o)yield kM(s)?new Uint8Array(s):s})(),n=r.readyState===1,i;return r.addEventListener("open",()=>{n=!0,i=null}),r.addEventListener("close",()=>{n=!1,i=null}),r.addEventListener("error",o=>{n||(i=o.error??new Error(`connect ECONNREFUSED ${r.url}`))}),Object.assign(t,{connected:e})};var DM=(r,e)=>{e=e??{};let t=RM(r),n=e.remoteAddress,i=e.remotePort;if(r.url!=null)try{let s=new URL(r.url);n=s.hostname,i=parseInt(s.port,10)}catch{}if(n==null||i==null)throw new Error("Remote connection did not have address and/or port");return{sink:CM(r,e),source:t,connected:async()=>{await t.connected()},close:async()=>{(r.readyState===r.CONNECTING||r.readyState===r.OPEN)&&await new Promise(s=>{r.addEventListener("close",()=>{s()}),r.close()})},destroy:()=>{r.terminate!=null?r.terminate():r.close()},remoteAddress:n,remotePort:i,socket:r}};var OM=WebSocket;var xJ={"http:":"ws:","https:":"wss:"},NM="ws:",BM=(r,e)=>{if(r.startsWith("//")&&(r=`${e?.protocol??NM}${r}`),r.startsWith("/")&&e!=null){let n=e.protocol??NM,i=e.host,o=e.port!=null&&i?.endsWith(`:${e.port}`)!==!0?`:${e.port}`:"";r=`${n}//${i}${o}${r}`}let t=new URL(r);for(let[n,i]of Object.entries(xJ))t.protocol===n&&(t.protocol=i);return t};function LM(r,e){let t=typeof window>"u"?void 0:window.location;e=e??{};let n=BM(r,t),i=new OM(n.toString(),e.websocket);return DM(i,e)}function MM(r){return r.filter(e=>ql.exactMatch(e)||na.exactMatch(e))}function UM(){throw new Error("WebSocket Servers can not be created in the browser!")}function FM(r,e,t){let n=t.metrics,i=t.metricPrefix??"",o={log:t.logger.forComponent("libp2p:websockets:connection"),async sink(c){try{await r.sink((async function*(){for await(let l of c)l instanceof Uint8Array?yield l:yield l.subarray()})())}catch(l){l.type!=="aborted"&&o.log.error(l)}},source:r.source,remoteAddr:e,timeline:{open:Date.now()},async close(c={}){let l=Date.now();if(c.signal==null){let f=AbortSignal.timeout(500);c={...c,signal:f}}let u=()=>{let{host:f,port:d}=o.remoteAddr.toOptions();o.log("timeout closing stream to %s:%s after %dms, destroying it manually",f,d,Date.now()-l),this.abort(new Je("Socket close timeout"))};c.signal?.addEventListener("abort",u);try{await r.close()}catch(f){o.log.error("error closing WebSocket gracefully - %e",f),this.abort(f)}finally{c.signal?.removeEventListener("abort",u),o.timeline.close=Date.now()}},abort(c){o.log.error("destroying WebSocket after error - %e",c),r.destroy(),o.timeline.close=Date.now(),n?.increment({[`${i}error`]:!0})}},s=!1,a=r.socket.close.bind(r.socket);return r.socket.close=(...c)=>(s=!0,a(...c)),r.socket.addEventListener("close",c=>{if(o.log('closed %s, code %d, reason "%s", wasClean %s',s?"locally":"by remote",c.code,c.reason,c.wasClean),!c.wasClean){o.abort(new La(`${s?"Local":"Remote"} did not close WebSocket cleanly`));return}n?.increment({[`${i}close`]:!0}),o.timeline.close=Date.now()},{once:!0}),o}var LE=class{log;init;logger;metrics;components;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:websockets"),this.logger=e.logger,this.components=e,this.init=t,e.metrics!=null&&(this.metrics={dialerEvents:e.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}[Ba]=!0;[Symbol.toStringTag]="@libp2p/websockets";[et]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=await this._connect(e,t),i=FM(n,e,{logger:this.logger,metrics:this.metrics?.dialerEvents});this.log("new outbound connection %s",i.remoteAddr);let o=await t.upgrader.upgradeOutbound(i,t);return this.log("outbound connection %s upgraded",i.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=e.toOptions();this.log("dialing %s:%s",n.host,n.port);let i=ve(),o=LM(wd(e),this.init);o.socket.addEventListener("error",()=>{let s=new La(`Could not connect to ${e.toString()}`);this.log.error("connection error:",s),this.metrics?.dialerEvents.increment({error:!0}),i.reject(s)});try{t.onProgress?.(new X("websockets:open-connection")),await dt(Promise.race([o.connected(),i.promise]),t.signal)}catch(s){throw t.signal?.aborted&&this.metrics?.dialerEvents.increment({abort:!0}),o.close().catch(a=>{this.log.error("error closing raw socket",a)}),s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return UM({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e=Array.isArray(e)?e:[e],this.init?.filter!=null?this.init?.filter(e):MM(e)}dialFilter(e){return this.listenFilter(e)}};function a8(r={}){return e=>new LE(e,r)}var ME=mt(Uy(),1);function c8(r,e){let t=e.map((n,i)=>({record:Bn(n),index:i}));return t.sort((n,i)=>{let o=n.record.sequence,s=i.record.sequence;if(o>s)return-1;if(o<s)return 1;if(n.record.validityType===Fr.ValidityType.EOL&&i.record.validityType===Fr.ValidityType.EOL){let a=ME.default.fromString(n.record.validity).toDate(),c=ME.default.fromString(i.record.validity).toDate();if(a.getTime()>c.getTime())return-1;if(a.getTime()<c.getTime())return 1}return 0}),t[0].index}var $M="5.5.1",HM="helia";var VM={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function B0(r={}){let e=`${HM}/${$M} ${W3()}`;return{privateKey:r.privateKey,dns:r.dns,nodeInfo:{userAgent:e},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[yv(),SM(),i8(),a8()],connectionEncrypters:[C4()],streamMuxers:[FD(),lN()],peerDiscovery:[tO(VM)],services:{autoNAT:zD(),dcutr:mO(),delegatedRouting:()=>Qy("https://delegated-ipfs.dev",K9()),dht:rN({clientMode:!0,validators:{ipns:ic},selectors:{ipns:c8}}),identify:vO(),identifyPush:AO(),keychain:y4(r.keychain),ping:hN()}}}async function KM(r){let e=r.libp2p??{};e.privateKey==null&&r.datastore!=null&&(e.privateKey=await Mb(r.datastore,r.keychain));let t=B0(e);return t.datastore=t.datastore??r.datastore,await G3({...t,...e,start:!1})}async function zM(r={}){let e=r.datastore??new Wl,t=r.blockstore??new Tm,n;return nR(r.libp2p)?n=r.libp2p:n=await KM({...r,libp2p:{dns:r.dns,...r.libp2p,start:void 0},datastore:e}),{...r,libp2p:n,datastore:e,blockstore:t,blockBrokers:r.blockBrokers??[bm(),um()],routers:r.routers??[Cm(n),_m()],metrics:n.metrics}}async function qM(r={}){let e=await zM(r),t=new py(e);return e.start!==!1&&await t.start(),t}function jM(){let r=B0();r.start=!1,r.addresses={listen:[]},r.transports=[i8(),a8()],r.peerDiscovery=[];let e={dcutr:r.services.dcutr,identify:r.services.identify,keychain:r.services.keychain,ping:r.services.ping};return{...r,start:!1,services:e}}var l8=class extends Error{static name="DNSLinkNotFoundError";constructor(e="DNSLink not found"){super(e),this.name="DNSLinkNotFoundError"}},u8=class extends Error{static name="RecordsFailedValidationError";constructor(e="Records failed validation"){super(e),this.name="RecordsFailedValidationError"}},f8=class extends Error{static name="UnsupportedMultibasePrefixError";constructor(e="Unsupported multibase prefix"){super(e),this.name="UnsupportedMultibasePrefixError"}},d8=class extends Error{static name="UnsupportedMultihashCodecError";constructor(e="Unsupported multihash codec"){super(e),this.name="UnsupportedMultihashCodecError"}},h8=class extends Error{static name="InvalidValueError";constructor(e="Invalid value"){super(e),this.name="InvalidValueError"}};var vJ=32;async function WM(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");n("query %s for TXT and CNAME records",r);let s=((await t.query(r,{...i,types:[an.TXT]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d TXT records for %s",s.length,r);for(let l of s)try{let u=l.data;if(u.startsWith('"')&&u.endsWith('"')&&(u=u.substring(1,u.length-1)),!u.startsWith("dnslink="))continue;n("%s TXT %s",l.name,u),u=u.replace("dnslink=","");let[,f,d,...h]=u.split("/");if(f==="ipfs")try{return{value:`/ipfs/${G.parse(d)}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}else if(f==="ipns"){try{let m;return d.charAt(0)==="1"||d.charAt(0)==="Q"?m=gt(d):m=vn(G.parse(d)),{value:`/ipns/${m}${h.length>0?`/${h.join("/")}`:""}`,answer:l}}catch{}return await p8(d,e-1,t,n,i)}else{if(f==="dnslink")return await p8(d,e-1,t,n,i);n('unknown protocol "%s" in DNSLink record for domain: %s',f,r);continue}}catch(u){n.error("could not parse DNS link record for domain %s, %s",r,l.data,u)}n("no DNSLink records found for %s, falling back to CNAME",r);let c=((await t.query(r,{...i,types:[an.CNAME]}))?.Answer??[]).sort((l,u)=>l.data.localeCompare(u.data));n("found %d CNAME records for %s",c.length,r);for(let l of c)try{return await p8(l.data,e-1,t,n,i)}catch(u){n.error("domain %s cname %s had no DNSLink records",r,l.data,u)}throw new l8(`No DNSLink records found for domain: ${r}`)}async function p8(r,e,t,n,i={}){if(e===0)throw new Error("recursion limit exceeded");r.startsWith("_dnslink.")||(r=`_dnslink.${r}`);try{return await WM(r,e,t,n,i)}catch(o){if(o.code!=="ENOTFOUND"&&o.code!=="ENODATA"&&o.name!=="DNSLinkNotFoundError"&&o.name!=="NotFoundError")throw o;return r.startsWith("_dnslink.")?r=r.replace("_dnslink.",""):r=`_dnslink.${r}`,WM(r,e,t,n,i)}}async function GM(r,e,t,n={}){return p8(r,n.maxRecursiveDepth??vJ,e,t,n)}var UE=class{routing;constructor(e){this.routing=e}async put(e,t,n={}){try{await this.routing.put(e,t,n)}catch(i){throw n.onProgress?.(new X("ipns:routing:helia:error",i)),i}}async get(e,t={}){try{return await this.routing.get(e,t)}catch(n){throw t.onProgress?.(new X("ipns:routing:helia:error",n)),n}}};function XM(r){return new UE(r)}function m8(r){return new it("/dht/record/"+z(r,"base32"),!1)}function YM(r){return{async put(e,t,n={}){try{let i=m8(e);try{let s=await r.get(i),a=Mt.deserialize(s);if(he(a.value,t))return}catch(s){if(s.name!=="NotFoundError")throw s}let o=new Mt(e,t,new Date);n.onProgress?.(new X("ipns:routing:datastore:put")),await r.put(i,o.serialize(),n)}catch(i){throw n.onProgress?.(new X("ipns:routing:datastore:error",i)),i}},async get(e,t={}){try{let n=m8(e);t.onProgress?.(new X("ipns:routing:datastore:get"));let i=await r.get(n,t),o=Mt.deserialize(i);return{record:o.value,created:o.timeReceived}}catch(n){throw t.onProgress?.(new X("ipns:routing:datastore:error",n)),n}},async has(e,t={}){let n=m8(e);return r.has(n,t)},async delete(e,t){let n=m8(e);return r.delete(n,t)}}}var FE="/ipns/";function $E(r,e){return r.code===e}var Ia=Ue("helia:ipns"),JM=60*1e3,eU=60*JM,SJ=48*eU,HE=23*eU,QM=BigInt(JM)*5000000n,ZM={[mn.prefix]:mn,[Ye.prefix]:Ye},VE=class{routers;localStore;timeout;dns;log;constructor(e,t=[]){this.routers=[XM(e.routing),...t],this.localStore=YM(e.datastore),this.dns=e.dns,this.log=e.logger.forComponent("helia:ipns")}async publish(e,t,n={}){try{let i=1n,o=ia(e.publicKey.toMultihash());if(await this.localStore.has(o,n)){let{record:l}=await this.localStore.get(o,n);i=Bn(l).sequence+1n}let s=n.ttl!=null?BigInt(n.ttl)*1000000n:QM,a=await Xk(e,t,i,n.lifetime??SJ,{...n,ttlNs:s}),c=nc(a);return await this.localStore.put(o,c,n),n.offline!==!0&&await Promise.all(this.routers.map(async l=>{await l.put(o,c,n)})),a}catch(i){throw n.onProgress?.(new X("ipns:publish:error",i)),i}}async resolve(e,t={}){let n=BS(e)?e.toMultihash():e,i=ia(n),o=await this.#t(i,t);return{...await this.#e(o.value,t),record:o}}async resolveDNSLink(e,t={}){let n=await GM(e,this.dns,this.log,t);return{...await this.#e(n.value,t),answer:n.answer}}republish(e={}){if(this.timeout!=null)throw new Error("Republish is already running");e.signal?.addEventListener("abort",()=>{clearTimeout(this.timeout)});async function t(){let n=Date.now();e.onProgress?.(new X("ipns:republish:start"));let o=Date.now()-n,s=HE-o;s<0&&(s=e.interval??HE),setTimeout(()=>{t().catch(a=>{Ia.error("error republishing",a)})},s)}this.timeout=setTimeout(()=>{t().catch(n=>{Ia.error("error republishing",n)})},e.interval??HE)}async#e(e,t={}){let n=e.split("/");try{let i=n[1];if(i==="ipns"){let o=n[2],s=o.substring(0,1),a;if(s==="1"||s==="Q")a=Ye.decode(`z${o}`);else if(ZM[s]!=null)a=ZM[s].decode(o);else throw new f8(`Unsupported multibase prefix "${s}"`);let c;try{c=We(a)}catch{c=G.decode(a).multihash}if(!$E(c,0)&&!$E(c,18))throw new d8(`Unsupported multihash codec "${c.code}"`);let{cid:l}=await this.resolve(c,t),u=n.slice(3).join("/");return{cid:l,path:u}}else if(i==="ipfs"){let o=G.parse(n[2]),s=n.slice(3).join("/");return{cid:o,path:s}}}catch(i){Ia.error("error parsing ipfs path",i)}throw Ia.error("invalid ipfs path %s",e),new h8("Invalid value")}async#t(e,t={}){let n=[];if(await this.localStore.has(e,t))if(Ia("record is present in the cache"),t.nocache!==!0)try{let{record:a,created:c}=await this.localStore.get(e,t);this.log("record retrieved from cache"),await ic(e,a),this.log("record was valid");let l=Bn(a),u=Number((l.ttl??QM)/1000000n);if(c.getTime()+u>Date.now())return this.log("record TTL was valid"),l;if(t.offline===!0)return this.log("record TTL has been reached but we are resolving offline-only, returning record"),l;this.log("record TTL has been reached, searching routing for updates"),n.push(a)}catch(a){this.log("cached record was invalid",a),await this.localStore.delete(e,t)}else Ia("ignoring local cache due to nocache=true option");if(t.offline===!0)throw new qe("Record was not present in the cache or has expired");Ia("did not have record locally");let o=0;if(await Promise.all(this.routers.map(async a=>{let c;try{c=await a.get(e,{...t,validate:!1})}catch(l){Ia.error("error finding IPNS record",l);return}try{await ic(e,c),n.push(c)}catch(l){o++,Ia.error("error finding IPNS record",l)}})),n.length===0)throw o>0?new u8(`${o>1?`${o} records`:"Record"} found for routing key ${o>1?"were":"was"} invalid`):new qe("Could not find record for routing key");let s=n[c8(e,n)];return await this.localStore.put(e,s,t),Bn(s)}async republishRecord(e,t,n={}){let i;try{if(i=Em(t)?.toMultihash(),i==null)if(typeof e=="string"){e.startsWith(FE)&&(e=e.slice(FE.length));try{i=gt(e).toMultihash()}catch(a){throw new Error(`Invalid string key: ${a.message}`)}}else i=e;if(i==null)throw new Error("No public key multihash found to determine the routing key");let o=ia(i),s=nc(t);await ic(o,s),await this.localStore.put(o,s,n),n.offline!==!0&&await Promise.all(this.routers.map(async a=>{await a.put(o,s,n)}))}catch(o){throw n.onProgress?.(new X("ipns:republish:error",{key:i,record:t,err:o})),o}}};function tU(r,{routers:e=[]}={}){return new VE(r,e)}var sf=class extends Map{#e=0;#t=new Map;#r=new Map;#s;#c;#l;constructor(e={}){if(super(),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");if(typeof e.maxAge=="number"&&e.maxAge===0)throw new TypeError("`maxAge` must be a number greater than 0");this.#s=e.maxSize,this.#c=e.maxAge||Number.POSITIVE_INFINITY,this.#l=e.onEviction}get __oldCache(){return this.#r}#o(e){if(typeof this.#l=="function")for(let[t,n]of e)this.#l(t,n.value)}#n(e,t){return typeof t.expiry=="number"&&t.expiry<=Date.now()?(typeof this.#l=="function"&&this.#l(e,t.value),this.delete(e)):!1}#i(e,t){if(this.#n(e,t)===!1)return t.value}#h(e,t){return t.expiry?this.#i(e,t):t.value}#a(e,t){let n=t.get(e);return this.#h(e,n)}#f(e,t){this.#t.set(e,t),this.#e++,this.#e>=this.#s&&(this.#e=0,this.#o(this.#r),this.#r=this.#t,this.#t=new Map)}#u(e,t){this.#r.delete(e),this.#f(e,t)}*#d(){for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#n(t,n)===!1&&(yield e)}for(let e of this.#t){let[t,n]=e;this.#n(t,n)===!1&&(yield e)}}get(e){if(this.#t.has(e)){let t=this.#t.get(e);return this.#h(e,t)}if(this.#r.has(e)){let t=this.#r.get(e);if(this.#n(e,t)===!1)return this.#u(e,t),t.value}}set(e,t,{maxAge:n=this.#c}={}){let i=typeof n=="number"&&n!==Number.POSITIVE_INFINITY?Date.now()+n:void 0;return this.#t.has(e)?this.#t.set(e,{value:t,expiry:i}):this.#f(e,{value:t,expiry:i}),this}has(e){return this.#t.has(e)?!this.#n(e,this.#t.get(e)):this.#r.has(e)?!this.#n(e,this.#r.get(e)):!1}peek(e){if(this.#t.has(e))return this.#a(e,this.#t);if(this.#r.has(e))return this.#a(e,this.#r)}expiresIn(e){let t=this.#t.get(e)??this.#r.get(e);if(t)return t.expiry?t.expiry-Date.now():Number.POSITIVE_INFINITY}delete(e){let t=this.#t.delete(e);return t&&this.#e--,this.#r.delete(e)||t}clear(){this.#t.clear(),this.#r.clear(),this.#e=0}resize(e){if(!(e&&e>0))throw new TypeError("`maxSize` must be a number greater than 0");let t=[...this.#d()],n=t.length-e;n<0?(this.#t=new Map(t),this.#r=new Map,this.#e=t.length):(n>0&&this.#o(t.slice(0,n)),this.#r=new Map(t.slice(n)),this.#t=new Map,this.#e=0),this.#s=e}evict(e=1){let t=Number(e);if(!t||t<=0)return;let n=[...this.#d()],i=Math.trunc(Math.min(t,Math.max(n.length-1,0)));i<=0||(this.#o(n.slice(0,i)),this.#r=new Map(n.slice(i)),this.#t=new Map,this.#e=0)}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.#t){let[t,n]=e;this.#n(t,n)===!1&&(yield[t,n.value])}for(let e of this.#r){let[t,n]=e;this.#t.has(t)||this.#n(t,n)===!1&&(yield[t,n.value])}}*entriesDescending(){let e=[...this.#t];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#n(i,o)===!1&&(yield[i,o.value])}e=[...this.#r];for(let t=e.length-1;t>=0;--t){let n=e[t],[i,o]=n;this.#t.has(i)||this.#n(i,o)===!1&&(yield[i,o.value])}}*entriesAscending(){for(let[e,t]of this.#d())yield[e,t.value]}get size(){if(!this.#e)return this.#r.size;let e=0;for(let t of this.#r.keys())this.#t.has(t)||e++;return Math.min(this.#e+e,this.#s)}get maxSize(){return this.#s}entries(){return this.entriesAscending()}forEach(e,t=this){for(let[n,i]of this.entriesAscending())e.call(t,i,n,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};function af(r,e={}){let t=Kd(r),n={_cancelled:!1,async start(){this._cancelled=!1},async pull(i){try{let{value:o,done:s}=await t.next();if(this._cancelled)return;if(s===!0){i.close();return}i.enqueue(o)}catch(o){i.error(o)}},cancel(){this._cancelled=!0}};return new globalThis.ReadableStream(n,e)}var Pr=class extends Error{static name="InvalidRangeError";constructor(e="Invalid range request"){super(e),this.name="InvalidRangeError"}},g8=class extends Error{static name="NoContentError";constructor(e="No content found"){super(e),this.name="NoContentError"}},y8=class extends Error{static name="SubdomainNotSupportedError";constructor(e="Subdomain not supported"){super(e),this.name="SubdomainNotSupportedError"}};function rU(r,e){if(r==null)return;if(r instanceof Headers)return r.get(e)??void 0;if(Array.isArray(r))return r.find(([i])=>i.toLowerCase()===e.toLowerCase())?.[1];let t=Object.keys(r).find(n=>n.toLowerCase()===e.toLowerCase());if(t!=null)return r[t]}function nU(r,e,t){if((r??0)>(e??1/0))throw new Pr("Invalid range: Range-start index is greater than range-end index.");if(r!=null&&(e??0)>=(t??1/0))throw new Pr("Invalid range: Range-end index is greater than or equal to the size of the file.");if(r==null&&(e??0)>(t??1/0))throw new Pr("Invalid range: Range-end index is greater than the size of the file.");if(r!=null&&r<0)throw new Pr("Invalid range: Range-start index cannot be negative.");if(r!=null&&e!=null)return{byteSize:e-r+1,start:r,end:e};if(r==null&&e!=null)return t==null?{end:e}:e===t?{byteSize:t,start:0,end:t-1}:{byteSize:e,start:t-e,end:t-1};if(r!=null&&e==null){if(t==null)return{start:r};let n=t-1;return{byteSize:t-r,start:r,end:n}}return{byteSize:t,start:0,end:t!=null?t-1:0}}function iU({ttl:r,protocol:e,response:t}){if(t.headers.has("cache-control"))return;let n;e==="ipfs"?n="public, max-age=29030400, immutable":r==null?n="public, max-age=300":n=`public, max-age=${r}`,t.headers.set("cache-control",n)}function w8({byteStart:r,byteEnd:e,byteSize:t}){let n=t??"*";if((e??0)>=(t??1/0))throw new Pr("Invalid range: Range-end index is greater than or equal to the size of the file.");if((r??0)>=(t??1/0))throw new Pr("Invalid range: Range-start index is greater than or equal to the size of the file.");if(r!=null&&e==null)return t==null?`bytes */${n}`:`bytes ${r}-${t-1}/${t}`;if(r==null&&e!=null){if(t==null)return`bytes */${n}`;let i=t-1;return`bytes ${i-e+1}-${i}/${t}`}return r==null&&e==null?`bytes */${n}`:`bytes ${r}-${e}/${n}`}function x8(r,e){e!=null&&r.headers.set("X-Ipfs-Roots",L0(e))}function L0(r){return r.map(e=>e.toV1().toString()).join(",")}function _J(r){return typeof r=="string"?r.length:r instanceof ArrayBuffer||r instanceof Uint8Array?r.byteLength:r instanceof Blob?r.size:(r instanceof ReadableStream,null)}function CJ(r){if(!r.startsWith("bytes="))throw new Pr("Invalid range request");let t=r.substring(6).split(",").map(i=>i.trim()),n=[];for(let i of t){let o=i.match(/^(?<start>\d+)?-(?<end>\d+)?$/);if(o?.groups==null)throw new Pr(`Invalid range specification: ${i}`);let{start:s,end:a}=o.groups;n.push({start:s??null,end:a??null})}if(n.length===0)throw new Pr("No valid ranges found");return{ranges:n}}var b8=class{headers;isRangeRequest;_fileSize;_body=null;rangeRequestHeader;log;multiPartBoundary;requestRanges=[];byteRanges=[];isMultiRangeRequest=!1;_isValidRangeRequest=!1;constructor(e,t){if(this.headers=t,this.log=e.forComponent("helia:verified-fetch:byte-range-context"),this.rangeRequestHeader=rU(this.headers,"Range"),this.rangeRequestHeader!=null){this.isRangeRequest=!0,this.log.trace("range request detected");try{let{ranges:n}=CJ(this.rangeRequestHeader);this.isMultiRangeRequest=n.length>1,this.requestRanges=n.map(i=>({start:i.start!=null?parseInt(i.start):null,end:i.end!=null?parseInt(i.end):null})),this.multiPartBoundary=`multipart_byteranges_${Math.floor(Math.random()*1e9)}`}catch(n){this.log.error("error parsing range request header - %e",n),this.requestRanges=[]}this.setOffsetDetails()}else this.log.trace("no range request detected"),this.isRangeRequest=!1}getByteRanges(){return this.byteRanges}setBody(e,t="application/octet-stream"){typeof e=="function"?this._body=this.createRangeStream(e,t):(this._body=e,this.setFileSize(this._fileSize??_J(e))),this.log.trace("set request body with fileSize %o",this._fileSize)}getBody(e){let t=this._body;if(t==null)return this.log.trace("body is null"),t;if(!this.isRangeRequest||!this.isValidRangeRequest)return this.log.trace("returning body unmodified for non-range, or invalid range, request"),t;if(this.isMultiRangeRequest)return this._body instanceof ReadableStream?this._body:af(this.getMultipartBody(e));if(this.byteRanges.length>0){let n=this.byteRanges[0];return t instanceof ReadableStream?t:((n.start!=null||n.end!=null)&&this.log.trace("returning body with byteStart=%o, byteEnd=%o, byteSize=%o",n.start,n.end,n.size),this.getSlicedBody(t,n))}return this.log.error("returning unmodified body for valid range request"),t}getSlicedBody(e,t){let n=t.start??0,i;return t.end!=null&&t.start!=null?i=t.end-t.start+1:i=void 0,this.log.trace("slicing body with offset=%o and length=%o",n,i),typeof e=="string"||e instanceof Blob||e instanceof ArrayBuffer||e instanceof Uint8Array?e.slice(n,i!==void 0?n+i:void 0):e}setFileSize(e){this._fileSize=e!=null?Number(e):null,this._isValidRangeRequest=!1,this.log.trace("set _fileSize to %o",this._fileSize),this.setOffsetDetails()}getFileSize(){return this._fileSize}isValidByteStart(e,t){return!(e!=null&&(e<0||this._fileSize!=null&&e>=this._fileSize||t!=null&&e>t))}isValidByteEnd(e,t){if(t!=null){if(t<0)return this.log.trace("invalid range request, byteEnd is less than 0"),!1;if(this._fileSize!=null&&t>=this._fileSize)return this.log.trace("invalid range request, byteEnd is greater than fileSize"),!1;if(e!=null&&t<e)return this.log.trace("invalid range request, byteEnd is less than byteStart"),!1}return!0}isValidByteRange(e){return this.log.trace("validating byte range: %o",e),e.start!=null&&!this.isValidByteStart(e.start,e.end)?(this.log.trace("invalid range request, byteStart is less than 0 or greater than fileSize"),!1):e.end!=null&&!this.isValidByteEnd(e.start,e.end)?(this.log.trace("invalid range request, byteEnd is less than 0 or greater than fileSize"),!1):!0}get isValidRangeRequest(){return this._isValidRangeRequest?!0:this.isRangeRequest?this.byteRanges.length===0?(this.log.trace("invalid range request, no valid ranges"),!1):this.byteRanges.every(t=>this.isValidByteRange(t))?(this._isValidRangeRequest=!0,!0):(this.log.trace("invalid range request, not all ranges are valid"),!1):!1}getLength(e){if(!this.isValidRangeRequest){this.log.error("cannot get length for invalid range request");return}if(!(this.isMultiRangeRequest&&e==null))return e??=this.byteRanges[0],this.log.trace("getting length for range: %o",e),e.end!=null&&e.start!=null?e.end-e.start+1:e.end!=null?e.end+1:e.size}setOffsetDetails(){if(this.requestRanges.length===0){this.log.trace("no request ranges defined");return}try{this.byteRanges=this.requestRanges.map(e=>{let{start:t,end:n,byteSize:i}=nU(e.start??void 0,e.end??void 0,this._fileSize??void 0);return{start:t,end:n,size:i}}),this.log.trace("set byte ranges: %o",this.byteRanges)}catch(e){this.log.error("error setting offset details: %o",e),this.byteRanges=[]}}async convertToUint8Array(e){if(typeof e=="string")return new TextEncoder().encode(e);if("arrayBuffer"in e&&typeof e.arrayBuffer=="function"){let t=await e.arrayBuffer();return new Uint8Array(t)}if("byteLength"in e&&!("buffer"in e))return new Uint8Array(e);if("buffer"in e&&"byteLength"in e&&"byteOffset"in e)return e;throw new Error("Unsupported content type for multipart response")}async*getMultipartBody(e="application/octet-stream"){let t=this._body;if(t instanceof ReadableStream)return t;if(t===null)throw new Error("Cannot create multipart body from null");let n=new TextEncoder;for(let i of this.byteRanges){if(i.start===void 0||i.end===void 0)continue;let o=`\r
|
|
83
83
|
--${this.multiPartBoundary}\r
|
|
84
84
|
Content-Type: ${e}\r
|
|
85
85
|
Content-Range: ${w8({byteStart:i.start,byteEnd:i.end,byteSize:this._fileSize??void 0})}\r
|
|
@@ -92,7 +92,7 @@ Content-Range: ${w8({byteStart:u.start,byteEnd:u.end,byteSize:s??void 0})}\r
|
|
|
92
92
|
\r
|
|
93
93
|
`;l.enqueue(n.encode(f))}try{let f=e(u);for await(let d of f)l.enqueue(d)}catch(f){throw a.error("Error processing range %o: %o",u,f),f}}c&&l.enqueue(n.encode(`\r
|
|
94
94
|
--${o}--`)),l.close()}catch(u){a.error("Error processing range(s): %o",u),l.error(u)}}})}};function KE(r,e,t){Object.defineProperty(r,e,{enumerable:!0,configurable:!1,set:()=>{},get:()=>t})}function ka(r,e){KE(r,"type",e)}function Pa(r,e){KE(r,"url",e)}function oU(r){KE(r,"redirected",!0)}function TJ(r,e,t){let n=new Response(e,{...t??{},status:200,statusText:"OK"});return t?.redirected===!0&&oU(n),ka(n,"basic"),Pa(n,r),n}function Hh(r,e,t){let n=new Response(e,{...t??{},status:502,statusText:"Bad Gateway"});return ka(n,"basic"),Pa(n,r),n}function v8(r,e,t){let n=new Response(e,{...t??{},status:501,statusText:"Not Implemented"});return n.headers.set("X-Content-Type-Options","nosniff"),ka(n,"basic"),Pa(n,r),n}function Ra(r,e,t){let n=new Response(e,{...t??{},status:406,statusText:"Not Acceptable"});return ka(n,"basic"),Pa(n,r),n}function A8(r,e,t){let n=new Response(e,{...t??{},status:404,statusText:"Not Found"});return ka(n,"basic"),Pa(n,r),n}function IJ(r){return Array.isArray(r)&&r.every(e=>e instanceof Error)}function M0(r,e,t){let n,i;IJ(e)?(n=e[e.length-1].stack,i=e.map(a=>({message:a.message,stack:a.stack??""}))):e instanceof Error&&(n=e.stack,i=[{message:e.message,stack:e.stack??""}]);let o=JSON.stringify({stack:n,errors:i}),s=new Response(o,{status:400,statusText:"Bad Request",...t??{},headers:{...t?.headers??{},"Content-Type":"application/json"}});return ka(s,"basic"),Pa(s,r),s}function U0(r,e,t){let n=new Response(null,{...t??{},status:301,statusText:"Moved Permanently",headers:{...t?.headers??{},location:e}});return ka(n,"basic"),Pa(n,r),n}function dn(r,e,{byteRangeContext:t,log:n},i){if(!t.isRangeRequest)return TJ(r,e,i);if(!t.isValidRangeRequest)return $h(r,e,i);let o;try{let s=new Headers(i?.headers),a=t.getContentType();a!=null?s.set("content-type",a):t.isMultiRangeRequest?s.set("content-type","multipart/byteranges"):s.set("content-range",t.contentRangeHeaderValue),o=new Response(e,{...i??{},status:206,statusText:"Partial Content",headers:s})}catch(s){return n?.error("failed to create range response",s),$h(r,e,i)}return i?.redirected===!0&&oU(o),ka(o,"basic"),Pa(o,r),o}function $h(r,e,t){let n=new Response(e,{...t??{},status:416,statusText:"Requested Range Not Satisfiable"});return ka(n,"basic"),Pa(n,r),n}var kt=class{codes=[];pluginOptions;_log;get log(){return this._log==null&&(this._log=this.pluginOptions.logger.forComponent(this.id)),this._log}constructor(e){this.pluginOptions=e}};var E8=class extends kt{id="byte-range-context-plugin";canHandle(e){return e.byteRangeContext==null}async handle(e){return e.byteRangeContext=new b8(this.pluginOptions.logger,e.options?.headers),e.modified++,e.byteRangeContext.isRangeRequest&&!e.byteRangeContext.isValidRangeRequest?$h(e.resource):null}};var jE=mt(S8(),1);var WE=40;function GE(r,e){if(!r.length)throw new Error("Unexpected end of data");let t=jE.default.decode(r);return e.seek(jE.default.decode.bytes),t}function XE(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=0;return{version:2,characteristics:[e.getBigUint64(t,!0),e.getBigUint64(t+=8,!0)],dataOffset:Number(e.getBigUint64(t+=8,!0)),dataSize:Number(e.getBigUint64(t+=8,!0)),indexOffset:Number(e.getBigUint64(t+=8,!0))}}var jc={Null:r=>r===null?r:void 0,Int:r=>Number.isInteger(r)?r:void 0,Float:r=>typeof r=="number"&&Number.isFinite(r)?r:void 0,String:r=>typeof r=="string"?r:void 0,Bool:r=>typeof r=="boolean"?r:void 0,Bytes:r=>r instanceof Uint8Array?r:void 0,Link:r=>r!==null&&typeof r=="object"&&r.asCID===r?r:void 0,List:r=>Array.isArray(r)?r:void 0,Map:r=>r!==null&&typeof r=="object"&&r.asCID!==r&&!Array.isArray(r)&&!(r instanceof Uint8Array)?r:void 0},F0={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":jc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(jc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=F0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=F0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:jc.Int,CarV1HeaderOrV2Pragma:r=>{if(jc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=F0["CarV1HeaderOrV2Pragma > roots (anon)"](r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=F0.Int(r[o]);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},$0={"CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)":jc.Link,"CarV1HeaderOrV2Pragma > roots (anon)":r=>{if(jc.List(r)!==void 0){for(let e=0;e<r.length;e++){let t=r[e];if(t=$0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](t),t===void 0)return;if(t!==r[e]){let n=r.slice(0,e);for(let i=e;i<r.length;i++){let o=r[i];if(o=$0["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](o),o===void 0)return;n.push(o)}return n}}return r}},Int:jc.Int,CarV1HeaderOrV2Pragma:r=>{if(jc.Map(r)===void 0)return;let e=Object.entries(r),t=r,n=1;for(let i=0;i<e.length;i++){let[o,s]=e[i];switch(o){case"roots":{let a=$0["CarV1HeaderOrV2Pragma > roots (anon)"](s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.roots=a}}break;case"version":{n--;let a=$0.Int(s);if(a===void 0)return;if(a!==s||t!==r){if(t===r){t={};for(let c=0;c<i;c++)t[e[c][0]]=e[c][1]}t.version=a}}break;default:return}}if(!(n>0))return t}},YE={toTyped:F0.CarV1HeaderOrV2Pragma,toRepresentation:$0.CarV1HeaderOrV2Pragma};var BZe=Hx();var qJ=mt(S8(),1);var $Ze=[new Y(I.map,2),new Y(I.string,"version"),new Y(I.uint,1),new Y(I.string,"roots")],HZe=new Y(I.tag,42);async function QE(r,e){let t=GE(await r.upTo(8),r);if(t===0)throw new Error("Invalid CAR header (zero length)");let n=await r.exactly(t,!0),i=rs(n);if(YE.toTyped(i)===void 0)throw new Error("Invalid CAR header format");if(i.version!==1&&i.version!==2||e!==void 0&&i.version!==e)throw new Error(`Invalid CAR version: ${i.version}${e!==void 0?` (expected ${e})`:""}`);if(i.version===1){if(!Array.isArray(i.roots))throw new Error("Invalid CAR header format");return i}if(i.roots!==void 0)throw new Error("Invalid CAR header format");let o=XE(await r.exactly(WE,!0));r.seek(o.dataOffset-r.pos);let s=await QE(r,1);return Object.assign(s,o)}function H0(r){let e=0;return{async upTo(t){return r.subarray(e,e+Math.min(t,r.length-e))},async exactly(t,n=!1){if(t>r.length-e)throw new Error("Unexpected end of data");let i=r.subarray(e,e+t);return n&&(e+=t),i},seek(t){e+=t},get pos(){return e}}}var ZE=mt(S8(),1),yU=1;function JE(r){let e=cd({version:yU,roots:r}),t=ZE.default.encode(e.length),n=new Uint8Array(t.length+e.length);return n.set(t,0),n.set(e,t.length),n}function wU(r){return{async setRoots(e){let t=JE(e);await r.write(t)},async writeBlock(e){let{cid:t,bytes:n}=e;await r.write(new Uint8Array(ZE.default.encode(t.bytes.length+n.length))),await r.write(t.bytes),n.length&&await r.write(n)},async close(){await r.end()},version(){return yU}}}function _8(){}function xU(){let r=[],e=null,t=_8,n=!1,i=null,o=_8,s=()=>(e||(e=new Promise(l=>{t=()=>{e=null,t=_8,l()}})),e),a={write(l){r.push(l);let u=s();return o(),u},async end(){n=!0;let l=s();o(),await l}},c={async next(){let l=r.shift();return l?(r.length===0&&t(),{done:!1,value:l}):n?(t(),{done:!0,value:void 0}):(i||(i=new Promise(u=>{o=()=>(i=null,o=_8,u(c.next()))})),i)}};return{writer:a,iterator:c}}var cf=class r{constructor(e,t){this._encoder=t,this._mutex=t.setRoots(e),this._ended=!1}async put(e){if(!(e.bytes instanceof Uint8Array)||!e.cid)throw new TypeError("Can only write {cid, bytes} objects");if(this._ended)throw new Error("Already closed");let t=G.asCID(e.cid);if(!t)throw new TypeError("Can only write {cid, bytes} objects");return this._mutex=this._mutex.then(()=>this._encoder.writeBlock({cid:t,bytes:e.bytes})),this._mutex}async close(){if(this._ended)throw new Error("Already closed");return await this._mutex,this._ended=!0,this._encoder.close()}version(){return this._encoder.version()}static create(e){e=XJ(e);let{encoder:t,iterator:n}=bU(),i=new r(e,t),o=new C8(n);return{writer:i,out:o}}static createAppender(){let{encoder:e,iterator:t}=bU();e.setRoots=()=>Promise.resolve();let n=new r([],e),i=new C8(t);return{writer:n,out:i}}static async updateRootsInBytes(e,t){let n=H0(e);await QE(n);let i=JE(t);if(Number(n.pos)!==i.length)throw new Error(`updateRoots() can only overwrite a header of the same length (old header is ${n.pos} bytes, new header is ${i.length} bytes)`);return e.set(i,0),e}},C8=class{constructor(e){this._iterator=e}[Symbol.asyncIterator](){if(this._iterating)throw new Error("Multiple iterator not supported");return this._iterating=!0,this._iterator}};function bU(){let r=xU(),{writer:e,iterator:t}=r;return{encoder:wU(e),iterator:t}}function XJ(r){if(r===void 0)return[];if(!Array.isArray(r)){let t=G.asCID(r);if(!t)throw new TypeError("roots must be a single CID or an array of CIDs");return[t]}let e=[];for(let t of r){let n=G.asCID(t);if(!n)throw new TypeError("roots must be a single CID or an array of CIDs");e.push(n)}return e}var Vh=class{async*export(e,t){for(let[,n]of t.links())yield n}};var T8=class{target;constructor(e){this.target=e}isTarget(e){return this.target.equals(e)}async*traverse(e,t){for(let[,n]of t.links())yield n}};var I8=class{components;log;constructor(e,t){this.components=e,this.log=e.logger.forComponent("helia:car")}async import(e,t){await Jr(this.components.blockstore.putMany(zt(e.blocks(),({cid:n,bytes:i})=>({cid:n,block:i})),t))}async export(e,t,n){let i=ve(),o=Array.isArray(e)?e:[e],s={currentPath:[],pathsToTarget:null},a=n?.traversal,c=n?.exporter??new Vh,l=new mo({concurrency:1}),u=!1;l.on("idle",()=>{if(u)i.resolve();else if(!u&&s.pathsToTarget?.length===o.length){this.log.trace("starting export of blocks to the car file"),u=!0;for(let f of s.pathsToTarget){let d=f.length-1,h=f[d];f.slice(0,-1).forEach(m=>{l.add(async()=>{await this.#t({cid:m,queue:l,writer:t,strategy:c,options:n,recursive:!1})}).catch(g=>{this.log.error("error during queue operation - %e",g)})}),l.add(async()=>{await this.#t({cid:h,queue:l,writer:t,strategy:c,options:n})}).catch(m=>{this.log.error("error during queue operation - %e",m)})}}else this.log.trace("no paths to target, skipping export"),i.reject(new Error("Could not traverse to target CID(s)"))}),l.on("error",f=>{l.clear(),i.reject(f)});for(let f of o)l.add(async()=>{this.log.trace("traversing dag from %c",f),await this.#e({cid:f,queue:l,strategy:a??new T8(f),traversalContext:s,parentPath:[],options:n})}).catch(d=>{this.log.error("error during queue operation - %e",d)});try{await i.promise}finally{await t.close()}}async*stream(e,t){let{writer:n,out:i}=cf.create(e);this.export(e,n,t).catch(o=>{this.log.error("error during streaming export - %e",o)});for await(let o of i)yield o}async#e({cid:e,queue:t,strategy:n,traversalContext:i,parentPath:o,options:s}){let a=[...o,e];if(n.isTarget(e)){i.pathsToTarget=i.pathsToTarget??[],i.pathsToTarget.push([...a]),this.log.trace("found path to target %c",e);return}let c=await this.components.getCodec(e.code),l=await this.components.blockstore.get(e,s),u=im({bytes:l,cid:e,codec:c});for await(let f of n.traverse(e,u))t.add(async()=>{await this.#e({cid:f,queue:t,strategy:n,traversalContext:i,parentPath:a??[],options:s})}).catch(d=>{this.log.error("error during traversal queue operation - %e",d)})}async#t({cid:e,queue:t,writer:n,strategy:i,options:o,recursive:s=!0}){if(o?.blockFilter?.has(e.multihash.bytes)===!0)return;let a=await this.components.getCodec(e.code),c=await this.components.blockstore.get(e,o);if(o?.blockFilter?.add(e.multihash.bytes),await n.put({cid:e,bytes:c}),s){let l=im({bytes:c,cid:e,codec:a});for await(let u of i.export(e,l))t.add(async()=>{await this.#t({cid:u,queue:t,writer:n,strategy:i,options:o})}).catch(f=>{this.log.error("error during export queue operation - %e",f)})}}};var V0=class{async*export(e,t){}};var k8=class extends Error{static code="ERR_NOT_UNIXFS";static message="Not a UnixFS node";static name="NotUnixFSError";code="ERR_NOT_UNIXFS";message="Not a UnixFS node";name="NotUnixFSError"};var P8=class{async*export(e,t){if(e.code!==112&&e.code!==85)throw new k8("Target CID was not UnixFS - use the SubGraphExporter to export arbitrary graphs");for(let[,n]of t.links())yield n}};var R8=class{pathToTarget;target;constructor(e){this.pathToTarget=e,this.target=e[e.length-1]}isTarget(e){return this.target.equals(e)}async*traverse(e,t){let n=this.pathToTarget.indexOf(e);yield this.pathToTarget[n+1]}};var K0=class r extends Error{static name="InvalidTypeError";static code="ERR_INVALID_TYPE";name=r.name;code=r.code;constructor(e="Invalid type"){super(e)}},D8=class r extends Error{static name="InvalidUnixFSMessageError";static code="ERR_INVALID_MESSAGE";name=r.name;code=r.code;constructor(e="Invalid message"){super(e)}};var Fo;(function(r){let e;(function(i){i.Raw="Raw",i.Directory="Directory",i.File="File",i.Metadata="Metadata",i.Symlink="Symlink",i.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(i){i[i.Raw=0]="Raw",i[i.Directory=1]="Directory",i[i.File=2]="File",i[i.Metadata=3]="Metadata",i[i.Symlink=4]="Symlink",i[i.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(i){i.codec=()=>St(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=be((i,o,s={})=>{if(s.lengthDelimited!==!1&&o.fork(),i.Type!=null&&(o.uint32(8),r.DataType.codec().encode(i.Type,o)),i.Data!=null&&(o.uint32(18),o.bytes(i.Data)),i.filesize!=null&&(o.uint32(24),o.uint64(i.filesize)),i.blocksizes!=null)for(let a of i.blocksizes)o.uint32(32),o.uint64(a);i.hashType!=null&&(o.uint32(40),o.uint64(i.hashType)),i.fanout!=null&&(o.uint32(48),o.uint64(i.fanout)),i.mode!=null&&(o.uint32(56),o.uint32(i.mode)),i.mtime!=null&&(o.uint32(66),O8.codec().encode(i.mtime,o)),s.lengthDelimited!==!1&&o.ldelim()},(i,o)=>{let s={blocksizes:[]},a=o==null?i.len:i.pos+o;for(;i.pos<a;){let c=i.uint32();switch(c>>>3){case 1:s.Type=r.DataType.codec().decode(i);break;case 2:s.Data=i.bytes();break;case 3:s.filesize=i.uint64();break;case 4:s.blocksizes.push(i.uint64());break;case 5:s.hashType=i.uint64();break;case 6:s.fanout=i.uint64();break;case 7:s.mode=i.uint32();break;case 8:s.mtime=O8.codec().decode(i,i.uint32());break;default:i.skipType(c&7);break}}return s})),n),r.encode=i=>xe(i,r.codec()),r.decode=i=>we(i,r.codec())})(Fo||(Fo={}));var O8;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.Seconds!=null&&(n.uint32(8),n.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(n.uint32(21),n.fixed32(t.FractionalNanoseconds)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.Seconds=t.int64();break;case 2:i.FractionalNanoseconds=t.fixed32();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>xe(t,r.codec()),r.decode=t=>we(t,r.codec())})(O8||(O8={}));var vU;(function(r){let e;r.codec=()=>(e==null&&(e=be((t,n,i={})=>{i.lengthDelimited!==!1&&n.fork(),t.MimeType!=null&&(n.uint32(10),n.string(t.MimeType)),i.lengthDelimited!==!1&&n.ldelim()},(t,n)=>{let i={},o=n==null?t.len:t.pos+n;for(;t.pos<o;){let s=t.uint32();switch(s>>>3){case 1:i.MimeType=t.string();break;default:t.skipType(s&7);break}}return i})),e),r.encode=t=>xe(t,r.codec()),r.decode=t=>we(t,r.codec())})(vU||(vU={}));var AU={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},YJ=["directory","hamt-sharded-directory"],EU=parseInt("0644",8),SU=parseInt("0755",8),_U=BigInt(1024),_e=class r{static unmarshal(e){let t=Fo.decode(e);if(t.fanout!=null&&t.fanout>_U)throw new D8(`Fanout size was too large - ${t.fanout} > ${_U}`);let n=new r({type:AU[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}type;data;blockSizes;hashType;fanout;mtime;_mode;_originalMode;constructor(e={type:"file"}){let{type:t,data:n,blockSizes:i,hashType:o,fanout:s,mtime:a,mode:c}=e;if(t!=null&&!Object.values(AU).includes(t))throw new K0("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=o,this.fanout=s,this.blockSizes=i??[],this._originalMode=0,this.mode=c,this.mtime=a}set mode(e){e==null?this._mode=this.isDirectory()?SU:EU:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return YJ.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Fo.DataType.Raw;break;case"directory":e=Fo.DataType.Directory;break;case"file":e=Fo.DataType.File;break;case"metadata":e=Fo.DataType.Metadata;break;case"symlink":e=Fo.DataType.Symlink;break;case"hamt-sharded-directory":e=Fo.DataType.HAMTShard;break;default:throw new K0(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===EU&&!this.isDirectory()&&(n=void 0),n===SU&&this.isDirectory()&&(n=void 0));let i;return this.mtime!=null&&(i={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Fo.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:i})}};function CU(r,e={}){return new I8(r,e)}function QJ({cid:r,ipfsPath:e,query:t}){return t.filename!=null?t.filename:`${e.replace(/\/ipfs\//,"").replace(/\/ipns\//,"").replace(/\//g,"_")}.car`}function ZJ({query:r}){let e=r["dag-scope"];return e==="all"||e==="entity"||e==="block"?e:"all"}var N8=class extends kt{id="car-plugin";canHandle(e){return this.log("checking if we can handle %c with accept %s",e.cid,e.accept),e.byteRangeContext==null||e.pathDetails==null?!1:e.accept?.startsWith("application/vnd.ipld.car")===!0||e.query.format==="car"}async handle(e){let{options:t,pathDetails:n,cid:i}=e;if(n==null)throw new Error("attempted to handle request for car with no path details");let{getBlockstore:o,helia:s}=this.pluginOptions;e.reqFormat="car",e.query.download=!0,e.query.filename=QJ(e);let a=o(i,e.resource,t?.session??!0,t),c=CU({blockstore:a,getCodec:s.getCodec,logger:s.logger}),l=n.ipfsRoots.filter(x=>!x.equals(i)),u={...t};l.length>0&&(u.traversal=new R8(l));let f=ZJ(e),d=n.terminalElement.cid??i;f==="block"?u.exporter=new V0:f==="entity"?d.code===tt?u.exporter=new P8:u.exporter=new V0:u.exporter=new Vh;let{writer:h,out:m}=cf.create(d),g=async function*(){for await(let x of m)yield x};c.export(i,h,u).catch(x=>{this.log.error("error exporting car - %e",x)}),e.byteRangeContext.setBody(af(g()));let w=dn(e.resource,e.byteRangeContext.getBody("application/vnd.ipld.car; version=1"),{byteRangeContext:e.byteRangeContext,log:this.log});return w.headers.set("content-type",e.byteRangeContext.getContentType()??"application/vnd.ipld.car; version=1"),w}};function TU(r){let e=En(r,{allowIndefinite:!1,coerceUndefinedToNull:!1,allowNaN:!1,allowInfinity:!1,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,allowBigInt:!1});return new TextDecoder().decode(cm(e))}var $o=class extends Error{name;code;constructor(e,t,n){super(e),this.name=t,this.code=n}},Ai=class extends $o{constructor(e="not a Unixfs node"){super(e,"NotUnixFSError","ERR_NOT_UNIXFS")}},Xn=class extends $o{constructor(e="invalid PBNode"){super(e,"InvalidPBNodeError","ERR_INVALID_PB_NODE")}},Wc=class extends $o{constructor(e="unknown error"){super(e,"InvalidPBNodeError","ERR_UNKNOWN_ERROR")}},z0=class extends $o{constructor(e="path already exists"){super(e,"AlreadyExistsError","ERR_ALREADY_EXISTS")}},Kh=class extends $o{constructor(e="path does not exist"){super(e,"DoesNotExistError","ERR_DOES_NOT_EXIST")}},zh=class extends $o{constructor(e="no content"){super(e,"NoContentError","ERR_NO_CONTENT")}},B8=class extends $o{constructor(e="not a file"){super(e,"NotAFileError","ERR_NOT_A_FILE")}},Gc=class extends $o{constructor(e="not a directory"){super(e,"NotADirectoryError","ERR_NOT_A_DIRECTORY")}},Ar=class extends $o{constructor(e="invalid parameters"){super(e,"InvalidParametersError","ERR_INVALID_PARAMETERS")}};function JJ(r){return r[Symbol.asyncIterator]!=null}function eee(r){if(JJ(r))return(async()=>{let t;for await(let n of r)t=n;return t})();let e;for(let t of r)e=t;return e}var Ho=eee;var L8=class r extends Error{static name="BadPathError";static code="ERR_BAD_PATH";name=r.name;code=r.code;constructor(e="Bad path"){super(e)}},no=class r extends Error{static name="NotFoundError";static code="ERR_NOT_FOUND";name=r.name;code=r.code;constructor(e="Not found"){super(e)}},M8=class r extends Error{static name="NoResolverError";static code="ERR_NO_RESOLVER";name=r.name;code=r.code;constructor(e="No resolver"){super(e)}},Er=class r extends Error{static name="NotUnixFSError";static code="ERR_NOT_UNIXFS";name=r.name;code=r.code;constructor(e="Not UnixFS"){super(e)}},U8=class r extends Error{static name="OverReadError";static code="ERR_OVER_READ";name=r.name;code=r.code;constructor(e="Over read"){super(e)}},F8=class r extends Error{static name="UnderReadError";static code="ERR_UNDER_READ";name=r.name;code=r.code;constructor(e="Under read"){super(e)}},$8=class r extends Error{static name="NoPropError";static code="ERR_NO_PROP";name=r.name;code=r.code;constructor(e="No Property found"){super(e)}},lf=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};function qh(r,e,t,n,i,o,s){let a=r,c=i;for(;o.length>0;){let l=o[0];if(l in a){o.shift(),c=`${c}/${l}`;let u=G.asCID(a[l]);if(u!=null)return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}},next:{cid:u,name:l,path:c,toResolve:o}};a=a[l]}else throw new $8(`No property named ${l} found in node ${t}`)}return{entry:{type:"object",name:n,path:i,cid:t,node:e,depth:s,size:BigInt(e.length),content:async function*(){yield r}}}}var tee=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=rs(c);return qh(l,c,r,e,t,n,o)},IU=tee;var ree=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=ud(c);return qh(l,c,r,e,t,n,o)},kU=ree;function nee(r,e,t,n){let i=BigInt(r.length),o=BigInt(e+i);return t>=o||n<e?new Uint8Array(0):(n>=e&&n<o&&(r=r.subarray(0,Number(n-e))),t>=e&&t<o&&(r=r.subarray(Number(t-e))),r)}var uf=nee;var iee=(r,e=0,t=r)=>{let n=BigInt(r),i=BigInt(e??0),o=BigInt(t);if(o!==n&&(o=i+o),o>n&&(o=n),i<0n)throw new lf("Offset must be greater than or equal to 0");if(i>n)throw new lf("Offset must be less than the file size");if(o<0n)throw new lf("Length must be greater than or equal to 0");if(o>n)throw new lf("Length must be less than the file size");return{start:i,end:o}},jh=iee;var oee=r=>{async function*e(t={}){let{start:n,end:i}=jh(r.length,t.offset,t.length),o=uf(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},see=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new no(`No link named ${t} found in raw node ${r}`);let c=We(r.multihash.bytes);return{entry:{type:"identity",name:e,path:t,cid:r,content:oee(c.digest),depth:o,size:BigInt(c.digest.length),node:c.digest}}},PU=see;var aee=async(r,e,t,n,i,o,s,a)=>{let c=await s.get(r,a),l=f7(c);return qh(l,c,r,e,t,n,o)},RU=aee;var cee=r=>{async function*e(t={}){let{start:n,end:i}=jh(r.length,t.offset,t.length),o=uf(r,0n,n,i);t.onProgress?.(new X("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(r.byteLength)})),yield o}return e},lee=async(r,e,t,n,i,o,s,a)=>{if(n.length>0)throw new no(`No link named ${t} found in raw node ${r}`);let c=await s.get(r,a);return{entry:{type:"raw",name:e,path:t,cid:r,content:cee(c),depth:o,size:BigInt(c.length),node:c}}},DU=lee;var V8=mt(BU(),1);function uee(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var Uet=ul({name:"murmur3-32",code:35,encode:r=>uee(V8.default.x86.hash32(r))}),ff=ul({name:"murmur3-128",code:34,encode:r=>al.fromHex(V8.default.x64.hash128(r))}),Fet=ul({name:"murmur3-x64-64",code:34,encode:r=>al.fromHex(V8.default.x64.hash128(r)).subarray(0,8)});var UU=mt(K8(),1);var Ei=class r{_options;_popCount;_parent;_posAtParent;_children;key;constructor(e,t,n=0){this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new UU.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((i,o,s)=>(o!=null&&(o instanceof r?i.push(o.serialize(e,t)):i.push(e(o,s))),i),n))}async asyncTransform(e,t){return FU(this,e,t)}toJSON(){return this.serialize(mee,gee)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?D(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof r?i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(pee);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}};function pee(r){return!!r}function mee(r,e){return r.key}function gee(r){return r}async function FU(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof Ei)await FU(i,e,t);else{let o=await e(i);n.push({bitField:r._children.bitField(),children:o})}return t(n)}var yee=[255,254,252,248,240,224,192,128],wee=[1,3,7,15,31,63,127,255],z8=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=xee(i,o-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function xee(r,e,t){let n=bee(e,t);return(r&n)>>>e}function bee(r,e){return yee[r]&wee[Math.min(e+r-1,7)]}function $U(r){function e(t){return t instanceof q8?t:new q8(t,r)}return e}var q8=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Xe([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new z8(t);this._buffers.push(n),this._availableBits+=n.availableBits()}};function Wh(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:$U(r.hashFn)};return new Ei(e)}var vee=async function(r){return(await ff.encode(r)).slice(0,8).reverse()},Aee=async(r,e,t)=>{let n=(e.tableSize()-1).toString(16).length;await Promise.all(r.map(async i=>{if(i.Name==null)throw new Error("Unexpected Link without a Name");if(i.Name.length===n){let o=parseInt(i.Name,16);e._putObjectAt(o,new Ei({hash:t._options.hash,bits:t._options.bits},e,o));return}await t.put(i.Name.substring(2),!0)}))},HU=(r,e)=>r.toString(16).toUpperCase().padStart(e,"0").substring(0,e),Eee=r=>{let e=r.bucket,t=[];for(;e._parent!=null;)t.push(e),e=e._parent;return t.push(e),t.reverse()},VU=async(r,e,t,n,i)=>{if(n==null){if(r.Data==null)throw new Er("no data in PBNode");let f;try{f=_e.unmarshal(r.Data)}catch(h){throw new Er(h.message)}if(f.type!=="hamt-sharded-directory")throw new Er("not a HAMT");if(f.fanout==null)throw new Er("missing fanout");let d=Wh({hashFn:vee,bits:Math.log2(Number(f.fanout))});n={rootBucket:d,hamtDepth:1,lastBucket:d}}let o=(n.lastBucket.tableSize()-1).toString(16).length;await Aee(r.Links,n.lastBucket,n.rootBucket);let s=await n.rootBucket._findNewBucketAndPos(e),a=HU(s.pos,o),c=Eee(s);c.length>n.hamtDepth&&(n.lastBucket=c[n.hamtDepth],a=HU(n.lastBucket._posAtParent,o));let l=r.Links.find(f=>{if(f.Name==null)return!1;let d=f.Name.substring(0,o),h=f.Name.substring(o);return!(d!==a||h!==""&&h!==e)});if(l==null)return;if(l.Name!=null&&l.Name.substring(o)===e)return l.Hash;n.hamtDepth++;let u=await t.get(l.Hash,i);return r=nr(u),VU(r,e,t,n,i)},KU=VU;function Gh(r){return r?.extended===!1}var See=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=c.offset??0,u=c.length??e.Links.length,f=e.Links.slice(l,u);c.onProgress?.(new X("unixfs:exporter:walk:directory",{cid:r})),yield*vt(f,d=>zt(d,h=>async()=>{let m=h.Name??"",g=`${n}/${m}`;return Gh(c)?{cid:h.Hash,name:m,path:g}:(await i(h.Hash,m,g,[],o+1,s,c)).entry}),d=>Cn(d,{ordered:!0,concurrency:c.blockReadConcurrency}),d=>di(d,h=>h!=null))}return a},zU=See;async function qU(r,e,t,n,i,o,s){if(e instanceof Uint8Array){let l=uf(e,n,i,o);t.push(l);return}if(e.Data==null)throw new Er("no data in PBNode");let a;try{a=_e.unmarshal(e.Data)}catch(l){throw new Er(l.message)}if(a.data!=null){let l=a.data,u=uf(l,n,i,o);t.push(u),n+=BigInt(u.byteLength)}let c=[];if(e.Links.length!==a.blockSizes.length)throw new Er("Inconsistent block sizes and dag links");for(let l=0;l<e.Links.length;l++){let u=e.Links[l],f=n,d=f+a.blockSizes[l];if((i>=f&&i<d||o>=f&&o<=d||i<f&&o>d)&&c.push({link:u,blockStart:n}),n=d,n>o)break}await vt(c,l=>zt(l,u=>async()=>{let f=await r.get(u.link.Hash,s);return{...u,block:f}}),l=>Cn(l,{ordered:!0,concurrency:s.blockReadConcurrency}),async l=>{for await(let{link:u,block:f,blockStart:d}of l){let h;switch(u.Hash.code){case tt:h=nr(f);break;case At:h=f;break;default:t.end(new Er(`Unsupported codec: ${u.Hash.code}`));return}let m=new mo({concurrency:1});m.on("error",g=>{t.end(g)}),m.add(async()=>{s.onProgress?.(new X("unixfs:exporter:walk:file",{cid:u.Hash})),await qU(r,h,t,d,i,o,s)}),await m.onIdle()}}),n>=o&&t.end()}var _ee=(r,e,t,n,i,o,s)=>{async function*a(c={}){let l=t.fileSize();if(l===void 0)throw new Error("File was a directory");let{start:u,end:f}=jh(l,c.offset,c.length);if(f===0n)return;let d=0n,h=f-u,m=ar();c.onProgress?.(new X("unixfs:exporter:walk:file",{cid:r})),qU(s,e,m,0n,u,f,c).catch(g=>{m.end(g)});for await(let g of m)if(g!=null){if(d+=BigInt(g.byteLength),d>h)throw m.end(),new U8("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");d===h&&m.end(),c.onProgress?.(new X("unixfs:exporter:progress:unixfs:file",{bytesRead:d,totalBytes:h,fileSize:l})),yield g}if(d<h)throw new F8("Traversed entire DAG but did not read enough bytes")}return a},eS=_ee;var Cee=(r,e,t,n,i,o,s)=>{function a(c={}){return c.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:r})),jU(e,n,i,o,s,c)}return a};async function*jU(r,e,t,n,i,o){let s=r.Links;if(r.Data==null)throw new Er("no data in PBNode");let a;try{a=_e.unmarshal(r.Data)}catch(u){throw new Er(u.message)}if(a.fanout==null)throw new Er("missing fanout");let c=(a.fanout-1n).toString(16).length,l=vt(s,u=>zt(u,f=>async()=>{let d=f.Name!=null?f.Name.substring(c):null;if(d!=null&&d!==""){let h=`${e}/${d}`;return Gh(o)?{entries:[{cid:f.Hash,name:d,path:h}]}:{entries:[(await t(f.Hash,d,h,[],n+1,i,o)).entry].filter(Boolean)}}else{let h=await i.get(f.Hash,o);return r=nr(h),o.onProgress?.(new X("unixfs:exporter:walk:hamt-sharded-directory",{cid:f.Hash})),{entries:jU(r,e,t,n,i,o)}}}),u=>Cn(u,{ordered:!0,concurrency:o.blockReadConcurrency}));for await(let{entries:u}of l)yield*u}var WU=Cee;var Tee=(r,e)=>r.Links.find(n=>n.Name===e)?.Hash,Iee={raw:eS,file:eS,directory:zU,"hamt-sharded-directory":WU,metadata:(r,e,t,n,i,o,s)=>()=>[],symlink:(r,e,t,n,i,o,s)=>()=>[]},kee=async(r,e,t,n,i,o,s,a)=>{if(Gh(a)&&n.length===0)return{entry:{cid:r,name:e,path:t}};let c=await s.get(r,a),l=nr(c),u,f;if(e==null&&(e=r.toString()),l.Data==null)throw new Er("no data in PBNode");try{u=_e.unmarshal(l.Data)}catch(h){throw new Er(h.message)}if(t==null&&(t=e),n.length>0){let h;if(u?.type==="hamt-sharded-directory"?h=await KU(l,n[0],s):h=Tee(l,n[0]),h==null)throw new no("file does not exist");let m=n.shift(),g=`${t}/${m}`;f={cid:h,toResolve:n,name:m??"",path:g}}let d=Iee[u.type](r,l,u,t,i,o,s);if(d==null)throw new no("could not find content exporter");return u.isDirectory()?{entry:{type:"directory",name:e,path:t,cid:r,content:d,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}:{entry:{type:"file",name:e,path:t,cid:r,content:d,unixfs:u,depth:o,node:l,size:u.fileSize()},next:f}},GU=kee;var Pee={[tt]:GU,[At]:DU,[Mr]:IU,[xo]:kU,[lr.code]:PU,[Go]:RU},XU=async(r,e,t,n,i,o,s)=>{let a=Pee[r.code];if(a==null)throw new M8(`No resolver for code ${r.code}`);return a(r,e,t,n,XU,i,o,s)},YU=XU;var Ree=(r="")=>(r.trim().match(/([^\\^/]|\\\/)+/g)??[]).filter(Boolean),Dee=r=>{if(r instanceof Uint8Array)return{cid:G.decode(r),toResolve:[]};let e=G.asCID(r);if(e!=null)return{cid:e,toResolve:[]};if(typeof r=="string"){r.indexOf("/ipfs/")===0&&(r=r.substring(6));let t=Ree(r);return{cid:G.parse(t[0]),toResolve:t.slice(1)}}throw new L8(`Unknown path type ${r}`)};async function*j0(r,e,t={}){let{cid:n,toResolve:i}=Dee(r),o=n.toString(),s=o,a=i.length;for(;;){let c=await YU(n,o,s,i,a,e,t);if(c.entry==null&&c.next==null)throw new no(`Could not resolve ${r}`);if(c.entry!=null&&(yield c.entry),c.next==null)return;i=c.next.toResolve,n=c.next.cid,o=c.next.name,s=c.next.path}}async function xr(r,e,t={}){let n=await Ho(j0(r,e,t));if(n==null)throw new no(`Could not resolve ${r}`);return n}async function*Xh(r,e,t={}){let n=await xr(r,e,t);if(n==null)return;if(yield n,n.type==="directory")for await(let o of i(n,t))yield o;async function*i(o,s){for await(let a of o.content(s))yield a,!(a instanceof Uint8Array)&&a.type==="directory"&&(yield*i(a,s))}}async function Oee(r,e,t){let n=[],i;for await(let o of j0(e,r,t))n.push(o.cid),i=o;if(i==null)throw new Kh("No terminal element found");return{ipfsRoots:n,terminalElement:i}}function Yh(r){return r.type==="object"}async function QU({cid:r,path:e,resource:t,options:n,blockstore:i,log:o}){try{return await Oee(i,`${r.toString()}/${e}`,n)}catch(s){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return["ERR_NO_PROP","ERR_NO_TERMINAL_ELEMENT","ERR_NOT_FOUND"].includes(s.code)?A8(t):(o.error("error walking path %s",e,s),Hh(t,"Error walking path"))}}var j8=class extends kt{id="dag-cbor-plugin";codes=[Mr];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i,plugins:o}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||!Yh(n.terminalElement)||e.code!==Mr||i==null||t!=null&&t.includes("text/html")&&o.includes("dag-cbor-plugin-html-preview")?!1:Yh(n.terminalElement)}async handle(e){let{cid:t,path:n,resource:i,accept:o,pathDetails:{terminalElement:s,ipfsRoots:a}}=e;this.log.trace("fetching %c/%s",t,n);let c=s.node,l;if(o==="application/octet-stream"||o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")l=c;else if(o==="application/vnd.ipld.dag-json")try{let d=rs(c);l=cy(d)}catch(d){return this.log.error("could not transform %c to application/vnd.ipld.dag-json",d),Ra(i)}else try{l=TU(c)}catch(d){if(o==="application/json")return this.log('could not decode DAG-CBOR as JSON-safe, but the client sent "Accept: application/json"',d),Ra(i);this.log("could not decode DAG-CBOR as JSON-safe, falling back to `application/octet-stream`",d),l=c}e.byteRangeContext.setBody(l);let u=o??(l instanceof Uint8Array?"application/octet-stream":"application/json"),f=dn(i,e.byteRangeContext.getBody(u),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??u),this.log.trace('setting content type to "%s"',e.byteRangeContext.getContentType()??u),x8(f,a),f}};function Nee(r){return r[Symbol.asyncIterator]!=null}function Bee(r,e=1){return e=Number(e),Nee(r)?(async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})():(function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})()}var W8=Bee;async function*W0(r,e=1){for await(let t of W8(r,e)){let n=t.map(async i=>i().then(o=>({ok:!0,value:o}),o=>({ok:!1,err:o})));for(let i=0;i<n.length;i++){let o=await n[i];if(o.ok)yield o.value;else throw o.err}}}var Lee=262144,G0=(r={})=>{let e=r.chunkSize??Lee;return async function*(n){let i=new pe,o=0,s=!1;for await(let a of n)for(i.append(a),o+=a.length;o>=e;)if(yield i.slice(0,e),s=!0,e===i.length)i=new pe,o=0;else{let c=new pe;c.append(i.sublist(e)),i=c,o-=e}(!s||o>0)&&(yield i.subarray(0,o))}};var Vo=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await Be.digest(r),i=G.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,t),i};function ZU(r){return async function*(t,n){let i=0n;for await(let o of t.content)yield async()=>{let s,a={codec:ir,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Rn,a.cidVersion=1):(s=new _e({type:r.leafType,data:o}),o=Qe({Data:s.marshal(),Links:[]}));let c=await Vo(o,n,a);return i+=BigInt(o.byteLength),r.onProgress?.(new X("unixfs:importer:progress:file:write",{bytesWritten:i,cid:c,path:t.path})),{cid:c,unixfs:s,size:BigInt(o.length),block:o}}}}var G8=class r extends Error{static name="InvalidParametersError";static code="ERR_INVALID_PARAMS";name=r.name;code=r.code;constructor(e="Invalid parameters"){super(e)}};var Xc=class r extends Error{static name="InvalidContentError";static code="ERR_INVALID_CONTENT";name=r.name;code=r.code;constructor(e="Invalid content"){super(e)}};var JU=async(r,e,t)=>{let n=new _e({type:"directory",mtime:r.mtime,mode:r.mode}),i=Qe(Wt({Data:n.marshal()})),o=await Vo(i,e,t),s=r.path;return{cid:o,path:s,unixfs:n,size:BigInt(i.length),originalPath:r.originalPath,block:i}};async function*Mee(r,e,t){let n=-1,i;for await(let o of W0(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){i={...o,single:!0};continue}else n===1&&i!=null&&(yield{...i,block:void 0,single:void 0},i=void 0);yield{...o,block:void 0}}i!=null&&(yield i)}function eF(r){return r.single===!0}var Uee=(r,e,t)=>async function(i){if(i.length===1&&eF(i[0])&&t.reduceSingleLeafToSelf){let u=i[0],f=u.block;return eF(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new _e({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),f={Data:u.unixfs.marshal(),Links:[]},u.block=Qe(Wt(f)),u.cid=await Vo(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:u.cid,path:u.originalPath})),{cid:u.cid,path:r.path,unixfs:u.unixfs,size:u.size,originalPath:u.originalPath}}let o=new _e({type:"file",mtime:r.mtime,mode:r.mode}),s=i.filter(u=>u.cid.code===At&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===At?(o.addBlockSize(u.size),{Name:"",Tsize:Number(u.size),Hash:u.cid}):(u.unixfs?.data==null?o.addBlockSize(u.unixfs?.fileSize()??0n):o.addBlockSize(BigInt(u.unixfs.data.length)),{Name:"",Tsize:Number(u.size),Hash:u.cid})),a={Data:o.marshal(),Links:s},c=Qe(Wt(a)),l=await Vo(c,e,t);return t.onProgress?.(new X("unixfs:importer:progress:file:layout",{cid:l,path:r.originalPath})),{cid:l,path:r.path,unixfs:o,size:BigInt(c.length+a.Links.reduce((u,f)=>u+(f.Tsize??0),0)),originalPath:r.originalPath,block:c}},tF=async(r,e,t)=>t.layout(Mee(r,e,t),Uee(r,e,t));function Fee(r){return Symbol.iterator in r}function $ee(r){return Symbol.asyncIterator in r}function Hee(r){try{if(r instanceof Uint8Array)return(async function*(){yield r})();if(Fee(r))return(async function*(){yield*r})();if($ee(r))return r}catch{throw new Xc("Content was invalid")}throw new Xc("Content was invalid")}function rF(r){return async function*(t,n){for await(let i of t){let o;if(i.path!=null&&(o=i.path,i.path=i.path.split("/").filter(s=>s!=null&&s!==".").join("/")),Vee(i)){let s={path:i.path,mtime:i.mtime,mode:i.mode,content:(async function*(){let c=0n;for await(let l of r.chunker(r.chunkValidator(Hee(i.content)))){let u=BigInt(l.byteLength);c+=u,r.onProgress?.(new X("unixfs:importer:progress:file:read",{bytesRead:c,chunkSize:u,path:i.path})),yield l}})(),originalPath:o},a=r.fileBuilder??tF;yield async()=>a(s,n,r)}else if(i.path!=null){let s={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:o},a=r.dirBuilder??JU;yield async()=>a(s,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function Vee(r){return r.content!=null}var nF=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new Xc("Content was invalid");if(typeof t=="string"||t instanceof String)yield D(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new Xc("Content was invalid")}};var Kee=174;function X0(r){let e=r?.maxChildrenPerNode??Kee;return async function t(n,i){let o=[];for await(let s of W8(n,e))o.push(await i(s));return o.length>1?t(o,i):o[0]}}var bs=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},Y0=G.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),Q0=G.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var df=class extends bs{_children;constructor(e,t){super(e,t),this._children=new Map}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(e,t)}async get(e){return Promise.resolve(this._children.get(e))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}*eachChildSeries(){for(let[e,t]of this._children.entries())yield{key:e,child:t}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[e,t]of this._children.entries())t.size!=null&&t.cid!=null&&(this.nodeSize+=e.length+(this.options.cidVersion===1?Q0.bytes.byteLength:Y0.bytes.byteLength));return this.nodeSize}async*flush(e){let t=[];for(let[c,l]of this._children.entries()){let u=l;if(l instanceof bs)for await(let f of l.flush(e))u=f,yield f;u.size!=null&&u.cid!=null&&t.push({Name:c,Tsize:Number(u.size),Hash:u.cid})}let n=new _e({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:n.marshal(),Links:t},o=Qe(Wt(i)),s=await Vo(o,e,this.options),a=o.length+i.Links.reduce((c,l)=>c+(l.Tsize??0),0);this.cid=s,this.size=a,yield{cid:s,unixfs:n,path:this.path,size:BigInt(a)}}};async function zee(r){return(await ff.encode(r)).slice(0,8).reverse()}var iF=BigInt(34),qee=8,tS=class extends bs{_bucket;constructor(e,t){super(e,t),this._bucket=Wh({hashFn:zee,bits:t.shardFanoutBits??qee})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}*eachChildSeries(){for(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=aF(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of sF(this._bucket,e,this,this.options))yield{...t,path:this.path}}},oF=tS;async function*sF(r,e,t,n){let i=r._children,o=(r.tableSize()-1).toString(16).length,s=[],a=0n;for(let m=0;m<i.length;m++){let g=i.get(m);if(g==null)continue;let w=m.toString(16).toUpperCase().padStart(o,"0");if(g instanceof Ei){let x;for await(let v of sF(g,e,null,n))x=v;if(x==null)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:w,Tsize:Number(x.size),Hash:x.cid}),a+=x.size}else if(jee(g.value)){let x=g.value,v;for await(let S of x.flush(e))v=S,yield v;if(v==null)throw new Error("Did not flush dir");let A=w+g.key;s.push({Name:A,Tsize:Number(v.size),Hash:v.cid}),a+=v.size}else{let x=g.value;if(x.cid==null)continue;let v=w+g.key,A=x.size;s.push({Name:v,Tsize:Number(A),Hash:x.cid}),a+=BigInt(A??0)}}let c=Uint8Array.from(i.bitField().reverse()),l=new _e({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:iF,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:s},f=Qe(Wt(u)),d=await Vo(f,e,n),h=BigInt(f.byteLength)+a;yield{cid:d,unixfs:l,size:h}}function jee(r){return typeof r.flush=="function"}function aF(r,e,t){let n=r._children,i=(r.tableSize()-1).toString(16).length,o=[];for(let l=0;l<n.length;l++){let u=n.get(l);if(u==null)continue;let f=l.toString(16).toUpperCase().padStart(i,"0");if(u instanceof Ei){let d=aF(u,null,t);o.push({Name:f,Tsize:Number(d),Hash:t.cidVersion===0?Y0:Q0})}else if(typeof u.value.flush=="function"){let h=u.value.nodeSize();o.push({Name:f+u.key,Tsize:Number(h),Hash:t.cidVersion===0?Y0:Q0})}else{let d=u.value;if(d.cid==null)continue;let h=f+u.key,m=d.size;o.push({Name:h,Tsize:Number(m),Hash:d.cid})}}let s=Uint8Array.from(n.bitField().reverse()),a=new _e({type:"hamt-sharded-directory",data:s,fanout:BigInt(r.tableSize()),hashType:iF,mtime:e?.mtime,mode:e?.mode});return Qe(Wt({Data:a.marshal(),Links:o})).length}async function rS(r,e,t,n){let i=e;e instanceof df&&e.estimateNodeSize()>t&&(i=await Wee(e,n));let o=i.parent;if(o!=null){if(i!==e){if(r!=null&&(r.parent=i),i.parentKey==null)throw new Error("No parent key found");await o.put(i.parentKey,i)}return rS(i,o,t,n)}return i}async function Wee(r,e){let t=new oF({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},e);for(let{key:n,child:i}of r.eachChildSeries())await t.put(n,i);return t}var cF=(r="")=>r.split(/(?<!\\)\//).filter(Boolean);async function Gee(r,e,t){let n=cF(r.path??""),i=n.length-1,o=e,s="";for(let a=0;a<n.length;a++){let c=n[a];s+=`${s!==""?"/":""}${c}`;let l=a===i;if(o.dirty=!0,o.cid=void 0,o.size=void 0,l)await o.put(c,r),e=await rS(null,o,t.shardSplitThresholdBytes,t);else{let u=await o.get(c);(u==null||!(u instanceof bs))&&(u=new df({root:!1,dir:!0,parent:o,parentKey:c,path:s,dirty:!0,flat:!0,mtime:u?.unixfs?.mtime,mode:u?.unixfs?.mode},t)),await o.put(c,u),o=u}}return e}async function*lF(r,e){if(!(r instanceof bs)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function uF(r){return async function*(t,n){let i=new df({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),o,s=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(o==null?(o=c,s=!0):o!==c&&(s=!1)),i=await Gee(a,i,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||s&&i.childCount()>1)yield*lF(i,n);else for(let a of i.eachChildSeries())a!=null&&(yield*lF(a.child,n))}}async function*hf(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let i=t.wrapWithDirectory??!1,o=t.shardSplitThresholdBytes??262144,s=t.shardFanoutBits??8,a=t.cidVersion??1,c=t.rawLeaves??!0,l=t.leafType??"file",u=t.fileImportConcurrency??50,f=t.blockWriteConcurrency??10,d=t.reduceSingleLeafToSelf??!0,h=t.chunker??G0(),m=t.chunkValidator??nF(),g=t.dagBuilder??rF({chunker:h,chunkValidator:m,wrapWithDirectory:i,layout:t.layout??X0(),bufferImporter:t.bufferImporter??ZU({cidVersion:a,rawLeaves:c,leafType:l,onProgress:t.onProgress}),blockWriteConcurrency:f,reduceSingleLeafToSelf:d,cidVersion:a,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),w=t.treeBuilder??uF({wrapWithDirectory:i,shardSplitThresholdBytes:o,shardFanoutBits:s,cidVersion:a,onProgress:t.onProgress});for await(let x of w(W0(g(n,e),u),e))yield{cid:x.cid,path:x.path,unixfs:x.unixfs,size:x.size}}async function fF(r,e,t={}){let n=await Ad(hf([r],e,t));if(n==null)throw new G8("Nothing imported");return n}async function dF(r,e,t={}){return fF({content:r},e,t)}async function hF(r,e,t={}){return fF({content:r},e,t)}var Z0={cidVersion:1,rawLeaves:!0,layout:X0({maxChildrenPerNode:1024}),chunker:G0({chunkSize:1048576})};async function*X8(r,e,t={}){yield*hf(r,e,{...Z0,...t})}async function pF(r,e,t={}){let{cid:n}=await dF(r,e,{...Z0,...t});return n}async function mF(r,e,t={}){let{cid:n}=await hF(r,e,{...Z0,...t});return n}async function gF(r,e,t={}){if(r.path==null)throw new Ar("path is required");if(r.content==null)throw new Ar("content is required");let n=await Ho(X8([r],e,{...Z0,...t,wrapWithDirectory:!0}));if(n==null)throw new Ar("Nothing imported");return n.cid}async function yF(r,e,t={}){if(r.content!=null)throw new Ar("Directories cannot have content, use addFile instead");let i=await(r.path==null?Ad:Ho)(X8([{...r,path:r.path??"-"}],e,{...Z0,...t,wrapWithDirectory:r.path!=null}));if(i==null)throw new Ar("Nothing imported");return i.cid}var sS=mt(K8(),1);function Q8(r){function e(t){return t instanceof Y8?t:new Y8(t,r)}return e}var Y8=class{_value;_hashFn;_depth;_availableBits;_currentBufferIndex;_buffers;constructor(e,t){if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let i=this._buffers[this._currentBufferIndex],o=Math.min(i.availableBits(),t),s=i.take(o);n=(n<<o)+s,t-=o,this._availableBits-=o,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?Xe([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new nS(t);this._buffers.push(n),this._availableBits+=n.availableBits()}},Xee=[255,254,252,248,240,224,192,128],Yee=[1,3,7,15,31,63,127,255],nS=class{_value;_currentBytePos;_currentBitPos;constructor(e){this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],o=this._currentBitPos+1,s=Math.min(o,t),a=Qee(i,o-s,s);n=(n<<s)+a,t-=s,this._currentBitPos-=s,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function Qee(r,e,t){let n=Zee(e,t);return(r&n)>>>e}function Zee(r,e){return Xee[r]&Yee[Math.min(e+r-1,7)]}var J0=BigInt(ff.code),pf=8;async function Qh(r){return(await ff.encode(r)).subarray(0,8).reverse()}var bF=mt(K8(),1);var Ko=async(r,e,t)=>{t.codec==null&&(t.codec=ir);let n=await Be.digest(r),i=G.create(t.cidVersion,t.codec.code,n);return await e.put(i,r,{...t,signal:t.signal}),i};var iS=class{options;root;dir;path;dirty;flat;parent;parentKey;unixfs;mode;mtime;cid;size;nodeSize;constructor(e,t){this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}},Z8=class extends iS{_bucket;constructor(e,t){super(e,t),this._bucket=Wh({hashFn:Qh,bits:8})}async put(e,t){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(e,t)}async get(e){return this._bucket.get(e)}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}async*eachChildSeries(){for(let{key:e,value:t}of this._bucket.eachLeafSeries())yield{key:e,child:t}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=xF(this._bucket,this,this.options),this.nodeSize)}async*flush(e){for await(let t of wF(this._bucket,e,this,this.options))yield{...t,path:this.path}}};async function*wF(r,e,t,n){let i=r._children,o=[],s=0n;for(let h=0;h<i.length;h++){let m=i.get(h);if(m==null)continue;let g=h.toString(16).toUpperCase().padStart(2,"0");if(m instanceof Ei){let w;for await(let x of wF(m,e,null,n))w=x;if(w==null)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:g,Tsize:Number(w.size),Hash:w.cid}),s+=w.size}else if(Jee(m.value)){let w=m.value,x;for await(let A of w.flush(e))x=A,yield x;if(x==null)throw new Error("Did not flush dir");let v=g+m.key;o.push({Name:v,Tsize:Number(x.size),Hash:x.cid}),s+=x.size}else{let w=m.value;if(w.cid==null)continue;let x=g+m.key,v=w.size;o.push({Name:x,Tsize:Number(v),Hash:w.cid}),s+=BigInt(v??0)}}let a=Uint8Array.from(i.bitField().reverse()),c=new _e({type:"hamt-sharded-directory",data:a,fanout:BigInt(r.tableSize()),hashType:J0,mtime:t?.mtime,mode:t?.mode}),l={Data:c.marshal(),Links:o},u=Qe(Wt(l)),f=await Ko(u,e,n),d=BigInt(u.byteLength)+s;yield{cid:f,unixfs:c,size:d}}function Jee(r){return typeof r.flush=="function"}function xF(r,e,t){let n=r._children,i=[];for(let c=0;c<n.length;c++){let l=n.get(c);if(l==null)continue;let u=c.toString(16).toUpperCase().padStart(2,"0");if(l instanceof Ei){let f=xF(l,null,t);i.push({Name:u,Tsize:Number(f),Hash:t.cidVersion===0?J8:ew})}else if(typeof l.value.flush=="function"){let d=l.value.nodeSize();i.push({Name:u+l.key,Tsize:Number(d),Hash:t.cidVersion===0?J8:ew})}else{let f=l.value;if(f.cid==null)continue;let d=u+l.key,h=f.size;i.push({Name:d,Tsize:Number(h),Hash:f.cid})}}let o=Uint8Array.from(n.bitField().reverse()),s=new _e({type:"hamt-sharded-directory",data:o,fanout:BigInt(r.tableSize()),hashType:J0,mtime:e?.mtime,mode:e?.mode});return Qe(Wt({Data:s.marshal(),Links:i})).length}var J8=G.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),ew=G.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");var oS=Ue("helia:unixfs:commands:utils:hamt-utils"),tw=r=>r.toString(16).toUpperCase().padStart(2,"0").substring(0,2),vF=async(r,e,t)=>{let n=new Z8({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:t.mtime,mode:t.mode},t);for(let o=0;o<e.length;o++)await n._bucket.put(e[o].name,{size:e[o].size,cid:e[o].cid});let i=await Ho(n.flush(r));if(i==null)throw new Error("Flushing shard yielded no result");return i},rw=async(r,e,t)=>{let n=_e.unmarshal(r[0].node.Data??new Uint8Array(0)),i=BigInt(Math.pow(2,pf));r.reverse();let o,s;for(let a=0;a<r.length;a++){let c=a===r.length-1,l=r[a],u=Uint8Array.from(l.children.bitField().reverse()),f=new _e({type:"hamt-sharded-directory",data:u,fanout:i,hashType:J0});c&&(f.mtime=n.mtime,f.mode=n.mode),s={Data:f.marshal(),Links:l.node.Links};let d=Qe(Wt(s));if(o=await Ko(d,e,t),!c){let h=r[a+1];if(h==null)throw new Error("Was not operating on shard root but also had no parent?");oS("updating link in parent sub-shard with prefix %s",h.prefix),h.node.Links=h.node.Links.filter(m=>m.Name!==h.prefix),h.node.Links.push({Name:h.prefix,Hash:o,Tsize:l.node.Links.reduce((m,g)=>m+(g.Tsize??0),d.byteLength)})}}if(o==null||s==null)throw new Error("Noting persisted");return{cid:o,node:s}},nw=async(r,e,t,n)=>{let o=Q8(Qh)(D(e)),s=[];for(;;){let a=await t.get(r,n),c=nr(a),l=new bF.default,u=await o.take(pf),f=tw(u);s.push({prefix:f,children:l,node:c});let d;for(let m of c.Links){let g=m.Name??"";if(g.length<2)throw new Error("Invalid HAMT - link name was too short");let w=parseInt(g.substring(0,2),16);l.set(w,!0),g.startsWith(f)&&(d=m)}if(d==null){oS("no link found with prefix %s for %s",f,e);break}let h=d.Name??"";if(h.length<2)throw new Error("Invalid HAMT - link name was too short");if(h.length===2){r=d.Hash,oS("descend into sub-shard with prefix %s",h);continue}break}return{path:s,hash:o}};async function iw(r,e,t,n){if(r.Data==null)throw new Error("DagPB node had no data");let i=_e.unmarshal(r.Data),o;if(i.type==="directory")o=ete(r);else if(i.type==="hamt-sharded-directory")o=await AF(r,0,t,e,n);else throw new Error("Can only estimate the size of directories or shards");return o>t}function ete(r){let e=0;for(let t of r.Links)e+=(t.Name??"").length,e+=t.Hash.version===1?ew.bytes.byteLength:J8.bytes.byteLength;return e}async function AF(r,e,t,n,i){if(e>t)return t;if(r.Data==null||!_e.unmarshal(r.Data).isDirectory())return e;for(let s of r.Links){let a=s.Name??"";if(a=a.substring(2),e+=a.length,e+=s.Hash.bytes.byteLength,s.Hash.code===tt){let c=await n.get(s.Hash,i),l=nr(c);e+=await AF(l,e,t,n,i)}}return e}var vs=Ue("helia:unixfs:components:utils:add-link");async function Zh(r,e,t,n){if(r.node.Data==null)throw new Ar("Invalid parent passed to addLink");if(_e.unmarshal(r.node.Data).type==="hamt-sharded-directory")return vs("adding link to sharded directory"),nte(r,e,t,n);vs(`adding ${e.Name} (${e.Hash}) to regular directory`);let o=await rte(r,e,t,n);if(await iw(o.node,t,n.shardSplitThresholdBytes,n)){vs("converting directory to sharded directory");let s=await tte(o,t);o.cid=s.cid,o.node=nr(await t.get(s.cid,n))}return o}var tte=async(r,e)=>{if(r.node.Data==null)throw new Ar("Invalid parent passed to convertToShardedDirectory");let t=_e.unmarshal(r.node.Data),n=await vF(e,r.node.Links.map(i=>({name:i.Name??"",size:BigInt(i.Tsize??0),cid:i.Hash})),{mode:t.mode,mtime:t.mtime,cidVersion:r.cid.version});return vs(`converted directory to sharded directory ${n.cid}`),n},rte=async(r,e,t,n)=>{let i=r.node.Links.filter(u=>{let f=u.Name===e.Name;if(f&&!n.allowOverwriting)throw new z0;return!f});if(i.push(e),r.node.Data==null)throw new Xn("Parent node with no data passed to addToDirectory");let o=_e.unmarshal(r.node.Data),s;if(o.mtime!=null){let u=Date.now(),f=Math.floor(u/1e3);o.mtime={secs:BigInt(f),nsecs:(u-f*1e3)*1e3},s=o.marshal()}else s=r.node.Data;r.node=Wt({Data:s,Links:i});let a=Qe(r.node),c=await Be.digest(a),l=G.create(r.cid.version,tt,c);return await t.put(l,a),{node:r.node,cid:l}},nte=async(r,e,t,n)=>{let{path:i,hash:o}=await nw(r.cid,e.Name,t,n),s=i[i.length-1];if(s==null)throw new Error("Invalid HAMT, could not generate path");let a=s.prefix,c=parseInt(a,16);vs("next prefix for %s is %s",e.Name,a);let l=`${a}${e.Name}`,u=s.node.Links.find(f=>(f.Name??"").startsWith(a));if(u!=null)if(vs("link %s was present in shard",l),u.Name===l){if(!n.allowOverwriting)throw new z0;vs("overwriting %s in sub-shard",e.Name),s.node.Links=s.node.Links.filter(f=>f.Name!==l),s.node.Links.push({Name:l,Hash:e.Hash,Tsize:e.Tsize})}else{if(u.Name?.length===2)throw new Error("Existing link was sub-shard?!");{vs("prefix %s already exists, creating new sub-shard",a);let f=s.node.Links.findIndex(w=>w.Name?.startsWith(a)),d=s.node.Links.splice(f,1)[0],h=(d.Name??"").substring(2),g=Q8(Qh)(D(h));for(let w=0;w<i.length;w++)await g.take(pf);for(;;){let w=await g.take(pf),x=tw(w);d.Name=`${x}${h}`;let v=await o.take(pf),A=tw(v);if(x===A){let M=new sS.default;M.set(v,!0),i.push({prefix:A,children:M,node:{Links:[]}});continue}let S=new sS.default;S.set(v,!0),S.set(w,!0),i.push({prefix:a,children:S,node:{Links:[d,{Name:`${A}${e.Name}`,Hash:e.Hash,Tsize:e.Tsize}]}});break}}}else vs("link %s was not present in sub-shard",l),e.Name=l,s.node.Links.push(e),s.children.set(c,!0),vs("adding %s to existing sub-shard",l);return rw(i,t,n)};async function Yc(r,e,t={}){let n=await xr(r,e,t);if(n.type!=="directory")throw new Gc(`${r.toString()} was not a UnixFS directory`);return{cid:r,node:n.node}}async function Jh(r,e,t,n){let i=await xr(r,t,n);if(i.type!=="directory"&&i.type!=="file"&&i.type!=="raw")throw new Ai(`${r.toString()} was not a UnixFS node`);return{Name:e,Tsize:i.node instanceof Uint8Array?i.node.byteLength:ite(i.node),Hash:r}}function ite(r){let e=r.Links.reduce((t,n)=>t+(n.Tsize??0),0);return Qe(r).byteLength+e}var ote=Ue("helia:unixfs:components:utils:resolve");async function As(r,e,t,n){if(e==null||e==="")return{cid:r};let i=`/ipfs/${r}${e==null?"":`/${e}`}`,o=await oa(j0(i,t,n));if(o.length===0)throw new Kh("Could not find path in directory");return ote("resolved %s to %c",e,r),{cid:o[o.length-1].cid,path:e,segments:o}}async function ep(r,e,t,n){if(e.segments==null||e.segments.length===0)return r;let i=e.segments.pop();if(i==null)throw new Error("Insufficient segments");i.cid=r,e.segments.reverse();for(let o of e.segments){let[s,a]=await Promise.all([Yc(o.cid,t,n),Jh(i.cid,i.name,t,n)]);r=(await Zh(s,a,t,{...n,allowOverwriting:!0,cidVersion:r.version})).cid,o.cid=r,i=o}return r}var ste=Gt.bind({ignoreUndefined:!0}),ate={};async function*EF(r,e,t={}){let n=ste(ate,t),i=await As(r,n.path,e,n),o=await xr(i.cid,e,n);if(o.type!=="file"&&o.type!=="raw")throw new B8;if(o.content==null)throw new zh;yield*o.content(n)}var cte=Gt.bind({ignoreUndefined:!0}),lte=Ue("helia:unixfs:chmod"),ute={recursive:!1,shardSplitThresholdBytes:262144};async function SF(r,e,t,n={}){let i=cte(ute,n),o=await As(r,i.path,t,n);if(lte("chmod %c %d",o.cid,e),i.recursive){let d=await vt(async function*(){for await(let h of Xh(o.cid,t,n)){let m,g=[];if(h.type==="raw")m=new _e({type:"file",data:h.node});else if(h.type==="file"||h.type==="directory")m=h.unixfs,g=h.node.Links;else throw new Ai;m.mode=e;let w={Data:m.marshal(),Links:g};yield{path:h.path,content:w}}},h=>hf(h,t,{...i,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,v=Qe(x),A=await Ko(v,g,{...i,cidVersion:r.version});if(x.Data==null)throw new Xn(`${A} had no data`);let S=_e.unmarshal(x.Data);return{cid:A,size:BigInt(v.length),path:w.path,unixfs:S}}}}),async h=>Ho(h));if(d==null)throw new Wc(`Could not chmod ${o.cid.toString()}`);return ep(d.cid,o,t,i)}let s=await t.get(o.cid,n),a,c=[];if(o.cid.code===At)a=new _e({type:"file",data:s});else{let d=nr(s);if(d.Data==null)throw new Xn(`${o.cid.toString()} had no data`);c=d.Links,a=_e.unmarshal(d.Data)}a.mode=e;let l=Qe({Data:a.marshal(),Links:c}),u=await Be.digest(l),f=G.create(o.cid.version,tt,u);return await t.put(f,l),ep(f,o,t,i)}var fte=Gt.bind({ignoreUndefined:!0}),dte=Ue("helia:unixfs:cp"),hte={force:!1,shardSplitThresholdBytes:262144};async function _F(r,e,t,n,i={}){let o=fte(hte,i);if(t.includes("/"))throw new Ar("Name must not have slashes");let[s,a]=await Promise.all([Yc(e,n,o),Jh(r,t,n,o)]);return dte('Adding %c as "%s" to %c',r,t,e),(await Zh(s,a,n,{allowOverwriting:o.force,cidVersion:e.version,...o})).cid}var pte=Gt.bind({ignoreUndefined:!0}),mte={};async function*CF(r,e,t={}){let n=pte(mte,t),i=await As(r,n.path,e,n),o=await xr(i.cid,e,{...t,extended:!0});if(o.type==="file"||o.type==="raw"){t.extended===!1?yield{name:o.name,path:o.path,cid:o.cid}:yield o;return}if(o.content==null)throw new zh;if(o.type!=="directory")throw new Gc;yield*o.content(t)}var gte=Gt.bind({ignoreUndefined:!0}),TF=Ue("helia:unixfs:mkdir"),yte={cidVersion:1,force:!1,shardSplitThresholdBytes:262144};async function IF(r,e,t,n={}){let i=gte(yte,n);if(e.includes("/"))throw new Ar("Path must not have slashes");if((await xr(r,t,n)).type!=="directory")throw new Gc(`${r.toString()} was not a UnixFS directory`);TF("creating %s",e);let a={Data:new _e({type:"directory",mode:i.mode,mtime:i.mtime}).marshal(),Links:[]},c=Qe(a),l=await Be.digest(c),u=G.create(i.cidVersion,tt,l);await t.put(u,c);let[f,d]=await Promise.all([Yc(r,t,i),Jh(u,e,t,i)]);return TF("adding empty dir called %s to %c",e,r),(await Zh(f,d,t,{...i,allowOverwriting:i.force})).cid}var sw=Ue("helia:unixfs:utils:remove-link");async function kF(r,e,t,n){if(r.node.Data==null)throw new Xn("Parent node had no data");if(_e.unmarshal(r.node.Data).type==="hamt-sharded-directory"){sw(`removing ${e} from sharded directory`);let o=await xte(r,e,t,n);return await iw(o.node,t,n.shardSplitThresholdBytes,n)?o:(sw("converting shard to flat directory %c",r.cid),bte(o,t,n))}return sw(`removing link ${e} regular directory`),wte(r,e,t,n)}var wte=async(r,e,t,n)=>{r.node.Links=r.node.Links.filter(s=>s.Name!==e);let i=Qe(r.node),o=await Ko(i,t,{...n,cidVersion:r.cid.version});return sw(`Updated regular directory ${o}`),{node:r.node,cid:o}},xte=async(r,e,t,n)=>{let{path:i}=await nw(r.cid,e,t,n),o=i[i.length-1];if(o==null)throw new Error("Invalid HAMT, could not generate path");let s=o.node.Links.filter(l=>(l.Name??"").substring(2)===e).map(l=>l.Name).pop();if(s==null)throw new Error("File not found");let a=s.substring(0,2),c=parseInt(a,16);if(o.node.Links=o.node.Links.filter(l=>l.Name!==s),o.children.unset(c),o.node.Links.length===1)for(;i.length!==1;){let l=i[i.length-1];if(l==null||l.node.Links.length>1)break;i.pop();let u=i[i.length-1];if(u==null)break;let f=l.node.Links[0];u.node.Links=u.node.Links.filter(d=>!(d.Name??"").startsWith(u.prefix)),u.node.Links.push({Hash:f.Hash,Name:`${u.prefix}${(f.Name??"").substring(2)}`,Tsize:f.Tsize})}return rw(i,t,n)},bte=async(r,e,t)=>{if(r.node.Data==null)throw new Ar("Invalid parent passed to convertToFlatDirectory");let n={Links:[]},i=await xr(r.cid,e);if(i.type!=="directory")throw new Error("Unexpected node type");for await(let c of i.content()){let l=0;c.node instanceof Uint8Array?l=c.node.byteLength:l=Qe(c.node).length,n.Links.push({Hash:c.cid,Name:c.name,Tsize:l})}let o=_e.unmarshal(r.node.Data);n.Data=new _e({type:"directory",mode:o.mode,mtime:o.mtime}).marshal();let s=Qe(Wt(n));return{cid:await Ko(s,e,{codec:ir,cidVersion:r.cid.version,signal:t.signal}),node:n}};var vte=Gt.bind({ignoreUndefined:!0}),Ate=Ue("helia:unixfs:rm"),Ete={shardSplitThresholdBytes:262144};async function PF(r,e,t,n={}){let i=vte(Ete,n);if(e.includes("/"))throw new Ar("Name must not have slashes");let o=await Yc(r,t,i);return Ate("Removing %s from %c",e,r),(await kF(o,e,t,{...i,cidVersion:r.version})).cid}var RF=1877,aw=1604,Ste=Gt.bind({ignoreUndefined:!0}),_te=Ue("helia:unixfs:stat"),Cte={};async function DF(r,e,t={}){let n=Ste(Cte,t),i=await As(r,t.path,e,n);_te("stat %c",i.cid);let o=await xr(i.cid,e,n);if(o.type==="raw")return t.extended===!0?Pte(o):kte(o);if(o.type==="file"||o.type==="directory")return t.extended===!0?Ite(o,e,t.filter??new td({filterSize:1024}),t):Tte(o);throw new Ai}function Tte(r){return{type:r.type,cid:r.cid,unixfs:r.unixfs,mode:r.unixfs.mode??(r.unixfs.isDirectory()?RF:aw),mtime:r.unixfs.mtime,size:r.unixfs.fileSize()}}async function Ite(r,e,t,n){let i=await OF(r.cid,e,!1,t,n);return{type:r.type,cid:r.cid,unixfs:r.unixfs,size:r.unixfs.isDirectory()?i.dirSize:r.unixfs.fileSize(),mode:r.unixfs.mode??(r.unixfs.isDirectory()?RF:aw),mtime:r.unixfs.mtime,localSize:i.localSize,dagSize:i.dagSize,deduplicatedDagSize:i.deduplicatedDagSize,blocks:i.blocks,uniqueBlocks:i.uniqueBlocks}}function kte(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:aw,mtime:void 0,size:BigInt(r.node.byteLength)}}function Pte(r){return{type:r.type,cid:r.cid,unixfs:void 0,mode:aw,mtime:void 0,size:BigInt(r.node.byteLength),localSize:BigInt(r.node.byteLength),dagSize:BigInt(r.node.byteLength),deduplicatedDagSize:BigInt(r.node.byteLength),blocks:1n,uniqueBlocks:1n}}async function OF(r,e,t,n,i){let o={dirSize:0n,localSize:0n,dagSize:0n,deduplicatedDagSize:0n,blocks:0n,uniqueBlocks:0n};try{let s=n.has(r.bytes);n.add(r.bytes);let a=await e.get(r,i);if(o.blocks++,o.dagSize+=BigInt(a.byteLength),s||(o.uniqueBlocks++,o.deduplicatedDagSize+=BigInt(a.byteLength)),r.code===At)o.localSize+=BigInt(a.byteLength),t&&(o.dirSize+=BigInt(a.byteLength));else if(r.code===tt){let c=nr(a),l;if(c.Data!=null&&(l=_e.unmarshal(c.Data)),c.Links.length>0){for(let u of c.Links){let f=await OF(u.Hash,e,Rte(u,l),n,i);o.localSize+=f.localSize,o.dagSize+=f.dagSize,o.deduplicatedDagSize+=f.deduplicatedDagSize,o.blocks+=f.blocks,o.uniqueBlocks+=f.uniqueBlocks,o.dirSize+=f.dirSize}t&&l!=null&&(o.dirSize+=l.fileSize())}else{if(l==null)throw new Xn(`PBNode ${r.toString()} had no data`);l.data!=null&&(o.localSize+=BigInt(l.data.byteLength??0)),t&&(o.dirSize+=l.fileSize())}}else throw new Wc(`${r.toString()} was neither DAG_PB nor RAW`)}catch(s){if(s.name!=="NotFoundError"||i.offline!==!0)throw s}return o}function Rte(r,e){if(e==null)return!1;let t=r.Name;return t==null?!1:e.type==="directory"?!0:e.type==="hamt-sharded-directory"&&t.length>2}var Dte=Gt.bind({ignoreUndefined:!0}),Ote=Ue("helia:unixfs:touch"),Nte={recursive:!1,shardSplitThresholdBytes:262144};async function NF(r,e,t={}){let n=Dte(Nte,t),i=await As(r,n.path,e,n),o=n.mtime??{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(Ote("touch %c %o",i.cid,o),n.recursive){let d=await vt(async function*(){for await(let h of Xh(i.cid,e)){let m,g;if(h.type==="raw")m=new _e({data:h.node}),g=[];else if(h.type==="file"||h.type==="directory")m=h.unixfs,g=h.node.Links;else throw new Ai;m.mtime=o;let w={Data:m.marshal(),Links:g};yield{path:h.path,content:w}}},h=>hf(h,e,{...n,dagBuilder:async function*(m,g){for await(let w of m)yield async function(){let x=w.content,v=Qe(x),A=await Ko(v,g,{...n,cidVersion:r.version});if(x.Data==null)throw new Xn(`${A} had no data`);let S=_e.unmarshal(x.Data);return{cid:A,size:BigInt(v.length),path:w.path,unixfs:S}}}}),async h=>Ho(h));if(d==null)throw new Wc(`Could not chmod ${i.cid.toString()}`);return ep(d.cid,i,e,n)}let s=await e.get(i.cid,t),a,c=[];if(i.cid.code===At)a=new _e({data:s});else{let d=nr(s);if(c=d.Links,d.Data==null)throw new Xn(`${i.cid.toString()} had no data`);a=_e.unmarshal(d.Data)}a.mtime=o;let l=Qe({Data:a.marshal(),Links:c}),u=await Be.digest(l),f=G.create(i.cid.version,tt,u);return await e.put(f,l),ep(f,i,e,n)}var cw=class{components;constructor(e){this.components=e}async*addAll(e,t={}){yield*X8(e,this.components.blockstore,t)}async addBytes(e,t={}){return pF(e,this.components.blockstore,t)}async addByteStream(e,t={}){return mF(e,this.components.blockstore,t)}async addFile(e,t={}){return gF(e,this.components.blockstore,t)}async addDirectory(e={},t={}){return yF(e,this.components.blockstore,t)}async*cat(e,t={}){yield*EF(e,this.components.blockstore,t)}async chmod(e,t,n={}){return SF(e,t,this.components.blockstore,n)}async cp(e,t,n,i={}){return _F(e,t,n,this.components.blockstore,i)}async*ls(e,t={}){yield*CF(e,this.components.blockstore,t)}async mkdir(e,t,n={}){return IF(e,t,this.components.blockstore,n)}async rm(e,t,n={}){return PF(e,t,this.components.blockstore,n)}async stat(e,t={}){return DF(e,this.components.blockstore,t)}async touch(e,t={}){return NF(e,this.components.blockstore,t)}};function BF(r){return new cw(r)}var UF=mt(LF(),1);var cS={128:"\u20AC",130:"\u201A",131:"\u0192",132:"\u201E",133:"\u2026",134:"\u2020",135:"\u2021",136:"\u02C6",137:"\u2030",138:"\u0160",139:"\u2039",140:"\u0152",142:"\u017D",145:"\u2018",146:"\u2019",147:"\u201C",148:"\u201D",149:"\u2022",150:"\u2013",151:"\u2014",152:"\u02DC",153:"\u2122",154:"\u0161",155:"\u203A",156:"\u0153",158:"\u017E",159:"\u0178"},Bte={};for(let[r,e]of Object.entries(cS))Bte[e]=Number.parseInt(r);function MF(r,e="utf-8"){switch(e.toLowerCase()){case"utf-8":case"utf8":return typeof globalThis.TextDecoder<"u"?new globalThis.TextDecoder("utf-8").decode(r):Lte(r);case"utf-16le":return Mte(r);case"ascii":return Ute(r);case"latin1":case"iso-8859-1":return Fte(r);case"windows-1252":return $te(r);default:throw new RangeError(`Encoding '${e}' not supported`)}}function Lte(r){let e="",t=0;for(;t<r.length;){let n=r[t++];if(n<128)e+=String.fromCharCode(n);else if(n<224){let i=r[t++]&63;e+=String.fromCharCode((n&31)<<6|i)}else if(n<240){let i=r[t++]&63,o=r[t++]&63;e+=String.fromCharCode((n&15)<<12|i<<6|o)}else{let i=r[t++]&63,o=r[t++]&63,s=r[t++]&63,a=(n&7)<<18|i<<12|o<<6|s;a-=65536,e+=String.fromCharCode(55296+(a>>10&1023),56320+(a&1023))}}return e}function Mte(r){let e="";for(let t=0;t<r.length;t+=2)e+=String.fromCharCode(r[t]|r[t+1]<<8);return e}function Ute(r){return String.fromCharCode(...r.map(e=>e&127))}function Fte(r){return String.fromCharCode(...r)}function $te(r){let e="";for(let t of r)t>=128&&t<=159&&cS[t]?e+=cS[t]:e+=String.fromCharCode(t);return e}function Yn(r){return new DataView(r.buffer,r.byteOffset)}var FF={len:1,get(r,e){return Yn(r).getUint8(e)},put(r,e,t){return Yn(r).setUint8(e,t),e+1}},Ut={len:2,get(r,e){return Yn(r).getUint16(e,!0)},put(r,e,t){return Yn(r).setUint16(e,t,!0),e+2}},tp={len:2,get(r,e){return Yn(r).getUint16(e)},put(r,e,t){return Yn(r).setUint16(e,t),e+2}};var sr={len:4,get(r,e){return Yn(r).getUint32(e,!0)},put(r,e,t){return Yn(r).setUint32(e,t,!0),e+4}},$F={len:4,get(r,e){return Yn(r).getUint32(e)},put(r,e,t){return Yn(r).setUint32(e,t),e+4}};var HF={len:4,get(r,e){return Yn(r).getInt32(e)},put(r,e,t){return Yn(r).setInt32(e,t),e+4}};var VF={len:8,get(r,e){return Yn(r).getBigUint64(e,!0)},put(r,e,t){return Yn(r).setBigUint64(e,t,!0),e+8}};var Qn=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){let n=e.subarray(t,t+this.len);return MF(n,this.encoding)}};var Vte="End-Of-Stream",Ft=class extends Error{constructor(){super(Vte),this.name="EndOfStreamError"}},mf=class extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var gf=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new Ft;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");let o=Math.min(i.length,t);e.set(i.subarray(0,o),n),n+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new mf;let i=await this.readFromStream(e.subarray(n),t);if(i===0)break;n+=i}if(!t&&n<e.length)throw new Ft;return n}};var lw=class extends gf{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}};var eg=class extends lw{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}};var rp=class extends gf{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let i=await this.reader.read();if(i.done){this.endOfStream=!0;break}i.value&&(n+=this.writeChunk(e.subarray(n),i.value))}if(!t&&n===0&&this.endOfStream)throw new Ft;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function lS(r){try{let e=r.getReader({mode:"byob"});return e instanceof ReadableStreamDefaultReader?new rp(e):new eg(e)}catch(e){if(e instanceof TypeError)return new rp(r.getReader());throw e}}var Qc=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new Ft;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new Ft;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ft;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ft;return e.get(this.numBuffer,0)}async ignore(e){if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}};var zte=256e3,uw=class extends Qc{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),i=n.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let o=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<n.length)throw new Ft;return o}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=0;if(n.position){let o=n.position-this.position;if(o>0){let s=new Uint8Array(n.length+o);return i=await this.peekBuffer(s,{mayBeLess:n.mayBeLess}),e.set(s.subarray(o)),i-o}if(o<0)throw new Error("Cannot peek from a negative offset in a stream")}if(n.length>0){try{i=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(o){if(t?.mayBeLess&&o instanceof Ft)return 0;throw o}if(!n.mayBeLess&&i<n.length)throw new Ft}return i}async ignore(e){let t=Math.min(zte,e),n=new Uint8Array(t),i=0;for(;i<e;){let o=e-i,s=await this.readBuffer(n,{length:Math.min(t,o)});if(s<0)return s;i+=s}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}};var fw=class extends Qc{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&i<n.length)throw new Ft;return e.set(this.uint8Array.subarray(n.position,n.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function KF(r,e){let t=lS(r),n=e??{},i=n.onClose;return n.onClose=async()=>{if(await t.close(),i)return i()},new uw(t,n)}function zF(r,e){return new fw(r,e)}var _i=Uint8Array,np=Uint16Array,jte=Int32Array,qF=new _i([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),jF=new _i([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Wte=new _i([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),WF=function(r,e){for(var t=new np(31),n=0;n<31;++n)t[n]=e+=1<<r[n-1];for(var i=new jte(t[30]),n=1;n<30;++n)for(var o=t[n];o<t[n+1];++o)i[o]=o-t[n]<<5|n;return{b:t,r:i}},GF=WF(qF,2),XF=GF.b,Gte=GF.r;XF[28]=258,Gte[258]=28;var YF=WF(jF,0),Xte=YF.b,sat=YF.r,dS=new np(32768);for(ut=0;ut<32768;++ut)Da=(ut&43690)>>1|(ut&21845)<<1,Da=(Da&52428)>>2|(Da&13107)<<2,Da=(Da&61680)>>4|(Da&3855)<<4,dS[ut]=((Da&65280)>>8|(Da&255)<<8)>>1;var Da,ut,tg=(function(r,e,t){for(var n=r.length,i=0,o=new np(e);i<n;++i)r[i]&&++o[r[i]-1];var s=new np(e);for(i=1;i<e;++i)s[i]=s[i-1]+o[i-1]<<1;var a;if(t){a=new np(1<<e);var c=15-e;for(i=0;i<n;++i)if(r[i])for(var l=i<<4|r[i],u=e-r[i],f=s[r[i]-1]++<<u,d=f|(1<<u)-1;f<=d;++f)a[dS[f]>>c]=l}else for(a=new np(n),i=0;i<n;++i)r[i]&&(a[i]=dS[s[r[i]-1]++]>>15-r[i]);return a}),rg=new _i(288);for(ut=0;ut<144;++ut)rg[ut]=8;var ut;for(ut=144;ut<256;++ut)rg[ut]=9;var ut;for(ut=256;ut<280;++ut)rg[ut]=7;var ut;for(ut=280;ut<288;++ut)rg[ut]=8;var ut,QF=new _i(32);for(ut=0;ut<32;++ut)QF[ut]=5;var ut;var Yte=tg(rg,9,1);var Qte=tg(QF,5,1),uS=function(r){for(var e=r[0],t=1;t<r.length;++t)r[t]>e&&(e=r[t]);return e},zo=function(r,e,t){var n=e/8|0;return(r[n]|r[n+1]<<8)>>(e&7)&t},fS=function(r,e){var t=e/8|0;return(r[t]|r[t+1]<<8|r[t+2]<<16)>>(e&7)},Zte=function(r){return(r+7)/8|0},Jte=function(r,e,t){return(e==null||e<0)&&(e=0),(t==null||t>r.length)&&(t=r.length),new _i(r.subarray(e,t))};var ere=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Si=function(r,e,t){var n=new Error(e||ere[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,Si),!t)throw n;return n},hS=function(r,e,t,n){var i=r.length,o=n?n.length:0;if(!i||e.f&&!e.l)return t||new _i(0);var s=!t,a=s||e.i!=2,c=e.i;s&&(t=new _i(i*3));var l=function(Ci){var hn=t.length;if(Ci>hn){var io=new _i(Math.max(hn*2,Ci));io.set(t),t=io}},u=e.f||0,f=e.p||0,d=e.b||0,h=e.l,m=e.d,g=e.m,w=e.n,x=i*8;do{if(!h){u=zo(r,f,1);var v=zo(r,f+1,3);if(f+=3,v)if(v==1)h=Yte,m=Qte,g=9,w=5;else if(v==2){var F=zo(r,f,31)+257,N=zo(r,f+10,15)+4,R=F+zo(r,f+5,31)+1;f+=14;for(var _=new _i(R),$=new _i(19),V=0;V<N;++V)$[Wte[V]]=zo(r,f+V*3,7);f+=N*3;for(var H=uS($),E=(1<<H)-1,T=tg($,H,1),V=0;V<R;){var C=T[zo(r,f,E)];f+=C&15;var A=C>>4;if(A<16)_[V++]=A;else{var O=0,j=0;for(A==16?(j=3+zo(r,f,3),f+=2,O=_[V-1]):A==17?(j=3+zo(r,f,7),f+=3):A==18&&(j=11+zo(r,f,127),f+=7);j--;)_[V++]=O}}var Q=_.subarray(0,F),U=_.subarray(F);g=uS(Q),w=uS(U),h=tg(Q,g,1),m=tg(U,w,1)}else Si(1);else{var A=Zte(f)+4,S=r[A-4]|r[A-3]<<8,M=A+S;if(M>i){c&&Si(0);break}a&&l(d+S),t.set(r.subarray(A,M),d),e.b=d+=S,e.p=f=M*8,e.f=u;continue}if(f>x){c&&Si(0);break}}a&&l(d+131072);for(var Z=(1<<g)-1,te=(1<<w)-1,q=f;;q=f){var O=h[fS(r,f)&Z],Te=O>>4;if(f+=O&15,f>x){c&&Si(0);break}if(O||Si(2),Te<256)t[d++]=Te;else if(Te==256){q=f,h=null;break}else{var Ne=Te-254;if(Te>264){var V=Te-257,se=qF[V];Ne=zo(r,f,(1<<se)-1)+XF[V],f+=se}var Le=m[fS(r,f)&te],Ke=Le>>4;Le||Si(3),f+=Le&15;var U=Xte[Ke];if(Ke>3){var se=jF[Ke];U+=fS(r,f)&(1<<se)-1,f+=se}if(f>x){c&&Si(0);break}a&&l(d+131072);var ft=d+Ne;if(d<U){var He=o-U,st=Math.min(U,ft);for(He+d<0&&Si(3);d<st;++d)t[d]=n[He+d]}for(;d<ft;++d)t[d]=t[d-U]}}e.l=h,e.p=q,e.b=d,e.f=u,h&&(u=1,e.m=g,e.d=m,e.n=w)}while(!u);return d!=t.length&&s?Jte(t,0,d):t.subarray(0,d)};var tre=new _i(0);var rre=function(r){(r[0]!=31||r[1]!=139||r[2]!=8)&&Si(6,"invalid gzip data");var e=r[3],t=10;e&4&&(t+=(r[10]|r[11]<<8)+2);for(var n=(e>>3&1)+(e>>4&1);n>0;n-=!r[t++]);return t+(e&2)},nre=function(r){var e=r.length;return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0};var ire=function(r,e){return((r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31)&&Si(6,"invalid zlib data"),(r[1]>>5&1)==+!e&&Si(6,"invalid zlib data: "+(r[1]&32?"need":"unexpected")+" dictionary"),(r[1]>>3&4)+2};function ore(r,e){return hS(r,{i:2},e&&e.out,e&&e.dictionary)}function sre(r,e){var t=rre(r);return t+8>r.length&&Si(6,"invalid gzip data"),hS(r.subarray(t,-8),{i:2},e&&e.out||new _i(nre(r)),e&&e.dictionary)}function are(r,e){return hS(r.subarray(ire(r,e&&e.dictionary),-4),{i:2},e&&e.out,e&&e.dictionary)}function ZF(r,e){return r[0]==31&&r[1]==139&&r[2]==8?sre(r,e):(r[0]&15)!=8||r[0]>>4>7||(r[0]<<8|r[1])%31?ore(r,e):are(r,e)}var cre=typeof TextDecoder<"u"&&new TextDecoder,lre=0;try{cre.decode(tre,{stream:!0}),lre=1}catch{}var a$=mt(n$(),1);var wf={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},pS={get(r){let e=Ut.get(r,6);return{signature:sr.get(r,0),compressedSize:sr.get(r,8),uncompressedSize:sr.get(r,12)}},len:16},i$={get(r){let e=Ut.get(r,6);return{signature:sr.get(r,0),minVersion:Ut.get(r,4),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,8),compressedSize:sr.get(r,18),uncompressedSize:sr.get(r,22),filenameLength:Ut.get(r,26),extraFieldLength:Ut.get(r,28),filename:null}},len:30},o$={get(r){return{signature:sr.get(r,0),nrOfThisDisk:Ut.get(r,4),nrOfThisDiskWithTheStart:Ut.get(r,6),nrOfEntriesOnThisDisk:Ut.get(r,8),nrOfEntriesOfSize:Ut.get(r,10),sizeOfCd:sr.get(r,12),offsetOfStartOfCd:sr.get(r,16),zipFileCommentLength:Ut.get(r,20)}},len:22},s$={get(r){let e=Ut.get(r,8);return{signature:sr.get(r,0),minVersion:Ut.get(r,6),dataDescriptor:!!(e&8),compressedMethod:Ut.get(r,10),compressedSize:sr.get(r,20),uncompressedSize:sr.get(r,24),filenameLength:Ut.get(r,28),extraFieldLength:Ut.get(r,30),fileCommentLength:Ut.get(r,32),relativeOffsetOfLocalHeader:sr.get(r,42),filename:null}},len:46};function c$(r){let e=new Uint8Array(sr.len);return sr.put(e,0,r),e}var Es=(0,a$.default)("tokenizer:inflate"),mS=256*1024,Are=c$(wf.DataDescriptor),pw=c$(wf.EndOfCentralDirectory),mw=class{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(mS)}async isZip(){return await this.peekSignature()===wf.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(sr)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let i=n.length-4;i>=0;i--)if(n[i]===pw[0]&&n[i+1]===pw[1]&&n[i+2]===pw[2]&&n[i+3]===pw[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){Es("Cannot reading central-directory without random-read support");return}Es("Reading central-directory...");let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Es("Central-directory 32-bit signature found");let n=await this.tokenizer.readToken(o$,t),i=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let o=0;o<n.nrOfEntriesOfSize;++o){let s=await this.tokenizer.readToken(s$);if(s.signature!==wf.CentralFileHeader)throw new Error("Expected Central-File-Header signature");s.filename=await this.tokenizer.readToken(new Qn(s.filenameLength,"utf-8")),await this.tokenizer.ignore(s.extraFieldLength),await this.tokenizer.ignore(s.fileCommentLength),i.push(s),Es(`Add central-directory file-entry: n=${o+1}/${i.length}: filename=${i[o].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let i=await this.readLocalFileHeader();if(!i)break;let o=e(i);n=!!o.stop;let s;if(await this.tokenizer.ignore(i.extraFieldLength),i.dataDescriptor&&i.compressedSize===0){let a=[],c=mS;Es("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let l=-1;for(;l<0&&c===mS;){c=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),l=Ere(this.syncBuffer.subarray(0,c),Are);let u=l>=0?l:c;if(o.handler){let f=new Uint8Array(u);await this.tokenizer.readBuffer(f),a.push(f)}else await this.tokenizer.ignore(u)}Es(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),o.handler&&await this.inflate(i,Sre(a),o.handler)}else o.handler?(Es(`Reading compressed-file-data: ${i.compressedSize} bytes`),s=new Uint8Array(i.compressedSize),await this.tokenizer.readBuffer(s),await this.inflate(i,s,o.handler)):(Es(`Ignoring compressed-file-data: ${i.compressedSize} bytes`),await this.tokenizer.ignore(i.compressedSize));if(Es(`Reading data-descriptor at pos=${this.tokenizer.position}`),i.dataDescriptor&&(await this.tokenizer.readToken(pS)).signature!==134695760)throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-pS.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let i=t(n);if(i.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let o=await this.readLocalFileHeader();if(o){await this.tokenizer.ignore(o.extraFieldLength);let s=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(s),await this.inflate(o,s,i.handler)}}if(i.stop)break}}inflate(e,t,n){if(e.compressedMethod===0)return n(t);Es(`Decompress filename=${e.filename}, compressed-size=${t.length}`);let i=ZF(t);return n(i)}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(sr);if(e===wf.LocalFileHeader){let t=await this.tokenizer.readToken(i$);return t.filename=await this.tokenizer.readToken(new Qn(t.filenameLength,"utf-8")),t}if(e===wf.CentralFileHeader)return!1;throw e===3759263696?new Error("Encrypted ZIP"):new Error("Unexpected signature")}};function Ere(r,e){let t=r.length,n=e.length;if(n>t)return-1;for(let i=0;i<=t-n;i++){let o=!0;for(let s=0;s<n;s++)if(r[i+s]!==e[s]){o=!1;break}if(o)return i}return-1}function Sre(r){let e=r.reduce((i,o)=>i+o.length,0),t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var gat={utf8:new globalThis.TextDecoder("utf8")};var yat=new globalThis.TextEncoder;var wat=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function gS(r){let{byteLength:e}=r;if(e===6)return r.getUint16(0)*2**32+r.getUint32(2);if(e===5)return r.getUint8(0)*2**32+r.getUint32(1);if(e===4)return r.getUint32(0);if(e===3)return r.getUint8(0)*2**16+r.getUint16(1);if(e===2)return r.getUint16(0);if(e===1)return r.getUint8(0)}function _re(r,e){let t=r.length,n=e.length;if(n===0||n>t)return-1;let i=t-n;for(let o=0;o<=i;o++){let s=!0;for(let a=0;a<n;a++)if(r[o+a]!==e[a]){s=!1;break}if(s)return o}return-1}function l$(r,e){return _re(r,e)!==-1}function u$(r){return[...r].map(e=>e.charCodeAt(0))}function f$(r,e=0){let t=Number.parseInt(new Qn(6).get(r,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(t))return!1;let n=256;for(let i=e;i<e+148;i++)n+=r[i];for(let i=e+156;i<e+512;i++)n+=r[i];return t===n}var d$={get:(r,e)=>r[e+3]&127|r[e+2]<<7|r[e+1]<<14|r[e]<<21,len:4};var h$=["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"],p$=["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/x-flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"];var yS=4100;async function m$(r){return new xS().fromBuffer(r)}function wS(r){switch(r.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:"application/vnd.oasis.opendocument.text-template"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:"application/vnd.oasis.opendocument.spreadsheet-template"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:"application/vnd.oasis.opendocument.presentation-template"};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:"application/vnd.oasis.opendocument.graphics"};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:"application/vnd.oasis.opendocument.graphics-template"};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:"application/vnd.openxmlformats-officedocument.presentationml.slideshow"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.template"};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.template"};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:"application/vnd.openxmlformats-officedocument.presentationml.template"};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"};default:}}function Ss(r,e,t){t={offset:0,...t};for(let[n,i]of e.entries())if(t.mask){if(i!==(t.mask[n]&r[n+t.offset]))return!1}else if(i!==r[n+t.offset])return!1;return!0}var xS=class{constructor(e){this.detectors=[...e?.customDetectors??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:e?.signal}}async fromTokenizer(e){let t=e.position;for(let n of this.detectors){let i=await n.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(zF(t,this.tokenizerOptions))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){let t=await KF(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){let{sampleSize:n=yS}=t,i,o,s=e.getReader({mode:"byob"});try{let{value:l,done:u}=await s.read(new Uint8Array(n));if(o=l,!u&&l)try{i=await this.fromBuffer(l.slice(0,n))}catch(f){if(!(f instanceof Ft))throw f;i=void 0}o=l}finally{s.releaseLock()}let a=new TransformStream({async start(l){l.enqueue(o)},transform(l,u){u.enqueue(l)}}),c=e.pipeThrough(a);return c.fileType=i,c}check(e,t){return Ss(this.buffer,e,t)}checkString(e,t){return this.check(u$(e),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(yS),e.fileInfo.size===void 0&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);let t=await e.readToken(d$);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let t;return await new mw(e).unzip(n=>{switch(n.filename){case"META-INF/mozilla.rsa":return t={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return t={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(i){let o=new TextDecoder("utf-8").decode(i).trim();t=wS(o)},stop:!0};case"[Content_Types].xml":return{async handler(i){let o=new TextDecoder("utf-8").decode(i),s=o.indexOf('.main+xml"');if(s===-1){let a="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";o.includes(`ContentType="${a}"`)&&(t=wS(a))}else{o=o.slice(0,Math.max(0,s));let a=o.lastIndexOf('"'),c=o.slice(Math.max(0,a+1));t=wS(c)}},stop:!0};default:return/classes\d*\.dex/.test(n.filename)?(t={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),t??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),Ss(t,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Ss(t,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Ss(t,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Ss(t,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Ss(t,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Ss(t,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/x-flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF")){try{if(await e.ignore(1350)===1350){let i=new Uint8Array(Math.min(10485760,e.fileInfo.size-1350));if(await e.readBuffer(i,{mayBeLess:!0}),l$(i,new TextEncoder().encode("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}}catch(t){if(!(t instanceof Ft))throw t}return{ext:"pdf",mime:"application/pdf"}}if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){let t=await this.readTiffHeader(!1);if(t)return t}if(this.check([77,77])){let t=await this.readTiffHeader(!0);if(t)return t}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function t(){let a=await e.peekNumber(FF),c=128,l=0;for(;(a&c)===0&&c!==0;)++l,c>>=1;let u=new Uint8Array(l+1);return await e.readBuffer(u),u}async function n(){let a=await t(),c=await t();c[0]^=128>>c.length-1;let l=Math.min(6,c.length),u=new DataView(a.buffer),f=new DataView(c.buffer,c.length-l,l);return{id:gS(u),len:gS(f)}}async function i(a){for(;a>0;){let c=await n();if(c.id===17026)return(await e.readToken(new Qn(c.len))).replaceAll(/\00.*$/g,"");await e.ignore(c.len),--a}}let o=await n();switch(await i(o.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1"))return{ext:"parquet",mime:"application/x-parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){let t=new Qn(4,"latin1").get(this.buffer,2);if(t.match("^d*")&&t>=1e3&&t<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>"))return await e.ignore(8),await e.readToken(new Qn(13,"ascii"))==="debian-binary"?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"};if(this.checkString("WEBVTT")&&[`
|
|
95
|
-
`,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(HF),type:await e.readToken(new Qn(4,"latin1"))}}do{let n=await t();if(n.length<0)return;switch(n.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new Qn(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let n=new Uint8Array(16);return await e.readBuffer(n),{id:n,size:Number(await e.readToken(VF))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),i=n.size-24;if(Ss(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let o=new Uint8Array(16);if(i-=await e.readBuffer(o),Ss(o,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Ss(o,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(i)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Qn(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.slice(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),f$(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(yS),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?tp:Ut);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?tp:Ut);for(let n=0;n<t;++n){let i=await this.readTiffTag(e);if(i)return i}}async readTiffHeader(e){let t=(e?tp:Ut).get(this.buffer,2),n=(e?$F:sr).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let o=(e?tp:Ut).get(this.buffer,8),s=(e?tp:Ut).get(this.buffer,10);if(o===28&&s===254||o===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}},Tat=new Set(h$),Iat=new Set(p$);var Zc=Ue("helia:verified-fetch:content-type-parser"),gw="application/octet-stream";function Cre(r){return Zc("checking for svg"),/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function Tre(r){Zc("checking for json");try{return JSON.parse(r),!0}catch(e){return Zc("failed to parse as json",e),!1}}function Ire(r){Zc("checking for text");let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function kre(r){return Zc("checking for html"),/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function g$(r,e){Zc("contentTypeParser called for fileName: %s, byte size=%s",e,r.length);let t=(await m$(r))?.mime;if(t!=null)return Zc("detectedType: %s",t),t;if(Zc("no detectedType"),e==null){let n=Ire(r);return n!=null?Cre(n)?"image/svg+xml":await Tre(n)?"application/json":await kre(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":gw}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return gw}}function y$(r){return r?.then!=null}async function ng({bytes:r,path:e,contentTypeParser:t,log:n,defaultContentType:i="application/octet-stream",filename:o}){let s;if(t!=null)try{let a;o==null?(a=e.split("/").pop()?.trim(),a=a===""||a?.split(".").length===1?void 0:a):a=o;let c=t(r,a);if(y$(c)){let l=await c;l!=null&&(s=l)}else c!=null&&(s=c);n.trace("contentTypeParser returned %s",s)}catch(a){n.error("error parsing content type",a)}return s===gw&&(s=i),s??i}async function bS(r,e,t,n){let i=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),o=r[Symbol.asyncIterator](),{value:s,done:a}=await o.next();if(a===!0)throw i.error("no content found for path",e),new g8;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await o.next();if(n?.signal?.aborted){l.error(new Je(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var yw=class extends kt{id="dag-pb-plugin";codes=[tt];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||i==null?!1:e.code===tt}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let o=new URL(t.toString());return o.pathname.endsWith("/")?null:(o.pathname=`${o.pathname}/`,o.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:i=!1,pathDetails:o,query:s}=e,{handleServerTiming:a,contentTypeParser:c,helia:l,getBlockstore:u}=this.pluginOptions,f=this.log,d=e.resource,h=e.path,m=!1,g=e.byteRangeContext,w=o.ipfsRoots,x=o.terminalElement,v=x.cid,A=BF({...l,blockstore:u(e.cid,e.resource,n?.session??!0,n)});if(x?.type==="directory"){let S=x.cid,M=this.getRedirectUrl(e);if(M!=null){if(f.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw f('could not redirect to %s as redirect option was set to "error"',M),new TypeError("Failed to fetch");if(n?.redirect==="manual")return f("returning 301 permanent redirect to %s",M),U0(d,M);f("following redirect to %s",M),d=M,m=!0}let F="index.html";try{f.trace("found directory at %c/%s, looking for index.html",t,h);let N=await a("exporter-dir","",async()=>xr(`/ipfs/${S}/${F}`,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i);f.trace("found root file at %c/%s with cid %c",S,F,N.cid),h=F,v=N.cid}catch(N){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);this.log.error("error loading path %c/%s",S,F,N),e.isDirectory=!0,e.directoryEntries=[],e.modified++,this.log.trace("attempting to get directory entries because index.html was not found");try{for await(let R of A.ls(S,{signal:n?.signal,onProgress:n?.onProgress}))e.directoryEntries.push(R);return null}catch(R){return f.error("error listing directory %c",S,R),v8("Unable to get directory contents")}}finally{n?.onProgress?.(new X("verified-fetch:request:end",{cid:S,path:F}))}}try{let S=await A.stat(v,{extended:!0,signal:AbortSignal.timeout(500)});g.setFileSize(S.size)}catch(S){f.error("error getting exact file size for %c/%s - %e",t,h,S),g.setFileSize(o.terminalElement.size),f.trace("using terminal element size of %d for %c/%s",o.terminalElement.size,t,h)}try{let S=await a("exporter-file","",async()=>xr(v,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i),M,F;if(g.isValidRangeRequest)F=await this.handleRangeRequest(e,S);else{let R=S.content({signal:n?.signal,onProgress:n?.onProgress});f("got async iterator for %c/%s",t,h);let _=await a("stream-and-chunk","",async()=>bS(R,h??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),i),$=_.stream;M=_.firstChunk,F=await a("get-content-type","",async()=>ng({filename:s.filename,bytes:M,path:h,contentTypeParser:c,log:f}),i),g.setBody($)}let N=dn(d,g.getBody(F),{byteRangeContext:g,log:f},{redirected:m});return N.headers.set("Content-Type",g.getContentType()??F),x8(N,w),N}catch(S){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return f.error("error streaming %c/%s",t,h,S),g.isRangeRequest&&S.code==="ERR_INVALID_PARAMS"?$h(d):Hh(d.toString(),"Unable to stream content")}}async handleRangeRequest(e,t){let{path:n,byteRangeContext:i,options:o,withServerTiming:s=!1}=e,{handleServerTiming:a,contentTypeParser:c}=this.pluginOptions,l=this.log,u=t.content({signal:o?.signal,onProgress:o?.onProgress,offset:0,length:8192}),{firstChunk:f}=await bS(u,n??"",this.pluginOptions.logger,{onProgress:o?.onProgress,signal:o?.signal}),d=await a("get-content-type","",async()=>ng({bytes:f,path:n,contentTypeParser:c,log:l}),s);return i?.setBody(h=>{if(o?.signal?.aborted)throw new Je(o?.signal?.reason??"aborted while streaming");return t.content({signal:o?.signal,onProgress:o?.onProgress,offset:h.start??0,length:i.getLength(h)})},d),d}};var ww=class extends kt{id="dag-walk-plugin";canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===tt||n.code===Mr}async handle(e){let{cid:t,resource:n,options:i,withServerTiming:o=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,i?.session??!0,i),l=await a("path-walking","",async()=>QU({...e,blockstore:c,log:this.log}),o);return l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.modified++,e.pathDetails=l,null)}};function xw(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?gt(r):vn(G.parse(r))}var ig=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},Oa=class extends ig{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var bw=class extends kt{id="ipns-record-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:i}=e,{helia:o}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new Oa("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:M0(t,new Error("Invalid IPNS name"))});let s;try{let d;t.startsWith("ipns://")?d=t.replace("ipns://",""):t.includes("/ipns/")?d=t.split("/ipns/")[1].split("/")[0].split("?")[0]:d=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',d),s=xw(d)}catch(d){throw this.log.error("could not parse peer id from IPNS url %s",t,d),new Oa("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:M0(t,d)})}let a=Xe([D("/ipns/"),s.toMultihash().bytes]),c=new it("/dht/record/"+z(a,"base32"),!1),l=await o.datastore.get(c,i),u=Mt.deserialize(l);e.byteRangeContext.setBody(u.value);let f=dn(t,e.byteRangeContext.getBody("application/vnd.ipfs.ipns-record"),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??"application/vnd.ipfs.ipns-record"),f}};var vw=class extends kt{id="json-plugin";codes=[xo,Go];canHandle({cid:e,accept:t,byteRangeContext:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:t==="application/vnd.ipld.dag-json"&&e.code!==Mr?!0:xo===e.code||Go===e.code}async handle(e){let{path:t,resource:n,cid:i,accept:o,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",i,t);let l=e.pathDetails?.terminalElement.cid??e.cid,f=await a(l,n,c,s).get(l,s),d;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let g=ud(f);d=cd(g)}catch(g){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",g),Ra(n)}else d=f;let h;o==null?xo===i.code?h="application/vnd.ipld.dag-json":h="application/json":h=o.split(";")[0],e.byteRangeContext.setBody(d);let m=dn(n,e.byteRangeContext.getBody(h),{byteRangeContext:e.byteRangeContext,log:this.log});return m.headers.set("content-type",e.byteRangeContext.getContentType()??h),e.byteRangeContext.isValidRangeRequest||m.headers.set("content-length",d.length.toString()),m}};var Pre=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function Rre({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(i=>i.split(";")[0]).map(i=>i.trim());for(let i of n){if(i==="*/*")return;if(Pre.includes(i??""))return i}}var Aw=class extends kt{id="raw-plugin";codes=[At,lr.code];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:i,accept:o,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,f=this.log;if(o==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${i.toString()}.bin`,f.trace("Set content disposition...")):f.trace("Did NOT set content disposition..."),t!==""&&i.code===At)throw f.trace("404-ing raw codec request for %c/%s",i,t),new Oa("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:A8(n,"Raw codec does not support paths")});let d=e.pathDetails?.terminalElement.cid??e.cid,m=await c(d,n,u,a).get(d,a);e.byteRangeContext.setBody(m);let g=await ng({filename:s.filename,bytes:m,path:t,defaultContentType:Rre({headers:a?.headers,accept:o}),contentTypeParser:l,log:f}),w=dn(n,e.byteRangeContext.getBody(g),{byteRangeContext:e.byteRangeContext,log:f},{redirected:!1});return w.headers.set("content-type",e.byteRangeContext.getContentType()??g),w}};var Dre=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",Ore=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function Jc({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:i,contentPrefix:o}){let s=Dre({weak:t,reqFormat:e}),a=Ore({reqFormat:e});return(n!=null||i!=null)&&(a+=`.${n??"0"}-${i??"N"}`),`${s}"${o??""}${r.toString()}${a}"`}var Oct=D("ustar\0","binary"),Nct=D("ustar ","binary"),Bct=D(" \0","binary");var A$=mt(x$(),1);function Bre(r){return r[Symbol.asyncIterator]!=null}function Lre(r){if(Bre(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Xe([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Xe(e,t)}var b$=Lre;var Mre="0000000000000000000",Ure="7777777777777777777",Fre=48,$re=D("ustar\0","binary"),Hre=D("00","binary"),Vre=parseInt("7777",8),Kre=257,zre=263,qre=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},jre=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},el=function(r,e){let t=r.toString(8);return t.length>e?D(Ure.slice(0,e)+" "):D(Mre.slice(0,e-t.length)+t+" ")},vS=function(r){let e=D(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function v$(r){let e="";r.name!=null&&(e+=vS(" path="+r.name+`
|
|
95
|
+
`,"\r"," "," ","\0"].some(t=>this.checkString(t,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){await e.ignore(8);async function t(){return{length:await e.readToken(HF),type:await e.readToken(new Qn(4,"latin1"))}}do{let n=await t();if(n.length<0)return;switch(n.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(n.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/x-apache-arrow"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&(this.buffer[8]&96)!==0){let t=new Qn(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(t){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return t.startsWith("3g")?t.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function t(){let n=new Uint8Array(16);return await e.readBuffer(n),{id:n,size:Number(await e.readToken(VF))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){let n=await t(),i=n.size-24;if(Ss(n.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let o=new Uint8Array(16);if(i-=await e.readBuffer(o),Ss(o,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Ss(o,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(i)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10]))switch(await e.ignore(20),await e.readToken(new Qn(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){let t=new DataView(this.buffer.buffer).getUint32(12,!0);if(t>12&&this.buffer.length>=t+16)try{let n=new TextDecoder().decode(this.buffer.slice(16,t+16));if(JSON.parse(n).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),f$(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"}};detectImprecise=async e=>{if(this.buffer=new Uint8Array(yS),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]})?{ext:"aac",mime:"audio/aac"}:{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}};async readTiffTag(e){let t=await this.tokenizer.readToken(e?tp:Ut);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"};default:}}async readTiffIFD(e){let t=await this.tokenizer.readToken(e?tp:Ut);for(let n=0;n<t;++n){let i=await this.readTiffTag(e);if(i)return i}}async readTiffHeader(e){let t=(e?tp:Ut).get(this.buffer,2),n=(e?$F:sr).get(this.buffer,4);if(t===42){if(n>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(n>=8){let o=(e?tp:Ut).get(this.buffer,8),s=(e?tp:Ut).get(this.buffer,10);if(o===28&&s===254||o===31&&s===11)return{ext:"nef",mime:"image/x-nikon-nef"}}}return await this.tokenizer.ignore(n),await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(t===43)return{ext:"tif",mime:"image/tiff"}}},Tat=new Set(h$),Iat=new Set(p$);var Zc=Ue("helia:verified-fetch:content-type-parser"),gw="application/octet-stream";function Cre(r){return Zc("checking for svg"),/^(<\?xml[^>]+>)?[^<^\w]+<svg/ig.test(r)}async function Tre(r){Zc("checking for json");try{return JSON.parse(r),!0}catch(e){return Zc("failed to parse as json",e),!1}}function Ire(r){Zc("checking for text");let e=new TextDecoder("utf-8",{fatal:!0});try{return e.decode(r)}catch{return null}}async function kre(r){return Zc("checking for html"),/^\s*<(?:!doctype\s+html|html|head|body)\b/i.test(r)}async function g$(r,e){Zc("contentTypeParser called for fileName: %s, byte size=%s",e,r.length);let t=(await m$(r))?.mime;if(t!=null)return Zc("detectedType: %s",t),t==="application/xml"&&e?.toLowerCase().endsWith(".svg")?"image/svg+xml":t;if(Zc("no detectedType"),e==null){let n=Ire(r);return n!=null?Cre(n)?"image/svg+xml":await Tre(n)?"application/json":await kre(n)?"text/html; charset=utf-8":"text/plain; charset=utf-8":gw}switch(e.split(".").pop()){case"css":return"text/css";case"html":return"text/html; charset=utf-8";case"js":return"application/javascript";case"json":return"application/json";case"txt":return"text/plain";case"woff2":return"font/woff2";case"svg":return"image/svg+xml";case"csv":return"text/csv";case"doc":return"application/msword";case"xls":return"application/vnd.ms-excel";case"ppt":return"application/vnd.ms-powerpoint";case"msi":return"application/x-msdownload";default:return gw}}function y$(r){return r?.then!=null}async function ng({bytes:r,path:e,contentTypeParser:t,log:n,defaultContentType:i="application/octet-stream",filename:o}){let s;if(t!=null)try{let a;o==null?(a=e.split("/").pop()?.trim(),a=a===""||a?.split(".").length===1?void 0:a):a=o;let c=t(r,a);if(y$(c)){let l=await c;l!=null&&(s=l)}else c!=null&&(s=c);n.trace("contentTypeParser returned %s",s)}catch(a){n.error("error parsing content type",a)}return s===gw&&(s=i),s??i}async function bS(r,e,t,n){let i=t.forComponent("helia:verified-fetch:get-stream-from-async-iterable"),o=r[Symbol.asyncIterator](),{value:s,done:a}=await o.next();if(a===!0)throw i.error("no content found for path",e),new g8;return{stream:new ReadableStream({async start(l){n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(s)},async pull(l){let{value:u,done:f}=await o.next();if(n?.signal?.aborted){l.error(new Je(n.signal.reason??"signal aborted by user")),l.close();return}if(f===!0){u!=null&&(n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)),l.close();return}n?.onProgress?.(new X("verified-fetch:request:progress:chunk")),l.enqueue(u)}}),firstChunk:s}}var yw=class extends kt{id="dag-pb-plugin";codes=[tt];canHandle({cid:e,accept:t,pathDetails:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),n==null||i==null?!1:e.code===tt}getRedirectUrl(e){let{resource:t,path:n}=e;if(n===""?!t.toString().endsWith("/"):!n.endsWith("/"))try{let o=new URL(t.toString());return o.pathname.endsWith("/")?null:(o.pathname=`${o.pathname}/`,o.toString())}catch{return`${t.toString()}/`}return null}async handle(e){let{cid:t,options:n,withServerTiming:i=!1,pathDetails:o,query:s}=e,{handleServerTiming:a,contentTypeParser:c,helia:l,getBlockstore:u}=this.pluginOptions,f=this.log,d=e.resource,h=e.path,m=!1,g=e.byteRangeContext,w=o.ipfsRoots,x=o.terminalElement,v=x.cid,A=BF({...l,blockstore:u(e.cid,e.resource,n?.session??!0,n)});if(x?.type==="directory"){let S=x.cid,M=this.getRedirectUrl(e);if(M!=null){if(f.trace("directory url normalization spec requires redirect..."),n?.redirect==="error")throw f('could not redirect to %s as redirect option was set to "error"',M),new TypeError("Failed to fetch");if(n?.redirect==="manual")return f("returning 301 permanent redirect to %s",M),U0(d,M);f("following redirect to %s",M),d=M,m=!0}let F="index.html";try{f.trace("found directory at %c/%s, looking for index.html",t,h);let N=await a("exporter-dir","",async()=>xr(`/ipfs/${S}/${F}`,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i);f.trace("found root file at %c/%s with cid %c",S,F,N.cid),h=F,v=N.cid}catch(N){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);this.log.error("error loading path %c/%s",S,F,N),e.isDirectory=!0,e.directoryEntries=[],e.modified++,this.log.trace("attempting to get directory entries because index.html was not found");try{for await(let R of A.ls(S,{signal:n?.signal,onProgress:n?.onProgress,extended:!1}))e.directoryEntries.push(R);return null}catch(R){return f.error("error listing directory %c",S,R),v8("Unable to get directory contents")}}finally{n?.onProgress?.(new X("verified-fetch:request:end",{cid:S,path:F}))}}try{let S=await A.stat(v,{extended:!0,signal:AbortSignal.timeout(500)});g.setFileSize(S.size)}catch(S){f.error("error getting exact file size for %c/%s - %e",t,h,S),g.setFileSize(o.terminalElement.size),f.trace("using terminal element size of %d for %c/%s",o.terminalElement.size,t,h)}try{let S=await a("exporter-file","",async()=>xr(v,l.blockstore,{signal:n?.signal,onProgress:n?.onProgress}),i),M,F;if(g.isValidRangeRequest)F=await this.handleRangeRequest(e,S);else{let R=S.content({signal:n?.signal,onProgress:n?.onProgress});f("got async iterator for %c/%s",t,h);let _=await a("stream-and-chunk","",async()=>bS(R,h??"",this.pluginOptions.logger,{onProgress:n?.onProgress,signal:n?.signal}),i),$=_.stream;M=_.firstChunk,F=await a("get-content-type","",async()=>ng({filename:s.filename,bytes:M,path:h,contentTypeParser:c,log:f}),i),g.setBody($)}let N=dn(d,g.getBody(F),{byteRangeContext:g,log:f},{redirected:m});return N.headers.set("Content-Type",g.getContentType()??F),x8(N,w),N}catch(S){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return f.error("error streaming %c/%s",t,h,S),g.isRangeRequest&&S.code==="ERR_INVALID_PARAMS"?$h(d):Hh(d.toString(),"Unable to stream content")}}async handleRangeRequest(e,t){let{path:n,byteRangeContext:i,options:o,withServerTiming:s=!1}=e,{handleServerTiming:a,contentTypeParser:c}=this.pluginOptions,l=this.log,u=t.content({signal:o?.signal,onProgress:o?.onProgress,offset:0,length:8192}),{firstChunk:f}=await bS(u,n??"",this.pluginOptions.logger,{onProgress:o?.onProgress,signal:o?.signal}),d=await a("get-content-type","",async()=>ng({bytes:f,path:n,contentTypeParser:c,log:l}),s);return i?.setBody(h=>{if(o?.signal?.aborted)throw new Je(o?.signal?.reason??"aborted while streaming");return t.content({signal:o?.signal,onProgress:o?.onProgress,offset:h.start??0,length:i.getLength(h)})},d),d}};var ww=class extends kt{id="dag-walk-plugin";canHandle(e){this.log("checking if we can handle %c with accept %s",e.cid,e.accept);let{pathDetails:t,cid:n}=e;return t!=null?!1:n.code===tt||n.code===Mr}async handle(e){let{cid:t,resource:n,options:i,withServerTiming:o=!1}=e,{getBlockstore:s,handleServerTiming:a}=this.pluginOptions,c=s(t,n,i?.session??!0,i),l=await a("path-walking","",async()=>QU({...e,blockstore:c,log:this.log}),o);return l instanceof Response?(this.log.trace("path walking failed"),l.status===404?l:null):(e.modified++,e.pathDetails=l,null)}};function xw(r){return r.charAt(0)==="1"||r.charAt(0)==="Q"?gt(r):vn(G.parse(r))}var ig=class extends Error{name="PluginError";code;fatal;details;response;constructor(e,t,n){super(t),this.code=e,this.fatal=n?.fatal??!1,this.details=n?.details,this.response=n?.response}},Oa=class extends ig{name="PluginFatalError";constructor(e,t,n){super(e,t,{...n,fatal:!0}),this.name="PluginFatalError"}};var bw=class extends kt{id="ipns-record-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipfs.ipns-record"||n.format==="ipns-record"}async handle(e){let{resource:t,path:n,options:i}=e,{helia:o}=this.pluginOptions;if(e.reqFormat="ipns-record",n!==""||!(t.startsWith("ipns://")||t.includes(".ipns.")||t.includes("/ipns/")))throw this.log.error('invalid request for IPNS name "%s" and path "%s"',t,n),new Oa("ERR_INVALID_IPNS_NAME","Invalid IPNS name",{response:M0(t,new Error("Invalid IPNS name"))});let s;try{let d;t.startsWith("ipns://")?d=t.replace("ipns://",""):t.includes("/ipns/")?d=t.split("/ipns/")[1].split("/")[0].split("?")[0]:d=t.split(".ipns.")[0].split("://")[1],this.log.trace('trying to parse peer id from "%s"',d),s=xw(d)}catch(d){throw this.log.error("could not parse peer id from IPNS url %s",t,d),new Oa("ERR_NO_PEER_ID_FOUND","could not parse peer id from url",{response:M0(t,d)})}let a=Xe([D("/ipns/"),s.toMultihash().bytes]),c=new it("/dht/record/"+z(a,"base32"),!1),l=await o.datastore.get(c,i),u=Mt.deserialize(l);e.byteRangeContext.setBody(u.value);let f=dn(t,e.byteRangeContext.getBody("application/vnd.ipfs.ipns-record"),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??"application/vnd.ipfs.ipns-record"),f}};var vw=class extends kt{id="json-plugin";codes=[xo,Go];canHandle({cid:e,accept:t,byteRangeContext:n}){return this.log("checking if we can handle %c with accept %s",e,t),n==null?!1:t==="application/vnd.ipld.dag-json"&&e.code!==Mr?!0:xo===e.code||Go===e.code}async handle(e){let{path:t,resource:n,cid:i,accept:o,options:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.session??!0;this.log.trace("fetching %c/%s",i,t);let l=e.pathDetails?.terminalElement.cid??e.cid,f=await a(l,n,c,s).get(l,s),d;if(o==="application/vnd.ipld.dag-cbor"||o==="application/cbor")try{let g=ud(f);d=cd(g)}catch(g){return this.log.error("could not transform %c to application/vnd.ipld.dag-cbor",g),Ra(n)}else d=f;let h;o==null?xo===i.code?h="application/vnd.ipld.dag-json":h="application/json":h=o.split(";")[0],e.byteRangeContext.setBody(d);let m=dn(n,e.byteRangeContext.getBody(h),{byteRangeContext:e.byteRangeContext,log:this.log});return m.headers.set("content-type",e.byteRangeContext.getContentType()??h),e.byteRangeContext.isValidRangeRequest||m.headers.set("content-length",d.length.toString()),m}};var Pre=["application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/octet-stream"];function Rre({headers:r,accept:e}){let n=(e??new Headers(r).get("accept")??"").split(",").map(i=>i.split(";")[0]).map(i=>i.trim());for(let i of n){if(i==="*/*")return;if(Pre.includes(i??""))return i}}var Aw=class extends kt{id="raw-plugin";codes=[At,lr.code];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/vnd.ipld.raw"||n.format==="raw"}async handle(e){let{path:t,resource:n,cid:i,accept:o,query:s,options:a}=e,{getBlockstore:c,contentTypeParser:l}=this.pluginOptions,u=a?.session??!0,f=this.log;if(o==="application/vnd.ipld.raw"||s.format==="raw"?(e.reqFormat="raw",e.query.download=!0,e.query.filename=e.query.filename??`${i.toString()}.bin`,f.trace("Set content disposition...")):f.trace("Did NOT set content disposition..."),t!==""&&i.code===At)throw f.trace("404-ing raw codec request for %c/%s",i,t),new Oa("ERR_RAW_PATHS_NOT_SUPPORTED","Raw codec does not support paths",{response:A8(n,"Raw codec does not support paths")});let d=e.pathDetails?.terminalElement.cid??e.cid,m=await c(d,n,u,a).get(d,a);e.byteRangeContext.setBody(m);let g=await ng({filename:s.filename,bytes:m,path:t,defaultContentType:Rre({headers:a?.headers,accept:o}),contentTypeParser:l,log:f}),w=dn(n,e.byteRangeContext.getBody(g),{byteRangeContext:e.byteRangeContext,log:f},{redirected:!1});return w.headers.set("content-type",e.byteRangeContext.getContentType()??g),w}};var Dre=({weak:r,reqFormat:e})=>e==="tar"||e==="car"||e==="ipns-record"||r===!0?"W/":"",Ore=({reqFormat:r})=>r==null?"":r==="tar"?".x-tar":`.${r}`;function Jc({cid:r,reqFormat:e,weak:t,rangeStart:n,rangeEnd:i,contentPrefix:o}){let s=Dre({weak:t,reqFormat:e}),a=Ore({reqFormat:e});return(n!=null||i!=null)&&(a+=`.${n??"0"}-${i??"N"}`),`${s}"${o??""}${r.toString()}${a}"`}var Oct=D("ustar\0","binary"),Nct=D("ustar ","binary"),Bct=D(" \0","binary");var A$=mt(x$(),1);function Bre(r){return r[Symbol.asyncIterator]!=null}function Lre(r){if(Bre(r))return(async()=>{let n=new Uint8Array(0);for await(let i of r)n=Xe([n,i],n.length+i.length);return n})();let e=[],t=0;for(let n of r)e.push(n),t+=n.byteLength;return Xe(e,t)}var b$=Lre;var Mre="0000000000000000000",Ure="7777777777777777777",Fre=48,$re=D("ustar\0","binary"),Hre=D("00","binary"),Vre=parseInt("7777",8),Kre=257,zre=263,qre=function(r){switch(r){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72;default:return 0}},jre=function(r){let e=256;for(let t=0;t<148;t++)e+=r[t];for(let t=156;t<512;t++)e+=r[t];return e},el=function(r,e){let t=r.toString(8);return t.length>e?D(Ure.slice(0,e)+" "):D(Mre.slice(0,e-t.length)+t+" ")},vS=function(r){let e=D(r).byteLength,t=Math.floor(Math.log(e)/Math.log(10))+1;return e+t>=Math.pow(10,t)&&t++,`${e+t}${r}`};function v$(r){let e="";r.name!=null&&(e+=vS(" path="+r.name+`
|
|
96
96
|
`)),r.linkname!=null&&(e+=vS(" linkpath="+r.linkname+`
|
|
97
97
|
`));let t=r.pax;if(t!=null)for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e+=vS(" "+n+"="+t[n]+`
|
|
98
98
|
`));return D(e)}function Ew(r){let e=new Uint8Array(512),t=r.name,n="";if(r.typeflag===5&&t[t.length-1]!=="/"&&(t+="/"),D(t).byteLength!==t.length)return null;for(;D(t).byteLength>100;){let i=t.indexOf("/");if(i===-1)return null;n+=n!==""?"/"+t.slice(0,i):t.slice(0,i),t=t.slice(i+1)}return D(t).byteLength>100||D(n).byteLength>155||r.linkname!=null&&D(r.linkname).byteLength>100?null:(e.set(D(t),0),e.set(el(r.mode&Vre,6),100),e.set(el(r.uid,6),108),e.set(el(r.gid,6),116),e.set(el(r.size,11),124),e.set(el(r.mtime.getTime()/1e3|0,11),136),e[156]=Fre+qre(r.type),r.linkname!=null&&e.set(D(r.linkname),157),e.set($re,Kre),e.set(Hre,zre),r.uname!=null&&e.set(D(r.uname),265),r.gname!=null&&e.set(D(r.gname),297),e.set(el(r.devmajor??0,6),329),e.set(el(r.devminor??0,6),337),n!=null&&e.set(D(n),345),e.set(el(jre(e),6),148),e)}var{S_IFMT:Gre,S_IFBLK:Xre,S_IFCHR:Yre,S_IFDIR:Qre,S_IFIFO:Zre,S_IFLNK:Jre}=A$.default,ene=parseInt("755",8),tne=parseInt("644",8),E$=new Uint8Array(1024);function rne(r=0){switch(r&Gre){case Xre:return"block-device";case Yre:return"character-device";case Qre:return"directory";case Zre:return"fifo";case Jre:return"symlink";default:return"file"}}function ES(r){return r&=511,r!==0?E$.subarray(0,512-r):new Uint8Array(0)}function AS(r){if(r.pax==null){let e=Ew(r);if(e!=null)return e}return nne(r)}function nne(r){let e=v$(r),t={name:"PaxHeader",mode:r.mode,uid:r.uid,gid:r.gid,size:e.length,mtime:r.mtime,type:"pax-header",linkname:r.linkname,uname:r.uname,gname:r.gname,devmajor:r.devmajor,devminor:r.devminor};return new pe(Ew(t)??new Uint8Array(0),e,ES(e.length),Ew({...t,size:r.size,type:r.type})??new Uint8Array(0)).subarray()}function Sw(){return async function*(r){for await(let{header:e,body:t}of r){let n={...e,size:e.type==="symlink"?0:e.size??0,type:e.type??rne(e.mode),mode:e.mode??(e.type==="directory"?ene:tne),uid:e.uid??0,gid:e.gid??0,mtime:e.mtime??new Date};if(typeof t=="string"&&(t=D(t)),t instanceof Uint8Array||ki(t)){n.size=t.length,yield AS(n),yield ki(t)?t.subarray():t,yield ES(n.size);continue}if(n.type==="symlink"&&n.linkname==null){if(t==null)throw new Error("type was symlink but no linkname or body specified");n.linkname=z(await b$(t)),yield AS(n);continue}if(yield AS(n),n.type!=="file"&&n.type!=="contiguous-file")continue;let i=0;for await(let o of t??[])i+=o.length,yield ki(o)?o.subarray():o;if(i!==n.size)throw new Error(`size mismatch, wrote ${i} of ${n.size} bytes`);yield ES(n.size)}yield E$}}var ine=["file","raw","directory"];function one(r){let e,t;return(r.type==="file"||r.type==="directory")&&(e=r.unixfs.mode,t=r.unixfs.mtime!=null?new Date(Number(r.unixfs.mtime.secs*1000n)):void 0),{name:r.path,mode:e,mtime:t,size:Number(r.size),type:r.type==="directory"?"directory":"file"}}function S$(r){if(!ine.includes(r.type))throw new Ai(`${r.type} is not a UnixFS node`);let e={header:one(r)};return(r.type==="file"||r.type==="raw")&&(e.body=r.content()),e}async function*_$(r,e,t){let n=await xr(r,e,t);if(n.type==="file"||n.type==="raw"){yield*vt([S$(n)],Sw());return}if(n.type==="directory"){yield*vt(Xh(r,e,t),i=>zt(i,o=>S$(o)),Sw());return}throw new Ai("Not a UnixFS node")}var _w=class extends kt{id="tar-plugin";codes=[];canHandle({cid:e,accept:t,query:n,byteRangeContext:i}){return this.log("checking if we can handle %c with accept %s",e,t),i==null?!1:t==="application/x-tar"||n.format==="tar"}async handle(e){let{cid:t,path:n,resource:i,options:o,pathDetails:s}=e,{getBlockstore:a}=this.pluginOptions,c=s?.terminalElement.cid??t;if(c.code!==tt&&c.code!==At)return Ra("only UnixFS data can be returned in a TAR file");e.reqFormat="tar",e.query.download=!0,e.query.filename=e.query.filename??`${c.toString()}.tar`;let l=a(c,i,o?.session,o),u=af(_$(`/ipfs/${t}/${n}`,l,o));e.byteRangeContext.setBody(u);let f=dn(i,e.byteRangeContext.getBody("application/x-tar"),{byteRangeContext:e.byteRangeContext,log:this.log});return f.headers.set("content-type",e.byteRangeContext.getContentType()??"application/x-tar"),f.headers.set("etag",Jc({cid:c,reqFormat:e.reqFormat,weak:!0})),f}};function C$(r){let e=sne(r);return e===r?`filename="${r}"`:`filename="${e}"; filename*=UTF-8''${encodeURIComponent(r)}`}function sne(r){return r.replace(/[^\x00-\x7F]/g,"_")}var ane={[Mr]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","text/html"],[xo]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[Go]:["application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car"],[tt]:["application/octet-stream","application/json","application/vnd.ipld.dag-cbor","application/cbor","application/vnd.ipld.dag-json","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.car","application/x-tar"],[At]:["application/octet-stream","application/vnd.ipld.raw","application/vnd.ipfs.ipns-record","application/vnd.ipld.dag-json","application/vnd.ipld.car","application/x-tar"]};function T$(r,e){let t=ane[r.code];if(e!=null)return cne(e,t)}function cne(r,e){let t=r.split(",").map(n=>{let i=n.trim().split(";");return{mimeType:`${i[0]}`.trim(),weight:lne(i[1])}}).sort((n,i)=>n.weight===i.weight?0:n.weight>i.weight?-1:1).map(n=>n.mimeType);for(let n of t)for(let i of e)if(n.includes(i)||n==="*/*"||n.startsWith("*/")&&i.split("/")[1]===n.split("/")[1]||n.endsWith("/*")&&i.split("/")[0]===n.split("/")[0])return i}function lne(r){if(r!=null&&(r=r.trim()),r?.startsWith("q=")!==!0)return 1;let e=parseFloat(r.replace("q=",""));return isNaN(e)?0:e}var Cw={raw:"application/vnd.ipld.raw",car:"application/vnd.ipld.car","dag-json":"application/vnd.ipld.dag-json","dag-cbor":"application/vnd.ipld.dag-cbor",json:"application/json",cbor:"application/cbor","ipns-record":"application/vnd.ipfs.ipns-record",tar:"application/x-tar"};function I$(r){if(r!=null)return Cw[r]}function SS(r){let e=r.get("accept");return!!(e!=null&&Object.values(Cw).includes(e))}function _S(r){let e=r?.format;return!!(e!=null&&Object.keys(Cw).includes(e))}function k$({query:r,headers:e}){return SS(e)||_S(r)}function P$({query:r,headers:e,logger:t}){let n=t.forComponent("helia:verified-fetch:get-resolved-accept-header"),i=new Headers(e),o=i.get("accept")??void 0;if(o!=null&&n('incoming accept header "%s"',o),!k$({query:r,headers:i}))return n("no explicit IPLD content-type requested, returning incoming accept header %s",o),o;let s=I$(r?.format);r?.format!=null&&n('incoming query format "%s", mapped to %s',r.format,s);let a=o;return!SS(i)&&_S(r)&&(n("accept header not recognized, but query format provided, setting accept header to %s",s),a=s),n('resolved accept header to "%s"',a),a}async function og(r,e,t){let n=performance.now();try{let i=await t(),s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:i,header:a,error:null}}catch(i){let s=(performance.now()-n).toFixed(1),a=`${r};dur=${s};desc="${e}"`;return{result:null,error:i,header:a}}}var Tw=class{lru;constructor(e){this.lru=new sf({maxSize:e})}get(e){return this.lru.get(e)}set(e,t,n){this.lru.set(e,t,{maxAge:Date.now()+n})}has(e){return this.get(e)!=null}remove(e){this.lru.delete(e)}clear(){this.lru.clear()}};var R$=new Tw(1e3),une=/^(?<protocol>ip[fn]s):\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,fne=/^\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,dne=/^https?:\/\/(.*[^/])\/(?<protocol>ip[fn]s)\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/,hne=/^https?:\/\/(?<cidOrPeerIdOrDnsLink>[^/?]+)\.(?<protocol>ip[fn]s)\.([^/?]+)\/?(?<path>[^?]*)\??(?<queryString>.*)$/;function pne(r){let e=r?.protocol;if(e==null)return!1;let t=r?.cidOrPeerIdOrDnsLink;if(t==null)return!1;let n=r?.path,i=r?.queryString;return["ipns","ipfs"].includes(e)&&typeof t=="string"&&(n==null||typeof n=="string")&&(i==null||typeof i=="string")}function sg(r){for(let e of[hne,une,dne,fne]){let t=r.match(e);if(pne(t?.groups))return t.groups}throw new TypeError(`Invalid URL: ${r}, please use ipfs://, ipns://, or gateway URLs only`)}function mne(r){if(r==null)return;let e=r.answer?.TTL,t=r.record?.ttl,n=t!=null?Number(t/BigInt(1e9)):void 0;return e??n}var gne=/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/;function yne(r){return gne.test(r)&&r.includes("-")&&!r.includes(".")}function wne(r){return r.replace(/--/g,"%").replace(/-/g,".").replace(/%/g,"-")}async function D$({urlString:r,ipns:e,logger:t,withServerTiming:n=!1},i){let o=t.forComponent("helia:verified-fetch:parse-url-string"),{protocol:s,cidOrPeerIdOrDnsLink:a,path:c,queryString:l}=sg(r),u,f,d=[],h,m=[];if(s==="ipfs")try{u=G.parse(a)}catch(x){o.error(x),d.push(new TypeError("Invalid CID for ipfs://<cid> URL"))}else if(h=R$.get(a),h!=null)u=h.cid,f=h.path,o.trace("resolved %s to %c from cache",a,u);else{o.trace("Attempting to resolve PeerId for %s",a);let x;try{x=xw(a);let v=x?.publicKey;if(v==null)throw new TypeError("cidOrPeerIdOrDnsLink contains no public key");if(n){let A=async()=>e.resolve(v,i),S=await og("ipns.resolve",`Resolve IPNS name ${a}`,A);if(m.push(S),S.error!=null)throw S.error;h=S.result}else h=await e.resolve(v,i);u=h?.cid,f=h?.path,o.trace("resolved %s to %c",a,u)}catch(v){if(i?.signal?.aborted)throw new Je(i?.signal?.reason);x==null?(o.error('could not parse PeerId string "%s"',a,v),d.push(new TypeError(`Could not parse PeerId in ipns url "${a}", ${v.message}`))):(o.error("could not resolve PeerId %c",x,v),d.push(new TypeError(`Could not resolve PeerId "${a}": ${v.message}`)))}if(u==null){let v=a;yne(a)&&(v=wne(a),o.trace('decoded dnslink from "%s" to "%s"',a,v)),o.trace("Attempting to resolve DNSLink for %s",v);try{if(n){let A=await og("ipns.resolveDNSLink",`Resolve DNSLink ${v}`,e.resolveDNSLink.bind(e,v,i));if(m.push(A),A.error!=null)throw A.error;h=A.result}else h=await e.resolveDNSLink(v,i);u=h?.cid,f=h?.path,o.trace("resolved %s to %c",v,u)}catch(A){if(i?.signal?.aborted)throw new Je(i?.signal?.reason);o.error('could not resolve DnsLink for "%s"',a,A),d.push(A)}}}if(u==null)throw d.length===1?d[0]:(d.push(new Error(`Invalid resource. Cannot determine CID from URL "${r}".`)),d);let g=mne(h);h!=null&&(g=g??120,o.trace("caching %s resolved to %s with TTL: %s",a,u,g),R$.set(a,h,g*1e3));let w={};if(l!=null&&l.length>0){let x=l.split("&");for(let v of x){let[A,S]=v.split("=");w[A]=decodeURIComponent(S)}w.download!=null&&(w.download=w.download==="true"),w.filename!=null&&(w.filename=w.filename.toString())}return{protocol:s,cid:u,path:xne(f,c??""),query:w,ttl:g,ipfsPath:`/${s}/${a}${c!=null&&c!==""?`/${c}`:""}`,serverTimings:m}}function xne(r,e){let t="";return r!=null&&(t+=r),e.length>0&&(t=`${t.length>0?`${t}/`:t}${e}`),t=t.replace(/\/(\/)+/g,"/"),t.startsWith("/")&&(t=t.substring(1)),t.split("/").map(decodeURIComponent).join("/")}function O$(r){return r.match(/\.[a-zA-Z0-9]{1,4}$/)!=null||r.endsWith("/")?r:`${r}/`}async function N$({resource:r,options:e,logger:t,cid:n,fetch:i=globalThis.fetch}){let o=t.forComponent("helia:verified-fetch:get-redirect-response");if(typeof r!="string"||e==null||["ipfs://","ipns://"].some(u=>r.startsWith(u)))return null;let s=new Headers(e?.headers),a=s.get("x-forwarded-host"),c=s.get("host");if(s.get("x-forwarded-for")==null&&a==null&&c==null)return o.trace("no redirect info found in headers"),null;o.trace("checking for redirect info");try{let u=sg(r),f=new URL(r),d=a??f.host,h=new URL(f);if(u.protocol==="ipfs"&&n.version===0?h.host=`${n.toV1()}.ipfs.${d}`:h.host=`${u.cidOrPeerIdOrDnsLink}.${u.protocol}.${d}`,c?.includes(u.protocol)===!0&&h.host.includes(c))return o.trace("request was for a subdomain already, not setting location header"),null;if(c!=null&&!h.host.includes(c))return o.trace("host header is not the same as the subdomain url host, not setting location header"),null;if(f.host===h.host)return o.trace("req url is the same as the subdomain url, not setting location header"),null;h.pathname=O$(f.pathname.replace(`/${u.cidOrPeerIdOrDnsLink}`,"").replace(`/${u.protocol}`,"")),o.trace("subdomain url %s",h.href);let m=new URL(f,`${f.protocol}//${d}`);m.pathname=O$(f.pathname),o.trace("path url %s",m.href);try{let g=await i(h,{method:"HEAD"});if(g.ok)return o("subdomain supported, redirecting to subdomain"),U0(r.toString(),h.href);throw o("subdomain not supported, subdomain failed with status %s %s",g.status,g.statusText),new y8("subdomain not supported")}catch(g){return o("subdomain not supported",g),m.href===f.href?(o("path url is the same as the request url, not setting location header"),null):U0(r.toString(),m.href)}}catch(u){o.error("error setting location header for x-forwarded-host",u)}return null}async function B$(r,{ipns:e,logger:t},{withServerTiming:n=!1,...i}={withServerTiming:!1}){if(typeof r=="string")return D$({urlString:r,ipns:e,logger:t,withServerTiming:n},i);let o=G.asCID(r);if(o!=null)return{cid:o,protocol:"ipfs",path:"",query:{},ipfsPath:`/ipfs/${o.toString()}`,ttl:29030400,serverTimings:[]};throw new TypeError(`Invalid resource. Cannot determine CID from resource: ${r}`)}function L$(r){let e=G.asCID(r);if(e!=null)return`ipfs://${e}`;try{return`ipfs://${G.parse(r.toString())}`}catch{}let{protocol:t,cidOrPeerIdOrDnsLink:n}=sg(r.toString());return`${t}://${n}`}var bne=100,vne=60*1e3;function Ane(r){if(r==null)return;let e;return r?.signal===null?e=void 0:e=r?.signal,{...r,signal:e}}var Iw=class{helia;ipns;log;contentTypeParser;blockstoreSessions;serverTimingHeaders=[];withServerTiming;plugins=[];constructor({helia:e,ipns:t},n){this.helia=e,this.log=e.logger.forComponent("helia:verified-fetch"),this.ipns=t??tU(e),this.contentTypeParser=n?.contentTypeParser??g$,this.blockstoreSessions=new sf({maxSize:n?.sessionCacheSize??bne,maxAge:n?.sessionTTLms??vne,onEviction:(a,c)=>{c.close()}}),this.withServerTiming=n?.withServerTiming??!1;let i={...n,logger:uT("helia:verified-fetch"),getBlockstore:(a,c,l,u)=>this.getBlockstore(a,c,l,u),handleServerTiming:async(a,c,l)=>this.handleServerTiming(a,c,l,this.withServerTiming),helia:e,contentTypeParser:this.contentTypeParser},o=[new ww(i),new E8(i),new bw(i),new N8(i),new Aw(i),new _w(i),new vw(i),new j8(i),new yw(i)],s=n?.plugins?.map(a=>a(i))??[];if(s.length>0){let a=new Map(o.map(l=>[l.id,l])),c=new Map(s.map(l=>[l.id,l]));this.plugins=o.map(l=>c.get(l.id)??l),this.plugins.push(...s.filter(l=>!a.has(l.id)))}else this.plugins=o;this.log.trace("created VerifiedFetch instance")}getBlockstore(e,t,n=!0,i={}){let o=L$(t);if(!n)return this.helia.blockstore;let s=this.blockstoreSessions.get(o);return s==null&&(s=this.helia.blockstore.createSession(e,i),this.blockstoreSessions.set(o,s)),s}async handleServerTiming(e,t,n,i){if(!i)return n();let{error:o,result:s,header:a}=await og(e,t,n);if(this.serverTimingHeaders.push(a),o!=null)throw o;return s}handleFinalResponse(e,{query:t,cid:n,reqFormat:i,ttl:o,protocol:s,ipfsPath:a,pathDetails:c,byteRangeContext:l,options:u}={}){if(this.serverTimingHeaders.length>0){let d=this.serverTimingHeaders.join(", ");e.headers.set("Server-Timing",d),this.serverTimingHeaders=[]}if(e.headers.get("Transfer-Encoding")!=="chunked"&&l!=null){let d=l.getLength();d!=null&&(this.log.trace("Setting Content-Length from byteRangeContext: %d",d),e.headers.set("Content-Length",d.toString()))}let f;if(this.log.trace("checking for content disposition"),t?.download===!0?f="attachment":this.log.trace("download not requested"),t?.filename!=null?(f==null&&(f="inline"),f=`${f}; ${C$(t.filename)}`):this.log.trace("no filename specified in query"),f!=null?e.headers.set("Content-Disposition",f):this.log.trace("no content disposition specified"),n!=null&&e.headers.get("etag")==null&&e.headers.set("etag",Jc({cid:c?.terminalElement.cid??n,reqFormat:i,weak:!1})),s!=null&&iU({response:e,ttl:o,protocol:s}),a!=null&&e.headers.set("X-Ipfs-Path",a),e.headers.set("Access-Control-Allow-Origin","*"),e.headers.set("Access-Control-Allow-Methods","GET, HEAD, OPTIONS"),e.headers.set("Access-Control-Allow-Headers","Range, X-Requested-With"),e.headers.set("Access-Control-Expose-Headers","Content-Range, Content-Length, X-Ipfs-Path, X-Stream-Output"),i!=="car"?e.headers.set("Accept-Ranges","bytes"):e.headers.set("Accept-Ranges","none"),u?.method==="HEAD"){let d=e?.headers;return new Response(null,{status:200,headers:d})}return e}async runPluginPipeline(e,t=3){let n,i=0,o=new Set,s=e.modified;for(;i<t;){this.log(`Starting pipeline pass #${i+1}`),i++;let a=this.plugins.filter(u=>!o.has(u.id)).filter(u=>u.canHandle(e));if(a.length===0){this.log.trace("No plugins can handle the current context.. checking by CID code");let u=this.plugins.filter(f=>f.codes.includes(e.cid.code));if(u.length>0)a.push(...u);else{this.log.trace("No plugins found that can handle request by CID code; exiting pipeline.");break}}this.log.trace("Plugins ready to handle request: ",a.map(u=>u.id).join(", "));let c=!1,l=!1;for(let u of a){try{this.log.trace("Invoking plugin:",u.id),o.add(u.id);let f=await u.handle(e);if(f!=null){n=f,l=!0;break}}catch(f){if(e.options?.signal?.aborted)throw new Je(e.options?.signal?.reason);if(this.log.error("Error in plugin:",u.constructor.name,f),f.name==="PluginFatalError")return f.response??Hh(e.resource,"Failed to fetch")}finally{let f=e.modified;c=f!==s,c&&(s=f)}if(n!=null){this.log.trace("Plugin produced final response:",u.id);break}}if(l&&n!=null)break;if(!c){this.log.trace("No context changes and no final response; exiting pipeline.");break}}return n}async fetch(e,t){if(this.log("fetch %s",e),t?.method==="OPTIONS")return this.handleFinalResponse(new Response(null,{status:200}));let n=Ane(t),i=n?.withServerTiming??this.withServerTiming;n?.onProgress?.(new X("verified-fetch:request:start",{resource:e}));let o;try{o=await this.handleServerTiming("parse-resource","",async()=>B$(e,{ipns:this.ipns,logger:this.helia.logger},{withServerTiming:i,...n}),i),this.serverTimingHeaders.push(...o.serverTimings.map(({header:d})=>d))}catch(d){if(n?.signal?.aborted)throw new Je(n?.signal?.reason);return this.log.error("error parsing resource %s",e,d),this.handleFinalResponse(M0(e.toString(),d))}n?.onProgress?.(new X("verified-fetch:request:resolve",{cid:o.cid,path:o.path}));let s=P$({query:o.query,headers:n?.headers,logger:this.helia.logger}),a=T$(o.cid,s);if(this.log("output type %s",a),s!=null&&a==null)return this.handleFinalResponse(Ra(e.toString()));let c=a?.split(";")[0]??"application/octet-stream",l=await N$({resource:e,options:n,logger:this.helia.logger,cid:o.cid});if(l!=null)return this.handleFinalResponse(l);let u={...o,resource:e.toString(),accept:a,options:n,withServerTiming:i,onProgress:n?.onProgress,modified:0,plugins:this.plugins.map(d=>d.id)};this.log.trace('finding handler for cid code "%s" and response content type "%s"',o.cid.code,c);let f=await this.runPluginPipeline(u);return n?.onProgress?.(new X("verified-fetch:request:end",{cid:o.cid,path:o.path})),this.handleFinalResponse(f??v8(e.toString()),u)}async start(){await this.helia.start()}async stop(){await this.helia.stop()}};var ag,kw=async function(e,t){return ag==null&&(ag=await CS()),ag(e,t)};kw.start=async function(){await ag?.start()};kw.stop=async function(){await ag?.stop()};function Ene(r){return"ipfs-_blank"}function Sne(r,e){let t=e.globalData.gatewayURLWithoutSubdomain.host;return`<a class="ipfs-hash" translate="no" href="${e.globalData.gatewayURLWithoutSubdomain.protocol}//${t}/ipfs/${r.hash}?filename=${r.name}">${r.shortHash}</a>`}function _ne(r){let e=r.split("."),t=[];for(let n=e.length-1;n>=0;n--){let i=e[n];if(i==="ipfs"||i==="ipns")break;t.push(i)}return t.reverse(),t.join(".")}function Cne(r){let e;try{e=new URL(r)}catch{e=new URL("https://inbrowser.link")}return e.host=_ne(e.host),e}function Tne(r){return r.path!=null?`Index of <a href="${`${r.globalData.gatewayURL}/${r.path}`}">${r.name}</a>`:`Index of ${r.name} ${r.path}`}function Ine(r){return r.listing.map(e=>`<div class="type-icon">
|
|
@@ -104,7 +104,7 @@ Content-Range: ${w8({byteStart:u.start,byteEnd:u.end,byteSize:s??void 0})}\r
|
|
|
104
104
|
<div class="nowrap">
|
|
105
105
|
${Sne(e,r)}
|
|
106
106
|
</div>
|
|
107
|
-
<div class="nowrap" title="Cumulative size of IPFS DAG (data + metadata)">${e.size}</div>`).join(" ")}function kne(r){return r.path.split("/").pop()??r.path}function Pne(r){return r.length<=11?r:`${r.slice(0,4)}...${r.slice(-4)}`}var M$=(r,e,{gatewayURL:t,dnsLink:n,log:i})=>{i("loading directory html for %s",r.path);let o={globalData:{gatewayURL:t,gatewayURLWithoutSubdomain:Cne(t),dnsLink:n??!1},listing:e.map(s=>({size:s.size
|
|
107
|
+
<div class="nowrap" title="Cumulative size of IPFS DAG (data + metadata)">${e.size}</div>`).join(" ")}function kne(r){return r.path.split("/").pop()??r.path}function Pne(r){return r.length<=11?r:`${r.slice(0,4)}...${r.slice(-4)}`}var M$=(r,e,{gatewayURL:t,dnsLink:n,log:i})=>{i("loading directory html for %s",r.path);let o={globalData:{gatewayURL:t,gatewayURLWithoutSubdomain:Cne(t),dnsLink:n??!1},listing:e.map(s=>({size:s.size?.toString()??"?",name:s.name,path:kne(s),hash:s.cid.toString(),shortHash:Pne(s.cid.toString())})),name:r.name,size:r.size.toString(),path:r.path,breadcrumbs:[],backLink:"",hash:r.cid.toString()};return`<!DOCTYPE html>
|
|
108
108
|
<html lang="en">
|
|
109
109
|
<head>
|
|
110
110
|
<meta charset="utf-8">
|