@serfab/quereus-plugin-sereus 1.5.0 → 1.6.0

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.
@@ -1,4 +1,4 @@
1
- /* @serfab/quereus-plugin-sereus 1.5.0 — browser bundle */
1
+ /* @serfab/quereus-plugin-sereus 1.6.0 — browser bundle */
2
2
  var _ke=Object.create;var v3=Object.defineProperty;var Pke=Object.getOwnPropertyDescriptor;var Rke=Object.getOwnPropertyNames;var Lke=Object.getPrototypeOf,Mke=Object.prototype.hasOwnProperty;var _=(r,e)=>()=>(r&&(e=r(r=0)),e);var Nr=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),W=(r,e)=>{for(var t in e)v3(r,t,{get:e[t],enumerable:!0})},Bke=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Rke(e))!Mke.call(r,o)&&o!==t&&v3(r,o,{get:()=>e[o],enumerable:!(n=Pke(e,o))||n.enumerable});return r};var Ri=(r,e,t)=>(t=r!=null?_ke(Lke(r)):{},Bke(e||!r||!r.__esModule?v3(t,"default",{value:r,enumerable:!0}):t,r));var $te=Nr((Lvt,zte)=>{var xg=1e3,vg=xg*60,Eg=vg*60,xh=Eg*24,V5e=xh*7,q5e=xh*365.25;zte.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return j5e(r);if(t==="number"&&isFinite(r))return e.long?W5e(r):G5e(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function j5e(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*q5e;case"weeks":case"week":case"w":return t*V5e;case"days":case"day":case"d":return t*xh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Eg;case"minutes":case"minute":case"mins":case"min":case"m":return t*vg;case"seconds":case"second":case"secs":case"sec":case"s":return t*xg;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function G5e(r){var e=Math.abs(r);return e>=xh?Math.round(r/xh)+"d":e>=Eg?Math.round(r/Eg)+"h":e>=vg?Math.round(r/vg)+"m":e>=xg?Math.round(r/xg)+"s":r+"ms"}function W5e(r){var e=Math.abs(r);return e>=xh?TI(r,e,xh,"day"):e>=Eg?TI(r,e,Eg,"hour"):e>=vg?TI(r,e,vg,"minute"):e>=xg?TI(r,e,xg,"second"):r+" ms"}function TI(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var Vte=Nr((Mvt,Hte)=>{function Y5e(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=a,t.humanize=$te(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let h=0;h<u.length;h++)d=(d<<5)-d+u.charCodeAt(h),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,h=null,p,f;function g(...y){if(!g.enabled)return;let m=g,w=Number(new Date),b=w-(d||w);m.diff=b,m.prev=d,m.curr=w,d=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let x=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,A)=>{if(T==="%%")return"%";x++;let v=t.formatters[A];if(typeof v=="function"){let C=y[x];T=v.call(m,C),y.splice(x,1),x--}return T}),t.formatArgs.call(m,y),(m.log||t.log).apply(m,y)}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:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,f=t.enabled(u)),f),set:y=>{h=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let h=t(this.namespace+(typeof d>"u"?":":d)+u);return h.log=this.log,h}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of d)h[0]==="-"?t.skips.push(h.slice(1)):t.names.push(h)}function s(u,d){let h=0,p=0,f=-1,g=0;for(;h<u.length;)if(p<d.length&&(d[p]===u[h]||d[p]==="*"))d[p]==="*"?(f=p,g=h,p++):(h++,p++);else if(f!==-1)p=f+1,g++,h=g;else return!1;for(;p<d.length&&d[p]==="*";)p++;return p===d.length}function i(){let u=[...t.names,...t.skips.map(d=>"-"+d)].join(",");return t.enable(""),u}function a(u){for(let d of t.skips)if(s(u,d))return!1;for(let d of t.names)if(s(u,d))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}Hte.exports=Y5e});var qte=Nr((Xo,kI)=>{Xo.formatArgs=Z5e;Xo.save=J5e;Xo.load=Q5e;Xo.useColors=X5e;Xo.storage=e8e();Xo.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`."))}})();Xo.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 X5e(){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 Z5e(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+kI.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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}Xo.log=console.debug||console.log||(()=>{});function J5e(r){try{r?Xo.storage.setItem("debug",r):Xo.storage.removeItem("debug")}catch{}}function Q5e(){let r;try{r=Xo.storage.getItem("debug")||Xo.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function e8e(){try{return localStorage}catch{}}kI.exports=Vte()(Xo);var{formatters:t8e}=kI.exports;t8e.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});function Oe(r=0){return new Uint8Array(r)}function ar(r=0){return new Uint8Array(r)}var Xt=_(()=>{});function mt(r){if(r<y3e)return 1;if(r<b3e)return 2;if(r<w3e)return 3;if(r<XB)return 4;if(r<ZB)return 5;if(r<JB)return 6;if(r<QB)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function ul(r,e,t=0){switch(mt(r)){case 8:e[t++]=r&255|at,r/=128;case 7:e[t++]=r&255|at,r/=128;case 6:e[t++]=r&255|at,r/=128;case 5:e[t++]=r&255|at,r/=128;case 4:e[t++]=r&255|at,r>>>=7;case 3:e[t++]=r&255|at,r>>>=7;case 2:e[t++]=r&255|at,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function x3e(r,e,t=0){switch(mt(r)){case 8:e.set(t++,r&255|at),r/=128;case 7:e.set(t++,r&255|at),r/=128;case 6:e.set(t++,r&255|at),r/=128;case 5:e.set(t++,r&255|at),r/=128;case 4:e.set(t++,r&255|at),r>>>=7;case 3:e.set(t++,r&255|at),r>>>=7;case 2:e.set(t++,r&255|at),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function eO(r,e){let t=r[e],n=0;if(n+=t&oo,t<at||(t=r[e+1],n+=(t&oo)<<7,t<at)||(t=r[e+2],n+=(t&oo)<<14,t<at)||(t=r[e+3],n+=(t&oo)<<21,t<at)||(t=r[e+4],n+=(t&oo)*XB,t<at)||(t=r[e+5],n+=(t&oo)*ZB,t<at)||(t=r[e+6],n+=(t&oo)*JB,t<at)||(t=r[e+7],n+=(t&oo)*QB,t<at))return n;throw new RangeError("Could not decode varint")}function v3e(r,e){let t=r.get(e),n=0;if(n+=t&oo,t<at||(t=r.get(e+1),n+=(t&oo)<<7,t<at)||(t=r.get(e+2),n+=(t&oo)<<14,t<at)||(t=r.get(e+3),n+=(t&oo)<<21,t<at)||(t=r.get(e+4),n+=(t&oo)*XB,t<at)||(t=r.get(e+5),n+=(t&oo)*ZB,t<at)||(t=r.get(e+6),n+=(t&oo)*JB,t<at)||(t=r.get(e+7),n+=(t&oo)*QB,t<at))return n;throw new RangeError("Could not decode varint")}function oi(r,e,t=0){return e==null&&(e=ar(mt(r))),e instanceof Uint8Array?ul(r,e,t):x3e(r,e,t)}function so(r,e=0){return r instanceof Uint8Array?eO(r,e):v3e(r,e)}var y3e,b3e,w3e,XB,ZB,JB,QB,at,oo,si=_(()=>{Xt();y3e=Math.pow(2,7),b3e=Math.pow(2,14),w3e=Math.pow(2,21),XB=Math.pow(2,28),ZB=Math.pow(2,35),JB=Math.pow(2,42),QB=Math.pow(2,49),at=128,oo=127});function E3e(r){return r?.buffer instanceof ArrayBuffer}function tO(r){if(E3e(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}var rO=_(()=>{});function Ye(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ar(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return tO(t)}var Mr=_(()=>{Xt();rO()});function ee(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 Ne=_(()=>{});function Dne(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function uT(r){return!!r?.[_ne]}var _ne,Y,ct=_(()=>{Xt();Mr();Ne();_ne=Symbol.for("@achingbrain/uint8arraylist");Y=class r{bufs;length;[_ne]=!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(uT(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(uT(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=Dne(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Dne(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(uT(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:o}=this._subList(e,t);return Ye(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Ye(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!uT(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let h=l;h>=0;h--){let p=this.get(d+h);if(n[h]!==p){u=Math.max(1,h-a[p]);break}}if(u===0)return d}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=ar(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 o=Oe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=Oe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=Oe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=ar(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 o=Oe(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=Oe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=Oe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=Oe(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=Oe(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!ee(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((o,s)=>o+s.byteLength,0)),n.length=t,n}}});var Kne=Nr((Ykt,Fne)=>{var Ng=1e3,Ug=Ng*60,Fg=Ug*60,Bh=Fg*24,_3e=Bh*7,P3e=Bh*365.25;Fne.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return R3e(r);if(t==="number"&&isFinite(r))return e.long?M3e(r):L3e(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function R3e(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*P3e;case"weeks":case"week":case"w":return t*_3e;case"days":case"day":case"d":return t*Bh;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Fg;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ug;case"seconds":case"second":case"secs":case"sec":case"s":return t*Ng;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function L3e(r){var e=Math.abs(r);return e>=Bh?Math.round(r/Bh)+"d":e>=Fg?Math.round(r/Fg)+"h":e>=Ug?Math.round(r/Ug)+"m":e>=Ng?Math.round(r/Ng)+"s":r+"ms"}function M3e(r){var e=Math.abs(r);return e>=Bh?yT(r,e,Bh,"day"):e>=Fg?yT(r,e,Fg,"hour"):e>=Ug?yT(r,e,Ug,"minute"):e>=Ng?yT(r,e,Ng,"second"):r+" ms"}function yT(r,e,t,n){var o=e>=t*1.5;return Math.round(r/t)+" "+n+(o?"s":"")}});var $ne=Nr((Xkt,zne)=>{function B3e(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=o,t.enabled=a,t.humanize=Kne(),t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let h=0;h<u.length;h++)d=(d<<5)-d+u.charCodeAt(h),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u){let d,h=null,p,f;function g(...y){if(!g.enabled)return;let m=g,w=Number(new Date),b=w-(d||w);m.diff=b,m.prev=d,m.curr=w,d=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let x=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,A)=>{if(T==="%%")return"%";x++;let v=t.formatters[A];if(typeof v=="function"){let C=y[x];T=v.call(m,C),y.splice(x,1),x--}return T}),t.formatArgs.call(m,y),(m.log||t.log).apply(m,y)}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:()=>h!==null?h:(p!==t.namespaces&&(p=t.namespaces,f=t.enabled(u)),f),set:y=>{h=y}}),typeof t.init=="function"&&t.init(g),g}function n(u,d){let h=t(this.namespace+(typeof d>"u"?":":d)+u);return h.log=this.log,h}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of d)h[0]==="-"?t.skips.push(h.slice(1)):t.names.push(h)}function s(u,d){let h=0,p=0,f=-1,g=0;for(;h<u.length;)if(p<d.length&&(d[p]===u[h]||d[p]==="*"))d[p]==="*"?(f=p,g=h,p++):(h++,p++);else if(f!==-1)p=f+1,g++,h=g;else return!1;for(;p<d.length&&d[p]==="*";)p++;return p===d.length}function i(){let u=[...t.names,...t.skips.map(d=>"-"+d)].join(",");return t.enable(""),u}function a(u){for(let d of t.skips)if(s(u,d))return!1;for(let d of t.names)if(s(u,d))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}zne.exports=B3e});var Hne=Nr((Qo,bT)=>{Qo.formatArgs=N3e;Qo.save=U3e;Qo.load=F3e;Qo.useColors=O3e;Qo.storage=K3e();Qo.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`."))}})();Qo.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 O3e(){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 N3e(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+bT.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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}Qo.log=console.debug||console.log||(()=>{});function U3e(r){try{r?Qo.storage.setItem("debug",r):Qo.storage.removeItem("debug")}catch{}}function F3e(){let r;try{r=Qo.storage.getItem("debug")||Qo.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function K3e(){try{return localStorage}catch{}}bT.exports=$ne()(Qo);var{formatters:z3e}=bT.exports;z3e.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Gne,Wne=_(()=>{Gne=Symbol.for("@libp2p/connection")});var Yne=_(()=>{});var Xne=_(()=>{});var Zne=_(()=>{});var fO,Jne=_(()=>{fO=Symbol.for("@libp2p/content-routing")});var ji,xT,vT,q,zt,Fa,Nh,fl,ET,Dd,Vv,Uh,zg,_d,ST,CT,AT,Ds,IT,$g,hl,Hg,qv,TT,Vg,An,Qne=_(()=>{ji=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}},xT=class extends Error{static name="UnexpectedPeerError";constructor(e="Unexpected Peer"){super(e),this.name="UnexpectedPeerError"}},vT=class extends Error{static name="InvalidCryptoExchangeError";constructor(e="Invalid crypto exchange"){super(e),this.name="InvalidCryptoExchangeError"}},q=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},zt=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},Fa=class extends Error{static name="InvalidPrivateKeyError";constructor(e="Invalid private key"){super(e),this.name="InvalidPrivateKeyError"}},Nh=class extends Error{static name="ConnectionClosedError";constructor(e="The connection is closed"){super(e),this.name="ConnectionClosedError"}},fl=class extends Error{static name="MuxerClosedError";constructor(e="The muxer is closed"){super(e),this.name="MuxerClosedError"}},ET=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}},Dd=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},Vv=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}},Uh=class extends Error{static name="NotFoundError";constructor(e="Not found"){super(e),this.name="NotFoundError"}},zg=class extends Error{static name="InvalidPeerIdError";constructor(e="Invalid PeerID"){super(e),this.name="InvalidPeerIdError"}},_d=class extends Error{static name="InvalidMultiaddrError";constructor(e="Invalid multiaddr"){super(e),this.name="InvalidMultiaddrError"}},ST=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},CT=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},AT=class extends Error{static name="UnsupportedProtocolError";constructor(e="Unsupported protocol error"){super(e),this.name="UnsupportedProtocolError"}},Ds=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}},IT=class extends Error{static name="ProtocolError";constructor(e="Protocol error"){super(e),this.name="ProtocolError"}},$g=class extends Error{static name="TimeoutError";constructor(e="Timed out"){super(e),this.name="TimeoutError"}},hl=class extends Error{static name="NotStartedError";constructor(e="Not started"){super(e),this.name="NotStartedError"}},Hg=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},qv=class extends Error{static name="LimitedConnectionError";constructor(e="Limited connection"){super(e),this.name="LimitedConnectionError"}},TT=class extends Error{static name="TooManyInboundProtocolStreamsError";constructor(e="Too many inbound protocol streams"){super(e),this.name="TooManyInboundProtocolStreamsError"}},Vg=class extends Error{static name="TooManyOutboundProtocolStreamsError";constructor(e="Too many outbound protocol streams"){super(e),this.name="TooManyOutboundProtocolStreamsError"}},An=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var kT,Pd,DT,_T,eoe=_(()=>{kT=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},Pd=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},DT=class extends Pd{constructor(e,t){super(!0,e,t)}},_T=class extends Pd{constructor(e,t){super(!1,e,t)}}});var toe=_(()=>{});var roe=_(()=>{});var noe=_(()=>{});var ooe=_(()=>{});var jv,soe=_(()=>{jv=Symbol.for("@libp2p/peer-discovery")});function Rd(r){return!!r?.[PT]}var PT,ioe=_(()=>{PT=Symbol.for("@libp2p/peer-id")});var aoe=_(()=>{});var hO,coe=_(()=>{hO=Symbol.for("@libp2p/peer-routing")});var Gv,loe=_(()=>{Gv="keep-alive"});var uoe=_(()=>{});function RT(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function doe(...r){let e=[];for(let t of r)RT(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 foe(...r){let e=[];for(let t of r)RT(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 hoe=_(()=>{});var poe=_(()=>{});var moe=_(()=>{});var goe=_(()=>{});var yoe=_(()=>{});var Wv,boe=_(()=>{(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(Wv||(Wv={}))});var Lt,_s=_(()=>{Lt=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 o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var In,pO,se=_(()=>{Wne();Yne();Xne();Zne();Jne();Qne();eoe();toe();roe();noe();ooe();soe();ioe();aoe();coe();loe();uoe();hoe();poe();moe();goe();yoe();boe();_s();In=Symbol.for("@libp2p/service-capabilities"),pO=Symbol.for("@libp2p/service-dependencies")});function woe(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 Ld(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")}var GDt,Yv=_(()=>{GDt=new Uint8Array(0)});function j3e(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var G3e,W3e,xoe,voe=_(()=>{G3e=j3e,W3e=G3e,xoe=W3e});function Eoe(r,e){return new yO({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Soe({name:r,prefix:e,encode:t,decode:n}){return new bO(r,e,t,n)}function qg({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=xoe(t,r);return Soe({prefix:e,name:r,encode:n,decode:s=>Ld(o(s))})}function Y3e(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function X3e(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Z3e(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Ka({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Z3e(n);return Soe({prefix:e,name:r,encode(s){return X3e(s,n,t)},decode(s){return Y3e(s,o,t,r)}})}var mO,gO,yO,bO,LT=_(()=>{Yv();voe();mO=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")}},gO=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Eoe(this,e)}},yO=class{decoders;constructor(e){this.decoders=e}or(e){return Eoe(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`)}};bO=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new mO(e,t,n),this.decoder=new gO(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Ur,e_t,Fh=_(()=>{LT();Ur=qg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),e_t=qg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var Xv,n_t,o_t,s_t,i_t,a_t,c_t,l_t,u_t,Coe=_(()=>{LT();Xv=Ka({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),n_t=Ka({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o_t=Ka({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),s_t=Ka({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),i_t=Ka({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),a_t=Ka({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),c_t=Ka({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),l_t=Ka({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),u_t=Ka({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var MT,h_t,Aoe=_(()=>{LT();MT=qg({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),h_t=qg({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});function koe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=t4e;)e[t++]=r&255|Ioe,r/=128;for(;r&e4e;)e[t++]=r&255|Ioe,r>>>=7;return e[t]=r|0,koe.bytes=t-n+1,e}function wO(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw wO.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&Toe)<<o:(i&Toe)*Math.pow(2,o),o+=7}while(i>=n4e);return wO.bytes=s-n,t}var J3e,Ioe,Q3e,e4e,t4e,r4e,n4e,Toe,o4e,s4e,i4e,a4e,c4e,l4e,u4e,d4e,f4e,h4e,p4e,m4e,Zv,Doe=_(()=>{J3e=koe,Ioe=128,Q3e=127,e4e=~Q3e,t4e=Math.pow(2,31);r4e=wO,n4e=128,Toe=127;o4e=Math.pow(2,7),s4e=Math.pow(2,14),i4e=Math.pow(2,21),a4e=Math.pow(2,28),c4e=Math.pow(2,35),l4e=Math.pow(2,42),u4e=Math.pow(2,49),d4e=Math.pow(2,56),f4e=Math.pow(2,63),h4e=function(r){return r<o4e?1:r<s4e?2:r<i4e?3:r<a4e?4:r<c4e?5:r<l4e?6:r<u4e?7:r<d4e?8:r<f4e?9:10},p4e={encode:J3e,decode:r4e,encodingLength:h4e},m4e=p4e,Zv=m4e});function Jv(r,e=0){return[Zv.decode(r,e),Zv.decode.bytes]}function jg(r,e,t=0){return Zv.encode(r,e,t),e}function Gg(r){return Zv.encodingLength(r)}var xO=_(()=>{Doe()});function Yg(r,e){let t=e.byteLength,n=Gg(r),o=n+Gg(t),s=new Uint8Array(o+t);return jg(r,s,0),jg(t,s,n),s.set(e,o),new Wg(r,t,e,s)}function Qv(r){let e=Ld(r),[t,n]=Jv(e),[o,s]=Jv(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Wg(t,o,i,e)}function Poe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&woe(r.bytes,t.bytes)}}var Wg,eE=_(()=>{Yv();xO();Wg=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}}});var Roe=_(()=>{});function Loe(r,e){let{bytes:t,version:n}=r;return n===0?y4e(t,vO(r),e??Ur.encoder):b4e(t,vO(r),e??Xv.encoder)}function vO(r){let e=Moe.get(r);if(e==null){let t=new Map;return Moe.set(r,t),t}return e}function g4e(r,e){switch(r[0]){case"Q":{let t=e??Ur;return[Ur.prefix,t.decode(`${Ur.prefix}${r}`)]}case Ur.prefix:{let t=e??Ur;return[Ur.prefix,t.decode(r)]}case Xv.prefix:{let t=e??Xv;return[Xv.prefix,t.decode(r)]}case MT.prefix:{let t=e??MT;return[MT.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 y4e(r,e,t){let{prefix:n}=t;if(n!==Ur.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function b4e(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}function Boe(r,e,t){let n=Gg(r),o=n+Gg(e),s=new Uint8Array(o+t.byteLength);return jg(r,s,0),jg(e,s,n),s.set(t,o),s}var Moe,Ps,tE,w4e,x4e,Xg=_(()=>{Coe();Aoe();Fh();Yv();eE();xO();Roe();Moe=new WeakMap;Ps=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==tE)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==w4e)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=Yg(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&&Poe(e.multihash,n.multihash)}toString(e){return Loe(this,e)}toJSON(){return{"/":Loe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Boe(n,o,s.bytes))}else if(t[x4e]===!0){let{version:n,multihash:o,code:s}=t,i=Qv(o);return r.create(n,s,i)}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!==tE)throw new Error(`Version 0 CID must use dag-pb (code: ${tE}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Boe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,tE,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,o=Ld(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Wg(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=Jv(e.subarray(t));return t+=h,d},o=n(),s=tE;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=g4e(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return vO(s).set(n,e),s}};tE=112,w4e=18;x4e=Symbol.for("@ipld/js-cid/CID")});function E4e(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 Yg(Ooe,Noe(r))}var Ooe,v4e,Noe,za,Zg=_(()=>{Yv();eE();Ooe=0,v4e="identity",Noe=Ld;za={code:Ooe,name:v4e,encode:Noe,digest:E4e}});function Uoe(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 pl(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Kh(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Kh(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Foe(r){return new TextEncoder().encode(r)}function Koe(r){return new TextDecoder().decode(r)}function S4e(r){return r?.buffer instanceof ArrayBuffer}function Kh(r){return S4e(r)?r:r.slice()}var I_t,Md=_(()=>{I_t=new Uint8Array(0)});function C4e(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var A4e,I4e,$oe,Hoe=_(()=>{A4e=C4e,I4e=A4e,$oe=I4e});function Voe(r,e){return new CO({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Jg({name:r,prefix:e,encode:t,decode:n}){return new AO(r,e,t,n)}function Bd({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=$oe(t,r);return Jg({prefix:e,name:r,encode:n,decode:s=>pl(o(s))})}function T4e(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function k4e(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function D4e(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function cr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=D4e(n);return Jg({prefix:e,name:r,encode(s){return k4e(s,n,t)},decode(s){return T4e(s,o,t,r)}})}var EO,SO,CO,AO,Gi=_(()=>{Md();Hoe();EO=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")}},SO=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Voe(this,e)}},CO=class{decoders;constructor(e){this.decoders=e}or(e){return Voe(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`)}};AO=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new EO(e,t,n),this.decoder=new SO(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var IO={};W(IO,{base10:()=>_4e});var _4e,qoe=_(()=>{Gi();_4e=Bd({prefix:"9",name:"base10",alphabet:"0123456789"})});var TO={};W(TO,{base16:()=>P4e,base16upper:()=>R4e});var P4e,R4e,joe=_(()=>{Gi();P4e=cr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),R4e=cr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var kO={};W(kO,{base2:()=>L4e});var L4e,Goe=_(()=>{Gi();L4e=cr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var DO={};W(DO,{base256emoji:()=>U4e});function O4e(r){return r.reduce((e,t)=>(e+=M4e[t],e),"")}function N4e(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=B4e[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Woe,M4e,B4e,U4e,Yoe=_(()=>{Gi();Woe=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}"),M4e=Woe.reduce((r,e,t)=>(r[t]=e,r),[]),B4e=Woe.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);U4e=Jg({prefix:"\u{1F680}",name:"base256emoji",encode:O4e,decode:N4e})});var _O={};W(_O,{base32:()=>Qg,base32hex:()=>$4e,base32hexpad:()=>V4e,base32hexpadupper:()=>q4e,base32hexupper:()=>H4e,base32pad:()=>K4e,base32padupper:()=>z4e,base32upper:()=>F4e,base32z:()=>j4e});var Qg,F4e,K4e,z4e,$4e,H4e,V4e,q4e,j4e,PO=_(()=>{Gi();Qg=cr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),F4e=cr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),K4e=cr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),z4e=cr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$4e=cr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),H4e=cr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),V4e=cr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),q4e=cr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),j4e=cr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var RO={};W(RO,{base36:()=>rE,base36upper:()=>G4e});var rE,G4e,LO=_(()=>{Gi();rE=Bd({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),G4e=Bd({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var MO={};W(MO,{base58btc:()=>$a,base58flickr:()=>W4e});var $a,W4e,BO=_(()=>{Gi();$a=Bd({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),W4e=Bd({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var OO={};W(OO,{base64:()=>Y4e,base64pad:()=>X4e,base64url:()=>Z4e,base64urlpad:()=>J4e});var Y4e,X4e,Z4e,J4e,Xoe=_(()=>{Gi();Y4e=cr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),X4e=cr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Z4e=cr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),J4e=cr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var NO={};W(NO,{base8:()=>Q4e});var Q4e,Zoe=_(()=>{Gi();Q4e=cr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var UO={};W(UO,{identity:()=>eMe});var eMe,Joe=_(()=>{Md();Gi();eMe=Jg({prefix:"\0",name:"identity",encode:r=>Koe(r),decode:r=>Foe(r)})});var $_t,H_t,Qoe=_(()=>{$_t=new TextEncoder,H_t=new TextDecoder});var ese=_(()=>{Md()});function nse(r,e,t){e=e||[],t=t||0;for(var n=t;r>=iMe;)e[t++]=r&255|tse,r/=128;for(;r&sMe;)e[t++]=r&255|tse,r>>>=7;return e[t]=r|0,nse.bytes=t-n+1,e}function FO(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw FO.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&rse)<<o:(i&rse)*Math.pow(2,o),o+=7}while(i>=cMe);return FO.bytes=s-n,t}var nMe,tse,oMe,sMe,iMe,aMe,cMe,rse,lMe,uMe,dMe,fMe,hMe,pMe,mMe,gMe,yMe,bMe,wMe,xMe,nE,ose=_(()=>{nMe=nse,tse=128,oMe=127,sMe=~oMe,iMe=Math.pow(2,31);aMe=FO,cMe=128,rse=127;lMe=Math.pow(2,7),uMe=Math.pow(2,14),dMe=Math.pow(2,21),fMe=Math.pow(2,28),hMe=Math.pow(2,35),pMe=Math.pow(2,42),mMe=Math.pow(2,49),gMe=Math.pow(2,56),yMe=Math.pow(2,63),bMe=function(r){return r<lMe?1:r<uMe?2:r<dMe?3:r<fMe?4:r<hMe?5:r<pMe?6:r<mMe?7:r<gMe?8:r<yMe?9:10},wMe={encode:nMe,decode:aMe,encodingLength:bMe},xMe=wMe,nE=xMe});function oE(r,e=0){return[nE.decode(r,e),nE.decode.bytes]}function ey(r,e,t=0){return nE.encode(r,e,t),e}function ty(r){return nE.encodingLength(r)}var NT=_(()=>{ose()});function ny(r,e){let t=e.byteLength,n=ty(r),o=n+ty(t),s=new Uint8Array(o+t);return ey(r,s,0),ey(t,s,n),s.set(e,o),new ry(r,t,e,s)}function sse(r){let e=pl(r),[t,n]=oE(e),[o,s]=oE(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new ry(t,o,i,e)}function ise(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Uoe(r.bytes,t.bytes)}}var ry,iE=_(()=>{Md();NT();ry=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Kh(n),this.bytes=Kh(o)}}});var KO={};W(KO,{identity:()=>SMe});function EMe(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 ny(ase,cse(r))}var ase,vMe,cse,SMe,lse=_(()=>{Md();iE();ase=0,vMe="identity",cse=pl;SMe={code:ase,name:vMe,encode:cse,digest:EMe}});function $O({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new zO(r,e,t,n,o)}function use(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 ny(e,r)}var CMe,zO,HO=_(()=>{iE();CMe=20;zO=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??CMe,this.maxDigestLength=s}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?use(n,this.code,t?.truncate):n.then(o=>use(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var VO={};W(VO,{sha256:()=>AMe,sha512:()=>IMe});function fse(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var AMe,IMe,hse=_(()=>{HO();AMe=$O({name:"sha2-256",code:18,encode:fse("SHA-256")}),IMe=$O({name:"sha2-512",code:19,encode:fse("SHA-512")})});var qO=_(()=>{});function pse(r,e){let{bytes:t,version:n}=r;return n===0?kMe(t,jO(r),e??$a.encoder):DMe(t,jO(r),e??Qg.encoder)}function jO(r){let e=mse.get(r);if(e==null){let t=new Map;return mse.set(r,t),t}return e}function TMe(r,e){switch(r[0]){case"Q":{let t=e??$a;return[$a.prefix,t.decode(`${$a.prefix}${r}`)]}case $a.prefix:{let t=e??$a;return[$a.prefix,t.decode(r)]}case Qg.prefix:{let t=e??Qg;return[Qg.prefix,t.decode(r)]}case rE.prefix:{let t=e??rE;return[rE.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 kMe(r,e,t){let{prefix:n}=t;if(n!==$a.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function DMe(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}function gse(r,e,t){let n=ty(r),o=n+ty(e),s=new Uint8Array(o+t.byteLength);return ey(r,s,0),ey(e,s,n),s.set(t,o),s}var mse,UT,aE,_Me,PMe,yse=_(()=>{PO();LO();BO();Md();iE();NT();qO();mse=new WeakMap;UT=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Kh(o),this["/"]=this.bytes}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!==aE)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==_Me)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=ny(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&&ise(e.multihash,n.multihash)}toString(e){return pse(this,e)}toJSON(){return{"/":pse(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??gse(n,o,s.bytes))}else if(t[PMe]===!0){let{version:n,multihash:o,code:s}=t,i=sse(o);return r.create(n,s,i)}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!==aE)throw new Error(`Version 0 CID must use dag-pb (code: ${aE}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=gse(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,aE,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,o=pl(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new ry(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=oE(e.subarray(t));return t+=h,d},o=n(),s=aE;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=TMe(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return jO(s).set(n,e),s}};aE=112,_Me=18;PMe=Symbol.for("@ipld/js-cid/CID")});var bse=_(()=>{});var wse=_(()=>{});var xse=_(()=>{});var vse=_(()=>{});var Ese=_(()=>{bse();wse();xse();qO();vse()});var Sse=_(()=>{Md();yse();iE();HO();NT();Ese()});var GO,dPt,Cse=_(()=>{qoe();joe();Goe();Yoe();PO();LO();BO();Xoe();Zoe();Joe();Qoe();ese();lse();hse();Sse();GO={...UO,...kO,...NO,...IO,...TO,..._O,...RO,...MO,...OO,...DO},dPt={...VO,...KO}});function Ise(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Ase,WO,RMe,FT,YO=_(()=>{Cse();Xt();Ase=Ise("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),WO=Ise("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=ar(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),RMe={utf8:Ase,"utf-8":Ase,hex:GO.base16,latin1:WO,ascii:WO,binary:WO,...GO},FT=RMe});function K(r,e="utf8"){let t=FT[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var me=_(()=>{YO()});function z(r,e="utf8"){let t=FT[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Le=_(()=>{YO()});function ZO(r,e={offset:0}){let t=r[e.offset]&LMe;if(e.offset++,Tse[t]!=null)return Tse[t](r,e);throw new Error("No decoder for tag "+t)}function lE(r,e){let t=0;if((r[e.offset]&XO)===XO){let n=r[e.offset]&MMe,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function cE(r,e){lE(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=ZO(r,e);if(n===null)break;t.push(n)}return t}function BMe(r,e){let t=lE(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function OMe(r,e){let t=lE(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function NMe(r,e){return e.offset++,null}function UMe(r,e){let t=lE(r,e),n=r[e.offset];e.offset++;let o=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 o}function FMe(r,e){let t=lE(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function KMe(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function JO(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=KMe(r.byteLength);return new Y(Uint8Array.from([e.byteLength|XO]),e)}function kse(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),JO(e),e)}function Dse(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),JO(t),t)}function KT(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),JO(t),t)}var LMe,XO,MMe,Tse,_se=_(()=>{ct();LMe=parseInt("11111",2),XO=parseInt("10000000",2),MMe=parseInt("01111111",2),Tse={0:cE,1:cE,2:BMe,3:UMe,4:FMe,5:NMe,6:OMe,16:cE,22:cE,48:cE}});async function Pse(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var Rse=_(()=>{});function Lse(r){let e=ZO(r);return Mse(e)}function Mse(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===QO*2+1)return n=z(e.subarray(t,t+QO),"base64url"),o=z(e.subarray(t+QO),"base64url"),new oy({...VMe,key_ops:["verify"],x:n,y:o});if(e.byteLength===eN*2+1)return n=z(e.subarray(t,t+eN),"base64url"),o=z(e.subarray(t+eN),"base64url"),new oy({...qMe,key_ops:["verify"],x:n,y:o});if(e.byteLength===tN*2+1)return n=z(e.subarray(t,t+tN),"base64url"),o=z(e.subarray(t+tN),"base64url"),new oy({...jMe,key_ops:["verify"],x:n,y:o});throw new q(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Bse(r){return KT([kse(Uint8Array.from([1])),KT([GMe(r.crv)],160),KT([Dse(new Y(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function GMe(r){if(r==="P-256")return zMe;if(r==="P-384")return $Me;if(r==="P-521")return HMe;throw new q(`Invalid curve ${r}`)}var zMe,$Me,HMe,VMe,qMe,jMe,QO,eN,tN,rN=_(()=>{se();ct();me();Le();_se();Ose();zMe=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),$Me=Uint8Array.from([6,5,43,129,4,0,34]),HMe=Uint8Array.from([6,5,43,129,4,0,35]),VMe={ext:!0,kty:"EC",crv:"P-256"},qMe={ext:!0,kty:"EC",crv:"P-384"},jMe={ext:!0,kty:"EC",crv:"P-521"},QO=32,eN=48,tN=66});var oy,Ose=_(()=>{Fh();Xg();Zg();Ne();uE();rN();Rse();oy=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Bse(this.jwk)),this._raw}toMultihash(){return za.digest(sy(this))}toCID(){return Ps.createV1(114,this.toMultihash())}toString(){return Ur.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}async verify(e,t,n){return Pse(this.jwk,t,e,n)}}});function zh(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ci(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function Me(r,e,t=""){let n=zh(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function $h(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ci(r.outputLen),ci(r.blockLen)}function iy(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 Use(r,e){Me(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Wi(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function zT(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Yi(r,e){return r<<32-e|r>>>e}function gl(r){if(Me(r),Fse)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=WMe[r[t]];return e}function Nse(r){if(r>=ml._0&&r<=ml._9)return r-ml._0;if(r>=ml.A&&r<=ml.F)return r-(ml.A-10);if(r>=ml.a&&r<=ml.f)return r-(ml.a-10)}function yl(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Fse)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 o=0,s=0;o<t;o++,s+=2){let i=Nse(r.charCodeAt(s)),a=Nse(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function es(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];Me(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function nN(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function ts(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var Fse,WMe,ml,oN,Xi=_(()=>{Fse=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",WMe=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));ml={_0:48,_9:57,A:65,F:70,a:97,f:102};oN=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function Kse(r,e,t){return r&e^~r&t}function zse(r,e,t){return r&e^r&t^e&t}var dE,bl,Tn,$se=_(()=>{Xi();dE=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=zT(this.buffer)}update(e){iy(this),Me(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=zT(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){iy(this),Use(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Wi(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=zT(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must 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 d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},bl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Tn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function YMe(r,e=!1){return e?{h:Number(r&$T),l:Number(r>>Hse&$T)}:{h:Number(r>>Hse&$T)|0,l:Number(r&$T)|0}}function Vse(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=YMe(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}function Ha(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var $T,Hse,sN,iN,Hh,Vh,fE,hE,qse,jse,Gse,Wse,Yse,Xse,Zse=_(()=>{$T=BigInt(4294967295),Hse=BigInt(32);sN=(r,e,t)=>r>>>t,iN=(r,e,t)=>r<<32-t|e>>>t,Hh=(r,e,t)=>r>>>t|e<<32-t,Vh=(r,e,t)=>r<<32-t|e>>>t,fE=(r,e,t)=>r<<64-t|e>>>t-32,hE=(r,e,t)=>r>>>t-32|e<<64-t;qse=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),jse=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Gse=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Wse=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Yse=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),Xse=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0});var ZMe,Od,aN,cN,Jse,JMe,QMe,Nd,Ud,lN,uN,lt,Qse,Va=_(()=>{$se();Zse();Xi();ZMe=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]),Od=new Uint32Array(64),aN=class extends dE{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)Od[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=Od[d-15],p=Od[d-2],f=Yi(h,7)^Yi(h,18)^h>>>3,g=Yi(p,17)^Yi(p,19)^p>>>10;Od[d]=g+Od[d-7]+f+Od[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=Yi(a,6)^Yi(a,11)^Yi(a,25),p=u+h+Kse(a,c,l)+ZMe[d]+Od[d]|0,g=(Yi(n,2)^Yi(n,13)^Yi(n,22))+zse(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Wi(Od)}destroy(){this.set(0,0,0,0,0,0,0,0),Wi(this.buffer)}},cN=class extends aN{A=bl[0]|0;B=bl[1]|0;C=bl[2]|0;D=bl[3]|0;E=bl[4]|0;F=bl[5]|0;G=bl[6]|0;H=bl[7]|0;constructor(){super(32)}},Jse=Vse(["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))),JMe=Jse[0],QMe=Jse[1],Nd=new Uint32Array(80),Ud=new Uint32Array(80),lN=class extends dE{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:p,Gl:f,Hh:g,Hl:y}=this;return[e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y]}set(e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)Nd[b]=e.getUint32(t),Ud[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=Nd[b-15]|0,S=Ud[b-15]|0,T=Hh(x,S,1)^Hh(x,S,8)^sN(x,S,7),A=Vh(x,S,1)^Vh(x,S,8)^iN(x,S,7),v=Nd[b-2]|0,C=Ud[b-2]|0,P=Hh(v,C,19)^fE(v,C,61)^sN(v,C,6),F=Vh(v,C,19)^hE(v,C,61)^iN(v,C,6),R=Gse(A,F,Ud[b-7],Ud[b-16]),k=Wse(R,T,P,Nd[b-7],Nd[b-16]);Nd[b]=k|0,Ud[b]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:p,Fl:f,Gh:g,Gl:y,Hh:m,Hl:w}=this;for(let b=0;b<80;b++){let x=Hh(d,h,14)^Hh(d,h,18)^fE(d,h,41),S=Vh(d,h,14)^Vh(d,h,18)^hE(d,h,41),T=d&p^~d&g,A=h&f^~h&y,v=Yse(w,S,A,QMe[b],Ud[b]),C=Xse(v,m,x,T,JMe[b],Nd[b]),P=v|0,F=Hh(n,o,28)^fE(n,o,34)^fE(n,o,39),R=Vh(n,o,28)^hE(n,o,34)^hE(n,o,39),k=n&s^n&a^s&a,I=o&i^o&c^i&c;m=g|0,w=y|0,g=p|0,y=f|0,p=d|0,f=h|0,{h:d,l:h}=Ha(l|0,u|0,C|0,P|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=qse(P,R,I);n=jse(E,C,F,k),o=E|0}({h:n,l:o}=Ha(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=Ha(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=Ha(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Ha(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=Ha(this.Eh|0,this.El|0,d|0,h|0),{h:p,l:f}=Ha(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:y}=Ha(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:w}=Ha(this.Hh|0,this.Hl|0,m|0,w|0),this.set(n,o,s,i,a,c,l,u,d,h,p,f,g,y,m,w)}roundClean(){Wi(Nd,Ud)}destroy(){Wi(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},uN=class extends lN{Ah=Tn[0]|0;Al=Tn[1]|0;Bh=Tn[2]|0;Bl=Tn[3]|0;Ch=Tn[4]|0;Cl=Tn[5]|0;Dh=Tn[6]|0;Dl=Tn[7]|0;Eh=Tn[8]|0;El=Tn[9]|0;Fh=Tn[10]|0;Fl=Tn[11]|0;Gh=Tn[12]|0;Gl=Tn[13]|0;Hh=Tn[14]|0;Hl=Tn[15]|0;constructor(){super(64)}},lt=nN(()=>new cN,oN(1)),Qse=nN(()=>new uN,oN(3))});function wl(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function eie(r){if(typeof r=="bigint"){if(!HT(r))throw new Error("positive bigint expected, got "+r)}else ci(r);return r}function pE(r){let e=eie(r).toString(16);return e.length&1?"0"+e:e}function tie(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?fN:BigInt("0x"+r)}function ay(r){return tie(gl(r))}function qa(r){return tie(gl(qh(Me(r)).reverse()))}function VT(r,e){ci(e),r=eie(r);let t=yl(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function mE(r,e){return VT(r,e).reverse()}function qh(r){return Uint8Array.from(r)}function eBe(r,e,t){return HT(r)&&HT(e)&&HT(t)&&e<=r&&r<t}function Fd(r,e,t,n){if(!eBe(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function hN(r){let e;for(e=0;r>fN;r>>=dN,e+=1);return e}function rie(r,e,t){if(ci(r,"hashLen"),ci(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},h=(...y)=>t(l,es(c,...y)),p=(y=o)=>{l=h(s,y),c=h(),y.length!==0&&(l=h(i,y),c=h())},f=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=h();let w=c.slice();m.push(w),y+=c.length}return es(...m)};return(y,m)=>{d(),p(y);let w;for(;!(w=m(f()));)p();return d(),w}}function ja(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function cy(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var fN,dN,HT,gE,ly=_(()=>{Xi();Xi();fN=BigInt(0),dN=BigInt(1);HT=r=>typeof r=="bigint"&&fN<=r;gE=r=>(dN<<BigInt(r))-dN});function $t(r,e){let t=r%e;return t>=Lo?t:e+t}function Mt(r,e,t){let n=r;for(;e-- >Lo;)n*=n,n%=t;return n}function nie(r,e){if(r===Lo)throw new Error("invert: expected non-zero number");if(e<=Lo)throw new Error("invert: expected positive modulus, got "+e);let t=$t(r,e),n=e,o=Lo,s=Yr,i=Yr,a=Lo;for(;t!==Lo;){let l=n/t,u=n%t,d=o-i*l,h=s-a*l;n=t,t=u,o=i,s=a,i=d,a=h}if(n!==Yr)throw new Error("invert: does not exist");return $t(o,e)}function mN(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function uie(r,e){let t=(r.ORDER+Yr)/iie,n=r.pow(e,t);return mN(r,n,e),n}function nBe(r,e){let t=(r.ORDER-aie)/cie,n=r.mul(e,jh),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,jh),o),a=r.mul(s,r.sub(i,r.ONE));return mN(r,a,e),a}function oBe(r){let e=uy(r),t=die(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+tBe)/lie;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),d=a.mul(l,o),h=a.mul(l,s),p=a.eql(a.sqr(u),c),f=a.eql(a.sqr(d),c);l=a.cmov(l,u,p),u=a.cmov(h,d,f);let g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return mN(a,y,c),y}}function die(r){if(r<sie)throw new Error("sqrt is not defined for small field");let e=r-Yr,t=0;for(;e%jh===Lo;)e/=jh,t++;let n=jh,o=uy(r);for(;oie(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return uie;let s=o.pow(n,e),i=(e+Yr)/jh;return function(c,l){if(c.is0(l))return l;if(oie(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,s),h=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let f=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(f++,g=c.sqr(g),f===u)throw new Error("Cannot find square root");let y=Yr<<BigInt(u-f-1),m=c.pow(d,y);u=f,d=c.sqr(m),h=c.mul(h,d),p=c.mul(p,m)}return p}}function sBe(r){return r%iie===sie?uie:r%cie===aie?nBe:r%lie===rBe?oBe(r):die(r)}function gN(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=iBe.reduce((n,o)=>(n[o]="function",n),e);return ja(r,t),r}function aBe(r,e,t){if(t<Lo)throw new Error("invalid exponent, negatives unsupported");if(t===Lo)return r.ONE;if(t===Yr)return e;let n=r.ONE,o=e;for(;t>Lo;)t&Yr&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Yr;return n}function yE(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function oie(r,e){let t=(r.ORDER-Yr)/jh,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function cBe(r,e){e!==void 0&&ci(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function uy(r,e={}){return new pN(r,e)}function hie(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 yN(r){let e=hie(r);return e+Math.ceil(e/2)}function bN(r,e,t=!1){Me(r);let n=r.length,o=hie(e),s=yN(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?qa(r):ay(r),a=$t(i,e-Yr)+Yr;return t?mE(a,o):VT(a,o)}var Lo,Yr,jh,sie,iie,aie,tBe,cie,rBe,lie,fie,iBe,pN,dy=_(()=>{ly();Lo=BigInt(0),Yr=BigInt(1),jh=BigInt(2),sie=BigInt(3),iie=BigInt(4),aie=BigInt(5),tBe=BigInt(7),cie=BigInt(8),rBe=BigInt(9),lie=BigInt(16);fie=(r,e)=>($t(r,e)&Yr)===Yr,iBe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];pN=class{ORDER;BITS;BYTES;isLE;ZERO=Lo;ONE=Yr;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Lo)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=cBe(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return $t(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Lo<=e&&e<this.ORDER}is0(e){return e===Lo}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Yr)===Yr}neg(e){return $t(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return $t(e*e,this.ORDER)}add(e,t){return $t(e+t,this.ORDER)}sub(e,t){return $t(e-t,this.ORDER)}mul(e,t){return $t(e*t,this.ORDER)}pow(e,t){return aBe(this,e,t)}div(e,t){return $t(e*nie(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return nie(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=sBe(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?mE(e,this.BYTES):VT(e,this.BYTES)}fromBytes(e,t=!1){Me(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?qa(e):ay(e);if(a&&(c=$t(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return yE(this,e)}cmov(e,t,n){return n?t:e}}});function bE(r,e){let t=e.negate();return r?t:e}function Wh(r,e){let t=yE(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function yie(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function wN(r,e){yie(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=gE(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function pie(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=Gh);let l=e*n,u=l+Math.abs(a)-1,d=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:p,offsetF:l}}function vN(r){return bie.get(r)||1}function mie(r){if(r!==fy)throw new Error("invalid wNAF")}function wie(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>fy||n>fy;)t&Gh&&(s=s.add(o)),n&Gh&&(i=i.add(o)),o=o.double(),t>>=Gh,n>>=Gh;return{p1:s,p2:i}}function gie(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return gN(e),e}else return uy(r,{isLE:t})}function qT(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>fy))throw new Error(`CURVE.${c} must be positive bigint`)}let o=gie(e.p,t.Fp,n),s=gie(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.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:o,Fn:s}}function py(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var fy,Gh,xN,bie,hy,jT=_(()=>{ly();dy();fy=BigInt(0),Gh=BigInt(1);xN=new WeakMap,bie=new WeakMap;hy=class{BASE;ZERO;Fn;bits;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 o=e;for(;t>fy;)t&Gh&&(n=n.add(o)),o=o.double(),t>>=Gh;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=wN(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=wN(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:p}=pie(n,a,i);n=c,u?s=s.add(bE(h,t[p])):o=o.add(bE(d,t[l]))}return mie(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=wN(e,this.bits);for(let i=0;i<s.windows&&n!==fy;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=pie(n,i,s);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return mie(n),o}getPrecomputes(e,t,n){let o=xN.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),xN.set(t,o))),o}cached(e,t,n){let o=vN(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=vN(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){yie(t,this.bits),bie.set(e,t),xN.delete(e)}hasCache(e){return vN(e)!==1}}});function uBe(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function xie(r,e={}){let t=qT("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;ja(e,{},{uvRatio:"function"});let a=EN<<BigInt(o.BYTES*8)-Xr,c=y=>n.create(y),l=e.uvRatio||((y,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,m))}}catch{return{isValid:!1,value:Kd}}});if(!uBe(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(y,m,w=!1){let b=w?Xr:Kd;return Fd("coordinate "+y,m,b,a),m}function d(y){if(!(y instanceof f))throw new Error("EdwardsPoint expected")}let h=cy((y,m)=>{let{X:w,Y:b,Z:x}=y,S=y.is0();m==null&&(m=S?lBe:n.inv(x));let T=c(w*m),A=c(b*m),v=n.mul(x,m);if(S)return{x:Kd,y:Xr};if(v!==Xr)throw new Error("invZ was invalid");return{x:T,y:A}}),p=cy(y=>{let{a:m,d:w}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:b,Y:x,Z:S,T}=y,A=c(b*b),v=c(x*x),C=c(S*S),P=c(C*C),F=c(A*m),R=c(C*c(F+v)),k=c(P+c(w*c(A*v)));if(R!==k)throw new Error("bad point: equation left != right (1)");let I=c(b*x),E=c(S*T);if(I!==E)throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,Xr,c(s.Gx*s.Gy));static ZERO=new f(Kd,Xr,Xr,Kd);static Fp=n;static Fn=o;X;Y;Z;T;constructor(m,w,b,x){this.X=u("x",m),this.Y=u("y",w),this.Z=u("z",b,!0),this.T=u("t",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof f)throw new Error("extended point not allowed");let{x:w,y:b}=m||{};return u("x",w),u("y",b),new f(w,b,Xr,c(w*b))}static fromBytes(m,w=!1){let b=n.BYTES,{a:x,d:S}=s;m=qh(Me(m,b,"point")),wl(w,"zip215");let T=qh(m),A=m[b-1];T[b-1]=A&-129;let v=qa(T),C=w?a:n.ORDER;Fd("point.y",v,Kd,C);let P=c(v*v),F=c(P-Xr),R=c(S*P-x),{isValid:k,value:I}=l(F,R);if(!k)throw new Error("bad point: invalid y coordinate");let E=(I&Xr)===Xr,D=(A&128)!==0;if(!w&&I===Kd&&D)throw new Error("bad point: x=0 and x_0=1");return D!==E&&(I=c(-I)),f.fromAffine({x:I,y:v})}static fromHex(m,w=!1){return f.fromBytes(yl(m),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return g.createCache(this,m),w||this.multiply(EN),this}assertValidity(){p(this)}equals(m){d(m);let{X:w,Y:b,Z:x}=this,{X:S,Y:T,Z:A}=m,v=c(w*A),C=c(S*x),P=c(b*A),F=c(T*x);return v===C&&P===F}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=s,{X:w,Y:b,Z:x}=this,S=c(w*w),T=c(b*b),A=c(EN*c(x*x)),v=c(m*S),C=w+b,P=c(c(C*C)-S-T),F=v+T,R=F-A,k=v-T,I=c(P*R),E=c(F*k),D=c(P*k),M=c(R*F);return new f(I,E,M,D)}add(m){d(m);let{a:w,d:b}=s,{X:x,Y:S,Z:T,T:A}=this,{X:v,Y:C,Z:P,T:F}=m,R=c(x*v),k=c(S*C),I=c(A*b*F),E=c(T*P),D=c((x+S)*(v+C)-R-k),M=E-I,B=E+I,L=c(k-w*R),O=c(D*M),U=c(B*L),$=c(D*L),J=c(M*B);return new f(O,U,J,$)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:b}=g.cached(this,m,x=>Wh(f,x));return Wh(f,[w,b])[0]}multiplyUnsafe(m,w=f.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===Kd?f.ZERO:this.is0()||m===Xr?this:g.unsafe(this,m,b=>Wh(f,b),w)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(m){return h(this,m)}clearCofactor(){return i===Xr?this:this.multiplyUnsafe(i)}toBytes(){let{x:m,y:w}=this.toAffine(),b=n.toBytes(w);return b[b.length-1]|=m&Xr?128:0,b}toHex(){return gl(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new hy(f,o.BITS);return f.BASE.precompute(8),f}function vie(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');ja(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||ts,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,C,P)=>{if(wl(P,"phflag"),C.length||P)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(qa(v))}function d(v){let C=b.secretKey;Me(v,b.secretKey,"secretKey");let P=Me(e(v),2*C,"hashedSecretKey"),F=c(P.slice(0,C)),R=P.slice(C,2*C),k=u(F);return{head:F,prefix:R,scalar:k}}function h(v){let{head:C,prefix:P,scalar:F}=d(v),R=o.multiply(F),k=R.toBytes();return{head:C,prefix:P,scalar:F,point:R,pointBytes:k}}function p(v){return h(v).pointBytes}function f(v=Uint8Array.of(),...C){let P=es(...C);return u(e(l(P,Me(v,void 0,"context"),!!n)))}function g(v,C,P={}){v=Me(v,void 0,"message"),n&&(v=n(v));let{prefix:F,scalar:R,pointBytes:k}=h(C),I=f(P.context,F,v),E=o.multiply(I).toBytes(),D=f(P.context,E,k,v),M=i.create(I+D*R);if(!i.isValid(M))throw new Error("sign failed: invalid s");let B=es(E,i.toBytes(M));return Me(B,b.signature,"result")}let y={zip215:!0};function m(v,C,P,F=y){let{context:R,zip215:k}=F,I=b.signature;v=Me(v,I,"signature"),C=Me(C,void 0,"message"),P=Me(P,b.publicKey,"publicKey"),k!==void 0&&wl(k,"zip215"),n&&(C=n(C));let E=I/2,D=v.subarray(0,E),M=qa(v.subarray(E,I)),B,L,O;try{B=r.fromBytes(P,k),L=r.fromBytes(D,k),O=o.multiplyUnsafe(M)}catch{return!1}if(!k&&B.isSmallOrder())return!1;let U=f(R,L.toBytes(),B.toBytes(),C);return L.add(B.multiplyUnsafe(U)).subtract(O).clearCofactor().is0()}let w=s.BYTES,b={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(v=a(b.seed)){return Me(v,b.seed,"seed")}function S(v){return zh(v)&&v.length===i.BYTES}function T(v,C){try{return!!r.fromBytes(v,C)}catch{return!1}}let A={getExtendedPublicKey:h,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:T,toMontgomery(v){let{y:C}=r.fromBytes(v),P=b.publicKey,F=P===32;if(!F&&P!==57)throw new Error("only defined for 25519 and 448");let R=F?s.div(Xr+C,Xr-C):s.div(C-Xr,C+Xr);return s.toBytes(R)},toMontgomerySecret(v){let C=b.secretKey;Me(v,C);let P=e(v.subarray(0,C));return c(P).subarray(0,C)}};return Object.freeze({keygen:py(x,p),getPublicKey:p,sign:g,verify:m,utils:A,Point:r,lengths:b})}var Kd,Xr,EN,lBe,Eie=_(()=>{ly();jT();Kd=BigInt(0),Xr=BigInt(1),EN=BigInt(2),lBe=BigInt(8)});function dBe(r){return ja(r,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...r})}function Sie(r){let e=dBe(r),{P:t,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||ts,l=a?255:448,u=a?32:56,d=BigInt(a?9:5),h=BigInt(a?121665:39081),p=a?GT**BigInt(254):GT**BigInt(447),f=a?BigInt(8)*GT**BigInt(251)-my:BigInt(4)*GT**BigInt(445)-my,g=p+f+my,y=I=>$t(I,t),m=w(d);function w(I){return mE(y(I),u)}function b(I){let E=qh(Me(I,u,"uCoordinate"));return a&&(E[31]&=127),y(qa(E))}function x(I){return qa(o(qh(Me(I,u,"scalar"))))}function S(I,E){let D=P(b(E),x(I));if(D===wE)throw new Error("invalid private or public key received");return w(D)}function T(I){return S(I,m)}let A=T,v=S;function C(I,E,D){let M=y(I*(E-D));return E=y(E-M),D=y(D+M),{x_2:E,x_3:D}}function P(I,E){Fd("u",I,wE,t),Fd("scalar",E,p,g);let D=E,M=I,B=my,L=wE,O=I,U=my,$=wE;for(let X=BigInt(l-1);X>=wE;X--){let N=D>>X&my;$^=N,{x_2:B,x_3:O}=C($,B,O),{x_2:L,x_3:U}=C($,L,U),$=N;let H=B+L,Z=y(H*H),ae=B-L,Q=y(ae*ae),oe=Z-Q,Fe=O+U,nr=O-U,fe=y(nr*H),Ce=y(Fe*ae),Ve=fe+Ce,Er=fe-Ce;O=y(Ve*Ve),U=y(M*y(Er*Er)),B=y(Z*Q),L=y(oe*(Z+y(h*oe)))}({x_2:B,x_3:O}=C($,B,O)),{x_2:L,x_3:U}=C($,L,U);let J=s(L);return y(B*J)}let F={secretKey:u,publicKey:u,seed:u},R=(I=c(u))=>(Me(I,F.seed,"seed"),I),k={randomSecretKey:R};return Object.freeze({keygen:py(R,A),getSharedSecret:v,getPublicKey:A,scalarMult:S,scalarMultBase:T,utils:k,GuBytes:m.slice(),lengths:F})}var wE,my,GT,Cie=_(()=>{ly();jT();dy();wE=BigInt(0),my=BigInt(1),GT=BigInt(2)});function Tie(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=WT,a=r*r%s*r%s,c=Mt(a,Aie,s)*a%s,l=Mt(c,fBe,s)*r%s,u=Mt(l,pBe,s)*l%s,d=Mt(u,e,s)*u%s,h=Mt(d,t,s)*d%s,p=Mt(h,n,s)*h%s,f=Mt(p,o,s)*p%s,g=Mt(f,o,s)*p%s,y=Mt(g,e,s)*u%s;return{pow_p_5_8:Mt(y,Aie,s)*r%s,b2:a}}function kie(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function yBe(r,e){let t=WT,n=$t(e*e*e,t),o=$t(n*n*e,t),s=Tie(r*o).pow_p_5_8,i=$t(r*n*s,t),a=$t(e*i*i,t),c=i,l=$t(i*Iie,t),u=a===r,d=a===$t(-r,t),h=a===$t(-r*Iie,t);return u&&(i=c),(d||h)&&(i=l),fie(i,t)&&(i=$t(-i,t)),{isValid:u||d,value:i}}function wBe(r){return vie(bBe,Qse,Object.assign({adjustScalarBytes:kie},r))}var fBe,Aie,hBe,pBe,mBe,WT,gBe,Iie,bBe,Ht,xE,Ga=_(()=>{Va();Eie();dy();Cie();fBe=BigInt(1),Aie=BigInt(2),hBe=BigInt(3),pBe=BigInt(5),mBe=BigInt(8),WT=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),gBe={p:WT,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mBe,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};Iie=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");bBe=xie(gBe,{uvRatio:yBe});Ht=wBe({}),xE=(()=>{let r=WT;return Sie({P:r,type:"x25519",powPminus2:e=>{let{pow_p_5_8:t,b2:n}=Tie(e);return $t(Mt(t,hBe,r)*n,r)},adjustScalarBytes:kie})})()});var vE,YT,SN=_(()=>{vE=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},YT=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}});var Die,_ie=_(()=>{SN();Die={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new YT("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 XT,Pie=_(()=>{_ie();XT=Die});async function vBe(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await XT.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await XT.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 EBe(r,e,t){return Ht.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Rie(r,e,t){return CN==null&&(CN=await xBe),CN?vBe(r,e,t):EBe(r,e,t)}var ZT,CN,xBe,AN=_(()=>{Ga();Le();Pie();ZT=32,xBe=(async()=>{try{return await XT.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})()});function JT(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var IN=_(()=>{Mr();me()});var QT,Mie=_(()=>{Fh();Xg();Zg();Ne();IN();uE();kN();AN();QT=class{type="Ed25519";raw;constructor(e){this.raw=TN(e,ZT)}toMultihash(){return za.digest(sy(this))}toCID(){return Ps.createV1(114,this.toMultihash())}toString(){return Ur.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Rie(this.raw,t,e);return JT(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}}});function Bie(r){return r=TN(r,ZT),new QT(r)}function TN(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new q(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var kN=_(()=>{se();Mie();AN()});function Oie(r,e,t){DN[0]=r,e[t]=zd[0],e[t+1]=zd[1],e[t+2]=zd[2],e[t+3]=zd[3]}function Nie(r,e){return zd[0]=r[e],zd[1]=r[e+1],zd[2]=r[e+2],zd[3]=r[e+3],DN[0]}function Uie(r,e,t){_N[0]=r,e[t]=io[0],e[t+1]=io[1],e[t+2]=io[2],e[t+3]=io[3],e[t+4]=io[4],e[t+5]=io[5],e[t+6]=io[6],e[t+7]=io[7]}function Fie(r,e){return io[0]=r[e],io[1]=r[e+1],io[2]=r[e+2],io[3]=r[e+3],io[4]=r[e+4],io[5]=r[e+5],io[6]=r[e+6],io[7]=r[e+7],_N[0]}var DN,zd,_N,io,PN=_(()=>{DN=new Float32Array([-0]),zd=new Uint8Array(DN.buffer);_N=new Float64Array([-0]),io=new Uint8Array(_N.buffer)});var CBe,ABe,Rs,Yh,Kie,RN=_(()=>{CBe=BigInt(Number.MAX_SAFE_INTEGER),ABe=BigInt(Number.MIN_SAFE_INTEGER),Rs=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 Yh;if(e<CBe&&e>ABe)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Kie&&(o=0n,++n>Kie&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return Yh;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}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):Yh}},Yh=new Rs(0,0);Yh.toBigInt=function(){return 0n};Yh.zzEncode=Yh.zzDecode=function(){return this};Yh.length=function(){return 1};Kie=4294967296n});function zie(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 $ie(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function LN(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}var MN=_(()=>{});function Zi(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function e6(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function EE(r){return new BN(r instanceof Uint8Array?r:r.subarray())}var BN,t6=_(()=>{si();PN();RN();MN();BN=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,Zi(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 Zi(this,4);return e6(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Zi(this,4);return e6(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw Zi(this,4);let e=Nie(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Zi(this,4);let e=Fie(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 Zi(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return $ie(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw Zi(this,e);this.pos+=e}else do if(this.pos>=this.len)throw Zi(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 Rs(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 Zi(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 Zi(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 Zi(this,8);let e=e6(this.buf,this.pos+=4),t=e6(this.buf,this.pos+=4);return new Rs(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=eO(this.buf,this.pos);return this.pos+=mt(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 ye(r,e,t){let n=EE(r);return e.decode(n,void 0,t)}var Vie=_(()=>{t6()});function ON(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ar(i);o+i>e&&(n=ar(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var qie=_(()=>{Xt()});function NN(){}function TBe(r){return globalThis.Buffer!=null?ar(r):IBe(r)}function UN(r,e,t){e[t]=r&255}function kBe(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function r6(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 SE(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 DBe(r,e,t){e.set(r,t)}function _Be(r,e,t){e.set(r,t)}function PBe(r,e,t){r.length<40?LN(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(K(r),t)}function zN(){return new CE}var Xh,FN,IBe,CE,KN,$N=_(()=>{si();Xt();me();PN();RN();qie();MN();Xh=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};FN=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},IBe=ON();CE=class{len;head;tail;states;constructor(){this.len=0,this.head=new Xh(NN,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Xh(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new KN((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(r6,10,Rs.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Rs.fromBigInt(e);return this._push(r6,t.length(),t)}uint64Number(e){return this._push(ul,mt(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=Rs.fromBigInt(e).zzEncode();return this._push(r6,t.length(),t)}sint64Number(e){let t=Rs.fromNumber(e).zzEncode();return this._push(r6,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(UN,1,e?1:0)}fixed32(e){return this._push(SE,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Rs.fromBigInt(e);return this._push(SE,4,t.lo)._push(SE,4,t.hi)}fixed64Number(e){let t=Rs.fromNumber(e);return this._push(SE,4,t.lo)._push(SE,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(Oie,4,e)}double(e){return this._push(Uie,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(UN,1,0):this.uint32(t)._push(DBe,t,e)}string(e){let t=zie(e);return t!==0?this.uint32(t)._push(LN,t,e):this._push(UN,1,0)}fork(){return this.states=new FN(this),this.head=this.tail=new Xh(NN,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 Xh(NN,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=TBe(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};KN=class extends Xh{next;constructor(e,t){super(kBe,e,t),this.next=void 0}};globalThis.Buffer!=null&&(CE.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(_Be,e,r),this},CE.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(PBe,e,r),this})});function be(r,e){let t=zN();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var jie=_(()=>{$N()});function*Ji(r,e,t){let n=EE(r);yield*e.stream(n,void 0,"$",t)}var Gie=_(()=>{t6()});function o6(r,e,t,n,o){return{name:r,type:e,encode:t,decode:n,stream:o}}var n6,HN=_(()=>{n6={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5}});function Pt(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(i,a){let c=e(i);a.int32(c)},n=function(i){let a=i.int32();return e(a)},o=function*(i){let a=i.int32();yield e(a)};return o6("enum",n6.VARINT,t,n,o)}var Wie=_(()=>{HN()});function we(r,e,t){return o6("message",n6.LENGTH_DELIMITED,r,e,t)}var Yie=_(()=>{HN()});var lr,AE,kn=_(()=>{Vie();jie();Gie();Wie();Yie();t6();$N();lr=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"},AE=class extends Error{code="ERR_MAX_SIZE";name="MaxSizeError"}});var Ls,VN,IE,qN,Xie=_(()=>{kn();(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ls||(Ls={}));(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(VN||(VN={}));(function(r){r.codec=()=>Pt(VN)})(Ls||(Ls={}));(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ls.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Ls.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(IE||(IE={}));(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ls.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Ls.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(qN||(qN={}))});var s6,gy,jN=_(()=>{Xi();s6=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if($h(e),Me(t,void 0,"key"),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 n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);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),Wi(o)}update(e){return iy(this),this.iHash.update(e),this}digestInto(e){iy(this),Me(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,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()}},gy=(r,e,t)=>new s6(r,e).update(t).digest();gy.create=(r,e)=>new s6(r,e)});function LBe(r,e,t){let[[n,o],[s,i]]=e,a=Zie(i*r,t),c=Zie(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,d=l<xl,h=u<xl;d&&(l=-l),h&&(u=-u);let p=gE(Math.ceil(hN(t)/2))+yy;if(l<xl||l>=p||u<xl||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:d,k1:l,k2neg:h,k2:u}}function WN(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function GN(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return wl(t.lowS,"lowS"),wl(t.prehash,"prehash"),t.format!==void 0&&WN(t.format),t}function Qie(r,e={}){let t=qT("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;ja(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=tae(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(R,k,I){let{x:E,y:D}=k.toAffine(),M=n.toBytes(E);if(wl(I,"isCompressed"),I){u();let B=!n.isOdd(D);return es(eae(B),M)}else return es(Uint8Array.of(4),M,n.toBytes(D))}function h(R){Me(R,void 0,"Point");let{publicKey:k,publicKeyUncompressed:I}=l,E=R.length,D=R[0],M=R.subarray(1);if(E===k&&(D===2||D===3)){let B=n.fromBytes(M);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let L=g(B),O;try{O=n.sqrt(L)}catch(J){let X=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();let U=n.isOdd(O);return(D&1)===1!==U&&(O=n.neg(O)),{x:B,y:O}}else if(E===I&&D===4){let B=n.BYTES,L=n.fromBytes(M.subarray(0,B)),O=n.fromBytes(M.subarray(B,B*2));if(!y(L,O))throw new Error("bad point: is not on curve");return{x:L,y:O}}else throw new Error(`bad point: got length ${E}, expected compressed=${k} or uncompressed=${I}`)}let p=e.toBytes||d,f=e.fromBytes||h;function g(R){let k=n.sqr(R),I=n.mul(k,R);return n.add(n.add(I,n.mul(R,s.a)),s.b)}function y(R,k){let I=n.sqr(k),E=g(R);return n.eql(I,E)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(s.a,i6),MBe),w=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(m,w)))throw new Error("bad curve params: a or b");function b(R,k,I=!1){if(!n.isValid(k)||I&&n.is0(k))throw new Error(`bad point coordinate ${R}`);return k}function x(R){if(!(R instanceof C))throw new Error("Weierstrass Point expected")}function S(R){if(!c||!c.basises)throw new Error("no endo");return LBe(R,c.basises,o.ORDER)}let T=cy((R,k)=>{let{X:I,Y:E,Z:D}=R;if(n.eql(D,n.ONE))return{x:I,y:E};let M=R.is0();k==null&&(k=M?n.ONE:n.inv(D));let B=n.mul(I,k),L=n.mul(E,k),O=n.mul(D,k);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:B,y:L}}),A=cy(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:k,y:I}=R.toAffine();if(!n.isValid(k)||!n.isValid(I))throw new Error("bad point: x or y not field elements");if(!y(k,I))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(R,k,I,E,D){return I=new C(n.mul(I.X,R),I.Y,I.Z),k=bE(E,k),I=bE(D,I),k.add(I)}class C{static BASE=new C(s.Gx,s.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(k,I,E){this.X=b("x",k),this.Y=b("y",I,!0),this.Z=b("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(k){let{x:I,y:E}=k||{};if(!k||!n.isValid(I)||!n.isValid(E))throw new Error("invalid affine point");if(k instanceof C)throw new Error("projective point not allowed");return n.is0(I)&&n.is0(E)?C.ZERO:new C(I,E,n.ONE)}static fromBytes(k){let I=C.fromAffine(f(Me(k,void 0,"point")));return I.assertValidity(),I}static fromHex(k){return C.fromBytes(yl(k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,I=!0){return F.createCache(this,k),I||this.multiply(i6),this}assertValidity(){A(this)}hasEvenY(){let{y:k}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(k)}equals(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.eql(n.mul(I,L),n.mul(M,D)),U=n.eql(n.mul(E,L),n.mul(B,D));return O&&U}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:k,b:I}=s,E=n.mul(I,i6),{X:D,Y:M,Z:B}=this,L=n.ZERO,O=n.ZERO,U=n.ZERO,$=n.mul(D,D),J=n.mul(M,M),X=n.mul(B,B),N=n.mul(D,M);return N=n.add(N,N),U=n.mul(D,B),U=n.add(U,U),L=n.mul(k,U),O=n.mul(E,X),O=n.add(L,O),L=n.sub(J,O),O=n.add(J,O),O=n.mul(L,O),L=n.mul(N,L),U=n.mul(E,U),X=n.mul(k,X),N=n.sub($,X),N=n.mul(k,N),N=n.add(N,U),U=n.add($,$),$=n.add(U,$),$=n.add($,X),$=n.mul($,N),O=n.add(O,$),X=n.mul(M,B),X=n.add(X,X),$=n.mul(X,N),L=n.sub(L,$),U=n.mul(X,J),U=n.add(U,U),U=n.add(U,U),new C(L,O,U)}add(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.ZERO,U=n.ZERO,$=n.ZERO,J=s.a,X=n.mul(s.b,i6),N=n.mul(I,M),H=n.mul(E,B),Z=n.mul(D,L),ae=n.add(I,E),Q=n.add(M,B);ae=n.mul(ae,Q),Q=n.add(N,H),ae=n.sub(ae,Q),Q=n.add(I,D);let oe=n.add(M,L);return Q=n.mul(Q,oe),oe=n.add(N,Z),Q=n.sub(Q,oe),oe=n.add(E,D),O=n.add(B,L),oe=n.mul(oe,O),O=n.add(H,Z),oe=n.sub(oe,O),$=n.mul(J,Q),O=n.mul(X,Z),$=n.add(O,$),O=n.sub(H,$),$=n.add(H,$),U=n.mul(O,$),H=n.add(N,N),H=n.add(H,N),Z=n.mul(J,Z),Q=n.mul(X,Q),H=n.add(H,Z),Z=n.sub(N,Z),Z=n.mul(J,Z),Q=n.add(Q,Z),N=n.mul(H,Q),U=n.add(U,N),N=n.mul(oe,Q),O=n.mul(ae,O),O=n.sub(O,N),N=n.mul(ae,H),$=n.mul(oe,$),$=n.add($,N),new C(O,U,$)}subtract(k){return this.add(k.negate())}is0(){return this.equals(C.ZERO)}multiply(k){let{endo:I}=e;if(!o.isValidNot0(k))throw new Error("invalid scalar: out of range");let E,D,M=B=>F.cached(this,B,L=>Wh(C,L));if(I){let{k1neg:B,k1:L,k2neg:O,k2:U}=S(k),{p:$,f:J}=M(L),{p:X,f:N}=M(U);D=J.add(N),E=v(I.beta,$,X,B,O)}else{let{p:B,f:L}=M(k);E=B,D=L}return Wh(C,[E,D])[0]}multiplyUnsafe(k){let{endo:I}=e,E=this;if(!o.isValid(k))throw new Error("invalid scalar: out of range");if(k===xl||E.is0())return C.ZERO;if(k===yy)return E;if(F.hasCache(this))return this.multiply(k);if(I){let{k1neg:D,k1:M,k2neg:B,k2:L}=S(k),{p1:O,p2:U}=wie(C,E,M,L);return v(I.beta,O,U,D,B)}else return F.unsafe(E,k)}toAffine(k){return T(this,k)}isTorsionFree(){let{isTorsionFree:k}=e;return i===yy?!0:k?k(C,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:k}=e;return i===yy?this:k?k(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return wl(k,"isCompressed"),this.assertValidity(),p(C,this,k)}toHex(k=!0){return gl(this.toBytes(k))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,F=new hy(C,e.endo?Math.ceil(P/2):P);return C.BASE.precompute(8),C}function eae(r){return Uint8Array.of(r?2:3)}function tae(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function BBe(r,e={}){let{Fn:t}=r,n=e.randomBytes||ts,o=Object.assign(tae(r.Fp,t),{seed:yN(t.ORDER)});function s(p){try{let f=t.fromBytes(p);return t.isValidNot0(f)}catch{return!1}}function i(p,f){let{publicKey:g,publicKeyUncompressed:y}=o;try{let m=p.length;return f===!0&&m!==g||f===!1&&m!==y?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return bN(Me(p,o.seed,"seed"),t.ORDER)}function c(p,f=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(f)}function l(p){let{secretKey:f,publicKey:g,publicKeyUncompressed:y}=o;if(!zh(p)||"_lengths"in t&&t._lengths||f===g)return;let m=Me(p,void 0,"key").length;return m===g||m===y}function u(p,f,g=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(f)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(p);return r.fromBytes(f).multiply(y).toBytes(g)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=py(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:d,lengths:o})}function rae(r,e,t={}){$h(e),ja(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||ts,o=t.hmac||((I,E)=>gy(e,I,E)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p}=BBe(r,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=a*Jie<s.ORDER;function y(I){let E=a>>yy;return I>E}function m(I,E){if(!i.isValidNot0(E))throw new Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return E}function w(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(I,E){WN(E);let D=p.signature,M=E==="compact"?D:E==="recovered"?D+1:void 0;return Me(I,M)}class x{r;s;recovery;constructor(E,D,M){if(this.r=m("r",E),this.s=m("s",D),M!=null){if(w(),![0,1,2,3].includes(M))throw new Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(E,D=f.format){b(E,D);let M;if(D==="der"){let{r:U,s:$}=$d.toSig(Me(E));return new x(U,$)}D==="recovered"&&(M=E[0],D="compact",E=E.subarray(1));let B=p.signature/2,L=E.subarray(0,B),O=E.subarray(B,B*2);return new x(i.fromBytes(L),i.fromBytes(O),M)}static fromHex(E,D){return this.fromBytes(yl(E),D)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new x(this.r,this.s,E)}recoverPublicKey(E){let{r:D,s:M}=this,B=this.assertRecovery(),L=B===2||B===3?D+a:D;if(!s.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=s.toBytes(L),U=r.fromBytes(es(eae((B&1)===0),O)),$=i.inv(L),J=T(Me(E,void 0,"msgHash")),X=i.create(-J*$),N=i.create(M*$),H=r.BASE.multiplyUnsafe(X).add(U.multiplyUnsafe(N));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(E=f.format){if(WN(E),E==="der")return yl($d.hexFromSig(this));let{r:D,s:M}=this,B=i.toBytes(D),L=i.toBytes(M);return E==="recovered"?(w(),es(Uint8Array.of(this.assertRecovery()),B,L)):es(B,L)}toHex(E){return gl(this.toBytes(E))}}let S=t.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let D=ay(E),M=E.length*8-c;return M>0?D>>BigInt(M):D},T=t.bits2int_modN||function(E){return i.create(S(E))},A=gE(c);function v(I){return Fd("num < 2^"+c,I,xl,A),i.toBytes(I)}function C(I,E){return Me(I,void 0,"message"),E?Me(e(I),void 0,"prehashed message"):I}function P(I,E,D){let{lowS:M,prehash:B,extraEntropy:L}=GN(D,f);I=C(I,B);let O=T(I),U=i.fromBytes(E);if(!i.isValidNot0(U))throw new Error("invalid private key");let $=[v(U),v(O)];if(L!=null&&L!==!1){let H=L===!0?n(p.secretKey):L;$.push(Me(H,void 0,"extraEntropy"))}let J=es(...$),X=O;function N(H){let Z=S(H);if(!i.isValidNot0(Z))return;let ae=i.inv(Z),Q=r.BASE.multiply(Z).toAffine(),oe=i.create(Q.x);if(oe===xl)return;let Fe=i.create(ae*i.create(X+oe*U));if(Fe===xl)return;let nr=(Q.x===oe?0:2)|Number(Q.y&yy),fe=Fe;return M&&y(Fe)&&(fe=i.neg(Fe),nr^=1),new x(oe,fe,g?void 0:nr)}return{seed:J,k2sig:N}}function F(I,E,D={}){let{seed:M,k2sig:B}=P(I,E,D);return rie(e.outputLen,i.BYTES,o)(M,B).toBytes(D.format)}function R(I,E,D,M={}){let{lowS:B,prehash:L,format:O}=GN(M,f);if(D=Me(D,void 0,"publicKey"),E=C(E,L),!zh(I)){let U=I instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}b(I,O);try{let U=x.fromBytes(I,O),$=r.fromBytes(D);if(B&&U.hasHighS())return!1;let{r:J,s:X}=U,N=T(E),H=i.inv(X),Z=i.create(N*H),ae=i.create(J*H),Q=r.BASE.multiplyUnsafe(Z).add($.multiplyUnsafe(ae));return Q.is0()?!1:i.create(Q.x)===J}catch{return!1}}function k(I,E,D={}){let{prehash:M}=GN(D,f);return E=C(E,M),x.fromBytes(I,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:F,verify:R,recoverPublicKey:k,Signature:x,hash:e})}var Zie,YN,$d,xl,yy,Jie,i6,MBe,nae=_(()=>{jN();Xi();ly();jT();dy();Zie=(r,e)=>(r+(r>=0?e:-e)/Jie)/e;YN=class extends Error{constructor(e=""){super(e)}},$d={Err:YN,_tlv:{encode:(r,e)=>{let{Err:t}=$d;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,o=pE(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?pE(o.length/2|128):"";return pE(r)+s+o+e},decode(r,e){let{Err:t}=$d,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 o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&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)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=$d;if(r<xl)throw new e("integer: negative integers are not allowed");let t=pE(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}=$d;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 ay(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=$d,o=Me(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=$d,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},xl=BigInt(0),yy=BigInt(1),Jie=BigInt(2),i6=BigInt(3),MBe=BigInt(4)});function NBe(r){let e=ZN.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Mt(u,t,e)*u%e,h=Mt(d,t,e)*u%e,p=Mt(h,oae,e)*l%e,f=Mt(p,o,e)*p%e,g=Mt(f,s,e)*f%e,y=Mt(g,a,e)*g%e,m=Mt(y,c,e)*y%e,w=Mt(m,a,e)*g%e,b=Mt(w,t,e)*u%e,x=Mt(b,i,e)*f%e,S=Mt(x,n,e)*l%e,T=Mt(S,oae,e);if(!XN.eql(XN.sqr(T),r))throw new Error("Cannot find square root");return T}var ZN,OBe,oae,XN,UBe,Ie,Mo=_(()=>{Va();dy();nae();ZN={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},OBe={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},oae=BigInt(2);XN=uy(ZN.p,{sqrt:NBe}),UBe=Qie(ZN,{Fp:XN,endo:OBe}),Ie=rae(UBe,lt)});function QN({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new JN(r,e,t,n,o)}function sae(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 Yg(e,r)}var FBe,JN,iae=_(()=>{eE();FBe=20;JN=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??FBe,this.maxDigestLength=s}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?sae(n,this.code,t?.truncate):n.then(o=>sae(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});function aae(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var a6,z5t,eU=_(()=>{iae();a6=QN({name:"sha2-256",code:18,encode:aae("SHA-256")}),z5t=QN({name:"sha2-512",code:19,encode:aae("SHA-512")})});function cae(r,e,t,n){let o=a6.digest(t instanceof Uint8Array?t:t.subarray());if(JT(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ie.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new vE(String(s))});try{return n?.signal?.throwIfAborted(),Ie.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new vE(String(s))}}var lae=_(()=>{Mo();eU();SN();IN()});var c6,uae=_(()=>{Fh();Xg();Zg();Ne();uE();tU();lae();c6=class{type="secp256k1";raw;_key;constructor(e){this._key=fae(e),this.raw=dae(this._key)}toMultihash(){return za.digest(sy(this))}toCID(){return Ps.createV1(114,this.toMultihash())}toString(){return Ur.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return cae(this._key,t,e,n)}}});function hae(r){return new c6(r)}function dae(r){return Ie.Point.fromBytes(r).toBytes()}function fae(r){try{return Ie.Point.fromBytes(r),r}catch(e){throw new zt(String(e))}}var tU=_(()=>{se();Mo();uae()});function pae(r){let{Type:e,Data:t}=IE.decode(r.digest),n=t??new Uint8Array;switch(e){case Ls.Ed25519:return Bie(n);case Ls.secp256k1:return hae(n);case Ls.ECDSA:return Lse(n);default:throw new An}}function sy(r){return IE.encode({Type:Ls[r.type],Data:r.raw})}var uE=_(()=>{se();rN();kN();Xie();tU()});var mae,KBe,TE,kE,DE,_E,zBe,PE,gae=_(()=>{se();Fh();Xg();Zg();Ne();me();Le();mae=Symbol.for("nodejs.util.inspect.custom"),KBe=114,TE=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()})`}[PT]=!0;toString(){return this.string==null&&(this.string=Ur.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Ps.createV1(KBe,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ee(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ee(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[mae](){return`PeerId(${this.toString()})`}},kE=class extends TE{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},DE=class extends TE{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},_E=class extends TE{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},zBe=2336,PE=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=za.digest(K(this.url))}[mae](){return`PeerId(${this.url})`}[PT]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Ps.createV1(zBe,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}}});var bae={};W(bae,{peerIdFromCID:()=>Wa,peerIdFromMultihash:()=>El,peerIdFromPrivateKey:()=>RE,peerIdFromPublicKey:()=>vl,peerIdFromString:()=>le});function le(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Qv(Ur.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return Wa(Ps.parse(r));if(e==null)throw new q('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Qv(e.decode(r))}return El(t)}function vl(r){if(r.type==="Ed25519")return new DE({multihash:r.toCID().multihash,publicKey:r});if(r.type==="secp256k1")return new _E({multihash:r.toCID().multihash,publicKey:r});if(r.type==="RSA")return new kE({multihash:r.toCID().multihash,publicKey:r});throw new An}function RE(r){return vl(r.publicKey)}function El(r){if(VBe(r))return new kE({multihash:r});if(HBe(r))try{let e=pae(r);if(e.type==="Ed25519")return new DE({multihash:r,publicKey:e});if(e.type==="secp256k1")return new _E({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new PE(new URL(t))}throw new CT("Supplied PeerID Multihash is invalid")}function Wa(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==$Be&&r.code!==yae)throw new ST("Supplied PeerID CID is invalid");if(r.code===yae){let e=z(r.multihash.digest);return new PE(new URL(e))}return El(r.multihash)}function HBe(r){return r.code===za.code}function VBe(r){return r.code===a6.code}var $Be,yae,Be=_(()=>{uE();se();Fh();Xg();eE();Zg();eU();Le();gae();$Be=114,yae=2336});var ec,pS,Zle=_(()=>{ec=class{entries;constructor(e){this.entries=e}},pS=class{partitions;nodes;constructor(e,t){this.partitions=e,this.nodes=t}}});var Pl,eb,HF=_(()=>{Pl=class r{node;index;constructor(e,t){this.node=e,this.index=t}clone(){return new r(this.node,this.index)}},eb=class r{branches;leafNode;leafIndex;on;version;constructor(e,t,n,o,s){this.branches=e,this.leafNode=t,this.leafIndex=n,this.on=o,this.version=s}isEqual(e){return this.leafNode===e.leafNode&&this.leafIndex===e.leafIndex&&this.on===e.on&&this.version===e.version}clone(){return new r(this.branches.map(e=>e.clone()),this.leafNode,this.leafIndex,this.on,this.version)}}});var fi,ek,tk,Jle=_(()=>{Zle();HF();fi=64,ek=class{keyFromEntry;compare;_root;_version=0;constructor(e=n=>n,t=(n,o)=>n<o?-1:n>o?1:0){this.keyFromEntry=e,this.compare=t,this._root=new ec([])}first(){return this.getFirst(this._root)}last(){return this.getLast(this._root)}find(e){return this.getPath(this._root,e)}get(e){return this.at(this.find(e))}at(e){return this.validatePath(e),e.on?e.leafNode.entries[e.leafIndex]:void 0}*range(e){let t=e.first?this.findFirst(e):e.isAscending?this.first():this.last(),n=e.last?this.findLast(e):e.isAscending?this.last():this.first(),o=n.on?this.keyFromEntry(n.leafNode.entries[n.leafIndex]):void 0,s=e.isAscending?this.internalAscending(t):this.internalDescending(t),i=e.isAscending?1:-1;for(let a of s){if(!a.on||!n.on||this.compareKeys(this.keyFromEntry(a.leafNode.entries[a.leafIndex]),o)*i>0)break;yield a}}isValid(e){return e.version===this._version}insert(e){Object.freeze(e);let t=this.internalInsert(e);return t.on&&(t.version=++this._version),t}updateAt(e,t){this.validatePath(e),e.on&&Object.freeze(t);let n=this.internalUpdate(e,t);return n[0].on&&(n[0].version=++this._version),n}upsert(e){let t=this.find(this.keyFromEntry(e));return Object.freeze(e),t.on?t.leafNode.entries[t.leafIndex]=e:this.internalInsertAt(t,e),t.version=++this._version,t}merge(e,t){let n=this.keyFromEntry(e),o=this.find(n);return o.on?this.updateAt(o,t(o.leafNode.entries[o.leafIndex])):(this.internalInsertAt(o,Object.freeze(e)),o.on=!0,o.version=++this._version,[o,!1])}deleteAt(e){this.validatePath(e);let t=this.internalDelete(e);return t&&++this._version,t}ascending(e){return this.validatePath(e),this.internalAscending(e.clone())}descending(e){return this.validatePath(e),this.internalDescending(e.clone())}getCount(e){let t=0,n=e?e.path.clone():this.first();if(e?.ascending??!0)for(;n.on;)t+=n.leafNode.entries.length-n.leafIndex,n.leafIndex=n.leafNode.entries.length-1,this.internalNext(n);else for(;n.on;)t+=n.leafIndex+1,n.leafIndex=0,this.internalPrior(n);return t}next(e){let t=e.clone();return this.moveNext(t),t}moveNext(e){this.validatePath(e),this.internalNext(e)}prior(e){let t=e.clone();return this.movePrior(t),t}movePrior(e){this.validatePath(e),this.internalPrior(e)}compareKeys(e,t){let n=this.compare(e,t);if(n!==0&&n===this.compare(t,e))throw new Error("Inconsistent comparison function for given values");return n}*internalAscending(e){for(this.validatePath(e);e.on;)yield e,this.moveNext(e)}*internalDescending(e){for(this.validatePath(e);e.on;)yield e,this.movePrior(e)}findFirst(e){let t=this.find(e.first.key);return(!t.on||e.first&&!e.first.inclusive)&&(e.isAscending?this.internalNext(t):this.internalPrior(t)),t}findLast(e){let t=this.find(e.last.key);return(!t.on||e.last&&!e.last.inclusive)&&(e.isAscending?this.internalPrior(t):this.internalNext(t)),t}getPath(e,t){if(e instanceof ec){let n=e,[o,s]=this.indexOfEntry(n.entries,t);return new eb([],n,s,o,this._version)}else{let n=e,o=this.indexOfKey(n.partitions,t),s=this.getPath(n.nodes[o],t);return s.branches.unshift(new Pl(n,o)),s}}indexOfEntry(e,t){let n=0,o=e.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compareKeys(t,this.keyFromEntry(e[s])),i===0)return[!0,s];i<0?o=s-1:n=s+1}return[!1,n]}indexOfKey(e,t){let n=0,o=e.length-1,s=0,i=-1;for(;n<=o;){if(s=n+o>>>1,i=this.compareKeys(t,e[s]),i===0)return s+1;i<0?o=s-1:n=s+1}return n}internalNext(e){if(e.on)if(e.leafIndex>=e.leafNode.entries.length-1){let t=0,n=!1,o=e.branches.length-1;for(;t<=o&&!n;){let s=e.branches[o-t];s.index===s.node.partitions.length?++t:n=!0}if(!n)e.leafIndex=e.leafNode.entries.length,e.on=!1;else{e.branches.splice(-t,t);let s=e.branches.at(-1);++s.index,this.moveToFirst(s.node.nodes[s.index],e)}}else++e.leafIndex,e.on=!0;else if(e.on=e.branches.every(t=>t.index>=0&&t.index<t.node.nodes.length)&&e.leafIndex>=0&&e.leafIndex<e.leafNode.entries.length,e.on)return}internalPrior(e){if(this.validatePath(e),e.leafIndex<=0){let t=0,n=!1,o=e.branches.length-1;for(;t<=o&&!n;)e.branches[o-t].index===0?++t:n=!0;if(!n)e.leafIndex=0,e.on=!1;else{e.branches.splice(-t,t);let s=e.branches.at(-1);--s.index,this.moveToLast(s.node.nodes[s.index],e)}}else--e.leafIndex,e.on=!0}internalUpdate(e,t){if(e.on){let n=this.keyFromEntry(e.leafNode.entries[e.leafIndex]),o=this.keyFromEntry(t);if(this.compareKeys(n,o)!==0){let s=this.internalInsert(t);return s.on&&(this.internalDelete(this.find(n)),s=this.find(o)),[s,!1]}else e.leafNode.entries[e.leafIndex]=t}return[e,!0]}internalDelete(e){if(e.on){if(e.leafNode.entries.splice(e.leafIndex,1),e.branches.length>0){if(e.leafIndex===0&&e.leafNode.entries.length>0){let n=e.branches.at(-1);this.updatePartition(n.index,e,e.branches.length-1,this.keyFromEntry(e.leafNode.entries[e.leafIndex]))}let t=this.rebalanceLeaf(e);t&&(this._root=t)}return e.on=!1,!0}else return!1}internalInsert(e){let t=this.find(this.keyFromEntry(e));return t.on?(t.on=!1,t):(this.internalInsertAt(t,e),t.on=!0,t)}internalInsertAt(e,t){let n=this.leafInsert(e,t),o=e.branches.length-1;for(;n&&o>=0;)n=this.branchInsert(e,o,n),--o;if(n){let s=new pS([n.key],[this._root,n.right]);this._root=s,e.branches.unshift(new Pl(s,n.indexDelta))}}moveToFirst(e,t){if(e instanceof ec){let n=e;t.leafNode=n,t.leafIndex=0,t.on=n.entries.length>0}else t.branches.push(new Pl(e,0)),this.moveToFirst(e.nodes[0],t)}moveToLast(e,t){if(e instanceof ec){let n=e,o=n.entries.length;t.leafNode=n,t.on=o>0,t.leafIndex=o>0?o-1:0}else{let n=e,o=new Pl(n,n.partitions.length);t.branches.push(o),this.moveToLast(n.nodes[o.index],t)}}getFirst(e){if(e instanceof ec){let t=e;return new eb([],t,0,t.entries.length>0,this._version)}else{let t=e,n=this.getFirst(t.nodes[0]);return n.branches.unshift(new Pl(t,0)),n}}getLast(e){if(e instanceof ec){let t=e,n=t.entries.length;return new eb([],t,n>0?n-1:0,n>0,this._version)}else{let t=e,n=t.nodes.length-1,o=this.getLast(t.nodes[n]);return o.branches.unshift(new Pl(t,n)),o}}leafInsert(e,t){let{leafNode:n,leafIndex:o}=e;if(n.entries.length<fi){n.entries.splice(o,0,t);return}let s=n.entries.length+1>>>1,i=n.entries.splice(s),a=new ec(i),c=o<s?0:1;return c?(e.leafNode=a,e.leafIndex-=n.entries.length,a.entries.splice(e.leafIndex,0,t)):n.entries.splice(o,0,t),new tk(this.keyFromEntry(i[0]),a,c)}branchInsert(e,t,n){let o=e.branches[t],{index:s,node:i}=o;if(o.index+=n.indexDelta,i.partitions.splice(s,0,n.key),i.nodes.splice(s+1,0,n.right),i.nodes.length<=fi)return;let a=i.nodes.length>>>1,c=i.partitions.splice(a),l=i.partitions.pop(),u=i.nodes.splice(a),d=new pS(c,u),h=o.index<a?0:1;return h&&(o.index-=a,o.node=d),new tk(l,d,h)}rebalanceLeaf(e){if(e.leafNode.entries.length>=fi>>>1)return;let t=e.leafNode,n=e.branches.at(-1),o=e.branches.length-1,s=n.index,i=n.node,a=i.nodes[s+1];if(a&&a.entries.length>fi>>>1){let l=a.entries.shift();t.entries.push(l),this.updatePartition(s+1,e,o,this.keyFromEntry(a.entries[0]));return}let c=i.nodes[s-1];if(c&&c.entries.length>fi>>>1){let l=c.entries.pop();t.entries.unshift(l),this.updatePartition(s,e,o,this.keyFromEntry(l)),e.leafIndex+=1;return}if(a&&a.entries.length+t.entries.length<=fi)return t.entries.push(...a.entries),i.partitions.splice(s,1),i.nodes.splice(s+1,1),s===0&&this.updatePartition(s,e,o,this.keyFromEntry(t.entries[0])),this.rebalanceBranch(e,o);if(c&&c.entries.length+t.entries.length<=fi)return e.leafNode=c,e.leafIndex+=c.entries.length,c.entries.push(...t.entries),i.partitions.splice(s-1,1),i.nodes.splice(s,1),this.rebalanceBranch(e,o)}rebalanceBranch(e,t){let n=e.branches[t],o=n.node;if(t===0&&o.partitions.length===0)return e.branches[t+1]?.node??e.leafNode;if(t===0||o.nodes.length>=fi>>>1)return;let s=e.branches.at(t-1),i=s.index,a=s.node,c=a.nodes[i+1];if(c&&c.nodes.length>fi>>>1){o.partitions.push(a.partitions[i]);let u=c.nodes.shift();o.nodes.push(u);let d=c.partitions.shift();this.updatePartition(i+1,e,t-1,d);return}let l=a.nodes[i-1];if(l&&l.nodes.length>fi>>>1){o.partitions.unshift(a.partitions[i-1]);let u=l.nodes.pop();o.nodes.unshift(u);let d=l.partitions.pop();n.index+=1,this.updatePartition(i,e,t-1,d);return}if(c&&c.nodes.length+o.nodes.length<=fi){let u=a.partitions.splice(i,1)[0];return o.partitions.push(u),o.partitions.push(...c.partitions),o.nodes.push(...c.nodes),a.nodes.splice(i+1,1),i===0&&a.partitions.length>0&&this.updatePartition(i,e,t-1,a.partitions[0]),this.rebalanceBranch(e,t-1)}if(l&&l.nodes.length+o.nodes.length<=fi){n.node=l,n.index+=l.nodes.length;let u=a.partitions.splice(i-1,1)[0];return l.partitions.push(u),l.partitions.push(...o.partitions),l.nodes.push(...o.nodes),a.nodes.splice(i,1),this.rebalanceBranch(e,t-1)}}updatePartition(e,t,n,o){let s=t.branches[n];e>0?s.node.partitions[e-1]=o:n!==0&&this.updatePartition(t.branches[n-1].index,t,n-1,o)}validatePath(e){if(!this.isValid(e))throw new Error("Path is invalid due to mutation of the tree")}},tk=class{key;right;indexDelta;constructor(e,t,n){this.key=e,this.right=t,this.indexDelta=n}}});var Qle=_(()=>{});var eue=_(()=>{Jle();Qle();HF()});function tue(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 Rl(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 rue(r){return new TextEncoder().encode(r)}function nue(r){return new TextDecoder().decode(r)}var kNt,Xd=_(()=>{kNt=new Uint8Array(0)});function aue(r,e,t){e=e||[],t=t||0;for(var n=t;r>=pFe;)e[t++]=r&255|sue,r/=128;for(;r&hFe;)e[t++]=r&255|sue,r>>>=7;return e[t]=r|0,aue.bytes=t-n+1,e}function VF(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw VF.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&iue)<<o:(i&iue)*Math.pow(2,o),o+=7}while(i>=gFe);return VF.bytes=s-n,t}var dFe,sue,fFe,hFe,pFe,mFe,gFe,iue,yFe,bFe,wFe,xFe,vFe,EFe,SFe,CFe,AFe,IFe,TFe,kFe,mS,cue=_(()=>{dFe=aue,sue=128,fFe=127,hFe=~fFe,pFe=Math.pow(2,31);mFe=VF,gFe=128,iue=127;yFe=Math.pow(2,7),bFe=Math.pow(2,14),wFe=Math.pow(2,21),xFe=Math.pow(2,28),vFe=Math.pow(2,35),EFe=Math.pow(2,42),SFe=Math.pow(2,49),CFe=Math.pow(2,56),AFe=Math.pow(2,63),IFe=function(r){return r<yFe?1:r<bFe?2:r<wFe?3:r<xFe?4:r<vFe?5:r<EFe?6:r<SFe?7:r<CFe?8:r<AFe?9:10},TFe={encode:dFe,decode:mFe,encodingLength:IFe},kFe=TFe,mS=kFe});function gS(r,e=0){return[mS.decode(r,e),mS.decode.bytes]}function tb(r,e,t=0){return mS.encode(r,e,t),e}function rb(r){return mS.encodingLength(r)}var nk=_(()=>{cue()});function ob(r,e){let t=e.byteLength,n=rb(r),o=n+rb(t),s=new Uint8Array(o+t);return tb(r,s,0),tb(t,s,n),s.set(e,o),new nb(r,t,e,s)}function yS(r){let e=Rl(r),[t,n]=gS(e),[o,s]=gS(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new nb(t,o,i,e)}function lue(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&tue(r.bytes,t.bytes)}}var nb,ib=_(()=>{Xd();nk();nb=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}}});function jF({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new qF(r,e,t,n,o)}function uue(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 ob(e,r)}var DFe,qF,GF=_(()=>{ib();DFe=20;qF=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??DFe,this.maxDigestLength=s}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?uue(n,this.code,t?.truncate):n.then(o=>uue(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var WF={};W(WF,{sha256:()=>Zd,sha512:()=>_Fe});function fue(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Zd,_Fe,bS=_(()=>{GF();Zd=jF({name:"sha2-256",code:18,encode:fue("SHA-256")}),_Fe=jF({name:"sha2-512",code:19,encode:fue("SHA-512")})});function PFe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var RFe,LFe,hue,pue=_(()=>{RFe=PFe,LFe=RFe,hue=LFe});function mue(r,e){return new ZF({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function ab({name:r,prefix:e,encode:t,decode:n}){return new JF(r,e,t,n)}function Jd({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=hue(t,r);return ab({prefix:e,name:r,encode:n,decode:s=>Rl(o(s))})}function MFe(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function BFe(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function OFe(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function fr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=OFe(n);return ab({prefix:e,name:r,encode(s){return BFe(s,n,t)},decode(s){return MFe(s,o,t,r)}})}var YF,XF,ZF,JF,ta=_(()=>{Xd();pue();YF=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")}},XF=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 mue(this,e)}},ZF=class{decoders;constructor(e){this.decoders=e}or(e){return mue(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`)}};JF=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new YF(e,t,n),this.decoder=new XF(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var QF={};W(QF,{base10:()=>NFe});var NFe,gue=_(()=>{ta();NFe=Jd({prefix:"9",name:"base10",alphabet:"0123456789"})});var eK={};W(eK,{base16:()=>UFe,base16upper:()=>FFe});var UFe,FFe,yue=_(()=>{ta();UFe=fr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),FFe=fr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var tK={};W(tK,{base2:()=>KFe});var KFe,bue=_(()=>{ta();KFe=fr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var rK={};W(rK,{base256emoji:()=>qFe});function HFe(r){return r.reduce((e,t)=>(e+=zFe[t],e),"")}function VFe(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=$Fe[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var wue,zFe,$Fe,qFe,xue=_(()=>{ta();wue=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}"),zFe=wue.reduce((r,e,t)=>(r[t]=e,r),[]),$Fe=wue.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);qFe=ab({prefix:"\u{1F680}",name:"base256emoji",encode:HFe,decode:VFe})});var nK={};W(nK,{base32:()=>tc,base32hex:()=>YFe,base32hexpad:()=>ZFe,base32hexpadupper:()=>JFe,base32hexupper:()=>XFe,base32pad:()=>GFe,base32padupper:()=>WFe,base32upper:()=>jFe,base32z:()=>QFe});var tc,jFe,GFe,WFe,YFe,XFe,ZFe,JFe,QFe,wS=_(()=>{ta();tc=fr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),jFe=fr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),GFe=fr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),WFe=fr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),YFe=fr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),XFe=fr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZFe=fr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),JFe=fr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),QFe=fr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var oK={};W(oK,{base36:()=>xS,base36upper:()=>eKe});var xS,eKe,sK=_(()=>{ta();xS=Jd({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),eKe=Jd({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var iK={};W(iK,{base58btc:()=>hr,base58flickr:()=>tKe});var hr,tKe,Ll=_(()=>{ta();hr=Jd({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tKe=Jd({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});var lK={};W(lK,{base64:()=>aK,base64pad:()=>rKe,base64url:()=>cK,base64urlpad:()=>nKe});var aK,rKe,cK,nKe,ok=_(()=>{ta();aK=fr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rKe=fr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cK=fr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nKe=fr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var uK={};W(uK,{base8:()=>oKe});var oKe,vue=_(()=>{ta();oKe=fr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var dK={};W(dK,{identity:()=>sKe});var sKe,Eue=_(()=>{Xd();ta();sKe=ab({prefix:"\0",name:"identity",encode:r=>nue(r),decode:r=>rue(r)})});var WNt,YNt,Sue=_(()=>{WNt=new TextEncoder,YNt=new TextDecoder});var Cue=_(()=>{Xd()});var fK={};W(fK,{identity:()=>ra});function lKe(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 ob(Aue,Iue(r))}var Aue,cKe,Iue,ra,ip=_(()=>{Xd();ib();Aue=0,cKe="identity",Iue=Rl;ra={code:Aue,name:cKe,encode:Iue,digest:lKe}});var hK=_(()=>{});function Tue(r,e){let{bytes:t,version:n}=r;return n===0?dKe(t,pK(r),e??hr.encoder):fKe(t,pK(r),e??tc.encoder)}function pK(r){let e=kue.get(r);if(e==null){let t=new Map;return kue.set(r,t),t}return e}function uKe(r,e){switch(r[0]){case"Q":{let t=e??hr;return[hr.prefix,t.decode(`${hr.prefix}${r}`)]}case hr.prefix:{let t=e??hr;return[hr.prefix,t.decode(r)]}case tc.prefix:{let t=e??tc;return[tc.prefix,t.decode(r)]}case xS.prefix:{let t=e??xS;return[xS.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 dKe(r,e,t){let{prefix:n}=t;if(n!==hr.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function fKe(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}function Due(r,e,t){let n=rb(r),o=n+rb(e),s=new Uint8Array(o+t.byteLength);return tb(r,s,0),tb(e,s,n),s.set(t,o),s}var kue,Rn,vS,hKe,pKe,ap=_(()=>{wS();sK();Ll();Xd();ib();nk();hK();kue=new WeakMap;Rn=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==vS)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==hKe)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=ob(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&&lue(e.multihash,n.multihash)}toString(e){return Tue(this,e)}toJSON(){return{"/":Tue(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Due(n,o,s.bytes))}else if(t[pKe]===!0){let{version:n,multihash:o,code:s}=t,i=yS(o);return r.create(n,s,i)}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!==vS)throw new Error(`Version 0 CID must use dag-pb (code: ${vS}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Due(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,vS,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,o=Rl(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new nb(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=gS(e.subarray(t));return t+=h,d},o=n(),s=vS;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=uKe(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return pK(s).set(n,e),s}};vS=112,hKe=18;pKe=Symbol.for("@ipld/js-cid/CID")});var _ue=_(()=>{});var Pue=_(()=>{});var Rue=_(()=>{});var Lue=_(()=>{});var Mue=_(()=>{_ue();Pue();Rue();hK();Lue()});var mK=_(()=>{Xd();ap();ib();GF();nk();Mue()});var ES,hUt,gK=_(()=>{gue();yue();bue();xue();wS();sK();Ll();ok();vue();Eue();Sue();Cue();ip();bS();mK();ES={...dK,...tK,...uK,...QF,...eK,...nK,...oK,...iK,...lK,...rK},hUt={...WF,...fK}});function Ml(r=0){return new Uint8Array(r)}function ao(r=0){return new Uint8Array(r)}var Qd=_(()=>{});function Oue(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Bue,yK,mKe,sk,bK=_(()=>{gK();Qd();Bue=Oue("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),yK=Oue("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=ao(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),mKe={utf8:Bue,"utf-8":Bue,hex:ES.base16,latin1:yK,ascii:yK,binary:yK,...ES},sk=mKe});function pr(r,e="utf8"){let t=sk[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var ef=_(()=>{bK()});function Ir(r,e="utf8"){let t=sk[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var rc=_(()=>{bK()});async function Or(r){let e=r.toMultihash().bytes;return await Zd.encode(e)}async function Jt(r){return await Zd.encode(r)}function lb(r){let e="";for(let t=0;t<r.length;t++)e+=gKe[r[t]];return e}function ub(r){return pr(r,"base64url")}function ik(r){let e=Ir(r,"base64url");if(e.length!==cb)throw new Error(`base64urlToCoord: expected ${cb} bytes, got ${e.length}`);return e}var cb,gKe,IUt,SS=_(()=>{"use strict";bS();ef();rc();cb=32;gKe=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));IUt=new RegExp(`^[0-9a-fA-F]{${cb*2}}$`)});function yKe(r){if(r.length!==cb)throw new Error(`DigitreeStore: ring coordinate must be ${cb} bytes, got ${r.length}`)}function CS(r){let e=Nue.get(r.coord);if(e!==void 0&&e.id===r.id)return e.key;let t=`${lb(r.coord)}|${r.id}`;return Nue.set(r.coord,{id:r.id,key:t}),t}var Nue,tf,wK=_(()=>{"use strict";eue();SS();Nue=new WeakMap;tf=class{byKey;byId;membershipCounts=new Map;stateCounts=new Map;constructor(){this.byKey=new ek(e=>CS(e)),this.byId=new Map}bumpCount(e,t,n){let o=(e.get(t)??0)+n;o<=0?e.delete(t):e.set(t,o)}tally(e,t){this.bumpCount(this.membershipCounts,e.membership,t),this.bumpCount(this.stateCounts,e.state,t)}countByMembership(e){return this.membershipCounts.get(e)??0}countByState(e){return this.stateCounts.get(e)??0}put(e){yKe(e.coord);let t=CS(e),n=this.byId.get(e.id);if(n!==void 0){let o=CS(n);if(o!==t){let s=this.byKey.find(o);s.on&&this.byKey.deleteAt(s)}}return this.byKey.upsert(e),this.byId.set(e.id,e),n&&this.tally(n,-1),this.tally(e,1),e}upsert(e,t){let n=Date.now(),o=this.getById(e);return o?this.put({...o,coord:t,lastAccess:n}):this.put({id:e,coord:t,relevance:0,lastAccess:n,state:"disconnected",membership:"unknown",negotiateFailures:0,lastNegotiateFailureAt:0,contactFailures:0,lastContactFailureAt:0,accessCount:0,successCount:0,failureCount:0,avgLatencyMs:null})}update(e,t){let n=this.getById(e);n&&this.put({...n,...t})}getById(e){return this.byId.get(e)}remove(e){let t=this.byId.get(e);if(!t)return;let n=this.byKey.find(CS(t));n.on&&(this.tally(this.byKey.at(n),-1),this.byKey.deleteAt(n)),this.byId.delete(e)}list(){let e=[];for(let t of this.byKey.ascending(this.byKey.first()))e.push(this.byKey.at(t));return e}size(){return this.byId.size}setState(e,t){this.update(e,{state:t})}setMembership(e,t){this.update(e,{membership:t})}ceilPath(e){let t=`${e}|\0`,n=this.byKey.find(t);return n.on||(n=this.byKey.next(n)),n}floorPath(e){let t=`${e}|\uFFFF`,n=this.byKey.find(t);return n.on||(n=this.byKey.prior(n)),n}*walkRing(e,t,n,o){let s=t==="next"?l=>this.byKey.next(l):l=>this.byKey.prior(l),i=t==="next"?()=>this.byKey.first():()=>this.byKey.last(),a=e,c=0;for(;c<n;){if(!a.on&&(a=i(),!a.on))return;let l=this.byKey.at(a);c++,(!o||o(l))&&(yield l),a=s(a)}}collectRing(e,t,n,o){let s=new Set;if(n<=0)return[];let i=o?this.size():Number.POSITIVE_INFINITY;for(let a of this.walkRing(e,t,i,o))if(s.has(a.id)||(s.add(a.id),s.size>=n))break;return Array.from(s)}successorOfCoord(e,t){let n=this.ceilPath(lb(e));for(let o of this.walkRing(n,"next",this.size(),t))return o}predecessorOfCoord(e,t){let n=this.floorPath(lb(e));for(let o of this.walkRing(n,"prior",this.size(),t))return o}neighborsRight(e,t,n){return this.collectRing(this.ceilPath(lb(e)),"next",t,n)}neighborsLeft(e,t,n){return this.collectRing(this.floorPath(lb(e)),"prior",t,n)}walkFrom(e,t,n){let o=[],s=e,i=this.size();if(t<=0||i===0)return{entries:o,next:s};let a=e?this.byKey.next(this.byKey.find(e.key)):this.byKey.first();for(let c of this.walkRing(a,"next",i,n))if(o.push(c),s={key:CS(c)},o.length>=t)break;return{entries:o,next:s}}exportEntries(){return this.list().map(e=>({id:e.id,coord:ub(e.coord),relevance:e.relevance,lastAccess:e.lastAccess,state:e.state,membership:e.membership,negotiateFailures:e.negotiateFailures,contactFailures:e.contactFailures,accessCount:e.accessCount,successCount:e.successCount,failureCount:e.failureCount,avgLatencyMs:e.avgLatencyMs,...e.metadata?{metadata:e.metadata}:{}}))}importEntries(e){let t=e.map(o=>({s:o,coord:ik(o.coord)})),n=new Set;for(let{s:o,coord:s}of t){let i={id:o.id,coord:s,relevance:o.relevance,lastAccess:o.lastAccess,state:"disconnected",membership:o.membership??"unknown",negotiateFailures:0,lastNegotiateFailureAt:0,contactFailures:0,lastContactFailureAt:0,accessCount:o.accessCount,successCount:o.successCount,failureCount:o.failureCount,avgLatencyMs:o.avgLatencyMs??null,...o.metadata?{metadata:o.metadata}:{}};this.put(i),n.add(i.id)}return n.size}}});function Jr(r){if(r<bKe)return 1;if(r<wKe)return 2;if(r<xKe)return 3;if(r<xK)return 4;if(r<vK)return 5;if(r<EK)return 6;if(r<SK)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function db(r,e,t=0){switch(Jr(r)){case 8:e[t++]=r&255|ut,r/=128;case 7:e[t++]=r&255|ut,r/=128;case 6:e[t++]=r&255|ut,r/=128;case 5:e[t++]=r&255|ut,r/=128;case 4:e[t++]=r&255|ut,r>>>=7;case 3:e[t++]=r&255|ut,r>>>=7;case 2:e[t++]=r&255|ut,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function vKe(r,e,t=0){switch(Jr(r)){case 8:e.set(t++,r&255|ut),r/=128;case 7:e.set(t++,r&255|ut),r/=128;case 6:e.set(t++,r&255|ut),r/=128;case 5:e.set(t++,r&255|ut),r/=128;case 4:e.set(t++,r&255|ut),r>>>=7;case 3:e.set(t++,r&255|ut),r>>>=7;case 2:e.set(t++,r&255|ut),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function CK(r,e){let t=r[e],n=0;if(n+=t&co,t<ut||(t=r[e+1],n+=(t&co)<<7,t<ut)||(t=r[e+2],n+=(t&co)<<14,t<ut)||(t=r[e+3],n+=(t&co)<<21,t<ut)||(t=r[e+4],n+=(t&co)*xK,t<ut)||(t=r[e+5],n+=(t&co)*vK,t<ut)||(t=r[e+6],n+=(t&co)*EK,t<ut)||(t=r[e+7],n+=(t&co)*SK,t<ut))return n;throw new RangeError("Could not decode varint")}function EKe(r,e){let t=r.get(e),n=0;if(n+=t&co,t<ut||(t=r.get(e+1),n+=(t&co)<<7,t<ut)||(t=r.get(e+2),n+=(t&co)<<14,t<ut)||(t=r.get(e+3),n+=(t&co)<<21,t<ut)||(t=r.get(e+4),n+=(t&co)*xK,t<ut)||(t=r.get(e+5),n+=(t&co)*vK,t<ut)||(t=r.get(e+6),n+=(t&co)*EK,t<ut)||(t=r.get(e+7),n+=(t&co)*SK,t<ut))return n;throw new RangeError("Could not decode varint")}function AK(r,e,t=0){return e==null&&(e=ao(Jr(r))),e instanceof Uint8Array?db(r,e,t):vKe(r,e,t)}function Bl(r,e=0){return r instanceof Uint8Array?CK(r,e):EKe(r,e)}var bKe,wKe,xKe,xK,vK,EK,SK,ut,co,Ol=_(()=>{Qd();bKe=Math.pow(2,7),wKe=Math.pow(2,14),xKe=Math.pow(2,21),xK=Math.pow(2,28),vK=Math.pow(2,35),EK=Math.pow(2,42),SK=Math.pow(2,49),ut=128,co=127});var Uue=_(()=>{});function Nl(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=ao(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var IS=_(()=>{Qd();Uue()});function Os(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 cp=_(()=>{});function Fue(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function ak(r){return!!r?.[Kue]}var Kue,Tr,Ul=_(()=>{Qd();IS();cp();Kue=Symbol.for("@achingbrain/uint8arraylist");Tr=class r{bufs;length;[Kue]=!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(ak(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(ak(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=Fue(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Fue(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(ak(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:o}=this._subList(e,t);return Nl(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:Nl(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ak(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let h=l;h>=0;h--){let p=this.get(d+h);if(n[h]!==p){u=Math.max(1,h-a[p]);break}}if(u===0)return d}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=ao(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 o=Ml(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=Ml(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=Ml(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=ao(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 o=Ml(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=Ml(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=Ml(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=Ml(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=Ml(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!Os(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((o,s)=>o+s.byteLength,0)),n.length=t,n}}});var IK=_(()=>{});var ck,fb,lk,TS,TK=_(()=>{ck=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},fb=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},lk=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"},TS=class extends Error{name="UnexpectedEOFError";code="ERR_UNEXPECTED_EOF"}});function uk(r){return r[Symbol.asyncIterator]!=null}var kK=_(()=>{});function zue(r,e){if(r.byteLength>e)throw new fb("Message length too long")}function kS(r,e){e=e??{};let t=e.lengthEncoder??fk,n=e?.maxDataLength??4194304;function*o(s){zue(s,n);let i=t(s.byteLength);i instanceof Uint8Array?yield i:yield*i,s instanceof Uint8Array?yield s:yield*s}return uk(r)?(async function*(){for await(let s of r)yield*o(s)})():(function*(){for(let s of r)yield*o(s)})()}var fk,$ue=_(()=>{Ol();Ul();Qd();IK();TK();kK();fk=r=>{let e=Jr(r),t=ao(e);return AK(r,t),fk.bytes=e,t};fk.bytes=0;kS.single=(r,e)=>{e=e??{};let t=e.lengthEncoder??fk,n=e?.maxDataLength??4194304;return zue(r,n),new Tr(t(r.byteLength),r)}});function hb(r,e){let t=new Tr,n=lp.LENGTH,o=-1,s=e?.lengthDecoder??DK,i=e?.maxLengthLength??8,a=e?.maxDataLength??4194304;function*c(){for(;t.byteLength>0;){if(n===lp.LENGTH)try{if(o=s(t),o<0)throw new ck("Invalid message length");if(o>a)throw new fb("Message length too long");let l=s.bytes;t.consume(l),e?.onLength!=null&&e.onLength(o),n=lp.DATA}catch(l){if(l instanceof RangeError){if(t.byteLength>i)throw new lk("Message length length too long");break}throw l}if(n===lp.DATA){if(t.byteLength<o)break;let l=t.sublist(0,o);t.consume(o),e?.onData!=null&&e.onData(l),yield l,n=lp.LENGTH}}}return uk(r)?(async function*(){for await(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new TS("Unexpected end of input")})():(function*(){for(let l of r)t.append(l),yield*c();if(t.byteLength>0)throw new TS("Unexpected end of input")})()}var lp,DK,Hue=_(()=>{Ol();Ul();IK();TK();kK();(function(r){r[r.LENGTH=0]="LENGTH",r[r.DATA=1]="DATA"})(lp||(lp={}));DK=r=>{let e=Bl(r);return DK.bytes=Jr(e),e};DK.bytes=0;hb.fromReader=(r,e)=>{let t=1,n=(async function*(){for(;;)try{let{done:s,value:i}=await r.next(t);if(s===!0)return;i!=null&&(yield i)}catch(s){if(s.code==="ERR_UNDER_READ")return{done:!0,value:null};throw s}finally{t=1}})();return hb(n,{...e??{},onLength:s=>{t=s}})}});var _K=_(()=>{$ue();Hue()});var DS,hk,PK=_(()=>{DS=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},hk=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}}});var que,jue=_(()=>{PK();que={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new hk("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 pk,Gue=_(()=>{jue();pk=que});var Wue=_(()=>{});var Yue=_(()=>{});var Xue=_(()=>{});var Zue=_(()=>{});var Jue=_(()=>{});var hi,mk,gk,yk,_S,Que=_(()=>{hi=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},mk=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}},gk=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},yk=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}},_S=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}}});var ede=_(()=>{});var tde=_(()=>{});var rde=_(()=>{});var nde=_(()=>{});var ode=_(()=>{});var bk,sde=_(()=>{bk=Symbol.for("@libp2p/peer-discovery")});var RK,ide=_(()=>{RK=Symbol.for("@libp2p/peer-id")});var ade=_(()=>{});var cde=_(()=>{});var lde=_(()=>{});var ude=_(()=>{});var dde=_(()=>{});var fde=_(()=>{});var hde=_(()=>{});var pde=_(()=>{});var mde=_(()=>{});var gde,yde=_(()=>{(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(gde||(gde={}))});var wk,LK=_(()=>{wk=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 o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}}});var nc=_(()=>{Wue();Yue();Xue();Zue();Jue();Que();ede();tde();rde();nde();ode();sde();ide();ade();cde();lde();ude();dde();fde();hde();pde();mde();yde();LK()});function BK(r,e={offset:0}){let t=r[e.offset]&CKe;if(e.offset++,bde[t]!=null)return bde[t](r,e);throw new Error("No decoder for tag "+t)}function RS(r,e){let t=0;if((r[e.offset]&MK)===MK){let n=r[e.offset]&AKe,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function PS(r,e){RS(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=BK(r,e);if(n===null)break;t.push(n)}return t}function IKe(r,e){let t=RS(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function TKe(r,e){let t=RS(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function kKe(r,e){return e.offset++,null}function DKe(r,e){let t=RS(r,e),n=r[e.offset];e.offset++;let o=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 o}function _Ke(r,e){let t=RS(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function PKe(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Tr;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function OK(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=PKe(r.byteLength);return new Tr(Uint8Array.from([e.byteLength|MK]),e)}function wde(r){let e=new Tr,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Tr(Uint8Array.from([2]),OK(e),e)}function xde(r){let e=Uint8Array.from([0]),t=new Tr(e,r);return new Tr(Uint8Array.from([3]),OK(t),t)}function xk(r,e=48){let t=new Tr;for(let n of r)t.append(n);return new Tr(Uint8Array.from([e]),OK(t),t)}var CKe,MK,AKe,bde,vde=_(()=>{Ul();CKe=parseInt("11111",2),MK=parseInt("10000000",2),AKe=parseInt("01111111",2),bde={0:PS,1:PS,2:IKe,3:DKe,4:_Ke,5:kKe,6:TKe,16:PS,22:PS,48:PS}});async function Ede(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var Sde=_(()=>{});function Cde(r){let e=BK(r);return Ade(e)}function Ade(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===NK*2+1)return n=pr(e.subarray(t,t+NK),"base64url"),o=pr(e.subarray(t+NK),"base64url"),new pb({...BKe,key_ops:["verify"],x:n,y:o});if(e.byteLength===UK*2+1)return n=pr(e.subarray(t,t+UK),"base64url"),o=pr(e.subarray(t+UK),"base64url"),new pb({...OKe,key_ops:["verify"],x:n,y:o});if(e.byteLength===FK*2+1)return n=pr(e.subarray(t,t+FK),"base64url"),o=pr(e.subarray(t+FK),"base64url"),new pb({...NKe,key_ops:["verify"],x:n,y:o});throw new hi(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Ide(r){return xk([wde(Uint8Array.from([1])),xk([UKe(r.crv)],160),xk([xde(new Tr(Uint8Array.from([4]),Ir(r.x??"","base64url"),Ir(r.y??"","base64url")))],161)]).subarray()}function UKe(r){if(r==="P-256")return RKe;if(r==="P-384")return LKe;if(r==="P-521")return MKe;throw new hi(`Invalid curve ${r}`)}var RKe,LKe,MKe,BKe,OKe,NKe,NK,UK,FK,KK=_(()=>{nc();Ul();rc();ef();vde();Tde();RKe=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),LKe=Uint8Array.from([6,5,43,129,4,0,34]),MKe=Uint8Array.from([6,5,43,129,4,0,35]),BKe={ext:!0,kty:"EC",crv:"P-256"},OKe={ext:!0,kty:"EC",crv:"P-384"},NKe={ext:!0,kty:"EC",crv:"P-521"},NK=32,UK=48,FK=66});var pb,Tde=_(()=>{Ll();ap();ip();cp();LS();KK();Sde();pb=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Ide(this.jwk)),this._raw}toMultihash(){return ra.digest(mb(this))}toCID(){return Rn.createV1(114,this.toMultihash())}toString(){return hr.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Os(this.raw,e.raw)}async verify(e,t,n){return Ede(this.jwk,t,e,n)}}});function up(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function oc(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function ze(r,e,t=""){let n=up(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function vk(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");oc(r.outputLen),oc(r.blockLen)}function gb(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 Dde(r,e){ze(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Kl(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ek(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function na(r,e){return r<<32-e|r>>>e}function zl(r){if(ze(r),_de)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=FKe[r[t]];return e}function kde(r){if(r>=Fl._0&&r<=Fl._9)return r-Fl._0;if(r>=Fl.A&&r<=Fl.F)return r-(Fl.A-10);if(r>=Fl.a&&r<=Fl.f)return r-(Fl.a-10)}function $l(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(_de)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 o=0,s=0;o<t;o++,s+=2){let i=kde(r.charCodeAt(s)),a=kde(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function os(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];ze(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function zK(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function yb(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var _de,FKe,Fl,$K,dp=_(()=>{_de=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",FKe=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));Fl={_0:48,_9:57,A:65,F:70,a:97,f:102};$K=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])})});function Pde(r,e,t){return r&e^~r&t}function Rde(r,e,t){return r&e^r&t^e&t}var MS,Hl,Ln,Lde=_(()=>{dp();MS=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ek(this.buffer)}update(e){gb(this),ze(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Ek(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){gb(this),Dde(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Kl(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=Ek(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must 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 d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Hl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ln=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});function KKe(r,e=!1){return e?{h:Number(r&Sk),l:Number(r>>Mde&Sk)}:{h:Number(r>>Mde&Sk)|0,l:Number(r&Sk)|0}}function Bde(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=KKe(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}function sc(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var Sk,Mde,HK,VK,fp,hp,BS,OS,Ode,Nde,Ude,Fde,Kde,zde,$de=_(()=>{Sk=BigInt(4294967295),Mde=BigInt(32);HK=(r,e,t)=>r>>>t,VK=(r,e,t)=>r<<32-t|e>>>t,fp=(r,e,t)=>r>>>t|e<<32-t,hp=(r,e,t)=>r<<32-t|e>>>t,BS=(r,e,t)=>r<<64-t|e>>>t-32,OS=(r,e,t)=>r>>>t-32|e<<64-t;Ode=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),Nde=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,Ude=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),Fde=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,Kde=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),zde=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0});var $Ke,rf,qK,jK,Hde,HKe,VKe,nf,of,GK,WK,Vde,qde,YK=_(()=>{Lde();$de();dp();$Ke=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]),rf=new Uint32Array(64),qK=class extends MS{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)rf[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=rf[d-15],p=rf[d-2],f=na(h,7)^na(h,18)^h>>>3,g=na(p,17)^na(p,19)^p>>>10;rf[d]=g+rf[d-7]+f+rf[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=na(a,6)^na(a,11)^na(a,25),p=u+h+Pde(a,c,l)+$Ke[d]+rf[d]|0,g=(na(n,2)^na(n,13)^na(n,22))+Rde(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Kl(rf)}destroy(){this.set(0,0,0,0,0,0,0,0),Kl(this.buffer)}},jK=class extends qK{A=Hl[0]|0;B=Hl[1]|0;C=Hl[2]|0;D=Hl[3]|0;E=Hl[4]|0;F=Hl[5]|0;G=Hl[6]|0;H=Hl[7]|0;constructor(){super(32)}},Hde=Bde(["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))),HKe=Hde[0],VKe=Hde[1],nf=new Uint32Array(80),of=new Uint32Array(80),GK=class extends MS{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:p,Gl:f,Hh:g,Hl:y}=this;return[e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y]}set(e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)nf[b]=e.getUint32(t),of[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=nf[b-15]|0,S=of[b-15]|0,T=fp(x,S,1)^fp(x,S,8)^HK(x,S,7),A=hp(x,S,1)^hp(x,S,8)^VK(x,S,7),v=nf[b-2]|0,C=of[b-2]|0,P=fp(v,C,19)^BS(v,C,61)^HK(v,C,6),F=hp(v,C,19)^OS(v,C,61)^VK(v,C,6),R=Ude(A,F,of[b-7],of[b-16]),k=Fde(R,T,P,nf[b-7],nf[b-16]);nf[b]=k|0,of[b]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:p,Fl:f,Gh:g,Gl:y,Hh:m,Hl:w}=this;for(let b=0;b<80;b++){let x=fp(d,h,14)^fp(d,h,18)^BS(d,h,41),S=hp(d,h,14)^hp(d,h,18)^OS(d,h,41),T=d&p^~d&g,A=h&f^~h&y,v=Kde(w,S,A,VKe[b],of[b]),C=zde(v,m,x,T,HKe[b],nf[b]),P=v|0,F=fp(n,o,28)^BS(n,o,34)^BS(n,o,39),R=hp(n,o,28)^OS(n,o,34)^OS(n,o,39),k=n&s^n&a^s&a,I=o&i^o&c^i&c;m=g|0,w=y|0,g=p|0,y=f|0,p=d|0,f=h|0,{h:d,l:h}=sc(l|0,u|0,C|0,P|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=Ode(P,R,I);n=Nde(E,C,F,k),o=E|0}({h:n,l:o}=sc(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=sc(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=sc(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=sc(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=sc(this.Eh|0,this.El|0,d|0,h|0),{h:p,l:f}=sc(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:y}=sc(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:w}=sc(this.Hh|0,this.Hl|0,m|0,w|0),this.set(n,o,s,i,a,c,l,u,d,h,p,f,g,y,m,w)}roundClean(){Kl(nf,of)}destroy(){Kl(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},WK=class extends GK{Ah=Ln[0]|0;Al=Ln[1]|0;Bh=Ln[2]|0;Bl=Ln[3]|0;Ch=Ln[4]|0;Cl=Ln[5]|0;Dh=Ln[6]|0;Dl=Ln[7]|0;Eh=Ln[8]|0;El=Ln[9]|0;Fh=Ln[10]|0;Fl=Ln[11]|0;Gh=Ln[12]|0;Gl=Ln[13]|0;Hh=Ln[14]|0;Hl=Ln[15]|0;constructor(){super(64)}},Vde=zK(()=>new jK,$K(1)),qde=zK(()=>new WK,$K(3))});function Vl(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function jde(r){if(typeof r=="bigint"){if(!Ck(r))throw new Error("positive bigint expected, got "+r)}else oc(r);return r}function NS(r){let e=jde(r).toString(16);return e.length&1?"0"+e:e}function Gde(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ZK:BigInt("0x"+r)}function bb(r){return Gde(zl(r))}function pp(r){return Gde(zl(Ik(ze(r)).reverse()))}function Ak(r,e){oc(e),r=jde(r);let t=$l(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function JK(r,e){return Ak(r,e).reverse()}function Ik(r){return Uint8Array.from(r)}function qKe(r,e,t){return Ck(r)&&Ck(e)&&Ck(t)&&e<=r&&r<t}function US(r,e,t,n){if(!qKe(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function QK(r){let e;for(e=0;r>ZK;r>>=XK,e+=1);return e}function Wde(r,e,t){if(oc(r,"hashLen"),oc(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},h=(...y)=>t(l,os(c,...y)),p=(y=o)=>{l=h(s,y),c=h(),y.length!==0&&(l=h(i,y),c=h())},f=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=h();let w=c.slice();m.push(w),y+=c.length}return os(...m)};return(y,m)=>{d(),p(y);let w;for(;!(w=m(f()));)p();return d(),w}}function sf(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function wb(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var ZK,XK,Ck,FS,KS=_(()=>{dp();dp();ZK=BigInt(0),XK=BigInt(1);Ck=r=>typeof r=="bigint"&&ZK<=r;FS=r=>(XK<<BigInt(r))-XK});function kr(r,e){let t=r%e;return t>=No?t:e+t}function Vt(r,e,t){let n=r;for(;e-- >No;)n*=n,n%=t;return n}function Yde(r,e){if(r===No)throw new Error("invert: expected non-zero number");if(e<=No)throw new Error("invert: expected positive modulus, got "+e);let t=kr(r,e),n=e,o=No,s=Qr,i=Qr,a=No;for(;t!==No;){let l=n/t,u=n%t,d=o-i*l,h=s-a*l;n=t,t=u,o=i,s=a,i=d,a=h}if(n!==Qr)throw new Error("invert: does not exist");return kr(o,e)}function t9(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function rfe(r,e){let t=(r.ORDER+Qr)/Jde,n=r.pow(e,t);return t9(r,n,e),n}function WKe(r,e){let t=(r.ORDER-Qde)/efe,n=r.mul(e,mp),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,mp),o),a=r.mul(s,r.sub(i,r.ONE));return t9(r,a,e),a}function YKe(r){let e=xb(r),t=nfe(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+jKe)/tfe;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),d=a.mul(l,o),h=a.mul(l,s),p=a.eql(a.sqr(u),c),f=a.eql(a.sqr(d),c);l=a.cmov(l,u,p),u=a.cmov(h,d,f);let g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return t9(a,y,c),y}}function nfe(r){if(r<Zde)throw new Error("sqrt is not defined for small field");let e=r-Qr,t=0;for(;e%mp===No;)e/=mp,t++;let n=mp,o=xb(r);for(;Xde(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return rfe;let s=o.pow(n,e),i=(e+Qr)/mp;return function(c,l){if(c.is0(l))return l;if(Xde(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,s),h=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let f=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(f++,g=c.sqr(g),f===u)throw new Error("Cannot find square root");let y=Qr<<BigInt(u-f-1),m=c.pow(d,y);u=f,d=c.sqr(m),h=c.mul(h,d),p=c.mul(p,m)}return p}}function XKe(r){return r%Jde===Zde?rfe:r%efe===Qde?WKe:r%tfe===GKe?YKe(r):nfe(r)}function r9(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=ZKe.reduce((n,o)=>(n[o]="function",n),e);return sf(r,t),r}function JKe(r,e,t){if(t<No)throw new Error("invalid exponent, negatives unsupported");if(t===No)return r.ONE;if(t===Qr)return e;let n=r.ONE,o=e;for(;t>No;)t&Qr&&(n=r.mul(n,o)),o=r.sqr(o),t>>=Qr;return n}function zS(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function Xde(r,e){let t=(r.ORDER-Qr)/mp,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function QKe(r,e){e!==void 0&&oc(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function xb(r,e={}){return new e9(r,e)}function sfe(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 n9(r){let e=sfe(r);return e+Math.ceil(e/2)}function o9(r,e,t=!1){ze(r);let n=r.length,o=sfe(e),s=n9(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?pp(r):bb(r),a=kr(i,e-Qr)+Qr;return t?JK(a,o):Ak(a,o)}var No,Qr,mp,Zde,Jde,Qde,jKe,efe,GKe,tfe,ofe,ZKe,e9,$S=_(()=>{KS();No=BigInt(0),Qr=BigInt(1),mp=BigInt(2),Zde=BigInt(3),Jde=BigInt(4),Qde=BigInt(5),jKe=BigInt(7),efe=BigInt(8),GKe=BigInt(9),tfe=BigInt(16);ofe=(r,e)=>(kr(r,e)&Qr)===Qr,ZKe=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];e9=class{ORDER;BITS;BYTES;isLE;ZERO=No;ONE=Qr;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=No)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=QKe(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return kr(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return No<=e&&e<this.ORDER}is0(e){return e===No}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Qr)===Qr}neg(e){return kr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return kr(e*e,this.ORDER)}add(e,t){return kr(e+t,this.ORDER)}sub(e,t){return kr(e-t,this.ORDER)}mul(e,t){return kr(e*t,this.ORDER)}pow(e,t){return JKe(this,e,t)}div(e,t){return kr(e*Yde(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Yde(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=XKe(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?JK(e,this.BYTES):Ak(e,this.BYTES)}fromBytes(e,t=!1){ze(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?pp(e):bb(e);if(a&&(c=kr(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return zS(this,e)}cmov(e,t,n){return n?t:e}}});function HS(r,e){let t=e.negate();return r?t:e}function yp(r,e){let t=zS(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function lfe(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function s9(r,e){lfe(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=FS(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function ife(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=gp);let l=e*n,u=l+Math.abs(a)-1,d=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:p,offsetF:l}}function a9(r){return ufe.get(r)||1}function afe(r){if(r!==vb)throw new Error("invalid wNAF")}function dfe(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>vb||n>vb;)t&gp&&(s=s.add(o)),n&gp&&(i=i.add(o)),o=o.double(),t>>=gp,n>>=gp;return{p1:s,p2:i}}function cfe(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return r9(e),e}else return xb(r,{isLE:t})}function Tk(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>vb))throw new Error(`CURVE.${c} must be positive bigint`)}let o=cfe(e.p,t.Fp,n),s=cfe(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.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:o,Fn:s}}function kk(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var vb,gp,i9,ufe,Eb,c9=_(()=>{KS();$S();vb=BigInt(0),gp=BigInt(1);i9=new WeakMap,ufe=new WeakMap;Eb=class{BASE;ZERO;Fn;bits;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 o=e;for(;t>vb;)t&gp&&(n=n.add(o)),o=o.double(),t>>=gp;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=s9(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=s9(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:p}=ife(n,a,i);n=c,u?s=s.add(HS(h,t[p])):o=o.add(HS(d,t[l]))}return afe(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=s9(e,this.bits);for(let i=0;i<s.windows&&n!==vb;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=ife(n,i,s);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return afe(n),o}getPrecomputes(e,t,n){let o=i9.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),i9.set(t,o))),o}cached(e,t,n){let o=a9(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=a9(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){lfe(t,this.bits),ufe.set(e,t),i9.delete(e)}hasCache(e){return a9(e)!==1}}});function t9e(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function ffe(r,e={}){let t=Tk("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;sf(e,{},{uvRatio:"function"});let a=l9<<BigInt(o.BYTES*8)-en,c=y=>n.create(y),l=e.uvRatio||((y,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,m))}}catch{return{isValid:!1,value:af}}});if(!t9e(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(y,m,w=!1){let b=w?en:af;return US("coordinate "+y,m,b,a),m}function d(y){if(!(y instanceof f))throw new Error("EdwardsPoint expected")}let h=wb((y,m)=>{let{X:w,Y:b,Z:x}=y,S=y.is0();m==null&&(m=S?e9e:n.inv(x));let T=c(w*m),A=c(b*m),v=n.mul(x,m);if(S)return{x:af,y:en};if(v!==en)throw new Error("invZ was invalid");return{x:T,y:A}}),p=wb(y=>{let{a:m,d:w}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:b,Y:x,Z:S,T}=y,A=c(b*b),v=c(x*x),C=c(S*S),P=c(C*C),F=c(A*m),R=c(C*c(F+v)),k=c(P+c(w*c(A*v)));if(R!==k)throw new Error("bad point: equation left != right (1)");let I=c(b*x),E=c(S*T);if(I!==E)throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,en,c(s.Gx*s.Gy));static ZERO=new f(af,en,en,af);static Fp=n;static Fn=o;X;Y;Z;T;constructor(m,w,b,x){this.X=u("x",m),this.Y=u("y",w),this.Z=u("z",b,!0),this.T=u("t",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof f)throw new Error("extended point not allowed");let{x:w,y:b}=m||{};return u("x",w),u("y",b),new f(w,b,en,c(w*b))}static fromBytes(m,w=!1){let b=n.BYTES,{a:x,d:S}=s;m=Ik(ze(m,b,"point")),Vl(w,"zip215");let T=Ik(m),A=m[b-1];T[b-1]=A&-129;let v=pp(T),C=w?a:n.ORDER;US("point.y",v,af,C);let P=c(v*v),F=c(P-en),R=c(S*P-x),{isValid:k,value:I}=l(F,R);if(!k)throw new Error("bad point: invalid y coordinate");let E=(I&en)===en,D=(A&128)!==0;if(!w&&I===af&&D)throw new Error("bad point: x=0 and x_0=1");return D!==E&&(I=c(-I)),f.fromAffine({x:I,y:v})}static fromHex(m,w=!1){return f.fromBytes($l(m),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return g.createCache(this,m),w||this.multiply(l9),this}assertValidity(){p(this)}equals(m){d(m);let{X:w,Y:b,Z:x}=this,{X:S,Y:T,Z:A}=m,v=c(w*A),C=c(S*x),P=c(b*A),F=c(T*x);return v===C&&P===F}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=s,{X:w,Y:b,Z:x}=this,S=c(w*w),T=c(b*b),A=c(l9*c(x*x)),v=c(m*S),C=w+b,P=c(c(C*C)-S-T),F=v+T,R=F-A,k=v-T,I=c(P*R),E=c(F*k),D=c(P*k),M=c(R*F);return new f(I,E,M,D)}add(m){d(m);let{a:w,d:b}=s,{X:x,Y:S,Z:T,T:A}=this,{X:v,Y:C,Z:P,T:F}=m,R=c(x*v),k=c(S*C),I=c(A*b*F),E=c(T*P),D=c((x+S)*(v+C)-R-k),M=E-I,B=E+I,L=c(k-w*R),O=c(D*M),U=c(B*L),$=c(D*L),J=c(M*B);return new f(O,U,J,$)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:b}=g.cached(this,m,x=>yp(f,x));return yp(f,[w,b])[0]}multiplyUnsafe(m,w=f.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===af?f.ZERO:this.is0()||m===en?this:g.unsafe(this,m,b=>yp(f,b),w)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(m){return h(this,m)}clearCofactor(){return i===en?this:this.multiplyUnsafe(i)}toBytes(){let{x:m,y:w}=this.toAffine(),b=n.toBytes(w);return b[b.length-1]|=m&en?128:0,b}toHex(){return zl(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new Eb(f,o.BITS);return f.BASE.precompute(8),f}function hfe(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');sf(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||yb,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,C,P)=>{if(Vl(P,"phflag"),C.length||P)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(pp(v))}function d(v){let C=b.secretKey;ze(v,b.secretKey,"secretKey");let P=ze(e(v),2*C,"hashedSecretKey"),F=c(P.slice(0,C)),R=P.slice(C,2*C),k=u(F);return{head:F,prefix:R,scalar:k}}function h(v){let{head:C,prefix:P,scalar:F}=d(v),R=o.multiply(F),k=R.toBytes();return{head:C,prefix:P,scalar:F,point:R,pointBytes:k}}function p(v){return h(v).pointBytes}function f(v=Uint8Array.of(),...C){let P=os(...C);return u(e(l(P,ze(v,void 0,"context"),!!n)))}function g(v,C,P={}){v=ze(v,void 0,"message"),n&&(v=n(v));let{prefix:F,scalar:R,pointBytes:k}=h(C),I=f(P.context,F,v),E=o.multiply(I).toBytes(),D=f(P.context,E,k,v),M=i.create(I+D*R);if(!i.isValid(M))throw new Error("sign failed: invalid s");let B=os(E,i.toBytes(M));return ze(B,b.signature,"result")}let y={zip215:!0};function m(v,C,P,F=y){let{context:R,zip215:k}=F,I=b.signature;v=ze(v,I,"signature"),C=ze(C,void 0,"message"),P=ze(P,b.publicKey,"publicKey"),k!==void 0&&Vl(k,"zip215"),n&&(C=n(C));let E=I/2,D=v.subarray(0,E),M=pp(v.subarray(E,I)),B,L,O;try{B=r.fromBytes(P,k),L=r.fromBytes(D,k),O=o.multiplyUnsafe(M)}catch{return!1}if(!k&&B.isSmallOrder())return!1;let U=f(R,L.toBytes(),B.toBytes(),C);return L.add(B.multiplyUnsafe(U)).subtract(O).clearCofactor().is0()}let w=s.BYTES,b={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(v=a(b.seed)){return ze(v,b.seed,"seed")}function S(v){return up(v)&&v.length===i.BYTES}function T(v,C){try{return!!r.fromBytes(v,C)}catch{return!1}}let A={getExtendedPublicKey:h,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:T,toMontgomery(v){let{y:C}=r.fromBytes(v),P=b.publicKey,F=P===32;if(!F&&P!==57)throw new Error("only defined for 25519 and 448");let R=F?s.div(en+C,en-C):s.div(C-en,C+en);return s.toBytes(R)},toMontgomerySecret(v){let C=b.secretKey;ze(v,C);let P=e(v.subarray(0,C));return c(P).subarray(0,C)}};return Object.freeze({keygen:kk(x,p),getPublicKey:p,sign:g,verify:m,utils:A,Point:r,lengths:b})}var af,en,l9,e9e,pfe=_(()=>{KS();c9();af=BigInt(0),en=BigInt(1),l9=BigInt(2),e9e=BigInt(8)});function i9e(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=u9,a=r*r%s*r%s,c=Vt(a,mfe,s)*a%s,l=Vt(c,r9e,s)*r%s,u=Vt(l,n9e,s)*l%s,d=Vt(u,e,s)*u%s,h=Vt(d,t,s)*d%s,p=Vt(h,n,s)*h%s,f=Vt(p,o,s)*p%s,g=Vt(f,o,s)*p%s,y=Vt(g,e,s)*u%s;return{pow_p_5_8:Vt(y,mfe,s)*r%s,b2:a}}function a9e(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}function c9e(r,e){let t=u9,n=kr(e*e*e,t),o=kr(n*n*e,t),s=i9e(r*o).pow_p_5_8,i=kr(r*n*s,t),a=kr(e*i*i,t),c=i,l=kr(i*gfe,t),u=a===r,d=a===kr(-r,t),h=a===kr(-r*gfe,t);return u&&(i=c),(d||h)&&(i=l),ofe(i,t)&&(i=kr(-i,t)),{isValid:u||d,value:i}}function u9e(r){return hfe(l9e,qde,Object.assign({adjustScalarBytes:a9e},r))}var r9e,mfe,n9e,o9e,u9,s9e,gfe,l9e,yfe,bfe=_(()=>{YK();pfe();$S();r9e=BigInt(1),mfe=BigInt(2),n9e=BigInt(5),o9e=BigInt(8),u9=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),s9e={p:u9,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:o9e,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};gfe=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");l9e=ffe(s9e,{uvRatio:c9e});yfe=u9e({})});async function f9e(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await pk.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await pk.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 h9e(r,e,t){return yfe.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function wfe(r,e,t){return d9==null&&(d9=await d9e),d9?f9e(r,e,t):h9e(r,e,t)}var Dk,d9,d9e,f9=_(()=>{bfe();ef();Gue();Dk=32,d9e=(async()=>{try{return await pk.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})()});function _k(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var h9=_(()=>{IS();rc()});var Pk,vfe=_(()=>{Ll();ap();ip();cp();h9();LS();m9();f9();Pk=class{type="Ed25519";raw;constructor(e){this.raw=p9(e,Dk)}toMultihash(){return ra.digest(mb(this))}toCID(){return Rn.createV1(114,this.toMultihash())}toString(){return hr.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Os(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=wfe(this.raw,t,e);return _k(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}}});function Efe(r){return r=p9(r,Dk),new Pk(r)}function p9(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new hi(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var m9=_(()=>{nc();vfe();f9()});function Sfe(r,e,t){g9[0]=r,e[t]=cf[0],e[t+1]=cf[1],e[t+2]=cf[2],e[t+3]=cf[3]}function Cfe(r,e){return cf[0]=r[e],cf[1]=r[e+1],cf[2]=r[e+2],cf[3]=r[e+3],g9[0]}function Afe(r,e,t){y9[0]=r,e[t]=lo[0],e[t+1]=lo[1],e[t+2]=lo[2],e[t+3]=lo[3],e[t+4]=lo[4],e[t+5]=lo[5],e[t+6]=lo[6],e[t+7]=lo[7]}function Ife(r,e){return lo[0]=r[e],lo[1]=r[e+1],lo[2]=r[e+2],lo[3]=r[e+3],lo[4]=r[e+4],lo[5]=r[e+5],lo[6]=r[e+6],lo[7]=r[e+7],y9[0]}var g9,cf,y9,lo,b9=_(()=>{g9=new Float32Array([-0]),cf=new Uint8Array(g9.buffer);y9=new Float64Array([-0]),lo=new Uint8Array(y9.buffer)});var m9e,g9e,Ns,bp,Tfe,w9=_(()=>{m9e=BigInt(Number.MAX_SAFE_INTEGER),g9e=BigInt(Number.MIN_SAFE_INTEGER),Ns=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 bp;if(e<m9e&&e>g9e)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>Tfe&&(o=0n,++n>Tfe&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return bp;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}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):bp}},bp=new Ns(0,0);bp.toBigInt=function(){return 0n};bp.zzEncode=bp.zzDecode=function(){return this};bp.length=function(){return 1};Tfe=4294967296n});function kfe(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 Dfe(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function x9(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}var v9=_(()=>{});function oa(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Rk(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function S9(r){return new E9(r instanceof Uint8Array?r:r.subarray())}var E9,C9=_(()=>{Ol();b9();w9();v9();E9=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,oa(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 oa(this,4);return Rk(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw oa(this,4);return Rk(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw oa(this,4);let e=Cfe(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw oa(this,4);let e=Ife(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 oa(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Dfe(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw oa(this,e);this.pos+=e}else do if(this.pos>=this.len)throw oa(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 Ns(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 oa(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 oa(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 oa(this,8);let e=Rk(this.buf,this.pos+=4),t=Rk(this.buf,this.pos+=4);return new Ns(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=CK(this.buf,this.pos);return this.pos+=Jr(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 Lk(r,e,t){let n=S9(r);return e.decode(n,void 0,t)}var Pfe=_(()=>{C9()});function A9(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return ao(i);o+i>e&&(n=ao(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Rfe=_(()=>{Qd()});function I9(){}function b9e(r){return globalThis.Buffer!=null?ao(r):y9e(r)}function T9(r,e,t){e[t]=r&255}function w9e(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function Mk(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 VS(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 x9e(r,e,t){e.set(r,t)}function v9e(r,e,t){e.set(r,t)}function E9e(r,e,t){r.length<40?x9(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Ir(r),t)}function _9(){return new qS}var wp,k9,y9e,qS,D9,P9=_(()=>{Ol();Qd();rc();b9();w9();Rfe();v9();wp=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};k9=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},y9e=A9();qS=class{len;head;tail;states;constructor(){this.len=0,this.head=new wp(I9,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new wp(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new D9((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(Mk,10,Ns.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ns.fromBigInt(e);return this._push(Mk,t.length(),t)}uint64Number(e){return this._push(db,Jr(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=Ns.fromBigInt(e).zzEncode();return this._push(Mk,t.length(),t)}sint64Number(e){let t=Ns.fromNumber(e).zzEncode();return this._push(Mk,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(T9,1,e?1:0)}fixed32(e){return this._push(VS,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ns.fromBigInt(e);return this._push(VS,4,t.lo)._push(VS,4,t.hi)}fixed64Number(e){let t=Ns.fromNumber(e);return this._push(VS,4,t.lo)._push(VS,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(Sfe,4,e)}double(e){return this._push(Afe,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(T9,1,0):this.uint32(t)._push(x9e,t,e)}string(e){let t=kfe(e);return t!==0?this.uint32(t)._push(x9,t,e):this._push(T9,1,0)}fork(){return this.states=new k9(this),this.head=this.tail=new wp(I9,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 wp(I9,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=b9e(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};D9=class extends wp{next;constructor(e,t){super(w9e,e,t),this.next=void 0}};globalThis.Buffer!=null&&(qS.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(v9e,e,r),this},qS.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(E9e,e,r),this})});function Bk(r,e){let t=_9();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Lfe=_(()=>{P9()});function Ok(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}var Sb,R9=_(()=>{(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"})(Sb||(Sb={}))});function L9(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return Ok("enum",Sb.VARINT,t,n)}var Mfe=_(()=>{R9()});function Nk(r,e){return Ok("message",Sb.LENGTH_DELIMITED,r,e)}var Bfe=_(()=>{R9()});var Ofe=_(()=>{Pfe();Lfe();Mfe();Bfe();C9();P9()});var Us,M9,jS,B9,Nfe=_(()=>{Ofe();(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Us||(Us={}));(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(M9||(M9={}));(function(r){r.codec=()=>L9(M9)})(Us||(Us={}));(function(r){let e;r.codec=()=>(e==null&&(e=Nk((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Us.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Us.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Bk(t,r.codec()),r.decode=(t,n)=>Lk(t,r.codec(),n)})(jS||(jS={}));(function(r){let e;r.codec=()=>(e==null&&(e=Nk((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Us.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Us.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Bk(t,r.codec()),r.decode=(t,n)=>Lk(t,r.codec(),n)})(B9||(B9={}))});var Uk,O9,Ufe=_(()=>{dp();Uk=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(vk(e),ze(t,void 0,"key"),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 n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);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),Kl(o)}update(e){return gb(this),this.iHash.update(e),this}digestInto(e){gb(this),ze(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,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()}},O9=(r,e,t)=>new Uk(r,e).update(t).digest();O9.create=(r,e)=>new Uk(r,e)});function C9e(r,e,t){let[[n,o],[s,i]]=e,a=Ffe(i*r,t),c=Ffe(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,d=l<ql,h=u<ql;d&&(l=-l),h&&(u=-u);let p=FS(Math.ceil(QK(t)/2))+Cb;if(l<ql||l>=p||u<ql||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:d,k1:l,k2neg:h,k2:u}}function U9(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function N9(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Vl(t.lowS,"lowS"),Vl(t.prehash,"prehash"),t.format!==void 0&&U9(t.format),t}function zfe(r,e={}){let t=Tk("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;sf(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=Hfe(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(R,k,I){let{x:E,y:D}=k.toAffine(),M=n.toBytes(E);if(Vl(I,"isCompressed"),I){u();let B=!n.isOdd(D);return os($fe(B),M)}else return os(Uint8Array.of(4),M,n.toBytes(D))}function h(R){ze(R,void 0,"Point");let{publicKey:k,publicKeyUncompressed:I}=l,E=R.length,D=R[0],M=R.subarray(1);if(E===k&&(D===2||D===3)){let B=n.fromBytes(M);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let L=g(B),O;try{O=n.sqrt(L)}catch(J){let X=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();let U=n.isOdd(O);return(D&1)===1!==U&&(O=n.neg(O)),{x:B,y:O}}else if(E===I&&D===4){let B=n.BYTES,L=n.fromBytes(M.subarray(0,B)),O=n.fromBytes(M.subarray(B,B*2));if(!y(L,O))throw new Error("bad point: is not on curve");return{x:L,y:O}}else throw new Error(`bad point: got length ${E}, expected compressed=${k} or uncompressed=${I}`)}let p=e.toBytes||d,f=e.fromBytes||h;function g(R){let k=n.sqr(R),I=n.mul(k,R);return n.add(n.add(I,n.mul(R,s.a)),s.b)}function y(R,k){let I=n.sqr(k),E=g(R);return n.eql(I,E)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(s.a,Fk),A9e),w=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(m,w)))throw new Error("bad curve params: a or b");function b(R,k,I=!1){if(!n.isValid(k)||I&&n.is0(k))throw new Error(`bad point coordinate ${R}`);return k}function x(R){if(!(R instanceof C))throw new Error("Weierstrass Point expected")}function S(R){if(!c||!c.basises)throw new Error("no endo");return C9e(R,c.basises,o.ORDER)}let T=wb((R,k)=>{let{X:I,Y:E,Z:D}=R;if(n.eql(D,n.ONE))return{x:I,y:E};let M=R.is0();k==null&&(k=M?n.ONE:n.inv(D));let B=n.mul(I,k),L=n.mul(E,k),O=n.mul(D,k);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:B,y:L}}),A=wb(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:k,y:I}=R.toAffine();if(!n.isValid(k)||!n.isValid(I))throw new Error("bad point: x or y not field elements");if(!y(k,I))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(R,k,I,E,D){return I=new C(n.mul(I.X,R),I.Y,I.Z),k=HS(E,k),I=HS(D,I),k.add(I)}class C{static BASE=new C(s.Gx,s.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(k,I,E){this.X=b("x",k),this.Y=b("y",I,!0),this.Z=b("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(k){let{x:I,y:E}=k||{};if(!k||!n.isValid(I)||!n.isValid(E))throw new Error("invalid affine point");if(k instanceof C)throw new Error("projective point not allowed");return n.is0(I)&&n.is0(E)?C.ZERO:new C(I,E,n.ONE)}static fromBytes(k){let I=C.fromAffine(f(ze(k,void 0,"point")));return I.assertValidity(),I}static fromHex(k){return C.fromBytes($l(k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,I=!0){return F.createCache(this,k),I||this.multiply(Fk),this}assertValidity(){A(this)}hasEvenY(){let{y:k}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(k)}equals(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.eql(n.mul(I,L),n.mul(M,D)),U=n.eql(n.mul(E,L),n.mul(B,D));return O&&U}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:k,b:I}=s,E=n.mul(I,Fk),{X:D,Y:M,Z:B}=this,L=n.ZERO,O=n.ZERO,U=n.ZERO,$=n.mul(D,D),J=n.mul(M,M),X=n.mul(B,B),N=n.mul(D,M);return N=n.add(N,N),U=n.mul(D,B),U=n.add(U,U),L=n.mul(k,U),O=n.mul(E,X),O=n.add(L,O),L=n.sub(J,O),O=n.add(J,O),O=n.mul(L,O),L=n.mul(N,L),U=n.mul(E,U),X=n.mul(k,X),N=n.sub($,X),N=n.mul(k,N),N=n.add(N,U),U=n.add($,$),$=n.add(U,$),$=n.add($,X),$=n.mul($,N),O=n.add(O,$),X=n.mul(M,B),X=n.add(X,X),$=n.mul(X,N),L=n.sub(L,$),U=n.mul(X,J),U=n.add(U,U),U=n.add(U,U),new C(L,O,U)}add(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.ZERO,U=n.ZERO,$=n.ZERO,J=s.a,X=n.mul(s.b,Fk),N=n.mul(I,M),H=n.mul(E,B),Z=n.mul(D,L),ae=n.add(I,E),Q=n.add(M,B);ae=n.mul(ae,Q),Q=n.add(N,H),ae=n.sub(ae,Q),Q=n.add(I,D);let oe=n.add(M,L);return Q=n.mul(Q,oe),oe=n.add(N,Z),Q=n.sub(Q,oe),oe=n.add(E,D),O=n.add(B,L),oe=n.mul(oe,O),O=n.add(H,Z),oe=n.sub(oe,O),$=n.mul(J,Q),O=n.mul(X,Z),$=n.add(O,$),O=n.sub(H,$),$=n.add(H,$),U=n.mul(O,$),H=n.add(N,N),H=n.add(H,N),Z=n.mul(J,Z),Q=n.mul(X,Q),H=n.add(H,Z),Z=n.sub(N,Z),Z=n.mul(J,Z),Q=n.add(Q,Z),N=n.mul(H,Q),U=n.add(U,N),N=n.mul(oe,Q),O=n.mul(ae,O),O=n.sub(O,N),N=n.mul(ae,H),$=n.mul(oe,$),$=n.add($,N),new C(O,U,$)}subtract(k){return this.add(k.negate())}is0(){return this.equals(C.ZERO)}multiply(k){let{endo:I}=e;if(!o.isValidNot0(k))throw new Error("invalid scalar: out of range");let E,D,M=B=>F.cached(this,B,L=>yp(C,L));if(I){let{k1neg:B,k1:L,k2neg:O,k2:U}=S(k),{p:$,f:J}=M(L),{p:X,f:N}=M(U);D=J.add(N),E=v(I.beta,$,X,B,O)}else{let{p:B,f:L}=M(k);E=B,D=L}return yp(C,[E,D])[0]}multiplyUnsafe(k){let{endo:I}=e,E=this;if(!o.isValid(k))throw new Error("invalid scalar: out of range");if(k===ql||E.is0())return C.ZERO;if(k===Cb)return E;if(F.hasCache(this))return this.multiply(k);if(I){let{k1neg:D,k1:M,k2neg:B,k2:L}=S(k),{p1:O,p2:U}=dfe(C,E,M,L);return v(I.beta,O,U,D,B)}else return F.unsafe(E,k)}toAffine(k){return T(this,k)}isTorsionFree(){let{isTorsionFree:k}=e;return i===Cb?!0:k?k(C,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:k}=e;return i===Cb?this:k?k(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return Vl(k,"isCompressed"),this.assertValidity(),p(C,this,k)}toHex(k=!0){return zl(this.toBytes(k))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,F=new Eb(C,e.endo?Math.ceil(P/2):P);return C.BASE.precompute(8),C}function $fe(r){return Uint8Array.of(r?2:3)}function Hfe(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function I9e(r,e={}){let{Fn:t}=r,n=e.randomBytes||yb,o=Object.assign(Hfe(r.Fp,t),{seed:n9(t.ORDER)});function s(p){try{let f=t.fromBytes(p);return t.isValidNot0(f)}catch{return!1}}function i(p,f){let{publicKey:g,publicKeyUncompressed:y}=o;try{let m=p.length;return f===!0&&m!==g||f===!1&&m!==y?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return o9(ze(p,o.seed,"seed"),t.ORDER)}function c(p,f=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(f)}function l(p){let{secretKey:f,publicKey:g,publicKeyUncompressed:y}=o;if(!up(p)||"_lengths"in t&&t._lengths||f===g)return;let m=ze(p,void 0,"key").length;return m===g||m===y}function u(p,f,g=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(f)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(p);return r.fromBytes(f).multiply(y).toBytes(g)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=kk(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:d,lengths:o})}function Vfe(r,e,t={}){vk(e),sf(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||yb,o=t.hmac||((I,E)=>O9(e,I,E)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p}=I9e(r,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=a*Kfe<s.ORDER;function y(I){let E=a>>Cb;return I>E}function m(I,E){if(!i.isValidNot0(E))throw new Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return E}function w(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(I,E){U9(E);let D=p.signature,M=E==="compact"?D:E==="recovered"?D+1:void 0;return ze(I,M)}class x{r;s;recovery;constructor(E,D,M){if(this.r=m("r",E),this.s=m("s",D),M!=null){if(w(),![0,1,2,3].includes(M))throw new Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(E,D=f.format){b(E,D);let M;if(D==="der"){let{r:U,s:$}=lf.toSig(ze(E));return new x(U,$)}D==="recovered"&&(M=E[0],D="compact",E=E.subarray(1));let B=p.signature/2,L=E.subarray(0,B),O=E.subarray(B,B*2);return new x(i.fromBytes(L),i.fromBytes(O),M)}static fromHex(E,D){return this.fromBytes($l(E),D)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new x(this.r,this.s,E)}recoverPublicKey(E){let{r:D,s:M}=this,B=this.assertRecovery(),L=B===2||B===3?D+a:D;if(!s.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=s.toBytes(L),U=r.fromBytes(os($fe((B&1)===0),O)),$=i.inv(L),J=T(ze(E,void 0,"msgHash")),X=i.create(-J*$),N=i.create(M*$),H=r.BASE.multiplyUnsafe(X).add(U.multiplyUnsafe(N));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(E=f.format){if(U9(E),E==="der")return $l(lf.hexFromSig(this));let{r:D,s:M}=this,B=i.toBytes(D),L=i.toBytes(M);return E==="recovered"?(w(),os(Uint8Array.of(this.assertRecovery()),B,L)):os(B,L)}toHex(E){return zl(this.toBytes(E))}}let S=t.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let D=bb(E),M=E.length*8-c;return M>0?D>>BigInt(M):D},T=t.bits2int_modN||function(E){return i.create(S(E))},A=FS(c);function v(I){return US("num < 2^"+c,I,ql,A),i.toBytes(I)}function C(I,E){return ze(I,void 0,"message"),E?ze(e(I),void 0,"prehashed message"):I}function P(I,E,D){let{lowS:M,prehash:B,extraEntropy:L}=N9(D,f);I=C(I,B);let O=T(I),U=i.fromBytes(E);if(!i.isValidNot0(U))throw new Error("invalid private key");let $=[v(U),v(O)];if(L!=null&&L!==!1){let H=L===!0?n(p.secretKey):L;$.push(ze(H,void 0,"extraEntropy"))}let J=os(...$),X=O;function N(H){let Z=S(H);if(!i.isValidNot0(Z))return;let ae=i.inv(Z),Q=r.BASE.multiply(Z).toAffine(),oe=i.create(Q.x);if(oe===ql)return;let Fe=i.create(ae*i.create(X+oe*U));if(Fe===ql)return;let nr=(Q.x===oe?0:2)|Number(Q.y&Cb),fe=Fe;return M&&y(Fe)&&(fe=i.neg(Fe),nr^=1),new x(oe,fe,g?void 0:nr)}return{seed:J,k2sig:N}}function F(I,E,D={}){let{seed:M,k2sig:B}=P(I,E,D);return Wde(e.outputLen,i.BYTES,o)(M,B).toBytes(D.format)}function R(I,E,D,M={}){let{lowS:B,prehash:L,format:O}=N9(M,f);if(D=ze(D,void 0,"publicKey"),E=C(E,L),!up(I)){let U=I instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}b(I,O);try{let U=x.fromBytes(I,O),$=r.fromBytes(D);if(B&&U.hasHighS())return!1;let{r:J,s:X}=U,N=T(E),H=i.inv(X),Z=i.create(N*H),ae=i.create(J*H),Q=r.BASE.multiplyUnsafe(Z).add($.multiplyUnsafe(ae));return Q.is0()?!1:i.create(Q.x)===J}catch{return!1}}function k(I,E,D={}){let{prehash:M}=N9(D,f);return E=C(E,M),x.fromBytes(I,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:F,verify:R,recoverPublicKey:k,Signature:x,hash:e})}var Ffe,F9,lf,ql,Cb,Kfe,Fk,A9e,qfe=_(()=>{Ufe();dp();KS();c9();$S();Ffe=(r,e)=>(r+(r>=0?e:-e)/Kfe)/e;F9=class extends Error{constructor(e=""){super(e)}},lf={Err:F9,_tlv:{encode:(r,e)=>{let{Err:t}=lf;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,o=NS(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?NS(o.length/2|128):"";return NS(r)+s+o+e},decode(r,e){let{Err:t}=lf,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 o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&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)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=lf;if(r<ql)throw new e("integer: negative integers are not allowed");let t=NS(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}=lf;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 bb(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=lf,o=ze(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=lf,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},ql=BigInt(0),Cb=BigInt(1),Kfe=BigInt(2),Fk=BigInt(3),A9e=BigInt(4)});function k9e(r){let e=z9.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Vt(u,t,e)*u%e,h=Vt(d,t,e)*u%e,p=Vt(h,jfe,e)*l%e,f=Vt(p,o,e)*p%e,g=Vt(f,s,e)*f%e,y=Vt(g,a,e)*g%e,m=Vt(y,c,e)*y%e,w=Vt(m,a,e)*g%e,b=Vt(w,t,e)*u%e,x=Vt(b,i,e)*f%e,S=Vt(x,n,e)*l%e,T=Vt(S,jfe,e);if(!K9.eql(K9.sqr(T),r))throw new Error("Cannot find square root");return T}var z9,T9e,jfe,K9,D9e,Ab,$9=_(()=>{YK();$S();qfe();z9={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},T9e={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},jfe=BigInt(2);K9=xb(z9.p,{sqrt:k9e}),D9e=zfe(z9,{Fp:K9,endo:T9e}),Ab=Vfe(D9e,Vde)});function Gfe(r,e,t,n){let o=Zd.digest(t instanceof Uint8Array?t:t.subarray());if(_k(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ab.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new DS(String(s))});try{return n?.signal?.throwIfAborted(),Ab.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new DS(String(s))}}var Wfe=_(()=>{$9();bS();PK();h9()});var Kk,Yfe=_(()=>{Ll();ap();ip();cp();LS();H9();Wfe();Kk=class{type="secp256k1";raw;_key;constructor(e){this._key=Zfe(e),this.raw=Xfe(this._key)}toMultihash(){return ra.digest(mb(this))}toCID(){return Rn.createV1(114,this.toMultihash())}toString(){return hr.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:Os(this.raw,e.raw)}verify(e,t,n){return Gfe(this._key,t,e,n)}}});function Jfe(r){return new Kk(r)}function Xfe(r){return Ab.Point.fromBytes(r).toBytes()}function Zfe(r){try{return Ab.Point.fromBytes(r),r}catch(e){throw new mk(String(e))}}var H9=_(()=>{nc();$9();Yfe()});function Qfe(r){let{Type:e,Data:t}=jS.decode(r.digest),n=t??new Uint8Array;switch(e){case Us.Ed25519:return Efe(n);case Us.secp256k1:return Jfe(n);case Us.ECDSA:return Cde(n);default:throw new _S}}function mb(r){return jS.encode({Type:Us[r.type],Data:r.raw})}var LS=_(()=>{nc();KK();m9();Nfe();H9()});var ehe=_(()=>{});var the=_(()=>{});var zk,rhe=_(()=>{zk=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let h=Number.parseInt(d,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}}});function V9(r){if(!(r.length>P9e))return $k.new(r).parseWith(()=>$k.readIPv4Addr())}function q9(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>_9e))return $k.new(r).parseWith(()=>$k.readIPv6Addr())}var _9e,P9e,$k,GS=_(()=>{rhe();_9e=45,P9e=15,$k=new zk});var Hk=_(()=>{WS()});var q7t,j7t,WS=_(()=>{GS();Hk();q7t=parseInt("0xFFFF",16),j7t=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255])});var j9=_(()=>{GS();WS()});var G9=_(()=>{GS();j9();WS();Hk()});var W9=_(()=>{G9();Hk();WS();G9();j9()});var she=_(()=>{W9()});var ihe=_(()=>{});var ahe=_(()=>{});var che=_(()=>{ahe()});var lhe=_(()=>{});function Ib(r){return!!V9(r)}function YS(r){return!!q9(r)}var Tb=_(()=>{GS()});var uhe=Nr(XS=>{(function(){var r,e,t,n,o,s,i,a;a=function(c){var l,u,d,h;return l=(c&255<<24)>>>24,u=(c&255<<16)>>>16,d=(c&65280)>>>8,h=c&255,[l,u,d,h].join(".")},i=function(c){var l,u,d,h,p,f;for(l=[],d=h=0;h<=3&&c.length!==0;d=++h){if(d>0){if(c[0]!==".")throw new Error("Invalid IP");c=c.substring(1)}f=e(c),p=f[0],u=f[1],c=c.substring(u),l.push(p)}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"),s=t("a"),o=t("A"),e=function(c){var l,u,d,h,p;for(h=0,l=10,u="9",d=0,c.length>1&&c[d]==="0"&&(c[d+1]==="x"||c[d+1]==="X"?(d+=2,l=16):"0"<=c[d+1]&&c[d+1]<="9"&&(d++,l=8,u="7")),p=d;d<c.length;){if("0"<=c[d]&&c[d]<=u)h=h*l+(t(c[d])-n)>>>0;else if(l===16)if("a"<=c[d]&&c[d]<="f")h=h*l+(10+t(c[d])-s)>>>0;else if("A"<=c[d]&&c[d]<="F")h=h*l+(10+t(c[d])-o)>>>0;else break;else break;if(h>4294967295)throw new Error("too large");d++}if(d===p)throw new Error("empty octet");return[h,d]},r=(function(){function c(l,u){var d,h,p,f;if(typeof l!="string")throw new Error("Missing `net' parameter");if(u||(f=l.split("/",2),l=f[0],u=f[1]),u||(u=32),typeof u=="string"&&u.indexOf(".")>-1){try{this.maskLong=i(u)}catch(g){throw d=g,new Error("Invalid mask: "+u)}for(h=p=32;p>=0;h=--p)if(this.maskLong===4294967295<<32-h>>>0){this.bitmask=h;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=(i(l)&this.maskLong)>>>0}catch(g){throw d=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):(i(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,d,h;for(h=i(this.first),d=i(this.last),u=0;h<=d;)l(a(h),h,u),u++,h++},c.prototype.toString=function(){return this.base+"/"+this.bitmask},c})(),XS.ip2long=i,XS.long2ip=a,XS.Netmask=r}).call(XS)});var dhe,U9e,Izt,fhe=_(()=>{Tb();dhe=Ri(uhe(),1),U9e=["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"],Izt=U9e.map(r=>new dhe.Netmask(r))});var hhe=_(()=>{});var phe=_(()=>{the();she();ihe();che();lhe();hhe()});var mhe=_(()=>{});var kb=_(()=>{mhe()});function X9(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){h(ghe(i));return}if(i&&(c=()=>{h(ghe(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,h),t===Number.POSITIVE_INFINITY)return;let p=new Y9;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(f){h(f)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?h(o):(p.message=o??`Promise timed out after ${t} milliseconds`,h(p))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var Y9,ghe,yhe=_(()=>{Y9=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},ghe=r=>r.reason??new DOMException("This operation was aborted.","AbortError")});function K9e(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=F9e(r),d=async(...p)=>{let f=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(f))return}catch(g){n(),i(g);return}c.push(f),t.count===c.length&&(n(),s(c))},h=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,d);for(let p of t.rejectionEvents)a.includes(p)||u(p,h)};for(let p of a)l(p,d);for(let p of t.rejectionEvents)a.includes(p)||l(p,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=X9(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function bhe(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=K9e(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var F9e,whe=_(()=>{yhe();F9e=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}}});var xhe=_(()=>{});var ZS,Z9=_(()=>{ZS=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"}});function z9e(r){return r.reason}async function xp(r,e,t){if(e==null)return r;let n=t?.translateError??z9e;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var vp=_(()=>{});var vhe=_(()=>{kb()});var Zzt,Ehe=_(()=>{kb();vp();Ul();Zzt=Math.pow(2,20)*4});var She=_(()=>{});var Che=_(()=>{});var Ahe=_(()=>{vp()});var Ihe=_(()=>{});var J9=_(()=>{});var The=_(()=>{});var khe=_(()=>{J9()});var Mn,jl,qk,jk,Db=_(()=>{Mn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},jl=class extends Error{static name="ValidationError";name="ValidationError"},qk=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},jk=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"}});var Q9=_(()=>{});function t7(r){return e=>pr(e,r)}function r7(r){return e=>Ir(e,r)}function _b(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Ep(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function Dhe(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=Ir(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 o=Ep(n);return Nl([t,o],t.length+o.length)}function _he(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=tc.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 o=Ep(n);return Nl([t,o],t.length+o.length)}function n7(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=pr(e,"base32"),o=_b(t);return`${n}:${o}`}function Mhe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Mn(`Invalid IPv6 address "${r}"`)}}function Bhe(r){return H9e.decode(r)}function Ohe(r){return e=>r.encoder.encode(e)}var o7,Phe,Rhe,Lhe,e7,H9e,Nhe=_(()=>{Tb();wS();gK();IS();rc();ef();Db();o7=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Mn("Invalid byte value in IP address");e[n]=o}),e},Phe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ib(t[n]),i;s&&(i=o7(t[n]),t[n]=pr(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,pr(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Mn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},Rhe=function(r){if(r.byteLength!==4)throw new Mn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},Lhe=function(r){if(r.byteLength!==16)throw new Mn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Mn(`Invalid IPv6 address "${t}"`)}};e7=Object.values(ES).map(r=>r.decoder),H9e=(function(){let r=e7[0].or(e7[1]);return e7.slice(2).forEach(e=>r=r.or(e)),r})()});function V9e(r){if(parseInt(r).toString()!==r)throw new jl("Value must be an integer")}function q9e(r){if(r<0)throw new jl("Value must be a positive integer, or zero")}function j9e(r){return e=>{if(e>r)throw new jl(`Value must be smaller than or equal to ${r}`)}}function G9e(...r){return e=>{for(let t of r)t(e)}}var JS,Uhe=_(()=>{Db();JS=G9e(V9e,q9e,j9e(65535))});var tn,s7,Gl,M7e,Gk=_(()=>{Tb();mK();ok();Q9();Db();Nhe();Uhe();tn=-1,s7=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 jk(`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)}))}},Gl=new s7,M7e=[{code:4,name:"ip4",size:32,valueToBytes:o7,bytesToValue:Rhe,validate:r=>{if(!Ib(r))throw new jl(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Ep,bytesToValue:_b,validate:JS},{code:273,name:"udp",size:16,valueToBytes:Ep,bytesToValue:_b,validate:JS},{code:33,name:"dccp",size:16,valueToBytes:Ep,bytesToValue:_b,validate:JS},{code:41,name:"ip6",size:128,valueToBytes:Phe,bytesToValue:Lhe,stringToValue:Mhe,validate:r=>{if(!YS(r))throw new jl(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:tn},{code:43,name:"ipcidr",size:8,bytesToValue:t7("base10"),valueToBytes:r7("base10")},{code:53,name:"dns",size:tn},{code:54,name:"dns4",size:tn},{code:55,name:"dns6",size:tn},{code:56,name:"dnsaddr",size:tn},{code:132,name:"sctp",size:16,valueToBytes:Ep,bytesToValue:_b,validate:JS},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:tn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:tn,bytesToValue:t7("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?r7("base58btc")(r):Rn.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:n7,valueToBytes:Dhe},{code:445,name:"onion3",size:296,bytesToValue:n7,valueToBytes:_he},{code:446,name:"garlic64",size:tn},{code:447,name:"garlic32",size:tn},{code:448,name:"tls"},{code:449,name:"sni",size:tn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:tn,bytesToValue:Ohe(cK),valueToBytes:Bhe},{code:480,name:"http"},{code:481,name:"http-path",size:tn,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:tn}];M7e.forEach(r=>{Gl.addProtocol(r)})});function Fhe(r){let e=[],t=0;for(;t<r.length;){let n=Bl(r,t),o=Gl.getProtocol(n),s=Jr(n),i=B7e(o,r,t+s),a=0;i>0&&o.size===tn&&(a=Jr(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??pr(d)}e.push(l),t+=c}return e}function Khe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Gl.getProtocol(n.code),s=Jr(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Ir(n.value),a=i.byteLength,o.size===tn&&(c=Jr(a)));let l=new Uint8Array(s+c+a),u=0;db(n.code,l,u),u+=s,i!=null&&(o.size===tn&&(db(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Nl(t,e)}function zhe(r){if(r.charAt(0)!=="/")throw new Mn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Gl.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Mn(`Component ${o} 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 Mn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Mn("Incomplete multiaddr");return e}function $he(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Gl.getProtocol(e.code);if(t==null)throw new Mn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function B7e(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Bl(e,t)}var Hhe=_(()=>{Ol();IS();rc();ef();Db();Gk()});function N7e(r){if(r==null&&(r="/"),qhe(r))return r.getComponents();if(r instanceof Uint8Array)return Fhe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),zhe(r);if(Array.isArray(r))return r;throw new Mn("Must be a string, Uint8Array, Component[], or another Multiaddr")}function U7e(r){r.getComponents().forEach(e=>{let t=Gl.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}var O7e,i7,Wk,Vhe=_(()=>{cp();Hhe();Db();Gk();QS();O7e=Symbol.for("nodejs.util.inspect.custom"),i7=Symbol.for("@multiformats/multiaddr");Wk=class r{[i7]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=N7e(e),t.validate!==!1&&U7e(this)}get bytes(){return this.#r==null&&(this.#r=Khe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=$he(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new qk(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return Os(this.bytes,e.bytes)}[O7e](){return`Multiaddr(${this.toString()})`}}});function qhe(r){return!!r?.[i7]}function Yk(r){return new Wk(r)}var QS=_(()=>{Vhe();Gk();Q9()});var jhe=_(()=>{});var Ghe=_(()=>{Tb();W9()});var Whe=_(()=>{Tb();QS()});var Yhe=_(()=>{});var Xhe=_(()=>{});var Zhe=_(()=>{vp()});var Jhe=_(()=>{Zhe()});var Qhe=_(()=>{kb();Jhe()});function K7e(r){return typeof r?.closeRead=="function"}function z7e(r){return typeof r?.close=="function"}function a7(r){return K7e(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:z7e(r)?r.status!=="open":!1}function $7e(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function epe(r,e){let t=e?.maxBufferSize??F7e,n=new Tr,o,s=!1;if(!$7e(r))throw new hi("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new Xk("Stream was unwrapped");if(a7(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new ZS(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await xp(o.promise,u?.signal),a7(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(a7(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new ZS(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,d){if(s===!0)throw new Xk("Stream was unwrapped");r.send(u)||await bhe(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}var F7e,Xk,tpe=_(()=>{nc();Qhe();kb();whe();vp();Ol();Ul();Z9();F7e=4194304,Xk=class extends Error{static name="UnwrappedError";name="UnwrappedError"}});var xHt,vHt,rpe=_(()=>{Ol();Ul();xHt=1024*1024*4,vHt=1024*1024*4});var npe=_(()=>{});function ope(r){if(r===null)return"null";if(r===void 0)return"undefined";if(r===!0||r===!1)return"boolean";let e=typeof r;if(e==="string"||e==="number"||e==="bigint"||e==="symbol")return e;if(e==="function")return"Function";if(Array.isArray(r))return"Array";if(r instanceof Uint8Array)return"Uint8Array";if(r.constructor===Object)return"Object";let t=V7e(r);return t||"Object"}function V7e(r){let e=Object.prototype.toString.call(r).slice(8,-1);if(H7e.includes(e))return e}var H7e,spe=_(()=>{H7e=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]});var G,de,Fs=_(()=>{G=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}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};G.uint=new G(0,"uint",!0);G.negint=new G(1,"negint",!0);G.bytes=new G(2,"bytes",!0);G.string=new G(3,"string",!0);G.array=new G(4,"array",!1);G.map=new G(5,"map",!1);G.tag=new G(6,"tag",!1);G.float=new G(7,"float",!0);G.false=new G(7,"false",!0);G.true=new G(7,"true",!0);G.null=new G(7,"null",!0);G.undefined=new G(7,"undefined",!0);G.break=new G(7,"break",!0);de=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}`}}});function Zk(r){return e1&&globalThis.Buffer.isBuffer(r)}function Jk(r){return r instanceof Uint8Array?Zk(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):r:Uint8Array.from(r)}function Qk(r,e){if(Zk(r)&&Zk(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 ipe(r){let e=[],t=0;for(let n=0;n<r.length;n++){let o=r.charCodeAt(n);o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&n+1<r.length&&(r.charCodeAt(n+1)&64512)===56320?(o=65536+((o&1023)<<10)+(r.charCodeAt(++n)&1023),e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128)}return e}var e1,q7e,j7e,G7e,c7,ic,ape,cpe,lpe,Pb=_(()=>{e1=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",q7e=new TextEncoder;j7e=24,G7e=200,c7=e1?r=>r.length>=j7e?globalThis.Buffer.from(r):ipe(r):r=>r.length>=G7e?q7e.encode(r):ipe(r),ic=r=>Uint8Array.from(r),ape=e1?(r,e,t)=>Zk(r)?new Uint8Array(r.subarray(e,t)):r.slice(e,t):(r,e,t)=>r.slice(e,t),cpe=e1?(r,e)=>(r=r.map(t=>t instanceof Uint8Array?t:globalThis.Buffer.from(t)),Jk(globalThis.Buffer.concat(r,e))):(r,e)=>{let t=new Uint8Array(e),n=0;for(let o of r)n+o.length>t.length&&(o=o.subarray(0,t.length-n)),t.set(o,n),n+=o.length;return t},lpe=e1?r=>globalThis.Buffer.allocUnsafe(r):r=>new Uint8Array(r)});var W7e,t1,eD,upe=_(()=>{Pb();W7e=256,t1=class{constructor(e=W7e){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 o=t.length-(this.maxCursor-this.cursor)-1;t.set(e,o)}else{if(t){let o=t.length-(this.maxCursor-this.cursor)-1;o<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,o),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=lpe(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=ape(n,0,this.cursor)}else t=cpe(this.chunks,this.cursor);return e&&this.reset(),t}},eD=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}push(e){if(this.cursor+e.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}}});function Wl(r,e,t){if(r.length-e<t)throw new Error(`${et} not enough data for type`)}var et,l7,r1,sa=_(()=>{et="CBOR decode error:",l7="CBOR encode error:",r1=[];r1[23]=1;r1[24]=2;r1[25]=3;r1[26]=5;r1[27]=9});function Ks(r,e,t){Wl(r,e,1);let n=r[e];if(t.strict===!0&&n<rn[0])throw new Error(`${et} integer encoded in more bytes than necessary (strict decode)`);return n}function zs(r,e,t){Wl(r,e,2);let n=r[e]<<8|r[e+1];if(t.strict===!0&&n<rn[1])throw new Error(`${et} integer encoded in more bytes than necessary (strict decode)`);return n}function $s(r,e,t){Wl(r,e,4);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3];if(t.strict===!0&&n<rn[2])throw new Error(`${et} integer encoded in more bytes than necessary (strict decode)`);return n}function Hs(r,e,t){Wl(r,e,8);let n=r[e]*16777216+(r[e+1]<<16)+(r[e+2]<<8)+r[e+3],o=r[e+4]*16777216+(r[e+5]<<16)+(r[e+6]<<8)+r[e+7],s=(BigInt(n)<<BigInt(32))+BigInt(o);if(t.strict===!0&&s<rn[3])throw new Error(`${et} integer encoded in more bytes than necessary (strict decode)`);if(s<=Number.MAX_SAFE_INTEGER)return Number(s);if(t.allowBigInt===!0)return s;throw new Error(`${et} integers outside of the safe integer range are not supported`)}function dpe(r,e,t,n){return new de(G.uint,Ks(r,e+1,n),2)}function fpe(r,e,t,n){return new de(G.uint,zs(r,e+1,n),3)}function hpe(r,e,t,n){return new de(G.uint,$s(r,e+1,n),5)}function ppe(r,e,t,n){return new de(G.uint,Hs(r,e+1,n),9)}function pi(r,e){return nn(r,0,e.value)}function nn(r,e,t){if(t<rn[0]){let n=Number(t);r.push([e|n])}else if(t<rn[1]){let n=Number(t);r.push([e|24,n])}else if(t<rn[2]){let n=Number(t);r.push([e|25,n>>>8,n&255])}else if(t<rn[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<rn[4]){let o=[e|27,0,0,0,0,0,0,0],s=Number(n&BigInt(4294967295)),i=Number(n>>BigInt(32)&BigInt(4294967295));o[8]=s&255,s=s>>8,o[7]=s&255,s=s>>8,o[6]=s&255,s=s>>8,o[5]=s&255,o[4]=i&255,i=i>>8,o[3]=i&255,i=i>>8,o[2]=i&255,i=i>>8,o[1]=i&255,r.push(o)}else throw new Error(`${et} encountered BigInt larger than allowable range`)}}var rn,ac=_(()=>{Fs();sa();rn=[24,256,65536,4294967296,BigInt("18446744073709551616")];pi.encodedSize=function(e){return nn.encodedSize(e.value)};nn.encodedSize=function(e){return e<rn[0]?1:e<rn[1]?2:e<rn[2]?3:e<rn[3]?5:9};pi.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0}});function mpe(r,e,t,n){return new de(G.negint,-1-Ks(r,e+1,n),2)}function gpe(r,e,t,n){return new de(G.negint,-1-zs(r,e+1,n),3)}function ype(r,e,t,n){return new de(G.negint,-1-$s(r,e+1,n),5)}function wpe(r,e,t,n){let o=Hs(r,e+1,n);if(typeof o!="bigint"){let s=-1-o;if(s>=Number.MIN_SAFE_INTEGER)return new de(G.negint,s,9)}if(n.allowBigInt!==!0)throw new Error(`${et} integers outside of the safe integer range are not supported`);return new de(G.negint,u7-BigInt(o),9)}function tD(r,e){let t=e.value,n=typeof t=="bigint"?t*u7-bpe:t*-1-1;nn(r,e.type.majorEncoded,n)}var u7,bpe,d7=_(()=>{Fs();ac();sa();u7=BigInt(-1),bpe=BigInt(1);tD.encodedSize=function(e){let t=e.value,n=typeof t=="bigint"?t*u7-bpe:t*-1-1;return n<rn[0]?1:n<rn[1]?2:n<rn[2]?3:n<rn[3]?5:9};tD.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0}});function n1(r,e,t,n){Wl(r,e,t+n);let o=r.slice(e+t,e+t+n);return new de(G.bytes,o,t+n)}function xpe(r,e,t,n){return n1(r,e,1,t)}function vpe(r,e,t,n){return n1(r,e,2,Ks(r,e+1,n))}function Epe(r,e,t,n){return n1(r,e,3,zs(r,e+1,n))}function Spe(r,e,t,n){return n1(r,e,5,$s(r,e+1,n))}function Cpe(r,e,t,n){let o=Hs(r,e+1,n);if(typeof o=="bigint")throw new Error(`${et} 64-bit integer bytes lengths not supported`);return n1(r,e,9,o)}function rD(r){return r.encodedBytes===void 0&&(r.encodedBytes=G.equals(r.type,G.string)?c7(r.value):r.value),r.encodedBytes}function Rb(r,e){let t=rD(e);nn(r,e.type.majorEncoded,t.length),r.push(t)}function X7e(r,e){return r.length<e.length?-1:r.length>e.length?1:Qk(r,e)}var nD=_(()=>{Fs();sa();ac();Pb();Rb.encodedSize=function(e){let t=rD(e);return nn.encodedSize(t.length)+t.length};Rb.compareTokens=function(e,t){return X7e(rD(e),rD(t))}});function Q7e(r,e,t){if(t-e<J7e){let o="";for(let s=e;s<t;s++){let i=r[s];if(i&128)return Ape.decode(r.subarray(e,t));o+=String.fromCharCode(i)}return o}return Ape.decode(r.subarray(e,t))}function o1(r,e,t,n,o){let s=t+n;Wl(r,e,s);let i=new de(G.string,Q7e(r,e+t,e+s),s);return o.retainStringBytes===!0&&(i.byteValue=r.slice(e+t,e+s)),i}function Ipe(r,e,t,n){return o1(r,e,1,t,n)}function Tpe(r,e,t,n){return o1(r,e,2,Ks(r,e+1,n),n)}function kpe(r,e,t,n){return o1(r,e,3,zs(r,e+1,n),n)}function Dpe(r,e,t,n){return o1(r,e,5,$s(r,e+1,n),n)}function _pe(r,e,t,n){let o=Hs(r,e+1,n);if(typeof o=="bigint")throw new Error(`${et} 64-bit integer string lengths not supported`);return o1(r,e,9,o,n)}var Ape,J7e,Ppe,f7=_(()=>{Fs();sa();ac();nD();Ape=new TextDecoder,J7e=32;Ppe=Rb});function Lb(r,e,t,n){return new de(G.array,n,t)}function Rpe(r,e,t,n){return Lb(r,e,1,t)}function Lpe(r,e,t,n){return Lb(r,e,2,Ks(r,e+1,n))}function Mpe(r,e,t,n){return Lb(r,e,3,zs(r,e+1,n))}function Bpe(r,e,t,n){return Lb(r,e,5,$s(r,e+1,n))}function Ope(r,e,t,n){let o=Hs(r,e+1,n);if(typeof o=="bigint")throw new Error(`${et} 64-bit integer array lengths not supported`);return Lb(r,e,9,o)}function Npe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${et} indefinite length items not allowed`);return Lb(r,e,1,1/0)}function oD(r,e){nn(r,G.array.majorEncoded,e.value)}var h7=_(()=>{Fs();ac();sa();oD.compareTokens=pi.compareTokens;oD.encodedSize=function(e){return nn.encodedSize(e.value)}});function Mb(r,e,t,n){return new de(G.map,n,t)}function Upe(r,e,t,n){return Mb(r,e,1,t)}function Fpe(r,e,t,n){return Mb(r,e,2,Ks(r,e+1,n))}function Kpe(r,e,t,n){return Mb(r,e,3,zs(r,e+1,n))}function zpe(r,e,t,n){return Mb(r,e,5,$s(r,e+1,n))}function $pe(r,e,t,n){let o=Hs(r,e+1,n);if(typeof o=="bigint")throw new Error(`${et} 64-bit integer map lengths not supported`);return Mb(r,e,9,o)}function Hpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${et} indefinite length items not allowed`);return Mb(r,e,1,1/0)}function sD(r,e){nn(r,G.map.majorEncoded,e.value)}var p7=_(()=>{Fs();ac();sa();sD.compareTokens=pi.compareTokens;sD.encodedSize=function(e){return nn.encodedSize(e.value)}});function Vpe(r,e,t,n){return new de(G.tag,t,1)}function qpe(r,e,t,n){return new de(G.tag,Ks(r,e+1,n),2)}function jpe(r,e,t,n){return new de(G.tag,zs(r,e+1,n),3)}function Gpe(r,e,t,n){return new de(G.tag,$s(r,e+1,n),5)}function Wpe(r,e,t,n){return new de(G.tag,Hs(r,e+1,n),9)}function iD(r,e){nn(r,G.tag.majorEncoded,e.value)}var m7=_(()=>{Fs();ac();iD.compareTokens=pi.compareTokens;iD.encodedSize=function(e){return nn.encodedSize(e.value)}});function Ype(r,e,t,n){if(n.allowUndefined===!1)throw new Error(`${et} undefined values are not supported`);return n.coerceUndefinedToNull===!0?new de(G.null,null,1):new de(G.undefined,void 0,1)}function Xpe(r,e,t,n){if(n.allowIndefinite===!1)throw new Error(`${et} indefinite length items not allowed`);return new de(G.break,void 0,1)}function x7(r,e,t){if(t){if(t.allowNaN===!1&&Number.isNaN(r))throw new Error(`${et} NaN values are not supported`);if(t.allowInfinity===!1&&(r===1/0||r===-1/0))throw new Error(`${et} Infinity values are not supported`)}return new de(G.float,r,e)}function Zpe(r,e,t,n){return x7(v7(r,e+1),3,n)}function Jpe(r,e,t,n){return x7(E7(r,e+1),5,n)}function Qpe(r,e,t,n){return x7(nme(r,e+1),9,n)}function aD(r,e,t){let n=e.value;if(n===!1)r.push([G.float.majorEncoded|g7]);else if(n===!0)r.push([G.float.majorEncoded|y7]);else if(n===null)r.push([G.float.majorEncoded|b7]);else if(n===void 0)r.push([G.float.majorEncoded|w7]);else{let o,s=!1;(!t||t.float64!==!0)&&(tme(n),o=v7(ia,1),n===o||Number.isNaN(n)?(ia[0]=249,r.push(ia.slice(0,3)),s=!0):(rme(n),o=E7(ia,1),n===o&&(ia[0]=250,r.push(ia.slice(0,5)),s=!0))),s||(oze(n),o=nme(ia,1),ia[0]=251,r.push(ia.slice(0,9)))}}function tme(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 o=t-127;o<-24?mi.setUint16(0,0):o<-14?mi.setUint16(0,(e&2147483648)>>16|1<<24+o,!1):mi.setUint16(0,(e&2147483648)>>16|o+15<<10|n>>13,!1)}}}function v7(r,e){if(r.length-e<2)throw new Error(`${et} 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,o=t&1023,s;return n===0?s=o*2**-24:n!==31?s=(o+1024)*2**(n-25):s=o===0?1/0:NaN,t&32768?-s:s}function rme(r){mi.setFloat32(0,r,!1)}function E7(r,e){if(r.length-e<4)throw new Error(`${et} not enough data for float32`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,4).getFloat32(0,!1)}function oze(r){mi.setFloat64(0,r,!1)}function nme(r,e){if(r.length-e<8)throw new Error(`${et} not enough data for float64`);let t=(r.byteOffset||0)+e;return new DataView(r.buffer,t,8).getFloat64(0,!1)}var g7,y7,b7,w7,eme,mi,ia,S7=_(()=>{Fs();sa();ac();g7=20,y7=21,b7=22,w7=23;aD.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){tme(n);let o=v7(ia,1);if(n===o||Number.isNaN(n))return 3;if(rme(n),o=E7(ia,1),n===o)return 5}return 9};eme=new ArrayBuffer(9),mi=new DataView(eme,1),ia=new Uint8Array(eme,0);aD.compareTokens=pi.compareTokens});function tt(r,e,t){throw new Error(`${et} encountered invalid minor (${t}) for major ${r[e]>>>5}`)}function cD(r){return()=>{throw new Error(`${et} ${r}`)}}function ome(r){switch(r.type){case G.false:return ic([244]);case G.true:return ic([245]);case G.null:return ic([246]);case G.bytes:return r.value.length?void 0:ic([64]);case G.string:return r.value===""?ic([96]):void 0;case G.array:return r.value===0?ic([128]):void 0;case G.map:return r.value===0?ic([160]):void 0;case G.uint:return r.value<24?ic([Number(r.value)]):void 0;case G.negint:if(r.value>=-24)return ic([31-Number(r.value)])}}var ie,cc,C7=_(()=>{Fs();ac();d7();nD();f7();h7();p7();m7();S7();sa();Pb();ie=[];for(let r=0;r<=23;r++)ie[r]=tt;ie[24]=dpe;ie[25]=fpe;ie[26]=hpe;ie[27]=ppe;ie[28]=tt;ie[29]=tt;ie[30]=tt;ie[31]=tt;for(let r=32;r<=55;r++)ie[r]=tt;ie[56]=mpe;ie[57]=gpe;ie[58]=ype;ie[59]=wpe;ie[60]=tt;ie[61]=tt;ie[62]=tt;ie[63]=tt;for(let r=64;r<=87;r++)ie[r]=xpe;ie[88]=vpe;ie[89]=Epe;ie[90]=Spe;ie[91]=Cpe;ie[92]=tt;ie[93]=tt;ie[94]=tt;ie[95]=cD("indefinite length bytes/strings are not supported");for(let r=96;r<=119;r++)ie[r]=Ipe;ie[120]=Tpe;ie[121]=kpe;ie[122]=Dpe;ie[123]=_pe;ie[124]=tt;ie[125]=tt;ie[126]=tt;ie[127]=cD("indefinite length bytes/strings are not supported");for(let r=128;r<=151;r++)ie[r]=Rpe;ie[152]=Lpe;ie[153]=Mpe;ie[154]=Bpe;ie[155]=Ope;ie[156]=tt;ie[157]=tt;ie[158]=tt;ie[159]=Npe;for(let r=160;r<=183;r++)ie[r]=Upe;ie[184]=Fpe;ie[185]=Kpe;ie[186]=zpe;ie[187]=$pe;ie[188]=tt;ie[189]=tt;ie[190]=tt;ie[191]=Hpe;for(let r=192;r<=215;r++)ie[r]=Vpe;ie[216]=qpe;ie[217]=jpe;ie[218]=Gpe;ie[219]=Wpe;ie[220]=tt;ie[221]=tt;ie[222]=tt;ie[223]=tt;for(let r=224;r<=243;r++)ie[r]=cD("simple values are not supported");ie[244]=tt;ie[245]=tt;ie[246]=tt;ie[247]=Ype;ie[248]=cD("simple values are not supported");ie[249]=Zpe;ie[250]=Jpe;ie[251]=Qpe;ie[252]=tt;ie[253]=tt;ie[254]=tt;ie[255]=Xpe;cc=[];for(let r=0;r<24;r++)cc[r]=new de(G.uint,r,1);for(let r=-1;r>=-24;r--)cc[31-r]=new de(G.negint,r,1);cc[64]=new de(G.bytes,new Uint8Array(0),1);cc[96]=new de(G.string,"",1);cc[128]=new de(G.array,0,1);cc[160]=new de(G.map,0,1);cc[244]=new de(G.false,!1,1);cc[245]=new de(G.true,!0,1);cc[246]=new de(G.null,null,1)});function ize(){let r=[];return r[G.uint.major]=pi,r[G.negint.major]=tD,r[G.bytes.major]=Rb,r[G.string.major]=Ppe,r[G.array.major]=oD,r[G.map.major]=sD,r[G.tag.major]=iD,r[G.float.major]=aD,r}function lD(r,e={},t){let n=ope(r),o=e&&e.typeEncoders&&e.typeEncoders[n]||df[n];if(typeof o=="function"){let i=o(r,n,e,t);if(i!=null)return i}let s=df[n];if(!s)throw new Error(`${l7} unsupported type: ${n}`);return s(r,n,e,t)}function lze(r,e){e.mapSorter&&r.sort(e.mapSorter)}function uze(r,e){if(r[0]instanceof de&&e[0]instanceof de){let t=r[0],n=e[0];return t._keyBytes||(t._keyBytes=sme(t.value)),n._keyBytes||(n._keyBytes=sme(n.value)),Qk(t._keyBytes,n._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function sme(r){return dze(r,aze,ime)}function ame(r,e,t,n){if(Array.isArray(e))for(let o of e)ame(r,o,t,n);else t[e.type.major](r,e,n)}function dze(r,e,t,n){let o=n instanceof Uint8Array,s=o?new eD(n):cze,i=lD(r,t);if(!Array.isArray(i)&&t.quickEncodeToken){let a=t.quickEncodeToken(i);if(a)return o?(s.push(a),s.toBytes()):a;let c=e[i.type.major];if(c.encodedSize){let l=c.encodedSize(i,t);if(o||(s=new t1(l)),c(s,i,t),s.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${i} was wrong`);return o?s.toBytes():Jk(s.chunks[0])}}return s.reset(),ame(s,i,e,t),s.toBytes(!0)}var ime,aze,cze,uD,uf,df,fVt,hVt,pVt,mVt,gVt,yVt,bVt,wVt,xVt,vVt,EVt,cme=_(()=>{spe();Fs();upe();sa();C7();Pb();ac();d7();nD();f7();h7();p7();m7();S7();ime=Object.freeze({float64:!0,mapSorter:uze,quickEncodeToken:ome});aze=ize(),cze=new t1,uD=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(`${l7} object contains circular references`);return new r(t,e)}},uf={null:new de(G.null,null),undefined:new de(G.undefined,void 0),true:new de(G.true,!0),false:new de(G.false,!1),emptyArray:new de(G.array,0),emptyMap:new de(G.map,0)},df={number(r,e,t,n){return!Number.isInteger(r)||!Number.isSafeInteger(r)?new de(G.float,r):r>=0?new de(G.uint,r):new de(G.negint,r)},bigint(r,e,t,n){return r>=BigInt(0)?new de(G.uint,r):new de(G.negint,r)},Uint8Array(r,e,t,n){return new de(G.bytes,r)},string(r,e,t,n){return new de(G.string,r)},boolean(r,e,t,n){return r?uf.true:uf.false},null(r,e,t,n){return uf.null},undefined(r,e,t,n){return uf.undefined},ArrayBuffer(r,e,t,n){return new de(G.bytes,new Uint8Array(r))},DataView(r,e,t,n){return new de(G.bytes,new Uint8Array(r.buffer,r.byteOffset,r.byteLength))},Array(r,e,t,n){if(!r.length)return t.addBreakTokens===!0?[uf.emptyArray,new de(G.break)]:uf.emptyArray;n=uD.createCheck(n,r);let o=[],s=0;for(let i of r)o[s++]=lD(i,t,n);return t.addBreakTokens?[new de(G.array,r.length),o,new de(G.break)]:[new de(G.array,r.length),o]},Object(r,e,t,n){let o=e!=="Object",s=o?r.keys():Object.keys(r),i=o?r.size:s.length,a;if(i){a=new Array(i),n=uD.createCheck(n,r);let c=!o&&t.ignoreUndefinedProperties,l=0;for(let u of s){let d=o?r.get(u):r[u];c&&d===void 0||(a[l++]=[lD(u,t,n),lD(d,t,n)])}l<i&&(a.length=l)}return a?.length?(lze(a,t),t.addBreakTokens?[new de(G.map,a.length),a,new de(G.break)]:[new de(G.map,a.length),a]):t.addBreakTokens===!0?[uf.emptyMap,new de(G.break)]:uf.emptyMap}};df.Map=df.Object;df.Buffer=df.Uint8Array;for(let r of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))df[`${r}Array`]=df.DataView;fVt=G.uint.majorEncoded,hVt=G.negint.majorEncoded,pVt=G.bytes.majorEncoded,mVt=G.string.majorEncoded,gVt=G.array.majorEncoded,yVt=G.float.majorEncoded|g7,bVt=G.float.majorEncoded|y7,wVt=G.float.majorEncoded|b7,xVt=G.float.majorEncoded|w7,vVt=BigInt(-1),EVt=BigInt(1)});var lme=_(()=>{sa();Fs();C7();Pb()});var ume=_(()=>{cme();lme();Fs()});var dme=_(()=>{ume();_K();kb();Ul()});function mze(r,e){if(typeof r=="string")return gze(r);if(typeof r=="number")return wze(r,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function gze(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,o=parseFloat(t),s=n.toLowerCase();switch(s){case"years":case"year":case"yrs":case"yr":case"y":return o*315576e5;case"months":case"month":case"mo":return o*26298e5;case"weeks":case"week":case"w":return o*6048e5;case"days":case"day":case"d":return o*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return o*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return o*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return o*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:throw Error(`Unknown unit "${s}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function yze(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 bze(r){let e=Math.abs(r);return e>=315576e5?Cp(r,e,315576e5,"year"):e>=26298e5?Cp(r,e,26298e5,"month"):e>=6048e5?Cp(r,e,6048e5,"week"):e>=864e5?Cp(r,e,864e5,"day"):e>=36e5?Cp(r,e,36e5,"hour"):e>=6e4?Cp(r,e,6e4,"minute"):e>=1e3?Cp(r,e,1e3,"second"):`${r} ms`}function wze(r,e){if(typeof r!="number"||!Number.isFinite(r))throw Error("Value provided to ms.format() must be of type number.");return e?.long?bze(r):yze(r)}function Cp(r,e,t,n){let o=e>=t*1.5;return`${Math.round(r/t)} ${n}${o?"s":""}`}var dD,A7=_(()=>{dD=mze});function I7(r){t.debug=t,t.default=t,t.coerce=c,t.disable=s,t.enable=o,t.enabled=i,t.humanize=dD,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let h=0;h<u.length;h++)d=(d<<5)-d+u.charCodeAt(h),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let h,p=null,f,g;function y(...m){if(!y.enabled)return;let w=y,b=Number(new Date),x=b-(h||b);w.diff=x,w.prev=h,w.curr=b,h=b,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let S=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(A,v)=>{if(A==="%%")return"%";S++;let C=t.formatters[v];if(typeof C=="function"){let P=m[S];A=C.call(w,P),m.splice(S,1),S--}return A}),t.formatArgs.call(w,m),d?.onLog!=null&&d.onLog(...m),(w.log||t.log).apply(w,m)}return y.namespace=u,y.useColors=t.useColors(),y.color=t.selectColor(u),y.extend=n,y.destroy=t.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,g=t.enabled(u)),g),set:m=>{p=m}}),typeof t.init=="function"&&t.init(y),y}function n(u,d){let h=t(this.namespace+(typeof d>"u"?":":d)+u);return h.log=this.log,h}function o(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,h=(typeof u=="string"?u:"").split(/[\s,]+/),p=h.length;for(d=0;d<p;d++)h[d]&&(u=h[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function s(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function i(u){if(u[u.length-1]==="*")return!0;let d,h;for(d=0,h=t.skips.length;d<h;d++)if(t.skips[d].test(u))return!1;for(d=0,h=t.names.length;d<h;d++)if(t.names[d].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 fme=_(()=>{A7()});function vze(){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 Eze(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+dD(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,o=>{o!=="%%"&&(t++,o==="%c"&&(n=t))}),r.splice(n,0,e)}function Cze(r){try{r?fD?.setItem("debug",r):fD?.removeItem("debug")}catch{}}function Aze(){let r;try{r=fD?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Ize(){try{return localStorage}catch{}}function Tze(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var fD,xze,Sze,hme,pme=_(()=>{A7();fme();fD=Ize(),xze=["#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"];Sze=console.debug??console.log??(()=>{});hme=I7({formatArgs:Eze,save:Cze,load:Aze,useColors:vze,setupFormatters:Tze,colors:xze,storage:fD,log:Sze})});var ss,mme=_(()=>{pme();ss=hme});function gme(r,e=""){let t=yme(r.message),n=yme(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
3
3
  `).join(`
4
4
  ${e}`)}`:`${t}
@@ -43,7 +43,7 @@ ${[...t.errors.entries()].map(([s,i])=>`
43
43
  `),t),n.trace('responded with "%s" for "%s"',s,s),o.unwrap(),s;if(s==="ls"){let i=new Y(...e.map(a=>Po.single(K(`${a}
44
44
  `))),K(`
45
45
  `));n.trace('respond with "%s" for %s',e,s),await o.write(i,t),n.trace('responded with "%s" for %s',e,s);continue}n.trace('respond with "na" for "%s"',s),await o.write(K(`na
46
- `),t),n('responded with "na" for "%s"',s)}}Be();se();_s();var fV=class extends Lt{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=jH(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new Pd(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Gne]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Af("Connection is not multiplexed");if(this.muxer.status!=="open")throw new Nh(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new Nh(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new qv("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await _0(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=gYe(n.protocol,this.components.registrar,t),s=Qwe(n.protocol,"outbound",this);if(s>o){let a=new Vg(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await P0(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=mYe(t.protocol,this.components.registrar);if(Qwe(t.protocol,"inbound",this)>o)throw new TT(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new qv("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function exe(r,e){return new fV(r,e)}function mYe(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return lV}function gYe(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??uV}function Qwe(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var bR=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=mo({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=mo({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new WP(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Nn([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new YP("Connection denied");await qt(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=le(n),await qt(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(yYe(n)){if(n.remotePeer==null)throw new _d(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(p=>p.code===421)?.value,h;d!=null&&(h=le(d)),n?.onProgress?.(new Dr(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:h}):this._encryptOutbound(o,{...n,remotePeer:h}))}if(s.equals(this.components.peerId)){let d=new zg("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Dr(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=exe(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await P0(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Wp(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Wp(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await _0(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Wp(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Wp(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await _0(e,o,n),i=t.get(s);if(i==null)throw new Af(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new Af(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await P0(e,o,n),i=t.get(s);if(i==null)throw new Af(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function yYe(r){return r.skipEncryption===!0}var wR="3.1.3",xR="js-libp2p";function rxe(r,e){return`${r??xR}/${e??wR} browser/${globalThis.navigator.userAgent}`}var vR=class extends Lt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Lt,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??w_(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??xR,s=e.nodeInfo?.version??wR,i=this.components=Rwe({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??rxe(o,s)},logger:this.logger,events:t,datastore:e.datastore??new kP,connectionGater:Mwe(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",gwe(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new bR(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new yR(this.components,e.transportManager)),this.configureComponent("connectionManager",new lR(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new uR(this.components,e.connectionMonitor)),this.configureComponent("registrar",new gR(this.components)),this.configureComponent("addressManager",new FP(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new hR(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new dR(this.components,{routers:c})),this.configureComponent("randomWalk",new pR(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",h=>{this.#e(h)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[fO]!=null&&(this.log("registering service %s for content routing",l),c.push(d[fO])),d[hO]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[hO])),d[jv]!=null&&(this.log("registering service %s for peer discovery",l),d[jv].addEventListener?.("peer",h=>{this.#e(h)}))}Lwe(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Mp;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new q("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new q("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){jd(e)&&(e=le(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ye([K("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Oye(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function nxe(r={}){r.privateKey??=await Bye("Ed25519");let e=new vR({...await Nye(r),peerId:RE(r.privateKey)});return r.start!==!1&&await e.start(),e}se();var Zpr=new Uint8Array(0);function oxe(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 If(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 bYe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var wYe=bYe,xYe=wYe,sxe=xYe;var hV=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")}},pV=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 ixe(this,e)}},mV=class{decoders;constructor(e){this.decoders=e}or(e){return ixe(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 ixe(r,e){return new mV({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gV=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new hV(e,t,n),this.decoder=new pV(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function axe({name:r,prefix:e,encode:t,decode:n}){return new gV(r,e,t,n)}function R0({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=sxe(t,r);return axe({prefix:e,name:r,encode:n,decode:s=>If(o(s))})}function vYe(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function EYe(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function SYe(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Tc({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=SYe(n);return axe({prefix:e,name:r,encode(s){return EYe(s,n,t)},decode(s){return vYe(s,o,t,r)}})}var Kn=R0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),omr=R0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var D2=Tc({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),amr=Tc({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cmr=Tc({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lmr=Tc({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),umr=Tc({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dmr=Tc({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fmr=Tc({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hmr=Tc({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pmr=Tc({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ER=R0({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ymr=R0({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var CYe=uxe,cxe=128,AYe=127,IYe=~AYe,TYe=Math.pow(2,31);function uxe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=TYe;)e[t++]=r&255|cxe,r/=128;for(;r&IYe;)e[t++]=r&255|cxe,r>>>=7;return e[t]=r|0,uxe.bytes=t-n+1,e}var kYe=yV,DYe=128,lxe=127;function yV(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw yV.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&lxe)<<o:(i&lxe)*Math.pow(2,o),o+=7}while(i>=DYe);return yV.bytes=s-n,t}var _Ye=Math.pow(2,7),PYe=Math.pow(2,14),RYe=Math.pow(2,21),LYe=Math.pow(2,28),MYe=Math.pow(2,35),BYe=Math.pow(2,42),OYe=Math.pow(2,49),NYe=Math.pow(2,56),UYe=Math.pow(2,63),FYe=function(r){return r<_Ye?1:r<PYe?2:r<RYe?3:r<LYe?4:r<MYe?5:r<BYe?6:r<OYe?7:r<NYe?8:r<UYe?9:10},KYe={encode:CYe,decode:kYe,encodingLength:FYe},zYe=KYe,_2=zYe;function P2(r,e=0){return[_2.decode(r,e),_2.decode.bytes]}function L0(r,e,t=0){return _2.encode(r,e,t),e}function M0(r){return _2.encodingLength(r)}function kc(r,e){let t=e.byteLength,n=M0(r),o=n+M0(t),s=new Uint8Array(o+t);return L0(r,s,0),L0(t,s,n),s.set(e,o),new B0(r,t,e,s)}function fxe(r){let e=If(r),[t,n]=P2(e),[o,s]=P2(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new B0(t,o,i,e)}function hxe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&oxe(r.bytes,t.bytes)}}var B0=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function pxe(r,e){let{bytes:t,version:n}=r;return n===0?HYe(t,wV(r),e??Kn.encoder):VYe(t,wV(r),e??D2.encoder)}var mxe=new WeakMap;function wV(r){let e=mxe.get(r);if(e==null){let t=new Map;return mxe.set(r,t),t}return e}var Dc=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==R2)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==qYe)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=kc(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&&hxe(e.multihash,n.multihash)}toString(e){return pxe(this,e)}toJSON(){return{"/":pxe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??gxe(n,o,s.bytes))}else if(t[jYe]===!0){let{version:n,multihash:o,code:s}=t,i=fxe(o);return r.create(n,s,i)}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!==R2)throw new Error(`Version 0 CID must use dag-pb (code: ${R2}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=gxe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,R2,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,o=If(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new B0(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=P2(e.subarray(t));return t+=h,d},o=n(),s=R2;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=$Ye(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return wV(s).set(n,e),s}};function $Ye(r,e){switch(r[0]){case"Q":{let t=e??Kn;return[Kn.prefix,t.decode(`${Kn.prefix}${r}`)]}case Kn.prefix:{let t=e??Kn;return[Kn.prefix,t.decode(r)]}case D2.prefix:{let t=e??D2;return[D2.prefix,t.decode(r)]}case ER.prefix:{let t=e??ER;return[ER.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 HYe(r,e,t){let{prefix:n}=t;if(n!==Kn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function VYe(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var R2=112,qYe=18;function gxe(r,e,t){let n=M0(r),o=n+M0(e),s=new Uint8Array(o+t.byteLength);return L0(r,s,0),L0(e,s,n),s.set(t,o),s}var jYe=Symbol.for("@ipld/js-cid/CID");var yxe=0,GYe="identity",bxe=If;function WYe(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 kc(yxe,bxe(r))}var O0={code:yxe,name:GYe,encode:bxe,digest:WYe};Ne();se();ct();me();Le();ct();var YYe=parseInt("11111",2),xV=parseInt("10000000",2),XYe=parseInt("01111111",2),wxe={0:L2,1:L2,2:ZYe,3:eXe,4:tXe,5:QYe,6:JYe,16:L2,22:L2,48:L2};function fu(r,e={offset:0}){let t=r[e.offset]&YYe;if(e.offset++,wxe[t]!=null)return wxe[t](r,e);throw new Error("No decoder for tag "+t)}function M2(r,e){let t=0;if((r[e.offset]&xV)===xV){let n=r[e.offset]&XYe,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function L2(r,e){M2(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=fu(r,e);if(n===null)break;t.push(n)}return t}function ZYe(r,e){let t=M2(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function JYe(r,e){let t=M2(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function QYe(r,e){return e.offset++,null}function eXe(r,e){let t=M2(r,e),n=r[e.offset];e.offset++;let o=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 o}function tXe(r,e){let t=M2(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function rXe(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function vV(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=rXe(r.byteLength);return new Y(Uint8Array.from([e.byteLength|xV]),e)}function fs(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),vV(e),e)}function SR(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),vV(t),t)}function Tf(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),vV(t),t)}async function xxe(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var nXe=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),oXe=Uint8Array.from([6,5,43,129,4,0,34]),sXe=Uint8Array.from([6,5,43,129,4,0,35]),iXe={ext:!0,kty:"EC",crv:"P-256"},aXe={ext:!0,kty:"EC",crv:"P-384"},cXe={ext:!0,kty:"EC",crv:"P-521"},EV=32,SV=48,CV=66;function vxe(r){let e=fu(r);return Exe(e)}function Exe(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===EV*2+1)return n=z(e.subarray(t,t+EV),"base64url"),o=z(e.subarray(t+EV),"base64url"),new N0({...iXe,key_ops:["verify"],x:n,y:o});if(e.byteLength===SV*2+1)return n=z(e.subarray(t,t+SV),"base64url"),o=z(e.subarray(t+SV),"base64url"),new N0({...aXe,key_ops:["verify"],x:n,y:o});if(e.byteLength===CV*2+1)return n=z(e.subarray(t,t+CV),"base64url"),o=z(e.subarray(t+CV),"base64url"),new N0({...cXe,key_ops:["verify"],x:n,y:o});throw new q(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Sxe(r){return Tf([fs(Uint8Array.from([1])),Tf([lXe(r.crv)],160),Tf([SR(new Y(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function lXe(r){if(r==="P-256")return nXe;if(r==="P-384")return oXe;if(r==="P-521")return sXe;throw new q(`Invalid curve ${r}`)}var N0=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Sxe(this.jwk)),this._raw}toMultihash(){return O0.digest(kf(this))}toCID(){return Dc.createV1(114,this.toMultihash())}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}async verify(e,t,n){return xxe(this.jwk,t,e,n)}};Ga();Le();var B2=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},CR=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Cxe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new CR("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 vi=Cxe;var AR=32;var AV,uXe=(async()=>{try{return await vi.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function dXe(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await vi.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await vi.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 fXe(r,e,t){return Ht.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Axe(r,e,t){return AV==null&&(AV=await uXe),AV?dXe(r,e,t):fXe(r,e,t)}se();Ne();Mr();me();function IR(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var TR=class{type="Ed25519";raw;constructor(e){this.raw=IV(e,AR)}toMultihash(){return O0.digest(kf(this))}toCID(){return Dc.createV1(114,this.toMultihash())}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Axe(this.raw,t,e);return IR(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Txe(r){return r=IV(r,AR),new TR(r)}function IV(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new q(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}kn();var cn;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(cn||(cn={}));var TV;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(TV||(TV={}));(function(r){r.codec=()=>Pt(TV)})(cn||(cn={}));var hu;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),cn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=cn.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(hu||(hu={}));var kV;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),cn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=cn.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(kV||(kV={}));se();me();var N2={};W(N2,{MAX_RSA_KEY_SIZE:()=>DV,generateRSAKeyPair:()=>Rxe,jwkToJWKKeyPair:()=>Lxe,jwkToPkcs1:()=>yXe,jwkToPkix:()=>LV,jwkToRSAPrivateKey:()=>NV,pkcs1MessageToJwk:()=>PV,pkcs1MessageToRSAPrivateKey:()=>MV,pkcs1ToJwk:()=>gXe,pkcs1ToRSAPrivateKey:()=>Pxe,pkixMessageToJwk:()=>RV,pkixMessageToRSAPublicKey:()=>OV,pkixToJwk:()=>bXe,pkixToRSAPublicKey:()=>BV});se();Va();me();Le();Ne();var U0=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=N2.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Dc.createV1(114,this._multihash)}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return _xe(this.jwk,t,e,n)}},O2=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=N2.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}sign(e,t){return Dxe(this.jwk,e,t)}};var DV=8192,_V=18,pXe=1062,mXe=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function gXe(r){let e=fu(r);return PV(e)}function PV(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 yXe(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 q("JWK was missing components");return Tf([fs(Uint8Array.from([0])),fs(K(r.n,"base64url")),fs(K(r.e,"base64url")),fs(K(r.d,"base64url")),fs(K(r.p,"base64url")),fs(K(r.q,"base64url")),fs(K(r.dp,"base64url")),fs(K(r.dq,"base64url")),fs(K(r.qi,"base64url"))]).subarray()}function bXe(r){let e=fu(r,{offset:0});return RV(e)}function RV(r){let e=fu(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function LV(r){if(r.n==null||r.e==null)throw new q("JWK was missing components");return Tf([mXe,SR(Tf([fs(K(r.n,"base64url")),fs(K(r.e,"base64url"))]))]).subarray()}function Pxe(r){let e=fu(r);return MV(e)}function MV(r){let e=PV(r);return NV(e)}function BV(r,e){if(r.byteLength>=pXe)throw new zt("Key size is too large");let t=fu(r,{offset:0});return OV(t,r,e)}function OV(r,e,t){let n=RV(r);if(t==null){let o=lt(hu.encode({Type:cn.RSA,Data:e}));t=kc(_V,o)}return new U0(n,t)}function NV(r){if(Bxe(r)>DV)throw new q("Key size is too large");let e=Lxe(r),t=lt(hu.encode({Type:cn.RSA,Data:LV(e.publicKey)})),n=kc(_V,t);return new O2(e.privateKey,new U0(e.publicKey,n))}async function Rxe(r){if(r>DV)throw new q("Key size is too large");let e=await Mxe(r),t=lt(hu.encode({Type:cn.RSA,Data:LV(e.publicKey)})),n=kc(_V,t);return new O2(e.privateKey,new U0(e.publicKey,n))}function Lxe(r){if(r==null)throw new q("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Mxe(r,e){let t=await vi.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 wXe(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Dxe(r,e,t){let n=await vi.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await vi.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function _xe(r,e,t,n){let o=await vi.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await vi.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function wXe(r,e){if(r.privateKey==null||r.publicKey==null)throw new q("Private and public key are required");let t=await Promise.all([vi.get().subtle.exportKey("jwk",r.privateKey),vi.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Bxe(r){if(r.kty!=="RSA")throw new q("invalid key type");if(r.n==null)throw new q("invalid key modulus");return K(r.n,"base64url").length*8}Mo();var xXe=20;function FV({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new UV(r,e,t,n,o)}var UV=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??xXe,this.maxDigestLength=s}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?Oxe(n,this.code,t?.truncate):n.then(o=>Oxe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Oxe(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 kc(e,r)}function Nxe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Uxe=FV({name:"sha2-256",code:18,encode:Nxe("SHA-256")}),Vgr=FV({name:"sha2-512",code:19,encode:Nxe("SHA-512")});function Fxe(r,e,t,n){let o=Uxe.digest(t instanceof Uint8Array?t:t.subarray());if(IR(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ie.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new B2(String(s))});try{return n?.signal?.throwIfAborted(),Ie.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new B2(String(s))}}se();Mo();Ne();var kR=class{type="secp256k1";raw;_key;constructor(e){this._key=zxe(e),this.raw=Kxe(this._key)}toMultihash(){return O0.digest(kf(this))}toCID(){return Dc.createV1(114,this.toMultihash())}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return Fxe(this._key,t,e,n)}};function $xe(r){return new kR(r)}function Kxe(r){return Ie.Point.fromBytes(r).toBytes()}function zxe(r){try{return Ie.Point.fromBytes(r),r}catch(e){throw new zt(String(e))}}function U2(r,e){let{Type:t,Data:n}=hu.decode(r),o=n??new Uint8Array;switch(t){case cn.RSA:return BV(o,e);case cn.Ed25519:return Txe(o);case cn.secp256k1:return $xe(o);case cn.ECDSA:return vxe(o);default:throw new An}}function kf(r){return hu.encode({Type:cn[r.type],Data:r.raw})}se();Be();Xt();var F0=!!globalThis.process?.env?.DUMP_SESSION_KEYS,KV=16;function vXe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function DR(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function _R(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function ln(r,e,t=""){let n=vXe(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function zV(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 Hxe(r,e){ln(r,void 0,"output");let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function pu(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function mu(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function EXe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var SXe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Vxe(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function qxe(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}var $V=(r,e)=>{function t(n,...o){if(ln(n,void 0,"key"),!SXe)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=o[0];ln(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&ln(o[1],void 0,"AAD");let i=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");ln(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ln(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(ln(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function HV(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!CXe(e))throw new Error("invalid output, must be aligned");return e}function jxe(r,e,t){DR(t);let n=new Uint8Array(16),o=EXe(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function CXe(r){return r.byteOffset%4===0}function K0(r){return Uint8Array.from(r)}var Wxe=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),AXe=Wxe("expand 16-byte k"),IXe=Wxe("expand 32-byte k"),TXe=pu(AXe),kXe=pu(IXe);function pe(r,e){return r<<e|r>>>32-e}function VV(r){return r.byteOffset%4===0}var PR=64,DXe=16,Yxe=2**32-1,Gxe=Uint32Array.of();function _Xe(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(PR),u=pu(l),d=VV(o)&&VV(s),h=d?pu(o):Gxe,p=d?pu(s):Gxe;for(let f=0;f<c;i++){if(r(e,t,n,u,i,a),i>=Yxe)throw new Error("arx: counter overflow");let g=Math.min(PR,c-f);if(d&&g===PR){let y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let m=0,w;m<DXe;m++)w=y+m,p[w]=h[w]^u[m];f+=PR;continue}for(let y=0,m;y<g;y++)m=f+y,s[m]=o[m]^l[y];f+=g}}function qV(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Vxe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return _R(o),_R(i),DR(s),DR(t),(a,c,l,u,d=0)=>{ln(a,void 0,"key"),ln(c,void 0,"nonce"),ln(l,void 0,"data");let h=l.length;if(u===void 0&&(u=new Uint8Array(h)),ln(u,void 0,"output"),_R(d),d<0||d>=Yxe)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);let p=[],f=a.length,g,y;if(f===32)p.push(g=K0(a)),y=kXe;else if(f===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),y=TXe,p.push(g);else throw ln(a,32,"arx key"),new Error("invalid key size");VV(c)||p.push(c=K0(c));let m=pu(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(y,m,pu(c.subarray(0,16)),m),c=c.subarray(16)}let w=16-o;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let x=new Uint8Array(12);x.set(c,s?0:12-c.length),c=x,p.push(c)}let b=pu(c);return _Xe(r,y,m,b,l,u,d,i),mu(...p),u}}function zn(r,e){return r[e++]&255|(r[e++]&255)<<8}var jV=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){e=K0(ln(e,32,"key"));let t=zn(e,0),n=zn(e,2),o=zn(e,4),s=zn(e,6),i=zn(e,8),a=zn(e,10),c=zn(e,12),l=zn(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=zn(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],h=i[5],p=i[6],f=i[7],g=i[8],y=i[9],m=zn(e,t+0),w=zn(e,t+2),b=zn(e,t+4),x=zn(e,t+6),S=zn(e,t+8),T=zn(e,t+10),A=zn(e,t+12),v=zn(e,t+14),C=s[0]+(m&8191),P=s[1]+((m>>>13|w<<3)&8191),F=s[2]+((w>>>10|b<<6)&8191),R=s[3]+((b>>>7|x<<9)&8191),k=s[4]+((x>>>4|S<<12)&8191),I=s[5]+(S>>>1&8191),E=s[6]+((S>>>14|T<<2)&8191),D=s[7]+((T>>>11|A<<5)&8191),M=s[8]+((A>>>8|v<<8)&8191),B=s[9]+(v>>>5|o),L=0,O=L+C*a+P*(5*y)+F*(5*g)+R*(5*f)+k*(5*p);L=O>>>13,O&=8191,O+=I*(5*h)+E*(5*d)+D*(5*u)+M*(5*l)+B*(5*c),L+=O>>>13,O&=8191;let U=L+C*c+P*a+F*(5*y)+R*(5*g)+k*(5*f);L=U>>>13,U&=8191,U+=I*(5*p)+E*(5*h)+D*(5*d)+M*(5*u)+B*(5*l),L+=U>>>13,U&=8191;let $=L+C*l+P*c+F*a+R*(5*y)+k*(5*g);L=$>>>13,$&=8191,$+=I*(5*f)+E*(5*p)+D*(5*h)+M*(5*d)+B*(5*u),L+=$>>>13,$&=8191;let J=L+C*u+P*l+F*c+R*a+k*(5*y);L=J>>>13,J&=8191,J+=I*(5*g)+E*(5*f)+D*(5*p)+M*(5*h)+B*(5*d),L+=J>>>13,J&=8191;let X=L+C*d+P*u+F*l+R*c+k*a;L=X>>>13,X&=8191,X+=I*(5*y)+E*(5*g)+D*(5*f)+M*(5*p)+B*(5*h),L+=X>>>13,X&=8191;let N=L+C*h+P*d+F*u+R*l+k*c;L=N>>>13,N&=8191,N+=I*a+E*(5*y)+D*(5*g)+M*(5*f)+B*(5*p),L+=N>>>13,N&=8191;let H=L+C*p+P*h+F*d+R*u+k*l;L=H>>>13,H&=8191,H+=I*c+E*a+D*(5*y)+M*(5*g)+B*(5*f),L+=H>>>13,H&=8191;let Z=L+C*f+P*p+F*h+R*d+k*u;L=Z>>>13,Z&=8191,Z+=I*l+E*c+D*a+M*(5*y)+B*(5*g),L+=Z>>>13,Z&=8191;let ae=L+C*g+P*f+F*p+R*h+k*d;L=ae>>>13,ae&=8191,ae+=I*u+E*l+D*c+M*a+B*(5*y),L+=ae>>>13,ae&=8191;let Q=L+C*y+P*g+F*f+R*p+k*h;L=Q>>>13,Q&=8191,Q+=I*d+E*u+D*l+M*c+B*a,L+=Q>>>13,Q&=8191,L=(L<<2)+L|0,L=L+O|0,O=L&8191,L=L>>>13,U+=L,s[0]=O,s[1]=U,s[2]=$,s[3]=J,s[4]=X,s[5]=N,s[6]=H,s[7]=Z,s[8]=ae,s[9]=Q}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;mu(n)}update(e){zV(this),ln(e),e=K0(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){mu(this.h,this.r,this.buffer,this.pad)}digestInto(e){zV(this),Hxe(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function PXe(r){let e=(n,o)=>r(o).update(n).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var Xxe=PXe(r=>new jV(r));function Qxe(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],h=e[2],p=e[3],f=e[4],g=e[5],y=e[6],m=e[7],w=o,b=t[0],x=t[1],S=t[2],T=i,A=a,v=c,C=l,P=u,F=d,R=h,k=p,I=f,E=g,D=y,M=m,B=w,L=b,O=x,U=S;for(let J=0;J<s;J+=2)T=T+P|0,B=pe(B^T,16),I=I+B|0,P=pe(P^I,12),T=T+P|0,B=pe(B^T,8),I=I+B|0,P=pe(P^I,7),A=A+F|0,L=pe(L^A,16),E=E+L|0,F=pe(F^E,12),A=A+F|0,L=pe(L^A,8),E=E+L|0,F=pe(F^E,7),v=v+R|0,O=pe(O^v,16),D=D+O|0,R=pe(R^D,12),v=v+R|0,O=pe(O^v,8),D=D+O|0,R=pe(R^D,7),C=C+k|0,U=pe(U^C,16),M=M+U|0,k=pe(k^M,12),C=C+k|0,U=pe(U^C,8),M=M+U|0,k=pe(k^M,7),T=T+F|0,U=pe(U^T,16),D=D+U|0,F=pe(F^D,12),T=T+F|0,U=pe(U^T,8),D=D+U|0,F=pe(F^D,7),A=A+R|0,B=pe(B^A,16),M=M+B|0,R=pe(R^M,12),A=A+R|0,B=pe(B^A,8),M=M+B|0,R=pe(R^M,7),v=v+k|0,L=pe(L^v,16),I=I+L|0,k=pe(k^I,12),v=v+k|0,L=pe(L^v,8),I=I+L|0,k=pe(k^I,7),C=C+P|0,O=pe(O^C,16),E=E+O|0,P=pe(P^E,12),C=C+P|0,O=pe(O^C,8),E=E+O|0,P=pe(P^E,7);let $=0;n[$++]=i+T|0,n[$++]=a+A|0,n[$++]=c+v|0,n[$++]=l+C|0,n[$++]=u+P|0,n[$++]=d+F|0,n[$++]=h+R|0,n[$++]=p+k|0,n[$++]=f+I|0,n[$++]=g+E|0,n[$++]=y+D|0,n[$++]=m+M|0,n[$++]=w+B|0,n[$++]=b+L|0,n[$++]=x+O|0,n[$++]=S+U|0}function RXe(r,e,t,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],d=e[3],h=e[4],p=e[5],f=e[6],g=e[7],y=t[0],m=t[1],w=t[2],b=t[3];for(let S=0;S<20;S+=2)o=o+c|0,y=pe(y^o,16),h=h+y|0,c=pe(c^h,12),o=o+c|0,y=pe(y^o,8),h=h+y|0,c=pe(c^h,7),s=s+l|0,m=pe(m^s,16),p=p+m|0,l=pe(l^p,12),s=s+l|0,m=pe(m^s,8),p=p+m|0,l=pe(l^p,7),i=i+u|0,w=pe(w^i,16),f=f+w|0,u=pe(u^f,12),i=i+u|0,w=pe(w^i,8),f=f+w|0,u=pe(u^f,7),a=a+d|0,b=pe(b^a,16),g=g+b|0,d=pe(d^g,12),a=a+d|0,b=pe(b^a,8),g=g+b|0,d=pe(d^g,7),o=o+l|0,b=pe(b^o,16),f=f+b|0,l=pe(l^f,12),o=o+l|0,b=pe(b^o,8),f=f+b|0,l=pe(l^f,7),s=s+u|0,y=pe(y^s,16),g=g+y|0,u=pe(u^g,12),s=s+u|0,y=pe(y^s,8),g=g+y|0,u=pe(u^g,7),i=i+d|0,m=pe(m^i,16),h=h+m|0,d=pe(d^h,12),i=i+d|0,m=pe(m^i,8),h=h+m|0,d=pe(d^h,7),a=a+c|0,w=pe(w^a,16),p=p+w|0,c=pe(c^p,12),a=a+c|0,w=pe(w^a,8),p=p+w|0,c=pe(c^p,7);let x=0;n[x++]=o,n[x++]=s,n[x++]=i,n[x++]=a,n[x++]=y,n[x++]=m,n[x++]=w,n[x++]=b}var LXe=qV(Qxe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),MXe=qV(Qxe,{counterRight:!1,counterLength:8,extendNonceFn:RXe,allowShortKeys:!1});var BXe=new Uint8Array(16),Zxe=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(BXe.subarray(t))},OXe=new Uint8Array(32);function Jxe(r,e,t,n,o){o!==void 0&&ln(o,void 0,"AAD");let s=r(e,t,OXe),i=jxe(n.length,o?o.length:0,!0),a=Xxe.create(s);o&&Zxe(a,o),Zxe(a,n),a.update(i);let c=a.digest();return mu(s,i),c}var eve=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=HV(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=Jxe(r,e,t,c,n);return i.set(l,a),mu(l),i},decrypt(s,i){i=HV(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Jxe(r,e,t,a,n);if(!qxe(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),mu(l),i}}),GV=$V({blockSize:64,nonceLength:12,tagLength:16},eve(LXe)),Hyr=$V({blockSize:64,nonceLength:24,tagLength:16},eve(MXe));Ga();jN();Xi();function rve(r,e,t){return $h(r),t===void 0&&(t=new Uint8Array(r.outputLen)),gy(r,t,e)}var WV=Uint8Array.of(0),tve=Uint8Array.of();function nve(r,e,t,n=32){$h(r),ci(n,"length");let o=r.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=tve:Me(t,void 0,"info");let i=new Uint8Array(s*o),a=gy.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)WV[0]=u+1,c.update(u===0?tve:l).update(t).update(WV).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Wi(l,WV),i.slice(0,n)}Va();var RR={hashSHA256(r){return lt(r.subarray())},getHKDF(r,e){let t=rve(lt,e,r),o=nve(lt,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=xE.utils.randomSecretKey();return{publicKey:xE.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:xE.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return xE.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return GV(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return GV(n,e,t).decrypt(r.subarray(),o)}};var ove=RR;function sve(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}Xt();var z0=r=>{let e=ar(2);return e[0]=r>>8,e[1]=r,e};z0.bytes=2;var $0=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};$0.bytes=2;function ive(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}Le();function YV(r,e){!e.enabled||!F0||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${z(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${z(r.privateKey,"hex")}`)):e("Missing local static keys."))}function XV(r,e){!e.enabled||!F0||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${z(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${z(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ave(r,e){!e.enabled||!F0||e(r?`REMOTE_STATIC_PUBLIC_KEY ${z(r.subarray(),"hex")}`:"Missing remote static public key.")}function ZV(r,e){!e.enabled||!F0||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${z(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function JV(r,e,t){!t.enabled||!F0||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&z(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&z(e.k,"hex")}`))}ct();Xt();var H0=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};Xt();var NXe=0,UXe=4294967295,FXe="Cipherstate has reached maximum n, a new handshake must be performed",LR=class{n;bytes;view;constructor(e=NXe){this.n=e,this.bytes=Oe(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>UXe)throw new Error(FXe)}};var Yp=Oe(0),V0=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new LR(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},QV=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=K(t,"utf-8");this.h=KXe(e,n),this.ck=this.h,this.cs=new V0(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new V0(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new Y(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,Yp);return[new V0(this.crypto,e),new V0(this.crypto,t)]}},eq=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new QV(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},F2=class extends eq{writeMessageA(e){return new Y(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new Y(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new Y(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new H0(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new H0(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new H0(`handshake stage 2 validation fail: ${t.message}`)}}};function KXe(r,e){if(e.length<=32){let t=Oe(32);return t.set(e),t}else return r.hash(e)}se();ct();Mr();me();kn();Xt();var MR;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);if(t.streamMuxers!=null)for(let s of t.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new lr('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new lr('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(MR||(MR={}));var K2;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),MR.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:Oe(0),identitySig:Oe(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.identityKey=t.bytes();break}case 2:{s.identitySig=t.bytes();break}case 4:{s.extensions=MR.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(K2||(K2={}));async function rq(r,e,t){let n=await r.sign(lve(e));return K2.encode({identityKey:kf(r.publicKey),identitySig:n,extensions:t})}async function nq(r,e,t){try{let n=K2.decode(r),o=U2(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=lve(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new xT(n.message)}}function lve(r){let e=K("noise-libp2p-static-key:");return r instanceof Uint8Array?Ye([e,r],e.length+r.length):(r.prepend(e),r)}var tq=class extends f0{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new B_({lengthDecoder:$0,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new Y;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(z0(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new Y;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-KV<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-KV);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function oq(r,e,t){return new tq(r,e,t)}async function uve(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await rq(s,a.publicKey,l),d=new F2({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});YV(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(Yp),e),t.trace("Stage 0 - Initiator finished sending first message."),XV(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let h=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),ZV(d.re,t),ave(d.rs,t),t.trace("Initiator going to check remote's signature...");let p=await nq(h,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[f,g]=d.ss.split();return JV(f,g,t),{payload:p,encrypt:y=>f.encryptWithAd(Yp,y),decrypt:(y,m)=>g.decryptWithAd(Yp,y,m)}}async function dve(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await rq(s,a.publicKey,l),d=new F2({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});YV(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),ZV(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),XV(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let h=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let p=await nq(h,d.rs,c),[f,g]=d.ss.split();return JV(f,g,t),{payload:p,encrypt:y=>g.encryptWithAd(Yp,y),decrypt:(y,m)=>f.decryptWithAd(Yp,y,m)}}var BR=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??ove;this.crypto=sve(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ive(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Oe(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[In]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=wf(e,{lengthEncoder:z0,lengthDecoder:$0,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=U2(s.payload.identityKey);return{connection:oq(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:vl(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new vT("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=wf(e,{lengthEncoder:z0,lengthDecoder:$0,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=U2(s.payload.identityKey);return{connection:oq(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:vl(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await uve({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await dve({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function fve(r={}){return e=>new BR(e,r)}se();ct();se();var Qt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Qt||(Qt={}));var nt;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(nt||(nt={}));var Zbr=Object.values(nt).filter(r=>typeof r!="string"),hve=0,Kr;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(Kr||(Kr={}));var _c=12;var gu=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function pve(r){return r?.reason!==null}var Gs=class extends gu{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Kr.ProtocolError),this.name="InvalidFrameError"}},q0=class extends gu{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Kr.ProtocolError),this.name="UnRequestedPingError"}},j0=class extends gu{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Kr.ProtocolError),this.name="NotMatchingPingError"}};var OR=class extends gu{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,Kr.ProtocolError),this.name="StreamAlreadyExistsError"}},NR=class extends gu{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,Kr.ProtocolError),this.name="DecodeInvalidVersionError"}},UR=class extends gu{static name="BothClientsError";constructor(e="Both clients"){super(e,Kr.ProtocolError),this.name="BothClientsError"}},G0=class extends gu{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Kr.ProtocolError),this.name="ReceiveWindowExceededError"}};var r0r=new Set([Gs.name,q0.name,j0.name,OR.name,NR.name,UR.name,G0.name]),$2=256*1024,FR=16*1024*1024;var H2={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:$2,maxStreamWindowSize:FR,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function mve(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new q("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new q("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new q("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new q("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<$2)throw new q("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new q("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new q("MaxStreamWindowSize must be less than equal MAX_UINT32")}ct();function yve(r){return r.header.type===Qt.Data&&r.data!==null}var gve=2**24;function zXe(r){if(r[0]!==hve)throw new Gs("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*gve+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*gve+(r[9]<<16)+(r[10]<<8)+r[11]}}var KR=class{buffer;constructor(){this.buffer=new Y}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=_c;if(this.buffer.byteLength<_c)return;let t=zXe(this.buffer.subarray(0,_c));if(t.type===Qt.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(_c,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function sq(r){let e=new Uint8Array(_c);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}ct();var jo;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(jo||(jo={}));var zR=class extends R_{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??$2;super({...e,maxMessageSize:t-_c}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??FR,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=jo.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let s=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,s);e.consume(s);let c=this.sendFrame({type:Qt.Data,flag:i,streamID:this.streamId,length:s},a);if(this.sendWindowCapacity-=s,n+=s,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:Qt.WindowUpdate,flag:nt.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|nt.FIN;this.sendFrame({type:Qt.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=jo.Paused}sendResume(){this.state=jo.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-_c,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!yve(e))throw new Gs("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new G0("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&nt.ACK)===nt.ACK&&this.state===jo.SYNSent&&(this.state=jo.Established),(e&nt.FIN)===nt.FIN&&this.onRemoteCloseWrite(),(e&nt.RST)===nt.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case jo.Init:return this.state=jo.SYNSent,nt.SYN;case jo.SYNReceived:return this.state=jo.Established,nt.ACK;default:return 0}}sendWindowUpdate(){if(this.state===jo.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Qt.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function bve(r){return{type:Qt[r.type],flags:[(r.flag&nt.SYN)===nt.SYN?"SYN":void 0,(r.flag&nt.ACK)===nt.ACK?"ACK":void 0,(r.flag&nt.FIN)===nt.FIN?"FIN":void 0,(r.flag&nt.RST)===nt.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var wve="/yamux/1.0.0",$R=class{protocol=wve;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[In]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new iq(e,{...this._init})}},iq=class extends P_{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:wve,name:"yamux"}),this.client=e.direction==="outbound",mve(t),this.enableKeepAlive=t.enableKeepAlive??H2.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??H2.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??H2.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??H2.maxOutboundStreams,this.decoder=new KR,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Ebe(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new fl("Muxer closed remotely");if(this.localGoAway!==void 0)throw new fl("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Vg("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,jo.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new fl("Muxer closed remotely");if(this.localGoAway!==void 0)throw new fl("Muxer closed locally");if(this.activePing!=null)return qt(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await qt(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??Kr.NormalTermination;this.log.trace("muxer close reason=%s",Kr[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=Kr.InternalError;pve(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(s=>s.streamId===e)!=null)throw new q("Stream already exists with that id");let o=new zR({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",bve(e.header)),t===0)switch(n){case Qt.Ping:{this.handlePing(e.header);return}case Qt.GoAway:{this.handleGoAway(o);return}default:throw new Gs("Invalid frame type")}else switch(e.header.type){case Qt.Data:case Qt.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new Gs("Invalid frame type")}}handlePing(e){if(e.flag===nt.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,nt.ACK);else if(e.flag===nt.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new Gs("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new q0("ping not requested");if(this.activePing.id!==e)throw new j0("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Kr[e]??"unknown"),this.remoteGoAway=e,e===Kr.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&nt.SYN)===nt.SYN&&this.incomingStream(t);let s=this.streams.find(i=>i.streamId===t);if(s===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case Qt.WindowUpdate:{s.handleWindowUpdate(e);return}case Qt.Data:{s.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new q("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Qt.WindowUpdate,flag:nt.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Qt.WindowUpdate,flag:nt.RST,streamID:e,length:0});return}let t=this._newStream(e,jo.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Qt.Data){if(t==null)throw new Gs("Invalid frame");n=new Y(sq(e),t)}else n=sq(e);return this.log.trace("sending frame %o",bve(e)),this.send(n)}sendPing(e,t=nt.SYN){t===nt.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:Qt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Kr.NormalTermination){this.log("sending GoAway reason=%s",Kr[e]),this.localGoAway=e,this.sendFrame({type:Qt.GoAway,flag:0,streamID:0,length:e})}};function xve(r={}){return()=>new $R(r)}se();me();Le();var vve="0.1.0";var Eve="id/push",Sve="1.0.0",Cve="1.0.0";kn();var Df;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 5:{s.protocolVersion=t.string();break}case 6:{s.agentVersion=t.string();break}case 1:{s.publicKey=t.bytes();break}case 2:{if(o.limits?.listenAddrs!=null&&s.listenAddrs.length===o.limits.listenAddrs)throw new lr('Decode error - map field "listenAddrs" had too many elements');s.listenAddrs.push(t.bytes());break}case 4:{s.observedAddr=t.bytes();break}case 3:{if(o.limits?.protocols!=null&&s.protocols.length===o.limits.protocols)throw new lr('Decode error - map field "protocols" had too many elements');s.protocols.push(t.string());break}case 8:{s.signedPeerRecord=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Df||(Df={}));se();var U0r=new Uint8Array(0);function Ave(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 _f(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 $Xe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var HXe=$Xe,VXe=HXe,Ive=VXe;var aq=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")}},cq=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Tve(this,e)}},lq=class{decoders;constructor(e){this.decoders=e}or(e){return Tve(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 Tve(r,e){return new lq({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var uq=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new aq(e,t,n),this.decoder=new cq(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function kve({name:r,prefix:e,encode:t,decode:n}){return new uq(r,e,t,n)}function W0({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Ive(t,r);return kve({prefix:e,name:r,encode:n,decode:s=>_f(o(s))})}function qXe(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function jXe(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function GXe(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Pc({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=GXe(n);return kve({prefix:e,name:r,encode(s){return jXe(s,n,t)},decode(s){return qXe(s,o,t,r)}})}var $n=W0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),q0r=W0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var V2=Pc({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),W0r=Pc({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Y0r=Pc({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),X0r=Pc({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Z0r=Pc({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),J0r=Pc({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Q0r=Pc({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ewr=Pc({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),twr=Pc({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var HR=W0({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),owr=W0({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var WXe=Pve,Dve=128,YXe=127,XXe=~YXe,ZXe=Math.pow(2,31);function Pve(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ZXe;)e[t++]=r&255|Dve,r/=128;for(;r&XXe;)e[t++]=r&255|Dve,r>>>=7;return e[t]=r|0,Pve.bytes=t-n+1,e}var JXe=dq,QXe=128,_ve=127;function dq(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw dq.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&_ve)<<o:(i&_ve)*Math.pow(2,o),o+=7}while(i>=QXe);return dq.bytes=s-n,t}var eZe=Math.pow(2,7),tZe=Math.pow(2,14),rZe=Math.pow(2,21),nZe=Math.pow(2,28),oZe=Math.pow(2,35),sZe=Math.pow(2,42),iZe=Math.pow(2,49),aZe=Math.pow(2,56),cZe=Math.pow(2,63),lZe=function(r){return r<eZe?1:r<tZe?2:r<rZe?3:r<nZe?4:r<oZe?5:r<sZe?6:r<iZe?7:r<aZe?8:r<cZe?9:10},uZe={encode:WXe,decode:JXe,encodingLength:lZe},dZe=uZe,q2=dZe;function j2(r,e=0){return[q2.decode(r,e),q2.decode.bytes]}function Y0(r,e,t=0){return q2.encode(r,e,t),e}function X0(r){return q2.encodingLength(r)}function Rc(r,e){let t=e.byteLength,n=X0(r),o=n+X0(t),s=new Uint8Array(o+t);return Y0(r,s,0),Y0(t,s,n),s.set(e,o),new Z0(r,t,e,s)}function Lve(r){let e=_f(r),[t,n]=j2(e),[o,s]=j2(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Z0(t,o,i,e)}function Mve(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ave(r.bytes,t.bytes)}}var Z0=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Bve(r,e){let{bytes:t,version:n}=r;return n===0?hZe(t,hq(r),e??$n.encoder):pZe(t,hq(r),e??V2.encoder)}var Ove=new WeakMap;function hq(r){let e=Ove.get(r);if(e==null){let t=new Map;return Ove.set(r,t),t}return e}var Lc=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==G2)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==mZe)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=Rc(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&&Mve(e.multihash,n.multihash)}toString(e){return Bve(this,e)}toJSON(){return{"/":Bve(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Nve(n,o,s.bytes))}else if(t[gZe]===!0){let{version:n,multihash:o,code:s}=t,i=Lve(o);return r.create(n,s,i)}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!==G2)throw new Error(`Version 0 CID must use dag-pb (code: ${G2}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Nve(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,G2,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,o=_f(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Z0(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=j2(e.subarray(t));return t+=h,d},o=n(),s=G2;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=fZe(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hq(s).set(n,e),s}};function fZe(r,e){switch(r[0]){case"Q":{let t=e??$n;return[$n.prefix,t.decode(`${$n.prefix}${r}`)]}case $n.prefix:{let t=e??$n;return[$n.prefix,t.decode(r)]}case V2.prefix:{let t=e??V2;return[V2.prefix,t.decode(r)]}case HR.prefix:{let t=e??HR;return[HR.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 hZe(r,e,t){let{prefix:n}=t;if(n!==$n.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function pZe(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var G2=112,mZe=18;function Nve(r,e,t){let n=X0(r),o=n+X0(e),s=new Uint8Array(o+t.byteLength);return Y0(r,s,0),Y0(e,s,n),s.set(t,o),s}var gZe=Symbol.for("@ipld/js-cid/CID");var Uve=0,yZe="identity",Fve=_f;function bZe(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 Rc(Uve,Fve(r))}var J0={code:Uve,name:yZe,encode:Fve,digest:bZe};Ne();se();ct();me();Le();ct();var wZe=parseInt("11111",2),pq=parseInt("10000000",2),xZe=parseInt("01111111",2),Kve={0:W2,1:W2,2:vZe,3:CZe,4:AZe,5:SZe,6:EZe,16:W2,22:W2,48:W2};function yu(r,e={offset:0}){let t=r[e.offset]&wZe;if(e.offset++,Kve[t]!=null)return Kve[t](r,e);throw new Error("No decoder for tag "+t)}function Y2(r,e){let t=0;if((r[e.offset]&pq)===pq){let n=r[e.offset]&xZe,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function W2(r,e){Y2(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=yu(r,e);if(n===null)break;t.push(n)}return t}function vZe(r,e){let t=Y2(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function EZe(r,e){let t=Y2(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function SZe(r,e){return e.offset++,null}function CZe(r,e){let t=Y2(r,e),n=r[e.offset];e.offset++;let o=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 o}function AZe(r,e){let t=Y2(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function IZe(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function mq(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=IZe(r.byteLength);return new Y(Uint8Array.from([e.byteLength|pq]),e)}function hs(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),mq(e),e)}function VR(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),mq(t),t)}function Pf(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),mq(t),t)}async function zve(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var TZe=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),kZe=Uint8Array.from([6,5,43,129,4,0,34]),DZe=Uint8Array.from([6,5,43,129,4,0,35]),_Ze={ext:!0,kty:"EC",crv:"P-256"},PZe={ext:!0,kty:"EC",crv:"P-384"},RZe={ext:!0,kty:"EC",crv:"P-521"},gq=32,yq=48,bq=66;function $ve(r){let e=yu(r);return Hve(e)}function Hve(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===gq*2+1)return n=z(e.subarray(t,t+gq),"base64url"),o=z(e.subarray(t+gq),"base64url"),new Q0({..._Ze,key_ops:["verify"],x:n,y:o});if(e.byteLength===yq*2+1)return n=z(e.subarray(t,t+yq),"base64url"),o=z(e.subarray(t+yq),"base64url"),new Q0({...PZe,key_ops:["verify"],x:n,y:o});if(e.byteLength===bq*2+1)return n=z(e.subarray(t,t+bq),"base64url"),o=z(e.subarray(t+bq),"base64url"),new Q0({...RZe,key_ops:["verify"],x:n,y:o});throw new q(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Vve(r){return Pf([hs(Uint8Array.from([1])),Pf([LZe(r.crv)],160),Pf([VR(new Y(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function LZe(r){if(r==="P-256")return TZe;if(r==="P-384")return kZe;if(r==="P-521")return DZe;throw new q(`Invalid curve ${r}`)}var Q0=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Vve(this.jwk)),this._raw}toMultihash(){return J0.digest(Rf(this))}toCID(){return Lc.createV1(114,this.toMultihash())}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}async verify(e,t,n){return zve(this.jwk,t,e,n)}};Ga();Le();var X2=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},qR=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var qve={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new qR("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 Ei=qve;var jR=32;var wq,MZe=(async()=>{try{return await Ei.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function BZe(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ei.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ei.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 OZe(r,e,t){return Ht.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function jve(r,e,t){return wq==null&&(wq=await MZe),wq?BZe(r,e,t):OZe(r,e,t)}se();Ne();Mr();me();function GR(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var WR=class{type="Ed25519";raw;constructor(e){this.raw=xq(e,jR)}toMultihash(){return J0.digest(Rf(this))}toCID(){return Lc.createV1(114,this.toMultihash())}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=jve(this.raw,t,e);return GR(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Wve(r){return r=xq(r,jR),new WR(r)}function xq(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new q(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}kn();var un;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(un||(un={}));var vq;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(vq||(vq={}));(function(r){r.codec=()=>Pt(vq)})(un||(un={}));var bu;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),un.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=un.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(bu||(bu={}));var Eq;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),un.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=un.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Eq||(Eq={}));se();me();var J2={};W(J2,{MAX_RSA_KEY_SIZE:()=>Sq,generateRSAKeyPair:()=>Qve,jwkToJWKKeyPair:()=>eEe,jwkToPkcs1:()=>zZe,jwkToPkix:()=>Tq,jwkToRSAPrivateKey:()=>Pq,pkcs1MessageToJwk:()=>Aq,pkcs1MessageToRSAPrivateKey:()=>kq,pkcs1ToJwk:()=>KZe,pkcs1ToRSAPrivateKey:()=>Jve,pkixMessageToJwk:()=>Iq,pkixMessageToRSAPublicKey:()=>_q,pkixToJwk:()=>$Ze,pkixToRSAPublicKey:()=>Dq});se();Va();me();Le();Ne();var ew=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=J2.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Lc.createV1(114,this._multihash)}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return Zve(this.jwk,t,e,n)}},Z2=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=J2.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}sign(e,t){return Xve(this.jwk,e,t)}};var Sq=8192,Cq=18,UZe=1062,FZe=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function KZe(r){let e=yu(r);return Aq(e)}function Aq(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 zZe(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 q("JWK was missing components");return Pf([hs(Uint8Array.from([0])),hs(K(r.n,"base64url")),hs(K(r.e,"base64url")),hs(K(r.d,"base64url")),hs(K(r.p,"base64url")),hs(K(r.q,"base64url")),hs(K(r.dp,"base64url")),hs(K(r.dq,"base64url")),hs(K(r.qi,"base64url"))]).subarray()}function $Ze(r){let e=yu(r,{offset:0});return Iq(e)}function Iq(r){let e=yu(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function Tq(r){if(r.n==null||r.e==null)throw new q("JWK was missing components");return Pf([FZe,VR(Pf([hs(K(r.n,"base64url")),hs(K(r.e,"base64url"))]))]).subarray()}function Jve(r){let e=yu(r);return kq(e)}function kq(r){let e=Aq(r);return Pq(e)}function Dq(r,e){if(r.byteLength>=UZe)throw new zt("Key size is too large");let t=yu(r,{offset:0});return _q(t,r,e)}function _q(r,e,t){let n=Iq(r);if(t==null){let o=lt(bu.encode({Type:un.RSA,Data:e}));t=Rc(Cq,o)}return new ew(n,t)}function Pq(r){if(rEe(r)>Sq)throw new q("Key size is too large");let e=eEe(r),t=lt(bu.encode({Type:un.RSA,Data:Tq(e.publicKey)})),n=Rc(Cq,t);return new Z2(e.privateKey,new ew(e.publicKey,n))}async function Qve(r){if(r>Sq)throw new q("Key size is too large");let e=await tEe(r),t=lt(bu.encode({Type:un.RSA,Data:Tq(e.publicKey)})),n=Rc(Cq,t);return new Z2(e.privateKey,new ew(e.publicKey,n))}function eEe(r){if(r==null)throw new q("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function tEe(r,e){let t=await Ei.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 HZe(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Xve(r,e,t){let n=await Ei.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ei.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Zve(r,e,t,n){let o=await Ei.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ei.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function HZe(r,e){if(r.privateKey==null||r.publicKey==null)throw new q("Private and public key are required");let t=await Promise.all([Ei.get().subtle.exportKey("jwk",r.privateKey),Ei.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function rEe(r){if(r.kty!=="RSA")throw new q("invalid key type");if(r.n==null)throw new q("invalid key modulus");return K(r.n,"base64url").length*8}Mo();var VZe=20;function Lq({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Rq(r,e,t,n,o)}var Rq=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??VZe,this.maxDigestLength=s}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?nEe(n,this.code,t?.truncate):n.then(o=>nEe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function nEe(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 Rc(e,r)}function oEe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var sEe=Lq({name:"sha2-256",code:18,encode:oEe("SHA-256")}),Pxr=Lq({name:"sha2-512",code:19,encode:oEe("SHA-512")});function iEe(r,e,t,n){let o=sEe.digest(t instanceof Uint8Array?t:t.subarray());if(GR(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ie.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new X2(String(s))});try{return n?.signal?.throwIfAborted(),Ie.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new X2(String(s))}}se();Mo();Ne();var YR=class{type="secp256k1";raw;_key;constructor(e){this._key=cEe(e),this.raw=aEe(this._key)}toMultihash(){return J0.digest(Rf(this))}toCID(){return Lc.createV1(114,this.toMultihash())}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return iEe(this._key,t,e,n)}};function lEe(r){return new YR(r)}function aEe(r){return Ie.Point.fromBytes(r).toBytes()}function cEe(r){try{return Ie.Point.fromBytes(r),r}catch(e){throw new zt(String(e))}}function XR(r,e){let{Type:t,Data:n}=bu.decode(r),o=n??new Uint8Array;switch(t){case un.RSA:return Dq(o,e);case un.Ed25519:return Wve(o);case un.secp256k1:return lEe(o);case un.ECDSA:return $ve(o);default:throw new An}}function Rf(r){return bu.encode({Type:un[r.type],Data:r.raw})}se();Be();me();var ps={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function uEe(r){if(r!=null&&r.length>0)try{return Pe(r)}catch{}}async function ZR(r,e,t,n,o){if(t("received identify from %p",n.remotePeer),o==null)throw new Ds("message was null or undefined");let s={};if(o.listenAddrs.length>0&&(s.addresses=o.listenAddrs.map(c=>({isCertified:!1,multiaddr:Pe(c)}))),o.protocols.length>0&&(s.protocols=o.protocols),o.publicKey!=null){let c=XR(o.publicKey);if(!vl(c).equals(n.remotePeer))throw new Ds("public key did not match remote PeerId");s.publicKey=c}let i;if(o.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let c=o.signedPeerRecord,l=await Ho.openAndCertify(c,Vo.DOMAIN),u=Vo.createFromProtobuf(l.payload),d=Wa(l.publicKey.toCID());if(!u.peerId.equals(d))throw new Ds("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(u.peerId))throw new Ds("signing key does not match remote PeerId");let h;try{h=await r.get(u.peerId)}catch(p){if(p.name!=="NotFoundError")throw p}if(h!=null&&(s.metadata=h.metadata,h.peerRecordEnvelope!=null)){let p=Ho.createFromProtobuf(h.peerRecordEnvelope),f=Vo.createFromProtobuf(p.payload);f.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,u.seqNumber),u=f,c=h.peerRecordEnvelope)}s.peerRecordEnvelope=c,s.addresses=u.multiaddrs.map(p=>({isCertified:!0,multiaddr:p})),i={seq:u.seqNumber,addresses:u.multiaddrs}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,s),await r.patch(n.remotePeer,s),o.agentVersion!=null||o.protocolVersion!=null){let c={};o.agentVersion!=null&&(c.AgentVersion=K(o.agentVersion)),o.protocolVersion!=null&&(c.ProtocolVersion=K(o.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,c),await r.merge(n.remotePeer,{metadata:c})}let a={peerId:n.remotePeer,protocolVersion:o.protocolVersion,agentVersion:o.agentVersion,publicKey:o.publicKey,listenAddrs:o.listenAddrs.map(c=>Pe(c)),observedAddr:o.observedAddr==null?void 0:Pe(o.observedAddr),protocols:o.protocols,signedPeerRecord:i,connection:n};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var tw=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??ps.timeout,this.maxInboundStreams=t.maxInboundStreams??ps.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ps.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??ps.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ps.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??ps.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??ps.protocolPrefix}/${vve}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:K(this.host.agentVersion),ProtocolVersion:K(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};var JR=class extends tw{connectionManager;concurrency;_push;constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??ps.protocolPrefix}/${Eve}/${Cve}`,log:e.logger.forComponent("libp2p:identify-push")}),this.connectionManager=e.connectionManager,this.concurrency=t.concurrency??ps.concurrency,this._push=ou(this.sendPushMessage.bind(this),t.debounce??1e3),(t.runOnSelfUpdate??ps.runOnSelfUpdate)&&e.events.addEventListener("self:peer:update",n=>{this.push().catch(o=>{this.log.error("error pushing updates to peers - %e",o)})})}[In]=["@libp2p/identify-push"];async push(){this._push()}async sendPushMessage(){if(this.isStarted())try{let e=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),t=new Vo({peerId:this.components.peerId,multiaddrs:e}),n=await Ho.seal(t,this.components.privateKey),o=this.components.registrar.getProtocols(),s=await this.components.peerStore.get(this.components.peerId),i=z(s.metadata.get("AgentVersion")??K(this.host.agentVersion)),a=z(s.metadata.get("ProtocolVersion")??K(this.host.protocolVersion)),c=this;async function*l(){for(let u of c.connectionManager.getConnections())(await c.components.peerStore.get(u.remotePeer)).protocols.includes(c.protocol)&&(yield async()=>{let h,p=AbortSignal.timeout(c.timeout);try{h=await u.newStream(c.protocol,{signal:p,runOnLimitedConnection:c.runOnLimitedConnection}),await su(h,{maxDataLength:c.maxMessageSize}).pb(Df).write({listenAddrs:e.map(g=>g.bytes),signedPeerRecord:n.marshal(),protocols:o,agentVersion:i,protocolVersion:a},{signal:p}),await h.close({signal:p})}catch(f){h?.log.newScope("identify-push")?.error("could not push identify update to peer",f),h?.abort(f)}})}await g2(T2(l(),{concurrency:this.concurrency}))}catch(e){this.log.error("error pushing updates to peers - %e",e)}}async handleProtocol(e,t){let n=e.log.newScope("identify-push");if(this.components.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let o={signal:AbortSignal.timeout(this.timeout)},i=await su(e,{maxDataLength:this.maxMessageSize}).pb(Df).read(o);await e.close(o),await ZR(this.components.peerStore,this.components.events,n,t,i),n.trace("handled push from %p",t.remotePeer)}};se();Be();var QR=class extends tw{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??ps.protocolPrefix}/${"id"}/${Sve}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??ps.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let o=n.detail;this.identify(o).catch(()=>{})})}[In]=["@libp2p/identify"];async _identify(e,t={}){let n,o;if(t.signal==null){let s=AbortSignal.timeout(this.timeout);t={...t,signal:s}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),o=n.log.newScope("identify");let s=su(n,{maxDataLength:this.maxMessageSize}).pb(Df),i=await s.read(t);return await s.unwrap().unwrap().close(t),i}catch(s){throw o?.error("identify failed - %e",s),n?.abort(s),s}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:o,protocols:s,observedAddr:i}=n;if(o==null)throw new Ds("Public key was missing from identify message");let a=XR(o),c=Wa(a.toCID());if(!e.remotePeer.equals(c))throw new Ds("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new Ds("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("completed for peer %p and protocols %o",c,s),ZR(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=uEe(e);if(t==null||(this.log.trace("our observed address was %a",t),da(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!dbe(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}jp.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let o=AbortSignal.timeout(this.timeout);let s=await this.components.peerStore.get(this.components.peerId,{signal:o}),i=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=s.peerRecordEnvelope;if(i.length>0&&a==null){let u=new Vo({peerId:this.components.peerId,multiaddrs:i});a=(await Ho.seal(u,this.components.privateKey,{signal:o})).marshal().subarray()}let c=t.remoteAddr.bytes;Ewe.matches(t.remoteAddr)||(c=void 0);let l=su(e).pb(Df);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Rf(this.components.privateKey.publicKey),listenAddrs:i.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:s.protocols},{signal:o}),n("close write"),await l.unwrap().unwrap().close({signal:o})}};function dEe(r={}){return e=>new QR(e,r)}function fEe(r={}){return e=>new JR(e,r)}se();Xi();function e5(r){if(isNaN(r)||r<=0)throw new q("random bytes length must be a Number bigger than 0");return ts(r)}se();ct();Ne();var hEe="1.0.0",pEe="ping",mEe="ipfs";var t5=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??mEe}/${pEe}/${hEe}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[In]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let o=AbortSignal.timeout(this.timeout);o.addEventListener("abort",()=>{e.abort(new $g("Ping timed out"))});let s=Date.now();for await(let i of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(i)||(n("waiting for stream to drain"),await Bt(e,"drain",{rejectionEvents:["close"],signal:o}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-s),await e.close({signal:o})}async ping(e,t={}){let n=e5(32),o=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),s=o.log.newScope("ping");try{let i=Date.now(),a=Promise.withResolvers(),c=new Y,l=u=>{if(c.append(u.data),c.byteLength===32){o.removeEventListener("message",l);let d=Date.now()-i;Promise.all([o.closeRead(t)]).then(()=>{if(ee(n,c.subarray()))a.resolve(d);else throw new IT(`Received wrong ping ack after ${d}ms`)}).catch(h=>{o.abort(h),a.reject(h)})}};return o.addEventListener("message",l),o.send(n),await o.close(t),await qt(a.promise,t.signal)}catch(i){throw s.error("error while pinging %o - %e",e,i),o?.abort(i),i}finally{o?.close()}}};function yEe(r={}){return e=>new t5(e,r)}var rw=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var wu=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};_s();var bEe=Symbol.for("@libp2p/service-dependencies");function JZe(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function wEe(r){let e=JZe(r);if(e==null)throw new rw(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var xEe=Ri(C_(),1),QZe=["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"],eJe=QZe.map(r=>new xEe.Netmask(r));function Mq(r){for(let e of eJe)if(e.contains(r))return!0;return!1}function tJe(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function rJe(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Mq(o)}function nJe(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function oJe(r){let e=r.split(":"),t=e[e.length-1];return Mq(t)}function sJe(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 vEe(r){if(kt(r))return Mq(r);if(tJe(r))return rJe(r);if(nJe(r))return oJe(r);if(rs(r))return sJe(r)}function EEe(r){try{let e=wEe(r);switch(e.type){case"ip4":case"ip6":return vEe(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}Ne();si();Mr();me();Le();var Hn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},xu=class extends Error{static name="ValidationError";name="ValidationError"},r5=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},n5=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var GEr=new Uint8Array(0);function SEe(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 vu(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 CEe(r){return new TextEncoder().encode(r)}function AEe(r){return new TextDecoder().decode(r)}var Fq={};W(Fq,{base32:()=>Mf,base32hex:()=>mJe,base32hexpad:()=>yJe,base32hexpadupper:()=>bJe,base32hexupper:()=>gJe,base32pad:()=>hJe,base32padupper:()=>pJe,base32upper:()=>fJe,base32z:()=>wJe});function iJe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var aJe=iJe,cJe=aJe,TEe=cJe;var Bq=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")}},Oq=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 kEe(this,e)}},Nq=class{decoders;constructor(e){this.decoders=e}or(e){return kEe(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 kEe(r,e){return new Nq({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Uq=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Bq(e,t,n),this.decoder=new Oq(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function nw({name:r,prefix:e,encode:t,decode:n}){return new Uq(r,e,t,n)}function Lf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=TEe(t,r);return nw({prefix:e,name:r,encode:n,decode:s=>vu(o(s))})}function lJe(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function uJe(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function dJe(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function mr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=dJe(n);return nw({prefix:e,name:r,encode(s){return uJe(s,n,t)},decode(s){return lJe(s,o,t,r)}})}var Mf=mr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fJe=mr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hJe=mr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pJe=mr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mJe=mr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gJe=mr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yJe=mr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bJe=mr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wJe=mr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Kq={};W(Kq,{base36:()=>Q2,base36upper:()=>xJe});var Q2=Lf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xJe=Lf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var zq={};W(zq,{base58btc:()=>Mc,base58flickr:()=>vJe});var Mc=Lf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vJe=Lf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var EJe=PEe,DEe=128,SJe=127,CJe=~SJe,AJe=Math.pow(2,31);function PEe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=AJe;)e[t++]=r&255|DEe,r/=128;for(;r&CJe;)e[t++]=r&255|DEe,r>>>=7;return e[t]=r|0,PEe.bytes=t-n+1,e}var IJe=$q,TJe=128,_Ee=127;function $q(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw $q.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&_Ee)<<o:(i&_Ee)*Math.pow(2,o),o+=7}while(i>=TJe);return $q.bytes=s-n,t}var kJe=Math.pow(2,7),DJe=Math.pow(2,14),_Je=Math.pow(2,21),PJe=Math.pow(2,28),RJe=Math.pow(2,35),LJe=Math.pow(2,42),MJe=Math.pow(2,49),BJe=Math.pow(2,56),OJe=Math.pow(2,63),NJe=function(r){return r<kJe?1:r<DJe?2:r<_Je?3:r<PJe?4:r<RJe?5:r<LJe?6:r<MJe?7:r<BJe?8:r<OJe?9:10},UJe={encode:EJe,decode:IJe,encodingLength:NJe},FJe=UJe,eC=FJe;function tC(r,e=0){return[eC.decode(r,e),eC.decode.bytes]}function ow(r,e,t=0){return eC.encode(r,e,t),e}function sw(r){return eC.encodingLength(r)}function aw(r,e){let t=e.byteLength,n=sw(r),o=n+sw(t),s=new Uint8Array(o+t);return ow(r,s,0),ow(t,s,n),s.set(e,o),new iw(r,t,e,s)}function REe(r){let e=vu(r),[t,n]=tC(e),[o,s]=tC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new iw(t,o,i,e)}function LEe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&SEe(r.bytes,t.bytes)}}var iw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function MEe(r,e){let{bytes:t,version:n}=r;return n===0?zJe(t,Hq(r),e??Mc.encoder):$Je(t,Hq(r),e??Mf.encoder)}var BEe=new WeakMap;function Hq(r){let e=BEe.get(r);if(e==null){let t=new Map;return BEe.set(r,t),t}return e}var cw=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==nC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==HJe)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=aw(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&&LEe(e.multihash,n.multihash)}toString(e){return MEe(this,e)}toJSON(){return{"/":MEe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??OEe(n,o,s.bytes))}else if(t[VJe]===!0){let{version:n,multihash:o,code:s}=t,i=REe(o);return r.create(n,s,i)}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!==nC)throw new Error(`Version 0 CID must use dag-pb (code: ${nC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=OEe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,nC,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,o=vu(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new iw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=tC(e.subarray(t));return t+=h,d},o=n(),s=nC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=KJe(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Hq(s).set(n,e),s}};function KJe(r,e){switch(r[0]){case"Q":{let t=e??Mc;return[Mc.prefix,t.decode(`${Mc.prefix}${r}`)]}case Mc.prefix:{let t=e??Mc;return[Mc.prefix,t.decode(r)]}case Mf.prefix:{let t=e??Mf;return[Mf.prefix,t.decode(r)]}case Q2.prefix:{let t=e??Q2;return[Q2.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 zJe(r,e,t){let{prefix:n}=t;if(n!==Mc.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function $Je(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var nC=112,HJe=18;function OEe(r,e,t){let n=sw(r),o=n+sw(e),s=new Uint8Array(o+t.byteLength);return ow(r,s,0),ow(e,s,n),s.set(t,o),s}var VJe=Symbol.for("@ipld/js-cid/CID");var qJe=20;function qq({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Vq(r,e,t,n,o)}var Vq=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??qJe,this.maxDigestLength=s}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?NEe(n,this.code,t?.truncate):n.then(o=>NEe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function NEe(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 aw(e,r)}var Gq={};W(Gq,{base64:()=>jJe,base64pad:()=>GJe,base64url:()=>jq,base64urlpad:()=>WJe});var jJe=mr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),GJe=mr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jq=mr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),WJe=mr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wq={};W(Wq,{base10:()=>YJe});var YJe=Lf({prefix:"9",name:"base10",alphabet:"0123456789"});var Yq={};W(Yq,{base16:()=>XJe,base16upper:()=>ZJe});var XJe=mr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ZJe=mr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xq={};W(Xq,{base2:()=>JJe});var JJe=mr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zq={};W(Zq,{base256emoji:()=>nQe});var FEe=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}"),QJe=FEe.reduce((r,e,t)=>(r[t]=e,r),[]),eQe=FEe.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function tQe(r){return r.reduce((e,t)=>(e+=QJe[t],e),"")}function rQe(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=eQe[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var nQe=nw({prefix:"\u{1F680}",name:"base256emoji",encode:tQe,decode:rQe});var Jq={};W(Jq,{base8:()=>oQe});var oQe=mr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qq={};W(Qq,{identity:()=>sQe});var sQe=nw({prefix:"\0",name:"identity",encode:r=>AEe(r),decode:r=>CEe(r)});var TSr=new TextEncoder,kSr=new TextDecoder;var ej={};W(ej,{identity:()=>uQe});var KEe=0,cQe="identity",zEe=vu;function lQe(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 aw(KEe,zEe(r))}var uQe={code:KEe,name:cQe,encode:zEe,digest:lQe};var tj={};W(tj,{sha256:()=>dQe,sha512:()=>fQe});function $Ee(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var dQe=qq({name:"sha2-256",code:18,encode:$Ee("SHA-256")}),fQe=qq({name:"sha2-512",code:19,encode:$Ee("SHA-512")});var HEe={...Qq,...Xq,...Jq,...Wq,...Yq,...Fq,...Kq,...zq,...Gq,...Zq},LSr={...tj,...ej};Mr();me();Le();function nj(r){return e=>z(e,r)}function oj(r){return e=>K(e,r)}function lw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Xp(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function VEe(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=K(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 o=Xp(n);return Ye([t,o],t.length+o.length)}function qEe(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=Mf.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 o=Xp(n);return Ye([t,o],t.length+o.length)}function sj(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=lw(t);return`${n}:${o}`}var ij=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Hn("Invalid byte value in IP address");e[n]=o}),e},jEe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=kt(t[n]),i;s&&(i=ij(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Hn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},GEe=function(r){if(r.byteLength!==4)throw new Hn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},WEe=function(r){if(r.byteLength!==16)throw new Hn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Hn(`Invalid IPv6 address "${t}"`)}};function YEe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Hn(`Invalid IPv6 address "${r}"`)}}var rj=Object.values(HEe).map(r=>r.decoder),hQe=(function(){let r=rj[0].or(rj[1]);return rj.slice(2).forEach(e=>r=r.or(e)),r})();function XEe(r){return hQe.decode(r)}function ZEe(r){return e=>r.encoder.encode(e)}function pQe(r){if(parseInt(r).toString()!==r)throw new xu("Value must be an integer")}function mQe(r){if(r<0)throw new xu("Value must be a positive integer, or zero")}function gQe(r){return e=>{if(e>r)throw new xu(`Value must be smaller than or equal to ${r}`)}}function yQe(...r){return e=>{for(let t of r)t(e)}}var oC=yQe(pQe,mQe,gQe(65535));var dn=-1,aj=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 n5(`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)}))}},Su=new aj,PQe=[{code:4,name:"ip4",size:32,valueToBytes:ij,bytesToValue:GEe,validate:r=>{if(!kt(r))throw new xu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:273,name:"udp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:33,name:"dccp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:41,name:"ip6",size:128,valueToBytes:jEe,bytesToValue:WEe,stringToValue:YEe,validate:r=>{if(!rs(r))throw new xu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dn},{code:43,name:"ipcidr",size:8,bytesToValue:nj("base10"),valueToBytes:oj("base10")},{code:53,name:"dns",size:dn},{code:54,name:"dns4",size:dn},{code:55,name:"dns6",size:dn},{code:56,name:"dnsaddr",size:dn},{code:132,name:"sctp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:dn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:dn,bytesToValue:nj("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?oj("base58btc")(r):cw.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:sj,valueToBytes:VEe},{code:445,name:"onion3",size:296,bytesToValue:sj,valueToBytes:qEe},{code:446,name:"garlic64",size:dn},{code:447,name:"garlic32",size:dn},{code:448,name:"tls"},{code:449,name:"sni",size:dn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:dn,bytesToValue:ZEe(jq),valueToBytes:XEe},{code:480,name:"http"},{code:481,name:"http-path",size:dn,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:dn}];PQe.forEach(r=>{Su.addProtocol(r)});function JEe(r){let e=[],t=0;for(;t<r.length;){let n=so(r,t),o=Su.getProtocol(n),s=mt(n),i=RQe(o,r,t+s),a=0;i>0&&o.size===dn&&(a=mt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??z(d)}e.push(l),t+=c}return e}function QEe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Su.getProtocol(n.code),s=mt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===dn&&(c=mt(a)));let l=new Uint8Array(s+c+a),u=0;ul(n.code,l,u),u+=s,i!=null&&(o.size===dn&&(ul(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ye(t,e)}function eSe(r){if(r.charAt(0)!=="/")throw new Hn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Su.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Hn(`Component ${o} 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 Hn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Hn("Incomplete multiaddr");return e}function tSe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Su.getProtocol(e.code);if(t==null)throw new Hn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function RQe(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:so(e,t)}var LQe=Symbol.for("nodejs.util.inspect.custom"),Aj=Symbol.for("@multiformats/multiaddr");function MQe(r){if(r==null&&(r="/"),rSe(r))return r.getComponents();if(r instanceof Uint8Array)return JEe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),eSe(r);if(Array.isArray(r))return r;throw new Hn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Cj=class r{[Aj]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=MQe(e),t.validate!==!1&&BQe(this)}get bytes(){return this.#r==null&&(this.#r=QEe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=tSe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new r5(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return ee(this.bytes,e.bytes)}[LQe](){return`Multiaddr(${this.toString()})`}};function BQe(r){r.getComponents().forEach(e=>{let t=Su.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function rSe(r){return!!r?.[Aj]}var Ot=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Se=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),nSe=r=>({match:e=>r.match(e)===!1?e:!1}),Ge=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),bo=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}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 Nt(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var OQe=Se(421),b1r=Nt(OQe),d5=Se(54),f5=Se(55),h5=Se(56),Tj=Se(53),w1r=Nt(d5,Ge(Se(421))),x1r=Nt(f5,Ge(Se(421))),v1r=Nt(h5,Ge(Se(421))),oSe=Nt(bo(Tj,h5,d5,f5),Ge(Se(421))),sSe=ot(Se(4),Ge(Se(43))),iSe=ot(Ge(Se(42)),Se(41),Ge(Se(43))),kj=bo(sSe,iSe),hw=bo(kj,Tj,d5,f5,h5),E1r=Nt(bo(kj,ot(bo(Tj,h5,d5,f5),Ge(Se(421))))),S1r=Nt(sSe),C1r=Nt(iSe),aSe=Nt(kj),Dj=ot(hw,Se(6)),sC=ot(hw,Se(273)),A1r=Nt(ot(Dj,Ge(Se(421)))),I1r=Nt(sC),_j=ot(sC,Ot(460),Ge(Se(421))),p5=ot(sC,Ot(461),Ge(Se(421))),NQe=bo(_j,p5),T1r=Nt(_j),k1r=Nt(p5),Ij=bo(hw,Dj,sC,_j,p5),cSe=bo(ot(Ij,Ot(477),Ge(Se(421)))),D1r=Nt(cSe),lSe=bo(ot(Ij,Ot(478),Ge(Se(421))),ot(Ij,Ot(448),Ge(Se(449)),Ot(477),Ge(Se(421)))),_1r=Nt(lSe),uSe=ot(sC,Ot(280),Ge(Se(466)),Ge(Se(466)),Ge(Se(421))),P1r=Nt(uSe),dSe=ot(p5,Ot(465),Ge(Se(466)),Ge(Se(466)),Ge(Se(421))),R1r=Nt(dSe),u5=bo(cSe,lSe,ot(Dj,Ge(Se(421))),ot(NQe,Ge(Se(421))),ot(hw,Ge(Se(421))),uSe,dSe,Se(421)),L1r=Nt(u5),UQe=ot(Ge(u5),Ot(290),nSe(Ot(281)),Ge(Se(421))),iC=Nt(UQe),FQe=bo(ot(u5,Ot(290),Ot(281),Ge(Se(421))),ot(u5,Ot(281),Ge(Se(421))),ot(Ot(281),Ge(Se(421)))),M1r=Nt(FQe),KQe=ot(hw,bo(ot(Se(6,"80")),ot(Se(6),Ot(480)),Ot(480)),Ge(Se(481)),Ge(Se(421))),B1r=Nt(KQe),zQe=ot(hw,bo(ot(Se(6,"443")),ot(Se(6,"443"),Ot(480)),ot(Se(6),Ot(443)),ot(Se(6),Ot(448),Ot(480)),ot(Ot(448),Ot(480)),Ot(448),Ot(443)),Ge(Se(481)),Ge(Se(421))),O1r=Nt(zQe),$Qe=bo(ot(Se(777),Ge(Se(421)))),N1r=Nt($Qe),HQe=bo(ot(Se(400),Ge(Se(421)))),U1r=Nt(HQe);var Jp=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};Ne();Xt();var VQe=Math.pow(2,7),qQe=Math.pow(2,14),jQe=Math.pow(2,21),Pj=Math.pow(2,28),Rj=Math.pow(2,35),Lj=Math.pow(2,42),Mj=Math.pow(2,49),er=128,wo=127;function pw(r){if(r<VQe)return 1;if(r<qQe)return 2;if(r<jQe)return 3;if(r<Pj)return 4;if(r<Rj)return 5;if(r<Lj)return 6;if(r<Mj)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Bj(r,e,t=0){switch(pw(r)){case 8:e[t++]=r&255|er,r/=128;case 7:e[t++]=r&255|er,r/=128;case 6:e[t++]=r&255|er,r/=128;case 5:e[t++]=r&255|er,r/=128;case 4:e[t++]=r&255|er,r>>>=7;case 3:e[t++]=r&255|er,r>>>=7;case 2:e[t++]=r&255|er,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function GQe(r,e){let t=r[e],n=0;if(n+=t&wo,t<er||(t=r[e+1],n+=(t&wo)<<7,t<er)||(t=r[e+2],n+=(t&wo)<<14,t<er)||(t=r[e+3],n+=(t&wo)<<21,t<er)||(t=r[e+4],n+=(t&wo)*Pj,t<er)||(t=r[e+5],n+=(t&wo)*Rj,t<er)||(t=r[e+6],n+=(t&wo)*Lj,t<er)||(t=r[e+7],n+=(t&wo)*Mj,t<er))return n;throw new RangeError("Could not decode varint")}function WQe(r,e){let t=r.get(e),n=0;if(n+=t&wo,t<er||(t=r.get(e+1),n+=(t&wo)<<7,t<er)||(t=r.get(e+2),n+=(t&wo)<<14,t<er)||(t=r.get(e+3),n+=(t&wo)<<21,t<er)||(t=r.get(e+4),n+=(t&wo)*Pj,t<er)||(t=r.get(e+5),n+=(t&wo)*Rj,t<er)||(t=r.get(e+6),n+=(t&wo)*Lj,t<er)||(t=r.get(e+7),n+=(t&wo)*Mj,t<er))return n;throw new RangeError("Could not decode varint")}function Oj(r,e=0){return r instanceof Uint8Array?GQe(r,e):WQe(r,e)}Mr();me();Le();var Vn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Cu=class extends Error{static name="ValidationError";name="ValidationError"},m5=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},g5=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var H1r=new Uint8Array(0);function fSe(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 Au(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Qp(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Qp(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function hSe(r){return new TextEncoder().encode(r)}function pSe(r){return new TextDecoder().decode(r)}function XQe(r){return r?.buffer instanceof ArrayBuffer}function Qp(r){return XQe(r)?r:r.slice()}var zj={};W(zj,{base32:()=>Of,base32hex:()=>iet,base32hexpad:()=>cet,base32hexpadupper:()=>uet,base32hexupper:()=>aet,base32pad:()=>oet,base32padupper:()=>set,base32upper:()=>net,base32z:()=>det});function ZQe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var JQe=ZQe,QQe=JQe,gSe=QQe;var Nj=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")}},Uj=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 ySe(this,e)}},Fj=class{decoders;constructor(e){this.decoders=e}or(e){return ySe(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 ySe(r,e){return new Fj({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Kj=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Nj(e,t,n),this.decoder=new Uj(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function mw({name:r,prefix:e,encode:t,decode:n}){return new Kj(r,e,t,n)}function Bf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=gSe(t,r);return mw({prefix:e,name:r,encode:n,decode:s=>Au(o(s))})}function eet(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function tet(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function ret(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function gr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=ret(n);return mw({prefix:e,name:r,encode(s){return tet(s,n,t)},decode(s){return eet(s,o,t,r)}})}var Of=gr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),net=gr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),oet=gr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),set=gr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iet=gr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),aet=gr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cet=gr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),uet=gr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),det=gr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $j={};W($j,{base36:()=>aC,base36upper:()=>fet});var aC=Bf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fet=Bf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Hj={};W(Hj,{base58btc:()=>Bc,base58flickr:()=>het});var Bc=Bf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),het=Bf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pet=xSe,bSe=128,met=127,get=~met,yet=Math.pow(2,31);function xSe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yet;)e[t++]=r&255|bSe,r/=128;for(;r&get;)e[t++]=r&255|bSe,r>>>=7;return e[t]=r|0,xSe.bytes=t-n+1,e}var bet=Vj,wet=128,wSe=127;function Vj(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Vj.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&wSe)<<o:(i&wSe)*Math.pow(2,o),o+=7}while(i>=wet);return Vj.bytes=s-n,t}var xet=Math.pow(2,7),vet=Math.pow(2,14),Eet=Math.pow(2,21),Cet=Math.pow(2,28),Aet=Math.pow(2,35),Iet=Math.pow(2,42),Tet=Math.pow(2,49),ket=Math.pow(2,56),Det=Math.pow(2,63),_et=function(r){return r<xet?1:r<vet?2:r<Eet?3:r<Cet?4:r<Aet?5:r<Iet?6:r<Tet?7:r<ket?8:r<Det?9:10},Pet={encode:pet,decode:bet,encodingLength:_et},Ret=Pet,cC=Ret;function lC(r,e=0){return[cC.decode(r,e),cC.decode.bytes]}function gw(r,e,t=0){return cC.encode(r,e,t),e}function yw(r){return cC.encodingLength(r)}function ww(r,e){let t=e.byteLength,n=yw(r),o=n+yw(t),s=new Uint8Array(o+t);return gw(r,s,0),gw(t,s,n),s.set(e,o),new bw(r,t,e,s)}function vSe(r){let e=Au(r),[t,n]=lC(e),[o,s]=lC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new bw(t,o,i,e)}function ESe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&fSe(r.bytes,t.bytes)}}var bw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Qp(n),this.bytes=Qp(o)}};function SSe(r,e){let{bytes:t,version:n}=r;return n===0?Met(t,qj(r),e??Bc.encoder):Bet(t,qj(r),e??Of.encoder)}var CSe=new WeakMap;function qj(r){let e=CSe.get(r);if(e==null){let t=new Map;return CSe.set(r,t),t}return e}var xw=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Qp(o),this["/"]=this.bytes}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!==dC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Oet)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=ww(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&&ESe(e.multihash,n.multihash)}toString(e){return SSe(this,e)}toJSON(){return{"/":SSe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ASe(n,o,s.bytes))}else if(t[Net]===!0){let{version:n,multihash:o,code:s}=t,i=vSe(o);return r.create(n,s,i)}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!==dC)throw new Error(`Version 0 CID must use dag-pb (code: ${dC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ASe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,dC,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,o=Au(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new bw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=lC(e.subarray(t));return t+=h,d},o=n(),s=dC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Let(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return qj(s).set(n,e),s}};function Let(r,e){switch(r[0]){case"Q":{let t=e??Bc;return[Bc.prefix,t.decode(`${Bc.prefix}${r}`)]}case Bc.prefix:{let t=e??Bc;return[Bc.prefix,t.decode(r)]}case Of.prefix:{let t=e??Of;return[Of.prefix,t.decode(r)]}case aC.prefix:{let t=e??aC;return[aC.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 Met(r,e,t){let{prefix:n}=t;if(n!==Bc.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Bet(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var dC=112,Oet=18;function ASe(r,e,t){let n=yw(r),o=n+yw(e),s=new Uint8Array(o+t.byteLength);return gw(r,s,0),gw(e,s,n),s.set(t,o),s}var Net=Symbol.for("@ipld/js-cid/CID");var Uet=20;function Gj({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new jj(r,e,t,n,o)}var jj=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Uet,this.maxDigestLength=s}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?ISe(n,this.code,t?.truncate):n.then(o=>ISe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ISe(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 ww(e,r)}var Yj={};W(Yj,{base64:()=>Fet,base64pad:()=>Ket,base64url:()=>Wj,base64urlpad:()=>zet});var Fet=gr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ket=gr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Wj=gr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zet=gr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xj={};W(Xj,{base10:()=>$et});var $et=Bf({prefix:"9",name:"base10",alphabet:"0123456789"});var Zj={};W(Zj,{base16:()=>Het,base16upper:()=>Vet});var Het=gr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vet=gr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Jj={};W(Jj,{base2:()=>qet});var qet=gr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qj={};W(Qj,{base256emoji:()=>Xet});var kSe=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}"),jet=kSe.reduce((r,e,t)=>(r[t]=e,r),[]),Get=kSe.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Wet(r){return r.reduce((e,t)=>(e+=jet[t],e),"")}function Yet(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Get[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Xet=mw({prefix:"\u{1F680}",name:"base256emoji",encode:Wet,decode:Yet});var eG={};W(eG,{base8:()=>Zet});var Zet=gr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tG={};W(tG,{identity:()=>Jet});var Jet=mw({prefix:"\0",name:"identity",encode:r=>pSe(r),decode:r=>hSe(r)});var S2r=new TextEncoder,C2r=new TextDecoder;var rG={};W(rG,{identity:()=>ntt});var DSe=0,ttt="identity",_Se=Au;function rtt(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 ww(DSe,_Se(r))}var ntt={code:DSe,name:ttt,encode:_Se,digest:rtt};var nG={};W(nG,{sha256:()=>ott,sha512:()=>stt});function PSe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ott=Gj({name:"sha2-256",code:18,encode:PSe("SHA-256")}),stt=Gj({name:"sha2-512",code:19,encode:PSe("SHA-512")});var RSe={...tG,...Jj,...eG,...Xj,...Zj,...zj,...$j,...Hj,...Yj,...Qj},D2r={...nG,...rG};Mr();me();Le();function sG(r){return e=>z(e,r)}function iG(r){return e=>K(e,r)}function vw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function em(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function LSe(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=K(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 o=em(n);return Ye([t,o],t.length+o.length)}function MSe(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=Of.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 o=em(n);return Ye([t,o],t.length+o.length)}function aG(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=vw(t);return`${n}:${o}`}var cG=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Vn("Invalid byte value in IP address");e[n]=o}),e},BSe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=kt(t[n]),i;s&&(i=cG(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Vn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},OSe=function(r){if(r.byteLength!==4)throw new Vn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},NSe=function(r){if(r.byteLength!==16)throw new Vn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Vn(`Invalid IPv6 address "${t}"`)}};function USe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Vn(`Invalid IPv6 address "${r}"`)}}var oG=Object.values(RSe).map(r=>r.decoder),itt=(function(){let r=oG[0].or(oG[1]);return oG.slice(2).forEach(e=>r=r.or(e)),r})();function FSe(r){return itt.decode(r)}function KSe(r){return e=>r.encoder.encode(e)}function att(r){if(parseInt(r).toString()!==r)throw new Cu("Value must be an integer")}function ctt(r){if(r<0)throw new Cu("Value must be a positive integer, or zero")}function ltt(r){return e=>{if(e>r)throw new Cu(`Value must be smaller than or equal to ${r}`)}}function utt(...r){return e=>{for(let t of r)t(e)}}var fC=utt(att,ctt,ltt(65535));var fn=-1,lG=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 g5(`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)}))}},Iu=new lG,Xtt=[{code:4,name:"ip4",size:32,valueToBytes:cG,bytesToValue:OSe,validate:r=>{if(!kt(r))throw new Cu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:273,name:"udp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:33,name:"dccp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:41,name:"ip6",size:128,valueToBytes:BSe,bytesToValue:NSe,stringToValue:USe,validate:r=>{if(!rs(r))throw new Cu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:fn},{code:43,name:"ipcidr",size:8,bytesToValue:sG("base10"),valueToBytes:iG("base10")},{code:53,name:"dns",size:fn},{code:54,name:"dns4",size:fn},{code:55,name:"dns6",size:fn},{code:56,name:"dnsaddr",size:fn},{code:132,name:"sctp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:fn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:fn,bytesToValue:sG("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?iG("base58btc")(r):xw.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:aG,valueToBytes:LSe},{code:445,name:"onion3",size:296,bytesToValue:aG,valueToBytes:MSe},{code:446,name:"garlic64",size:fn},{code:447,name:"garlic32",size:fn},{code:448,name:"tls"},{code:449,name:"sni",size:fn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:fn,bytesToValue:KSe(Wj),valueToBytes:FSe},{code:480,name:"http"},{code:481,name:"http-path",size:fn,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:fn}];Xtt.forEach(r=>{Iu.addProtocol(r)});function zSe(r){let e=[],t=0;for(;t<r.length;){let n=Oj(r,t),o=Iu.getProtocol(n),s=pw(n),i=Ztt(o,r,t+s),a=0;i>0&&o.size===fn&&(a=pw(i));let c=s+a+i,l={code:n,name:o.name,bytes:_n(r.subarray(t,t+c))};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??z(d)}e.push(l),t+=c}return e}function $Se(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Iu.getProtocol(n.code),s=pw(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===fn&&(c=pw(a)));let l=new Uint8Array(s+c+a),u=0;Bj(n.code,l,u),u+=s,i!=null&&(o.size===fn&&(Bj(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ye(t,e)}function HSe(r){if(r.charAt(0)!=="/")throw new Vn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Iu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Vn(`Component ${o} 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 Vn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Vn("Incomplete multiaddr");return e}function VSe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Iu.getProtocol(e.code);if(t==null)throw new Vn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Ztt(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Oj(e,t)}var Jtt=Symbol.for("nodejs.util.inspect.custom"),dG=Symbol.for("@multiformats/multiaddr");function Qtt(r){if(r==null&&(r="/"),qSe(r))return r.getComponents();if(r instanceof Uint8Array)return zSe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),HSe(r);if(Array.isArray(r))return r;throw new Vn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var b5=class r{[dG]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Qtt(e),t.validate!==!1&&ert(this)}get bytes(){return this.#r==null&&(this.#r=$Se(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=VSe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new m5(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return ee(this.bytes,e.bytes)}[Jtt](){return`Multiaddr(${this.toString()})`}};function ert(r){r.getComponents().forEach(e=>{let t=Iu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function qSe(r){return!!r?.[dG]}function fG(r){return new b5(r)}si();ct();var trt=4194304,w5=class extends Error{static name="UnwrappedError";name="UnwrappedError"},pG=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},mG=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},gG=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function rrt(r){return typeof r?.closeRead=="function"}function nrt(r){return typeof r?.close=="function"}function hG(r){return rrt(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:nrt(r)?r.status!=="open":!1}function ort(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function srt(r,e){let t=e?.maxBufferSize??trt,n=new Y,o,s=!1;if(!ort(r))throw new rw("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new w5("Stream was unwrapped");if(hG(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Jp(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await qt(o.promise,u?.signal),hG(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(hG(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Jp(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,d){if(s===!0)throw new w5("Stream was unwrapped");r.send(u)||await Bt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function irt(r,e={}){let t=srt(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=mt(e.maxDataLength));let n=e?.lengthDecoder??so,o=e?.lengthEncoder??oi;return{async read(i){let a=-1,c=new Y;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new pG("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new gG(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new mG(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Jp(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Jp(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function yG(r,e){let t=irt(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}kn();var fa;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>Pt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=we((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new lr('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(h&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new lr('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(p&7);break}}}})),n);function o(a){return be(a,r.codec())}r.encode=o;function s(a,c){return ye(a,r.codec(),c)}r.decode=s;function i(a,c){return Ji(a,r.codec(),c)}r.stream=i})(fa||(fa={}));function bG(r,e){return iC.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:oSe.matches(r)?!0:aSe.matches(r)?!EEe(r):!1}var jSe=1024*4,GSe=100,x5={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},v5=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??x5.timeout,this.retries=t.retries??x5.retries,this.maxInboundStreams=t.maxInboundStreams??x5.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??x5.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[bEe]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(hC,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{iC.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(hC,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(hC),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([hC],{signal:o.signal,runOnLimitedConnection:!0});let s=yG(t,{maxDataLength:jSe}).pb(fa);this.log("B sending connect to %p",e.remotePeer);let i=Date.now();await s.write({type:fa.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await s.read(o);if(a.type!==fa.Type.CONNECT)throw this.log("A sent wrong message type"),new wu("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new wu("DCUtR connect message had no multiaddrs");let l=Date.now()-i;this.log("A sending sync, rtt %dms",l),await s.write({type:fa.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await vbe(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:GSe,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(s){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let s=o.multiaddr;return s.getComponents().find(i=>i.code===421)?.value==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(o=>bG(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(iC.exactMatch(s.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close({signal:o}),!0}catch(s){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,s)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=yG(e,{maxDataLength:jSe}).pb(fa);this.log("A receiving connect");let s=await o.read(n);if(s.type!==fa.Type.CONNECT)throw this.log("B sent wrong message type"),new wu("DCUtR message type was incorrect");if(s.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new wu("DCUtR connect message had no multiaddrs");let i=this.getDialableMultiaddrs(s.observedAddresses);if(i.length===0)throw this.log("B had no dialable multiaddrs in %o",s.observedAddresses.map(l=>fG(l))),new wu("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:fa.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==fa.Type.SYNC)throw new wu("DCUtR message type was incorrect");this.log("A dialing",i);let c=await this.connectionManager.openConnection(i,{signal:n.signal,priority:GSe,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=fG(n);if(!bG(o,this.transportManager))continue;t.push(o)}catch{}return t}};var hC="/libp2p/dcutr";function WSe(r={}){return e=>new v5(e,r)}var Tu=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ku=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var E5=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var wG=Symbol.for("@libp2p/peer-id");_s();var YSe=Symbol.for("@libp2p/service-capabilities"),XSe=Symbol.for("@libp2p/service-dependencies");var CG={};W(CG,{base58btc:()=>Go,base58flickr:()=>prt});var dAr=new Uint8Array(0);function ZSe(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 Du(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return tm(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return tm(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function JSe(r){return new TextEncoder().encode(r)}function QSe(r){return new TextDecoder().decode(r)}function art(r){return r?.buffer instanceof ArrayBuffer}function tm(r){return art(r)?r:r.slice()}function crt(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var lrt=crt,urt=lrt,t1e=urt;var xG=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")}},vG=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 r1e(this,e)}},EG=class{decoders;constructor(e){this.decoders=e}or(e){return r1e(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 r1e(r,e){return new EG({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var SG=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new xG(e,t,n),this.decoder=new vG(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ew({name:r,prefix:e,encode:t,decode:n}){return new SG(r,e,t,n)}function Nf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=t1e(t,r);return Ew({prefix:e,name:r,encode:n,decode:s=>Du(o(s))})}function drt(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function frt(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function hrt(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function yr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=hrt(n);return Ew({prefix:e,name:r,encode(s){return frt(s,n,t)},decode(s){return drt(s,o,t,r)}})}var Go=Nf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),prt=Nf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var AG={};W(AG,{base32:()=>Uf,base32hex:()=>brt,base32hexpad:()=>xrt,base32hexpadupper:()=>vrt,base32hexupper:()=>wrt,base32pad:()=>grt,base32padupper:()=>yrt,base32upper:()=>mrt,base32z:()=>Ert});var Uf=yr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mrt=yr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),grt=yr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yrt=yr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),brt=yr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),wrt=yr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xrt=yr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),vrt=yr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ert=yr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var IG={};W(IG,{base36:()=>pC,base36upper:()=>Srt});var pC=Nf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Srt=Nf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Crt=s1e,n1e=128,Art=127,Irt=~Art,Trt=Math.pow(2,31);function s1e(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Trt;)e[t++]=r&255|n1e,r/=128;for(;r&Irt;)e[t++]=r&255|n1e,r>>>=7;return e[t]=r|0,s1e.bytes=t-n+1,e}var krt=TG,Drt=128,o1e=127;function TG(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw TG.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&o1e)<<o:(i&o1e)*Math.pow(2,o),o+=7}while(i>=Drt);return TG.bytes=s-n,t}var _rt=Math.pow(2,7),Prt=Math.pow(2,14),Rrt=Math.pow(2,21),Lrt=Math.pow(2,28),Mrt=Math.pow(2,35),Brt=Math.pow(2,42),Ort=Math.pow(2,49),Nrt=Math.pow(2,56),Urt=Math.pow(2,63),Frt=function(r){return r<_rt?1:r<Prt?2:r<Rrt?3:r<Lrt?4:r<Mrt?5:r<Brt?6:r<Ort?7:r<Nrt?8:r<Urt?9:10},Krt={encode:Crt,decode:krt,encodingLength:Frt},zrt=Krt,mC=zrt;function gC(r,e=0){return[mC.decode(r,e),mC.decode.bytes]}function Sw(r,e,t=0){return mC.encode(r,e,t),e}function Cw(r){return mC.encodingLength(r)}function Iw(r,e){let t=e.byteLength,n=Cw(r),o=n+Cw(t),s=new Uint8Array(o+t);return Sw(r,s,0),Sw(t,s,n),s.set(e,o),new Aw(r,t,e,s)}function rm(r){let e=Du(r),[t,n]=gC(e),[o,s]=gC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Aw(t,o,i,e)}function i1e(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ZSe(r.bytes,t.bytes)}}var Aw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=tm(n),this.bytes=tm(o)}};function a1e(r,e){let{bytes:t,version:n}=r;return n===0?Hrt(t,kG(r),e??Go.encoder):Vrt(t,kG(r),e??Uf.encoder)}var c1e=new WeakMap;function kG(r){let e=c1e.get(r);if(e==null){let t=new Map;return c1e.set(r,t),t}return e}var Oc=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=tm(o),this["/"]=this.bytes}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!==yC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==qrt)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=Iw(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&&i1e(e.multihash,n.multihash)}toString(e){return a1e(this,e)}toJSON(){return{"/":a1e(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??l1e(n,o,s.bytes))}else if(t[jrt]===!0){let{version:n,multihash:o,code:s}=t,i=rm(o);return r.create(n,s,i)}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!==yC)throw new Error(`Version 0 CID must use dag-pb (code: ${yC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=l1e(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,yC,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,o=Du(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Aw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=gC(e.subarray(t));return t+=h,d},o=n(),s=yC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=$rt(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return kG(s).set(n,e),s}};function $rt(r,e){switch(r[0]){case"Q":{let t=e??Go;return[Go.prefix,t.decode(`${Go.prefix}${r}`)]}case Go.prefix:{let t=e??Go;return[Go.prefix,t.decode(r)]}case Uf.prefix:{let t=e??Uf;return[Uf.prefix,t.decode(r)]}case pC.prefix:{let t=e??pC;return[pC.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 Hrt(r,e,t){let{prefix:n}=t;if(n!==Go.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Vrt(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var yC=112,qrt=18;function l1e(r,e,t){let n=Cw(r),o=n+Cw(e),s=new Uint8Array(o+t.byteLength);return Sw(r,s,0),Sw(e,s,n),s.set(t,o),s}var jrt=Symbol.for("@ipld/js-cid/CID");var DG={};W(DG,{identity:()=>bC});var u1e=0,Grt="identity",d1e=Du;function Wrt(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 Iw(u1e,d1e(r))}var bC={code:u1e,name:Grt,encode:d1e,digest:Wrt};var LG={};W(LG,{sha256:()=>RG,sha512:()=>Xrt});var Yrt=20;function PG({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new _G(r,e,t,n,o)}var _G=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Yrt,this.maxDigestLength=s}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?f1e(n,this.code,t?.truncate):n.then(o=>f1e(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function f1e(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 Iw(e,r)}function p1e(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var RG=PG({name:"sha2-256",code:18,encode:p1e("SHA-256")}),Xrt=PG({name:"sha2-512",code:19,encode:p1e("SHA-512")});Le();Ne();me();Le();var m1e=Symbol.for("nodejs.util.inspect.custom"),Zrt=114,wC=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()})`}[wG]=!0;toString(){return this.string==null&&(this.string=Go.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Oc.createV1(Zrt,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ee(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ee(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[m1e](){return`PeerId(${this.toString()})`}},C5=class extends wC{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},A5=class extends wC{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},I5=class extends wC{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Jrt=2336,T5=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=bC.digest(K(this.url))}[m1e](){return`PeerId(${this.url})`}[wG]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Oc.createV1(Jrt,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};function k5(r){if(ent(r))return new C5({multihash:r});if(Qrt(r))try{let e=wle(r);if(e.type==="Ed25519")return new A5({multihash:r,publicKey:e});if(e.type==="secp256k1")return new I5({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new T5(new URL(t))}throw new E5("Supplied PeerID Multihash is invalid")}function Qrt(r){return r.code===bC.code}function ent(r){return r.code===RG.code}function MG(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function D5(r){let e=rm(Go.decode(`z${r}`));return k5(e)}var _5=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 MG(this.set.entries(),e=>{let t=D5(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=D5(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return MG(this.set.values(),e=>D5(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 BG(){return new _5}me();var xC={hash:r=>Number(N1(r,{size:32})),hashV:(r,e)=>tnt(xC.hash(r,e))};function tnt(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),K(e,"base16")}me();Xt();Ne();var OG=64,ha=class{fp;h;seed;constructor(e,t,n,o=2){if(o>OG)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=Oe(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ee(this.fp,e.fp):!1}};function nm(r,e){return Math.floor(Math.random()*(e-r))+r}var om=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ha))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ha))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 ha))throw new TypeError("Invalid Fingerprint");let t=nm(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ha))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var rnt=500,vC=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??xC,this.seed=e.seed??nm(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=K(e));let t=new ha(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new om(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new om(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[nm(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new om(this.bucketSize));for(let a=0;a<rnt;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new om(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=K(e));let t=new ha(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=K(e));let t=new ha(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},nnt={1:.5,2:.84,4:.95,8:.98};function ont(r=.001){return r>.002?2:r>1e-5?4:8}function g1e(r,e=.001){let t=ont(e),n=nnt[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),OG);return{filterSize:o,bucketSize:t,fingerprintSize:s}}me();var P5=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??xC,this.seed=e.seed??nm(0,Math.pow(2,10)),this.filterSeries=[new vC({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=K(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 vC({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=K(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=K(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 NG(r,e=.001,t){return new P5({...g1e(r,e),...t??{}})}function snt(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function pa(r){let e=snt(r);if(e==null)throw new ku(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function y1e(r){try{let e=pa(r);return e.type==="ip6"?S_("2000::/3",e.host):!1}catch{return!1}}var b1e=Ri(C_(),1),int=["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"],ant=int.map(r=>new b1e.Netmask(r));function UG(r){for(let e of ant)if(e.contains(r))return!0;return!1}function cnt(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function lnt(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return UG(o)}function unt(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function dnt(r){let e=r.split(":"),t=e[e.length-1];return UG(t)}function fnt(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 w1e(r){if(kt(r))return UG(r);if(cnt(r))return lnt(r);if(unt(r))return dnt(r);if(rs(r))return fnt(r)}function FG(r){try{let e=pa(r);switch(e.type){case"ip4":case"ip6":return w1e(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}_s();function EC(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var R5=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},sm=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var L5=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Lr(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Tu)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function hnt(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var M5=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=hnt(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 Tu),this.cleanup())}async join(e){let t=new L5(e);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 qt(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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 B5=class extends Lt{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=EC(this.emitEmpty.bind(this),1),this.emitIdle=EC(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;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 R5;let n=new M5(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Tu)}),this.clear()}async onEmpty(e){this.size!==0&&await Bt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Bt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Bt(this,"idle",e)}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=Zo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Tu("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};Ne();Xt();var pnt=Math.pow(2,7),mnt=Math.pow(2,14),gnt=Math.pow(2,21),KG=Math.pow(2,28),zG=Math.pow(2,35),$G=Math.pow(2,42),HG=Math.pow(2,49),tr=128,xo=127;function Tw(r){if(r<pnt)return 1;if(r<mnt)return 2;if(r<gnt)return 3;if(r<KG)return 4;if(r<zG)return 5;if(r<$G)return 6;if(r<HG)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function VG(r,e,t=0){switch(Tw(r)){case 8:e[t++]=r&255|tr,r/=128;case 7:e[t++]=r&255|tr,r/=128;case 6:e[t++]=r&255|tr,r/=128;case 5:e[t++]=r&255|tr,r/=128;case 4:e[t++]=r&255|tr,r>>>=7;case 3:e[t++]=r&255|tr,r>>>=7;case 2:e[t++]=r&255|tr,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ynt(r,e){let t=r[e],n=0;if(n+=t&xo,t<tr||(t=r[e+1],n+=(t&xo)<<7,t<tr)||(t=r[e+2],n+=(t&xo)<<14,t<tr)||(t=r[e+3],n+=(t&xo)<<21,t<tr)||(t=r[e+4],n+=(t&xo)*KG,t<tr)||(t=r[e+5],n+=(t&xo)*zG,t<tr)||(t=r[e+6],n+=(t&xo)*$G,t<tr)||(t=r[e+7],n+=(t&xo)*HG,t<tr))return n;throw new RangeError("Could not decode varint")}function bnt(r,e){let t=r.get(e),n=0;if(n+=t&xo,t<tr||(t=r.get(e+1),n+=(t&xo)<<7,t<tr)||(t=r.get(e+2),n+=(t&xo)<<14,t<tr)||(t=r.get(e+3),n+=(t&xo)<<21,t<tr)||(t=r.get(e+4),n+=(t&xo)*KG,t<tr)||(t=r.get(e+5),n+=(t&xo)*zG,t<tr)||(t=r.get(e+6),n+=(t&xo)*$G,t<tr)||(t=r.get(e+7),n+=(t&xo)*HG,t<tr))return n;throw new RangeError("Could not decode varint")}function qG(r,e=0){return r instanceof Uint8Array?ynt(r,e):bnt(r,e)}Mr();me();Le();var qn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},_u=class extends Error{static name="ValidationError";name="ValidationError"},O5=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},N5=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var GG={};W(GG,{base64:()=>xnt,base64pad:()=>vnt,base64url:()=>jG,base64urlpad:()=>Ent});var xnt=yr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),vnt=yr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jG=yr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ent=yr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var WG={};W(WG,{base10:()=>Snt});var Snt=Nf({prefix:"9",name:"base10",alphabet:"0123456789"});var YG={};W(YG,{base16:()=>Cnt,base16upper:()=>Ant});var Cnt=yr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ant=yr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var XG={};W(XG,{base2:()=>Int});var Int=yr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ZG={};W(ZG,{base256emoji:()=>Pnt});var x1e=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}"),Tnt=x1e.reduce((r,e,t)=>(r[t]=e,r),[]),knt=x1e.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Dnt(r){return r.reduce((e,t)=>(e+=Tnt[t],e),"")}function _nt(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=knt[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Pnt=Ew({prefix:"\u{1F680}",name:"base256emoji",encode:Dnt,decode:_nt});var JG={};W(JG,{base8:()=>Rnt});var Rnt=yr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var QG={};W(QG,{identity:()=>Lnt});var Lnt=Ew({prefix:"\0",name:"identity",encode:r=>QSe(r),decode:r=>JSe(r)});var mTr=new TextEncoder,gTr=new TextDecoder;var v1e={...QG,...XG,...JG,...WG,...YG,...AG,...IG,...CG,...GG,...ZG},wTr={...LG,...DG};Mr();me();Le();function tW(r){return e=>z(e,r)}function rW(r){return e=>K(e,r)}function kw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function im(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function E1e(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=K(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 o=im(n);return Ye([t,o],t.length+o.length)}function S1e(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=Uf.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 o=im(n);return Ye([t,o],t.length+o.length)}function nW(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=kw(t);return`${n}:${o}`}var oW=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new qn("Invalid byte value in IP address");e[n]=o}),e},C1e=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=kt(t[n]),i;s&&(i=oW(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new qn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},A1e=function(r){if(r.byteLength!==4)throw new qn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},I1e=function(r){if(r.byteLength!==16)throw new qn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new qn(`Invalid IPv6 address "${t}"`)}};function T1e(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new qn(`Invalid IPv6 address "${r}"`)}}var eW=Object.values(v1e).map(r=>r.decoder),Ont=(function(){let r=eW[0].or(eW[1]);return eW.slice(2).forEach(e=>r=r.or(e)),r})();function k1e(r){return Ont.decode(r)}function D1e(r){return e=>r.encoder.encode(e)}function Nnt(r){if(parseInt(r).toString()!==r)throw new _u("Value must be an integer")}function Unt(r){if(r<0)throw new _u("Value must be a positive integer, or zero")}function Fnt(r){return e=>{if(e>r)throw new _u(`Value must be smaller than or equal to ${r}`)}}function Knt(...r){return e=>{for(let t of r)t(e)}}var SC=Knt(Nnt,Unt,Fnt(65535));var hn=-1,sW=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 N5(`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)}))}},Pu=new sW,Iot=[{code:4,name:"ip4",size:32,valueToBytes:oW,bytesToValue:A1e,validate:r=>{if(!kt(r))throw new _u(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:273,name:"udp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:33,name:"dccp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:41,name:"ip6",size:128,valueToBytes:C1e,bytesToValue:I1e,stringToValue:T1e,validate:r=>{if(!rs(r))throw new _u(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:hn},{code:43,name:"ipcidr",size:8,bytesToValue:tW("base10"),valueToBytes:rW("base10")},{code:53,name:"dns",size:hn},{code:54,name:"dns4",size:hn},{code:55,name:"dns6",size:hn},{code:56,name:"dnsaddr",size:hn},{code:132,name:"sctp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:hn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:hn,bytesToValue:tW("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?rW("base58btc")(r):Oc.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:nW,valueToBytes:E1e},{code:445,name:"onion3",size:296,bytesToValue:nW,valueToBytes:S1e},{code:446,name:"garlic64",size:hn},{code:447,name:"garlic32",size:hn},{code:448,name:"tls"},{code:449,name:"sni",size:hn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:hn,bytesToValue:D1e(jG),valueToBytes:k1e},{code:480,name:"http"},{code:481,name:"http-path",size:hn,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:hn}];Iot.forEach(r=>{Pu.addProtocol(r)});function _1e(r){let e=[],t=0;for(;t<r.length;){let n=qG(r,t),o=Pu.getProtocol(n),s=Tw(n),i=Tot(o,r,t+s),a=0;i>0&&o.size===hn&&(a=Tw(i));let c=s+a+i,l={code:n,name:o.name,bytes:_n(r.subarray(t,t+c))};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??z(d)}e.push(l),t+=c}return e}function P1e(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Pu.getProtocol(n.code),s=Tw(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===hn&&(c=Tw(a)));let l=new Uint8Array(s+c+a),u=0;VG(n.code,l,u),u+=s,i!=null&&(o.size===hn&&(VG(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ye(t,e)}function R1e(r){if(r.charAt(0)!=="/")throw new qn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Pu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new qn(`Component ${o} 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 qn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new qn("Incomplete multiaddr");return e}function L1e(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Pu.getProtocol(e.code);if(t==null)throw new qn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Tot(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:qG(e,t)}var kot=Symbol.for("nodejs.util.inspect.custom"),iW=Symbol.for("@multiformats/multiaddr");function Dot(r){if(r==null&&(r="/"),M1e(r))return r.getComponents();if(r instanceof Uint8Array)return _1e(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),R1e(r);if(Array.isArray(r))return r;throw new qn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var F5=class r{[iW]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Dot(e),t.validate!==!1&&_ot(this)}get bytes(){return this.#r==null&&(this.#r=P1e(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=L1e(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new O5(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return ee(this.bytes,e.bytes)}[kot](){return`Multiaddr(${this.toString()})`}};function _ot(r){r.getComponents().forEach(e=>{let t=Pu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function M1e(r){return!!r?.[iW]}function B1e(r){return new F5(r)}si();ct();var Pot=4194304,K5=class extends Error{static name="UnwrappedError";name="UnwrappedError"},cW=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},lW=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},uW=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Rot(r){return typeof r?.closeRead=="function"}function Lot(r){return typeof r?.close=="function"}function aW(r){return Rot(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Lot(r)?r.status!=="open":!1}function Mot(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Bot(r,e){let t=e?.maxBufferSize??Pot,n=new Y,o,s=!1;if(!Mot(r))throw new ku("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new K5("Stream was unwrapped");if(aW(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new sm(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await qt(o.promise,u?.signal),aW(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(aW(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new sm(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,d){if(s===!0)throw new K5("Stream was unwrapped");r.send(u)||await Bt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function Oot(r,e={}){let t=Bot(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=mt(e.maxDataLength));let n=e?.lengthDecoder??so,o=e?.lengthEncoder??oi;return{async read(i){let a=-1,c=new Y;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new cW("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new uW(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new lW(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new sm(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new sm(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function dW(r,e){let t=Oot(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var z5=class extends B5{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function O1e(r,e,t){let n,o,s=!1;function i(){let l={signal:o.signal},u;t?.timeout!=null&&(u=Nn([o.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),s=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,!o.signal.aborted&&(n=setTimeout(i,e))})}let a=EC(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var fW=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 N1e(r){let{name:e,metrics:t}=r,n;return t!=null?n=new fW({name:e,metrics:t}):n=new Map,n}var U1e="libp2p",F1e="autonat",K1e="1.0.0";kn();var Ut;(function(r){let e;(function(h){h.DIAL="DIAL",h.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(h){h[h.DIAL=0]="DIAL",h[h.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(h){h.codec=()=>Pt(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(h){h.OK="OK",h.E_DIAL_ERROR="E_DIAL_ERROR",h.E_DIAL_REFUSED="E_DIAL_REFUSED",h.E_BAD_REQUEST="E_BAD_REQUEST",h.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(h){h[h.OK=0]="OK",h[h.E_DIAL_ERROR=100]="E_DIAL_ERROR",h[h.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",h[h.E_BAD_REQUEST=200]="E_BAD_REQUEST",h[h.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(h){h.codec=()=>Pt(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(h){let p;h.codec=()=>(p==null&&(p=we((m,w,b={})=>{if(b.lengthDelimited!==!1&&w.fork(),m.id!=null&&(w.uint32(10),w.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let x of m.addrs)w.uint32(18),w.bytes(x);b.lengthDelimited!==!1&&w.ldelim()},(m,w,b={})=>{let x={addrs:[]},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{x.id=m.bytes();break}case 2:{if(b.limits?.addrs!=null&&x.addrs.length===b.limits.addrs)throw new lr('Decode error - repeated field "addrs" had too many elements');x.addrs.push(m.bytes());break}default:{m.skipType(T&7);break}}}return x},function*(m,w,b,x={}){let S={addrs:0},T=w==null?m.len:m.pos+w;for(;m.pos<T;){let A=m.uint32();switch(A>>>3){case 1:{yield{field:`${b}.id`,value:m.bytes()};break}case 2:{if(x.limits?.addrs!=null&&S.addrs===x.limits.addrs)throw new lr('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${b}.addrs[]`,index:S.addrs,value:m.bytes()},S.addrs++;break}default:{m.skipType(A&7);break}}}})),p);function f(m){return be(m,h.codec())}h.encode=f;function g(m,w){return ye(m,h.codec(),w)}h.decode=g;function y(m,w){return Ji(m,h.codec(),w)}h.stream=y})(s=r.PeerInfo||(r.PeerInfo={}));let i;(function(h){let p;h.codec=()=>(p==null&&(p=we((m,w,b={})=>{b.lengthDelimited!==!1&&w.fork(),m.peer!=null&&(w.uint32(10),r.PeerInfo.codec().encode(m.peer,w)),b.lengthDelimited!==!1&&w.ldelim()},(m,w,b={})=>{let x={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?x.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:b.limits?.peer}):m.skipType(T&7)}return x},function*(m,w,b,x={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${b}.peer`,{limits:x.limits?.peer}):m.skipType(T&7)}})),p);function f(m){return be(m,h.codec())}h.encode=f;function g(m,w){return ye(m,h.codec(),w)}h.decode=g;function y(m,w){return Ji(m,h.codec(),w)}h.stream=y})(i=r.Dial||(r.Dial={}));let a;(function(h){let p;h.codec=()=>(p==null&&(p=we((m,w,b={})=>{b.lengthDelimited!==!1&&w.fork(),m.status!=null&&(w.uint32(8),r.ResponseStatus.codec().encode(m.status,w)),m.statusText!=null&&(w.uint32(18),w.string(m.statusText)),m.addr!=null&&(w.uint32(26),w.bytes(m.addr)),b.lengthDelimited!==!1&&w.ldelim()},(m,w,b={})=>{let x={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{x.status=r.ResponseStatus.codec().decode(m);break}case 2:{x.statusText=m.string();break}case 3:{x.addr=m.bytes();break}default:{m.skipType(T&7);break}}}return x},function*(m,w,b,x={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{yield{field:`${b}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${b}.statusText`,value:m.string()};break}case 3:{yield{field:`${b}.addr`,value:m.bytes()};break}default:{m.skipType(T&7);break}}}})),p);function f(m){return be(m,h.codec())}h.encode=f;function g(m,w){return ye(m,h.codec(),w)}h.decode=g;function y(m,w){return Ji(m,h.codec(),w)}h.stream=y})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=we((h,p,f={})=>{f.lengthDelimited!==!1&&p.fork(),h.type!=null&&(p.uint32(8),r.MessageType.codec().encode(h.type,p)),h.dial!=null&&(p.uint32(18),r.Dial.codec().encode(h.dial,p)),h.dialResponse!=null&&(p.uint32(26),r.DialResponse.codec().encode(h.dialResponse,p)),f.lengthDelimited!==!1&&p.ldelim()},(h,p,f={})=>{let g={},y=p==null?h.len:h.pos+p;for(;h.pos<y;){let m=h.uint32();switch(m>>>3){case 1:{g.type=r.MessageType.codec().decode(h);break}case 2:{g.dial=r.Dial.codec().decode(h,h.uint32(),{limits:f.limits?.dial});break}case 3:{g.dialResponse=r.DialResponse.codec().decode(h,h.uint32(),{limits:f.limits?.dialResponse});break}default:{h.skipType(m&7);break}}}return g},function*(h,p,f,g={}){let y=p==null?h.len:h.pos+p;for(;h.pos<y;){let m=h.uint32();switch(m>>>3){case 1:{yield{field:`${f}.type`,value:r.MessageType.codec().decode(h)};break}case 2:{yield*r.Dial.codec().stream(h,h.uint32(),`${f}.dial`,{limits:g.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(h,h.uint32(),`${f}.dialResponse`,{limits:g.limits?.dialResponse});break}default:{h.skipType(m&7);break}}}})),c);function l(h){return be(h,r.codec())}r.encode=l;function u(h,p){return ye(h,r.codec(),p)}r.decode=u;function d(h,p){return Ji(h,r.codec(),p)}r.stream=d})(Ut||(Ut={}));var $ot=4,Hot=8,$5=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??U1e}/${F1e}/${K1e}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=N1e({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=O1e(this.findRandomPeers.bind(this),6e4),this.addressFilter=NG(1024)}[Symbol.toStringTag]="@libp2p/autonat";[YSe]=["@libp2p/autonat"];get[XSe](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=Nn([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=dW(e,{maxDataLength:this.maxMessageSize}).pb(Ut),s=await o.read({signal:n}),i=await this.handleAutonatMessage(s,t,{signal:n});await o.write(i,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>pa(d).host),s=e.dial;if(s==null)return this.log.error("dial was missing from message"),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let i,a=s.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=rm(a.id);i=k5(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",i),!t.remotePeer.equals(i))return this.log("target peer %p did not equal sending peer %p",i,t.remotePeer),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>B1e(d)).filter(d=>{try{let h=pa(d);return FG(d)?!1:h.host!==pa(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(h.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(h=>h.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${i.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",i),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),i);let l="",u=c[0];for(let d of c){let h;u=d;try{if(h=await this.components.connectionManager.openConnection(d,n),!h.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,h.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",i,d),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.OK,addr:h.remoteAddr.decapsulateCode(421).bytes}}}catch(p){this.log.error("could not dial %p - %e",i,p),l=p.message}finally{h!=null&&await h.close()}}return{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,s)=>o.type==="observed"&&s.type!=="observed"?1:s.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||pa(o.multiaddr).type==="ip6"&&(!t||!y1e(o.multiaddr))||FG(o.multiaddr)));for(let o of n){let s=o.multiaddr.toString(),i=this.dialResults.get(s);if(i!=null){if(i.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",i.multiaddr,e);continue}if(i.queue.size>10){this.log.trace("%a already has enough peers queued",i.multiaddr);continue}}if(i==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(s),this.addressFilter.has(s))continue;this.addressFilter.add(s),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",s),i={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:BG(),queue:new z5({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(s,i)}return i}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:i})=>pa(i).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),s=this.getFirstUnverifiedMultiaddr(o,n);if(s==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){s.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s.multiaddr),this.confirmAddress(s)):this.log("skipping verifying %a because we are too close to the connection limit",s.multiaddr);return}s.queue.add(async i=>{await this.askPeerToVerify(e,o,i)},{peerId:e.remotePeer,multiaddr:s.multiaddr}).catch(i=>{s?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,s?.multiaddr,i)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let s=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let i=await e.newStream(this.protocol,{signal:s});try{let a=dW(i).pb(Ut),[,c]=await Promise.all([a.write({type:Ut.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:s}),a.read({signal:s})]);if(c.type!==Ut.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Ut.ResponseStatus.OK&&l!==Ut.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Ut.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Ut.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===$ot&&this.confirmAddress(o),o.failure===Hot&&this.unconfirmAddress(o)}finally{try{await i.close({signal:s})}catch(a){i.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=pa(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new ku(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function z1e(r={}){return e=>new $5(e,r)}se();Be();_s();var Vot="bootstrap",qot=50,jot=1e3,hW=class extends Lt{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??jot,this.list=t.list.map(n=>Pe(n)).filter(n=>MP.matches(n)?n.getComponents().findLast(s=>s.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:le(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[jv]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[In]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??Vot]:{value:this._init.tagValue??qot,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function $1e(r){return e=>new hW(e,r)}var K6r=new Uint8Array(0);function H1e(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 Dw(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 Got(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var Wot=Got,Yot=Wot,V1e=Yot;var pW=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")}},mW=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 q1e(this,e)}},gW=class{decoders;constructor(e){this.decoders=e}or(e){return q1e(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 q1e(r,e){return new gW({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var yW=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new pW(e,t,n),this.decoder=new mW(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function j1e({name:r,prefix:e,encode:t,decode:n}){return new yW(r,e,t,n)}function _w({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=V1e(t,r);return j1e({prefix:e,name:r,encode:n,decode:s=>Dw(o(s))})}function Xot(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Zot(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Jot(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Nc({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Jot(n);return j1e({prefix:e,name:r,encode(s){return Zot(s,n,t)},decode(s){return Xot(s,o,t,r)}})}var Ru=_w({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),G6r=_w({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var CC=Nc({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),X6r=Nc({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Z6r=Nc({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),J6r=Nc({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Q6r=Nc({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ekr=Nc({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tkr=Nc({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rkr=Nc({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nkr=Nc({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var H5=_w({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ikr=_w({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Qot=Y1e,G1e=128,est=127,tst=~est,rst=Math.pow(2,31);function Y1e(r,e,t){e=e||[],t=t||0;for(var n=t;r>=rst;)e[t++]=r&255|G1e,r/=128;for(;r&tst;)e[t++]=r&255|G1e,r>>>=7;return e[t]=r|0,Y1e.bytes=t-n+1,e}var nst=bW,ost=128,W1e=127;function bW(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw bW.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&W1e)<<o:(i&W1e)*Math.pow(2,o),o+=7}while(i>=ost);return bW.bytes=s-n,t}var sst=Math.pow(2,7),ist=Math.pow(2,14),ast=Math.pow(2,21),cst=Math.pow(2,28),lst=Math.pow(2,35),ust=Math.pow(2,42),dst=Math.pow(2,49),fst=Math.pow(2,56),hst=Math.pow(2,63),pst=function(r){return r<sst?1:r<ist?2:r<ast?3:r<cst?4:r<lst?5:r<ust?6:r<dst?7:r<fst?8:r<hst?9:10},mst={encode:Qot,decode:nst,encodingLength:pst},gst=mst,AC=gst;function IC(r,e=0){return[AC.decode(r,e),AC.decode.bytes]}function Pw(r,e,t=0){return AC.encode(r,e,t),e}function Rw(r){return AC.encodingLength(r)}function V5(r,e){let t=e.byteLength,n=Rw(r),o=n+Rw(t),s=new Uint8Array(o+t);return Pw(r,s,0),Pw(t,s,n),s.set(e,o),new Lw(r,t,e,s)}function q5(r){let e=Dw(r),[t,n]=IC(e),[o,s]=IC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Lw(t,o,i,e)}function Z1e(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&H1e(r.bytes,t.bytes)}}var Lw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function J1e(r,e){let{bytes:t,version:n}=r;return n===0?bst(t,xW(r),e??Ru.encoder):wst(t,xW(r),e??CC.encoder)}var Q1e=new WeakMap;function xW(r){let e=Q1e.get(r);if(e==null){let t=new Map;return Q1e.set(r,t),t}return e}var vW=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==TC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xst)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=V5(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&&Z1e(e.multihash,n.multihash)}toString(e){return J1e(this,e)}toJSON(){return{"/":J1e(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??e2e(n,o,s.bytes))}else if(t[vst]===!0){let{version:n,multihash:o,code:s}=t,i=q5(o);return r.create(n,s,i)}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!==TC)throw new Error(`Version 0 CID must use dag-pb (code: ${TC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=e2e(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,TC,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,o=Dw(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Lw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=IC(e.subarray(t));return t+=h,d},o=n(),s=TC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=yst(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xW(s).set(n,e),s}};function yst(r,e){switch(r[0]){case"Q":{let t=e??Ru;return[Ru.prefix,t.decode(`${Ru.prefix}${r}`)]}case Ru.prefix:{let t=e??Ru;return[Ru.prefix,t.decode(r)]}case CC.prefix:{let t=e??CC;return[CC.prefix,t.decode(r)]}case H5.prefix:{let t=e??H5;return[H5.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 bst(r,e,t){let{prefix:n}=t;if(n!==Ru.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function wst(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var TC=112,xst=18;function e2e(r,e,t){let n=Rw(r),o=n+Rw(e),s=new Uint8Array(o+t.byteLength);return Pw(r,s,0),Pw(e,s,n),s.set(t,o),s}var vst=Symbol.for("@ipld/js-cid/CID");kn();var Uc;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Uc||(Uc={}));var EW;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(EW||(EW={}));(function(r){r.codec=()=>Pt(EW)})(Uc||(Uc={}));var j5;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Uc.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Uc.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(j5||(j5={}));var SW;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Uc.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Uc.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(SW||(SW={}));var Sst=20;function AW({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new CW(r,e,t,n,o)}var CW=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Sst,this.maxDigestLength=s}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?t2e(n,this.code,t?.truncate):n.then(o=>t2e(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function t2e(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 V5(e,r)}function r2e(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Cst=AW({name:"sha2-256",code:18,encode:r2e("SHA-256")}),xkr=AW({name:"sha2-512",code:19,encode:r2e("SHA-512")});function n2e(r){return j5.encode({Type:Uc[r.type],Data:r.raw})}Be();_s();se();var IW=1e3,o2e=60*IW,s2e=15,i2e=120*o2e;var TW="circuit-relay-source",Ckr=`${Gv}-circuit-relay`,a2e=2*o2e,c2e=BigInt(1<<17),kW="/libp2p/circuit/relay/0.2.0/hop",l2e="/libp2p/circuit/relay/0.2.0/stop",u2e=30*IW,Akr=30*IW,d2e=300;kn();Xt();var rr;(function(r){let e;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Pt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=we((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Mw.codec().encode(o.peer,s)),o.reservation!=null&&(s.uint32(26),G5.codec().encode(o.reservation,s)),o.limit!=null&&(s.uint32(34),Bw.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(40),Dt.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Mw.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=G5.codec().decode(o,o.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=Bw.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=Dt.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>be(o,r.codec()),r.decode=(o,s)=>ye(o,r.codec(),s)})(rr||(rr={}));var kC;(function(r){let e;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Pt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=we((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Mw.codec().encode(o.peer,s)),o.limit!=null&&(s.uint32(26),Bw.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(32),Dt.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Mw.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=Bw.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=Dt.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>be(o,r.codec()),r.decode=(o,s)=>ye(o,r.codec(),s)})(kC||(kC={}));var Mw;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={id:Oe(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.id=t.bytes();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new lr('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Mw||(Mw={}));var G5;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),W5.codec().encode(t.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.expire=t.uint64();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new lr('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}case 3:{s.voucher=W5.codec().decode(t,t.uint32(),{limits:o.limits?.voucher});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(G5||(G5={}));var Bw;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.duration=t.uint32();break}case 2:{s.data=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Bw||(Bw={}));var Dt;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Dt||(Dt={}));var DW;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(DW||(DW={}));(function(r){r.codec=()=>Pt(DW)})(Dt||(Dt={}));var Ow;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={relay:Oe(0),peer:Oe(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.relay=t.bytes();break}case 2:{s.peer=t.bytes();break}case 3:{s.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Ow||(Ow={}));var W5;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.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&&(n.uint32(26),Ow.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:Oe(0),payloadType:Oe(0),signature:Oe(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=Ow.codec().decode(t,t.uint32(),{limits:o.limits?.payload});break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(W5||(W5={}));var Y5=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},X5=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}};function f2e(r,e,t){let n=e.remaining,o=s=>{let i=BigInt(s.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new Y5(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",o)}function h2e(r,e,t,n,o){function s(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){o.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);i.push(u)}let a=Nn(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new X5(`duration limit of ${n.limit?.duration} ms exceeded`),s(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(f2e(e,c,o),f2e(r,c,o)),ybe(r,e,r).catch(u=>{s(u)}).finally(()=>{a.clear()})}var Fkr=Et(rt(MP.matchers[0],vt(290))),Kkr=Et(vt(290));var _W=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"}};function p2e(r,e){let t=new _W(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,o=()=>{n.abort(t)},s=AbortSignal.timeout(r);s.addEventListener("abort",o);let i=n.signal;return i.reset=a=>{s?.removeEventListener("abort",o),s=AbortSignal.timeout(a??r),s.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{s?.removeEventListener("abort",o),s=void 0},i}var Z5=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??s2e,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??i2e,this.defaultDurationLimit=t.defaultDurationLimit??a2e,this.defaultDataLimit=t.defaultDataLimit??c2e,this.reservations=j1({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let o=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&o==null)return{status:Dt.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",e),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),o={addr:t,expiry:s,limit:i,signal:p2e(this.reservationTtl)}),this.reservations.set(e,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:Dt.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var J5=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return Ow.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var Ast={maxOutboundStopStreams:d2e},Q5=class extends Lt{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??u2e,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Ast.maxOutboundStopStreams,this.reservationStore=new Z5(e,t.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(kW,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(kW),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let o={signal:n},s=su(e);try{let i=await s.pb(rr).read(o);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:s,request:i},o)}catch(i){this.log.error("error while handling hop - %e",i),await s.pb(rr).write({type:rr.Type.STATUS,status:Dt.MALFORMED_MESSAGE},o),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},o){switch(this.log("received hop message"),t.type){case rr.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},o);break;case rr.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(rr).write({type:rr.Type.STATUS,status:Dt.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let o=e.pb(rr);if(this.log("hop reserve request from %p",t.remotePeer),Ac.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await o.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await o.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},n);return}let s=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(s.status!==Dt.OK){await o.write({type:rr.Type.STATUS,status:s.status},n);return}if(s.expire!=null){let i=s.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[TW]:{value:1,ttl:i}}},n)}await o.write({type:rr.Type.STATUS,status:Dt.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await o.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[TW]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let s of this.components.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let o=await Ho.seal(new J5({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:n2e(o.publicKey),payloadType:o.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:o.signature}}}async handleConnect({stream:e,request:t,connection:n},o){let s=e.pb(rr);if(Ac.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(Pe),i=El(q5(t.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,d),await s.write({type:rr.Type.STATUS,status:Dt.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,Dt.NO_RESERVATION),await s.write({type:rr.Type.STATUS,status:Dt.NO_RESERVATION},o);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},o);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:rr.Type.STATUS,status:Dt.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:kC.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await s.write({type:rr.Type.STATUS,status:Dt.CONNECTION_FAILED},o);return}await s.write({type:rr.Type.STATUS,status:Dt.OK,limit:a?.limit},o),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),h2e(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let o=await e.newStream(l2e,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),s=su(o),i=s.pb(kC);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await o.close(n);return}if(a.status===Dt.OK)return this.log("stop request to %p was successful",e.remotePeer),s.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};function m2e(r={}){return e=>new Q5(e,r)}Be();var e8=class{store=new Map;async get(e){return this.store.get(e)}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async list(e){let t=[];for(let n of this.store.keys())n.startsWith(e)&&t.push(n);return t}};async function g2e(r,e,t,n=1e3){if(typeof r.listBlockIds!="function")return;let o=0;for await(let s of r.listBlockIds()){if(t())break;e.add(s),++o%n===0&&await new Promise(i=>setTimeout(i,0))}}function y2e(r,e){let t=Object.entries(e).filter(n=>n[1]!==void 0).filter(([,n])=>n.effectiveClusterSize!==r).map(([n,o])=>`${n} resolved ${o.effectiveClusterSize}`);if(t.length>0)throw new Error(`Cluster size mismatch at node startup: resolveClusterPolicy() produced clusterSize=${r}, but ${t.join(", ")}. Every cluster-size consumer must be constructed from the SAME resolved value (see cluster/cluster-policy.ts), or the membership admission gate's yardstick can diverge from the cohort width peer selection actually assembles.`)}Be();Uo();Le();var PW=class{components;running=!1;log;cfg;readyPromise=null;coordinatorCache=new Map;clusterCache=new Map;lastEstimate=null;reputation;libp2pRef;rebalanceMonitor;spreadOnChurnMonitor;constructor(e,t={}){this.components=e,this.log=te("network-manager"),this.cfg={clusterSize:t.clusterSize??1,seedKeys:t.seedKeys??[],estimation:t.estimation??{samples:8,kth:5,timeoutMs:1e3,ttlMs:6e4},readiness:t.readiness??{minPeers:1,maxWaitMs:2e3},cacheTTLs:t.cacheTTLs??{coordinatorMs:30*6e4,clusterMs:5*6e4},expectedRemotes:t.expectedRemotes??!1,allowClusterDownsize:t.allowClusterDownsize??!0,clusterSizeTolerance:t.clusterSizeTolerance??.5}}get effectiveClusterSize(){return this.cfg.clusterSize}setLibp2p(e){this.libp2pRef=e}setReputation(e){this.reputation=e}initRebalanceMonitor(e,t,n,o,s){let i=this.getLibp2p(),a=this.getFret();if(!i||!a)throw new Error("Cannot init RebalanceMonitor: libp2p or FRET not available");return this.rebalanceMonitor=new zD({libp2p:i,fret:a,partitionDetector:e,fretAdapter:t,trackedBlocks:n,keyNetwork:o,clusterSize:this.cfg.clusterSize},s),this.rebalanceMonitor}getRebalanceMonitor(){return this.rebalanceMonitor}initSpreadOnChurnMonitor(e,t,n,o,s,i,a){let c=this.getLibp2p(),l=this.getFret();if(!c||!l)throw new Error("Cannot init SpreadOnChurnMonitor: libp2p or FRET not available");return this.spreadOnChurnMonitor=new HD({libp2p:c,fret:l,partitionDetector:e,repo:t,peerNetwork:n,clusterSize:o,protocolPrefix:s,trackedBlocks:i},a),this.spreadOnChurnMonitor}getSpreadOnChurnMonitor(){return this.spreadOnChurnMonitor}getLibp2p(){return this.libp2pRef??this.components.libp2p}getFret(){let e=this.getLibp2p();if(e)return e.services?.fret}get[Symbol.toStringTag](){return"@libp2p/network-manager"}async start(){this.running||(this.running=!0)}async stop(){this.rebalanceMonitor&&await this.rebalanceMonitor.stop(),this.spreadOnChurnMonitor&&await this.spreadOnChurnMonitor.stop(),this.running=!1}async ready(){return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{let t=(await Promise.allSettled((this.cfg.seedKeys??[]).map(n=>this.seedKey(n)))).filter(n=>n.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(n=>setTimeout(n,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let n=await Jt(e);t.getNeighbors(n,"both",1)}toCacheKey(e){return z(e,"base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,n=e.peerStore?.getPeers?.()??[],o=(e.getConnections?.()??[]).map(a=>a.remotePeer),s=[...n.map(a=>a.id),...o];return s.filter((a,c)=>s.findIndex(l=>l.toString()===a.toString())===c).filter(a=>a.toString()!==t.toString())}getStatus(){let e=this.getLibp2p();if(!e)return{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0};let n=(e.peerStore?.getPeers?.()??[]).filter(o=>o.id.toString()!==e.peerId.toString()).length;return n===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:n}}async awaitHealthy(e,t){let n=Date.now();for(;Date.now()-n<t;){let s=this.getLibp2p();if(s){let i=s.getConnections?.()??[],a=new Set(i.map(c=>c.remotePeer.toString()));if(a.size>=e)return this.log("awaitHealthy: satisfied with %d connections",a.size),!0}await new Promise(i=>setTimeout(i,100))}let o=this.getLibp2p();if(o){let s=o.getConnections?.()??[],i=new Set(s.map(c=>c.remotePeer.toString())),a=i.size>=e;return this.log("awaitHealthy: timeout - %d connections (needed %d)",i.size,e),a}return!1}reportBadPeer(e,t=Qe.ConnectionFailure){this.reputation?.reportPeer(e.toString(),t)}isBlacklisted(e){return this.reputation?.isBanned(e.toString())??!1}recordCoordinator(e,t){let n=this.toCacheKey(e);this.coordinatorCache.set(n,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),n=this.getLibp2p();if(!n)throw new Error("Libp2p not initialized");if(t){let a=await Jt(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let u=le(l);if(!this.isBlacklisted(u))return u}}}let o=(n.getConnections?.()??[]).map(a=>a.remotePeer),s=[n.peerId,...o,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return s.length===0?n.peerId:s.reduce((a,c)=>this.lexLess(this.xor(a.toMultihash().bytes,e),this.xor(c.toMultihash().bytes,e))?a:c,s[0])}async getCluster(e){let t=this.toCacheKey(e),n=this.clusterCache.get(t);if(n&&n.expires>Date.now())return n.ids;let o=this.getFret(),s=this.getLibp2p();if(!s)throw new Error("Libp2p not initialized");if(o){let p=await Jt(e),f=o.getDiagnostics?.()??{},g=typeof f.estimate=="number"?f.estimate:typeof f.n=="number"?f.n:void 0,y=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(g)?g:this.cfg.clusterSize)),w=o.assembleCohort(p,y).map(b=>{try{return le(b)}catch(x){return this.log("Invalid peer ID in cohort: %s, %o",b,x),null}}).filter(b=>b!==null&&!this.isBlacklisted(b));if(w.length>0)return this.clusterCache.set(t,{ids:w,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=g!=null?{estimate:g,samples:f.samples??0,updated:Date.now()}:this.lastEstimate,w}let i=await this.findNearestPeerToKey(e),a=i.toMultihash().bytes,c=(s.getConnections?.()??[]).map(p=>p.remotePeer),u=[i,s.peerId,...c,...this.getKnownPeers()].filter((p,f,g)=>!this.isBlacklisted(p)&&g.findIndex(y=>y.toString()===p.toString())===f).sort((p,f)=>this.lexLess(this.xor(p.toMultihash().bytes,a),this.xor(f.toMultihash().bytes,a))?-1:1),d=Math.min(this.cfg.clusterSize,u.length),h=u.slice(0,d);return this.clusterCache.set(t,{ids:h,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),h}async getCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n){if(n.expires>Date.now())return n.id;this.coordinatorCache.delete(t)}let o=await this.getCluster(e),s=this.getLibp2p();if(!s)throw new Error("Libp2p not initialized");let i=o.filter(a=>!this.isBlacklisted(a)).sort((a,c)=>(this.reputation?.getScore(a.toString())??0)-(this.reputation?.getScore(c.toString())??0))[0]??s.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let n=Math.max(e.length,t.length),o=new Uint8Array(n);for(let s=0;s<n;s++){let i=e[e.length-1-s]??0,a=t[t.length-1-s]??0;o[n-1-s]=i^a}return o}lexLess(e,t){let n=Math.max(e.length,t.length);for(let o=0;o<n;o++){let s=e[o]??0,i=t[o]??0;if(s<i)return!0;if(s>i)return!1}return!1}};function b2e(r={}){return e=>new PW(e,r)}Be();var Lu=te("relay-reservation"),Ist="/p2p-circuit";function x2e(r){let e=[],t=[],n=new Set;for(let o of r){let s=Tst(o);if(s===void 0){e.push(o);continue}n.has(s.peerId)||(n.add(s.peerId),t.push(s),e.push(Ist))}return{listenAddrs:e,supervisedRelays:t}}function Tst(r){let e;try{e=Pe(r).getComponents()}catch{return}let t=e.filter(i=>i.name==="p2p-circuit").length,n=e[e.length-1],o=e[e.length-2];if(t!==1||n?.name!=="p2p-circuit"||o?.name!=="p2p"||o.value===void 0)return;let s;try{s=le(o.value).toString()}catch{return}return{dialAddr:Pe(e.slice(0,-1)).toString(),peerId:s}}function v2e(r){for(let e of kst(r)){let t=e.reservationStore;if(Dst(t))return{reservationStore:t}}return null}function kst(r){let e=r.components?.transportManager;if(typeof e?.getTransports!="function")return Lu.error("no transportManager.getTransports() on this node \u2014 libp2p internals moved?"),[];try{return e.getTransports()}catch(t){return Lu.error("transportManager.getTransports() threw: %o",t),[]}}function Dst(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.addRelay=="function"&&typeof e.hasReservation=="function"}function E2e(r,e){if(e.length!==0&&v2e(r)===null)throw new Error(`listen address names a relay (${e[0].dialAddr}) but the node has no circuit-relay transport \u2014 add circuitRelayTransport() to transports`)}function S2e(r,e){if(!(r.length===0||e===void 0||e.length===0))throw new Error(`listen address names a relay (${r[0].dialAddr}) but announceAddrs replaces the advertised address set, so the circuit address through it could never be advertised \u2014 drop announceAddrs or use appendAnnounceAddrs`)}function _st(r,e){let t=r.relayFilter;if(typeof t?.remove!="function")return!1;try{return t.remove(e.toMultihash().bytes)}catch(n){return Lu("could not clear the relayFilter entry for %s: %o",e.toString(),n),!1}}var Pst=1e4,Rst=5e3,Lst=1e3,Mst=3e4,Bst=100;function Ost(r,e,t={}){return new MW(r,e,t)}function C2e(r,e,t={}){let n=e.map(o=>Ost(r,o,t));return{supervisors:n,async awaitFirstDrives(){let s=(await Promise.all(n.map(async i=>({relay:i.relay,reason:await i.firstDrive})))).filter(i=>i.reason!==null);if(s.length!==0)throw new Error(s.map(i=>`could not reserve a circuit on relay ${i.relay.dialAddr}: ${i.reason}`).join("; "))},stop(){for(let o of n)o.stop()}}}var w2e=Symbol("relay-reservation-deadline-passed"),RW=r=>Math.max(0,r-Date.now()),LW=r=>r instanceof Error?r.message:String(r);function t8(r){r.unref?.()}function Nst(r){return new Promise(e=>{t8(setTimeout(e,r))})}var MW=class{node;relay;firstDrive;relayPeerId;driveTimeoutMs;checkMs;minBackoffMs;maxBackoffMs;pollMs;backoffMs;timer=null;stopped=!1;inFlight=!1;nextTickAtMs=null;failure=null;dialAbort=null;slotTakenLogged=!1;settleFirstDrive=()=>{};firstDriveSettled=!1;constructor(e,t,n){this.node=e,this.relay=t,this.relayPeerId=le(t.peerId),this.driveTimeoutMs=Math.max(1,n.driveTimeoutMs??Pst),this.checkMs=Math.max(1,n.checkMs??Rst),this.minBackoffMs=Math.max(1,n.minBackoffMs??Lst),this.maxBackoffMs=Math.max(this.minBackoffMs,n.maxBackoffMs??Mst),this.pollMs=Math.max(1,n.pollMs??Bst),this.backoffMs=this.minBackoffMs,this.firstDrive=new Promise(o=>{this.settleFirstDrive=o}),e.addEventListener("self:peer:update",this.onSelfPeerUpdate),e.addEventListener("peer:connect",this.onPeerConnect),this.tick("start")}get held(){return this.node.getMultiaddrs().some(e=>qU(e.toString(),this.relay.peerId,Lu))}get driving(){return this.inFlight}get retryAtMs(){return this.nextTickAtMs}get lastError(){return this.failure}stop(){this.stopped||(this.stopped=!0,this.clearTimer(),this.nextTickAtMs=null,this.node.removeEventListener("self:peer:update",this.onSelfPeerUpdate),this.node.removeEventListener("peer:connect",this.onPeerConnect),this.dialAbort?.abort(),this.settleFirst("the relay reservation supervisor was stopped before its first drive settled"))}onSelfPeerUpdate=()=>{this.wake("self:peer:update",!1)};onPeerConnect=e=>{e.detail.equals(this.relayPeerId)&&this.wake("peer:connect",!0)};wake(e,t){this.stopped||(t&&(this.backoffMs=this.minBackoffMs),!this.inFlight&&(this.clearTimer(),this.tick(e)))}async tick(e){if(!(this.stopped||this.inFlight)){if(this.nextTickAtMs=null,this.held){this.onHeld();return}if(await this.driveOnce(e),!this.stopped){if(this.held){this.onHeld();return}this.scheduleBackoff()}}}onHeld(){this.backoffMs=this.minBackoffMs,this.failure=null,this.slotTakenLogged=!1,this.settleFirst(null),this.schedule(this.checkMs)}async driveOnce(e){this.inFlight=!0,Lu("relay-reservation:drive relay=%s trigger=%s",this.relay.dialAddr,e);try{let t=await this.drive();if(this.stopped)return;this.failure=t,t===null?Lu("relay-reservation:held relay=%s",this.relay.dialAddr):Lu.error("relay-reservation:failed relay=%s reason=%s",this.relay.dialAddr,t)}catch(t){let n=LW(t);Lu.error("relay-reservation:drive-threw relay=%s err=%s",this.relay.dialAddr,n),this.stopped||(this.failure=n)}finally{this.inFlight=!1,this.stopped||this.settleFirst(this.failure)}}async drive(){let e=v2e(this.node);if(e===null)return"the node has no circuit-relay transport \u2014 add circuitRelayTransport() to transports";let t=Date.now()+this.driveTimeoutMs;_st(e.reservationStore,this.relayPeerId);let n=await this.dialRelay(t);if(n!==null)return n;if(this.stopped)return"stopped";let o=await this.requestReservation(e.reservationStore,t);return o!==null?o:await this.waitUntilHeld(t)?null:`relay ${this.relay.dialAddr} granted a reservation but no circuit address through it was published within ${this.driveTimeoutMs}ms`}async dialRelay(e){let t=new AbortController;this.dialAbort=t;let n=setTimeout(()=>t.abort(),RW(e));t8(n);try{return await this.node.dial(Pe(this.relay.dialAddr),{signal:t.signal}),null}catch(o){return`dial to relay ${this.relay.dialAddr} failed: ${LW(o)}`}finally{clearTimeout(n),this.dialAbort=null}}async requestReservation(e,t){let n,o=new Promise(s=>{n=setTimeout(()=>s(w2e),RW(t)),t8(n)});try{return await Promise.race([e.addRelay(this.relayPeerId,"discovered"),o])===w2e?`reservation request to relay ${this.relay.dialAddr} did not complete within ${this.driveTimeoutMs}ms`:null}catch(s){return this.describeReservationFailure(s)}finally{clearTimeout(n)}}describeReservationFailure(e){switch(e instanceof Error?e.name:""){case"HadEnoughRelaysError":{this.backoffMs=this.maxBackoffMs;let n=`this node's pending circuit slot is already filled by a reservation on another relay, so relay ${this.relay.dialAddr} was not asked; retrying every ${this.maxBackoffMs}ms until that reservation drops`;return this.slotTakenLogged||(this.slotTakenLogged=!0,Lu.error("relay-reservation:slot-taken relay=%s",this.relay.dialAddr)),n}case"UnsupportedProtocolError":return`the peer at ${this.relay.dialAddr} does not serve the circuit-relay hop protocol, so it is not a relay`;default:return`reservation request to relay ${this.relay.dialAddr} failed: ${LW(e)}`}}async waitUntilHeld(e){for(;;){if(this.held)return!0;if(this.stopped||Date.now()>=e)return!1;await Nst(Math.min(this.pollMs,RW(e)))}}scheduleBackoff(){let e=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*2,this.maxBackoffMs),this.schedule(e)}schedule(e){this.stopped||(this.clearTimer(),this.nextTickAtMs=Date.now()+e,this.timer=setTimeout(()=>{this.timer=null,this.tick("timer")},e),t8(this.timer))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}settleFirst(e){this.firstDriveSettled||(this.firstDriveSettled=!0,this.settleFirstDrive(e))}};Uo();Uo();var DC=te("ring-shift"),r8=class{deps;candidateMargin;inFlight=!1;constructor(e,t={}){this.deps=e,this.candidateMargin=t.candidateMargin??2}async executeShift(e){if(this.inFlight)return{status:"skipped",reason:"shift-in-flight"};let t=this.deps.fretAdapter.getMyArachnodeInfo();if(t?.status==="moving")return{status:"skipped",reason:"already-moving"};this.inFlight=!0;try{return e.direction==="out"?await this.moveOut(e.newRingDepth,t):await this.moveIn(e.newRingDepth,t)}finally{this.inFlight=!1}}reconcileOnStart(){let e=this.deps.fretAdapter.getMyArachnodeInfo();return!e||e.status!=="moving"?{reconciled:!1}:(this.deps.fretAdapter.setArachnodeInfo(e.moveFrom?this.clearMove({...e,ringDepth:e.moveFrom.ringDepth,partition:e.moveFrom.partition,status:"active"}):this.clearMove({...e,status:"active"})),DC("reconcile:resumed-old-range ring=%d",e.moveFrom?.ringDepth??e.ringDepth),{reconciled:!0})}async moveOut(e,t){let n=t?.ringDepth??0,o=await this.deps.ringSelector.createArachnodeInfo(this.deps.selfPeerId,e),s={...o,status:"moving",moveFrom:{ringDepth:n,partition:t?.partition}};this.deps.fretAdapter.setArachnodeInfo(s),DC("phaseA:advertise from=%d to=%d",n,e);let i=await this.computeShedBlocks(t?.partition,o.partition),a=Math.max(1,this.deps.getFloor()),c=await this.confirmShedRange(i,a);return c.ok?(this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...o,status:"active"})),i.length>0&&this.deps.onRelease(i),DC("phaseC:release from=%d to=%d shed=%d",n,e,i.length),{status:"moved-out",from:n,to:e,released:i}):(this.rollback(t),DC("phaseB:abort reason=%s \u2192 rolled-back to ring=%d",c.reason,n),{status:"rolled-back",ring:n,reason:c.reason})}async confirmShedRange(e,t){if(e.length===0)return{ok:!0};if(this.deps.partitionDetector.detectPartition())return{ok:!1,reason:"partition"};let n=await this.buildOwnersMap(e,t),{confirmed:o,unconfirmed:s}=await this.deps.confirmer.confirmReplicated(e,n,t);return s.length>0?{ok:!1,reason:`unconfirmed:${s.length}`}:o.length===e.length?{ok:!0}:{ok:!1,reason:"incomplete"}}async computeShedBlocks(e,t){let n=[];for(let o of this.deps.ownedBlocks){let s=await Jt(He(o));Zb(e,s)&&!Zb(t,s)&&n.push(o)}return n}async buildOwnersMap(e,t){let n=new Map,o=t+1+this.candidateMargin;for(let s of e){let i=await Jt(He(s)),c=this.deps.fret.assembleCohort(i,o).filter(l=>{if(l===this.deps.selfPeerId)return!1;let u=this.deps.fretAdapter.getArachnodeInfo(l);return u!==void 0&&Oge(u,i)});n.set(s,c)}return n}async moveIn(e,t){let n=t?.ringDepth??0,o=await this.deps.ringSelector.createArachnodeInfo(this.deps.selfPeerId,e);return this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...o,status:"active"})),DC("moveIn:advertise from=%d to=%d",n,e),{status:"moved-in",from:n,to:e}}rollback(e){if(e){this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...e,status:"active"}));return}let t=this.deps.fretAdapter.getMyArachnodeInfo();t?this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...t,ringDepth:0,partition:void 0,status:"active"})):this.deps.fretAdapter.setStatus("active")}clearMove(e){let{moveFrom:t,...n}=e;return n}};Uo();Be();Uo();var jt=512*1024;async function Mu(r,e,t,n,o=jt){let s;try{s=await E1(r,e,t),is(s,n),await s.close();let i=await fo(s,o);return i.length===0?void 0:i}finally{if(s!=null)try{await s.close()}catch{}}}var _C=class extends Error{constructor(e){super(`${e}: peer replied with no result (zero-length reply frame)`),this.name="NoResultReplyError"}};function PC(r,e){if(r===void 0)throw new _C(e);return r}async function n8(r,e,t,n){let o;try{o=await E1(r,e,t),is(o,n),await o.close()}finally{if(o!=null)try{await o.close()}catch{}}}function o8(r,e,t,n=jt){Ar(r,e,(o,s)=>{(async()=>{try{let i=await fo(o,n),a=await t(i,s.remotePeer);is(o,a??new Uint8Array(0)),await o.close()}catch{try{o.abort(new Error("cohort-topic stream handler error"))}catch{}}})()})}var RC="/optimystic/cohort-topic/1.0.0",BW=`${RC}/register`,OW=`${RC}/cohort-gossip`,Ust=`${RC}/promote`,NW=`${RC}/membership`,Fst=`${RC}/sign`,UW={register:BW,gossip:OW,promote:Ust,membership:NW,sign:Fst};function A2e(r){return[r.register,r.gossip,r.promote,r.membership,r.sign]}function Kst(r){return typeof r=="object"&&r!==null&&"commitCertificate"in r}var s8=class{node;fret;registerProtocol;ttl;maxBytes;clock;constructor(e,t,n={}){this.node=e,this.fret=t,this.registerProtocol=n.registerProtocol??BW,this.ttl=n.ttl??16,this.maxBytes=n.maxBytes??jt,this.clock=n.clock??(()=>Date.now())}async routeAndAct(e,t,n){let o=this.clock(),s={v:1,key:V(e),want_k:n.wantK,min_sigs:n.minSigs,ttl:this.ttl,activity:V(t),correlation_id:V(e)+":"+o,timestamp:o,signature:""},i=await this.fret.routeAct(s);return Kst(i)?j(i.commitCertificate):it({v:1,result:"no_state"},this.maxBytes)}async dialMember(e,t){let n=ice(e.id),o=await Mu(this.node,n,this.registerProtocol,t,this.maxBytes);return PC(o,"cohort-topic register dial")}};Be();var i8=class{node;resolver;handlers=new Set;gossipProtocol;wants;selfPeerId;constructor(e,t,n){this.node=e,this.resolver=t,this.gossipProtocol=n.gossipProtocol??OW,this.wants=n.wants??16,this.selfPeerId=n.selfPeerId}broadcast(e,t){this.broadcastOver(this.gossipProtocol,e,t)}broadcastOver(e,t,n){for(let o of this.resolver.cohortPeers(t,this.wants))o!==this.selfPeerId&&n8(this.node,le(o),e,n).catch(()=>{})}onMessage(e){return this.handlers.add(e),()=>this.handlers.delete(e)}get subscriberCount(){return this.handlers.size}deliver(e,t){let n={id:Ms(e)};for(let o of this.handlers)o(n,t)}};var a8=5e3,I2e=3e4;function T2e(){let r=new Map,e=new Map,t=new Map,n=(i,a)=>`${V(i)}|${V(a)}`,o=(i,a)=>`${V(i)}|${V(a)}`,s=(i,a,c,l)=>{let u=o(i,a),d=t.get(u);d!==void 0&&c<d.ref.effectiveAt||t.set(u,{ref:{topicId:V(i),childCohortCoord:V(a),effectiveAt:c},linked:l})};return{touch(i){let a=n(i.topicId,i.participantId),c=r.get(a);(c===void 0||i.lastPing>=c.lastPing)&&r.set(a,i),e.delete(a)},evicted(i){let a=n(i.topicId,i.participantId);e.set(a,{topicId:V(i.topicId),participantId:V(i.participantId),lastPing:i.lastPing}),r.delete(a)},childLink(i,a,c){s(i,a,c,!0)},childUnlink(i,a,c){s(i,a,c,!1)},isEmpty(){return r.size===0&&e.size===0&&t.size===0},drain(){let i=[],a=[];for(let l of t.values())(l.linked?i:a).push(l.ref);let c={records:[...r.values()].map(Xte),evicted:[...e.values()],childLinks:i,childUnlinks:a};return r.clear(),e.clear(),t.clear(),c}}}function k2e(r){let e=nre(r.profile,r.barometer);if(r.topicSummaries.length===0&&r.records.length===0&&r.evicted.length===0&&r.childLinks.length===0&&r.childUnlinks.length===0&&!(r.heartbeat&&e!==0))return;let n={v:1,fromMember:r.fromMember,coord:r.coord,cohortEpoch:r.cohortEpoch,treeTier:r.treeTier,willingnessBits:rre(e),loadBuckets:r.barometer.loadBuckets(),windowSeconds:r.windowSeconds,topicSummaries:r.topicSummaries,timestamp:r.timestamp,signature:""};return r.records.length>0&&(n.records=r.records),r.evicted.length>0&&(n.evicted=r.evicted),r.childLinks.length>0&&(n.childLinks=r.childLinks),r.childUnlinks.length>0&&(n.childUnlinks=r.childUnlinks),n}Be();var c8=class{node;resolver;byCoord=new Map;membershipProtocol;wants;maxBytes;constructor(e,t,n={}){this.node=e,this.resolver=t,this.membershipProtocol=n.membershipProtocol??NW,this.wants=n.wants??16,this.maxBytes=n.maxBytes??jt}current(e){return Promise.resolve(this.byCoord.get(V(e)))}has(e){return this.byCoord.has(V(e))}async fetch(e){let t=e;for(let n of this.resolver.cohortPeers(e,this.wants))try{let o=await Mu(this.node,le(n),this.membershipProtocol,t,this.maxBytes);if(o!==void 0)return this.cache(e,o),o}catch{}}cache(e,t){this.byCoord.set(V(e),t)}};var l8=class{latestCert;publish(e){this.latestCert=e}latest(){return this.latestCert}};var Kf=64,zst=5e3;function D2e(r,e,t){if(t.length===0||e.length!==t.length*Kf)return!1;for(let n=0;n<t.length;n++){let o=e.subarray(n*Kf,(n+1)*Kf);if(!Bo(t[n],r,o))return!1}return!0}var LC=class{deps;constructor(e){this.deps=e}async assemble(e,t){let n=new Map,o=Zt(this.deps.selfMember);if(this.deps.selfEligible?.()??!0){let l=await Bs(this.deps.privateKey,e);if(l.length!==Kf)throw new Error(`cohort threshold sign: self produced a ${l.length}-byte signature (expected ${Kf}); non-Ed25519 identity?`);n.set(V(this.deps.selfMember),{signer:this.deps.selfMember,sig:l})}let s=this.deps.cohortMembers().filter(l=>l!==o);if(s.length>0&&n.size<t){let l={v:1,kind:this.deps.kind,coord:V(this.deps.coord()),cohortEpoch:V(this.deps.cohortEpoch()),payload:V(e)},u=this.deps.collectTimeoutMs??zst;await Promise.all(s.map(d=>this.collectFrom(d,l,e,n,u)))}if(n.size<t)throw new Error(`cohort threshold sign: gathered ${n.size} of ${t} required signatures`);let i=[...n.values()].sort((l,u)=>wg(l.signer,u.signer)),a=i.map(l=>l.signer);return{thresholdSig:$st(i.map(l=>l.sig)),signers:a}}verify(e,t,n){return D2e(e,t,n)}async collectFrom(e,t,n,o,s){try{let i=await Hst(this.deps.dialSign(e,t),s);if(i===void 0||"refused"in i)return;let a=j(i.signer),c=j(i.signature);if(c.length!==Kf||!Bo(a,n,c))return;let l=V(a);if(o.has(l))return;o.set(l,{signer:a,sig:c})}catch{}}};function FW(){return{assemble:()=>Promise.reject(new Error("verify-only cohort threshold crypto cannot assemble signatures")),verify:D2e}}function $st(r){let e=new Uint8Array(r.length*Kf);for(let t=0;t<r.length;t++)e.set(r[t],t*Kf);return e}function Hst(r,e){return new Promise(t=>{let n=!1,o=setTimeout(()=>{n||(n=!0,t(void 0))},e);r.then(s=>{n||(n=!0,clearTimeout(o),t(s))},()=>{n||(n=!0,clearTimeout(o),t(void 0))})})}var Vst=2,u8=class{fret;k;selfPeerId;churnSlack;maxCommittedTier;constructor(e,t){this.fret=e,this.k=t.k,this.selfPeerId=t.selfPeerId,this.churnSlack=t.churnSlack??Vst,this.maxCommittedTier=t.maxCommittedTier??ol}directAnchor(e,t){if(t<=this.maxCommittedTier)return"unknown";try{if(this.fret.detectPartition?.()===!0)return"unknown";let n=j(e.cohortCoord),o=this.fret.assembleCohort(n,this.k);if(o.length<this.k||!o.includes(this.selfPeerId))return"unknown";let s=new Set(this.fret.assembleCohort(n,this.k+this.churnSlack)),i=e.signers.map(c=>Zt(j(c)));if(i.length===0)return"unknown";let a=0;for(let c of i)s.has(c)&&a++;return a===i.length?"anchored":a===0?"rejected":"unknown"}catch{return"unknown"}}};var MC=class{fret;constructor(e){this.fret=e}estimate(){let{size_estimate:e,confidence:t}=this.fret.getNetworkSizeEstimate();return{nEst:e,confidence:t}}};var qst=oS.deprioritize;function _2e(r){let e=r.bits??OI;return t=>{try{let n=Tv(t);if(n?.pow===void 0)return!1;let o=j(n.pow.nonce);return UI(r.hash.H(NI(t,o)),e)}catch{return!1}}}function P2e(r){let e=r.deprioritizeThreshold??qst;return t=>{try{let n=Tv(t);if(n?.reputation===void 0)return!1;let o=j(n.reputation.referee),s=j(n.reputation.sig);if(!Bo(o,Cg(t),s))return!1;let i=Zt(o);return!r.reputation.isBanned(i)&&r.reputation.getScore(i)<e}catch{return!1}}}function R2e(r){let{parentTopicView:e}=r;return t=>{try{let n=Tv(t);if(n?.parentRef===void 0)return!1;let{parentTopicId:o,sig:s}=n.parentRef;if(o===t.topicId)return!1;let i=bre(t,o);return Bo(j(t.participantCoord),i,j(s))?e.exists(j(o),t.tier):!1}catch{return!1}}}function L2e(r){let{membershipSource:e,addressing:t,committedReader:n}=r,o=r.maxNoPowTier??ol;return{exists(s,i){let a=t.coord0(s);return i<=o?n!==void 0&&n(a):e.has(a)}}}var jst=1<<24;function B2e(r){let e=r.bits??OI,t=r.maxNoPowTier??ol,n=r.maxIterations??jst;return async o=>{let s={topicId:o.topicId,tier:o.tier,participantCoord:o.participantCoord,timestamp:o.timestamp};if(o.tier<=t){if(r.endorse===void 0)return;let i=await r.endorse(Cg(s));return M2e({v:1,reputation:i})}for(let i=0;i<n;i++){let a=_6(16);if(UI(r.hash.H(NI(s,a)),e))return M2e({v:1,pow:{nonce:V(a)}})}}}function M2e(r){return j(fB(r))}var ms=te("cohort-topic");async function z2e(r,e,t={}){let n=t.profile??Rte(),o=t.protocols??UW,s=t.wantK??16,i=t.minSigs??Sv,a=t.fanout??16,c=t.maxBytes??jt,l=t.gossipIntervalMs??a8,u=t.willingnessHeartbeatMs??I2e,d=new gg,h=r.peerId.toString(),p=Ms(r.peerId),f=await Or(r.peerId),g=$i(d,a),y={cohortPeers(ce,Ke){return e.assembleCohort(ce,Ke)}},m=new s8(r,e,{registerProtocol:o.register,maxBytes:c}),w=new MC(e),b=new i8(r,y,{gossipProtocol:o.gossip,wants:s,selfPeerId:h}),x=new c8(r,y,{membershipProtocol:o.membership,wants:s,maxBytes:c}),S=new l8,T=Kte(d),A=QM(),v=Cv(FW(),i),C=async(ce,Ke)=>{let _e=await Mu(r,le(ce),o.sign,it(Ke,c),c);return SI(Yt(PC(_e,"cohort sign"),c))},P=ce=>{let Ke=e.assembleCohort(ce,s),_e=[p,...Ke.filter(bt=>bt!==h).map(bt=>Ms(bt))],yt=_e.map(V).sort().join("|"),xn=d.H(new TextEncoder().encode(yt));return{members:_e,cohortEpoch:xn}},F=Gst(t.privateKey,ms),R=t.privateKey===void 0?void 0:ce=>ce.signature.length>0&&Bo(j(ce.participantCoord),AI(ce),j(ce.signature)),k=t.privateKey===void 0?void 0:ce=>ce.signature.length>0&&Bo(j(ce.participantId),LM(ce),j(ce.signature)),I=t.privateKey,E=I===void 0?void 0:async ce=>V(await Bs(I,MM(ce))),D=I===void 0?void 0:(ce,Ke)=>{if(ce.signature.length===0)return!1;let _e=j(ce.fromMember);return Bo(_e,MM(ce),j(ce.signature))?P(Ke).members.map(Zt).includes(Zt(_e)):!1},M=iit(t.antiDos?.rateLimiter),B=(ce,Ke)=>{q2e(M,ce);let _e=it(ce,c);for(let yt of dit(ce,Ke))b.broadcastOver(o.promote,yt,_e)},L=t.antiDos?.parentTopicView??L2e({membershipSource:x,addressing:g,committedReader:t.committedParentTopicReader}),O=t.antiDos?.parentTopicView!==void 0||t.committedParentTopicReader!==void 0,U=Wst(t.antiDos,d,ms,L,O),$={hash:d,addressing:g,slots:T,barometer:A,transport:b,profile:n,selfMemberBytes:p,wantK:s,minSigs:i,maxBytes:c,willingnessHeartbeatMs:u,publishSink:S,privateKey:t.privateKey,router:m,antiDos:{rateLimiter:t.antiDos?.rateLimiter,replayGuard:t.antiDos?.replayGuard,topicBudget:t.antiDos?.topicBudget},bootstrapEvidence:U,promotionConfig:t.promotion,dialSign:C,cohortAround:P,verifyRegisterSig:R,verifyParticipantSig:k,signGossip:E,verifyGossip:D,broadcastNotice:B,onCertPublished:ce=>Fe.cache(ce),onEngineEvicted:ce=>Fe.forget(V(ce)),adoptedTransition:(ce,Ke,_e)=>M.transitions.get(H2e(V(ce),Ke,V(_e)))},J=Jst($,t.antiDos?.coordEnginesMax),X=ce=>{if(D===void 0)return;let Ke;try{Ke=CI(ce,c)}catch{return}if(Ke.treeTier!==0)return;let _e=j(Ke.coord);if(J.findByCoord(_e)===void 0&&D(Ke,_e))try{J.forCoord(_e,Ke.treeTier,p)}catch(yt){if(yt instanceof Nw)return;throw yt}},N=(ce,Ke)=>oit(ce,Ke,{privateKey:t.privateKey,selfMember:p,cohortMembersAround:_e=>P(_e).members.map(Zt),currentEpoch:_e=>P(_e).cohortEpoch,priorCohortMembersAt:(_e,yt)=>J.findByCoord(_e)?.cohortIdentityAt(yt),expectedMembershipFields:_e=>{let yt=P(_e),{cohortCoord:xn,cohortEpoch:bt,members:Ft}=RI({coord:_e,cohortEpoch:yt.cohortEpoch,members:yt.members,stabilizedAt:0});return{cohortCoord:xn,cohortEpoch:bt,members:Ft}},now:t.now??(()=>Date.now())}),H=OM(),Z=jM({transport:b,store:H,coord:f,localEpoch:()=>P(f).cohortEpoch,verifyInbound:D===void 0?void 0:ce=>D(ce,f)}),ae=x,Q=Qte({committed:ae,fret:ae}),oe=new u8(e,{k:s,selfPeerId:h}),Fe=ere({signer:v,router:Q,minSigs:i,anchor:oe,trustRoots:t.genesisTrustRoots??[]}),nr=B2e({hash:d,bits:t.antiDos?.powDifficultyBits}),fe=xre({self:p,hash:d,router:m,sizeEstimator:w,signer:F,gossipBus:Z,verifier:Fe,buildBootstrapEvidence:nr,config:{fanout:a,wantK:s,minSigs:i,maxMessageBytes:c}}),Ce=async(ce,Ke,_e)=>{let yt=j(ce.topicId),xn=j(ce.participantCoord),bt=g.coord(ce.treeTier,xn,yt),Ft;try{Ft=J.forCoord(bt,ce.treeTier,xn)}catch(Es){if(Es instanceof Nw)return ms("cohort-topic: register refused \u2014 coord-engine registry full"),{v:1,result:"unwilling_cohort",retryAfterMs:MI,reason:"coord-engine registry full"};throw Es}Ke!==void 0&&fit(e,s,bt,Ke);let nh=ce.treeTier>0?g.coord(ce.treeTier-1,xn,yt):void 0,Rr=ce.followOn===!0;return Ft.engine.handleRegister(ce,{followOn:Rr,treeTier:ce.treeTier,parentCoord:nh},_e)},Ve=t.privateKey===void 0?void 0:async(ce,Ke)=>{if(ce.thresholdSig.length===0)return!1;let _e,yt;try{_e=ce.signers.map(j),yt=j(ce.thresholdSig)}catch{return!1}return await Fe.verifyMessage(_e,j(ce.childCohortCoord),ce.childTier,GM(ce),yt,{minRefetchIntervalMs:d8,now:Ke})==="verified"},Er={coord:(ce,Ke,_e)=>g.coord(ce,Ke,_e),resolveParent:(ce,Ke,_e)=>J.forCoord(ce,Ke,_e),verifyChildLinkSig:Ve};await git(r,o,J,Ce,Er,i,N,Fe,M,b,X,S,x,f,c),e.setActivityHandler(async(ce,Ke)=>{let _e=Yt(j(ce),c),yt=BC(()=>vv(_e,i)),xn=yt!==void 0?await $2e(yt,Er,Date.now()):await Ce(xv(_e),Ke,Date.now());return{commitCertificate:V(it(xn,c))}});let Rt=!1,Sr=!1,or=async()=>{if(!(Rt||Sr)){Sr=!0;try{let ce=Date.now();for(let Ke of J.all()){if(Rt)break;try{await Ke.gossipRound(ce),await Ke.pumpMembership(ce),await Ke.demotionTick(ce)}catch(_e){ms("cohort-topic: gossip tick failed for a coord engine: %o",_e)}}M.rateLimiter.sweep(ce)}finally{Sr=!1}}},Co=setInterval(()=>{or()},l);return Co.unref?.(),{service:fe,registry:J,protocols:o,profile:n,gossipTransport:b,promoteGate:M,membershipSource:x,stop:async()=>{Rt=!0,clearInterval(Co),J.close(),Z.close(),await r.unhandle(A2e(o))}}}function Gst(r,e){if(r===void 0){let t=!1,n=()=>{t||(t=!0,e("no privateKey supplied to createCohortTopicHost; participant RegisterV1/RenewV1 bodies are UNSIGNED (interim \u2014 supply options.privateKey for peer-key signing)"))};return{signRegister:()=>(n(),Promise.resolve("")),signRenew:()=>(n(),Promise.resolve(""))}}return{signRegister:async t=>V(await Bs(r,AI(t))),signRenew:async t=>V(await Bs(r,LM(t)))}}function Wst(r,e,t,n,o){let s=r?.bootstrapEvidence,i=r?.reputation,a=s!==void 0||i!==void 0,c=s?.config?.maxNoPowTier??ol,l=_2e({hash:e,bits:r?.powDifficultyBits}),u=i===void 0?void 0:P2e({reputation:i,deprioritizeThreshold:r?.deprioritizeThreshold}),d=R2e({parentTopicView:n}),h=()=>!1,p=!1,f=w=>b=>(p||(p=!0,t("cohort-topic anti-DoS: bootstrap-evidence %s verifier is PERMISSIVE \u2014 no PoW/reputation view wired, so cold-root bootstrap is NOT cryptographically gated (interim; inject antiDos.bootstrapEvidence/reputation, see cohort-topic-bootstrap-evidence-scheme)",w)),!0),g=w=>a?h:f(w),y=f("parent-reference (T0/T1, no committed backing)"),m=w=>w.tier<=c&&!o?y(w):d(w);return yre({verifyPoW:s?.verifyPoW??(a?l:g("proof-of-work")),verifyReputation:s?.verifyReputation??u??g("reputation"),verifyParentReference:s?.verifyParentReference??(a?m:g("parent-reference")),config:s?.config})}async function Yst(r,e){let t=e.treeTier,n={v:1,topicId:V(e.topicId),childCohortCoord:V(e.childCohortCoord),childParticipantCoord:V(e.participantCoord),childTier:t,tier:Xst(e.opTier??0),effectiveAt:Date.now(),thresholdSig:"",signers:[],cohortEpoch:V(e.cohortEpoch())};if(e.signChildLink!==void 0){let{thresholdSig:i,signers:a}=await e.signChildLink.thresholdSign(GM(n));n.thresholdSig=V(i),n.signers=a.map(V)}let o=await r.router.routeAndAct(e.parentCoord,it(n,r.maxBytes),{wantK:r.wantK,minSigs:r.minSigs}),s=vI(Yt(o,r.maxBytes));if(s.result!=="linked")throw new Error(`cohort-topic child-link rejected by parent${s.reason!==void 0?`: ${s.reason}`:""}`)}function Xst(r){return!Number.isInteger(r)||r<0?0:r>3?3:r}var Zst=2048,Nw=class extends Error{constructor(e){super(`cohort-topic coord-engine registry full (max=${e}) \u2014 every slot holds a live cohort`),this.name="CoordEngineRegistryFullError"}},O2e={records:"pinned",forwarders:"pinned",children:1,promotion:1};function Jst(r,e=Zst){if(!Number.isInteger(e)||e<=0)throw new RangeError(`coordEnginesMax must be a positive integer, got ${e}`);let t=new Map,n=new Map,o=0,s=c=>{n.set(c,++o)},i=c=>{let l=c.liveness(),u=0;for(let d of Object.keys(O2e)){if(!l[d])continue;let h=O2e[d];if(h==="pinned")return;h>u&&(u=h)}return u},a=()=>{let c,l=1/0,u=1/0;for(let[h,p]of t){let f=i(p);if(f===void 0)continue;let g=n.get(h)??0;(f<l||f===l&&g<u)&&(l=f,u=g,c=h)}if(c===void 0)return!1;let d=t.get(c);return d.close(),t.delete(c),n.delete(c),r.onEngineEvicted?.(d.servedCoord),!0};return{forCoord(c,l,u){let d=V(c),h=t.get(d);if(h===void 0){if(t.size>=e&&!a())throw ms("cohort-topic: coord-engine registry full (max=%d) \u2014 refusing new coord %s",e,d),new Nw(e);h=eit(r,c,l,u),t.set(d,h)}return s(d),h},findByCoord(c){let l=V(c),u=t.get(l);return u!==void 0&&s(l),u},findHolder(c,l){for(let[u,d]of t)if(d.holds(c,l))return s(u),d},findServing(c,l){for(let[u,d]of t)if(d.treeTier===l&&d.servesTopic(c))return s(u),d},all(){return[...t.values()]},close(){for(let c of t.values())c.close();t.clear(),n.clear()}}}var zW=class{current;prior;lastPublished;observe(e,t){if(this.current?.epochKey===e)return;let n=t();this.prior=this.current,this.current=n}recordPublished(e){this.lastPublished=e}predecessor(){return this.lastPublished}membersAt(e){if(this.current?.epochKey===e)return this.current.memberStrs;if(this.prior?.epochKey===e)return this.prior.memberStrs}};function Qst(){let r=new Map,e=(t,n,o,s)=>{let i=V(t),a=r.get(i);a===void 0&&(a=new Map,r.set(i,a));let c=V(n),l=a.get(c);if(l===void 0)return a.set(c,{linked:s,lastEffectiveAt:o,topicId:t,childCohortCoord:n}),!0;if(o<=l.lastEffectiveAt)return!1;let u=l.linked!==s;return l.linked=s,l.lastEffectiveAt=o,u};return{recordChild(t,n,o){return e(t,n,o,!0)},unrecordChild(t,n,o){return e(t,n,o,!1)},count(t){let n=r.get(V(t));if(n===void 0)return 0;let o=0;for(let s of n.values())s.linked&&o++;return o},hasLinkedChildren(){for(let t of r.values())for(let n of t.values())if(n.linked)return!0;return!1},linkedChildren(){let t=[];for(let n of r.values())for(let o of n.values())o.linked&&t.push({topicId:o.topicId,childCohortCoord:o.childCohortCoord,effectiveAt:o.lastEffectiveAt});return t}}}function eit(r,e,t,n){let o=OM(),s=Qst(),i=new zW,a=N=>{let H=[...N.members];return{epoch:N.cohortEpoch,epochKey:V(N.cohortEpoch),memberBytes:H,memberStrs:H.map(Zt)}},c=()=>{let N=r.cohortAround(e);return i.observe(V(N.cohortEpoch),()=>a(N)),N},l=()=>c().cohortEpoch,u=jM({transport:r.transport,store:o,coord:e,localEpoch:l,verifyInbound:r.verifyGossip===void 0?void 0:N=>r.verifyGossip(N,e),onRecordsEvicted:N=>{for(let H of N)D.touch(H,o.directParticipants(H))},onChildDeltas:(N,H)=>{for(let Z of N)s.recordChild(j(Z.topicId),j(Z.childCohortCoord),Z.effectiveAt);for(let Z of H)s.unrecordChild(j(Z.topicId),j(Z.childCohortCoord),Z.effectiveAt)}}),d=u.view(),h=V(r.selfMemberBytes),p=T2e(),f=N=>{if(r.privateKey===void 0)return Cv(FW(),r.minSigs);let H=new LC({kind:N,privateKey:r.privateKey,selfMember:r.selfMemberBytes,coord:()=>e,cohortEpoch:l,cohortMembers:()=>c().members.map(Zt),dialSign:r.dialSign});return Cv(H,r.minSigs)},g=f("promotion"),y=f("membership"),m=f("childlink"),w=tre({signer:y,sink:r.publishSink,minSigs:r.minSigs,maxMessageBytes:r.maxBytes}),b=N=>{let{members:H,cohortEpoch:Z}=c();return{coord:e,cohortEpoch:Z,members:H,stabilizedAt:N}},x=r.privateKey!==void 0,S=(N,H)=>N.epochKey!==H.epochKey,T=async(N,H)=>{let Z=vh(RI(N)),ae=Zt(r.selfMemberBytes),Q=new LC({kind:"rotation",privateKey:r.privateKey,selfMember:r.selfMemberBytes,coord:()=>e,cohortEpoch:()=>H.epoch,cohortMembers:()=>[...H.memberStrs],dialSign:r.dialSign,selfEligible:()=>H.memberStrs.includes(ae)}),oe=Cv(Q,r.minSigs);try{let{thresholdSig:Fe,signers:nr}=await oe.thresholdSign(Z);return{prevEpoch:H.epoch,rotationSig:Fe,rotationSigners:nr}}catch(Fe){ms("cohort-topic: rotation attestation skipped at coord %s \u2014 predecessor quorum unavailable: %o",V(e),Fe);return}},A=!1,v=async(N,H)=>{if(A||!x)return;let Z=b(N),ae=a(Z),Q=i.predecessor(),oe=Q!==void 0&&S(Q,ae),Fe;if(oe){let nr=await T(Z,Q);Fe=await w.onStabilized(Z,N,nr)}else Fe=await(H?w.tick(Z,N):w.onStabilized(Z,N));return Fe!==void 0&&(i.recordPublished(ae),r.onCertPublished?.(Fe)),Fe},C=ore({barometer:r.barometer,view:d,selfMember:h,primaryTopicCount:N=>mit(o,r.selfMemberBytes,N),config:{cohortSize:r.wantK}}),P=ire({view:d,store:o,selfMember:h,childCohortCount:N=>s.count(N)}),F=ure({store:o,loadBucket:N=>r.barometer.bucket(F2e(o,N)),childCohortCount:N=>s.count(N),treeTier:()=>t,parentCoord:N=>r.addressing.coord(Math.max(0,t-1),n,N),cohortCoord:()=>e,cohortEpoch:l,signer:g,seedTransition:N=>r.adoptedTransition?.(e,t,N),config:r.promotionConfig??{capPromote:void 0}}),R=fre({parentRegistrar:{registerWithParent:(N,H,Z,ae)=>Yst(r,{topicId:N,parentCoord:H,treeTier:Z,opTier:ae,participantCoord:n,childCohortCoord:e,cohortEpoch:l,signChildLink:x?m:void 0})}}),k=BI(r.antiDos.rateLimiter),I=BI(r.antiDos.rateLimiter),E=DI(r.antiDos.replayGuard),D=mre({...r.antiDos.topicBudget,onEvict:N=>{R.remove(N),P.forget(N)}}),M=Yte({store:o,self:r.selfMemberBytes,slots:r.slots,cohort:c,gossip:{touch:N=>p.touch(N),evicted:N=>p.evicted(N)},verifyParticipantSig:r.verifyParticipantSig,freshness:r.antiDos.replayGuard}),B=wre({self:r.selfMemberBytes,profile:r.profile,hash:r.hash,store:o,slots:r.slots,willingness:C,promotion:F,coldStart:R,traffic:P,renewal:M,cohort:c,quorumWilling:N=>r.profile.willingTiers.has(N),rateLimiter:k,probeRateLimiter:I,replayGuard:E,topicBudget:D,bootstrapEvidence:r.bootstrapEvidence,verifyRegisterSig:r.verifyRegisterSig,onAdmit:N=>p.touch(N),onNotice:N=>r.broadcastNotice?.(N,e),log:ms}),L=()=>{let N=new Map;for(let H of o.listAll())N.set(V(H.topicId),H.topicId);return[...N.values()]},O,U,$=async N=>{if(A)return;B.sweepStale(N);let H=L().map(Ce=>are(Ce,P.publish(Ce,N),{tier:F2e(o,Ce),directParticipants:o.directParticipants(Ce),promoted:F.isPromoted(Ce),childCohortCount:s.count(Ce)}));if(U===void 0||N-U>=r.willingnessHeartbeatMs){let Ce=s.linkedChildren();for(let Ve of Ce)p.childLink(Ve.topicId,Ve.childCohortCoord,Ve.effectiveAt);Ce.length>0&&(U=N)}let{records:Z,evicted:ae,childLinks:Q,childUnlinks:oe}=p.drain(),nr=H.length===0&&Z.length===0&&ae.length===0&&Q.length===0&&oe.length===0&&(O===void 0||N-O>=r.willingnessHeartbeatMs),fe=k2e({fromMember:h,coord:V(e),cohortEpoch:V(l()),treeTier:t,heartbeat:nr,profile:r.profile,barometer:r.barometer,windowSeconds:rB,topicSummaries:H,records:Z,evicted:ae,childLinks:Q,childUnlinks:oe,timestamp:N});if(fe!==void 0)return O=N,r.signGossip!==void 0&&(fe.signature=await r.signGossip(fe)),u.broadcast(fe),fe},J=async N=>{if(!(A||!x))for(let H of L()){let Z;try{Z=await F.maybeDemote(H,N)}catch(ae){ms("cohort-topic: demotion sign/broadcast failed for topic %s: %o",V(H),ae);continue}Z!==void 0&&r.broadcastNotice?.(Z,e)}},X=()=>({records:o.listAll().length>0,forwarders:R.hasForwarders(),children:s.hasLinkedChildren(),promotion:F.hasAdoptedState()});return{servedCoord:e,treeTier:t,engine:B,cohort:c,cohortIdentityAt:N=>i.membersAt(V(N)),liveness:X,hasState:()=>X().records,hasForwarders:()=>X().forwarders,holds:(N,H)=>o.getByParticipant(N,H)!==void 0,records:N=>o.listByTopic(N),topicTraffic:N=>P.snapshot(N),recordQuery:(N,H)=>P.recordQuery(N,H),cohortView:()=>d,servesTopic:N=>o.directParticipants(N)>0||R.get(N)!==void 0,budgetHasTopic:N=>D.has(N),budgetParticipantCount:N=>D.participantCount(N),forwarder:N=>R.get(N),recordChild:(N,H,Z)=>{s.recordChild(N,H,Z)&&p.childLink(N,H,Z)},unrecordChild:(N,H,Z)=>{s.unrecordChild(N,H,Z)&&p.childUnlink(N,H,Z)},childCohortCount:N=>s.count(N),isPromoted:N=>F.isPromoted(N),applyPromotionNotice:(N,H)=>F.applyPromotionNotice(N,H),applyDemotionNotice:(N,H)=>F.applyDemotionNotice(N,H),onStabilized:N=>v(N,!1),pumpMembership:N=>v(N,!0),gossipRound:$,demotionTick:J,close:()=>{A=!0,u.close()}}}function tit(r,e,t){let n=j(e.topicId),o=j(e.participantId),s=r.findHolder(n,o);return s===void 0?{v:1,result:"unknown_registration"}:s.engine.handleRenew(e,t)}async function $2e(r,e,t){let n=j(r.topicId),o=j(r.childParticipantCoord),s=j(r.childCohortCoord),i=e.coord(r.childTier,o,n);if(!to(i,s))return{v:1,result:"rejected",reason:"coord mismatch"};let a=e.coord(r.childTier-1,o,n);if(e.verifyChildLinkSig!==void 0&&!await e.verifyChildLinkSig(r,t))return{v:1,result:"rejected",reason:"child cohort signature not verified"};let c;try{c=e.resolveParent(a,r.childTier-1,o)}catch(l){if(l instanceof Nw)return{v:1,result:"rejected",reason:"parent cohort capacity"};throw l}return c.recordChild(n,s,r.effectiveAt),{v:1,result:"linked"}}var rit=5e3,N2e={membership:"MembershipCertV1",promotion:"PromotionNoticeV1",demotion:"DemotionNoticeV1",childlink:"ChildLinkV1"};function U2e(r){try{let e=JSON.parse(new TextDecoder().decode(j(r)));return Array.isArray(e)?e:void 0}catch{return}}function nit(r,e){return Array.isArray(r)&&hit(r,e)}async function oit(r,e,t){if(t.privateKey===void 0)return{v:1,refused:!0,reason:"node has no signing key"};let n=j(r.coord),o=Zt(t.selfMember);if(r.kind==="rotation"){let d=j(r.cohortEpoch),h=t.priorCohortMembersAt?.(n,d);if(h===void 0)return{v:1,refused:!0,reason:"not a member of the prior cohort at prevEpoch"};if(!h.includes(o))return{v:1,refused:!0,reason:"self not in the prior cohort"};if(!h.includes(e))return{v:1,refused:!0,reason:"requester not in the prior cohort"};let p=U2e(r.payload);if(p===void 0||p[0]!==N2e.membership)return{v:1,refused:!0,reason:"rotation payload is not a MembershipCertV1 image"};let f=await Bs(t.privateKey,j(r.payload));return{v:1,signer:V(t.selfMember),signature:V(f)}}let s=t.cohortMembersAround(n);if(!s.includes(o))return{v:1,refused:!0,reason:"not a cohort member for coord"};if(!s.includes(e))return{v:1,refused:!0,reason:"requester not in cohort"};if(!to(j(r.cohortEpoch),t.currentEpoch(n)))return{v:1,refused:!0,reason:"cohort epoch mismatch"};let i=U2e(r.payload);if(i===void 0)return{v:1,refused:!0,reason:"payload is not a decodable signable image"};let a=N2e[r.kind];if(i[0]!==a)return{v:1,refused:!0,reason:`payload kind tag mismatch (expected ${a})`};let c=V(t.currentEpoch(n));if((r.kind==="membership"?i[2]:i[i.length-1])!==c)return{v:1,refused:!0,reason:"payload cohortEpoch does not match endorser view"};if(r.kind==="membership"){let d=t.expectedMembershipFields?.(n);if(d===void 0)return{v:1,refused:!0,reason:"no membership view to bind the cert against"};if(i[1]!==d.cohortCoord)return{v:1,refused:!0,reason:"payload cohortCoord does not match endorser view"};if(!nit(i[3],d.members))return{v:1,refused:!0,reason:"payload members do not match endorser view"};let h=i[4];if(typeof h!="number"||!Number.isFinite(h))return{v:1,refused:!0,reason:"payload stabilizedAt is not a finite number"};if(t.now!==void 0&&h>t.now()+rit)return{v:1,refused:!0,reason:"payload stabilizedAt is far-future"}}let u=await Bs(t.privateKey,j(r.payload));return{v:1,signer:V(t.selfMember),signature:V(u)}}var sit=8192;function iit(r){return{rateLimiter:BI(r),transitions:new Wr(sit)}}function H2e(r,e,t){return`${r}|${e}|${t}`}function V2e(r){return H2e(r.cohortCoord,"parentCohortCoord"in r?r.tier:r.fromTier,r.topicId)}function q2e(r,e){let t=V2e(e),n=r.transitions.get(t);(n===void 0||e.effectiveAt>n.effectiveAt)&&r.transitions.set(t,{effectiveAt:e.effectiveAt,promoted:!("parentCohortCoord"in e)})}function ait(r,e){let t=Yt(r,e),n=BC(()=>wI(t));if(n!==void 0)return{kind:"promotion",notice:n};let o=BC(()=>xI(t));if(o!==void 0)return{kind:"demotion",notice:o}}var d8=6e4;async function cit(r,e,t,n){if(e===void 0)return"dropped";let o,s;try{o=r.notice.signers.map(j),s=j(r.notice.thresholdSig)}catch{return"untrusted"}if(r.kind==="promotion"){let c=PI(r.notice);return await t.verifyMessage(o,e.servedCoord,r.notice.fromTier,c,s,{minRefetchIntervalMs:d8,now:n})!=="verified"?"untrusted":(e.applyPromotionNotice(r.notice,n),"applied")}let i=Ev(r.notice);return await t.verifyMessage(o,e.servedCoord,r.notice.tier,i,s,{minRefetchIntervalMs:d8,now:n})!=="verified"?"untrusted":(e.applyDemotionNotice(r.notice,n),"applied")}async function lit(r,e,t,n){let o=e.findByCoord(j(r.parentCohortCoord));if(o===void 0)return"no-parent";let s,i;try{s=r.signers.map(j),i=j(r.thresholdSig)}catch{return"untrusted"}let a=Ev(r);return await t.verifyMessage(s,j(r.cohortCoord),r.tier,a,i,{minRefetchIntervalMs:d8,now:n})!=="verified"?"untrusted":(o.unrecordChild(j(r.topicId),j(r.cohortCoord),r.effectiveAt),"unlinked")}async function uit(r,e,t,n,o,s,i){let a=ait(r,i);if(a===void 0)return ms("promote: dropped an undecodable notice frame"),"undecodable";let c=a.kind==="promotion"?a.notice.fromTier:a.notice.tier,l=j(a.notice.topicId);if(o.rateLimiter.check(e,l,s).ok===!1)return ms("promote: rate-limited %s notice for topic %s tier %d",a.kind,a.notice.topicId,c),"rate-limited";let u=t.findByCoord(j(a.notice.cohortCoord)),d;if(u===void 0)d="dropped";else{let p=o.transitions.get(V2e(a.notice));p!==void 0&&a.notice.effectiveAt<=p.effectiveAt?(ms("promote: stale %s notice for topic %s tier %d (effectiveAt %d <= last adopted %d)",a.kind,a.notice.topicId,c,a.notice.effectiveAt,p.effectiveAt),d="stale"):(d=await cit(a,u,n,s),d==="applied"?q2e(o,a.notice):ms("promote: %s %s notice for topic %s tier %d",d,a.kind,a.notice.topicId,c))}if(a.kind!=="demotion")return d;let h=await lit(a.notice,t,n,s);return d==="applied"?"applied":h==="unlinked"?"unlinked":h==="untrusted"?(ms("promote: untrusted demotion notice at parent for topic %s tier %d",a.notice.topicId,c),"untrusted"):d}function dit(r,e){return"parentCohortCoord"in r?[e,j(r.parentCohortCoord)]:[e]}function fit(r,e,t,n){let o=r.assembleCohort(t,e);pit(n,o)||ms("cohort cross-check mismatch at coord %s: FRET-routed=%o assembled=%o; trusting the recomputed assembly",V(t),n,o)}function hit(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function pit(r,e){if(r.length!==e.length)return!1;let t=new Set(r);return e.every(n=>t.has(n))}function mit(r,e,t){let n=new Set;for(let o of r.listAll())o.tier===t&&V(o.primary)===V(e)&&n.add(V(o.topicId));return n.size}function F2e(r,e){let t=r.listByTopic(e);return t.length>0?t[0].tier:0}async function git(r,e,t,n,o,s,i,a,c,l,u,d,h,p,f){await Promise.all([Ar(r,e.register,KW(async g=>{let y=Yt(g,f),m=BC(()=>bI(y));if(m!==void 0)return it(tit(t,m,Date.now()),f);let w=BC(()=>vv(y,s));if(w!==void 0)return it(await $2e(w,o,Date.now()),f);let b=xv(y),x=await n(b,void 0,Date.now());return it(x,f)},f)),Ar(r,e.gossip,K2e(async(g,y)=>{u(g),l.deliver(y.toString(),g)},f)),Ar(r,e.promote,K2e(async(g,y)=>{await uit(g,Ms(y),t,a,c,Date.now(),f)},f)),Ar(r,e.membership,KW(async g=>{let y=d.latest();return y!==void 0&&h.cache(p,y),y??new Uint8Array(0)},f)),Ar(r,e.sign,KW(async(g,y)=>{let m=EI(Yt(g,f)),w=await i(m,y.toString());return it(w,f)},f))])}function KW(r,e){return j2e(r,e)}function K2e(r,e){return j2e(async(t,n)=>{await r(t,n)},e)}function j2e(r,e){return(t,n)=>{(async()=>{try{let o=await fo(t,e),s=await r(o,n.remotePeer);s!==void 0&&is(t,s),await t.close()}catch{try{t.abort(new Error("cohort-topic handler error"))}catch{}}})()}}function BC(r){try{return r()}catch{return}}var yit=te("cohort-change-bridge");function bit(r){let e=r.source.onAnyCollectionChange(n=>wit(r,n));return{notifier:{onCollectionChange:(n,o)=>r.source.onCollectionChange(n,o)},unsubscribe:e}}function wit(r,e){try{if(!r.selfIsCohortMember(e))return;let t=r.service.onLocalCommit;if(!t)return;let n=r.extractCommitCert(e);if(!n)return;t(e,n)}catch(t){yit("origination hook threw for collection=%s rev=%d: %o",e.collectionId,e.rev,t)}}function G2e(r,e){let t=bit(e);return r.blockChangeNotifier=t.notifier,t}function OC(r){return He(r)}function W2e(r){let e=r.anchor??Ure(),t=r.addressing??$i(Cn());return n=>{if(n.tailId===void 0)return!1;let o=e.topicId(OC(n.tailId)),s=t.coord0(o);return r.fret.assembleCohort(s,r.wantK).includes(r.selfPeerId)}}Be();Uo();var $W="/optimystic/reactivity/1.0.0",HW=`${$W}/notify`,VW=`${$W}/push-state-gossip`,qW=`${$W}/recover`,Y2e={notify:HW,pushStateGossip:VW,recover:qW};function X2e(r){return[r.notify,r.pushStateGossip,r.recover]}var jW=te("reactivity-notify"),f8=class{node;handlers=new Set;notifyProtocol;maxBytes;selfPeerId;constructor(e,t={}){this.node=e,this.notifyProtocol=t.notifyProtocol??HW,this.maxBytes=t.maxBytes??jt,this.selfPeerId=t.selfPeerId}send(e,t){if(this.selfPeerId!==void 0&&e===this.selfPeerId)return Promise.resolve();try{let n=Kre(t);return n8(this.node,le(e),this.notifyProtocol,n).catch(o=>{jW("send to %s failed (swallowed): %o",e,o)})}catch(n){return jW("dropped a send to %s: %o",e,n),Promise.resolve()}}onNotification(e){return this.handlers.add(e),()=>this.handlers.delete(e)}deliver(e,t){let n;try{n=zre(t,this.maxBytes)}catch(s){jW("dropped an undecodable inbound frame from %s: %o",e,s);return}let o={id:Ms(e)};for(let s of this.handlers)s(o,n)}};function Z2e(r,e,t,n=jt){Ar(r,e,(o,s)=>{(async()=>{try{let i=await fo(o,n);t.deliver(s.remotePeer.toString(),i),await o.close()}catch{try{o.abort(new Error("reactivity notify stream handler error"))}catch{}}})()})}Be();var Uw=te("reactivity-recover");function xit(r){return Zt(j(r))}function Q2e(r){return{signBackfill:e=>V(GU(r,OB(e))),signResume:e=>V(GU(r,FB(e)))}}var h8=class extends Error{redirect;constructor(e){super(`reactivity recover: cohort rotated to tail ${e.newTailId} (effectiveAtRevision ${e.effectiveAtRevision})`),this.name="RotationRedirectError",this.redirect=e}};function eCe(r,e=qW,t=jt){return{exchange:(n,o)=>Mu(r,le(n),e,o,t)}}var p8=class{dialer;selfPeerId;cohortHintCache;resolveCohort;maxBytes;constructor(e){this.dialer=e.dialer,this.selfPeerId=e.selfPeerId,this.cohortHintCache=e.cohortHintCache,this.resolveCohort=e.resolveCohort,this.maxBytes=e.maxBytes??jt}backfillTransport(e,t){return async n=>{let o=zB({v:1,kind:"backfill",backfill:n},this.maxBytes),s=await this.exchange("backfill",o,e,t);if(s.backfillReply===void 0)throw new Error("reactivity recover: backfill reply missing its body");return s.backfillReply}}resumeTransport(e,t){return async n=>{let o=zB({v:1,kind:"resume",resume:n},this.maxBytes),s=await this.exchange("resume",o,e,t);if(s.resumeReply===void 0)throw new Error("reactivity recover: resume reply missing its body");return s.resumeReply}}async exchange(e,t,n,o){let s=this.selectTargets(n,o);if(s.length===0)throw new Error("reactivity recover: no serving cohort target resolved");let i;for(let a of s){let c;try{c=await this.dialer.exchange(a,t)}catch(u){i=u,Uw("recover dial to %s failed, trying next target: %o",a,u);continue}if(c===void 0){i=new _C(`reactivity recover ${e} from ${a}`),Uw("recover %s declined by %s, trying next target",e,a);continue}let l=fne(c,this.maxBytes);if(l.kind==="rotated")throw new h8(l.rotated);if(l.kind!==e)throw new Error(`reactivity recover: reply kind "${l.kind}" does not match request kind "${e}"`);return l}throw i??new Error("reactivity recover: all targets failed")}selectTargets(e,t){let n=new Set,o=[],s=a=>{a===void 0||a===this.selfPeerId||n.has(a)||(n.add(a),o.push(a))},i=this.cohortHintCache.get(t);if(i?.primary!==void 0)try{s(xit(i.primary))}catch(a){Uw("recover: malformed sticky primary for %s, skipping to cohort-walk: %o",t,a)}for(let a of this.resolveCohort(e))s(a);return o}};function J2e(r,e,t,n,o,s){let i=j(n);return Bo(e,t,i)?r.replayGuard.accept(i,Ms(e),o,s)?!0:(Uw("recover serve: replay/stale request from %s (declined)",e),!1):(Uw("recover serve: signature verification failed for %s (declined)",e),!1)}function vit(r,e,t){let n=r.maxBytes??jt,o=r.rotationFor?.({collectionId:e.collectionId},t);if(o!==void 0)return Kv({v:1,kind:"rotated",rotated:o},n);let s=r.pushStateForCollection(e.collectionId);if(s===void 0)return;let i=rne(s.replayBuffer,e,s.collectionId);return Kv({v:1,kind:"backfill",backfillReply:i},n)}function Eit(r,e,t){let n=r.maxBytes??jt,o=ri(j(e.latestKnownTailId)),s=r.rotationFor?.({topicId:o,collectionId:e.collectionId},t);if(s!==void 0)return Kv({v:1,kind:"rotated",rotated:s},n);let i=r.pushStateFor(o)??r.pushStateForCollection(e.collectionId);if(i===void 0)return;let a=cne(e,{buffer:i.replayBuffer,checkpoint:i.checkpoint,inheritedCheckpoint:i.inheritedCheckpoint,currentTailId:i.tailIdAtJoin,currentRevision:i.lastRevision,rotationRevision:i.lastRevision,expectedCollectionId:i.collectionId});return Kv({v:1,kind:"resume",resumeReply:a},n)}function Sit(r){let e=r.maxBytes??jt,t=r.clock??(()=>Date.now());return(n,o)=>{try{let s=dne(n,e),i=o.toString(),a=t();if(s.kind==="backfill"){let l=s.backfill;return l===void 0||!J2e(r,i,OB(l),l.signature,l.timestamp,a)?Promise.resolve(void 0):Promise.resolve(vit(r,l,a))}let c=s.resume;return c===void 0||!J2e(r,i,FB(c),c.signature,c.timestamp,a)?Promise.resolve(void 0):Promise.resolve(Eit(r,c,a))}catch(s){return Uw("recover serve: dropping request (declined): %o",s),Promise.resolve(void 0)}}}function tCe(r,e,t){let n=t.maxBytes??jt;o8(r,e,Sit(t),n)}var NC=te("reactivity-forwarder-host");function GW(r){return ri(j(r.tailId))}function rCe(r,e){let t=[];for(let n of r.records(e))if(n.appState!==void 0){try{Fre(n.appState)}catch{continue}t.push(Zt(n.participantId))}return t}var m8=class{transport;selfPeerId;profile;pushStateInit;verifierFor;directSubscribers;resolveChildPrimary;deliverLocal;clock;served=new Map;ingestTails=new Map;rotationGates=new Map;constructor(e){this.transport=e.transport,this.selfPeerId=e.selfPeerId,this.profile=e.profile,this.pushStateInit=e.pushStateInit,this.verifierFor=e.verifierFor,this.directSubscribers=e.directSubscribers,this.resolveChildPrimary=e.resolveChildPrimary,this.deliverLocal=e.deliverLocal,this.clock=e.clock??(()=>Date.now())}ingest(e,t){let n=this.topicKey(e),s=(this.ingestTails.get(n)??Promise.resolve()).then(()=>this.ingestSerialized(e,t,n),()=>this.ingestSerialized(e,t,n));return this.ingestTails.set(n,s),s}async ingestSerialized(e,t,n){try{let o=this.resolveServed(e,t,n);if(o===null||await o.forwarder.receive(t,this.clock())!=="forward")return;this.fanOut(e,o.pushState,t)}catch(o){NC("ingest failed for topic=%s rev=%d (isolated): %o",n,t.revision,o)}}async onInbound(e,t){let n;try{n=GW(t)}catch(o){NC("onInbound: undecodable tailId on rev=%d (dropped): %o",t.revision,o);return}this.deliverInProcess(n,t),await this.ingest(n,t)}pushStateFor(e){let t=this.served.get(this.topicKey(e));return t?.pushState}livePushStates(){let e=[];for(let t of this.served.values())t!==null&&e.push(t.pushState);return e}pushStateForCollection(e){let t;for(let n of this.served.values())n===null||n.pushState.collectionId!==e||(t===void 0||n.pushState.lastRevision>t.lastRevision)&&(t=n.pushState);return t}markRotated(e,t,n){let o=this.topicKey(e),s=this.rotationGates.get(o);s!==void 0&&t.effectiveAtRevision<=s.rotationRedirect.effectiveAtRevision||this.rotationGates.set(o,new eT({rotatedAt:n,newTailId:t.newTailId,effectiveAtRevision:t.effectiveAtRevision}))}rotationRedirectFor(e,t){let n=this.topicKey(e),o=this.rotationGates.get(n);if(o!==void 0){if(o.isDraining(t))return o.rotationRedirect;this.rotationGates.delete(n),this.served.delete(n),this.ingestTails.delete(n)}}fanOut(e,t,n){let o=this.directSubscribers(e);this.reconcileQueues(t,o),t.enqueueForSubscribers(o,n);for(let s of o){let i=t.perSubscriberQueue.peekQueue(s);if(i!==void 0)for(let a of i.drain())this.deliverTo(e,s,a)}for(let s of t.childCohorts){let i=s.primary??this.resolveChildPrimary?.(s);i!==void 0&&i!==this.selfPeerId&&this.dispatch(i,n)}}reconcileQueues(e,t){let n=new Set(t);for(let o of[...e.perSubscriberQueue.subscribers()])n.has(o)||e.perSubscriberQueue.remove(o)}deliverTo(e,t,n){t===this.selfPeerId?this.deliverInProcess(e,n):this.dispatch(t,n)}deliverInProcess(e,t){if(this.deliverLocal!==void 0)try{this.deliverLocal(e,t)}catch(n){NC("local delivery threw (isolated) for rev=%d: %o",t.revision,n)}}dispatch(e,t){let n;try{n=this.transport.send(e,t)}catch(o){NC("notify send to %s threw synchronously (isolated): %o",e,o);return}n.catch(o=>{NC("notify send to %s rejected (isolated): %o",e,o)})}resolveServed(e,t,n){let o=this.served.get(n);if(o!==void 0)return o;let s=pne(this.profile,this.pushStateInit(e,t));if(s===void 0)return this.served.set(n,null),null;let i={pushState:s,forwarder:Qre({state:s,verifier:this.verifierFor(e)})};return this.served.set(n,i),i}topicKey(e){return V(e)}};var g8=te("reactivity-origination"),y8=class{service;resolveContext;emit;markRotated;blockFill;clock;lastSeenTail=new Map;fillTrackers=new Map;constructor(e){this.service=e.service,this.resolveContext=e.resolveContext,this.emit=e.emit,this.markRotated=e.markRotated,this.blockFill=e.blockFill,this.clock=e.clock??(()=>Date.now())}install(){this.service.onLocalCommit=(e,t)=>this.originate(e,t)}originate(e,t){try{let n=this.resolveContext(e);if(n===void 0)return;this.observeTail(e,n);let o=$re(e,t,{tailId:V(n.tailId),timestamp:this.clock(),deltaMaxBytes:n.deltaMaxBytes,delta:n.delta,rotationHint:n.rotationHint,encodeSigner:s=>V(Ms(s))});this.emit(o)}catch(n){g8("origination failed for collection=%s rev=%d: %o",e.collectionId,e.rev,n)}}observeTail(e,t){try{this.trackBlockFill(e),this.detectTailRotation(e,t)}catch(n){g8("rotation/warm-up observation failed for collection=%s rev=%d (isolated): %o",e.collectionId,e.rev,n)}}trackBlockFill(e){let t=e.collectionId,n=this.fillTrackers.get(t);n===void 0&&(n=new QI(this.blockFill),this.fillTrackers.set(t,n));let o=n.onCommit();o.kind==="warmup"?g8("block-fill warm-up for collection=%s (%d committed, %d remaining) \u2014 anticipatory pre-dial is signal-only on a live node (successor tail not knowable; gated on 6.5-block-id-derivation)",t,o.count,o.remaining):o.kind==="filling"&&g8("block-fill filling commit for collection=%s (%d committed) \u2014 no live pre-announce (successor tail id not knowable; rotation observed on the next commit's tail-id change)",t,o.count)}detectTailRotation(e,t){let n=e.collectionId,o=V(t.tailId),s=this.lastSeenTail.get(n);if(s!==void 0&&s!==o){let i=ri(j(s));this.markRotated?.(i,{newTailId:o,effectiveAtRevision:e.rev},this.clock())}this.lastSeenTail.set(n,o)}};Uo();var UC=te("reactivity-push-state-gossip"),nCe=Number.MAX_SAFE_INTEGER,b8=class{gossipTransport;liveCollections;pushStateForGossip;isCohortMember;intervalMs;maxBytes;onTruncate;timer;stopped=!1;rounding=!1;constructor(e){this.gossipTransport=e.gossipTransport,this.liveCollections=e.liveCollections,this.pushStateForGossip=e.pushStateForGossip,this.isCohortMember=e.isCohortMember,this.intervalMs=e.intervalMs??a8,this.maxBytes=e.maxBytes??jt,this.onTruncate=e.onTruncate}start(){if(this.stopped||this.timer!==void 0)return;let e=setInterval(()=>{this.round()},this.intervalMs);e.unref?.(),this.timer=e}round(){if(!(this.stopped||this.rounding)){this.rounding=!0;try{for(let{pushState:e,cohortCoord:t}of this.liveCollections()){if(this.stopped)break;try{this.broadcastOne(e,t)}catch(n){UC("push-state gossip round failed for a collection (isolated): %o",n)}}}finally{this.rounding=!1}}}deliver(e,t){let n;try{n=Jre(t,this.maxBytes)}catch(s){UC("dropped an undecodable push-state gossip frame from %s: %o",e,s);return}if(this.isCohortMember!==void 0&&!this.isCohortMember(e,n)){UC("dropped push-state gossip from non-member %s for collection=%s topic=%s",e,n.collectionId,n.topicId);return}let o=this.pushStateForGossip(n);if(o!==void 0)try{o.mergeGossip(n)}catch(s){UC("push-state mergeGossip threw (isolated) for collection=%s: %o",n.collectionId,s)}}stop(){this.stopped=!0,this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}broadcastOne(e,t){let n=e.serializeGossip(),{frame:o,kept:s,total:i}=this.boundedFrame(n);s<i&&(UC("push-state gossip frame clipped for collection=%s: kept %d/%d most-recent replay entries to fit maxBytes=%d",n.collectionId,s,i,this.maxBytes),this.onTruncate?.({collectionId:n.collectionId,topicId:n.topicId,kept:s,total:i,frameBytes:o.length,maxBytes:this.maxBytes})),this.gossipTransport.broadcastOver(VW,t,o)}boundedFrame(e){let t=e.replayBuffer.entries.length,n=RB(e,nCe);if(n.length<=this.maxBytes)return{frame:n,kept:t,total:t};let o=0,s=t,i=0,a=this.encodeSlice(e,0);for(;o<=s;){let c=o+s>>>1,l=this.encodeSlice(e,c);l.length<=this.maxBytes?(i=c,a=l,o=c+1):s=c-1}return{frame:a,kept:i,total:t}}encodeSlice(e,t){let n=e.replayBuffer.entries,o=t>=n.length?n:n.slice(n.length-t),s={...e,replayBuffer:{capacity:e.replayBuffer.capacity,entries:o}};return RB(s,nCe)}};function oCe(r,e,t,n=jt){Ar(r,e,(o,s)=>{(async()=>{try{let i=await fo(o,n);t.deliver(s.remotePeer.toString(),i),await o.close()}catch{try{o.abort(new Error("reactivity push-state gossip stream handler error"))}catch{}}})()})}var FC=te("reactivity-rotation-rereg"),sCe=1024;function Cit(r,e){let t=setTimeout(r,e);return t.unref?.(),()=>clearTimeout(t)}var w8=class{reRegister;setTimer;now;pending=new Map;seen=new Set;stopped=!1;constructor(e){this.reRegister=e.reRegister,this.setTimer=e.setTimer??Cit,this.now=e.now??(()=>Date.now())}get pendingCount(){return this.pending.size}get seenCount(){return this.seen.size}schedule(e){if(this.stopped)return;let t=V(e.plan.newTopicId);if(this.seen.has(t)){FC("rotation re-registration already scheduled/fired for successor topic=%s \u2014 ignoring duplicate notice (preAnnounced=%s)",t,e.preAnnounced);return}this.seen.add(t);let n=Math.max(0,e.plan.fireAt-this.now()),o=e.plan,s=this.setTimer(()=>{this.fire(t,o)},n);this.pending.set(t,s),this.evictSeenOverCap(),FC("scheduled rotation re-registration for successor topic=%s in %dms (preAnnounced=%s)",t,n,e.preAnnounced)}cancel(e){if(e===void 0){for(let o of this.pending.values())o();this.pending.clear(),this.seen.clear();return}let t=V(e),n=this.pending.get(t);n!==void 0&&(n(),this.pending.delete(t)),this.seen.delete(t)}stop(){this.stopped=!0;for(let e of this.pending.values())e();this.pending.clear(),this.seen.clear()}evictSeenOverCap(){for(;this.seen.size>sCe;){let e=!1;for(let t of this.seen)if(!this.pending.has(t)){this.seen.delete(t),FC("rotation re-registration ledger at cap (%d) \u2014 evicted oldest fired successor topic=%s",sCe,t),e=!0;break}if(!e)break}}fire(e,t){if(this.pending.delete(e),!this.stopped)try{this.reRegister(t).catch(n=>{FC("rotation re-registration rejected for successor topic=%s (isolated, not retried): %o",e,n)})}catch(n){FC("rotation re-registration threw synchronously for successor topic=%s (isolated): %o",e,n)}}};var iCe=te("reactivity-subscribers"),x8=class{byTopic=new Map;register(e,t){let n=V(e),o=this.byTopic.get(n);return o===void 0&&(o=new Set,this.byTopic.set(n,o)),o.add(t),()=>this.unregister(e,t)}unregister(e,t){let n=V(e),o=this.byTopic.get(n);o!==void 0&&(o.delete(t),o.size===0&&this.byTopic.delete(n))}deliver(e,t){let n=this.byTopic.get(V(e));if(n!==void 0)for(let o of[...n])try{let s=o(t);s instanceof Promise&&s.catch(i=>iCe("subscriber delivery rejected (isolated) for rev=%d: %o",t.revision,i))}catch(s){iCe("subscriber handler threw (isolated) for rev=%d: %o",t.revision,s)}}get topicCount(){return this.byTopic.size}has(e){return this.byTopic.has(V(e))}};async function aCe(r,e){let t=[],n=[];for(let a of e.records){if(a.appState===void 0)continue;let c=Zt(a.participantId),l;try{l=_re(a.appState)}catch(u){e.log?.("matchmaking query handler: skipping undecodable record for %s: %o",c,u);continue}l.kind==="match-provider"?t.push({participantId:c,attachedAt:a.attachedAt,payload:l}):n.push({participantId:c,attachedAt:a.attachedAt,payload:l})}let o=Mre(r,t,n),s={v:1,truncated:o.truncated,cohortEpoch:V(e.cohortEpoch),topicTraffic:e.topicTraffic};o.providers!==void 0&&(s.providers=o.providers),o.seekers!==void 0&&(s.seekers=o.seekers);let i=await e.sign(Lre(s));return{...s,signature:i}}var Ait="/optimystic/matchmaking/1.0.0",WW=`${Ait}/query`,YW={query:WW};function cCe(r){return[r.query]}var XW=te("matchmaking-query");function kit(r){let e=r.maxBytes??jt;return async(t,n)=>{try{let o=Pre(t,e),s=j(o.topicId);if(r.gate!==void 0&&!r.gate(n,s)){XW("matchmaking query serve: rate-limited query from %s (no reply)",n.toString());return}let i=r.addressing.coord0(s),a=r.registry.findServing(s,0)??r.registry.findByCoord(i);if(a===void 0)return;a.recordQuery(s,(r.clock??Date.now)());let c=await aCe(o,{records:a.records(s),topicTraffic:a.topicTraffic(s),cohortEpoch:a.cohort().cohortEpoch,sign:r.sign,log:XW});return Rre(c,e)}catch(o){XW("matchmaking query serve: dropping query (no reply): %o",o);return}}}function lCe(r,e=WW,t){let n=t.maxBytes??jt;o8(r,e,kit(t),n)}var v8=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastSeen=t,n.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.consecutiveFailures++,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastGoodbye=t,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=this.getRecentGoodbyes(this.rapidChurnWindow),t=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return e.length+t.length>=this.rapidChurnThreshold}getUnreachablePeers(){return Array.from(this.peerStatuses.values()).filter(e=>e.consecutiveFailures>=this.unreachableThreshold&&!e.lastGoodbye).map(e=>e.peerId)}getRecentGoodbyes(e){let t=Date.now()-e;return Array.from(this.peerStatuses.values()).filter(n=>n.lastGoodbye&&n.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,n]of this.peerStatuses.entries())n.lastSeen<e&&this.peerStatuses.delete(t)}getStatistics(){let e=this.getUnreachablePeers().length,t=this.getRecentGoodbyes(this.rapidChurnWindow).length;return{totalPeers:this.peerStatuses.size,unreachable:e,recentGoodbyes:t}}reset(){this.peerStatuses.clear()}};function uCe(r,e){let t=r.effectiveSuperMajorityThreshold,n=e.effectiveSuperMajorityThreshold;if(t!==n)throw new Error(`Super-majority threshold mismatch at node startup: cluster member resolved ${t} but coordinator resolved ${n}. Both derive from consensusConfig.superMajorityThreshold (options.clusterPolicy?.superMajorityThreshold ?? DEFAULT_SUPER_MAJORITY_THRESHOLD=${yd}); they must be equal or the coordinator would declare transactions committed on a super-majority the member rejects as final.`)}var E8=te("peer-reputation"),KC=class{peers=new Map;halfLifeMs;thresholds;weights;maxPenaltiesPerPeer;maxPeers;selfPeerId;selfReportsRefused=0;newRecordsRefused=0;constructor(e){this.halfLifeMs=e?.halfLifeMs??30*6e4,this.thresholds={...oS,...e?.thresholds},this.weights={...SF,...e?.weights},this.maxPenaltiesPerPeer=e?.maxPenaltiesPerPeer??100,this.maxPeers=e?.maxPeers??1024,this.selfPeerId=e?.selfPeerId}reportPeer(e,t,n){if(this.refuseSelfReport(e,t,n))return;let o=this.getOrCreateRecord(e);if(!o)return;let s=this.weights[t],i={reason:t,weight:s,timestamp:Date.now(),context:n};o.penalties.push(i),o.lastPenalty=i.timestamp,this.pruneRecord(o);let a=this.computeScore(o);E8("report peerId=%s reason=%s weight=%d score=%d context=%s",e.substring(0,12),t,s,Math.round(a),n??"")}recordSuccess(e){if(this.isSelf(e))return;let t=this.getOrCreateRecord(e);t&&(t.successCount++,t.lastSuccess=Date.now())}getScore(e){let t=this.peers.get(e);return t?this.computeScore(t):0}isBanned(e){return this.getScore(e)>=this.thresholds.ban}isDeprioritized(e){return this.getScore(e)>=this.thresholds.deprioritize}getReputation(e){let t=this.getScore(e),n=this.peers.get(e);return{peerId:e,effectiveScore:t,isBanned:t>=this.thresholds.ban,isDeprioritized:t>=this.thresholds.deprioritize,penaltyCount:n?.penalties.length??0,successCount:n?.successCount??0,lastPenalty:n?.lastPenalty??0,lastSuccess:n?.lastSuccess??0}}getAllReputations(){let e=new Map;for(let t of this.peers.keys())e.set(t,this.getReputation(t));return e}resetPeer(e){this.peers.delete(e),E8("reset peerId=%s",e.substring(0,12))}isSelf(e){return this.selfPeerId!==void 0&&e===this.selfPeerId}refuseSelfReport(e,t,n){return this.isSelf(e)?(this.selfReportsRefused++,E8("refused self-report peerId=%s reason=%s context=%s refused=%d",e.substring(0,12),t,n??"",this.selfReportsRefused),!0):!1}getOrCreateRecord(e){let t=this.peers.get(e);if(t)return t;if(this.peers.size>=this.maxPeers&&!this.evictOne()){this.refuseNewRecord(e);return}let n={penalties:[],successCount:0,lastSuccess:0,lastPenalty:0};return this.peers.set(e,n),n}evictOne(){let e=this.pickEvictionVictim();return e===void 0?!1:(this.peers.delete(e),!0)}pickEvictionVictim(){let e,t=1/0,n=1/0;for(let[o,s]of this.peers){let i=this.computeScore(s);if(i>=this.thresholds.ban)continue;let a=Math.max(s.lastPenalty,s.lastSuccess);(i<t||i===t&&a<n)&&(e=o,t=i,n=a)}return e}refuseNewRecord(e){this.newRecordsRefused++,E8("refused new record, table full of banned peers peerId=%s maxPeers=%d refused=%d",e.substring(0,12),this.maxPeers,this.newRecordsRefused)}computeScore(e){let t=Date.now(),n=0;for(let o of e.penalties)n+=o.weight*this.decayFactor(t,o.timestamp);return n}decayFactor(e,t){let n=e-t;return n<=0?1:Math.pow(.5,n/this.halfLifeMs)}pruneRecord(e){let t=Date.now(),n=this.halfLifeMs*7;e.penalties=e.penalties.filter(o=>t-o.timestamp<n),e.penalties.length>this.maxPenaltiesPerPeer&&(e.penalties=e.penalties.slice(-this.maxPenaltiesPerPeer))}};var Dit=hCe,dCe=128,_it=127,Pit=~_it,Rit=Math.pow(2,31);function hCe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Rit;)e[t++]=r&255|dCe,r/=128;for(;r&Pit;)e[t++]=r&255|dCe,r>>>=7;return e[t]=r|0,hCe.bytes=t-n+1,e}var Lit=ZW,Mit=128,fCe=127;function ZW(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ZW.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&fCe)<<o:(i&fCe)*Math.pow(2,o),o+=7}while(i>=Mit);return ZW.bytes=s-n,t}var Bit=Math.pow(2,7),Oit=Math.pow(2,14),Nit=Math.pow(2,21),Uit=Math.pow(2,28),Fit=Math.pow(2,35),Kit=Math.pow(2,42),zit=Math.pow(2,49),$it=Math.pow(2,56),Hit=Math.pow(2,63),Vit=function(r){return r<Bit?1:r<Oit?2:r<Nit?3:r<Uit?4:r<Fit?5:r<Kit?6:r<zit?7:r<$it?8:r<Hit?9:10},qit={encode:Dit,decode:Lit,encodingLength:Vit},jit=qit,JW=jit;function QW(r,e,t=0){return JW.encode(r,e,t),e}function eY(r){return JW.encodingLength(r)}function pCe(r,e){let t=e.byteLength,n=eY(r),o=n+eY(t),s=new Uint8Array(o+t);return QW(r,s,0),QW(t,s,n),s.set(e,o),new tY(r,t,e,s)}var tY=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Yit=20;function nY({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new rY(r,e,t,n,o)}var rY=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Yit,this.maxDigestLength=s}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?mCe(n,this.code,t?.truncate):n.then(o=>mCe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function mCe(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 pCe(e,r)}function gCe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var oY=nY({name:"sha2-256",code:18,encode:gCe("SHA-256")}),BRr=nY({name:"sha2-512",code:19,encode:gCe("SHA-512")});var Fw={disputeEnabled:!1,disputeArbitrationTimeoutMs:6e4,engineHealthDisputeThreshold:3,engineHealthWindowMs:6e5};var sY=te("engine-health"),zC=class{state={disputesLost:0,recentLosses:[],unhealthy:!1};threshold;windowMs;constructor(e){this.threshold=e?.engineHealthDisputeThreshold??Fw.engineHealthDisputeThreshold,this.windowMs=e?.engineHealthWindowMs??Fw.engineHealthWindowMs}recordDisputeLoss(){let e=Date.now();this.state.recentLosses.push(e),this.pruneOldLosses(e),this.state.disputesLost=this.state.recentLosses.length,sY("dispute-loss-recorded",{recentLosses:this.state.recentLosses.length,threshold:this.threshold,wasUnhealthy:this.state.unhealthy}),this.state.recentLosses.length>=this.threshold&&!this.state.unhealthy&&(this.state.unhealthy=!0,this.state.unhealthySince=e,sY("engine-marked-unhealthy",{disputesLost:this.state.recentLosses.length,threshold:this.threshold,windowMs:this.windowMs}))}isUnhealthy(){return this.pruneOldLosses(Date.now()),this.state.unhealthy&&this.state.recentLosses.length<this.threshold&&(this.state.unhealthy=!1,this.state.unhealthySince=void 0,sY("engine-auto-recovered",{recentLosses:this.state.recentLosses.length,threshold:this.threshold})),this.state.unhealthy}getState(){return this.pruneOldLosses(Date.now()),{...this.state}}reset(){this.state={disputesLost:0,recentLosses:[],unhealthy:!1}}pruneOldLosses(e){let t=e-this.windowMs;this.state.recentLosses=this.state.recentLosses.filter(n=>n>t),this.state.disputesLost=this.state.recentLosses.length}};var jn=te("dispute"),$C=class r{peerId;privateKey;createDisputeClient;reputation;revalidate;config;engineHealth;selectArbitrators;onInvalidation;activeDisputes=new Map;resolvedDisputes=new Map;resolvedChallenges=new Map;disputedTransactions=new Set;invalidatedTransactions=new Set;constructor(e){this.peerId=e.peerId,this.privateKey=e.privateKey,this.createDisputeClient=e.createDisputeClient,this.reputation=e.reputation,this.revalidate=e.revalidate,this.config={...Fw,...e.config},this.engineHealth=new zC(this.config),this.selectArbitrators=e.selectArbitrators,this.onInvalidation=e.onInvalidation}getEngineHealth(){return this.engineHealth}isEnabled(){return this.config.disputeEnabled}getDisputeStatus(e){for(let[,t]of this.activeDisputes)if(t.originalMessageHash===e)return"committed-disputed";for(let[,t]of this.resolvedDisputes){let n=this.findChallengeForDispute(t.disputeId);if(n&&n.originalMessageHash===e)return t.outcome==="challenger-wins"?"committed-invalidated":t.outcome==="majority-wins"?"committed-validated":"committed-disputed"}}async initiateDispute(e,t){if(!this.config.disputeEnabled){jn("dispute-disabled",{messageHash:e.messageHash});return}if(this.disputedTransactions.has(e.messageHash)){jn("dispute-already-initiated",{messageHash:e.messageHash});return}if(this.engineHealth.isUnhealthy()){jn("dispute-skipped-unhealthy",{messageHash:e.messageHash});return}this.disputedTransactions.add(e.messageHash);let n=Date.now(),o=await this.computeDisputeId(e.messageHash,this.peerId.toString(),n),s=await this.signDispute(o),i=e.message.expiration?(e.message.expiration-Date.now())*2:this.config.disputeArbitrationTimeoutMs*2,a=n+Math.max(i,this.config.disputeArbitrationTimeoutMs),l=(e.message.coordinatingBlockIds??[])[0]??e.messageHash,u=Object.keys(e.peers),d=this.config.arbitratorCount??u.length,h=0,p=await this.computeEpochBytes(u),f;try{f=await this.selectArbitrators(l,u,d,h,p)}catch(b){jn("dispute-arbitrator-selection-failed",{disputeId:o,error:b instanceof Error?b.message:String(b)});return}if(f.length===0){jn("dispute-no-arbitrators",{disputeId:o});return}let g=f.map(b=>b.toString()),y={disputeId:o,originalMessageHash:e.messageHash,originalRecord:e,challengerPeerId:this.peerId.toString(),challengerEvidence:t,signature:s,timestamp:n,expiration:a,arbitratorSet:g};this.activeDisputes.set(o,y),jn("dispute-initiated",{disputeId:o,messageHash:e.messageHash});let m=await this.collectVotes(y,f),w=await this.resolveDispute(y,m);return this.resolvedChallenges.set(o,y),this.activeDisputes.delete(o),this.resolvedDisputes.set(o,w),this.applyReputationEffects(w,e),await this.maybeInvalidate(w,e,g),await this.broadcastResolution(w,f,u),jn("dispute-resolved",{disputeId:o,outcome:w.outcome,votes:m.length,affectedPeers:w.affectedPeers.length}),w}async handleChallenge(e){jn("dispute-handle-challenge",{disputeId:e.disputeId});let t=await this.computeChallengeTargetHash(e),n=await zE(e.arbitratorSet??[]);if(!await this.verifyDisputeSignature(e.disputeId,e.signature,e.challengerPeerId,e.originalRecord.peers[e.challengerPeerId]?.publicKey))return jn("dispute-invalid-challenge-signature",{disputeId:e.disputeId}),this.makeVote(e.disputeId,"inconclusive",{computedHash:"",engineId:"unknown",schemaHash:"",blockStateHashes:{}},t,n);let s;if(this.revalidate)try{s=await this.revalidate(e.originalRecord)}catch(a){jn("dispute-revalidation-failed",{disputeId:e.disputeId,error:a instanceof Error?a.message:String(a)})}if(!s)return this.makeVote(e.disputeId,"inconclusive",{computedHash:"",engineId:"unknown",schemaHash:"",blockStateHashes:{}},t,n);let i;return s.computedHash===e.challengerEvidence.computedHash?i="agree-with-challenger":i="agree-with-majority",this.makeVote(e.disputeId,i,s,t,n)}async computeChallengeTargetHash(e){let t=r.extractInvalidationTarget(e.originalRecord),n=t?{invalidatedActionId:t.actionId,blockIds:t.blockIds}:{invalidatedActionId:"",blockIds:[]};return KE(e.originalRecord.messageHash,n)}handleResolution(e){this.resolvedDisputes.set(e.disputeId,e),jn("dispute-resolution-received",{disputeId:e.disputeId,outcome:e.outcome});let t=this.peerId.toString(),n=e.affectedPeers.find(o=>o.peerId===t);n&&n.reason==="false-approval"&&this.engineHealth.recordDisputeLoss()}async collectVotes(e,t){let n=this.config.disputeArbitrationTimeoutMs,o=[],s=t.map(async a=>{try{return await this.createDisputeClient(a).sendChallenge(e,n)}catch(c){jn("dispute-vote-collection-failed",{disputeId:e.disputeId,arbitrator:a.toString(),error:c instanceof Error?c.message:String(c)});return}}),i=await Promise.allSettled(s);for(let a of i)a.status==="fulfilled"&&a.value&&o.push(a.value);return o}async resolveDispute(e,t){let n=t.filter(l=>l.vote==="agree-with-challenger").length,o=t.filter(l=>l.vote==="agree-with-majority").length,s=n+o,i=Math.ceil(s*2/3),a,c=[];if(s===0)a="inconclusive";else if(n>=i){a="challenger-wins";let l=e.originalRecord,u=await this.computePromiseHash(l);for(let[d,h]of Object.entries(l.promises))h.type==="approve"&&d!==e.challengerPeerId&&(await this.verifyPromiseSignature(l,d,u,h)?c.push({peerId:d,reason:"false-approval"}):jn("dispute-skip-unverified-approval",{disputeId:e.disputeId,peerId:d}))}else o>=i?(a="majority-wins",c.push({peerId:e.challengerPeerId,reason:"dispute-lost"})):a="inconclusive";return{disputeId:e.disputeId,outcome:a,votes:t,affectedPeers:c,timestamp:Date.now()}}applyReputationEffects(e,t){if(this.reputation){for(let n of e.affectedPeers)n.reason==="false-approval"?this.reputation.reportPeer(n.peerId,Qe.FalseApproval,`dispute:false-approval:${e.disputeId}`):n.reason==="dispute-lost"&&this.reputation.reportPeer(n.peerId,Qe.DisputeLost,`dispute:dispute-lost:${e.disputeId}`);if(e.outcome==="challenger-wins"){let n=this.peerId.toString();e.affectedPeers.some(o=>o.peerId===n)&&this.engineHealth.recordDisputeLoss()}}}async maybeInvalidate(e,t,n){if(e.outcome!=="challenger-wins"||!this.onInvalidation||this.invalidatedTransactions.has(t.messageHash))return;let o=r.extractInvalidationTarget(t);if(!o){jn("dispute-invalidation-no-target",{disputeId:e.disputeId,messageHash:t.messageHash});return}let s={invalidatedActionId:o.actionId,blockIds:o.blockIds},i=await KE(t.messageHash,s),a=await zE(n),c=await this.signArbitratorSet(e.disputeId,i,a);this.invalidatedTransactions.add(t.messageHash);let l={invalidatedActionId:o.actionId,invalidatedRev:o.rev,blockIds:o.blockIds,collectionId:o.collectionId,resolution:WU(e,t.messageHash,{arbitratorSet:n,challengerPeerId:this.peerId.toString(),arbitratorSetSignature:c})};try{await this.onInvalidation(l),jn("dispute-invalidation-originated",{disputeId:e.disputeId,invalidatedActionId:o.actionId,blockCount:o.blockIds.length})}catch(u){this.invalidatedTransactions.delete(t.messageHash),jn("dispute-invalidation-originate-failed",{disputeId:e.disputeId,error:u instanceof Error?u.message:String(u)})}}static extractInvalidationTarget(e){for(let t of e.message.operations)if("commit"in t){let n=t.commit;return{actionId:n.actionId,rev:n.rev,blockIds:n.blockIds,collectionId:n.headerId??e.message.coordinatingBlockIds?.[0]??n.blockIds[0]}}for(let t of e.message.operations)if("pend"in t){let n=t.pend,o=It(n.transforms);return{actionId:n.actionId,rev:n.rev??0,blockIds:o,collectionId:e.message.coordinatingBlockIds?.[0]??o[0]}}}async broadcastResolution(e,t,n){let o=new Set;for(let i of t)o.add(i.toString());for(let i of n)o.add(i);o.delete(this.peerId.toString());let s=Array.from(o).map(async i=>{try{let{peerIdFromString:a}=await Promise.resolve().then(()=>(Be(),bae));await this.createDisputeClient(a(i)).sendResolution(e)}catch(a){jn("dispute-broadcast-failed",{disputeId:e.disputeId,peer:i,error:a instanceof Error?a.message:String(a)})}});await Promise.allSettled(s)}async makeVote(e,t,n,o,s){let i=E6(e,t,n.computedHash,o,s),a=await this.privateKey.sign(i);return{version:Oy,disputeId:e,arbitratorPeerId:this.peerId.toString(),vote:t,evidence:n,signature:z(a,"base64url")}}async computeEpochBytes(e){let t=[...e].sort().join(",");return(await oY.digest(new TextEncoder().encode(t))).digest}async computeDisputeId(e,t,n){let o=`${e}+${t}+${n}`,s=new TextEncoder().encode(o),i=await oY.digest(s);return gT.encode(i.digest)}async signDispute(e){let t=new TextEncoder().encode(e),n=await this.privateKey.sign(t);return z(n,"base64url")}async signArbitratorSet(e,t,n){let o=await this.privateKey.sign(S6(e,t,n));return z(o,"base64url")}async verifyDisputeSignature(e,t,n,o){if(!o?.length)return!1;try{let s=typeof o=="string"?K(o,"base64url"):o;if(!nS(n,s))return!1;let i=np(s),a=new TextEncoder().encode(e),c=K(t,"base64url");return i.verify(a,c)}catch{return!1}}async computePromiseHash(e){return bh(e.messageHash,e.message,mg(e))}async verifyPromiseSignature(e,t,n,o){let s=e.peers[t]?.publicKey;if(!s?.length)return!1;try{let i=typeof s=="string"?K(s,"base64url"):s;if(!nS(t,i))return!1;let a=np(i),c=pg(n,o),l=K(o.signature,"base64url");return a.verify(c,l)}catch{return!1}}findChallengeForDispute(e){return this.activeDisputes.get(e)??this.resolvedChallenges.get(e)}};var HC=class r extends ai{protocol;constructor(e,t,n){super(e,t),this.protocol=(n??"/db-p2p")+"/dispute/1.0.0"}static create(e,t,n){return new r(e,t,n)}async sendChallenge(e,t){let n={type:"challenge",challenge:e},o=t?new AbortController:void 0,s=o?setTimeout(()=>o.abort(),t):void 0;try{return(await this.processMessage(n,this.protocol,{signal:o?.signal,dialTimeoutMs:3e3,maxDataLength:1048576})).vote}finally{s&&clearTimeout(s)}}async sendResolution(e,t){let n={type:"resolution",resolution:e};await this.processMessage(n,this.protocol,{...Ry(t),maxDataLength:1048576})}};function yCe(r){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,r>>>0,!0),e}function Zit(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function bCe(r,e,t,n){return Zit([r,yCe(e),t,yCe(n)])}async function iY(r,e,t){let{blockId:n,round:o,epoch:s,count:i,exclude:a}=r,c=[];if(i<=0)return c;let l=new Set(a);for(let u=0;c.length<i;u++){let d=await t(bCe(n,o,s,u)),h=l.size+1,p=-1,f,g=!1;for(;;){let y=await e(d,h),m=y.find(w=>!l.has(w));if(m!==void 0){f=m;break}if(y.length<h||y.length<=p){g=!0;break}p=y.length,h*=2}if(f!==void 0)c.push(f),l.add(f);else if(g)break}return c}var Jit=te("reactivity-node-wiring"),Kw=te("node-wiring");function Qit(r,e){if(!r)return{storage:new Vs,lease:void 0};let t=typeof r=="function"?r():r;return r_(t,`node:${e}`)}function eat(r){return r!==void 0?typeof r=="function"?r():r:(Kw("WARN: no kvStore supplied \u2014 using an in-memory store. The under-replication ledger (blocks this node acknowledged before every cohort member held them) will NOT survive a restart, so copies owed at shutdown are never sent. Supply NodeOptions.kvStore (e.g. FileKVStore) to keep it."),new e8)}function tat(r){if(!r)return;let e=r;return typeof e.ensure=="function"?e.ensure():r}function rat(r,e){let t=r.pushStateForCollection(e);return t===void 0?void 0:j(t.topicId)}async function wCe(r,e){let{storage:t,lease:n}=Qit(r.storage,r.networkName),o=eat(r.kvStore),s=new YD(o),i=async(R,k)=>{},a=new Dl(R=>new mc(R,t,i)),c,l,u,d={async update(R){if(!c)throw new Error("ClusterMember not initialized");return await c.update(R)}},h=Dge(a,()=>l),p={...r.authorizeInboundStream?{authorizeInboundStream:r.authorizeInboundStream}:{},...r.authorizeInboundStreamTimeoutMs!==void 0?{authorizeInboundStreamTimeoutMs:r.authorizeInboundStreamTimeoutMs}:{}},f=r.privateKey??await L6("Ed25519"),g=x2e(r.listenAddrs??e.listenAddrs);S2e(g.supervisedRelays,r.announceAddrs);let y=g.listenAddrs,m=r.transports??e.transports,w=r.cohortTopic?.enabled===!0,b=r.cohortTopic?.wantK??16,x=w?pce():void 0,S=x?(R,k)=>{x.put(R,k),r.onCommitCertificate?.(R,k)}:r.onCommitCertificate,T=X6(r),A,v=R=>A?.(R),C={start:!1,privateKey:f,addresses:{listen:y,...r.announceAddrs?{announce:r.announceAddrs}:{},...r.appendAnnounceAddrs?{appendAnnounce:r.appendAnnounceAddrs}:{}},connectionManager:{maxConnections:16,inboundUpgradeTimeout:1e4},...r.connectionGater?{connectionGater:r.connectionGater}:{},transports:m,connectionEncrypters:[fve({crypto:r.noiseCrypto})],connectionMonitor:r.connectionMonitor,streamMuxers:[xve()],services:{identify:dEe({protocolPrefix:`optimystic/${r.networkName}`}),identifyPush:fEe({protocolPrefix:`optimystic/${r.networkName}`}),ping:yEe(),dcutr:WSe(),autoNAT:z1e(),...r.relay?{relay:m2e(r.relayServerInit)}:{},cluster:R=>{let k=te("peer-address-book",R.peerId?.toString());return Xle({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1,...p})({registrar:R.registrar,cluster:d,peerId:R.peerId,getConnectionAddrs:async E=>{if(!u)return[];let D=u.getConnections?.(E)??[];return await Py(u,D,E,k)},recordPeerAddresses:(E,D)=>{u&&w6(u,E,D,k)}})},repo:R=>_ge({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1,...p})({registrar:R.registrar,repo:h}),sync:R=>Nge({protocolPrefix:`/optimystic/${r.networkName}`,...p})({registrar:R.registrar,repo:h}),blockTransfer:R=>vge({protocolPrefix:`/optimystic/${r.networkName}`,...r.blockTransfer?.requirePushCertificate!==void 0?{requirePushCertificate:r.blockTransfer.requirePushCertificate}:{},...p})({registrar:R.registrar,repo:a,superMajorityThreshold:T.superMajorityThreshold,onBlockHolders:v}),networkManager:R=>{let I=b2e({clusterSize:T.clusterSize,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(R);try{I.setLibp2p(R.libp2p)}catch(E){Kw("networkManager in-factory setLibp2p failed (proxy); real node injected post-construction: %o",E)}return I},fret:R=>{let I=KD({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(R);try{I.setLibp2p(R.libp2p)}catch(E){Kw("fret in-factory setLibp2p failed (proxy); real node injected post-construction: %o",E)}return I}},peerDiscovery:[...r.bootstrapNodes?.length?[$1e({list:r.bootstrapNodes})]:[]]},P=await nxe(C);if(u=P,n){let R=P.stop.bind(P);P.stop=async()=>{try{await R()}finally{await n.release()}}}let F=P.services;F.fret.setLibp2p(P),F.networkManager.setLibp2p(P),F.repo.setLibp2p(P),E2e(P,g.supervisedRelays),await P.start();try{if(g.supervisedRelays.length>0){let fe=C2e(P,g.supervisedRelays),Ce=P.stop.bind(P);P.stop=async()=>{try{fe.stop()}finally{await Ce()}},await fe.awaitFirstDrives()}let R=new KC({selfPeerId:P.peerId.toString()}),k=(r.bootstrapNodes?.length??0)>0?"joining":"forming",I=`/optimystic/${r.networkName}`,E=new Qb(P,T.clusterSize,void 0,k,r.persistence,R,I);await E.initFromPersistedState();let D=fe=>Ly.create(fe,E,I);F.networkManager.setReputation(R);let M=new v8,B=P.services?.fret,L=async(fe,Ce)=>{let Ve;try{Ve=le(fe)}catch{return}if(Ve.equals(P.peerId))return;let Er=new _p(Ve,E,I),Rt;try{let Sr=await Promise.race([Er.requestBlock({blockId:Ce,rev:void 0}),new Promise(or=>{Rt=setTimeout(()=>or({success:!1}),T.cohortQueryTimeoutMs),Rt.unref()})]);return Sr.success?Sr.archive:void 0}catch{return}finally{Rt!==void 0&&clearTimeout(Rt)}},O=W6({selfPeerId:P.peerId.toString(),fetchArchive:L,saveReplicatedBlock:(fe,Ce,Ve,Er)=>a.saveReplicatedBlock(fe,Ce,Ve,Er),simpleMajorityThreshold:T.simpleMajorityThreshold,superMajorityThreshold:T.superMajorityThreshold,repairCorroborationClusterSize:T.repairCorroborationClusterSize,reputation:R,onBlockHolders:v}),U=async fe=>{let Ce=await E.findCluster(He(fe)),Ve=0;if(B)try{Ve=B.getNetworkSizeEstimate().confidence}catch{}return{peers:Ce??{},confidence:Ve}};c=J6({storageRepo:a,peerNetwork:E,peerId:P.peerId,privateKey:f,protocolPrefix:I,partitionDetector:M,fretService:B,validator:r.validator,reputation:R,consensusConfig:T,stateStore:r.transactionStateStore,reconcileBlock:O,onCommitCertificate:S,onBlockHolders:v,deriveExpectedCluster:U});{let fe=P.stop.bind(P);P.stop=async()=>{try{c.dispose()}finally{await fe()}}}let $=WD(E,D,{...T},B,R,r.transactionStateStore),J=async(fe,Ce,Ve)=>{if(fe.equals(P.peerId))try{let or=(await a.get({blockIds:[Ce],context:Ve}))[Ce]?.state?.latest;if(!or)return;let Co=await sp(a,Ce,or);return Co?{...or,proof:Co}:or}catch{return}let Rt=await new _p(fe,E,I).requestBlock({blockId:Ce,rev:void 0});if(Rt.success&&Rt.archive){let Sr=Hle(Rt.archive);if(Sr)return Sr}};l=$({storageRepo:a,localCluster:c,localPeerId:P.peerId,clusterLatestCallback:J,acquireBlockFromCohort:O,underReplicationLedger:s,onBlockHolders:v}),uCe(c,l),r.transactionStateStore&&(await c.recoverTransactions(),await l.recoverTransactions());let X=P.services?.networkManager;y2e(T.clusterSize,{keyNetwork:E,networkManager:X});let N=new Set,H,Z=()=>{H||(H=a.onAnyCollectionChange(fe=>{for(let Ce of fe.blockIds)N.add(Ce)}))};{let fe=P.stop.bind(P);P.stop=async()=>{try{H?.()}finally{await fe()}}}let ae;if(X&&(r.spreadOnChurn?.enabled??!0)!==!1)try{ae=X.initSpreadOnChurnMonitor(M,a,E,T.clusterSize,I,N,r.spreadOnChurn),await ae.start(),Z()}catch(fe){Kw("spread-on-churn init failed: %o",fe)}P.spreadOnChurnMonitor=ae;{let fe=P.stop.bind(P);P.stop=async()=>{try{ae&&await ae.stop()}finally{await fe()}}}let Q;if((r.underReplicationDrain?.enabled??!0)!==!1){let{enabled:fe,pushDialTimeoutMs:Ce,pushResponseTimeoutMs:Ve,...Er}=r.underReplicationDrain??{};Q=new XD({libp2p:P,ledger:s,keyNetwork:E,partitionDetector:M,protocolPrefix:I,pushBlock:(Sr,or)=>qb(a,E,Sr,or,{reason:"replication",protocolPrefix:I,dialTimeoutMs:Ce??3e3,responseTimeoutMs:Ve??1e4}),emit:Sr=>a.emitBlockDurabilityReached(Sr)},Er),await Q.start();let Rt=P.stop.bind(P);P.stop=async()=>{try{await Q.stop()}finally{await Rt()}}}if(P.underReplicationDrain=Q,P.underReplicationLedger=s,r.arachnode?.enableRingZulu??!0){let fe=te("node-wiring:arachnode"),Ce=P.services?.fret;if(Ce){let Ve=new a_(Ce,P.peerId.toString()),Er=new Set;P.gcEligibleBlocks=Er;let Rt,Sr=new i_(t,r.arachnode?.storage??{}),or=new s_(Ve,Sr,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4},smoothingAlpha:.2,deadband:.5,minDwellMs:600*1e3}),Co=P.peerId.toString(),ce=await or.createArachnodeInfo(Co);Ve.setArachnodeInfo(ce),fe("Announced Arachnode membership: Ring %d",ce.ringDepth);let Ke=new o_(Ve,E,`/optimystic/${r.networkName}`,P.peerId.toString()),_e=async(bt,Ft)=>await Ke.restore(bt,Ft);if(a.createBlockStorage=bt=>new mc(bt,t,_e),X&&(r.rebalance?.enabled??!0)!==!1)try{let bt=new VD(a,E,M,I),Ft=X.initRebalanceMonitor(M,Ve,N,E,r.rebalance);await Ft.start(),A=Rr=>Ft.recordBlockHolders(Rr),Ft.onRebalance(Rr=>{bt.handleRebalanceEvent(Rr).then(Es=>{for(let Ta of Es.released)Ft.untrackBlock(Ta),Er.add(Ta);for(let[Ta,x3]of Es.growth)Ft.recordGrowthOutcome(Ta,x3);if(Es.underReplicated.length>0){let Ta=Ft.getGrowthDiagnostics();fe("cohort-growth: %d of %d grown blocks not confirmed on new peers this pass (awaiting-confirmation=%d given-up-pairs=%d)",Es.underReplicated.length,Rr.grown.size,Ta.blocksAwaitingConfirmation,Ta.abandonedPairs)}}).catch(Es=>{fe("rebalance reaction failed: %o",Es)})}),Rt=new r8({fretAdapter:Ve,ringSelector:or,fret:Ce,partitionDetector:M,confirmer:bt,ownedBlocks:N,selfPeerId:Co,getFloor:()=>Ft.getCohortSize(),onRelease:Rr=>{for(let Es of Rr)Ft.untrackBlock(Es),Er.add(Es)}}),Rt.reconcileOnStart(),Z(),P.rebalanceMonitor=Ft,P.blockTransferCoordinator=bt,P.ringShiftCoordinator=Rt;let nh=P.stop.bind(P);P.stop=async()=>{try{await Ft.stop()}finally{await nh()}}}catch(bt){fe("rebalance wiring init failed: %o",bt)}let yt=setInterval(async()=>{if(!Rt)return;let bt=await or.shouldTransition();if(bt.shouldMove&&bt.direction&&bt.newRingDepth!==void 0){fe("Ring transition needed: moving %s to Ring %d",bt.direction,bt.newRingDepth);try{let Ft=await Rt.executeShift({direction:bt.direction,newRingDepth:bt.newRingDepth});fe("Ring shift outcome: %o",Ft)}catch(Ft){fe("Ring shift failed: %o",Ft)}finally{or.recordShiftSettled()}}},6e4),xn=P.stop.bind(P);P.stop=async()=>{clearInterval(yt),await xn()}}else fe("FRET service not available, Arachnode disabled")}if(H&&typeof t.listBlockIds=="function"){let fe=!1,Ce=P.stop.bind(P);P.stop=async()=>{fe=!0,await Ce()},g2e(t,N,()=>fe).catch(Ve=>{Kw("owned-block-seed seed failed: %o",Ve)})}let Fe;if(r.dispute?.disputeEnabled){let fe=Ce=>HC.create(Ce,E,I);Fe=new $C({peerId:P.peerId,privateKey:f,peerNetwork:E,createDisputeClient:fe,reputation:R,validator:r.validator,config:r.dispute,selectArbitrators:async(Ce,Ve,Er,Rt,Sr)=>{let{hashKey:or}=await Promise.resolve().then(()=>(Uo(),wge)),Co=P.services?.fret;if(!Co)return[];let ce=new Set(Ve);return ce.add(P.peerId.toString()),(await iY({blockId:new TextEncoder().encode(Ce),round:Rt,epoch:Sr,count:Er,exclude:ce},(_e,yt)=>Co.assembleCohort(_e,yt),or)).map(_e=>le(_e))}})}if(Object.assign(P,{coordinatedRepo:l,storageRepo:a,blockChangeNotifier:a,keyNetwork:E,reputation:R,disputeService:Fe,peerPrivateKey:f}),w){let fe=tat(B);if(!fe)throw new Error("cohortTopic enabled but the FRET service is unavailable on the node");let Ce=await z2e(P,fe,{...r.cohortTopic.host??{},antiDos:{reputation:R,...r.cohortTopic.host?.antiDos},privateKey:f,wantK:b}),Ve=Y2e,Er=YW,Rt,Sr,or,Co;{let qe=P.stop.bind(P);P.stop=async()=>{try{Co?.stop(),or?.stop(),Sr?.(),await P.unhandle(X2e(Ve)),await P.unhandle(cCe(Er)),Rt?.(),await Ce.stop()}finally{await qe()}}}let ce=W2e({fret:fe,selfPeerId:P.peerId.toString(),wantK:b});Rt=G2e(P,{source:a,service:Ce.service,selfIsCohortMember:ce,extractCommitCert:mce(x)}).unsubscribe,P.cohortTopicHost=Ce;let Ke=P.peerId.toString(),_e=Ce.profile,yt=mne(_e),xn=$i(Cn()),bt=0,Ft=new x8;P.reactivitySubscribers=Ft;let nh=new f8(P,{selfPeerId:Ke}),Rr=new m8({transport:nh,selfPeerId:Ke,profile:_e,pushStateInit:(qe,Hr)=>({collectionId:Hr.collectionId,topicId:V(qe),tailIdAtJoin:Hr.tailId,deltaMaxBytes:yt.deltaMaxBytes}),verifierFor:()=>MB({verifier:Ce.service.verifier(),tier:Qn.T3}),directSubscribers:qe=>{let Hr=Ce.registry.findServing(qe,bt);return Hr===void 0?[]:rCe(Hr,qe)},resolveChildPrimary:qe=>{let Hr=fe.assembleCohort(j(qe.coord),b);return Hr.length>0?Hr[0]:void 0},deliverLocal:(qe,Hr)=>Ft.deliver(qe,Hr)});Z2e(P,Ve.notify,nh),Sr=nh.onNotification((qe,Hr)=>{Rr.onInbound(qe,Hr)}),new y8({service:Ce.service,resolveContext:qe=>{if(qe.tailId!==void 0)return{tailId:OC(qe.tailId),deltaMaxBytes:yt.deltaMaxBytes}},emit:qe=>{Rr.ingest(GW(qe),qe)},markRotated:(qe,Hr,BA)=>Rr.markRotated(qe,Hr,BA)}).install(),or=new b8({gossipTransport:Ce.gossipTransport,liveCollections:()=>Rr.livePushStates().map(qe=>({pushState:qe,cohortCoord:xn.coord0(j(qe.topicId))})),pushStateForGossip:qe=>Rr.pushStateFor(j(qe.topicId)),isCohortMember:(qe,Hr)=>fe.assembleCohort(xn.coord0(j(Hr.topicId)),b).includes(qe)}),oCe(P,Ve.pushStateGossip,or),or.start();let Ta=KB(),x3=qe=>fe.assembleCohort(xn.coord0(qe),b),kke=new p8({dialer:eCe(P,Ve.recover),selfPeerId:Ke,cohortHintCache:Ta,resolveCohort:x3});tCe(P,Ve.recover,{pushStateFor:Rr.pushStateFor.bind(Rr),pushStateForCollection:Rr.pushStateForCollection.bind(Rr),replayGuard:DI(),rotationFor:(qe,Hr)=>{let BA=qe.topicId??rat(Rr,qe.collectionId);return BA===void 0?void 0:Rr.rotationRedirectFor(BA,Hr)}});let Dke=Q2e(f);P.reactivityRecover=kke,P.reactivityRecoverSigners=Dke,P.reactivityCohortHintCache=Ta,Co=new w8({reRegister:qe=>(Jit("reactivity rotation re-registration fired for successor topic=%s (lastRevision=%d) but no subscribe factory is wired yet \u2014 deferred to optimystic-network-reactive-watch-integration-test",V(qe.newTopicId),qe.lastRevision),Promise.resolve())}),P.reactivityRotation=Co,lCe(P,Er.query,{registry:Ce.registry,addressing:xn,sign:async qe=>V(await Bs(f,qe))})}return P}catch(R){try{await P.stop()}catch(k){Kw("rollback stop failed after startup error: %o",k)}throw R}}async function S8(r){let e=r.transports;if(!e||e.length===0)throw new Error("createLibp2pNode (RN) requires options.transports. Provide an RN-compatible transport (e.g. WebSockets) and any required listenAddrs.");return await wCe(r,{listenAddrs:[],transports:e})}var T8r=te("network:get-manager");var K8r=te("cascade");var GLr=te("reactivity-subscription");var Bu=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Si=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},C8=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var A8=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}};var I8=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var zf=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},VC=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var T8=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},k8=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var D8=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var _8=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},am=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var qC=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var P8=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},zw=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},R8=class extends zw{constructor(e,t){super(!0,e,t)}},L8=class extends zw{constructor(e,t){super(!1,e,t)}};var aY=Symbol.for("@libp2p/peer-id");var xCe="keep-alive";function vCe(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ECe(...r){let e=[];for(let t of r)vCe(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 SCe(...r){let e=[];for(let t of r)vCe(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 M8=Symbol.for("@libp2p/transport");var CCe;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(CCe||(CCe={}));var Ci=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 o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var B8=Symbol.for("@libp2p/service-capabilities"),ACe=Symbol.for("@libp2p/service-dependencies");function zr(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 pn(r=0){return new Uint8Array(r)}function gs(r=0){return new Uint8Array(r)}var iat=Math.pow(2,7),aat=Math.pow(2,14),cat=Math.pow(2,21),cY=Math.pow(2,28),lY=Math.pow(2,35),uY=Math.pow(2,42),dY=Math.pow(2,49),dt=128,vo=127;function Gt(r){if(r<iat)return 1;if(r<aat)return 2;if(r<cat)return 3;if(r<cY)return 4;if(r<lY)return 5;if(r<uY)return 6;if(r<dY)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ai(r,e,t=0){switch(Gt(r)){case 8:e[t++]=r&255|dt,r/=128;case 7:e[t++]=r&255|dt,r/=128;case 6:e[t++]=r&255|dt,r/=128;case 5:e[t++]=r&255|dt,r/=128;case 4:e[t++]=r&255|dt,r>>>=7;case 3:e[t++]=r&255|dt,r>>>=7;case 2:e[t++]=r&255|dt,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lat(r,e,t=0){switch(Gt(r)){case 8:e.set(t++,r&255|dt),r/=128;case 7:e.set(t++,r&255|dt),r/=128;case 6:e.set(t++,r&255|dt),r/=128;case 5:e.set(t++,r&255|dt),r/=128;case 4:e.set(t++,r&255|dt),r>>>=7;case 3:e.set(t++,r&255|dt),r>>>=7;case 2:e.set(t++,r&255|dt),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function fY(r,e){let t=r[e],n=0;if(n+=t&vo,t<dt||(t=r[e+1],n+=(t&vo)<<7,t<dt)||(t=r[e+2],n+=(t&vo)<<14,t<dt)||(t=r[e+3],n+=(t&vo)<<21,t<dt)||(t=r[e+4],n+=(t&vo)*cY,t<dt)||(t=r[e+5],n+=(t&vo)*lY,t<dt)||(t=r[e+6],n+=(t&vo)*uY,t<dt)||(t=r[e+7],n+=(t&vo)*dY,t<dt))return n;throw new RangeError("Could not decode varint")}function uat(r,e){let t=r.get(e),n=0;if(n+=t&vo,t<dt||(t=r.get(e+1),n+=(t&vo)<<7,t<dt)||(t=r.get(e+2),n+=(t&vo)<<14,t<dt)||(t=r.get(e+3),n+=(t&vo)<<21,t<dt)||(t=r.get(e+4),n+=(t&vo)*cY,t<dt)||(t=r.get(e+5),n+=(t&vo)*lY,t<dt)||(t=r.get(e+6),n+=(t&vo)*uY,t<dt)||(t=r.get(e+7),n+=(t&vo)*dY,t<dt))return n;throw new RangeError("Could not decode varint")}function ICe(r,e,t=0){return e==null&&(e=gs(Gt(r))),e instanceof Uint8Array?Ai(r,e,t):lat(r,e,t)}function ma(r,e=0){return r instanceof Uint8Array?fY(r,e):uat(r,e)}function $r(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=gs(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var yY={};W(yY,{base10:()=>yat});var aMr=new Uint8Array(0);function TCe(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 Ou(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 kCe(r){return new TextEncoder().encode(r)}function DCe(r){return new TextDecoder().decode(r)}function dat(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var fat=dat,hat=fat,PCe=hat;var hY=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")}},pY=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 RCe(this,e)}},mY=class{decoders;constructor(e){this.decoders=e}or(e){return RCe(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 RCe(r,e){return new mY({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gY=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new hY(e,t,n),this.decoder=new pY(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $w({name:r,prefix:e,encode:t,decode:n}){return new gY(r,e,t,n)}function $f({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=PCe(t,r);return $w({prefix:e,name:r,encode:n,decode:s=>Ou(o(s))})}function pat(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function mat(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function gat(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function br({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=gat(n);return $w({prefix:e,name:r,encode(s){return mat(s,n,t)},decode(s){return pat(s,o,t,r)}})}var yat=$f({prefix:"9",name:"base10",alphabet:"0123456789"});var bY={};W(bY,{base16:()=>bat,base16upper:()=>wat});var bat=br({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wat=br({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var wY={};W(wY,{base2:()=>xat});var xat=br({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xY={};W(xY,{base256emoji:()=>Aat});var LCe=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}"),vat=LCe.reduce((r,e,t)=>(r[t]=e,r),[]),Eat=LCe.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Sat(r){return r.reduce((e,t)=>(e+=vat[t],e),"")}function Cat(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Eat[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Aat=$w({prefix:"\u{1F680}",name:"base256emoji",encode:Sat,decode:Cat});var vY={};W(vY,{base32:()=>Ii,base32hex:()=>Dat,base32hexpad:()=>Pat,base32hexpadupper:()=>Rat,base32hexupper:()=>_at,base32pad:()=>Tat,base32padupper:()=>kat,base32upper:()=>Iat,base32z:()=>Lat});var Ii=br({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Iat=br({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Tat=br({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kat=br({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dat=br({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_at=br({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Pat=br({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rat=br({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Lat=br({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var EY={};W(EY,{base36:()=>jC,base36upper:()=>Mat});var jC=$f({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mat=$f({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var SY={};W(SY,{base58btc:()=>_r,base58flickr:()=>Bat});var _r=$f({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bat=$f({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var CY={};W(CY,{base64:()=>Oat,base64pad:()=>Nat,base64url:()=>cm,base64urlpad:()=>Uat});var Oat=br({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Nat=br({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cm=br({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Uat=br({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var AY={};W(AY,{base8:()=>Fat});var Fat=br({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var IY={};W(IY,{identity:()=>Kat});var Kat=$w({prefix:"\0",name:"identity",encode:r=>DCe(r),decode:r=>kCe(r)});var SMr=new TextEncoder,CMr=new TextDecoder;var kY={};W(kY,{identity:()=>ga});var Hat=OCe,MCe=128,Vat=127,qat=~Vat,jat=Math.pow(2,31);function OCe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=jat;)e[t++]=r&255|MCe,r/=128;for(;r&qat;)e[t++]=r&255|MCe,r>>>=7;return e[t]=r|0,OCe.bytes=t-n+1,e}var Gat=TY,Wat=128,BCe=127;function TY(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw TY.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&BCe)<<o:(i&BCe)*Math.pow(2,o),o+=7}while(i>=Wat);return TY.bytes=s-n,t}var Yat=Math.pow(2,7),Xat=Math.pow(2,14),Zat=Math.pow(2,21),Jat=Math.pow(2,28),Qat=Math.pow(2,35),ect=Math.pow(2,42),tct=Math.pow(2,49),rct=Math.pow(2,56),nct=Math.pow(2,63),oct=function(r){return r<Yat?1:r<Xat?2:r<Zat?3:r<Jat?4:r<Qat?5:r<ect?6:r<tct?7:r<rct?8:r<nct?9:10},sct={encode:Hat,decode:Gat,encodingLength:oct},ict=sct,GC=ict;function WC(r,e=0){return[GC.decode(r,e),GC.decode.bytes]}function Hw(r,e,t=0){return GC.encode(r,e,t),e}function Vw(r){return GC.encodingLength(r)}function jw(r,e){let t=e.byteLength,n=Vw(r),o=n+Vw(t),s=new Uint8Array(o+t);return Hw(r,s,0),Hw(t,s,n),s.set(e,o),new qw(r,t,e,s)}function Hf(r){let e=Ou(r),[t,n]=WC(e),[o,s]=WC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qw(t,o,i,e)}function NCe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&TCe(r.bytes,t.bytes)}}var qw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var UCe=0,act="identity",FCe=Ou;function cct(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 jw(UCe,FCe(r))}var ga={code:UCe,name:act,encode:FCe,digest:cct};var PY={};W(PY,{sha256:()=>Gw,sha512:()=>uct});var lct=20;function _Y({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new DY(r,e,t,n,o)}var DY=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??lct,this.maxDigestLength=s}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?KCe(n,this.code,t?.truncate):n.then(o=>KCe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function KCe(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 jw(e,r)}function $Ce(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Gw=_Y({name:"sha2-256",code:18,encode:$Ce("SHA-256")}),uct=_Y({name:"sha2-512",code:19,encode:$Ce("SHA-512")});function HCe(r,e){let{bytes:t,version:n}=r;return n===0?fct(t,RY(r),e??_r.encoder):hct(t,RY(r),e??Ii.encoder)}var VCe=new WeakMap;function RY(r){let e=VCe.get(r);if(e==null){let t=new Map;return VCe.set(r,t),t}return e}var wr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==YC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==pct)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=jw(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&&NCe(e.multihash,n.multihash)}toString(e){return HCe(this,e)}toJSON(){return{"/":HCe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??qCe(n,o,s.bytes))}else if(t[mct]===!0){let{version:n,multihash:o,code:s}=t,i=Hf(o);return r.create(n,s,i)}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!==YC)throw new Error(`Version 0 CID must use dag-pb (code: ${YC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=qCe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,YC,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,o=Ou(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new qw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=WC(e.subarray(t));return t+=h,d},o=n(),s=YC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=dct(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return RY(s).set(n,e),s}};function dct(r,e){switch(r[0]){case"Q":{let t=e??_r;return[_r.prefix,t.decode(`${_r.prefix}${r}`)]}case _r.prefix:{let t=e??_r;return[_r.prefix,t.decode(r)]}case Ii.prefix:{let t=e??Ii;return[Ii.prefix,t.decode(r)]}case jC.prefix:{let t=e??jC;return[jC.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 fct(r,e,t){let{prefix:n}=t;if(n!==_r.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function hct(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var YC=112,pct=18;function qCe(r,e,t){let n=Vw(r),o=n+Vw(e),s=new Uint8Array(o+t.byteLength);return Hw(r,s,0),Hw(e,s,n),s.set(t,o),s}var mct=Symbol.for("@ipld/js-cid/CID");var Nu={...IY,...wY,...AY,...yY,...bY,...vY,...EY,...SY,...CY,...xY},jMr={...PY,...kY};function GCe(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var jCe=GCe("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),LY=GCe("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=gs(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),gct={utf8:jCe,"utf-8":jCe,hex:Nu.base16,latin1:LY,ascii:LY,binary:LY,...Nu},U8=gct;function Ze(r,e="utf8"){let t=U8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function We(r,e="utf8"){let t=U8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Gn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Uu=class extends Error{static name="ValidationError";name="ValidationError"},F8=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},K8=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var z8=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let h=Number.parseInt(d,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var yct=45,bct=15,$8=new z8;function WCe(r){if(!(r.length>bct))return $8.new(r).parseWith(()=>$8.readIPv4Addr())}function YCe(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yct))return $8.new(r).parseWith(()=>$8.readIPv6Addr())}function Ti(r){return!!WCe(r)}function Ww(r){return!!YCe(r)}function BY(r){return e=>We(e,r)}function OY(r){return e=>Ze(e,r)}function Yw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function lm(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function XCe(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=Ze(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 o=lm(n);return $r([t,o],t.length+o.length)}function ZCe(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=Ii.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 o=lm(n);return $r([t,o],t.length+o.length)}function NY(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=We(e,"base32"),o=Yw(t);return`${n}:${o}`}var UY=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Gn("Invalid byte value in IP address");e[n]=o}),e},JCe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ti(t[n]),i;s&&(i=UY(t[n]),t[n]=We(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,We(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Gn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},QCe=function(r){if(r.byteLength!==4)throw new Gn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},eAe=function(r){if(r.byteLength!==16)throw new Gn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Gn(`Invalid IPv6 address "${t}"`)}};function tAe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Gn(`Invalid IPv6 address "${r}"`)}}var MY=Object.values(Nu).map(r=>r.decoder),wct=(function(){let r=MY[0].or(MY[1]);return MY.slice(2).forEach(e=>r=r.or(e)),r})();function rAe(r){return wct.decode(r)}function nAe(r){return e=>r.encoder.encode(e)}function xct(r){if(parseInt(r).toString()!==r)throw new Uu("Value must be an integer")}function vct(r){if(r<0)throw new Uu("Value must be a positive integer, or zero")}function Ect(r){return e=>{if(e>r)throw new Uu(`Value must be smaller than or equal to ${r}`)}}function Sct(...r){return e=>{for(let t of r)t(e)}}var XC=Sct(xct,vct,Ect(65535));var mn=-1,FY=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 K8(`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)}))}},Fu=new FY,Uct=[{code:4,name:"ip4",size:32,valueToBytes:UY,bytesToValue:QCe,validate:r=>{if(!Ti(r))throw new Uu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:273,name:"udp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:33,name:"dccp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:41,name:"ip6",size:128,valueToBytes:JCe,bytesToValue:eAe,stringToValue:tAe,validate:r=>{if(!Ww(r))throw new Uu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mn},{code:43,name:"ipcidr",size:8,bytesToValue:BY("base10"),valueToBytes:OY("base10")},{code:53,name:"dns",size:mn},{code:54,name:"dns4",size:mn},{code:55,name:"dns6",size:mn},{code:56,name:"dnsaddr",size:mn},{code:132,name:"sctp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mn,bytesToValue:BY("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?OY("base58btc")(r):wr.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:NY,valueToBytes:XCe},{code:445,name:"onion3",size:296,bytesToValue:NY,valueToBytes:ZCe},{code:446,name:"garlic64",size:mn},{code:447,name:"garlic32",size:mn},{code:448,name:"tls"},{code:449,name:"sni",size:mn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mn,bytesToValue:nAe(cm),valueToBytes:rAe},{code:480,name:"http"},{code:481,name:"http-path",size:mn,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:mn}];Uct.forEach(r=>{Fu.addProtocol(r)});function oAe(r){let e=[],t=0;for(;t<r.length;){let n=ma(r,t),o=Fu.getProtocol(n),s=Gt(n),i=Fct(o,r,t+s),a=0;i>0&&o.size===mn&&(a=Gt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??We(d)}e.push(l),t+=c}return e}function sAe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Fu.getProtocol(n.code),s=Gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Ze(n.value),a=i.byteLength,o.size===mn&&(c=Gt(a)));let l=new Uint8Array(s+c+a),u=0;Ai(n.code,l,u),u+=s,i!=null&&(o.size===mn&&(Ai(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return $r(t,e)}function iAe(r){if(r.charAt(0)!=="/")throw new Gn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Fu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Gn(`Component ${o} 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 Gn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Gn("Incomplete multiaddr");return e}function aAe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Fu.getProtocol(e.code);if(t==null)throw new Gn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Fct(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ma(e,t)}var Kct=Symbol.for("nodejs.util.inspect.custom"),nX=Symbol.for("@multiformats/multiaddr");function zct(r){if(r==null&&(r="/"),cAe(r))return r.getComponents();if(r instanceof Uint8Array)return oAe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),iAe(r);if(Array.isArray(r))return r;throw new Gn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var rX=class r{[nX]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=zct(e),t.validate!==!1&&$ct(this)}get bytes(){return this.#r==null&&(this.#r=sAe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=aAe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new F8(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return zr(this.bytes,e.bytes)}[Kct](){return`Multiaddr(${this.toString()})`}};function $ct(r){r.getComponents().forEach(e=>{let t=Fu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function cAe(r){return!!r?.[nX]}var Ct=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),ke=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),lAe=r=>({match:e=>r.match(e)===!1?e:!1}),Je=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Eo=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),st=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function At(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Hct=ke(421),jBr=At(Hct),W8=ke(54),Y8=ke(55),X8=ke(56),sX=ke(53),GBr=At(W8,Je(ke(421))),WBr=At(Y8,Je(ke(421))),YBr=At(X8,Je(ke(421))),XBr=At(Eo(sX,X8,W8,Y8),Je(ke(421))),uAe=st(ke(4),Je(ke(43))),dAe=st(Je(ke(42)),ke(41),Je(ke(43))),iX=Eo(uAe,dAe),fm=Eo(iX,sX,W8,Y8,X8),ZBr=At(Eo(iX,st(Eo(sX,X8,W8,Y8),Je(ke(421))))),JBr=At(uAe),QBr=At(dAe),eOr=At(iX),aX=st(fm,ke(6)),ZC=st(fm,ke(273)),tOr=At(st(aX,Je(ke(421)))),rOr=At(ZC),cX=st(ZC,Ct(460),Je(ke(421))),Z8=st(ZC,Ct(461),Je(ke(421))),Vct=Eo(cX,Z8),nOr=At(cX),oOr=At(Z8),oX=Eo(fm,aX,ZC,cX,Z8),fAe=Eo(st(oX,Ct(477),Je(ke(421)))),hAe=At(fAe),pAe=Eo(st(oX,Ct(478),Je(ke(421))),st(oX,Ct(448),Je(ke(449)),Ct(477),Je(ke(421)))),mAe=At(pAe),gAe=st(ZC,Ct(280),Je(ke(466)),Je(ke(466)),Je(ke(421))),sOr=At(gAe),yAe=st(Z8,Ct(465),Je(ke(466)),Je(ke(466)),Je(ke(421))),iOr=At(yAe),G8=Eo(fAe,pAe,st(aX,Je(ke(421))),st(Vct,Je(ke(421))),st(fm,Je(ke(421))),gAe,yAe,ke(421)),bAe=At(G8),qct=st(Je(G8),Ct(290),lAe(Ct(281)),Je(ke(421))),J8=At(qct),jct=Eo(st(G8,Ct(290),Ct(281),Je(ke(421))),st(G8,Ct(281),Je(ke(421))),st(Ct(281),Je(ke(421)))),aOr=At(jct),Gct=Eo(st(fm,ke(6),Ct(480),Je(ke(421))),st(fm,Ct(480),Je(ke(421)))),cOr=At(Gct),Wct=st(fm,Eo(st(ke(6,"443"),Ct(480)),st(ke(6),Ct(443)),st(ke(6),Ct(448),Ct(480)),st(Ct(448),Ct(480)),Ct(448),Ct(443)),Je(ke(421))),lOr=At(Wct),Yct=Eo(st(ke(777),Je(ke(421)))),uOr=At(Yct),Xct=Eo(st(ke(400),Je(ke(421)))),dOr=At(Xct);var Wn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ku=class extends Error{static name="ValidationError";name="ValidationError"},Q8=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},eL=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function uX(r){return e=>We(e,r)}function dX(r){return e=>Ze(e,r)}function Qw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function hm(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function wAe(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=Ze(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 o=hm(n);return $r([t,o],t.length+o.length)}function xAe(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=Ii.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 o=hm(n);return $r([t,o],t.length+o.length)}function fX(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=We(e,"base32"),o=Qw(t);return`${n}:${o}`}var hX=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Wn("Invalid byte value in IP address");e[n]=o}),e},vAe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ti(t[n]),i;s&&(i=hX(t[n]),t[n]=We(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,We(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Wn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},EAe=function(r){if(r.byteLength!==4)throw new Wn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},SAe=function(r){if(r.byteLength!==16)throw new Wn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Wn(`Invalid IPv6 address "${t}"`)}};function CAe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Wn(`Invalid IPv6 address "${r}"`)}}var lX=Object.values(Nu).map(r=>r.decoder),Zct=(function(){let r=lX[0].or(lX[1]);return lX.slice(2).forEach(e=>r=r.or(e)),r})();function AAe(r){return Zct.decode(r)}function IAe(r){return e=>r.encoder.encode(e)}function Jct(r){if(parseInt(r).toString()!==r)throw new Ku("Value must be an integer")}function Qct(r){if(r<0)throw new Ku("Value must be a positive integer, or zero")}function elt(r){return e=>{if(e>r)throw new Ku(`Value must be smaller than or equal to ${r}`)}}function tlt(...r){return e=>{for(let t of r)t(e)}}var JC=tlt(Jct,Qct,elt(65535));var gn=-1,pX=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 eL(`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)}))}},zu=new pX,Blt=[{code:4,name:"ip4",size:32,valueToBytes:hX,bytesToValue:EAe,validate:r=>{if(!Ti(r))throw new Ku(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:273,name:"udp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:33,name:"dccp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:41,name:"ip6",size:128,valueToBytes:vAe,bytesToValue:SAe,stringToValue:CAe,validate:r=>{if(!Ww(r))throw new Ku(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:gn},{code:43,name:"ipcidr",size:8,bytesToValue:uX("base10"),valueToBytes:dX("base10")},{code:53,name:"dns",size:gn},{code:54,name:"dns4",size:gn},{code:55,name:"dns6",size:gn},{code:56,name:"dnsaddr",size:gn},{code:132,name:"sctp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:gn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:gn,bytesToValue:uX("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?dX("base58btc")(r):wr.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:fX,valueToBytes:wAe},{code:445,name:"onion3",size:296,bytesToValue:fX,valueToBytes:xAe},{code:446,name:"garlic64",size:gn},{code:447,name:"garlic32",size:gn},{code:448,name:"tls"},{code:449,name:"sni",size:gn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:gn,bytesToValue:IAe(cm),valueToBytes:AAe},{code:480,name:"http"},{code:481,name:"http-path",size:gn,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:gn}];Blt.forEach(r=>{zu.addProtocol(r)});function TAe(r){let e=[],t=0;for(;t<r.length;){let n=ma(r,t),o=zu.getProtocol(n),s=Gt(n),i=Olt(o,r,t+s),a=0;i>0&&o.size===gn&&(a=Gt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??We(d)}e.push(l),t+=c}return e}function kAe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=zu.getProtocol(n.code),s=Gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Ze(n.value),a=i.byteLength,o.size===gn&&(c=Gt(a)));let l=new Uint8Array(s+c+a),u=0;Ai(n.code,l,u),u+=s,i!=null&&(o.size===gn&&(Ai(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return $r(t,e)}function DAe(r){if(r.charAt(0)!=="/")throw new Wn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=zu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Wn(`Component ${o} 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 Wn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Wn("Incomplete multiaddr");return e}function _Ae(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=zu.getProtocol(e.code);if(t==null)throw new Wn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Olt(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ma(e,t)}var Nlt=Symbol.for("nodejs.util.inspect.custom"),EX=Symbol.for("@multiformats/multiaddr");function Ult(r){if(r==null&&(r="/"),PAe(r))return r.getComponents();if(r instanceof Uint8Array)return TAe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),DAe(r);if(Array.isArray(r))return r;throw new Wn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var tL=class r{[EX]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Ult(e),t.validate!==!1&&Flt(this)}get bytes(){return this.#r==null&&(this.#r=kAe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=_Ae(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new Q8(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return zr(this.bytes,e.bytes)}[Nlt](){return`Multiaddr(${this.toString()})`}};function Flt(r){r.getComponents().forEach(e=>{let t=zu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function PAe(r){return!!r?.[EX]}function RAe(r){return new tL(r)}var Klt=[6,53,56,54,55];function LAe(r){return OAe("sni",r)?.value}function MAe(r){let e=OAe("tcp",r)?.value;return e==null?"":`:${e}`}function OAe(r,e){return e.find(t=>t.name===r)}function BAe(r){return r.some(({code:e})=>e===448)}function ya(r,e){let t=NAe[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 NAe={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://${ya(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${ya(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`${ya(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ya(t,e)}`},http:(r,e)=>{let t=BAe(e),n=LAe(e),o=MAe(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ya(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ya(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ya(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ya(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ya(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=BAe(e),n=LAe(e),o=MAe(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ya(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ya(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function UAe(r,e){let n=RAe(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=NAe[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&Klt.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var SX=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},FAe=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function CX(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){h(FAe(i));return}if(i&&(c=()=>{h(FAe(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,h),t===Number.POSITIVE_INFINITY)return;let p=new SX;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(f){h(f)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?h(o):(p.message=o??`Promise timed out after ${t} milliseconds`,h(p))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var zlt=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function $lt(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=zlt(r),d=async(...p)=>{let f=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(f))return}catch(g){n(),i(g);return}c.push(f),t.count===c.length&&(n(),s(c))},h=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,d);for(let p of t.rejectionEvents)a.includes(p)||u(p,h)};for(let p of a)l(p,d);for(let p of t.rejectionEvents)a.includes(p)||l(p,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=CX(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function ba(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=$lt(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Fc=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function KAe(){throw new Error("WebSocket Servers can not be created in the browser!")}var QC=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},rL=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var zAe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new rL("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 nL=zAe;var HAe=Symbol.for("@achingbrain/uint8arraylist");function $Ae(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function oL(r){return!!r?.[HAe]}var xr=class r{bufs;length;[HAe]=!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(oL(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(oL(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=$Ae(this.bufs,e);return t.buf[t.index]}set(e,t){let n=$Ae(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(oL(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:o}=this._subList(e,t);return $r(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:$r(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!oL(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let h=l;h>=0;h--){let p=this.get(d+h);if(n[h]!==p){u=Math.max(1,h-a[p]);break}}if(u===0)return d}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=gs(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 o=pn(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=pn(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=pn(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=gs(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 o=pn(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=pn(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=pn(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=pn(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=pn(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!zr(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((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Hlt=parseInt("11111",2),AX=parseInt("10000000",2),Vlt=parseInt("01111111",2),VAe={0:eA,1:eA,2:qlt,3:Wlt,4:Ylt,5:Glt,6:jlt,16:eA,22:eA,48:eA};function IX(r,e={offset:0}){let t=r[e.offset]&Hlt;if(e.offset++,VAe[t]!=null)return VAe[t](r,e);throw new Error("No decoder for tag "+t)}function tA(r,e){let t=0;if((r[e.offset]&AX)===AX){let n=r[e.offset]&Vlt,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function eA(r,e){tA(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=IX(r,e);if(n===null)break;t.push(n)}return t}function qlt(r,e){let t=tA(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function jlt(r,e){let t=tA(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function Glt(r,e){return e.offset++,null}function Wlt(r,e){let t=tA(r,e),n=r[e.offset];e.offset++;let o=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 o}function Ylt(r,e){let t=tA(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Xlt(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new xr;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function TX(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Xlt(r.byteLength);return new xr(Uint8Array.from([e.byteLength|AX]),e)}function qAe(r){let e=new xr,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new xr(Uint8Array.from([2]),TX(e),e)}function jAe(r){let e=Uint8Array.from([0]),t=new xr(e,r);return new xr(Uint8Array.from([3]),TX(t),t)}function sL(r,e=48){let t=new xr;for(let n of r)t.append(n);return new xr(Uint8Array.from([e]),TX(t),t)}async function GAe(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var Zlt=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Jlt=Uint8Array.from([6,5,43,129,4,0,34]),Qlt=Uint8Array.from([6,5,43,129,4,0,35]),eut={ext:!0,kty:"EC",crv:"P-256"},tut={ext:!0,kty:"EC",crv:"P-384"},rut={ext:!0,kty:"EC",crv:"P-521"},kX=32,DX=48,_X=66;function WAe(r){let e=IX(r);return YAe(e)}function YAe(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===kX*2+1)return n=We(e.subarray(t,t+kX),"base64url"),o=We(e.subarray(t+kX),"base64url"),new ex({...eut,key_ops:["verify"],x:n,y:o});if(e.byteLength===DX*2+1)return n=We(e.subarray(t,t+DX),"base64url"),o=We(e.subarray(t+DX),"base64url"),new ex({...tut,key_ops:["verify"],x:n,y:o});if(e.byteLength===_X*2+1)return n=We(e.subarray(t,t+_X),"base64url"),o=We(e.subarray(t+_X),"base64url"),new ex({...rut,key_ops:["verify"],x:n,y:o});throw new Si(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function XAe(r){return sL([qAe(Uint8Array.from([1])),sL([nut(r.crv)],160),sL([jAe(new xr(Uint8Array.from([4]),Ze(r.x??"","base64url"),Ze(r.y??"","base64url")))],161)]).subarray()}function nut(r){if(r==="P-256")return Zlt;if(r==="P-384")return Jlt;if(r==="P-521")return Qlt;throw new Si(`Invalid curve ${r}`)}var ex=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=XAe(this.jwk)),this._raw}toMultihash(){return ga.digest(tx(this))}toCID(){return wr.createV1(114,this.toMultihash())}toString(){return _r.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:zr(this.raw,e.raw)}async verify(e,t,n){return GAe(this.jwk,t,e,n)}};function pm(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Kc(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function $e(r,e,t=""){let n=pm(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function iL(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Kc(r.outputLen),Kc(r.blockLen)}function rx(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 JAe(r,e){$e(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Hu(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function aL(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function wa(r,e){return r<<32-e|r>>>e}var QAe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",out=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Vu(r){if($e(r),QAe)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=out[r[t]];return e}var $u={_0:48,_9:57,A:65,F:70,a:97,f:102};function ZAe(r){if(r>=$u._0&&r<=$u._9)return r-$u._0;if(r>=$u.A&&r<=$u.F)return r-($u.A-10);if(r>=$u.a&&r<=$u.f)return r-($u.a-10)}function qu(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(QAe)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 o=0,s=0;o<t;o++,s+=2){let i=ZAe(r.charCodeAt(s)),a=ZAe(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ys(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];$e(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function PX(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function nx(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var RX=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function eIe(r,e,t){return r&e^~r&t}function tIe(r,e,t){return r&e^r&t^e&t}var rA=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=aL(this.buffer)}update(e){rx(this),$e(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=aL(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){rx(this),JAe(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Hu(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=aL(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must 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 d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},ju=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Yn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var cL=BigInt(4294967295),rIe=BigInt(32);function sut(r,e=!1){return e?{h:Number(r&cL),l:Number(r>>rIe&cL)}:{h:Number(r>>rIe&cL)|0,l:Number(r&cL)|0}}function nIe(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=sut(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var LX=(r,e,t)=>r>>>t,MX=(r,e,t)=>r<<32-t|e>>>t,mm=(r,e,t)=>r>>>t|e<<32-t,gm=(r,e,t)=>r<<32-t|e>>>t,nA=(r,e,t)=>r<<64-t|e>>>t-32,oA=(r,e,t)=>r>>>t-32|e<<64-t;function zc(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var oIe=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),sIe=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,iIe=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),aIe=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,cIe=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),lIe=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var aut=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]),qf=new Uint32Array(64),BX=class extends rA{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)qf[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=qf[d-15],p=qf[d-2],f=wa(h,7)^wa(h,18)^h>>>3,g=wa(p,17)^wa(p,19)^p>>>10;qf[d]=g+qf[d-7]+f+qf[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=wa(a,6)^wa(a,11)^wa(a,25),p=u+h+eIe(a,c,l)+aut[d]+qf[d]|0,g=(wa(n,2)^wa(n,13)^wa(n,22))+tIe(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Hu(qf)}destroy(){this.set(0,0,0,0,0,0,0,0),Hu(this.buffer)}},OX=class extends BX{A=ju[0]|0;B=ju[1]|0;C=ju[2]|0;D=ju[3]|0;E=ju[4]|0;F=ju[5]|0;G=ju[6]|0;H=ju[7]|0;constructor(){super(32)}};var uIe=nIe(["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))),cut=uIe[0],lut=uIe[1],jf=new Uint32Array(80),Gf=new Uint32Array(80),NX=class extends rA{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:p,Gl:f,Hh:g,Hl:y}=this;return[e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y]}set(e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)jf[b]=e.getUint32(t),Gf[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=jf[b-15]|0,S=Gf[b-15]|0,T=mm(x,S,1)^mm(x,S,8)^LX(x,S,7),A=gm(x,S,1)^gm(x,S,8)^MX(x,S,7),v=jf[b-2]|0,C=Gf[b-2]|0,P=mm(v,C,19)^nA(v,C,61)^LX(v,C,6),F=gm(v,C,19)^oA(v,C,61)^MX(v,C,6),R=iIe(A,F,Gf[b-7],Gf[b-16]),k=aIe(R,T,P,jf[b-7],jf[b-16]);jf[b]=k|0,Gf[b]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:p,Fl:f,Gh:g,Gl:y,Hh:m,Hl:w}=this;for(let b=0;b<80;b++){let x=mm(d,h,14)^mm(d,h,18)^nA(d,h,41),S=gm(d,h,14)^gm(d,h,18)^oA(d,h,41),T=d&p^~d&g,A=h&f^~h&y,v=cIe(w,S,A,lut[b],Gf[b]),C=lIe(v,m,x,T,cut[b],jf[b]),P=v|0,F=mm(n,o,28)^nA(n,o,34)^nA(n,o,39),R=gm(n,o,28)^oA(n,o,34)^oA(n,o,39),k=n&s^n&a^s&a,I=o&i^o&c^i&c;m=g|0,w=y|0,g=p|0,y=f|0,p=d|0,f=h|0,{h:d,l:h}=zc(l|0,u|0,C|0,P|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=oIe(P,R,I);n=sIe(E,C,F,k),o=E|0}({h:n,l:o}=zc(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=zc(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=zc(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=zc(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=zc(this.Eh|0,this.El|0,d|0,h|0),{h:p,l:f}=zc(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:y}=zc(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:w}=zc(this.Hh|0,this.Hl|0,m|0,w|0),this.set(n,o,s,i,a,c,l,u,d,h,p,f,g,y,m,w)}roundClean(){Hu(jf,Gf)}destroy(){Hu(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},UX=class extends NX{Ah=Yn[0]|0;Al=Yn[1]|0;Bh=Yn[2]|0;Bl=Yn[3]|0;Ch=Yn[4]|0;Cl=Yn[5]|0;Dh=Yn[6]|0;Dl=Yn[7]|0;Eh=Yn[8]|0;El=Yn[9]|0;Fh=Yn[10]|0;Fl=Yn[11]|0;Gh=Yn[12]|0;Gl=Yn[13]|0;Hh=Yn[14]|0;Hl=Yn[15]|0;constructor(){super(64)}};var dIe=PX(()=>new OX,RX(1));var fIe=PX(()=>new UX,RX(3));var KX=BigInt(0),FX=BigInt(1);function Gu(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function hIe(r){if(typeof r=="bigint"){if(!lL(r))throw new Error("positive bigint expected, got "+r)}else Kc(r);return r}function sA(r){let e=hIe(r).toString(16);return e.length&1?"0"+e:e}function pIe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?KX:BigInt("0x"+r)}function ox(r){return pIe(Vu(r))}function ym(r){return pIe(Vu(dL($e(r)).reverse()))}function uL(r,e){Kc(e),r=hIe(r);let t=qu(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function zX(r,e){return uL(r,e).reverse()}function dL(r){return Uint8Array.from(r)}var lL=r=>typeof r=="bigint"&&KX<=r;function uut(r,e,t){return lL(r)&&lL(e)&&lL(t)&&e<=r&&r<t}function iA(r,e,t,n){if(!uut(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function $X(r){let e;for(e=0;r>KX;r>>=FX,e+=1);return e}var aA=r=>(FX<<BigInt(r))-FX;function mIe(r,e,t){if(Kc(r,"hashLen"),Kc(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},h=(...y)=>t(l,ys(c,...y)),p=(y=o)=>{l=h(s,y),c=h(),y.length!==0&&(l=h(i,y),c=h())},f=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=h();let w=c.slice();m.push(w),y+=c.length}return ys(...m)};return(y,m)=>{d(),p(y);let w;for(;!(w=m(f()));)p();return d(),w}}function Wf(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function sx(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var Wo=BigInt(0),yn=BigInt(1),bm=BigInt(2),bIe=BigInt(3),wIe=BigInt(4),xIe=BigInt(5),dut=BigInt(7),vIe=BigInt(8),fut=BigInt(9),EIe=BigInt(16);function Pr(r,e){let t=r%e;return t>=Wo?t:e+t}function Wt(r,e,t){let n=r;for(;e-- >Wo;)n*=n,n%=t;return n}function gIe(r,e){if(r===Wo)throw new Error("invert: expected non-zero number");if(e<=Wo)throw new Error("invert: expected positive modulus, got "+e);let t=Pr(r,e),n=e,o=Wo,s=yn,i=yn,a=Wo;for(;t!==Wo;){let l=n/t,u=n%t,d=o-i*l,h=s-a*l;n=t,t=u,o=i,s=a,i=d,a=h}if(n!==yn)throw new Error("invert: does not exist");return Pr(o,e)}function VX(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function SIe(r,e){let t=(r.ORDER+yn)/wIe,n=r.pow(e,t);return VX(r,n,e),n}function hut(r,e){let t=(r.ORDER-xIe)/vIe,n=r.mul(e,bm),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,bm),o),a=r.mul(s,r.sub(i,r.ONE));return VX(r,a,e),a}function put(r){let e=ix(r),t=CIe(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+dut)/EIe;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),d=a.mul(l,o),h=a.mul(l,s),p=a.eql(a.sqr(u),c),f=a.eql(a.sqr(d),c);l=a.cmov(l,u,p),u=a.cmov(h,d,f);let g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return VX(a,y,c),y}}function CIe(r){if(r<bIe)throw new Error("sqrt is not defined for small field");let e=r-yn,t=0;for(;e%bm===Wo;)e/=bm,t++;let n=bm,o=ix(r);for(;yIe(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return SIe;let s=o.pow(n,e),i=(e+yn)/bm;return function(c,l){if(c.is0(l))return l;if(yIe(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,s),h=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let f=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(f++,g=c.sqr(g),f===u)throw new Error("Cannot find square root");let y=yn<<BigInt(u-f-1),m=c.pow(d,y);u=f,d=c.sqr(m),h=c.mul(h,d),p=c.mul(p,m)}return p}}function mut(r){return r%wIe===bIe?SIe:r%vIe===xIe?hut:r%EIe===fut?put(r):CIe(r)}var AIe=(r,e)=>(Pr(r,e)&yn)===yn,gut=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qX(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=gut.reduce((n,o)=>(n[o]="function",n),e);return Wf(r,t),r}function yut(r,e,t){if(t<Wo)throw new Error("invalid exponent, negatives unsupported");if(t===Wo)return r.ONE;if(t===yn)return e;let n=r.ONE,o=e;for(;t>Wo;)t&yn&&(n=r.mul(n,o)),o=r.sqr(o),t>>=yn;return n}function cA(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function yIe(r,e){let t=(r.ORDER-yn)/bm,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function but(r,e){e!==void 0&&Kc(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var HX=class{ORDER;BITS;BYTES;isLE;ZERO=Wo;ONE=yn;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Wo)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=but(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Pr(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Wo<=e&&e<this.ORDER}is0(e){return e===Wo}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&yn)===yn}neg(e){return Pr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Pr(e*e,this.ORDER)}add(e,t){return Pr(e+t,this.ORDER)}sub(e,t){return Pr(e-t,this.ORDER)}mul(e,t){return Pr(e*t,this.ORDER)}pow(e,t){return yut(this,e,t)}div(e,t){return Pr(e*gIe(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return gIe(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=mut(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?zX(e,this.BYTES):uL(e,this.BYTES)}fromBytes(e,t=!1){$e(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?ym(e):ox(e);if(a&&(c=Pr(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return cA(this,e)}cmov(e,t,n){return n?t:e}};function ix(r,e={}){return new HX(r,e)}function IIe(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 jX(r){let e=IIe(r);return e+Math.ceil(e/2)}function GX(r,e,t=!1){$e(r);let n=r.length,o=IIe(e),s=jX(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?ym(r):ox(r),a=Pr(i,e-yn)+yn;return t?zX(a,o):uL(a,o)}var ax=BigInt(0),wm=BigInt(1);function lA(r,e){let t=e.negate();return r?t:e}function xm(r,e){let t=cA(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function _Ie(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function WX(r,e){_Ie(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=aA(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function TIe(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=wm);let l=e*n,u=l+Math.abs(a)-1,d=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:p,offsetF:l}}var YX=new WeakMap,PIe=new WeakMap;function XX(r){return PIe.get(r)||1}function kIe(r){if(r!==ax)throw new Error("invalid wNAF")}var cx=class{BASE;ZERO;Fn;bits;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 o=e;for(;t>ax;)t&wm&&(n=n.add(o)),o=o.double(),t>>=wm;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=WX(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=WX(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:p}=TIe(n,a,i);n=c,u?s=s.add(lA(h,t[p])):o=o.add(lA(d,t[l]))}return kIe(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=WX(e,this.bits);for(let i=0;i<s.windows&&n!==ax;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=TIe(n,i,s);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return kIe(n),o}getPrecomputes(e,t,n){let o=YX.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),YX.set(t,o))),o}cached(e,t,n){let o=XX(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=XX(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){_Ie(t,this.bits),PIe.set(e,t),YX.delete(e)}hasCache(e){return XX(e)!==1}};function RIe(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>ax||n>ax;)t&wm&&(s=s.add(o)),n&wm&&(i=i.add(o)),o=o.double(),t>>=wm,n>>=wm;return{p1:s,p2:i}}function DIe(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return qX(e),e}else return ix(r,{isLE:t})}function fL(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>ax))throw new Error(`CURVE.${c} must be positive bigint`)}let o=DIe(e.p,t.Fp,n),s=DIe(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.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:o,Fn:s}}function hL(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Yf=BigInt(0),bn=BigInt(1),ZX=BigInt(2),wut=BigInt(8);function xut(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function LIe(r,e={}){let t=fL("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Wf(e,{},{uvRatio:"function"});let a=ZX<<BigInt(o.BYTES*8)-bn,c=y=>n.create(y),l=e.uvRatio||((y,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,m))}}catch{return{isValid:!1,value:Yf}}});if(!xut(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(y,m,w=!1){let b=w?bn:Yf;return iA("coordinate "+y,m,b,a),m}function d(y){if(!(y instanceof f))throw new Error("EdwardsPoint expected")}let h=sx((y,m)=>{let{X:w,Y:b,Z:x}=y,S=y.is0();m==null&&(m=S?wut:n.inv(x));let T=c(w*m),A=c(b*m),v=n.mul(x,m);if(S)return{x:Yf,y:bn};if(v!==bn)throw new Error("invZ was invalid");return{x:T,y:A}}),p=sx(y=>{let{a:m,d:w}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:b,Y:x,Z:S,T}=y,A=c(b*b),v=c(x*x),C=c(S*S),P=c(C*C),F=c(A*m),R=c(C*c(F+v)),k=c(P+c(w*c(A*v)));if(R!==k)throw new Error("bad point: equation left != right (1)");let I=c(b*x),E=c(S*T);if(I!==E)throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,bn,c(s.Gx*s.Gy));static ZERO=new f(Yf,bn,bn,Yf);static Fp=n;static Fn=o;X;Y;Z;T;constructor(m,w,b,x){this.X=u("x",m),this.Y=u("y",w),this.Z=u("z",b,!0),this.T=u("t",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof f)throw new Error("extended point not allowed");let{x:w,y:b}=m||{};return u("x",w),u("y",b),new f(w,b,bn,c(w*b))}static fromBytes(m,w=!1){let b=n.BYTES,{a:x,d:S}=s;m=dL($e(m,b,"point")),Gu(w,"zip215");let T=dL(m),A=m[b-1];T[b-1]=A&-129;let v=ym(T),C=w?a:n.ORDER;iA("point.y",v,Yf,C);let P=c(v*v),F=c(P-bn),R=c(S*P-x),{isValid:k,value:I}=l(F,R);if(!k)throw new Error("bad point: invalid y coordinate");let E=(I&bn)===bn,D=(A&128)!==0;if(!w&&I===Yf&&D)throw new Error("bad point: x=0 and x_0=1");return D!==E&&(I=c(-I)),f.fromAffine({x:I,y:v})}static fromHex(m,w=!1){return f.fromBytes(qu(m),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return g.createCache(this,m),w||this.multiply(ZX),this}assertValidity(){p(this)}equals(m){d(m);let{X:w,Y:b,Z:x}=this,{X:S,Y:T,Z:A}=m,v=c(w*A),C=c(S*x),P=c(b*A),F=c(T*x);return v===C&&P===F}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=s,{X:w,Y:b,Z:x}=this,S=c(w*w),T=c(b*b),A=c(ZX*c(x*x)),v=c(m*S),C=w+b,P=c(c(C*C)-S-T),F=v+T,R=F-A,k=v-T,I=c(P*R),E=c(F*k),D=c(P*k),M=c(R*F);return new f(I,E,M,D)}add(m){d(m);let{a:w,d:b}=s,{X:x,Y:S,Z:T,T:A}=this,{X:v,Y:C,Z:P,T:F}=m,R=c(x*v),k=c(S*C),I=c(A*b*F),E=c(T*P),D=c((x+S)*(v+C)-R-k),M=E-I,B=E+I,L=c(k-w*R),O=c(D*M),U=c(B*L),$=c(D*L),J=c(M*B);return new f(O,U,J,$)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:b}=g.cached(this,m,x=>xm(f,x));return xm(f,[w,b])[0]}multiplyUnsafe(m,w=f.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===Yf?f.ZERO:this.is0()||m===bn?this:g.unsafe(this,m,b=>xm(f,b),w)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(m){return h(this,m)}clearCofactor(){return i===bn?this:this.multiplyUnsafe(i)}toBytes(){let{x:m,y:w}=this.toAffine(),b=n.toBytes(w);return b[b.length-1]|=m&bn?128:0,b}toHex(){return Vu(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new cx(f,o.BITS);return f.BASE.precompute(8),f}function MIe(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Wf(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||nx,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,C,P)=>{if(Gu(P,"phflag"),C.length||P)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(ym(v))}function d(v){let C=b.secretKey;$e(v,b.secretKey,"secretKey");let P=$e(e(v),2*C,"hashedSecretKey"),F=c(P.slice(0,C)),R=P.slice(C,2*C),k=u(F);return{head:F,prefix:R,scalar:k}}function h(v){let{head:C,prefix:P,scalar:F}=d(v),R=o.multiply(F),k=R.toBytes();return{head:C,prefix:P,scalar:F,point:R,pointBytes:k}}function p(v){return h(v).pointBytes}function f(v=Uint8Array.of(),...C){let P=ys(...C);return u(e(l(P,$e(v,void 0,"context"),!!n)))}function g(v,C,P={}){v=$e(v,void 0,"message"),n&&(v=n(v));let{prefix:F,scalar:R,pointBytes:k}=h(C),I=f(P.context,F,v),E=o.multiply(I).toBytes(),D=f(P.context,E,k,v),M=i.create(I+D*R);if(!i.isValid(M))throw new Error("sign failed: invalid s");let B=ys(E,i.toBytes(M));return $e(B,b.signature,"result")}let y={zip215:!0};function m(v,C,P,F=y){let{context:R,zip215:k}=F,I=b.signature;v=$e(v,I,"signature"),C=$e(C,void 0,"message"),P=$e(P,b.publicKey,"publicKey"),k!==void 0&&Gu(k,"zip215"),n&&(C=n(C));let E=I/2,D=v.subarray(0,E),M=ym(v.subarray(E,I)),B,L,O;try{B=r.fromBytes(P,k),L=r.fromBytes(D,k),O=o.multiplyUnsafe(M)}catch{return!1}if(!k&&B.isSmallOrder())return!1;let U=f(R,L.toBytes(),B.toBytes(),C);return L.add(B.multiplyUnsafe(U)).subtract(O).clearCofactor().is0()}let w=s.BYTES,b={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(v=a(b.seed)){return $e(v,b.seed,"seed")}function S(v){return pm(v)&&v.length===i.BYTES}function T(v,C){try{return!!r.fromBytes(v,C)}catch{return!1}}let A={getExtendedPublicKey:h,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:T,toMontgomery(v){let{y:C}=r.fromBytes(v),P=b.publicKey,F=P===32;if(!F&&P!==57)throw new Error("only defined for 25519 and 448");let R=F?s.div(bn+C,bn-C):s.div(C-bn,C+bn);return s.toBytes(R)},toMontgomerySecret(v){let C=b.secretKey;$e(v,C);let P=e(v.subarray(0,C));return c(P).subarray(0,C)}};return Object.freeze({keygen:hL(x,p),getPublicKey:p,sign:g,verify:m,utils:A,Point:r,lengths:b})}var vut=BigInt(1),BIe=BigInt(2);var Eut=BigInt(5),Sut=BigInt(8),JX=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Cut={p:JX,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Sut,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Aut(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=JX,a=r*r%s*r%s,c=Wt(a,BIe,s)*a%s,l=Wt(c,vut,s)*r%s,u=Wt(l,Eut,s)*l%s,d=Wt(u,e,s)*u%s,h=Wt(d,t,s)*d%s,p=Wt(h,n,s)*h%s,f=Wt(p,o,s)*p%s,g=Wt(f,o,s)*p%s,y=Wt(g,e,s)*u%s;return{pow_p_5_8:Wt(y,BIe,s)*r%s,b2:a}}function Iut(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var OIe=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Tut(r,e){let t=JX,n=Pr(e*e*e,t),o=Pr(n*n*e,t),s=Aut(r*o).pow_p_5_8,i=Pr(r*n*s,t),a=Pr(e*i*i,t),c=i,l=Pr(i*OIe,t),u=a===r,d=a===Pr(-r,t),h=a===Pr(-r*OIe,t);return u&&(i=c),(d||h)&&(i=l),AIe(i,t)&&(i=Pr(-i,t)),{isValid:u||d,value:i}}var kut=LIe(Cut,{uvRatio:Tut});function Dut(r){return MIe(kut,fIe,Object.assign({adjustScalarBytes:Iut},r))}var NIe=Dut({});var pL=32;var QX,_ut=(async()=>{try{return await nL.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Put(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await nL.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await nL.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 Rut(r,e,t){return NIe.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function UIe(r,e,t){return QX==null&&(QX=await _ut),QX?Put(r,e,t):Rut(r,e,t)}function mL(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var gL=class{type="Ed25519";raw;constructor(e){this.raw=eZ(e,pL)}toMultihash(){return ga.digest(tx(this))}toCID(){return wr.createV1(114,this.toMultihash())}toString(){return _r.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:zr(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=UIe(this.raw,t,e);return mL(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function KIe(r){return r=eZ(r,pL),new gL(r)}function eZ(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Si(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var tZ=new Float32Array([-0]),Xf=new Uint8Array(tZ.buffer);function zIe(r,e,t){tZ[0]=r,e[t]=Xf[0],e[t+1]=Xf[1],e[t+2]=Xf[2],e[t+3]=Xf[3]}function $Ie(r,e){return Xf[0]=r[e],Xf[1]=r[e+1],Xf[2]=r[e+2],Xf[3]=r[e+3],tZ[0]}var rZ=new Float64Array([-0]),So=new Uint8Array(rZ.buffer);function HIe(r,e,t){rZ[0]=r,e[t]=So[0],e[t+1]=So[1],e[t+2]=So[2],e[t+3]=So[3],e[t+4]=So[4],e[t+5]=So[5],e[t+6]=So[6],e[t+7]=So[7]}function VIe(r,e){return So[0]=r[e],So[1]=r[e+1],So[2]=r[e+2],So[3]=r[e+3],So[4]=r[e+4],So[5]=r[e+5],So[6]=r[e+6],So[7]=r[e+7],rZ[0]}var Mut=BigInt(Number.MAX_SAFE_INTEGER),But=BigInt(Number.MIN_SAFE_INTEGER),Ws=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 vm;if(e<Mut&&e>But)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>qIe&&(o=0n,++n>qIe&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return vm;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}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):vm}},vm=new Ws(0,0);vm.toBigInt=function(){return 0n};vm.zzEncode=vm.zzDecode=function(){return this};vm.length=function(){return 1};var qIe=4294967296n;function jIe(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 GIe(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function nZ(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function xa(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function yL(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var oZ=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,xa(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 xa(this,4);return yL(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw xa(this,4);return yL(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw xa(this,4);let e=$Ie(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw xa(this,4);let e=VIe(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 xa(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return GIe(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw xa(this,e);this.pos+=e}else do if(this.pos>=this.len)throw xa(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 Ws(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 xa(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 xa(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 xa(this,8);let e=yL(this.buf,this.pos+=4),t=yL(this.buf,this.pos+=4);return new Ws(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=fY(this.buf,this.pos);return this.pos+=Gt(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 sZ(r){return new oZ(r instanceof Uint8Array?r:r.subarray())}function ki(r,e,t){let n=sZ(r);return e.decode(n,void 0,t)}function iZ(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return gs(i);o+i>e&&(n=gs(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Em=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function aZ(){}var lZ=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Out=iZ();function Nut(r){return globalThis.Buffer!=null?gs(r):Out(r)}var dA=class{len;head;tail;states;constructor(){this.len=0,this.head=new Em(aZ,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Em(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new uZ((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(bL,10,Ws.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ws.fromBigInt(e);return this._push(bL,t.length(),t)}uint64Number(e){return this._push(Ai,Gt(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=Ws.fromBigInt(e).zzEncode();return this._push(bL,t.length(),t)}sint64Number(e){let t=Ws.fromNumber(e).zzEncode();return this._push(bL,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(cZ,1,e?1:0)}fixed32(e){return this._push(uA,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ws.fromBigInt(e);return this._push(uA,4,t.lo)._push(uA,4,t.hi)}fixed64Number(e){let t=Ws.fromNumber(e);return this._push(uA,4,t.lo)._push(uA,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(zIe,4,e)}double(e){return this._push(HIe,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(cZ,1,0):this.uint32(t)._push(Fut,t,e)}string(e){let t=jIe(e);return t!==0?this.uint32(t)._push(nZ,t,e):this._push(cZ,1,0)}fork(){return this.states=new lZ(this),this.head=this.tail=new Em(aZ,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 Em(aZ,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=Nut(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function cZ(r,e,t){e[t]=r&255}function Uut(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var uZ=class extends Em{next;constructor(e,t){super(Uut,e,t),this.next=void 0}};function bL(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 uA(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 Fut(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(dA.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Kut,e,r),this},dA.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zut,e,r),this});function Kut(r,e,t){e.set(r,t)}function zut(r,e,t){r.length<40?nZ(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Ze(r),t)}function dZ(){return new dA}function Di(r,e){let t=dZ();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var lx;(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"})(lx||(lx={}));function wL(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Sm(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return wL("enum",lx.VARINT,t,n)}function _i(r,e){return wL("message",lx.LENGTH_DELIMITED,r,e)}var fA=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Ys;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ys||(Ys={}));var fZ;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(fZ||(fZ={}));(function(r){r.codec=()=>Sm(fZ)})(Ys||(Ys={}));var hA;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ys.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Ys.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(hA||(hA={}));var hZ;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ys.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Ys.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(hZ||(hZ={}));var xL=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(iL(e),$e(t,void 0,"key"),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 n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);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),Hu(o)}update(e){return rx(this),this.iHash.update(e),this}digestInto(e){rx(this),$e(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,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()}},pZ=(r,e,t)=>new xL(r,e).update(t).digest();pZ.create=(r,e)=>new xL(r,e);var YIe=(r,e)=>(r+(r>=0?e:-e)/XIe)/e;function Hut(r,e,t){let[[n,o],[s,i]]=e,a=YIe(i*r,t),c=YIe(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,d=l<Wu,h=u<Wu;d&&(l=-l),h&&(u=-u);let p=aA(Math.ceil($X(t)/2))+ux;if(l<Wu||l>=p||u<Wu||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:d,k1:l,k2neg:h,k2:u}}function gZ(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function mZ(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Gu(t.lowS,"lowS"),Gu(t.prehash,"prehash"),t.format!==void 0&&gZ(t.format),t}var yZ=class extends Error{constructor(e=""){super(e)}},Zf={Err:yZ,_tlv:{encode:(r,e)=>{let{Err:t}=Zf;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,o=sA(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?sA(o.length/2|128):"";return sA(r)+s+o+e},decode(r,e){let{Err:t}=Zf,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 o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&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)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Zf;if(r<Wu)throw new e("integer: negative integers are not allowed");let t=sA(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}=Zf;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 ox(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Zf,o=$e(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Zf,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Wu=BigInt(0),ux=BigInt(1),XIe=BigInt(2),vL=BigInt(3),Vut=BigInt(4);function ZIe(r,e={}){let t=fL("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Wf(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=QIe(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(R,k,I){let{x:E,y:D}=k.toAffine(),M=n.toBytes(E);if(Gu(I,"isCompressed"),I){u();let B=!n.isOdd(D);return ys(JIe(B),M)}else return ys(Uint8Array.of(4),M,n.toBytes(D))}function h(R){$e(R,void 0,"Point");let{publicKey:k,publicKeyUncompressed:I}=l,E=R.length,D=R[0],M=R.subarray(1);if(E===k&&(D===2||D===3)){let B=n.fromBytes(M);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let L=g(B),O;try{O=n.sqrt(L)}catch(J){let X=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();let U=n.isOdd(O);return(D&1)===1!==U&&(O=n.neg(O)),{x:B,y:O}}else if(E===I&&D===4){let B=n.BYTES,L=n.fromBytes(M.subarray(0,B)),O=n.fromBytes(M.subarray(B,B*2));if(!y(L,O))throw new Error("bad point: is not on curve");return{x:L,y:O}}else throw new Error(`bad point: got length ${E}, expected compressed=${k} or uncompressed=${I}`)}let p=e.toBytes||d,f=e.fromBytes||h;function g(R){let k=n.sqr(R),I=n.mul(k,R);return n.add(n.add(I,n.mul(R,s.a)),s.b)}function y(R,k){let I=n.sqr(k),E=g(R);return n.eql(I,E)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(s.a,vL),Vut),w=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(m,w)))throw new Error("bad curve params: a or b");function b(R,k,I=!1){if(!n.isValid(k)||I&&n.is0(k))throw new Error(`bad point coordinate ${R}`);return k}function x(R){if(!(R instanceof C))throw new Error("Weierstrass Point expected")}function S(R){if(!c||!c.basises)throw new Error("no endo");return Hut(R,c.basises,o.ORDER)}let T=sx((R,k)=>{let{X:I,Y:E,Z:D}=R;if(n.eql(D,n.ONE))return{x:I,y:E};let M=R.is0();k==null&&(k=M?n.ONE:n.inv(D));let B=n.mul(I,k),L=n.mul(E,k),O=n.mul(D,k);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:B,y:L}}),A=sx(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:k,y:I}=R.toAffine();if(!n.isValid(k)||!n.isValid(I))throw new Error("bad point: x or y not field elements");if(!y(k,I))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(R,k,I,E,D){return I=new C(n.mul(I.X,R),I.Y,I.Z),k=lA(E,k),I=lA(D,I),k.add(I)}class C{static BASE=new C(s.Gx,s.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(k,I,E){this.X=b("x",k),this.Y=b("y",I,!0),this.Z=b("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(k){let{x:I,y:E}=k||{};if(!k||!n.isValid(I)||!n.isValid(E))throw new Error("invalid affine point");if(k instanceof C)throw new Error("projective point not allowed");return n.is0(I)&&n.is0(E)?C.ZERO:new C(I,E,n.ONE)}static fromBytes(k){let I=C.fromAffine(f($e(k,void 0,"point")));return I.assertValidity(),I}static fromHex(k){return C.fromBytes(qu(k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,I=!0){return F.createCache(this,k),I||this.multiply(vL),this}assertValidity(){A(this)}hasEvenY(){let{y:k}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(k)}equals(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.eql(n.mul(I,L),n.mul(M,D)),U=n.eql(n.mul(E,L),n.mul(B,D));return O&&U}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:k,b:I}=s,E=n.mul(I,vL),{X:D,Y:M,Z:B}=this,L=n.ZERO,O=n.ZERO,U=n.ZERO,$=n.mul(D,D),J=n.mul(M,M),X=n.mul(B,B),N=n.mul(D,M);return N=n.add(N,N),U=n.mul(D,B),U=n.add(U,U),L=n.mul(k,U),O=n.mul(E,X),O=n.add(L,O),L=n.sub(J,O),O=n.add(J,O),O=n.mul(L,O),L=n.mul(N,L),U=n.mul(E,U),X=n.mul(k,X),N=n.sub($,X),N=n.mul(k,N),N=n.add(N,U),U=n.add($,$),$=n.add(U,$),$=n.add($,X),$=n.mul($,N),O=n.add(O,$),X=n.mul(M,B),X=n.add(X,X),$=n.mul(X,N),L=n.sub(L,$),U=n.mul(X,J),U=n.add(U,U),U=n.add(U,U),new C(L,O,U)}add(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.ZERO,U=n.ZERO,$=n.ZERO,J=s.a,X=n.mul(s.b,vL),N=n.mul(I,M),H=n.mul(E,B),Z=n.mul(D,L),ae=n.add(I,E),Q=n.add(M,B);ae=n.mul(ae,Q),Q=n.add(N,H),ae=n.sub(ae,Q),Q=n.add(I,D);let oe=n.add(M,L);return Q=n.mul(Q,oe),oe=n.add(N,Z),Q=n.sub(Q,oe),oe=n.add(E,D),O=n.add(B,L),oe=n.mul(oe,O),O=n.add(H,Z),oe=n.sub(oe,O),$=n.mul(J,Q),O=n.mul(X,Z),$=n.add(O,$),O=n.sub(H,$),$=n.add(H,$),U=n.mul(O,$),H=n.add(N,N),H=n.add(H,N),Z=n.mul(J,Z),Q=n.mul(X,Q),H=n.add(H,Z),Z=n.sub(N,Z),Z=n.mul(J,Z),Q=n.add(Q,Z),N=n.mul(H,Q),U=n.add(U,N),N=n.mul(oe,Q),O=n.mul(ae,O),O=n.sub(O,N),N=n.mul(ae,H),$=n.mul(oe,$),$=n.add($,N),new C(O,U,$)}subtract(k){return this.add(k.negate())}is0(){return this.equals(C.ZERO)}multiply(k){let{endo:I}=e;if(!o.isValidNot0(k))throw new Error("invalid scalar: out of range");let E,D,M=B=>F.cached(this,B,L=>xm(C,L));if(I){let{k1neg:B,k1:L,k2neg:O,k2:U}=S(k),{p:$,f:J}=M(L),{p:X,f:N}=M(U);D=J.add(N),E=v(I.beta,$,X,B,O)}else{let{p:B,f:L}=M(k);E=B,D=L}return xm(C,[E,D])[0]}multiplyUnsafe(k){let{endo:I}=e,E=this;if(!o.isValid(k))throw new Error("invalid scalar: out of range");if(k===Wu||E.is0())return C.ZERO;if(k===ux)return E;if(F.hasCache(this))return this.multiply(k);if(I){let{k1neg:D,k1:M,k2neg:B,k2:L}=S(k),{p1:O,p2:U}=RIe(C,E,M,L);return v(I.beta,O,U,D,B)}else return F.unsafe(E,k)}toAffine(k){return T(this,k)}isTorsionFree(){let{isTorsionFree:k}=e;return i===ux?!0:k?k(C,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:k}=e;return i===ux?this:k?k(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return Gu(k,"isCompressed"),this.assertValidity(),p(C,this,k)}toHex(k=!0){return Vu(this.toBytes(k))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,F=new cx(C,e.endo?Math.ceil(P/2):P);return C.BASE.precompute(8),C}function JIe(r){return Uint8Array.of(r?2:3)}function QIe(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function qut(r,e={}){let{Fn:t}=r,n=e.randomBytes||nx,o=Object.assign(QIe(r.Fp,t),{seed:jX(t.ORDER)});function s(p){try{let f=t.fromBytes(p);return t.isValidNot0(f)}catch{return!1}}function i(p,f){let{publicKey:g,publicKeyUncompressed:y}=o;try{let m=p.length;return f===!0&&m!==g||f===!1&&m!==y?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return GX($e(p,o.seed,"seed"),t.ORDER)}function c(p,f=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(f)}function l(p){let{secretKey:f,publicKey:g,publicKeyUncompressed:y}=o;if(!pm(p)||"_lengths"in t&&t._lengths||f===g)return;let m=$e(p,void 0,"key").length;return m===g||m===y}function u(p,f,g=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(f)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(p);return r.fromBytes(f).multiply(y).toBytes(g)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=hL(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:d,lengths:o})}function eTe(r,e,t={}){iL(e),Wf(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||nx,o=t.hmac||((I,E)=>pZ(e,I,E)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p}=qut(r,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=a*XIe<s.ORDER;function y(I){let E=a>>ux;return I>E}function m(I,E){if(!i.isValidNot0(E))throw new Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return E}function w(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(I,E){gZ(E);let D=p.signature,M=E==="compact"?D:E==="recovered"?D+1:void 0;return $e(I,M)}class x{r;s;recovery;constructor(E,D,M){if(this.r=m("r",E),this.s=m("s",D),M!=null){if(w(),![0,1,2,3].includes(M))throw new Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(E,D=f.format){b(E,D);let M;if(D==="der"){let{r:U,s:$}=Zf.toSig($e(E));return new x(U,$)}D==="recovered"&&(M=E[0],D="compact",E=E.subarray(1));let B=p.signature/2,L=E.subarray(0,B),O=E.subarray(B,B*2);return new x(i.fromBytes(L),i.fromBytes(O),M)}static fromHex(E,D){return this.fromBytes(qu(E),D)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new x(this.r,this.s,E)}recoverPublicKey(E){let{r:D,s:M}=this,B=this.assertRecovery(),L=B===2||B===3?D+a:D;if(!s.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=s.toBytes(L),U=r.fromBytes(ys(JIe((B&1)===0),O)),$=i.inv(L),J=T($e(E,void 0,"msgHash")),X=i.create(-J*$),N=i.create(M*$),H=r.BASE.multiplyUnsafe(X).add(U.multiplyUnsafe(N));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(E=f.format){if(gZ(E),E==="der")return qu(Zf.hexFromSig(this));let{r:D,s:M}=this,B=i.toBytes(D),L=i.toBytes(M);return E==="recovered"?(w(),ys(Uint8Array.of(this.assertRecovery()),B,L)):ys(B,L)}toHex(E){return Vu(this.toBytes(E))}}let S=t.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let D=ox(E),M=E.length*8-c;return M>0?D>>BigInt(M):D},T=t.bits2int_modN||function(E){return i.create(S(E))},A=aA(c);function v(I){return iA("num < 2^"+c,I,Wu,A),i.toBytes(I)}function C(I,E){return $e(I,void 0,"message"),E?$e(e(I),void 0,"prehashed message"):I}function P(I,E,D){let{lowS:M,prehash:B,extraEntropy:L}=mZ(D,f);I=C(I,B);let O=T(I),U=i.fromBytes(E);if(!i.isValidNot0(U))throw new Error("invalid private key");let $=[v(U),v(O)];if(L!=null&&L!==!1){let H=L===!0?n(p.secretKey):L;$.push($e(H,void 0,"extraEntropy"))}let J=ys(...$),X=O;function N(H){let Z=S(H);if(!i.isValidNot0(Z))return;let ae=i.inv(Z),Q=r.BASE.multiply(Z).toAffine(),oe=i.create(Q.x);if(oe===Wu)return;let Fe=i.create(ae*i.create(X+oe*U));if(Fe===Wu)return;let nr=(Q.x===oe?0:2)|Number(Q.y&ux),fe=Fe;return M&&y(Fe)&&(fe=i.neg(Fe),nr^=1),new x(oe,fe,g?void 0:nr)}return{seed:J,k2sig:N}}function F(I,E,D={}){let{seed:M,k2sig:B}=P(I,E,D);return mIe(e.outputLen,i.BYTES,o)(M,B).toBytes(D.format)}function R(I,E,D,M={}){let{lowS:B,prehash:L,format:O}=mZ(M,f);if(D=$e(D,void 0,"publicKey"),E=C(E,L),!pm(I)){let U=I instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}b(I,O);try{let U=x.fromBytes(I,O),$=r.fromBytes(D);if(B&&U.hasHighS())return!1;let{r:J,s:X}=U,N=T(E),H=i.inv(X),Z=i.create(N*H),ae=i.create(J*H),Q=r.BASE.multiplyUnsafe(Z).add($.multiplyUnsafe(ae));return Q.is0()?!1:i.create(Q.x)===J}catch{return!1}}function k(I,E,D={}){let{prehash:M}=mZ(D,f);return E=C(E,M),x.fromBytes(I,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:F,verify:R,recoverPublicKey:k,Signature:x,hash:e})}var wZ={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},jut={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var tTe=BigInt(2);function Gut(r){let e=wZ.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Wt(u,t,e)*u%e,h=Wt(d,t,e)*u%e,p=Wt(h,tTe,e)*l%e,f=Wt(p,o,e)*p%e,g=Wt(f,s,e)*f%e,y=Wt(g,a,e)*g%e,m=Wt(y,c,e)*y%e,w=Wt(m,a,e)*g%e,b=Wt(w,t,e)*u%e,x=Wt(b,i,e)*f%e,S=Wt(x,n,e)*l%e,T=Wt(S,tTe,e);if(!bZ.eql(bZ.sqr(T),r))throw new Error("Cannot find square root");return T}var bZ=ix(wZ.p,{sqrt:Gut}),Wut=ZIe(wZ,{Fp:bZ,endo:jut}),dx=eTe(Wut,dIe);function rTe(r,e,t,n){let o=Gw.digest(t instanceof Uint8Array?t:t.subarray());if(mL(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),dx.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new QC(String(s))});try{return n?.signal?.throwIfAborted(),dx.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new QC(String(s))}}var EL=class{type="secp256k1";raw;_key;constructor(e){this._key=oTe(e),this.raw=nTe(this._key)}toMultihash(){return ga.digest(tx(this))}toCID(){return wr.createV1(114,this.toMultihash())}toString(){return _r.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:zr(this.raw,e.raw)}verify(e,t,n){return rTe(this._key,t,e,n)}};function sTe(r){return new EL(r)}function nTe(r){return dx.Point.fromBytes(r).toBytes()}function oTe(r){try{return dx.Point.fromBytes(r),r}catch(e){throw new C8(String(e))}}function iTe(r){let{Type:e,Data:t}=hA.decode(r.digest),n=t??new Uint8Array;switch(e){case Ys.Ed25519:return KIe(n);case Ys.secp256k1:return sTe(n);case Ys.ECDSA:return WAe(n);default:throw new qC}}function tx(r){return hA.encode({Type:Ys[r.type],Data:r.raw})}var xZ={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},aTe={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cTe=new globalThis.TextEncoder;function Yut(r,e){let t=xZ[e],n=aTe[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Xut(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=xZ[e],o=aTe[e],s=r;for(;s.length>0;){let i=cTe.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function vZ(r,{size:e=32,utf8Buffer:t}={}){if(!xZ[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 Xut(r,e,t);r=cTe.encode(r)}return Yut(r,e)}var pA={hash:r=>Number(vZ(r,{size:32})),hashV:(r,e)=>Zut(pA.hash(r,e))};function Zut(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),Ze(e,"base16")}var EZ=64,va=class{fp;h;seed;constructor(e,t,n,o=2){if(o>EZ)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=pn(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?zr(this.fp,e.fp):!1}};function Cm(r,e){return Math.floor(Math.random()*(e-r))+r}var Am=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof va))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof va))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 va))throw new TypeError("Invalid Fingerprint");let t=Cm(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof va))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Jut=500,mA=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??pA,this.seed=e.seed??Cm(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=Ze(e));let t=new va(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Am(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Am(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Cm(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Am(this.bucketSize));for(let a=0;a<Jut;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Am(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=Ze(e));let t=new va(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=Ze(e));let t=new va(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Qut={1:.5,2:.84,4:.95,8:.98};function edt(r=.001){return r>.002?2:r>1e-5?4:8}function lTe(r,e=.001){let t=edt(e),n=Qut[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),EZ);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var SL=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??pA,this.seed=e.seed??Cm(0,Math.pow(2,10)),this.filterSeries=[new mA({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=Ze(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 mA({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=Ze(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=Ze(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 fx(r,e=.001,t){return new SL({...lTe(r,e),...t??{}})}function hx(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var CL=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}},px=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new CL(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 CL(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 SZ=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function mx(r={}){return tdt(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 tdt(r,e){e=e??{};let t=e.onEnd,n=new px,o,s,i,a=hx(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,m)=>{s=w=>{s=null,n.push(w);try{y(r(n))}catch(b){m(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=hx()})}},l=y=>s!=null?s(y):(n.push(y),o),u=y=>(n=new px,s!=null?s({error:y}):(n.push({error:y}),o)),d=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},h=y=>i?o:(i=!0,y!=null?u(y):l({done:!0})),p=()=>(n=new px,h(),{done:!0}),f=y=>(h(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:f,push:d,end:h,get readableLength(){return n.size},onEmpty:async y=>{let m=y?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let w,b;m!=null&&(w=new Promise((x,S)=>{b=()=>{S(new SZ)},m.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&m!=null&&m?.removeEventListener("abort",b)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(y){return g.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(y){return g.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:y=>g.onEmpty(y)},o}function gA(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var AL=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Im=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var IL=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function rdt(r){return r.reason}async function Tm(r,e,t){if(e==null)return r;let n=t?.translateError??rdt;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var TL=class{deferred;signal;constructor(e){this.signal=e,this.deferred=hx(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Bu)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ndt(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var kL=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=ndt(),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 Bu),this.cleanup())}async join(e={}){let t=new TL(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 Tm(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 DL=class extends Ci{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=gA(this.emitEmpty.bind(this),1),this.emitIdle=gA(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;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 AL;let n=new kL(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Bu)}),this.clear()}async onEmpty(e){this.size!==0&&await ba(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ba(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ba(this,"idle",e)}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=mx({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Bu("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var odt=Math.pow(2,20)*4,_L=class extends Ci{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??odt,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new xr,this.writeBuffer=new xr,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new IL)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Tm(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=mx(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new zf(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new R8(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new I8;this.dispatchEvent(new L8(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new zw))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new xr(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new P8(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new VC(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new VC(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var gx=class extends _L{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ba(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ba(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function yA(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var sdt=4194304,PL=class extends Error{static name="UnwrappedError";name="UnwrappedError"},AZ=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},IZ=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},TZ=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function idt(r){return typeof r?.closeRead=="function"}function adt(r){return typeof r?.close=="function"}function CZ(r){return idt(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:adt(r)?r.status!=="open":!1}function cdt(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function ldt(r,e){let t=e?.maxBufferSize??sdt,n=new xr,o,s=!1;if(!cdt(r))throw new Si("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new PL("Stream was unwrapped");if(CZ(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Im(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Tm(o.promise,u?.signal),CZ(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(CZ(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Im(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,d){if(s===!0)throw new PL("Stream was unwrapped");r.send(u)||await ba(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function udt(r,e={}){let t=ldt(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Gt(e.maxDataLength));let n=e?.lengthDecoder??ma,o=e?.lengthEncoder??ICe;return{async read(i){let a=-1,c=new xr;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new AZ("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new TZ(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new IZ(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Im(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Im(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new xr(o(i.byteLength),i),a)},async writeV(i,a){let c=new xr(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function bA(r,e){let t=udt(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var yx=class extends DL{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function uTe(r,e,t){let n,o,s=!1;function i(){let l={signal:o.signal};if(t?.timeout!=null){let u=yA([o.signal,AbortSignal.timeout(t.timeout)]);l.signal=u}s=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{s=!1,!o.signal.aborted&&(n=setTimeout(i,e))})}let a=gA(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var ddt=1024*1024*4,fdt=10,kZ=class extends gx{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??ddt,this.checkBufferedAmountTask=uTe(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??fdt),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=Ze(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function dTe(r){return new kZ(r)}var DZ=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"})})}[M8]=!0;[Symbol.toStringTag]="@libp2p/websockets";[B8]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=dTe({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=UAe(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new Fc("websockets:open-connection")),await ba(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new A8(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return KAe({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>hAe.exactMatch(t)||mAe.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function fTe(r={}){return e=>new DZ(e,r)}var hTe=Symbol.for("nodejs.util.inspect.custom"),hdt=114,wA=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()})`}[aY]=!0;toString(){return this.string==null&&(this.string=_r.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return wr.createV1(hdt,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return zr(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return zr(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[hTe](){return`PeerId(${this.toString()})`}},RL=class extends wA{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},LL=class extends wA{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ML=class extends wA{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},pdt=2336,xA=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ga.digest(Ze(this.url))}[hTe](){return`PeerId(${this.url})`}[aY]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return wr.createV1(pdt,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=We(e)),e.toString()===this.toString())}};var mdt=114,pTe=2336;function _Z(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Hf(_r.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return gdt(wr.parse(r));if(e==null)throw new Si('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Hf(e.decode(r))}return BL(t)}function BL(r){if(bdt(r))return new RL({multihash:r});if(ydt(r))try{let e=iTe(r);if(e.type==="Ed25519")return new LL({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ML({multihash:r,publicKey:e})}catch{let t=We(r.digest);return new xA(new URL(t))}throw new k8("Supplied PeerID Multihash is invalid")}function gdt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==mdt&&r.code!==pTe)throw new T8("Supplied PeerID CID is invalid");if(r.code===pTe){let e=We(r.multihash.digest);return new xA(new URL(e))}return BL(r.multihash)}function ydt(r){return r.code===ga.code}function bdt(r){return r.code===Gw.code}var Xn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Yu=class extends Error{static name="ValidationError";name="ValidationError"},OL=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},NL=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function RZ(r){return e=>We(e,r)}function LZ(r){return e=>Ze(e,r)}function bx(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function km(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function mTe(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=Ze(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 o=km(n);return $r([t,o],t.length+o.length)}function gTe(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=Ii.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 o=km(n);return $r([t,o],t.length+o.length)}function MZ(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=We(e,"base32"),o=bx(t);return`${n}:${o}`}var BZ=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Xn("Invalid byte value in IP address");e[n]=o}),e},yTe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ti(t[n]),i;s&&(i=BZ(t[n]),t[n]=We(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,We(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Xn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},bTe=function(r){if(r.byteLength!==4)throw new Xn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},wTe=function(r){if(r.byteLength!==16)throw new Xn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Xn(`Invalid IPv6 address "${t}"`)}};function xTe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Xn(`Invalid IPv6 address "${r}"`)}}var PZ=Object.values(Nu).map(r=>r.decoder),wdt=(function(){let r=PZ[0].or(PZ[1]);return PZ.slice(2).forEach(e=>r=r.or(e)),r})();function vTe(r){return wdt.decode(r)}function ETe(r){return e=>r.encoder.encode(e)}function xdt(r){if(parseInt(r).toString()!==r)throw new Yu("Value must be an integer")}function vdt(r){if(r<0)throw new Yu("Value must be a positive integer, or zero")}function Edt(r){return e=>{if(e>r)throw new Yu(`Value must be smaller than or equal to ${r}`)}}function Sdt(...r){return e=>{for(let t of r)t(e)}}var vA=Sdt(xdt,vdt,Edt(65535));var wn=-1,OZ=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 NL(`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)}))}},Xu=new OZ,cft=[{code:4,name:"ip4",size:32,valueToBytes:BZ,bytesToValue:bTe,validate:r=>{if(!Ti(r))throw new Yu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:273,name:"udp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:33,name:"dccp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:41,name:"ip6",size:128,valueToBytes:yTe,bytesToValue:wTe,stringToValue:xTe,validate:r=>{if(!Ww(r))throw new Yu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:wn},{code:43,name:"ipcidr",size:8,bytesToValue:RZ("base10"),valueToBytes:LZ("base10")},{code:53,name:"dns",size:wn},{code:54,name:"dns4",size:wn},{code:55,name:"dns6",size:wn},{code:56,name:"dnsaddr",size:wn},{code:132,name:"sctp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:wn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:wn,bytesToValue:RZ("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?LZ("base58btc")(r):wr.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:MZ,valueToBytes:mTe},{code:445,name:"onion3",size:296,bytesToValue:MZ,valueToBytes:gTe},{code:446,name:"garlic64",size:wn},{code:447,name:"garlic32",size:wn},{code:448,name:"tls"},{code:449,name:"sni",size:wn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:wn,bytesToValue:ETe(cm),valueToBytes:vTe},{code:480,name:"http"},{code:481,name:"http-path",size:wn,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:wn}];cft.forEach(r=>{Xu.addProtocol(r)});function STe(r){let e=[],t=0;for(;t<r.length;){let n=ma(r,t),o=Xu.getProtocol(n),s=Gt(n),i=lft(o,r,t+s),a=0;i>0&&o.size===wn&&(a=Gt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??We(d)}e.push(l),t+=c}return e}function CTe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Xu.getProtocol(n.code),s=Gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Ze(n.value),a=i.byteLength,o.size===wn&&(c=Gt(a)));let l=new Uint8Array(s+c+a),u=0;Ai(n.code,l,u),u+=s,i!=null&&(o.size===wn&&(Ai(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return $r(t,e)}function ATe(r){if(r.charAt(0)!=="/")throw new Xn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Xu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Xn(`Component ${o} 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 Xn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Xn("Incomplete multiaddr");return e}function ITe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Xu.getProtocol(e.code);if(t==null)throw new Xn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function lft(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ma(e,t)}var uft=Symbol.for("nodejs.util.inspect.custom"),NZ=Symbol.for("@multiformats/multiaddr");function dft(r){if(r==null&&(r="/"),TTe(r))return r.getComponents();if(r instanceof Uint8Array)return STe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ATe(r);if(Array.isArray(r))return r;throw new Xn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var FL=class r{[NZ]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=dft(e),t.validate!==!1&&fft(this)}get bytes(){return this.#r==null&&(this.#r=CTe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ITe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new OL(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return zr(this.bytes,e.bytes)}[uft](){return`Multiaddr(${this.toString()})`}};function fft(r){r.getComponents().forEach(e=>{let t=Xu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function TTe(r){return!!r?.[NZ]}function Ea(r){return new FL(r)}var UZ=1e3,kTe=60*UZ;var K7r=120*kTe,DTe=1,KL=5e3,_Te=100;var EA=`${xCe}-circuit-relay`,z7r=2*kTe,$7r=BigInt(1<<17),Dm="/libp2p/circuit/relay/0.2.0/hop",FZ="/libp2p/circuit/relay/0.2.0/stop",H7r=30*UZ,V7r=30*UZ,KZ=300,PTe=4096,RTe=.001;var Jf;(function(r){let e;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Sm(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=_i((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),xx.codec().encode(o.peer,s)),o.reservation!=null&&(s.uint32(26),zL.codec().encode(o.reservation,s)),o.limit!=null&&(s.uint32(34),vx.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(40),Zn.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=xx.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=zL.codec().decode(o,o.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=vx.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=Zn.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Di(o,r.codec()),r.decode=(o,s)=>ki(o,r.codec(),s)})(Jf||(Jf={}));var $c;(function(r){let e;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Sm(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=_i((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),xx.codec().encode(o.peer,s)),o.limit!=null&&(s.uint32(26),vx.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(32),Zn.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=xx.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=vx.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=Zn.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Di(o,r.codec()),r.decode=(o,s)=>ki(o,r.codec(),s)})($c||($c={}));var xx;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={id:pn(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.id=t.bytes();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new fA('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(xx||(xx={}));var zL;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),HL.codec().encode(t.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.expire=t.uint64();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new fA('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}case 3:{s.voucher=HL.codec().decode(t,t.uint32(),{limits:o.limits?.voucher});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(zL||(zL={}));var vx;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.duration=t.uint32();break}case 2:{s.data=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(vx||(vx={}));var Zn;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Zn||(Zn={}));var zZ;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(zZ||(zZ={}));(function(r){r.codec=()=>Sm(zZ)})(Zn||(Zn={}));var $L;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={relay:pn(0),peer:pn(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.relay=t.bytes();break}case 2:{s.peer=t.bytes();break}case 3:{s.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})($L||($L={}));var HL;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.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&&(n.uint32(26),$L.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:pn(0),payloadType:pn(0),signature:pn(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=$L.codec().decode(t,t.uint32(),{limits:o.limits?.payload});break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(HL||(HL={}));var SA=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},VL=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},qL=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function $Z(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var CA=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},jL=At(st(bAe.matchers[0],Ct(290))),GL=At(Ct(290));function WL(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var AA=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 WL(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 WL(this.map.values(),e=>e.key)}values(){return WL(this.map.values(),e=>e.value)}get size(){return this.map.size}};var YL=class{filter;constructor(e,t){this.filter=fx(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 HZ(r,e=.001){return new YL(r,e)}var XL=class extends Ci{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Dm,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(Dm)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=LTe(n),i=LTe(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new yx({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=yA([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function LTe(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(We(e)).getTime()}var VZ=class extends Ci{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??KL,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(GL.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(jL.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new am(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>Ea(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function BTe(r){return new VZ(r)}var OTe="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var NTe=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=OTe[t[r]&63];return e};var hft=60*1e3*10,pft=60*1e3*5,mft=30*1e3,ZL=class extends Ci{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new AA,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??_Te,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??KL,this.started=!1,this.relayFilter=fx(100),this.reserveQueue=new yx({concurrency:t?.reservationConcurrency??DTe,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(EA)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[EA]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=NTe();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new am("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new qL("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new am("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let f=this.connectionManager.getConnections(e),g=!1;if(f.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),f.map(y=>y.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),g=!0),g&&$Z(s.reservation.expire)>hft)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new SA("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(J8.matches(a.remoteAddr))throw new VL("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=$Z(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-pft,mft),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async f=>{this.log.error("could not refresh reservation to relay %p - %e",e,f),await this.#t(e)}).catch(f=>{this.log.error("could not remove expired reservation to relay %p - %e",e,f)})},u),h;if(t==="discovered"){let f=this.pendingReservations.pop();if(f==null)throw new SA("Made reservation on relay but did not need any more discovered relays");h={timeout:d,reservation:c,type:t,connection:a.id,id:f}}else h={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,h),await this.peerStore.merge(e,{tags:{[EA]:{value:1,ttl:l}}}),this.#r();let p={relay:e,details:h};return this.safeDispatchEvent("relay:created-reservation",{detail:p}),p}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Dm,t),s=bA(n).pb(Jf);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Jf.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===Zn.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=Ea(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=Ea(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>Ea(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[EA]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=fx(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var qZ=class extends gx{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function jZ(r){return new qZ(r)}var gft=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Ea)}catch{return!1}return!0},UTe={maxInboundStopStreams:KZ,maxOutboundStopStreams:KZ,stopTimeout:3e4},JL=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??UTe.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??UTe.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new XL(e,{filter:t.discoveryFilter??HZ(PTe,RTe)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new ZL(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[B8]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[ACe](){return this.discovery!=null?["@libp2p/identify"]:[]}[M8]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(FZ,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await ECe(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await SCe(this.discovery,this.reservationStore),await this.components.registrar.unhandle(FZ),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=Ea(n[0]),s=Ea(n[n.length-1]),i=o.getComponents().find(p=>p.code===421)?.value,a=s.getComponents().find(p=>p.code===421)?.value;if(i==null||a==null){let p=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${p}`),new _8(`C${p}`)}let c=_Z(i),l=_Z(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new Fc("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Fc("circuit-relay:reuse-connection"));let h;try{t.onProgress?.(new Fc("circuit-relay:open-hop-stream")),h=await d.newStream(Dm,t);let p=bA(h).pb(Jf);t.onProgress?.(new Fc("circuit-relay:write-connect-message")),await p.write({type:Jf.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[Ea(s).bytes]}},t),t.onProgress?.(new Fc("circuit-relay:read-connect-response"));let f=await p.read(t);if(f.status!==Zn.OK)throw new D8(`failed to connect via relay with status ${f?.status?.toString()??"undefined"}`);let g=new CA(f.limit),y=jZ({stream:p.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:g.onData,onDataWrite:g.onData,log:h.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(y,{...t,limits:g.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,f.limit??"none",d.id),m}catch(p){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,p),h?.abort(p),p}}createListener(e){return BTe({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>jL.exactMatch(t)||GL.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>J8.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=bA(e).pb($c),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==$c.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!gft(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=BL(Hf(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.OK},{signal:n});let a=new CA(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=jZ({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function FTe(r={}){return e=>new JL(e,r)}var YZ=(r,e)=>e.some(t=>r instanceof t),KTe,zTe;function yft(){return KTe||(KTe=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bft(){return zTe||(zTe=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var XZ=new WeakMap,GZ=new WeakMap,QL=new WeakMap;function wft(r){let e=new Promise((t,n)=>{let o=()=>{r.removeEventListener("success",s),r.removeEventListener("error",i)},s=()=>{t(_m(r.result)),o()},i=()=>{n(r.error),o()};r.addEventListener("success",s),r.addEventListener("error",i)});return QL.set(e,r),e}function xft(r){if(XZ.has(r))return;let e=new Promise((t,n)=>{let o=()=>{r.removeEventListener("complete",s),r.removeEventListener("error",i),r.removeEventListener("abort",i)},s=()=>{t(),o()},i=()=>{n(r.error||new DOMException("AbortError","AbortError")),o()};r.addEventListener("complete",s),r.addEventListener("error",i),r.addEventListener("abort",i)});XZ.set(r,e)}var ZZ={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return XZ.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return _m(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};function qTe(r){ZZ=r(ZZ)}function vft(r){return bft().includes(r)?function(...e){return r.apply(JZ(this),e),_m(this.request)}:function(...e){return _m(r.apply(JZ(this),e))}}function Eft(r){return typeof r=="function"?vft(r):(r instanceof IDBTransaction&&xft(r),YZ(r,yft())?new Proxy(r,ZZ):r)}function _m(r){if(r instanceof IDBRequest)return wft(r);if(GZ.has(r))return GZ.get(r);let e=Eft(r);return e!==r&&(GZ.set(r,e),QL.set(e,r)),e}var JZ=r=>QL.get(r);function jTe(r,e,{blocked:t,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(r,e),a=_m(i);return n&&i.addEventListener("upgradeneeded",c=>{n(_m(i.result),c.oldVersion,c.newVersion,_m(i.transaction),c)}),t&&i.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}var Sft=["get","getKey","getAll","getAllKeys","count"],Cft=["put","add","delete","clear"],WZ=new Map;function $Te(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(WZ.get(e))return WZ.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,o=Cft.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Sft.includes(t)))return;let s=async function(i,...a){let c=this.transaction(i,o?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),o&&c.done]))[0]};return WZ.set(e,s),s}qTe(r=>({...r,get:(e,t,n)=>$Te(e,t)||r.get(e,t,n),has:(e,t)=>!!$Te(e,t)||r.has(e,t)}));var Aft=["continue","continuePrimaryKey","advance"],HTe={},QZ=new WeakMap,GTe=new WeakMap,Ift={get(r,e){if(!Aft.includes(e))return r[e];let t=HTe[e];return t||(t=HTe[e]=function(...n){QZ.set(this,GTe.get(this)[e](...n))}),t}};async function*Tft(...r){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...r)),!e)return;e=e;let t=new Proxy(e,Ift);for(GTe.set(t,e),QL.set(t,JZ(e));e;)yield t,e=await(QZ.get(t)||e.continue()),QZ.delete(t)}function VTe(r,e){return e===Symbol.asyncIterator&&YZ(r,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&YZ(r,[IDBIndex,IDBObjectStore])}qTe(r=>({...r,get(e,t,n){return VTe(e,t)?Tft:r.get(e,t,n)},has(e,t){return VTe(e,t)||r.has(e,t)}}));var kft="optimystic",Dft=2;async function WTe(r=kft,e=Dft){return jTe(r,e,{upgrade(t){t.objectStoreNames.contains("metadata")||t.createObjectStore("metadata"),t.objectStoreNames.contains("revisions")||t.createObjectStore("revisions"),t.objectStoreNames.contains("pending")||t.createObjectStore("pending"),t.objectStoreNames.contains("transactions")||t.createObjectStore("transactions"),t.objectStoreNames.contains("proofs")||t.createObjectStore("proofs"),t.objectStoreNames.contains("materialized")||t.createObjectStore("materialized"),t.objectStoreNames.contains("kv")||t.createObjectStore("kv")}})}var eJ=Ri(QTe(),1);var $ft="optimystic:db-p2p-storage-web";vd("db-p2p-storage-web",eJ.default);function e6e(r){return(0,eJ.default)(`${$ft}:${r}`)}var Hft=e6e("storage:indexeddb"),tJ=class{db;identity;constructor(e){this.db=e,this.identity=Rge("idb-handle",e)}storeIdentity(){return this.identity}async getMetadata(e){return this.db.get("metadata",e)}async putMetadata(e,t){await this.db.put("metadata",t,e)}async getRevision(e,t){return this.db.get("revisions",[e,t])}async putRevision(e,t,n){await this.db.put("revisions",n,[e,t])}async*rangeRevisions(e,t,n,o){let s=IDBKeyRange.bound([e,t],[e,n]),i=this.db.transaction("revisions","readonly"),a=i.objectStore("revisions"),c=[],l=await a.openCursor(s,o?"prev":"next");for(;l;)c.push([l.key[1],l.value]),l=await l.continue();await i.done;for(let u of c)yield u}async getPending(e,t){return this.db.get("pending",[e,t])}async putPending(e,t,n){await this.db.put("pending",n,[e,t])}async deletePending(e,t){await this.db.delete("pending",[e,t])}async*listPendingActionIds(e){let t=IDBKeyRange.bound([e],[e,[]]),n=this.db.transaction("pending","readonly"),o=n.objectStore("pending"),s=[],i=await o.openKeyCursor(t);for(;i;)s.push(i.key[1]),i=await i.continue();await n.done;for(let a of s)yield a}async getTransaction(e,t){return this.db.get("transactions",[e,t])}async putTransaction(e,t,n){await this.db.put("transactions",n,[e,t])}async getProof(e,t){return this.db.get("proofs",[e,t])}async putProof(e,t,n){await this.db.put("proofs",n,[e,t])}async getMaterialized(e,t){return this.db.get("materialized",[e,t])}async putMaterialized(e,t,n){await this.db.put("materialized",n,[e,t])}async deleteMaterialized(e,t){await this.db.delete("materialized",[e,t])}async promote(e,t){let n=[e,t],o=this.db.transaction(["pending","transactions"],"readwrite"),s=o.objectStore("pending"),i=o.objectStore("transactions"),a=await s.get(n);if(!a)throw await o.done.catch(()=>{}),new Error(`Pending action ${t} not found for block ${e}`);await i.put(a,n),await s.delete(n),await o.done}async*listBlockIds(){let e=await this.db.getAllKeys("metadata");for(let t of e)yield t}async approximateBytesUsed(){try{return(await navigator.storage?.estimate?.())?.usage??0}catch(e){return Hft("navigator.storage.estimate() failed: %o",e),0}}},r3=class extends gf{constructor(e){super(new tJ(e))}};var $J=Ri(s6e(),1);import{QuereusError as Aa,StatusCode as Ia,builtinCollationResolver as _pt,BINARY_COLLATION as Ppt,compareSqlValues as Rpt,VirtualTable as Q6e,ConflictResolution as Bm,buildCheckConstraintSchema as Lpt,collectTableConstraintNames as Mpt,PhysicalType as Bpt,TEXT_TYPE as Opt,buildColumnIndexMap as eke,inferType as Npt,getTypeOrDefault as $6e,ConstraintError as Upt}from"@quereus/quereus";function rht(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function rJ(r,e,t=""){let n=rht(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function nJ(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 i6e(r,e){rJ(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function IA(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function s3(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Sa(r,e){return r<<32-e|r>>>e}function a6e(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function i3(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var c6e=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});Uo();Be();var oJ=class{async connect(e,t){return{}}},sJ=class{nodes;responsibilityK;failures;ring;constructor(e,t,n={}){this.nodes=e,this.responsibilityK=t,this.failures=n}async findCoordinator(e,t){let n=new Set((t?.excludedPeers??[]).map(s=>s.toString())),o=(await this.nearest(e,this.nodes.length)).find(s=>!n.has(s.peerId.toString()));if(!o)throw new Error("No coordinator available for key (all candidates excluded)");return o.peerId}async findCluster(e){if(this.failures.findClusterFails)return{};let t={};for(let n of await this.nearest(e,this.responsibilityK))t[n.peerId.toString()]={multiaddrs:["/ip4/127.0.0.1/tcp/8000"],publicKey:z(n.peerId.publicKey.raw,"base64url")};return t}async nearest(e,t){let{store:n,byId:o}=await this.ringStore();return Tp(n,await Jt(e),Math.min(t,o.size)).map(i=>o.get(i))}ringStore(){if(this.ring?.size!==this.nodes.length){let e=[...this.nodes];this.ring={size:e.length,ready:(async()=>{let t=new tf,n=new Map;for(let o of e)t.upsert(o.peerId.toString(),await Or(o.peerId)),n.set(o.peerId.toString(),o);return{store:t,byId:n}})()}}return this.ring.ready}},nht=(r,e,t)=>async(n,o)=>{if(n===e||t.silentPeers?.has(n))return;let s=r.find(i=>i.peerId.toString()===n);if(s)return await q6(s.storageRepo,o)};function oht(r){return X6({clusterSize:r.clusterSize,clusterPolicy:{...r.clusterPolicy,superMajorityThreshold:r.clusterPolicy?.superMajorityThreshold??r.superMajorityThreshold,allowDownsize:r.clusterPolicy?.allowDownsize??r.allowClusterDownsize}})}function sht(r,e){let t=new Uint8Array(32),n=new DataView(t.buffer);return n.setUint32(0,r),n.setUint32(4,e),t}async function l6e(r,e){let t={},n=oht(e),o=await Promise.all(Array.from({length:r},async(m,w)=>{let b=e.keySeed===void 0?await L6("Ed25519"):await ble("Ed25519",sht(e.keySeed,w));return{peerId:RE(b),privateKey:b}})),s=[],i=new oJ,a=new Map,c=new Map,l=new Map,u=new sJ(s,e.responsibilityK,t),d=e.wrapKeyNetwork?e.wrapKeyNetwork(u):u,h=m=>{let w=m.toString();return{findCoordinator:(b,x)=>d.findCoordinator(b,x),async findCluster(b){let x=await d.findCluster(b),S=t.partitionSides?.find(T=>T.has(w));if(S)for(let T of Object.keys(x))S.has(T)||delete x[T];return x}}},p=(m,w)=>{let{peerId:b,privateKey:x}=m,{rawStorage:S,index:T}=c.get(b.toString()),A=new Dl(R=>new mc(R,S)),v=nht(s,b.toString(),t),C=W6({selfPeerId:b.toString(),fetchArchive:async(R,k)=>w.stopped?void 0:await v(R,k),saveReplicatedBlock:(R,k,I,E)=>A.saveReplicatedBlock(R,k,I,E),simpleMajorityThreshold:n.simpleMajorityThreshold,superMajorityThreshold:n.superMajorityThreshold,repairCorroborationClusterSize:n.repairCorroborationClusterSize,onBlockHolders:e.onBlockHolders&&(R=>e.onBlockHolders(m,R))});a.set(b.toString(),C);let P=m.keyNetwork,F=e.deriveExpectedCluster?R=>e.deriveExpectedCluster(m,R):async R=>({peers:await P.findCluster(He(R))??{},confidence:e.meshConfidence?.(m)??1});m.storageRepo=A,m.clusterMember=J6({storageRepo:A,peerNetwork:i,peerId:b,privateKey:x,consensusConfig:n,reconcileBlock:C,deriveExpectedCluster:F,validator:e.validatorFactory?.(T,b),onBlockHolders:e.onBlockHolders&&(R=>e.onBlockHolders(m,R))})},f=m=>{let w=s.find(b=>b.peerId.equals(m));if(!w)throw new Error(`Unknown peer: ${m.toString()}`);return{async update(b){if(t.onClusterDelivery?.(m.toString(),b),t.failingPeers?.has(m.toString()))throw new Error(`Peer ${m.toString()} is unreachable`);return w.clusterMember.update(b)}}},g=(m,w)=>{let b=()=>new Error(`${m.peerId.toString()} was restarted; this instance is stopped`),x=async(A,v,C)=>{if(w.stopped)throw b();if(t.silentPeers?.has(A.toString()))throw new Error(`Peer ${A.toString()} is silent`);let P=s.find(I=>I.peerId.equals(A));if(!P)return;let R=(await P.storageRepo.get({blockIds:[v],context:C},{skipClusterFetch:!0}))[v]?.state?.latest;if(!R)return;let k=await sp(P.storageRepo,v,R);return k?{...R,proof:k}:R},S=m.keyNetwork,T=WD(S,A=>{let v=f(A);return{async update(C){if(w.stopped)throw b();return await v.update(C)}}},{...n});m.coordinatorRepo=T({storageRepo:m.storageRepo,localCluster:m.clusterMember,localPeerId:m.peerId,clusterLatestCallback:x,acquireBlockFromCohort:a.get(m.peerId.toString()),onBlockHolders:e.onBlockHolders&&(A=>e.onBlockHolders(m,A))})};for(let[m,{peerId:w,privateKey:b}]of o.entries()){let x=w.toString();c.set(x,{rawStorage:e.rawStorageFactory?e.rawStorageFactory(m):new Vs,index:m});let S={stopped:!1};l.set(x,S);let T={peerId:w,privateKey:b,keyNetwork:h(w),storageRepo:void 0,clusterMember:void 0,coordinatorRepo:void 0};p(T,S),s.push(T)}for(let m of s)g(m,l.get(m.peerId.toString()));return{nodes:s,failures:t,keyNetwork:d,restart:m=>{let w=m.peerId.toString();if(!s.includes(m))throw new Error(`restart: ${w} is not a node of this mesh`);l.get(w).stopped=!0,m.clusterMember.dispose();let b={stopped:!1};l.set(w,b),p(m,b),g(m,b)}}}var u6e=(r,e={})=>iht(r,e,void 0);function iht(r,e,t){let n=new Map;for(let o of r.nodes){let s=o.coordinatorRepo;n.set(o.peerId.toString(),e.wrapRepo?e.wrapRepo(s,o):s)}return new Mg({timeoutMs:e.timeoutMs??5e3,abortOrCancelTimeoutMs:e.abortOrCancelTimeoutMs??5e3,keyNetwork:r.keyNetwork,getRepo:o=>{let s=n.get(o.toString());if(!s)throw new Error(`Unknown peer ${o.toString()}`);return s},localPeerId:t?.peerId})}var NJ=Ri(m6e(),1);var uJ={};W(uJ,{base10:()=>Iht});var j$r=new Uint8Array(0);function g6e(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 Zu(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Mm(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Mm(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function y6e(r){return new TextEncoder().encode(r)}function b6e(r){return new TextDecoder().decode(r)}function wht(r){return r?.buffer instanceof ArrayBuffer}function Mm(r){return wht(r)?r:r.slice()}function xht(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var vht=xht,Eht=vht,x6e=Eht;var iJ=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")}},aJ=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 v6e(this,e)}},cJ=class{decoders;constructor(e){this.decoders=e}or(e){return v6e(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 v6e(r,e){return new cJ({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var lJ=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new iJ(e,t,n),this.decoder=new aJ(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Px({name:r,prefix:e,encode:t,decode:n}){return new lJ(r,e,t,n)}function Qf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=x6e(t,r);return Px({prefix:e,name:r,encode:n,decode:s=>Zu(o(s))})}function Sht(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Cht(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Aht(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function vr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Aht(n);return Px({prefix:e,name:r,encode(s){return Cht(s,n,t)},decode(s){return Sht(s,o,t,r)}})}var Iht=Qf({prefix:"9",name:"base10",alphabet:"0123456789"});var dJ={};W(dJ,{base16:()=>Tht,base16upper:()=>kht});var Tht=vr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kht=vr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fJ={};W(fJ,{base2:()=>Dht});var Dht=vr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var hJ={};W(hJ,{base256emoji:()=>Mht});var E6e=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}"),_ht=E6e.reduce((r,e,t)=>(r[t]=e,r),[]),Pht=E6e.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Rht(r){return r.reduce((e,t)=>(e+=_ht[t],e),"")}function Lht(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Pht[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Mht=Px({prefix:"\u{1F680}",name:"base256emoji",encode:Rht,decode:Lht});var pJ={};W(pJ,{base32:()=>Rx,base32hex:()=>Uht,base32hexpad:()=>Kht,base32hexpadupper:()=>zht,base32hexupper:()=>Fht,base32pad:()=>Oht,base32padupper:()=>Nht,base32upper:()=>Bht,base32z:()=>$ht});var Rx=vr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bht=vr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Oht=vr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nht=vr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Uht=vr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Fht=vr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kht=vr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zht=vr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$ht=vr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mJ={};W(mJ,{base36:()=>TA,base36upper:()=>Hht});var TA=Qf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Hht=Qf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gJ={};W(gJ,{base58btc:()=>Hc,base58flickr:()=>Vht});var Hc=Qf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vht=Qf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yJ={};W(yJ,{base64:()=>qht,base64pad:()=>jht,base64url:()=>Ght,base64urlpad:()=>Wht});var qht=vr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jht=vr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ght=vr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Wht=vr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var bJ={};W(bJ,{base8:()=>Yht});var Yht=vr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wJ={};W(wJ,{identity:()=>Xht});var Xht=Px({prefix:"\0",name:"identity",encode:r=>b6e(r),decode:r=>y6e(r)});var cHr=new TextEncoder,lHr=new TextDecoder;var vJ={};W(vJ,{identity:()=>wpt});var Qht=A6e,S6e=128,ept=127,tpt=~ept,rpt=Math.pow(2,31);function A6e(r,e,t){e=e||[],t=t||0;for(var n=t;r>=rpt;)e[t++]=r&255|S6e,r/=128;for(;r&tpt;)e[t++]=r&255|S6e,r>>>=7;return e[t]=r|0,A6e.bytes=t-n+1,e}var npt=xJ,opt=128,C6e=127;function xJ(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw xJ.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&C6e)<<o:(i&C6e)*Math.pow(2,o),o+=7}while(i>=opt);return xJ.bytes=s-n,t}var spt=Math.pow(2,7),ipt=Math.pow(2,14),apt=Math.pow(2,21),cpt=Math.pow(2,28),lpt=Math.pow(2,35),upt=Math.pow(2,42),dpt=Math.pow(2,49),fpt=Math.pow(2,56),hpt=Math.pow(2,63),ppt=function(r){return r<spt?1:r<ipt?2:r<apt?3:r<cpt?4:r<lpt?5:r<upt?6:r<dpt?7:r<fpt?8:r<hpt?9:10},mpt={encode:Qht,decode:npt,encodingLength:ppt},gpt=mpt,kA=gpt;function DA(r,e=0){return[kA.decode(r,e),kA.decode.bytes]}function Lx(r,e,t=0){return kA.encode(r,e,t),e}function Mx(r){return kA.encodingLength(r)}function Ox(r,e){let t=e.byteLength,n=Mx(r),o=n+Mx(t),s=new Uint8Array(o+t);return Lx(r,s,0),Lx(t,s,n),s.set(e,o),new Bx(r,t,e,s)}function I6e(r){let e=Zu(r),[t,n]=DA(e),[o,s]=DA(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Bx(t,o,i,e)}function T6e(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&g6e(r.bytes,t.bytes)}}var Bx=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Mm(n),this.bytes=Mm(o)}};var k6e=0,ypt="identity",D6e=Zu;function bpt(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 Ox(k6e,D6e(r))}var wpt={code:k6e,name:ypt,encode:D6e,digest:bpt};var CJ={};W(CJ,{sha256:()=>vpt,sha512:()=>Ept});var xpt=20;function SJ({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new EJ(r,e,t,n,o)}var EJ=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??xpt,this.maxDigestLength=s}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?_6e(n,this.code,t?.truncate):n.then(o=>_6e(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _6e(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 Ox(e,r)}function R6e(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var vpt=SJ({name:"sha2-256",code:18,encode:R6e("SHA-256")}),Ept=SJ({name:"sha2-512",code:19,encode:R6e("SHA-512")});function L6e(r,e){let{bytes:t,version:n}=r;return n===0?Cpt(t,AJ(r),e??Hc.encoder):Apt(t,AJ(r),e??Rx.encoder)}var M6e=new WeakMap;function AJ(r){let e=M6e.get(r);if(e==null){let t=new Map;return M6e.set(r,t),t}return e}var u3=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Mm(o),this["/"]=this.bytes}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!==PA)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ipt)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=Ox(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&&T6e(e.multihash,n.multihash)}toString(e){return L6e(this,e)}toJSON(){return{"/":L6e(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??B6e(n,o,s.bytes))}else if(t[Tpt]===!0){let{version:n,multihash:o,code:s}=t,i=I6e(o);return r.create(n,s,i)}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!==PA)throw new Error(`Version 0 CID must use dag-pb (code: ${PA}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=B6e(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,PA,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,o=Zu(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Bx(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=DA(e.subarray(t));return t+=h,d},o=n(),s=PA;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Spt(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return AJ(s).set(n,e),s}};function Spt(r,e){switch(r[0]){case"Q":{let t=e??Hc;return[Hc.prefix,t.decode(`${Hc.prefix}${r}`)]}case Hc.prefix:{let t=e??Hc;return[Hc.prefix,t.decode(r)]}case Rx.prefix:{let t=e??Rx;return[Rx.prefix,t.decode(r)]}case TA.prefix:{let t=e??TA;return[TA.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 Cpt(r,e,t){let{prefix:n}=t;if(n!==Hc.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Apt(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var PA=112,Ipt=18;function B6e(r,e,t){let n=Mx(r),o=n+Mx(e),s=new Uint8Array(o+t.byteLength);return Lx(r,s,0),Lx(e,s,n),s.set(t,o),s}var Tpt=Symbol.for("@ipld/js-cid/CID");var IJ={...wJ,...fJ,...bJ,...uJ,...dJ,...pJ,...mJ,...gJ,...yJ,...hJ},PHr={...CJ,...vJ};function O6e(r=0){return new Uint8Array(r)}function U6e(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var N6e=U6e("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),TJ=U6e("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=O6e(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),kpt={utf8:N6e,"utf-8":N6e,hex:IJ.base16,latin1:TJ,ascii:TJ,binary:TJ,...IJ},d3=kpt;function RA(r,e="utf8"){let t=d3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function F6e(r,e,t){return r&e^~r&t}function K6e(r,e,t){return r&e^r&t^e&t}var f3=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=s3(this.buffer)}update(e){nJ(this),rJ(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=s3(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){nJ(this),i6e(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,IA(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=s3(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must 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 d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ju=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Dpt=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]),eh=new Uint32Array(64),kJ=class extends f3{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)eh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=eh[d-15],p=eh[d-2],f=Sa(h,7)^Sa(h,18)^h>>>3,g=Sa(p,17)^Sa(p,19)^p>>>10;eh[d]=g+eh[d-7]+f+eh[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=Sa(a,6)^Sa(a,11)^Sa(a,25),p=u+h+F6e(a,c,l)+Dpt[d]+eh[d]|0,g=(Sa(n,2)^Sa(n,13)^Sa(n,22))+K6e(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){IA(eh)}destroy(){this.set(0,0,0,0,0,0,0,0),IA(this.buffer)}},DJ=class extends kJ{A=Ju[0]|0;B=Ju[1]|0;C=Ju[2]|0;D=Ju[3]|0;E=Ju[4]|0;F=Ju[5]|0;G=Ju[6]|0;H=Ju[7]|0;constructor(){super(32)}};var z6e=a6e(()=>new DJ,c6e(1));function _J(r,e="utf8"){let t=d3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Fpt="optimystic:quereus-plugin";vd("quereus-plugin",NJ.default);function b3(r){return(0,NJ.default)(`${Fpt}:${r}`)}function tke(r,e){return`${r}@${e.replace(/[\s%@,]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)}`}var H6e=b3("collection-factory");function Kpt(){return V(i3(4))}var zpt=class{nodeTagValue=Kpt();transactors=new Map;libp2pNodes=new Map;customTransactorCtors=new Map;customKeyNetworkCtors=new Map;readCacheLeases=[];async createOrGetCollection(r,e){let t=this.getCachedCollection(r,e);if(t)return t;let{transactor:n,collectionId:o,keyExtractor:s,compare:i}=await this.resolveTreeArgs(r),a=await Bv.createOrOpen(n,o,s,i);return this.cacheCollection(r,e,a),a}async getCollection(r,e){let t=this.getCachedCollection(r,e);if(t)return t;let{transactor:n,collectionId:o,keyExtractor:s,compare:i}=await this.resolveTreeArgs(r),a=await Bv.open(n,o,s,i);if(a)return this.cacheCollection(r,e,a),a}async resolveTreeArgs(r){let e=await this.getOrCreateTransactor(r),t=this.parseCollectionId(r.collectionUri);return{transactor:e,collectionId:t,keyExtractor:s=>this.extractKeyFromEntry(s),compare:(s,i)=>s<i?-1:s>i?1:0}}getCachedCollection(r,e){let t=this.getCollectionKey(r);return e?.isActive?e.collections.get(t):void 0}cacheCollection(r,e,t){e?.isActive&&e.collections.set(this.getCollectionKey(r),t)}async createTransactor(r){switch(r.transactor){case"network":return await this.createNetworkTransactor(r);case"local":return await this.createLocalTransactor(r);case"test":return await this.createTestTransactor();case"mesh-test":return await this.createMeshTestTransactor();default:return await this.createCustomTransactor(r.transactor)}}async getOrCreateTransactor(r){let e=this.getTransactorKey(r);if(this.transactors.has(e))return this.transactors.get(e);let t=await this.createTransactor(r);return this.transactors.set(e,t),t}async subscribeToCollectionChanges(r,e,t){let n=await this.getOrCreateTransactor(r);return wne(n)?n.onCollectionChange(e,t):(H6e(`[optimystic] transactor '${r.transactor}' does not support change notifications; reactive watch is a no-op for collection '${e}'`),()=>{})}async createNetworkTransactor(r){var e,t,n,o;let s=this.getNodeKey(r),i=this.libp2pNodes.get(s);if(!i){let p=await S8({port:((e=r.libp2pOptions)==null?void 0:e.port)??0,networkName:((t=r.libp2pOptions)==null?void 0:t.networkName)??"optimystic",bootstrapNodes:((n=r.libp2pOptions)==null?void 0:n.bootstrapNodes)??[],fretProfile:"edge",clusterSize:1,clusterPolicy:{allowDownsize:!0,sizeTolerance:1},arachnode:{enableRingZulu:!0}}),f=p.coordinatedRepo,g=p.blockChangeNotifier;i={node:p,coordinatedRepo:f,blockChangeNotifier:g},this.libp2pNodes.set(s,i)}let{node:a,coordinatedRepo:c,blockChangeNotifier:l}=i,u=`/optimystic/${((o=r.libp2pOptions)==null?void 0:o.networkName)??"optimystic"}`,d=this.resolveKeyNetwork(r.keyNetwork,a,u),h=p=>p.toString()===a.peerId.toString()?c:qD.create(p,d,u);return new Mg({timeoutMs:3e4,abortOrCancelTimeoutMs:5e3,dialTimeoutMs:3e3,keyNetwork:d,getRepo:h,localChangeNotifier:l,localPeerId:a.peerId})}async createLocalTransactor(r){var e;let{storage:t,lease:n}=r_(((e=r.rawStorageFactory)==null?void 0:e.call(r))??new Vs,"quereus:local");n&&this.readCacheLeases.push(n);let o=new Dl(i=>new mc(i,t));return{async get(i){return await o.get(i)},async getStatus(i){throw new Error("getStatus not implemented in local transactor")},async pend(i){return await o.pend(i)},async commit(i){return await o.commit(i)},async cancel(i){return await o.cancel(i)},onCollectionChange:o.onCollectionChange.bind(o)}}async createTestTransactor(){let r=new Vs,e=new Dl(n=>new mc(n,r));return{async get(n){return await e.get(n)},async getStatus(n){throw new Error("getStatus not implemented in test transactor")},async pend(n){return await e.pend(n)},async commit(n){return await e.commit(n)},async cancel(n){return await e.cancel(n)},onCollectionChange:e.onCollectionChange.bind(e)}}async createMeshTestTransactor(){let r=await l6e(1,{responsibilityK:1,clusterSize:1,superMajorityThreshold:.51});return u6e(r)}async createCustomTransactor(r){let e=this.customTransactorCtors.get(r);if(!e)throw new Error(`Custom transactor '${r}' not found. Register it first using collectionFactory.registerCustomTransactor().`);return new e}resolveKeyNetwork(r,e,t){switch(r){case"libp2p":{let n=e.keyNetwork;return n||new Qb(e,uS,void 0,void 0,void 0,void 0,t)}default:{let n=this.customKeyNetworkCtors.get(r);if(!n)throw new Error(`Custom key network '${r}' not found. Register it first using collectionFactory.registerCustomKeyNetwork().`);return new n}}}parseCollectionId(r){if(!r)throw new Error("Collection URI is required");return r.startsWith("tree://")?r.substring(7):r}getCollectionId(r){return this.parseCollectionId(r.collectionUri)}extractKeyFromEntry(r){return r[0]}getCollectionKey(r){return`${r.collectionUri}:${r.transactor}:${r.keyNetwork}`}getTransactorKey(r){return`${r.transactor}:${r.keyNetwork}`}getPeerId(r){let e=this.getNodeKey(r),t=this.libp2pNodes.get(e);return t?.node.peerId.toString()}getSigner(r){let e=this.getNodeKey(r),t=this.libp2pNodes.get(e),n=t?.node.peerPrivateKey;if(n)return async o=>V(await Bs(n,o))}registerLibp2pNode(r,e,t){let n=`${r}:0`;this.libp2pNodes.set(n,{node:e,coordinatedRepo:t})}nodeTag(){return this.nodeTagValue}setNodeTag(r){if(!/^\S+$/.test(r))throw new Error(`Node tag must be a single non-empty run of non-whitespace characters; got ${JSON.stringify(r)}`);this.nodeTagValue=r}registerTransactor(r,e){this.transactors.set(r,e)}registerCustomTransactor(r,e){this.customTransactorCtors.set(r,e)}registerCustomKeyNetwork(r,e){this.customKeyNetworkCtors.set(r,e)}getNodeKey(r){var e,t;let n=((e=r.libp2pOptions)==null?void 0:e.networkName)??"optimystic",o=((t=r.libp2pOptions)==null?void 0:t.port)??0;return`${n}:${o}`}clearCache(){this.transactors.clear()}async dispose(){let r=this.readCacheLeases;this.readCacheLeases=[],this.transactors.clear();for(let e of r)await e.release()}async shutdown(){for(let[r,{node:e}]of this.libp2pNodes.entries())H6e("Stopping libp2p node: %s",r),await e.stop();this.libp2pNodes.clear(),await this.dispose()}};function $pt(r){let e=i3(16);if(r){let n=new TextEncoder().encode(r),s=z6e(n).slice(0,16),i=new Uint8Array(32);return i.set(s,0),i.set(e,16),RA(i,"base64url")}let t=new Uint8Array(32);return t.set(e,0),t.set(i3(16),16),RA(t,"base64url")}var PJ=b3("txn-bridge"),V6e=(r,e)=>{var t;return((t=r.describe)==null?void 0:t.call(r))??`tree#${e}`},Hpt=r=>r.committedRevision===void 0?"unknown":r.committedRevision()??"none",Vpt=r=>r.committedActionId===void 0?"unknown":r.committedActionId()??"none",BJ=class extends Error{constructor(r,e,t){super(`Legacy multi-tree commit was not atomic: ${r.length} tree(s) were durably committed to storage before the commit failed and CANNOT be rolled back. Persisted (now out of sync with the unpersisted trees): [${r.join(", ")}]. Not persisted (reverted in-memory only): [${e.join(", ")}]. Underlying failure: ${t instanceof Error?t.message:String(t)}`),this.persisted=r,this.unpersisted=e,this.reason=t,this.name="PartialCommitError"}},rke=class nke extends Aa{constructor(e,t){super(e,Ia.BUSY,t),this.name="ConcurrentModificationError",Object.setPrototypeOf(this,nke.prototype)}},qpt="legacy",jpt=5*6e4,Gpt=class{currentTransaction=null;peerId;degradedReason=null;collectionFactory;accumulatedStatements=[];dirtyTrees=new Map;collectionRegistry=new Map;keyTakenMessages=new Map;entryChangedRenderers=new Map;savepoints=new Map;session=null;coordinator=null;engine=null;schemaHashProvider=null;constructor(r){this.collectionFactory=r}configureTransactionMode(r,e,t){this.coordinator=r,this.engine=e,this.schemaHashProvider=t}isTransactionModeEnabled(){return this.coordinator!==null&&this.engine!==null}registerCollection(r){let e=this.collectionRegistry.get(r.id);if(this.collectionRegistry.set(r.id,r),e!==r)for(let t of this.savepoints.values())t.has(r)||t.set(r,r.snapshotPending())}getCollectionRegistry(){return this.collectionRegistry}registerKeyTakenMessage(r,e){this.keyTakenMessages.set(r,e)}registerEntryChangedRenderer(r,e){this.entryChangedRenderers.set(r,e)}mapCommitRefusal(r){for(let e=r;e instanceof Error;e=e.cause)if(e instanceof Pg){let t=this.mapRefusal(e);return t===void 0||!(r instanceof Error)||r.message===t.message?r:t.raise(r)}return r}mapRefusal(r){var e;if(r instanceof Th){let t=this.keyTakenMessages.get(r.collectionId);return t===void 0?void 0:{message:t,raise:n=>new Upt(t,Ia.CONSTRAINT,n)}}if(r instanceof Rg){let t=(e=this.entryChangedRenderers.get(r.collectionId))==null?void 0:e(String(r.key));return t===void 0?void 0:{message:t,raise:n=>new rke(t,n)}}}async beginTransaction(r){var e;if((e=this.currentTransaction)!=null&&e.isActive)return this.currentTransaction;let t=await this.collectionFactory.getOrCreateTransactor(r),n=this.collectionFactory.getPeerId(r);if(this.peerId=n,this.accumulatedStatements=[],this.dirtyTrees.clear(),this.savepoints.clear(),this.coordinator&&this.engine&&this.schemaHashProvider){let s=await this.schemaHashProvider(),i=this.collectionFactory.getSigner(r);this.session=await $v.create(this.coordinator,this.engine,n,s,void 0,i)}else this.session=null;let o=this.session?this.session.getStampId():$pt(n);return this.currentTransaction={transactor:t,isActive:!0,collections:new Map,stampId:o},this.currentTransaction}async commitTransaction(){var r;if(!((r=this.currentTransaction)!=null&&r.isActive))throw new Error("No active transaction to commit");try{if(this.session){PJ.enabled&&this.logCommitCollections("session",[...this.collectionRegistry].map(([t,n])=>({id:String(t),staged:n.hasUnsyncedChanges(),rev:n.committedRevision()??"none",action:n.committedActionId()??"none"})));let e=await this.session.commit();if(!e.success)throw new Error(e.error||"Transaction commit failed")}else await this.commitDirtyTreesLegacy();this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,this.dirtyTrees.clear(),this.savepoints.clear(),this.degradedReason=null}catch(e){throw e instanceof BJ?(this.degradedReason=e.message,e):e instanceof ni?(this.degradedReason=e.message,this.currentTransaction.collections.clear(),this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,this.dirtyTrees.clear(),this.savepoints.clear(),e):(await this.rollbackTransaction(),this.mapCommitRefusal(e))}}logCommitCollections(r,e){let t=[...e].sort((o,s)=>o.id<s.id?-1:o.id>s.id?1:0),n=t.map(o=>`${o.id}=${o.staged===void 0?"unknown":o.staged?"staged":"clean"}`).join(" ");PJ("commit:collections mode=%s count=%d%s revs=%s node=%s",r,t.length,n?` ${n}`:"",t.map(o=>`${o.id}:${tke(o.rev,o.action)}`).join(","),this.collectionFactory.nodeTag())}async commitDirtyTreesLegacy(){let r=[...this.dirtyTrees.keys()];PJ.enabled&&this.logCommitCollections("legacy",r.map((t,n)=>{var o;return{id:V6e(t,n),staged:(o=t.hasUnsyncedChanges)==null?void 0:o.call(t),rev:Hpt(t),action:Vpt(t)}}));let e=this.legacyBatch(r);if(e===void 0){await this.sweepDirtyTreesLegacy(r);return}await this.commitBatchLegacy(e)}legacyBatch(r){var e;let t=r.filter(s=>{var i;return((i=s.hasUnsyncedChanges)==null?void 0:i.call(s))!==!1});if(t.length<2)return;let n=[];for(let s of t){let i=(e=s.getCollection)==null?void 0:e.call(s);if(i===void 0)return;n.push(i)}let o=n[0].transactor;if(!n.some(s=>s.transactor!==o)&&new Set(n.map(s=>s.id)).size===n.length)return{collections:n,transactor:o}}async commitBatchLegacy({collections:r,transactor:e}){let t=new zv(e,new Map(r.map(n=>[n.id,n])),{pendValidation:"none"});try{await t.commit(await this.legacyTransaction())}catch(n){throw n instanceof ni&&this.restoreUncommittedTrees(new Set(n.committedCollections)),n}}async legacyTransaction(){let r=await Rv(this.peerId??"local",Date.now(),"",qpt,jpt);return{stamp:r,statements:[],reads:[],id:await Lv(r.id,[],[])}}restoreUncommittedTrees(r){var e,t;for(let[n,o]of this.dirtyTrees){let s=(t=(e=n.getCollection)==null?void 0:e.call(n))==null?void 0:t.id;(s===void 0||!r.has(s))&&n.restore(o)}}async sweepDirtyTreesLegacy(r){var e;let t=[];if(r.length>1){for(let n of r)if(n.update!==void 0&&((e=n.hasUnsyncedChanges)==null?void 0:e.call(n))!==!1)try{await n.update()}catch(o){throw this.mapCommitRefusal(o)}}for(let n of r)try{await n.sync(),t.push(n)}catch(o){let s=this.mapCommitRefusal(o);if(t.length===0)throw s;let i=r.filter(u=>!t.includes(u));for(let u of i)u.restore(this.dirtyTrees.get(u));let a=u=>V6e(u,r.indexOf(u)),c=t.map(a),l=i.map(a);throw this.dirtyTrees.clear(),this.savepoints.clear(),this.currentTransaction.collections.clear(),this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,new BJ(c,l,s)}}async rollbackTransaction(){var r;if(!((r=this.currentTransaction)!=null&&r.isActive))throw new Error("No active transaction to rollback");if(this.session&&!this.session.isRolledBack())try{await this.session.rollback()}catch{}if(!this.session)for(let[e,t]of this.dirtyTrees)e.restore(t);this.dirtyTrees.clear(),this.savepoints.clear(),this.currentTransaction.collections.clear(),this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,this.degradedReason=null}getCurrentTransaction(){return this.currentTransaction}isDegraded(){return this.degradedReason!==null}getDegradedReason(){return this.degradedReason??void 0}getSession(){return this.session}isTransactionActive(){var r;return((r=this.currentTransaction)==null?void 0:r.isActive)??!1}markDirty(r){this.dirtyTrees.has(r)||this.dirtyTrees.set(r,r.snapshot())}forgetTree(r){var e;this.dirtyTrees.delete(r);let t=(e=r.getCollection)==null?void 0:e.call(r);t&&this.collectionRegistry.get(t.id)===t&&this.collectionRegistry.delete(t.id)}getDirtySnapshot(r){return this.dirtyTrees.get(r)}async addStatement(r){var e;if((e=this.currentTransaction)!=null&&e.isActive&&(this.accumulatedStatements.push(r),this.session)){let t=await this.session.execute(r,[]);if(!t.success)throw new Error(`Failed to record statement in transaction: ${t.error}`)}}getStatements(){return this.accumulatedStatements}getStatementCount(){return this.accumulatedStatements.length}createSavepoint(r){if(this.session||this.savepoints.has(r))return;let e=new Map;for(let t of this.collectionRegistry.values())e.set(t,t.snapshotPending());this.savepoints.set(r,e)}rollbackToSavepoint(r){let e=this.savepoints.get(r);if(e){for(let[t,n]of e)t.restorePending(n);for(let t of this.savepoints.keys())t>r&&this.savepoints.delete(t)}}releaseSavepoint(r){for(let e of this.savepoints.keys())e>=r&&this.savepoints.delete(e)}async cleanup(){var r;(r=this.currentTransaction)!=null&&r.isActive&&await this.rollbackTransaction(),this.currentTransaction=null}},Wpt=0,RJ=class{connectionId;tableName;txnBridge;options;constructor(r,e,t){this.connectionId=`optimystic-${r}-${++Wpt}`,this.tableName=r,this.txnBridge=e,this.options=t}async begin(){await this.txnBridge.beginTransaction(this.options)}async commit(){let r=this.txnBridge.getCurrentTransaction();r?.isActive||await this.txnBridge.beginTransaction(this.options),await this.txnBridge.commitTransaction()}async rollback(){await this.txnBridge.rollbackTransaction()}createSavepoint(r){this.txnBridge.createSavepoint(r)}releaseSavepoint(r){this.txnBridge.releaseSavepoint(r)}rollbackToSavepoint(r){this.txnBridge.rollbackToSavepoint(r)}async disconnect(){let r=this.txnBridge.getCurrentTransaction();r?.isActive&&await this.txnBridge.rollbackTransaction()}},oke="\0",Ypt="",ske="\0",Xpt="\xFF",ike="";function Zpt(r){return r.includes("\0")?r.replace(/\x00/g,"\0\xFF"):r}function Jpt(r){return r===null?oke:Ypt+Zpt(r)+ske}function MA(r){let e="";for(let t of r)e+=Jpt(t);return e}function m3(r){let e=[],t=0,n=r.length;for(;t<n;){if(r[t]===oke){e.push({isNull:!0,payload:""}),t+=1;continue}t+=1;let s="";for(;t<n;){let i=r[t];if(i===ske){if(r[t+1]===Xpt){s+="\0",t+=2;continue}t+=1;break}s+=i,t+=1}e.push({isNull:!1,payload:s})}return e}var ake=new Set(["transactor","keyNetwork","port","networkName","cache"]);function Qpt(r){let e=cke(r,t=>!ake.has(t));return Object.keys(e).length>0?e:void 0}function emt(r){return cke(r,e=>ake.has(e))}function cke(r,e){let t={};for(let[n,o]of Object.entries(r??{}))e(n)&&(t[n]=o);return t}function lke(r,e){return`tree://default/${r}/${e}`}function th(r,e){return MA([r,e])}function tmt(r){let e=m3(r);if(!(e.length!==2||e.some(t=>t.isNull))&&th(e[0].payload,e[1].payload)===r)return{schemaName:e[0].payload,tableName:e[1].payload}}function q6e(r){return new Map([...r].map(([e,t])=>[e,new Set(t)]))}function LA(r){let e=r;return e&&e.length>=2&&e[1]?e[1]:void 0}function uke(r){var e;return((e=r.vtabArgs)==null?void 0:e[0])||lke(r.schemaName,r.name)}var rmt=class{constructor(r,e){this.openTree=r,this.mergeLatest=e}tree;transactor;pending=new Map;removedIndexes=new Map;committedRecords;async catalogExists(r){return await this.committedTree(r)!==null}hasPending(r){return this.pending.has(r)}async readEntry(r,e){if(this.pending.has(r))return this.pending.get(r);let t=await this.committedTree(e);if(!t)return;let n=await t.find(r);return t.isValid(n)?t.at(n):void 0}write(r,e){this.pending.set(r,e)}excludeIndexAtCommit(r,e){let t=this.removedIndexes.get(r)??new Set;t.add(e.toLowerCase()),this.removedIndexes.set(r,t)}async recordForUri(r,e){let t=new Map(await this.committed(e));for(let[o,s]of this.pending){let i=LA(s);i?t.set(o,i):t.delete(o)}let n;for(let o of t.values())if(uke(o)===r){if(!o.droppedAt)return o;n=n??o}return n}checkpoint(){return{pending:new Map(this.pending),removedIndexes:q6e(this.removedIndexes)}}restore(r){this.pending=new Map(r.pending),this.removedIndexes=q6e(r.removedIndexes)}async commit(){let r=new Map;if(this.pending.size===0)return r;let e=await this.writableTree();await e.update();for(let[t,n]of this.pending){let o=LA(n);if(o&&!o.droppedAt){let s=await e.find(t),i=e.isValid(s)?LA(e.at(s)):void 0,a=i&&!i.droppedAt?i:void 0;r.set(t,[t,this.mergeLatest(o,this.withoutRemovedIndexes(t,a))])}else r.set(t,n)}return await e.stage([...r.entries()]),await e.sync(),r}withoutRemovedIndexes(r,e){let t=this.removedIndexes.get(r);return!e||!t?e:{...e,indexes:e.indexes.filter(n=>!t.has(n.name.toLowerCase()))}}async committedTree(r){if(this.tree===void 0){this.transactor=this.transactor??r;let e=await this.openTree(this.transactor,!1);e&&await e.update(),this.tree=e??null}return this.tree}async writableTree(){let r=await this.committedTree();if(r)return r;let e=await this.openTree(this.transactor,!0);if(!e)throw new Error("Schema catalog tree unavailable: create-on-missing resolved to nothing");return this.tree=e,e}async committed(r){if(!this.committedRecords){let e=new Map,t=await this.committedTree(r);if(t)for await(let n of t.range({isAscending:!0})){if(!t.isValid(n))continue;let o=t.at(n),s=LA(o);o&&s&&e.set(o[0],s)}this.committedRecords=e}return this.committedRecords}};function rh(r){return[...r].sort((e,t)=>e-t).join("_")}function nmt(r){return`_uniq_${r.map(t=>t.toLowerCase()).sort().map(t=>`${t.length}.${t}`).join("_")}`}function Kx(r){return r.predicate===void 0?`cols:${rh(r.columns)}`:`partial:${r.derivedFromIndex??rh(r.columns)}`}function g3(r,e){let t=[...r],n=new Map(r.map((o,s)=>[o.name,s]));for(let o of e){let s=n.get(o.name);s===void 0?t.push(o):o.unique&&!t[s].unique&&(t[s]={...t[s],unique:!0,predicate:t[s].predicate??o.predicate})}return t}function omt(r,e){return r===e?0:r===void 0?-1:e===void 0?1:r<e?-1:1}function LJ(r){return r.map((e,t)=>({item:e,position:t})).sort((e,t)=>omt(e.item.name,t.item.name)||e.position-t.position).map(({item:e})=>e)}function UJ(r){return{...r,indexes:LJ(r.indexes),...r.orphanedIndexes?{orphanedIndexes:LJ(r.orphanedIndexes)}:{},...r.checkConstraints?{checkConstraints:LJ(r.checkConstraints)}:{}}}function dke(r){return new Map(r.map((e,t)=>[e.name.toLowerCase(),t]))}function FJ(r){return`[${r.map(e=>e.name).join(", ")}]`}function fke(r){let e=dke(r.columns),t=[];for(let n of r.indexes)for(let o of n.columns)e.has(o.name.toLowerCase())||t.push({index:n.name,column:o.name});return t}function hke(r){let e=r.columns.length,t=(n,o)=>{if(!Number.isInteger(n)||n<0||n>=e)throw new Error(`Cannot persist table '${r.name}': ${o} position ${n} is out of range for its column list ${FJ(r.columns)}`)};for(let n of r.primaryKeyDefinition)t(n.index,"primary key");for(let n of r.uniqueConstraints??[])for(let o of n.columns)t(o,`unique constraint ${n.name?`'${n.name}' `:""}column`);for(let n of r.foreignKeys??[])for(let o of n.columns)t(o,`foreign key ${n.name?`'${n.name}' `:""}column`);for(let[n,o]of r.generatedColumnDependencies??[]){t(n,"generated column");for(let s of o)t(s,`generated column ${n} dependency`)}for(let n of r.generatedColumnTopoOrder??[])t(n,"generated column order")}function Om(r){if(Array.isArray(r))return r.map(Om);if(r===null||typeof r!="object"||r instanceof Uint8Array)return r;let e={};for(let t of Object.keys(r).sort()){if(t==="loc")continue;let n=r[t];n!==void 0&&(e[t]=Om(n))}return e}function Nx(r){return r&&r.length>0?[...r]:void 0}function Pi(r){return r&&Object.keys(r).length>0?{...r}:void 0}function h3(r){let e=r.indexes.map(t=>({...t,columns:t.columns.map(n=>{let o=r.columns[n.index];if(o===void 0)throw new Error(`Cannot persist table '${r.name}': index '${t.name}' addresses column position ${n.index}, which is out of range for its column list ${FJ(r.columns)}`);let{index:s,...i}=n;return{...i,name:o.name}})}));return{...r,indexes:e}}function Qu(r){let e=fke(r);if(e.length>0){let[o]=e;throw new Error(`Persisted catalog record for table '${r.name}' is unresolvable: index '${o.index}' names column '${o.column}', which is absent from its column list ${FJ(r.columns)}`)}hke(r);let t=dke(r.columns),n=r.indexes.map(o=>({...o,columns:o.columns.map(s=>{let{name:i,...a}=s;return{...a,index:t.get(i.toLowerCase())}})}));return{...r,indexes:n}}function j6e(r,e){let t=e.toLowerCase(),n=r.indexes.find(o=>o.name.toLowerCase()===t);if(n)return UJ({...r,indexes:r.indexes.filter(o=>o!==n),orphanedIndexes:g3([n],r.orphanedIndexes??[])})}function p3(r,e){let t=e?{...r,indexes:g3(r.indexes,e.indexes)}:r,n=g3(r.orphanedIndexes??[],e?.orphanedIndexes??[]);n.length>0&&(t={...t,orphanedIndexes:n}),t=UJ(t);let[o]=fke(t);if(o)throw new Error(`Cannot re-declare table '${t.name}' without column '${o.column}': persisted index '${o.index}' covers it. Drop the index or the table first.`);return hke(t),t}var smt=class{constructor(r){this.getSchemaTree=r}schemaCache=new Map;batch;beginBatch(){if(this.batch)throw new Error("A catalog batch is already open on this SchemaManager");this.batch=new rmt(this.getSchemaTree,p3)}async commitBatch(){let r=this.batch;if(!r)throw new Error("No catalog batch is open on this SchemaManager");this.batch=void 0;let e=await r.commit();for(let[t,n]of e)this.resolveAndCache(n)===void 0&&this.schemaCache.delete(t)}discardBatch(){this.batch=void 0}checkpointBatch(){var r;return(r=this.batch)==null?void 0:r.checkpoint()}restoreBatch(r){if(!this.batch)throw new Error("No catalog batch is open on this SchemaManager");this.batch.restore(r)}async requireSchemaTree(r){let e=await this.getSchemaTree(r,!0);if(!e)throw new Error("Schema catalog tree unavailable: create-on-missing resolved to nothing");return e}async storeSchema(r,e){await this.storeStoredSchema(this.tableSchemaToStored(r),e)}async storeStoredSchema(r,e){if(this.batch)return this.storeInBatch(this.batch,r,e);let t=await this.requireSchemaTree(e),n=th(r.schemaName,r.name);await t.update();let o=await t.find(n),s=t.isValid(o)?this.livePersistedEntry(t.at(o)):void 0,i=p3(h3(r),s),a=Qu(i);return await t.replace([[n,[n,i]]]),this.schemaCache.set(n,a),a}async storeInBatch(r,e,t){let n=th(e.schemaName,e.name),o=this.livePersistedEntry(await r.readEntry(n,t)),s=p3(h3(e),o);return r.write(n,[n,s]),Qu(s)}async readLiveInBatch(r,e,t){let n=this.livePersistedEntry(await r.readEntry(e,t));return n?Qu(n):void 0}mergeWithPersisted(r,e){return Qu(p3(h3(r),h3(e)))}anyPersistedEntry(r){return LA(r)}livePersistedEntry(r){let e=this.anyPersistedEntry(r);return e&&!e.droppedAt?e:void 0}droppedPersistedEntry(r){let e=this.anyPersistedEntry(r);return e&&e.droppedAt?e:void 0}resolveAndCache(r){let e=this.livePersistedEntry(r);if(!e)return;let t=Qu(e);return this.schemaCache.set(r[0],t),t}async getSchema(r,e,t){let n=th(r,e);if(this.batch)return this.readLiveInBatch(this.batch,n,t);let o=this.schemaCache.get(n);return o||await this.readSchemaFromCatalog(n,t)}async getSchemaFresh(r,e,t){let n=th(r,e),o=this.batch?await this.readLiveInBatch(this.batch,n,t):await this.readSchemaFromCatalog(n,t);return o||this.schemaCache.get(n)}async readSchemaFromCatalog(r,e){let t=await this.getSchemaTree(e);if(!t)return;await t.update();let n=await t.find(r);if(t.isValid(n))return this.resolveAndCache(t.at(n))}async deleteSchema(r,e,t){let n=th(r,e);if(this.schemaCache.delete(n),this.batch)return this.deleteInBatch(this.batch,n,t);let o=await this.getSchemaTree(t);if(!o)return;let s;try{await o.update();let i=await o.find(n),a=o.isValid(i)?this.anyPersistedEntry(o.at(i)):void 0;a&&(s={...a,droppedAt:a.droppedAt??new Date().toISOString()})}catch{s=void 0}await o.replace([[n,s?[n,s]:void 0]])}async deleteInBatch(r,e,t){if(!r.hasPending(e)&&!await r.catalogExists(t))return;let n;try{let o=this.anyPersistedEntry(await r.readEntry(e,t));o&&(n={...o,droppedAt:o.droppedAt??new Date().toISOString()})}catch{n=void 0}r.write(e,n?[e,n]:void 0)}async removeIndex(r,e,t,n){let o=th(r,e);if(this.batch)return this.removeIndexInBatch(this.batch,o,t,n);let s=await this.getSchemaTree(n);if(!s)return;await s.update();let i=await s.find(o),a=s.isValid(i)?this.livePersistedEntry(s.at(i)):void 0;if(!a)return;let c=j6e(a,t);if(!c)return Qu(a);await s.replace([[o,[o,c]]]);let l=Qu(c);return this.schemaCache.set(o,l),l}async removeIndexInBatch(r,e,t,n){let o=this.livePersistedEntry(await r.readEntry(e,n));if(!o)return;let s=j6e(o,t);return s?(r.write(e,[e,s]),r.excludeIndexAtCommit(e,t),Qu(s)):Qu(o)}async*catalogEntries(r){let e=await this.getSchemaTree(r);if(e){await e.update();for await(let t of e.range({isAscending:!0})){if(!e.isValid(t))continue;let n=e.at(t);n&&n.length>=1&&(yield n)}}}async listTables(r){let e=[];for await(let t of this.catalogEntries(r)){let n=tmt(t[0]);n&&(this.resolveAndCache(t),e.push(n))}return e}async findRecordForUri(r,e){if(this.batch)return this.batch.recordForUri(r,e);let t;for await(let n of this.catalogEntries(e)){let o=this.anyPersistedEntry(n);if(o&&uke(o)===r){if(!o.droppedAt)return o;t=t??o}}return t}async getDroppedSchemaRecord(r,e,t){let n=th(r,e);if(this.batch)return this.droppedPersistedEntry(await this.batch.readEntry(n,t));let o=await this.getSchemaTree(t);if(!o)return;await o.update();let s=await o.find(n);return o.isValid(s)?this.droppedPersistedEntry(o.at(s)):void 0}clearCache(){this.schemaCache.clear()}storedToTableSchema(r,e,t,n={}){var o,s;let i=r.columns.map(c=>this.storedToColumnSchema(c)),a=r.primaryKeyDefinition.map(c=>({index:c.index,desc:c.desc,collation:c.collation}));return{name:r.name,schemaName:r.schemaName,columns:i,columnIndexMap:eke(i),primaryKeyDefinition:a,primaryKeyDefaultConflict:r.primaryKeyDefaultConflict,synthesizedPrimaryKey:r.synthesizedPrimaryKey,checkConstraints:(r.checkConstraints??[]).map(c=>this.storedToCheckConstraint(c)),foreignKeys:(o=r.foreignKeys)==null?void 0:o.map(c=>this.storedToForeignKey(c)),vtabModule:e,vtabAuxData:t,vtabArgs:{...emt(n),...r.vtabArgs},vtabModuleName:r.vtabModuleName,isView:!1,indexes:r.indexes.length>0?this.storedIndexesToIndexSchemas(r.indexes):void 0,uniqueConstraints:this.storedToUniqueConstraints(r),mutationContext:(s=r.mutationContext)==null?void 0:s.map(c=>this.storedToMutationContextVar(c)),generatedColumnDependencies:r.generatedColumnDependencies?new Map(r.generatedColumnDependencies.map(([c,l])=>[c,[...l]])):void 0,generatedColumnTopoOrder:r.generatedColumnTopoOrder?[...r.generatedColumnTopoOrder]:void 0,tags:Pi(r.tags)}}storedToColumnSchema(r){return{name:r.name,logicalType:r.declaredType!==void 0?Npt(r.declaredType):$6e(r.affinity),declaredType:r.declaredType,notNull:r.notNull,primaryKey:r.primaryKey,pkOrder:r.pkOrder,defaultValue:r.defaultValue??null,collation:r.collation,collationExplicit:r.collationExplicit,generated:r.generated,generatedExpr:r.generatedExpr,generatedStored:r.generatedStored,pkDirection:r.pkDirection,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}storedToCheckConstraint(r){return{name:r.name,expr:r.expr,operations:r.operations,deferrable:r.deferrable,initiallyDeferred:r.initiallyDeferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}storedToForeignKey(r){return{name:r.name,columns:[...r.columns],referencedTable:r.referencedTable,referencedSchema:r.referencedSchema,referencedColumnNames:r.referencedColumnNames?[...r.referencedColumnNames]:void 0,onDelete:r.onDelete,onUpdate:r.onUpdate,deferred:r.deferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}storedToMutationContextVar(r){return{name:r.name,logicalType:$6e(r.type),notNull:r.notNull}}storedIndexesToIndexSchemas(r){return r.map(e=>({name:e.name,columns:e.columns.map(t=>({index:t.index,desc:t.desc,collation:t.collation})),unique:e.unique?!0:void 0,predicate:e.predicate,tags:Pi(e.tags)}))}storedToUniqueConstraints(r){let e=(r.uniqueConstraints??[]).map(n=>({name:n.name,columns:[...n.columns],defaultConflict:n.defaultConflict,predicate:n.predicate,tags:Pi(n.tags)})),t=new Set(e.map(Kx));for(let n of r.indexes){if(!n.unique)continue;let o={name:n.name,columns:n.columns.map(i=>i.index),predicate:n.predicate,derivedFromIndex:n.name},s=Kx(o);t.has(s)||(t.add(s),e.push(o))}return e.length>0?e:void 0}tableSchemaToStored(r){var e,t;let n=(r.uniqueConstraints??[]).filter(s=>s.derivedFromIndex===void 0).map(s=>({name:s.name,columns:[...s.columns],defaultConflict:s.defaultConflict,predicate:s.predicate?Om(s.predicate):void 0,tags:Pi(s.tags)})),o=r.generatedColumnDependencies?[...r.generatedColumnDependencies.entries()].sort(([s],[i])=>s-i).map(([s,i])=>[s,[...i]]):void 0;return UJ({name:r.name,schemaName:r.schemaName,columns:r.columns.map(s=>this.columnSchemaToStored(s)),primaryKeyDefinition:r.primaryKeyDefinition.map(s=>({index:s.index,desc:s.desc,collation:s.collation})),primaryKeyDefaultConflict:r.primaryKeyDefaultConflict,indexes:(r.indexes||[]).map(s=>this.indexSchemaToStored(s)),vtabModuleName:r.vtabModuleName,vtabArgs:Qpt(r.vtabArgs),uniqueConstraints:Nx(n),checkConstraints:Nx(r.checkConstraints.map(s=>this.checkConstraintToStored(s))),foreignKeys:Nx((e=r.foreignKeys)==null?void 0:e.map(s=>this.foreignKeyToStored(s))),mutationContext:Nx((t=r.mutationContext)==null?void 0:t.map(s=>({name:s.name,type:s.logicalType.name,notNull:s.notNull}))),tags:Pi(r.tags),synthesizedPrimaryKey:r.synthesizedPrimaryKey,generatedColumnDependencies:Nx(o),generatedColumnTopoOrder:Nx(r.generatedColumnTopoOrder)})}columnSchemaToStored(r){return{name:r.name,affinity:r.logicalType.name,declaredType:r.declaredType,notNull:r.notNull,primaryKey:r.primaryKey,pkOrder:r.pkOrder,defaultValue:r.defaultValue?Om(r.defaultValue):void 0,collation:r.collation,collationExplicit:r.collationExplicit?!0:void 0,generated:r.generated,generatedExpr:r.generatedExpr?Om(r.generatedExpr):void 0,generatedStored:r.generatedStored,pkDirection:r.pkDirection,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}withCheckConstraint(r,e){var t;let n=(t=e.name)==null?void 0:t.toLowerCase(),o=(r.checkConstraints??[]).filter(s=>{var i;return n===void 0||((i=s.name)==null?void 0:i.toLowerCase())!==n});return{...r,checkConstraints:[...o,this.checkConstraintToStored(e)]}}checkConstraintToStored(r){return{name:r.name,expr:Om(r.expr),operations:r.operations,deferrable:r.deferrable,initiallyDeferred:r.initiallyDeferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}foreignKeyToStored(r){return{name:r.name,columns:[...r.columns],referencedTable:r.referencedTable,referencedSchema:r.referencedSchema,referencedColumnNames:r.referencedColumnNames?[...r.referencedColumnNames]:void 0,onDelete:r.onDelete,onUpdate:r.onUpdate,deferred:r.deferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}indexSchemaToStored(r){return{name:r.name,columns:r.columns.map(e=>({index:e.index,desc:e.desc,collation:e.collation})),unique:r.unique?!0:void 0,predicate:r.predicate?Om(r.predicate):void 0,tags:Pi(r.tags)}}},imt=class{constructor(r,e="json"){this.schema=r,this.encoding=e}encodeRow(r){let e={};for(let t=0;t<this.schema.columns.length;t++){let n=this.schema.columns[t];if(!n)continue;let o=r[t];e[n.name]=this.normalizeValue(o??null)}if(this.encoding==="msgpack")throw new Error("msgpack encoding not yet implemented");return JSON.stringify(e)}decodeRow(r){let e;if(this.encoding==="msgpack")throw new Error("msgpack decoding not yet implemented");e=JSON.parse(r);let t=[];for(let n=0;n<this.schema.columns.length;n++){let o=this.schema.columns[n];o&&(t[n]=this.denormalizeValue(e[o.name],o))}return t}asPrimaryKeyTuple(r){if(r.length!==this.schema.primaryKeyDefinition.length)throw new Error(`Primary key requires ${this.schema.primaryKeyDefinition.length} values, got ${r.length}`);return r}extractPrimaryKey(r){if(r.length!==this.schema.columns.length)throw new Error(`extractPrimaryKey requires a full row of ${this.schema.columns.length} columns, got ${r.length} \u2014 did you pass a compact key tuple (one cell per primary-key column) instead? Use createPrimaryKey for that.`);let e=this.schema.primaryKeyDefinition.map(t=>this.serializeKeyPart(r[t.index]??null));return MA(e)}createPrimaryKey(r){if(r.length!==this.schema.primaryKeyDefinition.length)throw new Error(`Primary key requires ${this.schema.primaryKeyDefinition.length} values, got ${r.length}`);return MA(r.map(e=>this.serializeKeyPart(e??null)))}decodePrimaryKey(r){let e=m3(r);return this.schema.primaryKeyDefinition.map((t,n)=>{var o;return this.keyElementToValue(e[n],(o=this.schema.columns[t.index])==null?void 0:o.affinity)})}getPrimaryKeyIndices(){return this.schema.primaryKeyDefinition.map(r=>r.index)}getColumnCount(){return this.schema.columns.length}getColumnName(r){var e;return((e=this.schema.columns[r])==null?void 0:e.name)||""}getColumnIndex(r){return this.schema.columns.findIndex(e=>e.name.toLowerCase()===r.toLowerCase())}serializeKeyPart(r){return r==null?null:typeof r=="string"?r:typeof r=="number"||typeof r=="bigint"?r.toString():typeof r=="boolean"?r?"1":"0":r instanceof Uint8Array?RA(r,"base64"):String(r)}normalizeValue(r){return typeof r=="bigint"?r>=Number.MIN_SAFE_INTEGER&&r<=Number.MAX_SAFE_INTEGER?Number(r):{$bigint:r.toString()}:r instanceof Uint8Array&&this.encoding==="json"?RA(r,"base64"):r}denormalizeValue(r,e){return r==null?null:typeof r=="object"&&r!==null&&"$bigint"in r?BigInt(r.$bigint):e.affinity==="BLOB"&&typeof r=="string"?_J(r,"base64"):r}isColumnInPrimaryKey(r){return this.schema.primaryKeyDefinition.some(e=>e.index===r)}getSchema(){return this.schema}createPrimaryKeyComparator(){let r=this.schema.primaryKeyDefinition;if(r.length===0)return()=>0;let e=r.map(o=>_pt(o.collation||"BINARY")??Ppt),t=r.map(o=>o.desc||!1),n=r.map(o=>{var s;return(s=this.schema.columns[o.index])==null?void 0:s.affinity});return(o,s)=>{let i=this.decodeKeyForCompare(o),a=this.decodeKeyForCompare(s);for(let c=0;c<r.length;c++){let l=this.keyElementToValue(i[c],n[c]),u=this.keyElementToValue(a[c],n[c]),d=this.compareValues(l,u,e[c]);if(d!==0){let h=t[c]?-1:1;return d*h}}return 0}}decodeKeyForCompare(r){let e=r[0];return e==="\0"||e===""?m3(r):[{isNull:!1,payload:r}]}keyElementToValue(r,e){return!r||r.isNull?null:this.deserializeKeyPart(r.payload,e)}deserializeKeyPart(r,e){let t=(e||"").toUpperCase();if(t==="INTEGER"||t==="REAL"||t==="NUMERIC"){let n=Number(r);return!isNaN(n)&&r.trim()!==""?n:r}return t==="BLOB"?_J(r,"base64"):r}compareValues(r,e,t){return r===null&&e===null?0:r===null?-1:e===null?1:typeof r=="string"&&typeof e=="string"?t(r,e):typeof r=="number"&&typeof e=="number"?r<e?-1:r>e?1:0:Rpt(r,e)}};function amt(r){return r==null?null:typeof r=="string"?r:typeof r=="bigint"?Number(r).toExponential(15):typeof r=="number"?r.toExponential(15):r instanceof Uint8Array?btoa(String.fromCharCode(...r)):String(r)}function y3(r){return MA(r.map(e=>amt(e??null)))}function ed(r,e){return r+e}function pke(r,e,t){let[n,o]=e;return n===ed(t(r),o)}function mke(r,e){return r.columns.some(t=>e[t.index]===null||e[t.index]===void 0)}function gke(r){return new rl({key:r,inclusive:!0},{key:r+ike,inclusive:!1},!0)}function cmt(r){return{kind:"absentRange",range:gke(r)}}var lmt=class{constructor(r,e){this.schema=r,this.indexTreeFactory=e}indexTrees=new Map;uniqueEnforcementIndexes=[];async initialize(r){for(let e of this.schema.indexes){let t=await this.indexTreeFactory(e.name,r);this.indexTrees.set(e.name,t)}}getDeclaredIndexes(){return[...this.schema.indexes]}async setUniqueEnforcementIndexes(r,e){this.uniqueEnforcementIndexes=r;for(let t of r)if(!this.indexTrees.has(t.name)){let n=await this.indexTreeFactory(t.name,e);this.indexTrees.set(t.name,n)}}getAllMaintainedIndexes(){return[...this.schema.indexes,...this.uniqueEnforcementIndexes]}getIndexTree(r){return this.indexTrees.get(r)}getIndexTrees(){return[...this.indexTrees.values()]}registerIndexTree(r,e){this.indexTrees.set(r,e)}unregisterIndex(r){let e=r.toLowerCase(),t=this.schema.indexes.find(o=>o.name.toLowerCase()===e);if(!t)return;this.schema={...this.schema,indexes:this.schema.indexes.filter(o=>o!==t)};let n=this.indexTrees.get(t.name);return this.indexTrees.delete(t.name),n}setSchema(r){this.schema=r}createIndexKey(r,e){return y3(r.columns.map(t=>e[t.index]??null))}asIndexColumnTuple(r,e){if(e.length===0||e.length>r.columns.length)throw new Error(`Index '${r.name}' key tuple requires 1 to ${r.columns.length} values (a leading prefix is allowed), got ${e.length}`);return e}createIndexKeyFromTuple(r){return y3(r)}async insertIndexEntries(r,e,t,n){for(let o of this.getAllMaintainedIndexes()){let s=this.createIndexKey(o,r),i=this.indexTrees.get(o.name);if(!i)throw new Error(`Index tree not found: ${o.name}`);let a=ed(s,e);await i.stage([[a,[a,e],this.guardFor(o,s,n)]])}}guardFor(r,e,t){return t?.has(r.name)?cmt(e):void 0}async deleteIndexEntries(r,e,t){for(let n of this.getAllMaintainedIndexes()){let o=this.createIndexKey(n,r),s=this.indexTrees.get(n.name);if(!s)throw new Error(`Index tree not found: ${n.name}`);let i=ed(o,e);await s.stage([[i,void 0]])}}async updateIndexEntries(r,e,t,n,o,s){for(let i of this.getAllMaintainedIndexes()){let a=this.createIndexKey(i,r),c=this.createIndexKey(i,e),l=this.indexTrees.get(i.name);if(!l)throw new Error(`Index tree not found: ${i.name}`);let u=ed(a,t),d=ed(c,n);u!==d&&await l.stage([[u,void 0],[d,[d,n],this.guardFor(i,c,s)]])}}async*findByIndex(r,e){let t=this.indexTrees.get(r);if(!t)throw new Error(`Index tree not found: ${r}`);await t.update(),yield*this.findByIndexIn(t,e)}async*findByIndexIn(r,e){for await(let t of this.findEntriesIn(r,e))yield t[1]}async*findEntriesIn(r,e){for await(let t of r.range(gke(e))){if(!r.isValid(t))continue;let n=r.at(t);n!=null&&(yield n)}}async*allEntriesIn(r){for await(let e of r.range(new rl(void 0,void 0,!0))){if(!r.isValid(e))continue;let t=r.at(e);t!=null&&(yield t)}}async*scanIndexRange(r,e,t,n=!0){let o=this.indexTrees.get(r);if(!o)throw new Error(`Index tree not found: ${r}`);await o.update();let s=e!==void 0?{key:e,inclusive:!0}:void 0,i=t!==void 0?{key:t+ike,inclusive:!1}:void 0,a=new rl(s,i,n);for await(let c of o.range(a)){if(!o.isValid(c))continue;let l=o.at(c);l!=null&&(yield l[1])}}getIndexSchema(r){return this.schema.indexes.find(e=>e.name===r)}};function umt(r){let{index:e,kind:t,rows:n}=r,o=e.columns.length,s=new Map,i=new Set;for(let[u,d]of n){let h=ed(r.indexKeyOf(d),u);s.set(h,{primaryKey:u,row:d}),dmt(e,t,d)&&i.add(h)}let a=new Set,c=[];for(let[u,d]of r.entries){a.add(u);let h=fmt(u,d,o,r.indexKeyOf,n);h&&c.push(h)}let l=[];for(let[u,{primaryKey:d,row:h}]of s)a.has(u)||i.has(u)||l.push({expectedTreeKey:u,primaryKey:d,row:h,...yke(u,o)});return{table:r.table,index:e.name,kind:t,rowCount:n.size,entryCount:r.entries.length,missing:l,orphaned:c}}function dmt(r,e,t){return e==="unique-enforcement"&&mke(r,t)}function fmt(r,e,t,n,o){let s=o.get(e);if(s!==void 0&&pke(s,[r,e],n))return;let i=yke(r,t),a={treeKey:r,primaryKey:e,...i};return r!==ed(MA(i.indexPayloads),e)?{...a,reason:"malformed"}:s===void 0?{...a,reason:"no-row"}:{...a,reason:"stale-value",currentRow:s}}function yke(r,e){let t=m3(r).map(n=>n.isNull?null:n.payload);return{indexPayloads:t.slice(0,e),primaryKeyPayloads:t.slice(e)}}var Ca=b3("module"),G6e=new Set;function Ux(r,e){let t=`${r}: ${e instanceof Error?e.message:String(e)}`;return new Error(t,{cause:e})}var hmt=/[^A-Za-z0-9._-]/g,pmt=r=>r.replace(hmt,e=>{let t=e.charCodeAt(0);return t<=255?`%${t.toString(16).toUpperCase().padStart(2,"0")}`:`%u${t.toString(16).toUpperCase().padStart(4,"0")}`});async function*MJ(r,e){for await(let t of r.ascending(await r.first())){if(!r.isValid(t))continue;let n=r.at(t);if(!n||n.length<2)continue;let o=e.decodeRow(n[1]);yield{row:o,primaryKey:e.extractPrimaryKey(o)}}}async function W6e(r,e,t){let n=await r.find(t);if(!r.isValid(n))return;let o=r.at(n);if(!(!o||o.length<2))return e.decodeRow(o[1])}function Fx(r){return{kind:"unchanged",expected:r}}function OJ(r,e,t){return`Table '${r}' does not maintain index '${e}': ${t}, so reading through it would silently return incomplete results. Re-declare the index on this connection (CREATE INDEX) to re-attach it \u2014 DROP INDEX it first if this connection still lists it.`}function mmt(r,e,t){let n=r.columnIndexMap.get(e.toLowerCase()),o=r.columns.map((s,i)=>i===n?{...s,name:t}:s);return{...r,columns:Object.freeze(o),columnIndexMap:eke(o)}}function Y6e(r,e){let t=r.transactor||e.default_transactor||"network",n=r.keyNetwork||e.default_key_network||"libp2p",o=typeof r.port=="number"?r.port:typeof e.default_port=="number"?e.default_port:0,s=r.networkName||e.default_network_name||"optimystic",i=typeof e.rawStorageFactory=="function"?e.rawStorageFactory:void 0;return{transactor:t,keyNetwork:n,libp2pOptions:{port:o,networkName:s,bootstrapNodes:[]},rawStorageFactory:i}}function gmt(r,e){return X6e(r)===X6e(e)}function X6e(r){return JSON.stringify(r,(e,t)=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let n={};for(let o of Object.keys(t).sort())n[o]=t[o];return n}return t})}function Z6e(r){return`(${r.map(t=>t==null?"null":typeof t=="string"?JSON.stringify(t):t instanceof Uint8Array?`<blob ${t.length} bytes>`:String(t)).join(", ")})`}function ymt(r){return`(${r.map(e=>e.name).join(", ")})`}function J6e(r){return`(${r.primaryKeyDefinition.map(t=>{var n;let o=((n=r.columns[t.index])==null?void 0:n.name)??`#${t.index}`;return t.desc?`${o} desc`:o}).join(", ")})`}var bmt=class extends Q6e{collection;isInitialized=!1;initializationPromise;isProvisionallyInitialized=!1;provisionalInitPromise;declaredColumns;txnBridge;collectionFactory;options;schemaManager;rowCodec;indexManager;uniqueEnforcementIndexes=[];populatedUniqueTrees=new Set;connection;changeUnsubscribe;changeSubscribed=!1;tableSchema;constructor(r,e,t,n,o,s,i,a,c){super(r,e,t,n),this.tableSchema=o,this.declaredColumns=o.columns.length>0,this.options=s,this.collectionFactory=i,this.txnBridge=a,this.schemaManager=c,this.wantStatements=!0}async initialize(){if(this.isInitialized)return;if(this.initializationPromise)return this.initializationPromise;let r=(async()=>{if(this.provisionalInitPromise)try{await this.provisionalInitPromise}catch{}await this.doInitialize(!1)})().finally(()=>{this.initializationPromise===r&&(this.initializationPromise=void 0)});return this.initializationPromise=r,r}async initializeForCommittedRead(){if(this.isInitialized)return;if(this.initializationPromise)return this.initializationPromise;if(this.provisionalInitPromise)return this.provisionalInitPromise;if(!this.txnBridge.isTransactionActive())return this.initialize();if(this.isProvisionallyInitialized)return;let r=this.doInitialize(!0).finally(()=>{this.provisionalInitPromise=void 0});return this.provisionalInitPromise=r,r}async doInitialize(r){try{this.setErrorMessage(void 0);let e=r?null:this.txnBridge.getCurrentTransaction(),t=await this.collectionFactory.createOrGetCollection(this.options,e||void 0),n=await this.schemaManager.getSchema(this.schemaName,this.tableName,e?.transactor),o;if(this.declaredColumns){let c=this.schemaManager.tableSchemaToStored(this.tableSchema),l=n?this.schemaManager.mergeWithPersisted(c,n):c;if(!n){let u=await this.guardStorageAdoption(c,t,e?.transactor);u&&(l={...l,orphanedIndexes:u})}n&&gmt(l,n)?o=n:r?o=l:(!n&&c.indexes.length===0&&Ca("doInitialize(%s): persisting local DDL schema with no persisted catalog entry visible; if an entry exists but was unreadable, the write-time index union preserves its indexes",this.tableName),o=await this.schemaManager.storeStoredSchema(l,e?.transactor))}else if(n)this.tableSchema.columns=n.columns.map((c,l)=>({...this.schemaManager.storedToColumnSchema(c),affinity:c.affinity,index:l})),this.tableSchema.columnIndexMap=new Map(n.columns.map((c,l)=>[c.name.toLowerCase(),l])),this.tableSchema.primaryKeyDefinition=n.primaryKeyDefinition.map(c=>({index:c.index,desc:c.desc,collation:c.collation})),this.tableSchema.primaryKeyDefaultConflict=n.primaryKeyDefaultConflict,o=n;else throw new Error("Cannot create table without column definitions");this.attachPersistedUniqueConstraints(o);let s=new imt(o,this.options.encoding),i=new lmt(o,(c,l)=>this.openIndexTree(c,l));await i.initialize(e?.transactor);let a=this.buildUniqueEnforcementIndexes(o);if(await i.setUniqueEnforcementIndexes(a,e?.transactor),this.collection=t,this.rowCodec=s,this.indexManager=i,this.uniqueEnforcementIndexes=a,r){this.isProvisionallyInitialized=!0;return}this.registerCollections(),this.isProvisionallyInitialized=!1,this.isInitialized=!0,await this.ensureChangeSubscription()}catch(e){let t=Ux("Failed to initialize Optimystic table",e);throw this.setErrorMessage(t.message),t}}async guardStorageAdoption(r,e,t){let n=await this.schemaManager.getDroppedSchemaRecord(this.schemaName,this.tableName,t)??await this.schemaManager.findRecordForUri(this.options.collectionUri,t);if(!n)return;let o=g3(n.indexes,n.orphanedIndexes??[]),s=o.length>0?o:void 0;if(await this.hasNoRowsToBackfill(e))return s;let i=n.droppedAt?"a dropped table":`live table '${n.name}'`,a=new Map(n.columns.map(h=>[h.name.toLowerCase(),h])),c=r.columns.filter(h=>!a.has(h.name.toLowerCase()));if(c.length>0){let h=c.length===1?"column":"columns",p=c.map(f=>`'${f.name}'`).join(", ");throw new Error(`Cannot create table '${r.name}' over '${this.options.collectionUri}': that collection still holds rows from ${i} declared as ${ymt(n.columns)}, and this declaration adds ${h} ${p}, which those rows cannot supply. Use a different collection URI, or re-declare the columns the stored rows were written under.`)}let l=r.columns.filter(h=>{let p=a.get(h.name.toLowerCase());return p!==void 0&&p.affinity!==h.affinity});if(l.length>0){let h=l.length===1?"column":"columns",p=l.map(f=>{let g=a.get(f.name.toLowerCase());return`'${f.name}' as ${f.affinity} where the stored rows were written as ${g.affinity}`}).join(", ");throw new Error(`Cannot create table '${r.name}' over '${this.options.collectionUri}': that collection still holds rows from ${i}, and this declaration re-types ${h} ${p} \u2014 stored values are untagged, so they would be decoded as something other than what was written. Use a different collection URI, or re-declare the column types the stored rows were written under.`)}let u=J6e(r),d=J6e(n);if(u.toLowerCase()!==d.toLowerCase())throw new Error(`Cannot create table '${r.name}' over '${this.options.collectionUri}': that collection still holds rows from ${i} keyed on ${d}, and this declaration keys on ${u} \u2014 rows written under the old key can never be reached through the new one. Use a different collection URI, or re-declare the primary key the stored rows were written under.`);return s}async ensureChangeSubscription(){if(!this.changeSubscribed&&this.options.collectionUri!=="tree://optimystic/schema"){this.changeSubscribed=!0;try{let r=this.collectionFactory.getCollectionId(this.options);this.changeUnsubscribe=await this.collectionFactory.subscribeToCollectionChanges(this.options,r,e=>this.handleCollectionChange(e))}catch(r){this.changeSubscribed=!1,Ca(`WARN: failed to subscribe '${this.tableName}' to collection changes: ${r instanceof Error?r.message:String(r)}`)}}}handleCollectionChange(r){try{let e=this.db.notifyExternalChange(this.tableName,this.schemaName);e&&typeof e.catch=="function"&&e.catch(t=>{Ca(`WARN: notifyExternalChange failed for '${this.tableName}': ${t instanceof Error?t.message:String(t)}`)})}catch(e){Ca(`WARN: notifyExternalChange threw for '${this.tableName}': ${e instanceof Error?e.message:String(e)}`)}}teardownChangeSubscription(){if(this.changeUnsubscribe){try{this.changeUnsubscribe()}catch(r){Ca(`WARN: error tearing down change subscription for '${this.tableName}': ${r instanceof Error?r.message:String(r)}`)}this.changeUnsubscribe=void 0}this.changeSubscribed=!1}async disconnect(){}async ensureConnectionRegistered(){if(!this.connection){let r=this.db,e=r.getConnectionsForTable(this.tableName);e.length>0&&e[0]instanceof RJ?this.connection=e[0]:(this.connection=new RJ(this.tableName,this.txnBridge,this.options),await r.registerConnection(this.connection))}return this.connection}createConnection(){return new RJ(this.tableName,this.txnBridge,this.options)}getConnection(){return this.connection}async*query(r){yield*this.runQuery(r,!1)}async*queryCommitted(r){yield*this.runQuery(r,!0)}async*runQuery(r,e){if(e){let t=this.txnBridge.getDegradedReason();if(t!==void 0)throw new Aa(`Committed read refused: storage is in a partially-committed state and no coherent committed snapshot exists until the next successful commit or rollback. ${t}`,Ia.ERROR);await this.initializeForCommittedRead()}else await this.ensureConnectionRegistered(),this.isInitialized||await this.initialize();if(!this.collection||!this.rowCodec||!this.indexManager)throw new Error("Table not initialized");try{let t=this.parsePlanType(r.idxStr),n=this.parseIndexName(r.idxStr),o=n!=null&&n!=="_primary_",s;if(o&&r.args.length>0)s=n;else if(r.idxNum>=10&&!(t===2&&r.args.length>0)&&t!==3){if(!r.idxStr||typeof r.idxStr!="string")throw new Error("Index name not provided for index scan");s=r.idxStr}let i=this.collection,a=s!==void 0?this.resolveIndexTarget(s):void 0,c,l;if(e?(c=this.committedTreeView(i),l=a!==void 0?{...a,read:this.committedTreeView(a.tree)}:void 0):(await i.update(),c=i,a!==void 0&&(await a.tree.update(),l={...a,read:a.tree})),l!==void 0){let u=Ca.enabled?{matched:0,rejected:0}:void 0;try{yield*this.executeIndexScan(c,l,r.args,u)}finally{u!==void 0&&this.logIndexSeek(l,i,e,u)}}else t===2&&r.args.length>0?yield*this.executePointLookup(c,r.args):t===3?yield*this.executeRangeQuery(c,r):r.idxNum===1?yield*this.executePointLookup(c,r.args):r.idxNum===2?yield*this.executeRangeQuery(c,r):yield*this.executeTableScan(c)}catch(t){let n=Ux("Query failed",t);throw this.setErrorMessage(n.message),n}}resolveIndexTarget(r){if(!this.indexManager)throw new Error("Table not initialized");let e=this.indexManager.getIndexSchema(r);if(!e)throw new Aa(OJ(this.tableName,r,"it has no descriptor in this table instance's maintained index set, so writes skip it"),Ia.ERROR);let t=this.indexManager.getIndexTree(r);if(!t)throw new Aa(OJ(this.tableName,r,"its tree is not open on this table instance, so writes have nowhere to stage into"),Ia.ERROR);return{schema:e,tree:t}}logIndexSeek(r,e,t,n){let o=s=>tke(s.committedRevision()??"none",s.committedActionId()??"none");Ca("index:seek table=%s index=%s collection=%s main=%s arm=%s rev=%s main_rev=%s seek=%s matched=%d rejected=%d node=%s",this.tableName,r.schema.name,String(r.tree.getCollection().id),String(e.getCollection().id),t?"committed":"live",o(r.tree),o(e),n.key===void 0?"unset":pmt(n.key),n.matched,n.rejected,this.collectionFactory.nodeTag())}committedTreeView(r){let t=this.txnBridge.getDirtySnapshot(r)??r.snapshot();return r.readView(t)}parsePlanType(r){if(!r)return;let e=r.match(/plan=(\d+)/);return e?.[1]?parseInt(e[1],10):void 0}parseIndexName(r){if(!r)return;let e=r.match(/idx=([^(;]+)/);return e?.[1]||void 0}async*executePointLookup(r,e){if(!this.rowCodec||e.some(o=>o==null))return;let t=this.rowCodec.createPrimaryKey(this.rowCodec.asPrimaryKeyTuple(e)),n=await W6e(r,this.rowCodec,t);n!==void 0&&(yield n)}async*executeRangeQuery(r,e){yield*this.executeTableScan(r)}async*executeIndexScan(r,e,t,n){let o=this.rowCodec,s=this.indexManager;if(!o||!s||t.some(l=>l==null))return;let i=Math.min(t.length,e.schema.columns.length),a=i===0?y3([]):s.createIndexKeyFromTuple(s.asIndexColumnTuple(e.schema,t.slice(0,i)));n!==void 0&&(n.key=String(a));let c=l=>s.createIndexKey(e.schema,l);for await(let l of s.findEntriesIn(e.read,a)){n!==void 0&&n.matched++;let u=await W6e(r,o,l[1]);if(u===void 0||!pke(u,l,c)){n!==void 0&&n.rejected++;continue}yield u}}async*executeTableScan(r){if(!this.rowCodec)return;let e=5,t=0,n,o=new Set;for(;t<e;)try{let s=n?new rl({key:n,inclusive:!1},void 0,!0):new rl(void 0,void 0,!0),i=r.range(s);for await(let a of i){if(!r.isValid(a))continue;let c=r.at(a);if(c&&Array.isArray(c)&&c.length>=2){let l=c[0];if(o.has(l)){n=l;continue}let u=c[1],d=this.rowCodec.decodeRow(u);o.add(l),n=l,yield d}}return}catch(s){if((s instanceof Error?s.message:String(s)).includes("Path is invalid due to mutation")){if(t++,t>=e)throw new Error(`Table scan failed after ${e} retries due to concurrent mutations`);await new Promise(a=>setTimeout(a,50));continue}throw s}}markDirtyTrees(){if(this.collection&&this.txnBridge.markDirty(this.collection),this.indexManager)for(let r of this.indexManager.getIndexTrees())this.txnBridge.markDirty(r)}registerCollections(){if(this.collection&&(this.txnBridge.registerCollection(this.collection.getCollection()),this.txnBridge.registerKeyTakenMessage(this.collection.getCollection().id,this.uniqueConstraintMessage()),this.txnBridge.registerEntryChangedRenderer(this.collection.getCollection().id,r=>this.concurrentModificationMessage(r))),this.indexManager)for(let r of this.indexManager.getIndexTrees())this.txnBridge.registerCollection(r.getCollection());this.registerUniqueKeyTakenMessages()}registerUniqueKeyTakenMessages(){let r=this.tableSchema.uniqueConstraints;if(!(!r||r.length===0))for(let e of r){if(e.predicate!==void 0||e.columns.length===0)continue;let t=this.resolveEnforcingIndex(e);t&&this.txnBridge.registerKeyTakenMessage(t.tree.getCollection().id,this.uniqueConstraintMessage(e.columns))}}guardedUniqueIndexes(r){let e=this.tableSchema.uniqueConstraints;if(!e||e.length===0)return G6e;let t=new Set;for(let n of e){if(n.predicate!==void 0||n.columns.length===0||!n.columns.every(s=>r[s]!==null&&r[s]!==void 0))continue;let o=this.resolveEnforcingIndex(n);o&&t.add(o.descriptor.name)}return t.size===0?G6e:t}uniqueConstraintMessage(r){return`UNIQUE constraint failed: ${(r??this.tableSchema.primaryKeyDefinition.map(n=>n.index)).map(n=>{var o;return`${this.tableName}.${((o=this.tableSchema.columns[n])==null?void 0:o.name)??`col${n}`}`}).join(", ")}`}concurrentModificationMessage(r){var e;let t=((e=this.rowCodec)==null?void 0:e.decodePrimaryKey(r))??[];return`concurrent modification: another writer changed or removed the row in ${this.tableName} at primary key ${Z6e(t)}`}uniqueKeyFor(r,e){return y3(r.map(t=>e[t]??null))}attachPersistedUniqueConstraints(r){let e=this.schemaManager.storedToUniqueConstraints(r);if(!e)return;let t=this.tableSchema.uniqueConstraints??[],n=new Set(t.map(Kx)),o=e.filter(s=>!n.has(Kx(s)));o.length!==0&&(this.tableSchema={...this.tableSchema,uniqueConstraints:[...t,...o]})}buildUniqueEnforcementIndexes(r){let e=this.tableSchema.uniqueConstraints;if(!e||e.length===0)return[];let t=rh(r.primaryKeyDefinition.map(i=>i.index)),n=new Set(r.indexes.map(i=>rh(i.columns.map(a=>a.index)))),o=[],s=new Set;for(let i of e){if(i.predicate!==void 0||i.columns.length===0)continue;let a=rh(i.columns);a!==t&&(n.has(a)||s.has(a)||(s.add(a),o.push({name:nmt(i.columns.map(c=>this.columnNameAt(r,c))),columns:i.columns.map(c=>({index:c}))})))}return o}columnNameAt(r,e){let t=r.columns[e];if(t===void 0)throw new Error(`Table '${this.tableName}': unique constraint addresses column position ${e}, which is out of range for its ${r.columns.length} columns`);return t.name}resolveEnforcingIndex(r){if(!this.indexManager)return;let e=rh(r.columns);for(let t of this.indexManager.getDeclaredIndexes())if(rh(t.columns.map(n=>n.index))===e){let n=this.indexManager.getIndexTree(t.name);if(n)return{descriptor:t,tree:n,synthesized:!1}}for(let t of this.uniqueEnforcementIndexes)if(rh(t.columns.map(n=>n.index))===e){let n=this.indexManager.getIndexTree(t.name);if(n)return{descriptor:t,tree:n,synthesized:!0}}}async ensureUniquePopulated(r,e){if(this.populatedUniqueTrees.has(r.name)||!this.collection||!this.rowCodec||!this.indexManager||await this.hasNoRowsToBackfill())return;await e.update(),e.at(await e.first())===void 0&&await this.populateUniqueTree(r,e),this.populatedUniqueTrees.add(r.name)}async populateUniqueTree(r,e){if(!(!this.collection||!this.rowCodec||!this.indexManager)){await this.collection.update();for await(let{row:t,primaryKey:n}of MJ(this.collection,this.rowCodec)){if(mke(r,t))continue;let o=ed(this.indexManager.createIndexKey(r,t),n);await e.stage([[o,[o,n]]])}await e.sync()}}async scanUniqueConstraint(r,e,t){if(!this.collection||!this.rowCodec)return[];let n=this.uniqueKeyFor(r.columns,e),o=[];for await(let s of this.collection.range(new rl(void 0,void 0,!0))){if(!this.collection.isValid(s))continue;let i=this.collection.at(s);if(!i||i.length<2||t?.has(i[0]))continue;let a=this.rowCodec.decodeRow(i[1]);this.uniqueKeyFor(r.columns,a)===n&&o.push({pk:i[0],row:a,entry:i})}return o}async probeUniqueConstraint(r,e,t){if(!this.collection||!this.rowCodec||!this.indexManager)return[];let n=this.resolveEnforcingIndex(r);if(!n)return Ca(`WARN: no enforcing index for UNIQUE(${r.columns.join(",")}) on '${this.tableName}'; falling back to full scan`),this.scanUniqueConstraint(r,e,t);let{descriptor:o,tree:s,synthesized:i}=n;i&&await this.ensureUniquePopulated(o,s),await s.update();let a=this.indexManager.createIndexKey(o,e),c=[];for await(let l of this.indexManager.findByIndexIn(s,a)){if(t?.has(l))continue;let u=await this.collection.get(l);!u||u.length<2||c.push({pk:l,row:this.rowCodec.decodeRow(u[1]),entry:u})}return c}resolveConflictAction(r,e){return r??e??Bm.ABORT}pkDeclaredConflict(){if(this.tableSchema.primaryKeyDefaultConflict!==void 0)return this.tableSchema.primaryKeyDefaultConflict;for(let r of this.tableSchema.primaryKeyDefinition){let e=this.tableSchema.columns[r.index];if(e?.defaultConflict!==void 0)return e.defaultConflict}}async resolvePkMoveDecision(r,e){if(!this.collection||!this.rowCodec)throw new Error("Table not initialized");let t=await this.collection.get(r);if(t===void 0)return{kind:"clear"};let n=this.rowCodec.decodeRow(t[1]),o=this.resolveConflictAction(e,this.pkDeclaredConflict());return o===Bm.IGNORE?{kind:"swallow"}:o===Bm.REPLACE?{kind:"displace",row:n,entry:t}:{kind:"blocked",result:{status:"constraint",constraint:"unique",message:this.uniqueConstraintMessage(),existingRow:n}}}async resolveSecondaryUniqueDecision(r,e,t){let n=this.tableSchema.uniqueConstraints;if(!n||n.length===0)return{kind:"clear"};if(!this.collection||!this.rowCodec||!this.indexManager)return{kind:"clear"};let o=n.filter(i=>i.predicate===void 0&&i.columns.length>0&&i.columns.every(a=>r[a]!==null&&r[a]!==void 0)),s=new Map;for(let i of o){let a=await this.probeUniqueConstraint(i,r,t);if(a.length===0)continue;let c=this.resolveConflictAction(e,i.defaultConflict);if(c===Bm.IGNORE)return{kind:"swallow"};if(c===Bm.REPLACE){for(let l of a)s.set(l.pk,l);continue}return{kind:"blocked",result:{status:"constraint",constraint:"unique",message:this.uniqueConstraintMessage(i.columns),existingRow:a[0].row}}}return s.size>0?{kind:"evict",collisions:[...s.values()]}:{kind:"clear"}}async applyUniqueEvictions(r,e){if(!this.collection||!this.indexManager)throw new Error("Table not initialized");let t=[];for(let{pk:n,row:o,entry:s}of r)await this.collection.stage([[n,void 0,Fx(s)]]),await this.indexManager.deleteIndexEntries(o,n,e),t.push(o);return t}async requirePreWriteRow(r,e,t){if(!this.collection||!this.rowCodec)throw new Error("Table not initialized");let n=await this.collection.get(e);if(!n)throw new Aa(`${r} could not find the pre-write row in table ${this.tableSchema.name} at primary key ${Z6e(t)} \u2014 the engine and the collection disagree about what exists.`,Ia.ERROR);return{row:this.rowCodec.decodeRow(n[1]),entry:n}}async update(r){let{operation:e,values:t,mutationStatement:n}=r;if(await this.ensureConnectionRegistered(),this.isInitialized||await this.initialize(),!this.collection||!this.rowCodec||!this.indexManager)throw new Error("Table not initialized");n&&await this.txnBridge.addStatement(n);let o=this.txnBridge.getCurrentTransaction();try{switch(e){case"insert":if(!t)throw new Error("INSERT requires values");{let s=this.rowCodec.extractPrimaryKey(t),i=await this.collection.get(s);if(i!==void 0){let u=this.rowCodec.decodeRow(i[1]),d=this.resolveConflictAction(r.onConflict,this.pkDeclaredConflict());if(d===Bm.IGNORE)return{status:"ok"};if(d===Bm.REPLACE){let h=await this.resolveSecondaryUniqueDecision(t,r.onConflict,new Set([s]));if(h.kind==="blocked")return h.result;if(h.kind==="swallow")return{status:"ok"};let p=this.rowCodec.encodeRow(t);this.markDirtyTrees();let f=h.kind==="evict"?await this.applyUniqueEvictions(h.collisions,o?.transactor):[];return await this.collection.stage([[s,[s,p],Fx(i)]]),await this.indexManager.updateIndexEntries(u,t,s,s,o?.transactor,this.guardedUniqueIndexes(t)),{status:"ok",row:t,replacedRow:u,...f.length>0?{evictedRows:f}:{}}}return{status:"constraint",constraint:"unique",message:this.uniqueConstraintMessage(),existingRow:u}}let a=await this.resolveSecondaryUniqueDecision(t,r.onConflict);if(a.kind==="blocked")return a.result;if(a.kind==="swallow")return{status:"ok"};let c=this.rowCodec.encodeRow(t);this.markDirtyTrees();let l=a.kind==="evict"?await this.applyUniqueEvictions(a.collisions,o?.transactor):[];return await this.collection.stage([[s,[s,c],{kind:"absent"}]]),await this.indexManager.insertIndexEntries(t,s,o?.transactor,this.guardedUniqueIndexes(t)),{status:"ok",row:t,...l.length>0?{evictedRows:l}:{}}}case"update":if(!t)throw new Error("UPDATE requires values");if(!r.oldKeyValues)throw new Error("UPDATE requires old key values");{let s=this.rowCodec.asPrimaryKeyTuple(r.oldKeyValues),i=this.rowCodec.createPrimaryKey(s),a=this.rowCodec.extractPrimaryKey(t),c=this.rowCodec.encodeRow(t),{row:l,entry:u}=await this.requirePreWriteRow("UPDATE",i,s),d=i!==a?await this.resolvePkMoveDecision(a,r.onConflict):{kind:"clear"};if(d.kind==="blocked")return d.result;if(d.kind==="swallow")return{status:"ok"};let h=new Set([i]);d.kind==="displace"&&h.add(a);let p=await this.resolveSecondaryUniqueDecision(t,r.onConflict,h);if(p.kind==="blocked")return p.result;if(p.kind==="swallow")return{status:"ok"};this.markDirtyTrees();let f=p.kind==="evict"?await this.applyUniqueEvictions(p.collisions,o?.transactor):[],g=d.kind==="displace"?Fx(d.entry):{kind:"absent"};return await this.collection.stage(i!==a?[[i,void 0,Fx(u)],[a,[a,c],g]]:[[a,[a,c],Fx(u)]]),d.kind==="displace"&&await this.indexManager.deleteIndexEntries(d.row,a,o?.transactor),await this.indexManager.updateIndexEntries(l,t,i,a,o?.transactor,this.guardedUniqueIndexes(t)),{status:"ok",row:t,...d.kind==="displace"?{replacedRow:d.row}:{},...f.length>0?{evictedRows:f}:{}}}case"delete":if(!r.oldKeyValues)throw new Error("DELETE requires old key values");{let s=this.rowCodec.asPrimaryKeyTuple(r.oldKeyValues),i=this.rowCodec.createPrimaryKey(s),{row:a,entry:c}=await this.requirePreWriteRow("DELETE",i,s);return this.markDirtyTrees(),await this.collection.stage([[i,void 0,Fx(c)]]),await this.indexManager.deleteIndexEntries(a,i,o?.transactor),{status:"ok"}}default:throw new Error(`Unsupported operation: ${e}`)}}catch(s){if(s instanceof Aa)throw s;let i=this.txnBridge.mapCommitRefusal(s);if(i!==s&&i instanceof Error)throw this.setErrorMessage(i.message),i;let a=Ux(`${e} failed`,s);throw this.setErrorMessage(a.message),a}}mirrorDerivedUniqueConstraint(r){if(!r.unique)return;let e={columns:r.columns.map(o=>o.index),predicate:r.predicate,derivedFromIndex:r.name},t=Kx(e);(this.tableSchema.uniqueConstraints??[]).some(o=>o.derivedFromIndex===r.name||Kx(o)===t)||(this.tableSchema={...this.tableSchema,uniqueConstraints:[...this.tableSchema.uniqueConstraints??[],e]})}async addIndex(r,e){if(this.isInitialized||await this.initialize(),!this.schemaManager||!this.indexManager)throw new Error("Table not initialized");let t=await this.schemaManager.getSchemaFresh(this.schemaName,this.tableName);if(!t)throw new Error("Schema not found");let n=this.txnBridge.getCurrentTransaction(),o=t.indexes.find(l=>l.name===r.name);if(o||await this.guardIndexAdoption(r,t,n?.transactor),this.mirrorDerivedUniqueConstraint(r),o){let l=t;if(r.unique&&!o.unique){let{unique:d,predicate:h}=this.schemaManager.indexSchemaToStored(r),p={...t,indexes:t.indexes.map(f=>f.name===r.name?{...f,unique:d,predicate:h}:f)};l=await this.schemaManager.storeStoredSchema(p,n?.transactor)}let u=await this.reconcileMaintainedIndexes(l,n?.transactor);l!==t&&this.indexManager.setSchema(l),await this.backfillIndexTrees(u,e),this.registerUniqueKeyTakenMessages();return}let s={...t,indexes:[...t.indexes,this.schemaManager.indexSchemaToStored(r)]},i=await this.schemaManager.storeStoredSchema(s,n?.transactor),a=await this.openIndexTree(r.name,n?.transactor);this.indexManager.registerIndexTree(r.name,a);let c=await this.reconcileMaintainedIndexes(i,n?.transactor);await this.backfillIndexTrees(c,e),this.registerUniqueKeyTakenMessages()}async removeIndex(r){if(this.isInitialized||await this.initialize(),!this.schemaManager||!this.indexManager)throw new Error("Table not initialized");let e=this.txnBridge.getCurrentTransaction();await this.schemaManager.removeIndex(this.schemaName,this.tableName,r,e?.transactor);let t=this.indexManager.unregisterIndex(r);t&&this.txnBridge.forgetTree(t);let n=r.toLowerCase(),o=(this.tableSchema.uniqueConstraints??[]).filter(s=>{var i;return((i=s.derivedFromIndex)==null?void 0:i.toLowerCase())!==n});this.tableSchema={...this.tableSchema,indexes:(this.tableSchema.indexes??[]).filter(s=>s.name.toLowerCase()!==n),uniqueConstraints:o.length>0?o:void 0},await this.reassignUniqueEnforcement(e?.transactor)}async reassignUniqueEnforcement(r){if(!this.indexManager||!this.schemaManager)return;let e={...this.schemaManager.tableSchemaToStored(this.tableSchema),indexes:this.indexManager.getDeclaredIndexes()},t=new Set(this.uniqueEnforcementIndexes.map(o=>o.name)),n=this.buildUniqueEnforcementIndexes(e).filter(o=>!t.has(o.name));if(n.length!==0){await this.indexManager.setUniqueEnforcementIndexes([...this.uniqueEnforcementIndexes,...n],r);for(let o of n){let s=this.indexManager.getIndexTree(o.name);if(!s)throw new Error(`Index tree not found: ${o.name}`);this.txnBridge.registerCollection(s.getCollection()),await this.populateUniqueTree(o,s),this.populatedUniqueTrees.add(o.name),this.uniqueEnforcementIndexes=[...this.uniqueEnforcementIndexes,o]}this.registerUniqueKeyTakenMessages()}}async addCheckConstraint(r){var e;this.isInitialized||await this.initialize();let t=this.txnBridge.getCurrentTransaction(),n=await this.schemaManager.getSchemaFresh(this.schemaName,this.tableName,t?.transactor);if(!n)throw new Error(`Schema not found for Optimystic table '${this.schemaName}.${this.tableName}'. Cannot add CHECK constraint.`);await this.schemaManager.storeStoredSchema(this.schemaManager.withCheckConstraint(n,r),t?.transactor);let o=(e=r.name)==null?void 0:e.toLowerCase();this.tableSchema={...this.tableSchema,checkConstraints:[...this.tableSchema.checkConstraints.filter(s=>{var i;return o===void 0||((i=s.name)==null?void 0:i.toLowerCase())!==o}),r]}}async guardIndexAdoption(r,e,t){let n=(e.orphanedIndexes??[]).find(c=>c.name===r.name);if(!n)return;let o=r.columns.map(c=>{var l;return((l=this.tableSchema.columns[c.index])==null?void 0:l.name)??`#${c.index}`}),s=n.columns.map(c=>c.name);if(o.length===s.length&&o.every((c,l)=>c.toLowerCase()===s[l].toLowerCase()))return;let a=await this.openIndexTree(r.name,t);if(a.at(await a.first())!==void 0)throw new Error(`Cannot create index '${r.name}' over '${this.options.collectionUri}/index/${r.name}': that collection still holds entries from a dropped index of the same name declared on (${s.join(", ")}), not (${o.join(", ")}). Use a different index name, or a different collection URI for the table.`)}async backfillIndexTrees(r,e){if(r.length===0||!this.collection||!this.rowCodec||!this.indexManager)return;let t=this.indexManager,n=this.collection,o=this.rowCodec,s=r.map(a=>{let c=t.getIndexSchema(a),l=t.getIndexTree(a);if(!c||!l)throw new Error(`Cannot populate index '${a}' on '${this.tableName}': ${c?"tree":"descriptor"} not registered`);return{name:a,descriptor:c,tree:l}}),i=!1;if(!await this.hasNoRowsToBackfill()){await n.update();for await(let{row:a,primaryKey:c}of MJ(n,o)){for(let{descriptor:l,tree:u}of s){let d=ed(t.createIndexKey(l,a),c);await u.stage([[d,[d,c]]])}i=!0}}if(e){for(let{name:a,tree:c}of s)!i&&c.committedRevision()===void 0||c.hasUnsyncedChanges()&&e(a,c);return}await this.flushDirtyTrees(s)}async hasNoRowsToBackfill(r=this.collection){return r?r.at(await r.first())===void 0:!0}async verifyIndexes(){if(!this.collection||!this.rowCodec||!this.indexManager)throw new Error("Table not initialized");let r=this.indexManager,e=new Set(r.getDeclaredIndexes().map(s=>s.name)),t=r.getAllMaintainedIndexes().map(s=>{let i=r.getIndexTree(s.name);if(!i)throw new Error(`Index tree not found: ${s.name}`);return{index:s,tree:i}});await this.collection.update();for(let{tree:s}of t)await s.update();let n=new Map;for await(let{row:s,primaryKey:i}of MJ(this.collection,this.rowCodec))n.set(i,s);let o=[];for(let{index:s,tree:i}of t){let a=[];for await(let c of r.allEntriesIn(i))a.push(c);o.push(umt({table:this.tableName,index:s,kind:e.has(s.name)?"declared":"unique-enforcement",rows:n,entries:a,indexKeyOf:c=>r.createIndexKey(s,c)}))}return o}async flushDirtyTrees(r){for(let{tree:e}of r)e.hasUnsyncedChanges()&&await e.sync()}async openIndexTree(r,e){let t=`${this.options.collectionUri}/index/${r}`,n={...this.options,collectionUri:t},o=await this.collectionFactory.createOrGetCollection(n,e?{transactor:e,isActive:!0,collections:new Map,stampId:""}:void 0);return Ca("index:tree-open table=%s index=%s uri=%s collection=%s node=%s",this.tableName,r,t,String(o.getCollection().id),this.collectionFactory.nodeTag()),o}async reconcileMaintainedIndexes(r,e){if(!this.indexManager)throw new Error("Table not initialized");let t=this.indexManager,n=r.indexes.filter(o=>t.getIndexSchema(o.name)===void 0||t.getIndexTree(o.name)===void 0).map(o=>o.name);r.indexes.some(o=>t.getIndexSchema(o.name)===void 0)&&t.setSchema(r);for(let o of r.indexes){let s=t.getIndexTree(o.name);s||(s=await this.openIndexTree(o.name,e),t.registerIndexTree(o.name,s)),this.txnBridge.registerCollection(s.getCollection())}return n}indexMaintenanceState(r){return!this.indexManager||!this.isInitialized&&!this.isProvisionallyInitialized?"unknown":this.indexManager.getIndexSchema(r)===void 0||this.indexManager.getIndexTree(r)===void 0?"unmaintained":"maintained"}async begin(){try{await this.ensureConnectionRegistered(),await this.txnBridge.beginTransaction(this.options)}catch(r){let e=Ux("Begin transaction failed",r);throw this.setErrorMessage(e.message),e}}async commit(){try{await this.txnBridge.commitTransaction()}catch(r){let e=Ux("Commit transaction failed",r);throw this.setErrorMessage(e.message),e}}async rollback(){try{await this.txnBridge.rollbackTransaction()}catch(r){let e=Ux("Rollback transaction failed",r);throw this.setErrorMessage(e.message),e}}async deleteOwnSchema(){let r=this.txnBridge.getCurrentTransaction();await this.schemaManager.deleteSchema(this.schemaName,this.tableName,r?.transactor)}get catalogManager(){return this.schemaManager}markSchemaUnpersisted(r=new Set){if(this.indexManager){let e=this.indexManager.getDeclaredIndexes().filter(t=>!r.has(t.name));this.tableSchema={...this.tableSchema,indexes:this.schemaManager.storedIndexesToIndexSchemas(e)},r.size>0&&this.tableSchema.uniqueConstraints&&(this.tableSchema={...this.tableSchema,uniqueConstraints:this.tableSchema.uniqueConstraints.filter(t=>t.derivedFromIndex===void 0||!r.has(t.derivedFromIndex))})}this.isInitialized=!1,this.isProvisionallyInitialized=!1}},wmt=class extends Q6e{constructor(r){super(r.db,r.module,r.schemaName,r.tableName),this.inner=r,this.tableSchema=r.tableSchema}async*query(r){yield*this.inner.queryCommitted(r)}async update(){throw new Aa("Cannot modify committed-state snapshot",Ia.ERROR)}createConnection(){throw new Aa("A committed-read (_readCommitted) table cannot create a transaction connection",Ia.MISUSE)}getConnection(){}async disconnect(){}},xmt=class{constructor(r,e){this.collectionFactory=r,this.txnBridge=e}concurrencyMode="reentrant-reads";readCommittedSnapshot=!0;tables=new Map;schemaManagers=new Map;schemaBatch;createSchemaManager(r){var e,t;let n=[r.transactor??"",r.keyNetwork??"",((e=r.libp2pOptions)==null?void 0:e.networkName)??"",((t=r.libp2pOptions)==null?void 0:t.port)??0,r.rawStorageFactory?"1":"0"].join("|"),o=this.schemaManagers.get(n);if(o)return o;let s=new smt(async(i,a)=>{let c={collectionUri:"tree://optimystic/schema",transactor:r.transactor,keyNetwork:r.keyNetwork,libp2p:r.libp2p,libp2pOptions:r.libp2pOptions,cache:!0,encoding:"json",rawStorageFactory:r.rawStorageFactory},l=i?{transactor:i,isActive:!0,collections:new Map,stampId:""}:void 0;return a?await this.collectionFactory.createOrGetCollection(c,l):await this.collectionFactory.getCollection(c,l)});return this.schemaManagers.set(n,s),this.schemaBatch&&(s.beginBatch(),this.schemaBatch.managers.add(s)),s}async beginSchemaBatch(r,e){if(this.schemaBatch)throw new Error("Optimystic schema batch already open: beginSchemaBatch without a matching endSchemaBatch");let t=new Set;for(let n of this.schemaManagers.values())n.beginBatch(),t.add(n);this.schemaBatch={managers:t,written:new Map,dropped:new Map,deferred:new Map}}async endSchemaBatch(r,e,t){var n;let o=this.schemaBatch;if(!o)throw new Error("Optimystic schema batch is not open: endSchemaBatch without a matching beginSchemaBatch");this.schemaBatch=void 0;let s=!1,i;for(let a of o.managers){let c=new Map(o.deferred.get(a)),l="index-tree flush";try{for(let u of[...c.keys()])u.hasUnsyncedChanges()&&await u.sync(),c.delete(u);l="catalog commit",await a.commitBatch()}catch(u){a.discardBatch();let d=new Map;for(let{tableKey:f,indexName:g}of c.values())d.set(f,(d.get(f)??new Set).add(g));let h=[...o.written.get(a)??[]],p=[...o.dropped.get(a)??[]];for(let f of h)(n=this.tables.get(f))==null||n.markSchemaUnpersisted(d.get(f));Ca("endSchemaBatch: %s failed: %s. The catalog batch was not committed. %d table(s) will re-persist their schema on next touch (%s), without the %d index(es) whose tree did not land (%s); %d dropped table(s) keep a live catalog record past their DROP \u2014 the next hydrate resurrects them and a later CREATE over the same URI is not checked against them (%s)",l,u,h.length,h.join(", "),c.size,[...c.values()].map(({tableKey:f,indexName:g})=>`${f}.${g}`).join(", "),p.length,p.join(", ")),s||(s=!0,i=u)}}if(s)throw i}async underBatchCheckpoint(r,e,t,n){let o=this.schemaBatch;if(!o)return n();let s=r.catalogManager,i=s.checkpointBatch();try{let a=await n(),c=o[e].get(s)??new Set;return c.add(t),o[e].set(s,c),a}catch(a){throw i&&s.restoreBatch(i),a}}parseTableSchema(r){let e=r.vtabArgs||{},t=r.vtabAuxData??{};return{collectionUri:e[0]||lke(r.schemaName,r.name),...Y6e(e,t),cache:e.cache!==!1,encoding:e.encoding||"json"}}async instantiateTable(r,e,t){let n=`${e.schemaName}.${e.name}`.toLowerCase(),o=this.tables.get(n);if(o)return o;let s=t??this.parseTableSchema(e),i=this.createSchemaManager(s),a=new bmt(r,this,e.schemaName||"main",e.name,e,s,this.collectionFactory,this.txnBridge,i);return this.tables.set(n,a),a}async create(r,e){let t=`${e.schemaName}.${e.name}`.toLowerCase();if(this.tables.has(t))throw new Error(`Optimystic table '${e.name}' already exists in schema '${e.schemaName}'.`);let n=await this.instantiateTable(r,e);try{await this.underBatchCheckpoint(n,"written",t,async()=>{await n.initialize(),await n.ensureConnectionRegistered()})}catch(o){throw this.tables.delete(t),n.teardownChangeSubscription(),o}return n}async connect(r,e,t,n,o,s,i){let a=s?._readCommitted===!0,c=await this.resolveConnectedTable(r,n,o,a,i);return a?new wmt(c):c}async verifyIndexes(r,e,t="main"){var n;let o=r.schemaManager.findTable(e,t);if(o&&(o.vtabModule??((n=r.schemaManager.getModule(o.vtabModuleName))==null?void 0:n.module))!==this)throw new Error(`Cannot verify indexes of '${t}.${e}': it is not an Optimystic table (module '${o.vtabModuleName}').`);return await(await this.resolveConnectedTable(r,t,e,!1)).verifyIndexes()}async resolveConnectedTable(r,e,t,n,o){let s=await this.lookupOrInstantiate(r,e,t,o);if(!s)throw new Error(`Optimystic table definition for '${t}' not found. Cannot connect.`);let{table:i,fresh:a}=s;return n?await i.initializeForCommittedRead():(await i.initialize(),a&&await i.ensureConnectionRegistered()),i}async lookupOrInstantiate(r,e,t,n){let o=`${e}.${t}`.toLowerCase(),s=this.tables.get(o);if(s)return{table:s,fresh:!1};let i=n??r.schemaManager.findTable(t,e);if(i)return{table:await this.instantiateTable(r,i),fresh:!0}}async hydrateCatalog(r,e={},t){var n;let o=this.sessionDefaultVtabArgs(r),s=this.deriveDefaultOptions(e,o),i=this.createSchemaManager(s),a;try{a=await i.listTables()}catch(u){let d=u instanceof Error?u.message:String(u);if(/not found|missing|empty/i.test(d))return{tables:0,indexes:0};throw u}let c=0,l=0;for(let{schemaName:u,tableName:d}of a){let h=r.schemaManager.getSchema(u);if(h?.getTable(d))continue;let p=await i.getSchema(u,d);if(!p)continue;let f=i.storedToTableSchema(p,this,t,o);(h??r.schemaManager.addSchema(u)).addTable(f),c++,l+=((n=f.indexes)==null?void 0:n.length)??0}return{tables:c,indexes:l}}sessionDefaultVtabArgs(r){var e;let{name:t,args:n}=r.schemaManager.getDefaultVTabModule();return((e=r.schemaManager.getModule(t))==null?void 0:e.module)===this?n:{}}deriveDefaultOptions(r,e={}){return{collectionUri:"tree://optimystic/schema",...Y6e(e,r),cache:!0,encoding:"json"}}async createIndex(r,e,t,n){let o=`${e}.${t}`.toLowerCase(),s=await this.lookupOrInstantiate(r,e,t);if(!s)throw new Error(`Optimystic table '${t}' not found in schema '${e}'. Cannot create index.`);let{table:i,fresh:a}=s,c=this.schemaBatch,l=c?(u,d)=>{let h=i.catalogManager,p=c.deferred.get(h)??new Map;c.deferred.set(h,p.set(d,{tableKey:o,indexName:u}))}:void 0;await this.underBatchCheckpoint(i,"written",o,async()=>{a&&(await i.initialize(),await i.ensureConnectionRegistered()),await i.addIndex(n,l)})}async dropIndex(r,e,t,n){var o;let s=`${e}.${t}`.toLowerCase(),i=await this.lookupOrInstantiate(r,e,t);if(!i)throw new Error(`Optimystic table '${t}' not found in schema '${e}'. Cannot drop index.`);let{table:a,fresh:c}=i;await this.underBatchCheckpoint(a,"written",s,async()=>{c&&(await a.initialize(),await a.ensureConnectionRegistered()),await a.removeIndex(n)});let l=(o=this.schemaBatch)==null?void 0:o.deferred.get(a.catalogManager);if(l){let u=n.toLowerCase();for(let[d,h]of l)h.tableKey===s&&h.indexName.toLowerCase()===u&&l.delete(d)}}async alterTable(r,e,t,n){let o=r.schemaManager.findTable(t,e);if(!o)throw new Aa(`Optimystic table '${t}' not found in schema '${e}'. Cannot alter.`,Ia.ERROR);let s=i=>{throw new Aa(`Module for table '${o.name}' does not support ${i}`,Ia.UNSUPPORTED)};switch(n.type){case"addConstraint":return n.constraint.type==="check"?await this.addCheckConstraint(r,o,n.constraint):s("ADD CONSTRAINT");case"renameColumn":return mmt(o,n.oldName,n.newName);case"addColumn":return s("ALTER TABLE ADD COLUMN");case"dropColumn":return s("ALTER TABLE DROP COLUMN");case"dropConstraint":return s("ALTER TABLE DROP CONSTRAINT");case"renameConstraint":return s("ALTER TABLE RENAME CONSTRAINT");case"alterColumn":return s("ALTER COLUMN");case"alterPrimaryKey":return s("ALTER PRIMARY KEY")}}async addCheckConstraint(r,e,t){let n=Lpt(t,e.checkConstraints.length,Mpt(e)),{schemaName:o,name:s}=e,i=`${o}.${s}`.toLowerCase(),a=await this.lookupOrInstantiate(r,o,s,e);if(!a)throw new Error(`Optimystic table '${s}' not found in schema '${o}'. Cannot add CHECK constraint.`);let{table:c,fresh:l}=a;return await this.underBatchCheckpoint(c,"written",i,async()=>{l&&(await c.initialize(),await c.ensureConnectionRegistered()),await c.addCheckConstraint(n)}),{...e,checkConstraints:Object.freeze([...e.checkConstraints,n])}}getBestAccessPlan(r,e,t){let n=t.estimatedRows||1e6,s=Math.max(1e3,n),i=n,a=t.filters.map(()=>!1),c,l=!1,u=`Full table scan (${n} rows)`,d,h,p=e.primaryKeyDefinition.map(g=>g.index),f=p.length>0&&p.every(g=>t.filters.some(y=>y&&y.usable&&y.op==="="&&y.columnIndex===g));for(let g=0;g<t.filters.length;g++){let y=t.filters[g];if(!y||!y.usable)continue;let m=p.includes(y.columnIndex);if(m&&y.op==="="&&f){let w=Math.log2(Math.max(2,n))*2;s=w,i=1,a=t.filters.map(b=>b!=null&&b.usable&&b.op==="="&&p.includes(b.columnIndex)),l=!0,d="_primary_",h=[...p],u=`Primary key equality seek (cost: ${w.toFixed(2)})`,t.requiredOrdering&&t.requiredOrdering.length>0&&(c=[...t.requiredOrdering]);break}else if(m&&y.op==="="&&!f){let w=n*.3;w<s&&(s=w,i=Math.max(1,Math.floor(n*.3)),a=t.filters.map(()=>!1),l=!1,u=`Partial primary key scan (cost: ${w.toFixed(2)})`)}else if(m&&[">",">=","<","<="].includes(y.op)){let b=Math.log2(Math.max(2,n))*2+n*.25,x=Math.floor(n*.25);b<s&&(s=b,i=x,a=t.filters.map(()=>!1),u=`Primary key range scan (selectivity: ${.25.toFixed(2)}, cost: ${b.toFixed(2)})`)}}if(s>10&&e.indexes&&e.indexes.length>0)for(let g of e.indexes){let y=g.columns.map(b=>b.index),m=1,w=[];for(let b=0;b<y.length;b++){let x=y[b],S=!1;for(let T=0;T<t.filters.length;T++){let A=t.filters[T];if(!(!A||!A.usable)&&A.columnIndex===x&&A.op==="="){w.push(T),S=!0,m*=.1;break}}if(!S)break}if(w.length>0){let b=Math.log2(Math.max(2,n))*2+n*m,x=Math.max(1,Math.floor(n*m));b<s&&(s=b,i=x,a=t.filters.map((S,T)=>w.includes(T)),l=!1,d=g.name,h=w.map(S=>t.filters[S].columnIndex),u=`Index seek on ${g.name} (selectivity: ${m.toFixed(4)}, cost: ${b.toFixed(2)})`,t.requiredOrdering&&this.orderingMatchesIndex(t.requiredOrdering,g,e)&&(c=[...t.requiredOrdering]))}}return d!==void 0&&d!=="_primary_"&&this.assertIndexMaintained(e,d),{handledFilters:a,cost:s,rows:i,providesOrdering:c,indexName:d,seekColumnIndexes:h,isSet:l,explains:u}}assertIndexMaintained(r,e){var t;let n=`${r.schemaName}.${r.name}`.toLowerCase();if((((t=this.tables.get(n))==null?void 0:t.indexMaintenanceState(e))??"unknown")==="unmaintained")throw new Aa(OJ(r.name,e,"the catalog offers it to query planning, but this table instance's writes do not keep it up to date"),Ia.ERROR)}orderingMatchesIndex(r,e,t){if(r.length>e.columns.length)return!1;for(let n=0;n<r.length;n++){let o=r[n],s=e.columns[n];if(!o||!s||o.columnIndex!==s.index||!this.treeDeliversOrdering(o,t))return!1}return!0}treeDeliversOrdering(r,e){var t;if(r.desc)return!1;let n=e.columns[r.columnIndex];return!(!n||((t=n.logicalType)==null?void 0:t.physicalType)!==Bpt.TEXT||(n.collation||"BINARY").toUpperCase()!=="BINARY")}async destroy(r,e,t,n,o){let s=`${n}.${o}`.toLowerCase(),i=this.tables.get(s)??await this.instantiateForTeardown(r,n,o);if(i){i.teardownChangeSubscription();try{await this.underBatchCheckpoint(i,"dropped",s,()=>i.deleteOwnSchema())}catch(a){Ca("destroy(%s.%s): gravestone write failed; the catalog record outlives its DROP and a later CREATE over the same URI will not be checked against it: %s",n,o,a)}}this.tables.delete(s)}async instantiateForTeardown(r,e,t){let n=r.schemaManager.findTable(t,e);if(n)try{return await this.instantiateTable(r,n)}catch{return}}};function vmt(r){return function(){let t=r.getCurrentTransaction();return!t||!t.isActive?null:t.stampId}}var Emt=b3("plugin");function KJ(r,e={}){e.debug&&Emt("Optimystic plugin loading with config: %o",e);let t=new zpt,n=new Gpt(t),o=new xmt(t,n),s=vmt(n);return{vtables:[{name:"optimystic",module:o,auxData:e}],functions:[{schema:{name:"StampId",numArgs:0,flags:1,returnType:{typeClass:"scalar",logicalType:Opt,nullable:!0,isReadOnly:!0},implementation:s}}],collations:[],collectionFactory:t,txnBridge:n,hydrate:i=>o.hydrateCatalog(i,e,e),verifyIndexes:(i,a,c)=>o.verifyIndexes(i,a,c),dispose:()=>t.dispose()}}var bke=` table Header (
46
+ `),t),n('responded with "na" for "%s"',s)}}Be();se();_s();var fV=class extends Lt{id;remoteAddr;remotePeer;direction;timeline;direct;multiplexer;encryption;limits;log;maConn;muxer;components;outboundStreamProtocolNegotiationTimeout;inboundStreamProtocolNegotiationTimeout;closeTimeout;constructor(e,t){super(),this.components=e,this.id=t.id,this.remoteAddr=t.maConn.remoteAddr,this.remotePeer=t.remotePeer,this.direction=t.direction??"outbound",this.timeline=t.maConn.timeline,this.encryption=t.cryptoProtocol,this.limits=t.limits,this.maConn=t.maConn,this.log=t.maConn.log,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.closeTimeout=t.closeTimeout??1e3,this.direct=jH(t.maConn.remoteAddr),this.onIncomingStream=this.onIncomingStream.bind(this),this.remoteAddr.getComponents().find(n=>n.code===421)==null&&(this.remoteAddr=this.remoteAddr.encapsulate(`/p2p/${this.remotePeer}`)),t.muxer!=null&&(this.multiplexer=t.muxer.protocol,this.muxer=t.muxer,this.muxer.addEventListener("stream",this.onIncomingStream)),this.maConn.addEventListener("close",n=>{this.dispatchEvent(new Pd(n.local,n.error))})}[Symbol.toStringTag]="Connection";[Gne]=!0;get streams(){return this.muxer?.streams??[]}get status(){return this.maConn.status}newStream=async(e,t={})=>{if(this.muxer==null)throw new Af("Connection is not multiplexed");if(this.muxer.status!=="open")throw new Nh(`The connection muxer is "${this.muxer.status}" and not "open"`);if(this.maConn.status!=="open")throw new Nh(`The connection is "${this.status}" and not "open"`);if(this.limits!=null&&t?.runOnLimitedConnection!==!0)throw new qv("Cannot open protocol stream on limited connection");Array.isArray(e)||(e=[e]),this.log.trace("starting new stream for protocols %s",e);let n=await this.muxer.createStream({...t,protocol:e.length===1?e[0]:void 0});this.log.trace("started new stream %s for protocols %s",n.id,e);try{if(t.signal==null){n.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",e);let a=AbortSignal.timeout(this.outboundStreamProtocolNegotiationTimeout);t={...t,signal:a}}n.protocol===""?(n.log.trace("selecting protocol from protocols %s",e),n.protocol=await _0(n,e,t),n.log("negotiated protocol %s",n.protocol)):n.log("pre-negotiated protocol %s",n.protocol);let o=gYe(n.protocol,this.components.registrar,t),s=Qwe(n.protocol,"outbound",this);if(s>o){let a=new Vg(`Too many outbound protocol streams for protocol "${n.protocol}" - ${s}/${o}`);throw n.abort(a),a}await this.components.peerStore.merge(this.remotePeer,{protocols:[n.protocol]}),this.components.metrics?.trackProtocolStream(n);let i=this.components.registrar.getMiddleware(n.protocol);return await this.runMiddlewareChain(n,this,i)}catch(o){throw n.status==="open"?n.abort(o):this.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e",this.direction==="inbound"?"from":"to",this.remoteAddr,e,o),o}};async onIncomingStream(e){let t=e.detail,n=AbortSignal.timeout(this.inboundStreamProtocolNegotiationTimeout);t.log("start protocol negotiation, timing out after %dms",this.inboundStreamProtocolNegotiationTimeout);try{if(t.protocol===""){let l=this.components.registrar.getProtocols();t.log.trace("selecting protocol from protocols %s",l),t.protocol=await P0(t,l,{signal:n}),t.log("negotiated protocol %s",t.protocol)}else t.log("pre-negotiated protocol %s",t.protocol);let o=mYe(t.protocol,this.components.registrar);if(Qwe(t.protocol,"inbound",this)>o)throw new TT(`Too many inbound protocol streams for protocol "${t.protocol}" - limit ${o}`);await this.components.peerStore.merge(this.remotePeer,{protocols:[t.protocol]},{signal:n}),this.components.metrics?.trackProtocolStream(t);let{handler:i,options:a}=this.components.registrar.getHandler(t.protocol);if(this.limits!=null&&a.runOnLimitedConnection!==!0)throw new qv("Cannot open protocol stream on limited connection");let c=this.components.registrar.getMiddleware(t.protocol);c.push(async(l,u,d)=>{await i(l,u),d(l,u)}),await this.runMiddlewareChain(t,this,c)}catch(o){t.abort(o)}}async runMiddlewareChain(e,t,n){for(let o=0;o<n.length;o++){let s=n[o];e.log.trace("running middleware",o,s),await new Promise((i,a)=>{try{let c=s(e,t,(l,u)=>{e=l,t=u,i()});c instanceof Promise&&c.catch(a)}catch(c){a(c)}}),e.log.trace("ran middleware",o,s)}return e}async close(e={}){if(this.log("closing connection to %a",this.remoteAddr),e.signal==null){let t=AbortSignal.timeout(this.closeTimeout);e={...e,signal:t}}await this.muxer?.close(e),await this.maConn.close(e)}abort(e){this.muxer?.abort(e),this.maConn.abort(e)}};function exe(r,e){return new fV(r,e)}function mYe(r,e){try{let{options:t}=e.getHandler(r);if(t.maxInboundStreams!=null)return t.maxInboundStreams}catch(t){if(t.name!=="UnhandledProtocolError")throw t}return lV}function gYe(r,e,t={}){try{let{options:n}=e.getHandler(r);if(n.maxOutboundStreams!=null)return n.maxOutboundStreams}catch(n){if(n.name!=="UnhandledProtocolError")throw n}return t.maxOutboundStreams??uV}function Qwe(r,e,t){let n=0;return t.streams.forEach(o=>{o.direction===e&&o.protocol===r&&n++}),n}var bR=class{components;connectionEncrypters;streamMuxers;inboundUpgradeTimeout;inboundStreamProtocolNegotiationTimeout;outboundStreamProtocolNegotiationTimeout;events;metrics;connectionCloseTimeout;constructor(e,t){this.components=e,this.connectionEncrypters=mo({name:"libp2p_upgrader_connection_encrypters",metrics:this.components.metrics}),t.connectionEncrypters.forEach(n=>{this.connectionEncrypters.set(n.protocol,n)}),this.streamMuxers=mo({name:"libp2p_upgrader_stream_multiplexers",metrics:this.components.metrics}),t.streamMuxers.forEach(n=>{this.streamMuxers.set(n.protocol,n)}),this.inboundUpgradeTimeout=t.inboundUpgradeTimeout??1e4,this.inboundStreamProtocolNegotiationTimeout=t.inboundStreamProtocolNegotiationTimeout??1e4,this.outboundStreamProtocolNegotiationTimeout=t.outboundStreamProtocolNegotiationTimeout??1e4,this.connectionCloseTimeout=t.connectionCloseTimeout??1e3,this.events=e.events,this.metrics={dials:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dial_errors_total"),inboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_inbound_errors_total"),outboundErrors:e.metrics?.registerCounterGroup("libp2p_connection_manager_dials_outbound_errors_total")}}[Symbol.toStringTag]="@libp2p/upgrader";async shouldBlockConnection(e,...t){let n=this.components.connectionGater[e];if(n==null)return;if(await n.apply(this.components.connectionGater,t)===!0)throw new WP(`The multiaddr connection is blocked by gater.${e}`)}createInboundAbortSignal(e){let t=Nn([AbortSignal.timeout(this.inboundUpgradeTimeout),e]);return t}async upgradeInbound(e,t){let n=!1,o=this.createInboundAbortSignal(t.signal);try{if(this.metrics.dials?.increment({inbound:!0}),n=this.components.connectionManager.acceptIncomingConnection(e),!n)throw new YP("Connection denied");await qt(this.shouldBlockConnection("denyInboundConnection",e),o),await this._performUpgrade(e,"inbound",{...t,signal:o})}catch(s){throw this.metrics.errors?.increment({inbound:!0}),this.metrics.inboundErrors?.increment({[s.name??"Error"]:!0}),s}finally{o.clear(),n&&this.components.connectionManager.afterUpgradeInbound()}}async upgradeOutbound(e,t){try{this.metrics.dials?.increment({outbound:!0});let n=e.remoteAddr.getComponents().findLast(i=>i.code===421)?.value,o;n!=null&&(o=le(n),await qt(this.shouldBlockConnection("denyOutboundConnection",o,e),t.signal));let s="outbound";return t.initiator===!1&&(s="inbound"),await this._performUpgrade(e,s,t)}catch(n){throw this.metrics.errors?.increment({outbound:!0}),this.metrics.outboundErrors?.increment({[n.name??"Error"]:!0}),n}}async _performUpgrade(e,t,n){let o=e,s,i,a,c,l=`${parseInt(String(Math.random()*1e9)).toString(36)}${Date.now()}`;if(e.log=e.log.newScope(`${t}:${l}`),this.components.metrics?.trackMultiaddrConnection(e),e.log.trace("starting the %s connection upgrade",t),n?.skipProtection!==!0){let d=this.components.connectionProtector;d!=null&&(e.log("protecting the %s connection",t),o=await d.protect(o,n))}try{if(yYe(n)){if(n.remotePeer==null)throw new _d(`${t} connection that skipped encryption must have a peer id`);c="native",s=n.remotePeer}else{let d=e.remoteAddr.getComponents().findLast(p=>p.code===421)?.value,h;d!=null&&(h=le(d)),n?.onProgress?.(new Dr(`upgrader:encrypt-${t}-connection`)),{connection:o,remotePeer:s,protocol:c,streamMuxer:i}=await(t==="inbound"?this._encryptInbound(o,{...n,remotePeer:h}):this._encryptOutbound(o,{...n,remotePeer:h}))}if(s.equals(this.components.peerId)){let d=new zg("Can not dial self");throw e.abort(d),d}await this.shouldBlockConnection(t==="inbound"?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,e),n?.muxerFactory!=null?i=n.muxerFactory:i==null&&this.streamMuxers.size>0&&(n?.onProgress?.(new Dr(`upgrader:multiplex-${t}-connection`)),i=await(t==="inbound"?this._multiplexInbound(o,this.streamMuxers,n):this._multiplexOutbound(o,this.streamMuxers,n)))}catch(d){throw e.log.error("failed to upgrade %s connection %s %a - %e",t,t==="inbound"?"from":"to",e.remoteAddr,d),d}i!=null&&(e.log("create muxer %s",i.protocol),a=i.createStreamMuxer(o)),await this.shouldBlockConnection(t==="inbound"?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,e);let u=this._createConnection({id:l,cryptoProtocol:c,direction:t,maConn:e,stream:o,muxer:a,remotePeer:s,limits:n?.limits,closeTimeout:this.connectionCloseTimeout});return u.log("successfully upgraded connection"),u}_createConnection(e){let t=exe(this.components,{...e,outboundStreamProtocolNegotiationTimeout:this.outboundStreamProtocolNegotiationTimeout,inboundStreamProtocolNegotiationTimeout:this.inboundStreamProtocolNegotiationTimeout});return t.addEventListener("close",()=>{this.events.safeDispatchEvent("connection:close",{detail:t})}),this.events.safeDispatchEvent("connection:open",{detail:t}),t}async _encryptInbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{let o=await P0(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Wp(`no crypto module found for ${o}`);return e.log("encrypting inbound connection using %s",o),{...await s.secureInbound(e,t),protocol:o}}catch(o){throw new Wp(o.message)}}async _encryptOutbound(e,t){let n=Array.from(this.connectionEncrypters.keys());try{e.log.trace("selecting encrypter from %s",n);let o=await _0(e,n,t),s=this.connectionEncrypters.get(o);if(s==null)throw new Wp(`no crypto module found for ${o}`);return e.log("encrypting outbound connection using %s",o),{...await s.secureOutbound(e,t),protocol:o}}catch(o){throw new Wp(o.message)}}async _multiplexOutbound(e,t,n){let o=Array.from(t.keys());e.log("outbound selecting muxer %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await _0(e,o,n),i=t.get(s);if(i==null)throw new Af(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing outbound connection - %e",s),new Af(String(s))}}async _multiplexInbound(e,t,n){let o=Array.from(t.keys());e.log("inbound handling muxers %s",o);try{e.log.trace("selecting stream muxer from %s",o);let s=await P0(e,o,n),i=t.get(s);if(i==null)throw new Af(`No muxer configured for protocol "${s}"`);return e.log("selected %s as muxer protocol",s),i}catch(s){throw e.log.error("error multiplexing inbound connection - %e",s),s}}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}};function yYe(r){return r.skipEncryption===!0}var wR="3.1.3",xR="js-libp2p";function rxe(r,e){return`${r??xR}/${e??wR} browser/${globalThis.navigator.userAgent}`}var vR=class extends Lt{peerId;peerStore;contentRouting;peerRouting;metrics;services;logger;status;components;log;constructor(e){super(),this.status="stopped";let t=new Lt,n=t.dispatchEvent.bind(t);t.dispatchEvent=l=>{let u=n(l),d=this.dispatchEvent(new CustomEvent(l.type,{detail:l.detail}));return u||d},this.peerId=e.peerId,this.logger=e.logger??w_(),this.log=this.logger.forComponent("libp2p"),this.services={};let o=e.nodeInfo?.name??xR,s=e.nodeInfo?.version??wR,i=this.components=Rwe({peerId:e.peerId,privateKey:e.privateKey,nodeInfo:{name:o,version:s,userAgent:e.nodeInfo?.userAgent??rxe(o,s)},logger:this.logger,events:t,datastore:e.datastore??new kP,connectionGater:Mwe(e.connectionGater),dns:e.dns});e.metrics!=null&&(this.metrics=this.configureComponent("metrics",e.metrics(this.components))),this.peerStore=this.configureComponent("peerStore",gwe(i,{addressFilter:this.components.connectionGater.filterMultiaddrForPeer,...e.peerStore})),i.events.addEventListener("peer:update",l=>{if(l.detail.previous==null){let u={id:l.detail.peer.id,multiaddrs:l.detail.peer.addresses.map(d=>d.multiaddr)};i.events.safeDispatchEvent("peer:discovery",{detail:u})}}),e.connectionProtector!=null&&this.configureComponent("connectionProtector",e.connectionProtector(i)),this.components.upgrader=new bR(this.components,{connectionEncrypters:(e.connectionEncrypters??[]).map((l,u)=>this.configureComponent(`connection-encryption-${u}`,l(this.components))),streamMuxers:(e.streamMuxers??[]).map((l,u)=>this.configureComponent(`stream-muxers-${u}`,l(this.components))),inboundUpgradeTimeout:e.connectionManager?.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:e.connectionManager?.inboundStreamProtocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:e.connectionManager?.outboundStreamProtocolNegotiationTimeout,connectionCloseTimeout:e.connectionManager?.connectionCloseTimeout}),this.configureComponent("transportManager",new yR(this.components,e.transportManager)),this.configureComponent("connectionManager",new lR(this.components,e.connectionManager)),e.connectionMonitor?.enabled!==!1&&this.configureComponent("connectionMonitor",new uR(this.components,e.connectionMonitor)),this.configureComponent("registrar",new gR(this.components)),this.configureComponent("addressManager",new FP(this.components,e.addresses));let a=(e.peerRouters??[]).map((l,u)=>this.configureComponent(`peer-router-${u}`,l(this.components)));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new hR(this.components,{routers:a}));let c=(e.contentRouters??[]).map((l,u)=>this.configureComponent(`content-router-${u}`,l(this.components)));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new dR(this.components,{routers:c})),this.configureComponent("randomWalk",new pR(this.components)),(e.peerDiscovery??[]).forEach((l,u)=>{this.configureComponent(`peer-discovery-${u}`,l(this.components)).addEventListener("peer",h=>{this.#e(h)})}),e.transports?.forEach((l,u)=>{this.components.transportManager.add(this.configureComponent(`transport-${u}`,l(this.components)))}),e.services!=null)for(let l of Object.keys(e.services)){let u=e.services[l],d=u(this.components);if(d==null){this.log.error("service factory %s returned null or undefined instance",l);continue}this.services[l]=d,this.configureComponent(l,d),d[fO]!=null&&(this.log("registering service %s for content routing",l),c.push(d[fO])),d[hO]!=null&&(this.log("registering service %s for peer routing",l),a.push(d[hO])),d[jv]!=null&&(this.log("registering service %s for peer discovery",l),d[jv].addEventListener?.("peer",h=>{this.#e(h)}))}Lwe(i)}configureComponent(e,t){return t==null&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}async start(){if(this.status==="stopped"){this.status="starting",this.log("libp2p is starting");try{await this.components.beforeStart?.(),await this.components.start(),await this.components.afterStart?.(),this.status="started",this.safeDispatchEvent("start",{detail:this}),this.log("libp2p has started with peer id %p",this.peerId)}catch(e){throw this.log.error("an error occurred starting libp2p - %e",e),this.status="started",await this.stop(),e}}}async stop(){this.status==="started"&&(this.log("libp2p is stopping"),this.status="stopping",await this.components.beforeStop?.(),await this.components.stop(),await this.components.afterStop?.(),this.status="stopped",this.safeDispatchEvent("stop",{detail:this}),this.log("libp2p has stopped"))}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){let e=new Mp;for(let t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}async dial(e,t={}){return this.components.connectionManager.openConnection(e,{priority:75,...t})}async dialProtocol(e,t,n={}){if(t==null)throw new q("no protocols were provided to open a stream");if(t=Array.isArray(t)?t:[t],t.length===0)throw new q("no protocols were provided to open a stream");return this.components.connectionManager.openStream(e,t,n)}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}async hangUp(e,t={}){jd(e)&&(e=le(e.getComponents().findLast(n=>n.code===421)?.value??"")),await this.components.connectionManager.closeConnections(e,t)}async getPublicKey(e,t={}){if(this.log("getPublicKey %p",e),e.publicKey!=null)return e.publicKey;try{let i=await this.peerStore.get(e,t);if(i.id.publicKey!=null)return i.id.publicKey}catch(i){if(i.name!=="NotFoundError")throw i}let n=Ye([K("/pk/"),e.toMultihash().bytes]),o=await this.contentRouting.get(n,t),s=Oye(o);return await this.peerStore.patch(e,{publicKey:s},t),s}async handle(e,t,n){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async o=>{await this.components.registrar.handle(o,t,n)}))}async unhandle(e,t){Array.isArray(e)||(e=[e]),await Promise.all(e.map(async n=>{await this.components.registrar.unhandle(n,t)}))}async register(e,t,n){return this.components.registrar.register(e,t,n)}unregister(e){this.components.registrar.unregister(e)}use(e,t){this.components.registrar.use(e,Array.isArray(t)?t:[t])}unuse(e){this.components.registrar.unuse(e)}async isDialable(e,t={}){return this.components.connectionManager.isDialable(e,t)}#e(e){let{detail:t}=e;if(t.id.toString()===this.peerId.toString()){this.log.error("peer discovery mechanism discovered self");return}this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch(n=>{this.log.error("could not update multiaddrs of discovered peer - %e",n)})}};async function nxe(r={}){r.privateKey??=await Bye("Ed25519");let e=new vR({...await Nye(r),peerId:RE(r.privateKey)});return r.start!==!1&&await e.start(),e}se();var Zpr=new Uint8Array(0);function oxe(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 If(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 bYe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var wYe=bYe,xYe=wYe,sxe=xYe;var hV=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")}},pV=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 ixe(this,e)}},mV=class{decoders;constructor(e){this.decoders=e}or(e){return ixe(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 ixe(r,e){return new mV({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gV=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new hV(e,t,n),this.decoder=new pV(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function axe({name:r,prefix:e,encode:t,decode:n}){return new gV(r,e,t,n)}function R0({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=sxe(t,r);return axe({prefix:e,name:r,encode:n,decode:s=>If(o(s))})}function vYe(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function EYe(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function SYe(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Tc({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=SYe(n);return axe({prefix:e,name:r,encode(s){return EYe(s,n,t)},decode(s){return vYe(s,o,t,r)}})}var Kn=R0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),omr=R0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var D2=Tc({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),amr=Tc({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cmr=Tc({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lmr=Tc({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),umr=Tc({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dmr=Tc({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fmr=Tc({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hmr=Tc({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pmr=Tc({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var ER=R0({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ymr=R0({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var CYe=uxe,cxe=128,AYe=127,IYe=~AYe,TYe=Math.pow(2,31);function uxe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=TYe;)e[t++]=r&255|cxe,r/=128;for(;r&IYe;)e[t++]=r&255|cxe,r>>>=7;return e[t]=r|0,uxe.bytes=t-n+1,e}var kYe=yV,DYe=128,lxe=127;function yV(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw yV.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&lxe)<<o:(i&lxe)*Math.pow(2,o),o+=7}while(i>=DYe);return yV.bytes=s-n,t}var _Ye=Math.pow(2,7),PYe=Math.pow(2,14),RYe=Math.pow(2,21),LYe=Math.pow(2,28),MYe=Math.pow(2,35),BYe=Math.pow(2,42),OYe=Math.pow(2,49),NYe=Math.pow(2,56),UYe=Math.pow(2,63),FYe=function(r){return r<_Ye?1:r<PYe?2:r<RYe?3:r<LYe?4:r<MYe?5:r<BYe?6:r<OYe?7:r<NYe?8:r<UYe?9:10},KYe={encode:CYe,decode:kYe,encodingLength:FYe},zYe=KYe,_2=zYe;function P2(r,e=0){return[_2.decode(r,e),_2.decode.bytes]}function L0(r,e,t=0){return _2.encode(r,e,t),e}function M0(r){return _2.encodingLength(r)}function kc(r,e){let t=e.byteLength,n=M0(r),o=n+M0(t),s=new Uint8Array(o+t);return L0(r,s,0),L0(t,s,n),s.set(e,o),new B0(r,t,e,s)}function fxe(r){let e=If(r),[t,n]=P2(e),[o,s]=P2(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new B0(t,o,i,e)}function hxe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&oxe(r.bytes,t.bytes)}}var B0=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function pxe(r,e){let{bytes:t,version:n}=r;return n===0?HYe(t,wV(r),e??Kn.encoder):VYe(t,wV(r),e??D2.encoder)}var mxe=new WeakMap;function wV(r){let e=mxe.get(r);if(e==null){let t=new Map;return mxe.set(r,t),t}return e}var Dc=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==R2)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==qYe)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=kc(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&&hxe(e.multihash,n.multihash)}toString(e){return pxe(this,e)}toJSON(){return{"/":pxe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??gxe(n,o,s.bytes))}else if(t[jYe]===!0){let{version:n,multihash:o,code:s}=t,i=fxe(o);return r.create(n,s,i)}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!==R2)throw new Error(`Version 0 CID must use dag-pb (code: ${R2}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=gxe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,R2,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,o=If(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new B0(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=P2(e.subarray(t));return t+=h,d},o=n(),s=R2;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=$Ye(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return wV(s).set(n,e),s}};function $Ye(r,e){switch(r[0]){case"Q":{let t=e??Kn;return[Kn.prefix,t.decode(`${Kn.prefix}${r}`)]}case Kn.prefix:{let t=e??Kn;return[Kn.prefix,t.decode(r)]}case D2.prefix:{let t=e??D2;return[D2.prefix,t.decode(r)]}case ER.prefix:{let t=e??ER;return[ER.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 HYe(r,e,t){let{prefix:n}=t;if(n!==Kn.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function VYe(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var R2=112,qYe=18;function gxe(r,e,t){let n=M0(r),o=n+M0(e),s=new Uint8Array(o+t.byteLength);return L0(r,s,0),L0(e,s,n),s.set(t,o),s}var jYe=Symbol.for("@ipld/js-cid/CID");var yxe=0,GYe="identity",bxe=If;function WYe(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 kc(yxe,bxe(r))}var O0={code:yxe,name:GYe,encode:bxe,digest:WYe};Ne();se();ct();me();Le();ct();var YYe=parseInt("11111",2),xV=parseInt("10000000",2),XYe=parseInt("01111111",2),wxe={0:L2,1:L2,2:ZYe,3:eXe,4:tXe,5:QYe,6:JYe,16:L2,22:L2,48:L2};function fu(r,e={offset:0}){let t=r[e.offset]&YYe;if(e.offset++,wxe[t]!=null)return wxe[t](r,e);throw new Error("No decoder for tag "+t)}function M2(r,e){let t=0;if((r[e.offset]&xV)===xV){let n=r[e.offset]&XYe,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function L2(r,e){M2(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=fu(r,e);if(n===null)break;t.push(n)}return t}function ZYe(r,e){let t=M2(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function JYe(r,e){let t=M2(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function QYe(r,e){return e.offset++,null}function eXe(r,e){let t=M2(r,e),n=r[e.offset];e.offset++;let o=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 o}function tXe(r,e){let t=M2(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function rXe(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function vV(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=rXe(r.byteLength);return new Y(Uint8Array.from([e.byteLength|xV]),e)}function fs(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),vV(e),e)}function SR(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),vV(t),t)}function Tf(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),vV(t),t)}async function xxe(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var nXe=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),oXe=Uint8Array.from([6,5,43,129,4,0,34]),sXe=Uint8Array.from([6,5,43,129,4,0,35]),iXe={ext:!0,kty:"EC",crv:"P-256"},aXe={ext:!0,kty:"EC",crv:"P-384"},cXe={ext:!0,kty:"EC",crv:"P-521"},EV=32,SV=48,CV=66;function vxe(r){let e=fu(r);return Exe(e)}function Exe(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===EV*2+1)return n=z(e.subarray(t,t+EV),"base64url"),o=z(e.subarray(t+EV),"base64url"),new N0({...iXe,key_ops:["verify"],x:n,y:o});if(e.byteLength===SV*2+1)return n=z(e.subarray(t,t+SV),"base64url"),o=z(e.subarray(t+SV),"base64url"),new N0({...aXe,key_ops:["verify"],x:n,y:o});if(e.byteLength===CV*2+1)return n=z(e.subarray(t,t+CV),"base64url"),o=z(e.subarray(t+CV),"base64url"),new N0({...cXe,key_ops:["verify"],x:n,y:o});throw new q(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Sxe(r){return Tf([fs(Uint8Array.from([1])),Tf([lXe(r.crv)],160),Tf([SR(new Y(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function lXe(r){if(r==="P-256")return nXe;if(r==="P-384")return oXe;if(r==="P-521")return sXe;throw new q(`Invalid curve ${r}`)}var N0=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Sxe(this.jwk)),this._raw}toMultihash(){return O0.digest(kf(this))}toCID(){return Dc.createV1(114,this.toMultihash())}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}async verify(e,t,n){return xxe(this.jwk,t,e,n)}};Ga();Le();var B2=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},CR=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var Cxe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new CR("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 vi=Cxe;var AR=32;var AV,uXe=(async()=>{try{return await vi.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function dXe(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await vi.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await vi.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 fXe(r,e,t){return Ht.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function Axe(r,e,t){return AV==null&&(AV=await uXe),AV?dXe(r,e,t):fXe(r,e,t)}se();Ne();Mr();me();function IR(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var TR=class{type="Ed25519";raw;constructor(e){this.raw=IV(e,AR)}toMultihash(){return O0.digest(kf(this))}toCID(){return Dc.createV1(114,this.toMultihash())}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=Axe(this.raw,t,e);return IR(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Txe(r){return r=IV(r,AR),new TR(r)}function IV(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new q(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}kn();var cn;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(cn||(cn={}));var TV;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(TV||(TV={}));(function(r){r.codec=()=>Pt(TV)})(cn||(cn={}));var hu;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),cn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=cn.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(hu||(hu={}));var kV;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),cn.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=cn.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(kV||(kV={}));se();me();var N2={};W(N2,{MAX_RSA_KEY_SIZE:()=>DV,generateRSAKeyPair:()=>Rxe,jwkToJWKKeyPair:()=>Lxe,jwkToPkcs1:()=>yXe,jwkToPkix:()=>LV,jwkToRSAPrivateKey:()=>NV,pkcs1MessageToJwk:()=>PV,pkcs1MessageToRSAPrivateKey:()=>MV,pkcs1ToJwk:()=>gXe,pkcs1ToRSAPrivateKey:()=>Pxe,pkixMessageToJwk:()=>RV,pkixMessageToRSAPublicKey:()=>OV,pkixToJwk:()=>bXe,pkixToRSAPublicKey:()=>BV});se();Va();me();Le();Ne();var U0=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=N2.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Dc.createV1(114,this._multihash)}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return _xe(this.jwk,t,e,n)}},O2=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=N2.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}sign(e,t){return Dxe(this.jwk,e,t)}};var DV=8192,_V=18,pXe=1062,mXe=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function gXe(r){let e=fu(r);return PV(e)}function PV(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 yXe(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 q("JWK was missing components");return Tf([fs(Uint8Array.from([0])),fs(K(r.n,"base64url")),fs(K(r.e,"base64url")),fs(K(r.d,"base64url")),fs(K(r.p,"base64url")),fs(K(r.q,"base64url")),fs(K(r.dp,"base64url")),fs(K(r.dq,"base64url")),fs(K(r.qi,"base64url"))]).subarray()}function bXe(r){let e=fu(r,{offset:0});return RV(e)}function RV(r){let e=fu(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function LV(r){if(r.n==null||r.e==null)throw new q("JWK was missing components");return Tf([mXe,SR(Tf([fs(K(r.n,"base64url")),fs(K(r.e,"base64url"))]))]).subarray()}function Pxe(r){let e=fu(r);return MV(e)}function MV(r){let e=PV(r);return NV(e)}function BV(r,e){if(r.byteLength>=pXe)throw new zt("Key size is too large");let t=fu(r,{offset:0});return OV(t,r,e)}function OV(r,e,t){let n=RV(r);if(t==null){let o=lt(hu.encode({Type:cn.RSA,Data:e}));t=kc(_V,o)}return new U0(n,t)}function NV(r){if(Bxe(r)>DV)throw new q("Key size is too large");let e=Lxe(r),t=lt(hu.encode({Type:cn.RSA,Data:LV(e.publicKey)})),n=kc(_V,t);return new O2(e.privateKey,new U0(e.publicKey,n))}async function Rxe(r){if(r>DV)throw new q("Key size is too large");let e=await Mxe(r),t=lt(hu.encode({Type:cn.RSA,Data:LV(e.publicKey)})),n=kc(_V,t);return new O2(e.privateKey,new U0(e.publicKey,n))}function Lxe(r){if(r==null)throw new q("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function Mxe(r,e){let t=await vi.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 wXe(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Dxe(r,e,t){let n=await vi.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await vi.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function _xe(r,e,t,n){let o=await vi.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await vi.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function wXe(r,e){if(r.privateKey==null||r.publicKey==null)throw new q("Private and public key are required");let t=await Promise.all([vi.get().subtle.exportKey("jwk",r.privateKey),vi.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function Bxe(r){if(r.kty!=="RSA")throw new q("invalid key type");if(r.n==null)throw new q("invalid key modulus");return K(r.n,"base64url").length*8}Mo();var xXe=20;function FV({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new UV(r,e,t,n,o)}var UV=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??xXe,this.maxDigestLength=s}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?Oxe(n,this.code,t?.truncate):n.then(o=>Oxe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function Oxe(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 kc(e,r)}function Nxe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Uxe=FV({name:"sha2-256",code:18,encode:Nxe("SHA-256")}),Vgr=FV({name:"sha2-512",code:19,encode:Nxe("SHA-512")});function Fxe(r,e,t,n){let o=Uxe.digest(t instanceof Uint8Array?t:t.subarray());if(IR(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ie.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new B2(String(s))});try{return n?.signal?.throwIfAborted(),Ie.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new B2(String(s))}}se();Mo();Ne();var kR=class{type="secp256k1";raw;_key;constructor(e){this._key=zxe(e),this.raw=Kxe(this._key)}toMultihash(){return O0.digest(kf(this))}toCID(){return Dc.createV1(114,this.toMultihash())}toString(){return Kn.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return Fxe(this._key,t,e,n)}};function $xe(r){return new kR(r)}function Kxe(r){return Ie.Point.fromBytes(r).toBytes()}function zxe(r){try{return Ie.Point.fromBytes(r),r}catch(e){throw new zt(String(e))}}function U2(r,e){let{Type:t,Data:n}=hu.decode(r),o=n??new Uint8Array;switch(t){case cn.RSA:return BV(o,e);case cn.Ed25519:return Txe(o);case cn.secp256k1:return $xe(o);case cn.ECDSA:return vxe(o);default:throw new An}}function kf(r){return hu.encode({Type:cn[r.type],Data:r.raw})}se();Be();Xt();var F0=!!globalThis.process?.env?.DUMP_SESSION_KEYS,KV=16;function vXe(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function DR(r){if(typeof r!="boolean")throw new Error(`boolean expected, not ${r}`)}function _R(r){if(!Number.isSafeInteger(r)||r<0)throw new Error("positive integer expected, got "+r)}function ln(r,e,t=""){let n=vXe(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function zV(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 Hxe(r,e){ln(r,void 0,"output");let t=e.outputLen;if(r.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function pu(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function mu(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function EXe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}var SXe=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Vxe(r,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(r,e)}function qxe(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}var $V=(r,e)=>{function t(n,...o){if(ln(n,void 0,"key"),!SXe)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let u=o[0];ln(u,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let s=r.tagLength;s&&o[1]!==void 0&&ln(o[1],void 0,"AAD");let i=e(n,...o),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");ln(d,void 0,"output")}},c=!1;return{encrypt(u,d){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ln(u),a(i.encrypt.length,d),i.encrypt(u,d)},decrypt(u,d){if(ln(u),s&&u.length<s)throw new Error('"ciphertext" expected length bigger than tagLength='+s);return a(i.decrypt.length,d),i.decrypt(u,d)}}}return Object.assign(t,r),t};function HV(r,e,t=!0){if(e===void 0)return new Uint8Array(r);if(e.length!==r)throw new Error('"output" expected Uint8Array of length '+r+", got: "+e.length);if(t&&!CXe(e))throw new Error("invalid output, must be aligned");return e}function jxe(r,e,t){DR(t);let n=new Uint8Array(16),o=EXe(n);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(r),t),n}function CXe(r){return r.byteOffset%4===0}function K0(r){return Uint8Array.from(r)}var Wxe=r=>Uint8Array.from(r.split(""),e=>e.charCodeAt(0)),AXe=Wxe("expand 16-byte k"),IXe=Wxe("expand 32-byte k"),TXe=pu(AXe),kXe=pu(IXe);function pe(r,e){return r<<e|r>>>32-e}function VV(r){return r.byteOffset%4===0}var PR=64,DXe=16,Yxe=2**32-1,Gxe=Uint32Array.of();function _Xe(r,e,t,n,o,s,i,a){let c=o.length,l=new Uint8Array(PR),u=pu(l),d=VV(o)&&VV(s),h=d?pu(o):Gxe,p=d?pu(s):Gxe;for(let f=0;f<c;i++){if(r(e,t,n,u,i,a),i>=Yxe)throw new Error("arx: counter overflow");let g=Math.min(PR,c-f);if(d&&g===PR){let y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let m=0,w;m<DXe;m++)w=y+m,p[w]=h[w]^u[m];f+=PR;continue}for(let y=0,m;y<g;y++)m=f+y,s[m]=o[m]^l[y];f+=g}}function qV(r,e){let{allowShortKeys:t,extendNonceFn:n,counterLength:o,counterRight:s,rounds:i}=Vxe({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof r!="function")throw new Error("core must be a function");return _R(o),_R(i),DR(s),DR(t),(a,c,l,u,d=0)=>{ln(a,void 0,"key"),ln(c,void 0,"nonce"),ln(l,void 0,"data");let h=l.length;if(u===void 0&&(u=new Uint8Array(h)),ln(u,void 0,"output"),_R(d),d<0||d>=Yxe)throw new Error("arx: counter overflow");if(u.length<h)throw new Error(`arx: output (${u.length}) is shorter than data (${h})`);let p=[],f=a.length,g,y;if(f===32)p.push(g=K0(a)),y=kXe;else if(f===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),y=TXe,p.push(g);else throw ln(a,32,"arx key"),new Error("invalid key size");VV(c)||p.push(c=K0(c));let m=pu(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(y,m,pu(c.subarray(0,16)),m),c=c.subarray(16)}let w=16-o;if(w!==c.length)throw new Error(`arx: nonce must be ${w} or 16 bytes`);if(w!==12){let x=new Uint8Array(12);x.set(c,s?0:12-c.length),c=x,p.push(c)}let b=pu(c);return _Xe(r,y,m,b,l,u,d,i),mu(...p),u}}function zn(r,e){return r[e++]&255|(r[e++]&255)<<8}var jV=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;constructor(e){e=K0(ln(e,32,"key"));let t=zn(e,0),n=zn(e,2),o=zn(e,4),s=zn(e,6),i=zn(e,8),a=zn(e,10),c=zn(e,12),l=zn(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=zn(e,16+2*u)}process(e,t,n=!1){let o=n?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],u=i[3],d=i[4],h=i[5],p=i[6],f=i[7],g=i[8],y=i[9],m=zn(e,t+0),w=zn(e,t+2),b=zn(e,t+4),x=zn(e,t+6),S=zn(e,t+8),T=zn(e,t+10),A=zn(e,t+12),v=zn(e,t+14),C=s[0]+(m&8191),P=s[1]+((m>>>13|w<<3)&8191),F=s[2]+((w>>>10|b<<6)&8191),R=s[3]+((b>>>7|x<<9)&8191),k=s[4]+((x>>>4|S<<12)&8191),I=s[5]+(S>>>1&8191),E=s[6]+((S>>>14|T<<2)&8191),D=s[7]+((T>>>11|A<<5)&8191),M=s[8]+((A>>>8|v<<8)&8191),B=s[9]+(v>>>5|o),L=0,O=L+C*a+P*(5*y)+F*(5*g)+R*(5*f)+k*(5*p);L=O>>>13,O&=8191,O+=I*(5*h)+E*(5*d)+D*(5*u)+M*(5*l)+B*(5*c),L+=O>>>13,O&=8191;let U=L+C*c+P*a+F*(5*y)+R*(5*g)+k*(5*f);L=U>>>13,U&=8191,U+=I*(5*p)+E*(5*h)+D*(5*d)+M*(5*u)+B*(5*l),L+=U>>>13,U&=8191;let $=L+C*l+P*c+F*a+R*(5*y)+k*(5*g);L=$>>>13,$&=8191,$+=I*(5*f)+E*(5*p)+D*(5*h)+M*(5*d)+B*(5*u),L+=$>>>13,$&=8191;let J=L+C*u+P*l+F*c+R*a+k*(5*y);L=J>>>13,J&=8191,J+=I*(5*g)+E*(5*f)+D*(5*p)+M*(5*h)+B*(5*d),L+=J>>>13,J&=8191;let X=L+C*d+P*u+F*l+R*c+k*a;L=X>>>13,X&=8191,X+=I*(5*y)+E*(5*g)+D*(5*f)+M*(5*p)+B*(5*h),L+=X>>>13,X&=8191;let N=L+C*h+P*d+F*u+R*l+k*c;L=N>>>13,N&=8191,N+=I*a+E*(5*y)+D*(5*g)+M*(5*f)+B*(5*p),L+=N>>>13,N&=8191;let H=L+C*p+P*h+F*d+R*u+k*l;L=H>>>13,H&=8191,H+=I*c+E*a+D*(5*y)+M*(5*g)+B*(5*f),L+=H>>>13,H&=8191;let Z=L+C*f+P*p+F*h+R*d+k*u;L=Z>>>13,Z&=8191,Z+=I*l+E*c+D*a+M*(5*y)+B*(5*g),L+=Z>>>13,Z&=8191;let ae=L+C*g+P*f+F*p+R*h+k*d;L=ae>>>13,ae&=8191,ae+=I*u+E*l+D*c+M*a+B*(5*y),L+=ae>>>13,ae&=8191;let Q=L+C*y+P*g+F*f+R*p+k*h;L=Q>>>13,Q&=8191,Q+=I*d+E*u+D*l+M*c+B*a,L+=Q>>>13,Q&=8191,L=(L<<2)+L|0,L=L+O|0,O=L&8191,L=L>>>13,U+=L,s[0]=O,s[1]=U,s[2]=$,s[3]=J,s[4]=X,s[5]=N,s[6]=H,s[7]=Z,s[8]=ae,s[9]=Q}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,n[0]=e[0]+5,o=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+o,o=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;mu(n)}update(e){zV(this),ln(e),e=K0(e);let{buffer:t,blockLen:n}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);if(i===n){for(;n<=o-s;s+=n)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){mu(this.h,this.r,this.buffer,this.pad)}digestInto(e){zV(this),Hxe(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let i=0;i<8;i++)e[s++]=n[i]>>>0,e[s++]=n[i]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function PXe(r){let e=(n,o)=>r(o).update(n).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var Xxe=PXe(r=>new jV(r));function Qxe(r,e,t,n,o,s=20){let i=r[0],a=r[1],c=r[2],l=r[3],u=e[0],d=e[1],h=e[2],p=e[3],f=e[4],g=e[5],y=e[6],m=e[7],w=o,b=t[0],x=t[1],S=t[2],T=i,A=a,v=c,C=l,P=u,F=d,R=h,k=p,I=f,E=g,D=y,M=m,B=w,L=b,O=x,U=S;for(let J=0;J<s;J+=2)T=T+P|0,B=pe(B^T,16),I=I+B|0,P=pe(P^I,12),T=T+P|0,B=pe(B^T,8),I=I+B|0,P=pe(P^I,7),A=A+F|0,L=pe(L^A,16),E=E+L|0,F=pe(F^E,12),A=A+F|0,L=pe(L^A,8),E=E+L|0,F=pe(F^E,7),v=v+R|0,O=pe(O^v,16),D=D+O|0,R=pe(R^D,12),v=v+R|0,O=pe(O^v,8),D=D+O|0,R=pe(R^D,7),C=C+k|0,U=pe(U^C,16),M=M+U|0,k=pe(k^M,12),C=C+k|0,U=pe(U^C,8),M=M+U|0,k=pe(k^M,7),T=T+F|0,U=pe(U^T,16),D=D+U|0,F=pe(F^D,12),T=T+F|0,U=pe(U^T,8),D=D+U|0,F=pe(F^D,7),A=A+R|0,B=pe(B^A,16),M=M+B|0,R=pe(R^M,12),A=A+R|0,B=pe(B^A,8),M=M+B|0,R=pe(R^M,7),v=v+k|0,L=pe(L^v,16),I=I+L|0,k=pe(k^I,12),v=v+k|0,L=pe(L^v,8),I=I+L|0,k=pe(k^I,7),C=C+P|0,O=pe(O^C,16),E=E+O|0,P=pe(P^E,12),C=C+P|0,O=pe(O^C,8),E=E+O|0,P=pe(P^E,7);let $=0;n[$++]=i+T|0,n[$++]=a+A|0,n[$++]=c+v|0,n[$++]=l+C|0,n[$++]=u+P|0,n[$++]=d+F|0,n[$++]=h+R|0,n[$++]=p+k|0,n[$++]=f+I|0,n[$++]=g+E|0,n[$++]=y+D|0,n[$++]=m+M|0,n[$++]=w+B|0,n[$++]=b+L|0,n[$++]=x+O|0,n[$++]=S+U|0}function RXe(r,e,t,n){let o=r[0],s=r[1],i=r[2],a=r[3],c=e[0],l=e[1],u=e[2],d=e[3],h=e[4],p=e[5],f=e[6],g=e[7],y=t[0],m=t[1],w=t[2],b=t[3];for(let S=0;S<20;S+=2)o=o+c|0,y=pe(y^o,16),h=h+y|0,c=pe(c^h,12),o=o+c|0,y=pe(y^o,8),h=h+y|0,c=pe(c^h,7),s=s+l|0,m=pe(m^s,16),p=p+m|0,l=pe(l^p,12),s=s+l|0,m=pe(m^s,8),p=p+m|0,l=pe(l^p,7),i=i+u|0,w=pe(w^i,16),f=f+w|0,u=pe(u^f,12),i=i+u|0,w=pe(w^i,8),f=f+w|0,u=pe(u^f,7),a=a+d|0,b=pe(b^a,16),g=g+b|0,d=pe(d^g,12),a=a+d|0,b=pe(b^a,8),g=g+b|0,d=pe(d^g,7),o=o+l|0,b=pe(b^o,16),f=f+b|0,l=pe(l^f,12),o=o+l|0,b=pe(b^o,8),f=f+b|0,l=pe(l^f,7),s=s+u|0,y=pe(y^s,16),g=g+y|0,u=pe(u^g,12),s=s+u|0,y=pe(y^s,8),g=g+y|0,u=pe(u^g,7),i=i+d|0,m=pe(m^i,16),h=h+m|0,d=pe(d^h,12),i=i+d|0,m=pe(m^i,8),h=h+m|0,d=pe(d^h,7),a=a+c|0,w=pe(w^a,16),p=p+w|0,c=pe(c^p,12),a=a+c|0,w=pe(w^a,8),p=p+w|0,c=pe(c^p,7);let x=0;n[x++]=o,n[x++]=s,n[x++]=i,n[x++]=a,n[x++]=y,n[x++]=m,n[x++]=w,n[x++]=b}var LXe=qV(Qxe,{counterRight:!1,counterLength:4,allowShortKeys:!1}),MXe=qV(Qxe,{counterRight:!1,counterLength:8,extendNonceFn:RXe,allowShortKeys:!1});var BXe=new Uint8Array(16),Zxe=(r,e)=>{r.update(e);let t=e.length%16;t&&r.update(BXe.subarray(t))},OXe=new Uint8Array(32);function Jxe(r,e,t,n,o){o!==void 0&&ln(o,void 0,"AAD");let s=r(e,t,OXe),i=jxe(n.length,o?o.length:0,!0),a=Xxe.create(s);o&&Zxe(a,o),Zxe(a,n),a.update(i);let c=a.digest();return mu(s,i),c}var eve=r=>(e,t,n)=>({encrypt(s,i){let a=s.length;i=HV(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);r(e,t,c,c,1);let l=Jxe(r,e,t,c,n);return i.set(l,a),mu(l),i},decrypt(s,i){i=HV(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=Jxe(r,e,t,a,n);if(!qxe(c,l))throw new Error("invalid tag");return i.set(s.subarray(0,-16)),r(e,t,i,i,1),mu(l),i}}),GV=$V({blockSize:64,nonceLength:12,tagLength:16},eve(LXe)),Hyr=$V({blockSize:64,nonceLength:24,tagLength:16},eve(MXe));Ga();jN();Xi();function rve(r,e,t){return $h(r),t===void 0&&(t=new Uint8Array(r.outputLen)),gy(r,t,e)}var WV=Uint8Array.of(0),tve=Uint8Array.of();function nve(r,e,t,n=32){$h(r),ci(n,"length");let o=r.outputLen;if(n>255*o)throw new Error("Length must be <= 255*HashLen");let s=Math.ceil(n/o);t===void 0?t=tve:Me(t,void 0,"info");let i=new Uint8Array(s*o),a=gy.create(r,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)WV[0]=u+1,c.update(u===0?tve:l).update(t).update(WV).digestInto(l),i.set(l,o*u),a._cloneInto(c);return a.destroy(),c.destroy(),Wi(l,WV),i.slice(0,n)}Va();var RR={hashSHA256(r){return lt(r.subarray())},getHKDF(r,e){let t=rve(lt,e,r),o=nve(lt,t,void 0,96),s=o.subarray(0,32),i=o.subarray(32,64),a=o.subarray(64,96);return[s,i,a]},generateX25519KeyPair(){let r=xE.utils.randomSecretKey();return{publicKey:xE.getPublicKey(r),privateKey:r}},generateX25519KeyPairFromSeed(r){return{publicKey:xE.getPublicKey(r),privateKey:r}},generateX25519SharedKey(r,e){return xE.getSharedSecret(r.subarray(),e.subarray())},chaCha20Poly1305Encrypt(r,e,t,n){return GV(n,e,t).encrypt(r.subarray())},chaCha20Poly1305Decrypt(r,e,t,n,o){return GV(n,e,t).decrypt(r.subarray(),o)}};var ove=RR;function sve(r){return{generateKeypair:r.generateX25519KeyPair,dh:(e,t)=>r.generateX25519SharedKey(e.privateKey,t).subarray(0,32),encrypt:r.chaCha20Poly1305Encrypt,decrypt:r.chaCha20Poly1305Decrypt,hash:r.hashSHA256,hkdf:r.getHKDF}}Xt();var z0=r=>{let e=ar(2);return e[0]=r>>8,e[1]=r,e};z0.bytes=2;var $0=r=>{if(r.length<2)throw RangeError("Could not decode int16BE");if(r instanceof Uint8Array){let e=0;return e+=r[0]<<8,e+=r[1],e}return r.getUint16(0)};$0.bytes=2;function ive(r){return{xxHandshakeSuccesses:r.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:r.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:r.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:r.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:r.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}Le();function YV(r,e){!e.enabled||!F0||(r?(e(`LOCAL_STATIC_PUBLIC_KEY ${z(r.publicKey,"hex")}`),e(`LOCAL_STATIC_PRIVATE_KEY ${z(r.privateKey,"hex")}`)):e("Missing local static keys."))}function XV(r,e){!e.enabled||!F0||(r?(e(`LOCAL_PUBLIC_EPHEMERAL_KEY ${z(r.publicKey,"hex")}`),e(`LOCAL_PRIVATE_EPHEMERAL_KEY ${z(r.privateKey,"hex")}`)):e("Missing local ephemeral keys."))}function ave(r,e){!e.enabled||!F0||e(r?`REMOTE_STATIC_PUBLIC_KEY ${z(r.subarray(),"hex")}`:"Missing remote static public key.")}function ZV(r,e){!e.enabled||!F0||e(r?`REMOTE_EPHEMERAL_PUBLIC_KEY ${z(r.subarray(),"hex")}`:"Missing remote ephemeral keys.")}function JV(r,e,t){!t.enabled||!F0||(t(`CIPHER_STATE_1 ${r.n.getUint64()} ${r.k&&z(r.k,"hex")}`),t(`CIPHER_STATE_2 ${e.n.getUint64()} ${e.k&&z(e.k,"hex")}`))}ct();Xt();var H0=class r extends Error{code;constructor(e="Invalid crypto exchange"){super(e),this.code=r.code}static code="ERR_INVALID_CRYPTO_EXCHANGE"};Xt();var NXe=0,UXe=4294967295,FXe="Cipherstate has reached maximum n, a new handshake must be performed",LR=class{n;bytes;view;constructor(e=NXe){this.n=e,this.bytes=Oe(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,e,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>UXe)throw new Error(FXe)}};var Yp=Oe(0),V0=class{k;n;crypto;constructor(e,t=void 0,n=0){this.crypto=e,this.k=t,this.n=new LR(n)}hasKey(){return!!this.k}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();let n=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),n}decryptWithAd(e,t,n){if(!this.hasKey())return t;this.n.assertValue();let o=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,n);return this.n.increment(),o}},QV=class{cs;ck;h;crypto;constructor(e,t){this.crypto=e;let n=K(t,"utf-8");this.h=KXe(e,n),this.ck=this.h,this.cs=new V0(e)}mixKey(e){let[t,n]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new V0(this.crypto,n)}mixHash(e){this.h=this.crypto.hash(new Y(this.h,e))}encryptAndHash(e){let t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){let[e,t]=this.crypto.hkdf(this.ck,Yp);return[new V0(this.crypto,e),new V0(this.crypto,t)]}},eq=class{ss;s;e;rs;re;initiator;crypto;constructor(e){let{crypto:t,protocolName:n,prologue:o,initiator:s,s:i,e:a,rs:c,re:l}=e;this.crypto=t,this.ss=new QV(t,n),this.ss.mixHash(o),this.initiator=s,this.s=i,this.e=a,this.rs=c,this.re=l}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");let e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e,t=0){if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e,t=0){if(this.rs)throw new Error("remote static public key is already set");let n=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+n)throw new Error("message is not long enough");let o=e.sublist(t,t+n);return this.rs=this.ss.decryptAndHash(o),n}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}},F2=class extends eq{writeMessageA(e){return new Y(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){let t=this.writeE();this.writeEE();let n=this.writeS();return this.writeES(),new Y(t,n,this.ss.encryptAndHash(e))}writeMessageC(e){let t=this.writeS();return this.writeSE(),new Y(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(t){throw new H0(`handshake stage 0 validation fail: ${t.message}`)}}readMessageB(e){try{this.readE(e),this.readEE();let t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(t){throw new H0(`handshake stage 1 validation fail: ${t.message}`)}}readMessageC(e){try{let t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(t){throw new H0(`handshake stage 2 validation fail: ${t.message}`)}}};function KXe(r,e){if(e.length<=32){let t=Oe(32);return t.set(e),t}else return r.hash(e)}se();ct();Mr();me();kn();Xt();var MR;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.webtransportCerthashes!=null)for(let s of t.webtransportCerthashes)n.uint32(10),n.bytes(s);if(t.streamMuxers!=null)for(let s of t.streamMuxers)n.uint32(18),n.string(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={webtransportCerthashes:[],streamMuxers:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{if(o.limits?.webtransportCerthashes!=null&&s.webtransportCerthashes.length===o.limits.webtransportCerthashes)throw new lr('Decode error - map field "webtransportCerthashes" had too many elements');s.webtransportCerthashes.push(t.bytes());break}case 2:{if(o.limits?.streamMuxers!=null&&s.streamMuxers.length===o.limits.streamMuxers)throw new lr('Decode error - map field "streamMuxers" had too many elements');s.streamMuxers.push(t.string());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(MR||(MR={}));var K2;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.identityKey!=null&&t.identityKey.byteLength>0&&(n.uint32(10),n.bytes(t.identityKey)),t.identitySig!=null&&t.identitySig.byteLength>0&&(n.uint32(18),n.bytes(t.identitySig)),t.extensions!=null&&(n.uint32(34),MR.codec().encode(t.extensions,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={identityKey:Oe(0),identitySig:Oe(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.identityKey=t.bytes();break}case 2:{s.identitySig=t.bytes();break}case 4:{s.extensions=MR.codec().decode(t,t.uint32(),{limits:o.limits?.extensions});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(K2||(K2={}));async function rq(r,e,t){let n=await r.sign(lve(e));return K2.encode({identityKey:kf(r.publicKey),identitySig:n,extensions:t})}async function nq(r,e,t){try{let n=K2.decode(r),o=U2(n.identityKey);if(t?.equals(o)===!1)throw new Error(`Payload identity key ${o} does not match expected remote identity key ${t}`);if(!e)throw new Error("Remote static does not exist");let s=lve(e);if(!await o.verify(s,n.identitySig))throw new Error("Invalid payload signature");return n}catch(n){throw new xT(n.message)}}function lve(r){let e=K("noise-libp2p-static-key:");return r instanceof Uint8Array?Ye([e,r],e.length+r.length):(r.prepend(e),r)}var tq=class extends f0{stream;handshake;metrics;decoder;constructor(e,t,n){super({log:e.log,inactivityTimeout:e.inactivityTimeout,maxReadBufferLength:e.maxReadBufferLength,direction:e.direction}),this.stream=e,this.handshake=t,this.metrics=n,this.decoder=new B_({lengthDecoder:$0,maxBufferSize:16*1024*1024,encodingLength:()=>2});let o=c=>{try{for(let l of this.decoder.decode(c.data))this.onData(this.decrypt(l))}catch(l){this.abort(l)}};this.stream.addEventListener("message",o);let s=c=>{c.error!=null?c.local===!0?this.abort(c.error):this.onRemoteReset():this.onTransportClosed()};this.stream.addEventListener("close",s);let i=()=>{this.safeDispatchEvent("drain")};this.stream.addEventListener("drain",i);let a=()=>{this.onRemoteCloseWrite()};this.stream.addEventListener("remoteCloseWrite",a)}encrypt(e){let t=new Y;for(let n=0;n<e.byteLength;n+=65519){let o=n+65519;o>e.byteLength&&(o=e.byteLength);let s;e instanceof Uint8Array?s=this.handshake.encrypt(e.subarray(n,o)):s=this.handshake.encrypt(e.sublist(n,o)),this.metrics?.encryptedPackets.increment(),t.append(z0(s.byteLength)),t.append(s)}return t}decrypt(e){let t=new Y;for(let n=0;n<e.byteLength;n+=65535){let o=n+65535;if(o>e.byteLength&&(o=e.byteLength),o-KV<n)throw new Error("Invalid chunk");let s;e instanceof Uint8Array?s=e.subarray(n,o):s=e.sublist(n,o);let i=e.subarray(n,o-KV);try{let a=this.handshake.decrypt(s,i);this.metrics?.decryptedPackets.increment(),t.append(a)}catch(a){throw this.metrics?.decryptErrors.increment(),a}}return t}close(e){return this.stream.close(e)}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}sendReset(e){this.stream.abort(e)}sendData(e){return{sentBytes:e.byteLength,canSendMore:this.stream.send(this.encrypt(e))}}};function oq(r,e,t){return new tq(r,e,t)}async function uve(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await rq(s,a.publicKey,l),d=new F2({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:i,s:a});YV(d.s,t),t.trace("Stage 0 - Initiator starting to send first message."),await n.write(d.writeMessageA(Yp),e),t.trace("Stage 0 - Initiator finished sending first message."),XV(d.e,t),t.trace("Stage 1 - Initiator waiting to receive first message from responder...");let h=d.readMessageB(await n.read(e));t.trace("Stage 1 - Initiator received the message."),ZV(d.re,t),ave(d.rs,t),t.trace("Initiator going to check remote's signature...");let p=await nq(h,d.rs,c);t.trace("All good with the signature!"),t.trace("Stage 2 - Initiator sending third handshake message."),await n.write(d.writeMessageC(u),e),t.trace("Stage 2 - Initiator sent message with signed payload.");let[f,g]=d.ss.split();return JV(f,g,t),{payload:p,encrypt:y=>f.encryptWithAd(Yp,y),decrypt:(y,m)=>g.decryptWithAd(Yp,y,m)}}async function dve(r,e){let{log:t,connection:n,crypto:o,privateKey:s,prologue:i,s:a,remoteIdentityKey:c,extensions:l}=r,u=await rq(s,a.publicKey,l),d=new F2({crypto:o,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:i,s:a});YV(d.s,t),t.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(await n.read(e)),t.trace("Stage 0 - Responder received first message."),ZV(d.re,t),t.trace("Stage 1 - Responder sending out first message with signed payload and static key."),await n.write(d.writeMessageB(u),e),t.trace("Stage 1 - Responder sent the second handshake message with signed payload."),XV(d.e,t),t.trace("Stage 2 - Responder waiting for third handshake message...");let h=d.readMessageC(await n.read(e));t.trace("Stage 2 - Responder received the message, finished handshake.");let p=await nq(h,d.rs,c),[f,g]=d.ss.split();return JV(f,g,t),{payload:p,encrypt:y=>g.encryptWithAd(Yp,y),decrypt:(y,m)=>f.decryptWithAd(Yp,y,m)}}var BR=class{protocol="/noise";crypto;prologue;staticKey;extensions;metrics;components;log;constructor(e,t={}){let{staticNoiseKey:n,extensions:o,crypto:s,prologueBytes:i}=t,{metrics:a}=e;this.components=e,this.log=e.logger.forComponent("libp2p:noise");let c=s??ove;this.crypto=sve(c),this.extensions={webtransportCerthashes:[],...o},this.metrics=a?ive(a):void 0,n?this.staticKey=c.generateX25519KeyPairFromSeed(n):this.staticKey=c.generateX25519KeyPair(),this.prologue=i??Oe(0)}[Symbol.toStringTag]="@chainsafe/libp2p-noise";[In]=["@libp2p/connection-encryption","@chainsafe/libp2p-noise"];async secureOutbound(e,t){let n=e.log?.newScope("noise")??this.log,o=wf(e,{lengthEncoder:z0,lengthDecoder:$0,maxDataLength:65535}),s=await this.performHandshakeInitiator(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=U2(s.payload.identityKey);return{connection:oq(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:vl(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}getStreamMuxer(e){if(e==null||e.length===0)return;let t=this.components.upgrader.getStreamMuxers();if(t!=null)for(let n of e){let o=t.get(n);if(o!=null)return o}if(e.length)throw new vT("Early muxer negotiation was requested but the initiator and responder had no common muxers")}async secureInbound(e,t){let n=e.log?.newScope("noise")??this.log,o=wf(e,{lengthEncoder:z0,lengthDecoder:$0,maxDataLength:65535}),s=await this.performHandshakeResponder(o,this.components.privateKey,n,t?.remotePeer?.publicKey,t),i=U2(s.payload.identityKey);return{connection:oq(o.unwrap(),s,this.metrics),remoteExtensions:s.payload.extensions,remotePeer:vl(i),streamMuxer:t?.skipStreamMuxerNegotiation===!0?void 0:this.getStreamMuxer(s.payload.extensions?.streamMuxers)}}async performHandshakeInitiator(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await uve({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}async performHandshakeResponder(e,t,n,o,s){let i,a=s?.skipStreamMuxerNegotiation===!0?[]:[...this.components.upgrader.getStreamMuxers().keys()];try{i=await dve({connection:e,privateKey:t,remoteIdentityKey:o,log:n.newScope("xxhandshake"),crypto:this.crypto,prologue:this.prologue,s:this.staticKey,extensions:{streamMuxers:a,webtransportCerthashes:[],...this.extensions}},s),this.metrics?.xxHandshakeSuccesses.increment()}catch(c){throw this.metrics?.xxHandshakeErrors.increment(),c}return i}};function fve(r={}){return e=>new BR(e,r)}se();ct();se();var Qt;(function(r){r[r.Data=0]="Data",r[r.WindowUpdate=1]="WindowUpdate",r[r.Ping=2]="Ping",r[r.GoAway=3]="GoAway"})(Qt||(Qt={}));var nt;(function(r){r[r.SYN=1]="SYN",r[r.ACK=2]="ACK",r[r.FIN=4]="FIN",r[r.RST=8]="RST"})(nt||(nt={}));var Zbr=Object.values(nt).filter(r=>typeof r!="string"),hve=0,Kr;(function(r){r[r.NormalTermination=0]="NormalTermination",r[r.ProtocolError=1]="ProtocolError",r[r.InternalError=2]="InternalError"})(Kr||(Kr={}));var _c=12;var gu=class extends Error{static name="ProtocolError";reason;constructor(e,t){super(e),this.name="ProtocolError",this.reason=t}};function pve(r){return r?.reason!==null}var Gs=class extends gu{static name="InvalidFrameError";constructor(e="The frame was invalid"){super(e,Kr.ProtocolError),this.name="InvalidFrameError"}},q0=class extends gu{static name="UnRequestedPingError";constructor(e="Un-requested ping error"){super(e,Kr.ProtocolError),this.name="UnRequestedPingError"}},j0=class extends gu{static name="NotMatchingPingError";constructor(e="Not matching ping error"){super(e,Kr.ProtocolError),this.name="NotMatchingPingError"}};var OR=class extends gu{static name="StreamAlreadyExistsError";constructor(e="Stream already exists"){super(e,Kr.ProtocolError),this.name="StreamAlreadyExistsError"}},NR=class extends gu{static name="DecodeInvalidVersionError";constructor(e="Decode invalid version"){super(e,Kr.ProtocolError),this.name="DecodeInvalidVersionError"}},UR=class extends gu{static name="BothClientsError";constructor(e="Both clients"){super(e,Kr.ProtocolError),this.name="BothClientsError"}},G0=class extends gu{static name="ReceiveWindowExceededError";constructor(e="Receive window exceeded"){super(e,Kr.ProtocolError),this.name="ReceiveWindowExceededError"}};var r0r=new Set([Gs.name,q0.name,j0.name,OR.name,NR.name,UR.name,G0.name]),$2=256*1024,FR=16*1024*1024;var H2={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,maxMessageSize:64*1024,maxEarlyStreams:10,streamOptions:{initialStreamWindowSize:$2,maxStreamWindowSize:FR,inactivityTimeout:12e4,maxReadBufferLength:4194304,maxWriteBufferLength:1/0}};function mve(r){if(r.keepAliveInterval!=null&&r.keepAliveInterval<=0)throw new q("keep-alive interval must be positive");if(r.maxInboundStreams!=null&&r.maxInboundStreams<0)throw new q("max inbound streams must be larger or equal 0");if(r.maxOutboundStreams!=null&&r.maxOutboundStreams<0)throw new q("max outbound streams must be larger or equal 0");if(r.maxMessageSize!=null&&r.maxMessageSize<1024)throw new q("MaxMessageSize must be greater than a kilobyte");if(r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize<$2)throw new q("InitialStreamWindowSize must be larger or equal 256 kB");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.initialStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize<r.streamOptions?.initialStreamWindowSize)throw new q("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(r.streamOptions?.maxStreamWindowSize!=null&&r.streamOptions?.maxStreamWindowSize>2**32-1)throw new q("MaxStreamWindowSize must be less than equal MAX_UINT32")}ct();function yve(r){return r.header.type===Qt.Data&&r.data!==null}var gve=2**24;function zXe(r){if(r[0]!==hve)throw new Gs("Invalid frame version");return{type:r[1],flag:(r[2]<<8)+r[3],streamID:r[4]*gve+(r[5]<<16)+(r[6]<<8)+r[7],length:r[8]*gve+(r[9]<<16)+(r[10]<<8)+r[11]}}var KR=class{buffer;constructor(){this.buffer=new Y}*emitFrames(e){for(this.buffer.append(e);;){let t=this.readFrame();if(t===void 0)break;yield t}}readFrame(){let e=_c;if(this.buffer.byteLength<_c)return;let t=zXe(this.buffer.subarray(0,_c));if(t.type===Qt.Data){if(e+=t.length,this.buffer.byteLength<e)return;let n=this.buffer.sublist(_c,e);return this.buffer.consume(e),{header:t,data:n}}return this.buffer.consume(e),{header:t}}};function sq(r){let e=new Uint8Array(_c);return e[1]=r.type,e[2]=r.flag>>>8,e[3]=r.flag,e[4]=r.streamID>>>24,e[5]=r.streamID>>>16,e[6]=r.streamID>>>8,e[7]=r.streamID,e[8]=r.length>>>24,e[9]=r.length>>>16,e[10]=r.length>>>8,e[11]=r.length,e}ct();var jo;(function(r){r[r.Init=0]="Init",r[r.SYNSent=1]="SYNSent",r[r.SYNReceived=2]="SYNReceived",r[r.Established=3]="Established",r[r.Finished=4]="Finished",r[r.Paused=5]="Paused"})(jo||(jo={}));var zR=class extends R_{streamId;state;sendWindowCapacity;recvWindow;recvWindowCapacity;maxStreamWindowSize;epochStart;getRTT;sendFrame;constructor(e){let t=e.initialStreamWindowSize??$2;super({...e,maxMessageSize:t-_c}),this.streamId=e.streamId,this.state=e.state,this.sendWindowCapacity=t,this.recvWindow=t,this.recvWindowCapacity=this.recvWindow,this.maxStreamWindowSize=e.maxStreamWindowSize??FR,this.epochStart=Date.now(),this.getRTT=e.getRTT,this.sendFrame=e.sendFrame;let n=()=>{this.state=jo.Finished};this.addEventListener("close",n)}sendData(e){let t=e.byteLength,n=0,o=!0;for(this.log?.trace("send window capacity is %d bytes",this.sendWindowCapacity);e.byteLength>0;){if(this.sendWindowCapacity===0){o=!1,this.log?.trace("sent %d/%d bytes, exhausted send window, waiting for window update",n,t);break}let s=Math.min(this.sendWindowCapacity,e.byteLength),i=this.getSendFlags(),a=e.sublist(0,s);e.consume(s);let c=this.sendFrame({type:Qt.Data,flag:i,streamID:this.streamId,length:s},a);if(this.sendWindowCapacity-=s,n+=s,!c){o=c,this.log.trace("sent %d/%d bytes, wait for muxer to have more send capacity",n,t);break}}return{sentBytes:n,canSendMore:o}}sendReset(){this.sendFrame({type:Qt.WindowUpdate,flag:nt.RST,streamID:this.streamId,length:0})}async sendCloseWrite(){let e=this.getSendFlags()|nt.FIN;this.sendFrame({type:Qt.WindowUpdate,flag:e,streamID:this.streamId,length:0})}async sendCloseRead(e){e?.signal?.throwIfAborted()}sendPause(){this.state=jo.Paused}sendResume(){this.state=jo.Established,this.sendWindowUpdate()}handleWindowUpdate(e){this.processFlags(e.header.flag),this.sendWindowCapacity+=e.header.length,this.maxMessageSize=this.sendWindowCapacity-_c,this.maxMessageSize<0&&(this.maxMessageSize=0),this.maxMessageSize!==0&&this.writeBuffer.byteLength>0&&(this.log?.trace("window update of %d bytes allows more data to be sent, have %d bytes queued, sending data %s",e.header.length,this.writeBuffer.byteLength,this.sendingData),this.safeDispatchEvent("drain"))}handleData(e){if(!yve(e))throw new Gs("Frame was not data frame");if(this.processFlags(e.header.flag),this.recvWindowCapacity<e.header.length)throw new G0("Receive window exceeded");this.recvWindowCapacity-=e.header.length,this.onData(e.data),this.sendWindowUpdate()}processFlags(e){(e&nt.ACK)===nt.ACK&&this.state===jo.SYNSent&&(this.state=jo.Established),(e&nt.FIN)===nt.FIN&&this.onRemoteCloseWrite(),(e&nt.RST)===nt.RST&&this.onRemoteReset()}getSendFlags(){switch(this.state){case jo.Init:return this.state=jo.SYNSent,nt.SYN;case jo.SYNReceived:return this.state=jo.Established,nt.ACK;default:return 0}}sendWindowUpdate(){if(this.state===jo.Paused){this.epochStart=Date.now();return}let e=this.getSendFlags(),t=Date.now(),n=this.getRTT();if(e===0&&n>-1&&t-this.epochStart<=n*4&&(this.recvWindow=Math.min(this.recvWindow*2,this.maxStreamWindowSize)),this.recvWindowCapacity>=this.recvWindow&&e===0)return;let o=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:Qt.WindowUpdate,flag:e,streamID:this.streamId,length:o})}};function bve(r){return{type:Qt[r.type],flags:[(r.flag&nt.SYN)===nt.SYN?"SYN":void 0,(r.flag&nt.ACK)===nt.ACK?"ACK":void 0,(r.flag&nt.FIN)===nt.FIN?"FIN":void 0,(r.flag&nt.RST)===nt.RST?"RST":void 0].filter(Boolean),streamID:r.streamID,length:r.length}}var wve="/yamux/1.0.0",$R=class{protocol=wve;_init;constructor(e={}){this._init=e}[Symbol.toStringTag]="@chainsafe/libp2p-yamux";[In]=["@libp2p/stream-multiplexing"];createStreamMuxer(e){return new iq(e,{...this._init})}},iq=class extends P_{nextStreamID;nextPingID;activePing;rtt;client;localGoAway;remoteGoAway;numInboundStreams;numOutboundStreams;decoder;keepAlive;enableKeepAlive;keepAliveInterval;maxInboundStreams;maxOutboundStreams;constructor(e,t={}){super(e,{...t,protocol:wve,name:"yamux"}),this.client=e.direction==="outbound",mve(t),this.enableKeepAlive=t.enableKeepAlive??H2.enableKeepAlive,this.keepAliveInterval=t.keepAliveInterval??H2.keepAliveInterval,this.maxInboundStreams=t.maxInboundStreams??H2.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??H2.maxOutboundStreams,this.decoder=new KR,this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,this.log.trace("muxer created"),this.enableKeepAlive&&(this.log.trace("muxer keepalive enabled interval=%s",this.keepAliveInterval),this.keepAlive=Ebe(async n=>{try{await this.ping(n)}catch(o){this.log.error("ping error: %s",o)}},this.keepAliveInterval,{runImmediately:!0}),this.keepAlive.start())}onData(e){for(let t of this.decoder.emitFrames(e))this.handleFrame(t)}onCreateStream(){if(this.remoteGoAway!==void 0)throw new fl("Muxer closed remotely");if(this.localGoAway!==void 0)throw new fl("Muxer closed locally");let e=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.maxOutboundStreams)throw new Vg("max outbound streams exceeded");this.log.trace("new outgoing stream id=%s",e);let t=this._newStream(e,jo.Init,"outbound");return this.numOutboundStreams++,queueMicrotask(()=>{t.sendWindowUpdate()}),t}async ping(e){if(this.remoteGoAway!==void 0)throw new fl("Muxer closed remotely");if(this.localGoAway!==void 0)throw new fl("Muxer closed locally");if(this.activePing!=null)return qt(this.activePing.promise,e?.signal);this.activePing=Object.assign(Promise.withResolvers(),{id:this.nextPingID++,start:Date.now()}),this.sendPing(this.activePing.id);try{this.rtt=await qt(this.activePing.promise,e?.signal)}finally{this.activePing=void 0}return this.rtt}getRTT(){return this.rtt}async close(e={}){if(this.status==="open")try{let t=e?.reason??Kr.NormalTermination;this.log.trace("muxer close reason=%s",Kr[t]),await super.close(e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}abort(e){if(this.status==="open")try{super.abort(e);let t=Kr.InternalError;pve(e)&&(t=e.reason),this.log.error("muxer abort reason=%s error=%s",t,e),this.sendGoAway(t)}finally{this.keepAlive?.stop()}}onTransportClosed(){try{super.onTransportClosed()}finally{this.keepAlive?.stop()}}_newStream(e,t,n){if(this.streams.find(s=>s.streamId===e)!=null)throw new q("Stream already exists with that id");let o=new zR({...this.streamOptions,id:`${e}`,streamId:e,state:t,direction:n,sendFrame:this.sendFrame.bind(this),log:this.log.newScope(`${n}:${e}`),getRTT:this.getRTT.bind(this)});return o.addEventListener("close",()=>{this.closeStream(e)},{once:!0}),o}closeStream(e){this.client===(e%2===0)?this.numInboundStreams--:this.numOutboundStreams--}handleFrame(e){let{streamID:t,type:n,length:o}=e.header;if(this.log.trace("received frame %o",bve(e.header)),t===0)switch(n){case Qt.Ping:{this.handlePing(e.header);return}case Qt.GoAway:{this.handleGoAway(o);return}default:throw new Gs("Invalid frame type")}else switch(e.header.type){case Qt.Data:case Qt.WindowUpdate:{this.handleStreamMessage(e);return}default:throw new Gs("Invalid frame type")}}handlePing(e){if(e.flag===nt.SYN)this.log.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,nt.ACK);else if(e.flag===nt.ACK)this.log.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length);else throw new Gs("Invalid frame flag")}handlePingResponse(e){if(this.activePing===void 0)throw new q0("ping not requested");if(this.activePing.id!==e)throw new j0("ping doesn't match our id");this.activePing.resolve(Date.now()-this.activePing.start)}handleGoAway(e){this.log.trace("received GoAway reason=%s",Kr[e]??"unknown"),this.remoteGoAway=e,e===Kr.NormalTermination?this.onTransportClosed():this.abort(new Error("Remote sent GoAway"))}handleStreamMessage(e){let{streamID:t,flag:n,type:o}=e.header;(n&nt.SYN)===nt.SYN&&this.incomingStream(t);let s=this.streams.find(i=>i.streamId===t);if(s===void 0){this.log.trace("frame for missing stream id=%s",t);return}switch(o){case Qt.WindowUpdate:{s.handleWindowUpdate(e);return}case Qt.Data:{s.handleData(e);return}default:throw new Error("unreachable")}}incomingStream(e){if(this.client!==(e%2===0))throw new q("Both endpoints are clients");if(this.streams.find(n=>n.streamId===e))return;if(this.log.trace("new incoming stream id=%s",e),this.localGoAway!==void 0){this.sendFrame({type:Qt.WindowUpdate,flag:nt.RST,streamID:e,length:0});return}if(this.numInboundStreams>=this.maxInboundStreams){this.log("maxIncomingStreams exceeded, forcing stream reset"),this.sendFrame({type:Qt.WindowUpdate,flag:nt.RST,streamID:e,length:0});return}let t=this._newStream(e,jo.SYNReceived,"inbound");this.numInboundStreams++,this.onRemoteStream(t)}sendFrame(e,t){let n;if(e.type===Qt.Data){if(t==null)throw new Gs("Invalid frame");n=new Y(sq(e),t)}else n=sq(e);return this.log.trace("sending frame %o",bve(e)),this.send(n)}sendPing(e,t=nt.SYN){t===nt.SYN?this.log.trace("sending ping request pingId=%s",e):this.log.trace("sending ping response pingId=%s",e),this.sendFrame({type:Qt.Ping,flag:t,streamID:0,length:e})}sendGoAway(e=Kr.NormalTermination){this.log("sending GoAway reason=%s",Kr[e]),this.localGoAway=e,this.sendFrame({type:Qt.GoAway,flag:0,streamID:0,length:e})}};function xve(r={}){return()=>new $R(r)}se();me();Le();var vve="0.1.0";var Eve="id/push",Sve="1.0.0",Cve="1.0.0";kn();var Df;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.protocolVersion!=null&&(n.uint32(42),n.string(t.protocolVersion)),t.agentVersion!=null&&(n.uint32(50),n.string(t.agentVersion)),t.publicKey!=null&&(n.uint32(10),n.bytes(t.publicKey)),t.listenAddrs!=null)for(let s of t.listenAddrs)n.uint32(18),n.bytes(s);if(t.observedAddr!=null&&(n.uint32(34),n.bytes(t.observedAddr)),t.protocols!=null)for(let s of t.protocols)n.uint32(26),n.string(s);t.signedPeerRecord!=null&&(n.uint32(66),n.bytes(t.signedPeerRecord)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={listenAddrs:[],protocols:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 5:{s.protocolVersion=t.string();break}case 6:{s.agentVersion=t.string();break}case 1:{s.publicKey=t.bytes();break}case 2:{if(o.limits?.listenAddrs!=null&&s.listenAddrs.length===o.limits.listenAddrs)throw new lr('Decode error - map field "listenAddrs" had too many elements');s.listenAddrs.push(t.bytes());break}case 4:{s.observedAddr=t.bytes();break}case 3:{if(o.limits?.protocols!=null&&s.protocols.length===o.limits.protocols)throw new lr('Decode error - map field "protocols" had too many elements');s.protocols.push(t.string());break}case 8:{s.signedPeerRecord=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Df||(Df={}));se();var U0r=new Uint8Array(0);function Ave(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 _f(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 $Xe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var HXe=$Xe,VXe=HXe,Ive=VXe;var aq=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")}},cq=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 Tve(this,e)}},lq=class{decoders;constructor(e){this.decoders=e}or(e){return Tve(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 Tve(r,e){return new lq({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var uq=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new aq(e,t,n),this.decoder=new cq(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function kve({name:r,prefix:e,encode:t,decode:n}){return new uq(r,e,t,n)}function W0({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=Ive(t,r);return kve({prefix:e,name:r,encode:n,decode:s=>_f(o(s))})}function qXe(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function jXe(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function GXe(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Pc({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=GXe(n);return kve({prefix:e,name:r,encode(s){return jXe(s,n,t)},decode(s){return qXe(s,o,t,r)}})}var $n=W0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),q0r=W0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var V2=Pc({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),W0r=Pc({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Y0r=Pc({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),X0r=Pc({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Z0r=Pc({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),J0r=Pc({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Q0r=Pc({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),ewr=Pc({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),twr=Pc({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var HR=W0({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),owr=W0({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var WXe=Pve,Dve=128,YXe=127,XXe=~YXe,ZXe=Math.pow(2,31);function Pve(r,e,t){e=e||[],t=t||0;for(var n=t;r>=ZXe;)e[t++]=r&255|Dve,r/=128;for(;r&XXe;)e[t++]=r&255|Dve,r>>>=7;return e[t]=r|0,Pve.bytes=t-n+1,e}var JXe=dq,QXe=128,_ve=127;function dq(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw dq.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&_ve)<<o:(i&_ve)*Math.pow(2,o),o+=7}while(i>=QXe);return dq.bytes=s-n,t}var eZe=Math.pow(2,7),tZe=Math.pow(2,14),rZe=Math.pow(2,21),nZe=Math.pow(2,28),oZe=Math.pow(2,35),sZe=Math.pow(2,42),iZe=Math.pow(2,49),aZe=Math.pow(2,56),cZe=Math.pow(2,63),lZe=function(r){return r<eZe?1:r<tZe?2:r<rZe?3:r<nZe?4:r<oZe?5:r<sZe?6:r<iZe?7:r<aZe?8:r<cZe?9:10},uZe={encode:WXe,decode:JXe,encodingLength:lZe},dZe=uZe,q2=dZe;function j2(r,e=0){return[q2.decode(r,e),q2.decode.bytes]}function Y0(r,e,t=0){return q2.encode(r,e,t),e}function X0(r){return q2.encodingLength(r)}function Rc(r,e){let t=e.byteLength,n=X0(r),o=n+X0(t),s=new Uint8Array(o+t);return Y0(r,s,0),Y0(t,s,n),s.set(e,o),new Z0(r,t,e,s)}function Lve(r){let e=_f(r),[t,n]=j2(e),[o,s]=j2(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Z0(t,o,i,e)}function Mve(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Ave(r.bytes,t.bytes)}}var Z0=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function Bve(r,e){let{bytes:t,version:n}=r;return n===0?hZe(t,hq(r),e??$n.encoder):pZe(t,hq(r),e??V2.encoder)}var Ove=new WeakMap;function hq(r){let e=Ove.get(r);if(e==null){let t=new Map;return Ove.set(r,t),t}return e}var Lc=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==G2)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==mZe)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=Rc(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&&Mve(e.multihash,n.multihash)}toString(e){return Bve(this,e)}toJSON(){return{"/":Bve(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??Nve(n,o,s.bytes))}else if(t[gZe]===!0){let{version:n,multihash:o,code:s}=t,i=Lve(o);return r.create(n,s,i)}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!==G2)throw new Error(`Version 0 CID must use dag-pb (code: ${G2}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=Nve(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,G2,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,o=_f(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Z0(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=j2(e.subarray(t));return t+=h,d},o=n(),s=G2;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=fZe(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return hq(s).set(n,e),s}};function fZe(r,e){switch(r[0]){case"Q":{let t=e??$n;return[$n.prefix,t.decode(`${$n.prefix}${r}`)]}case $n.prefix:{let t=e??$n;return[$n.prefix,t.decode(r)]}case V2.prefix:{let t=e??V2;return[V2.prefix,t.decode(r)]}case HR.prefix:{let t=e??HR;return[HR.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 hZe(r,e,t){let{prefix:n}=t;if(n!==$n.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function pZe(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var G2=112,mZe=18;function Nve(r,e,t){let n=X0(r),o=n+X0(e),s=new Uint8Array(o+t.byteLength);return Y0(r,s,0),Y0(e,s,n),s.set(t,o),s}var gZe=Symbol.for("@ipld/js-cid/CID");var Uve=0,yZe="identity",Fve=_f;function bZe(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 Rc(Uve,Fve(r))}var J0={code:Uve,name:yZe,encode:Fve,digest:bZe};Ne();se();ct();me();Le();ct();var wZe=parseInt("11111",2),pq=parseInt("10000000",2),xZe=parseInt("01111111",2),Kve={0:W2,1:W2,2:vZe,3:CZe,4:AZe,5:SZe,6:EZe,16:W2,22:W2,48:W2};function yu(r,e={offset:0}){let t=r[e.offset]&wZe;if(e.offset++,Kve[t]!=null)return Kve[t](r,e);throw new Error("No decoder for tag "+t)}function Y2(r,e){let t=0;if((r[e.offset]&pq)===pq){let n=r[e.offset]&xZe,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function W2(r,e){Y2(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=yu(r,e);if(n===null)break;t.push(n)}return t}function vZe(r,e){let t=Y2(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function EZe(r,e){let t=Y2(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function SZe(r,e){return e.offset++,null}function CZe(r,e){let t=Y2(r,e),n=r[e.offset];e.offset++;let o=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 o}function AZe(r,e){let t=Y2(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function IZe(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new Y;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function mq(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=IZe(r.byteLength);return new Y(Uint8Array.from([e.byteLength|pq]),e)}function hs(r){let e=new Y,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new Y(Uint8Array.from([2]),mq(e),e)}function VR(r){let e=Uint8Array.from([0]),t=new Y(e,r);return new Y(Uint8Array.from([3]),mq(t),t)}function Pf(r,e=48){let t=new Y;for(let n of r)t.append(n);return new Y(Uint8Array.from([e]),mq(t),t)}async function zve(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var TZe=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),kZe=Uint8Array.from([6,5,43,129,4,0,34]),DZe=Uint8Array.from([6,5,43,129,4,0,35]),_Ze={ext:!0,kty:"EC",crv:"P-256"},PZe={ext:!0,kty:"EC",crv:"P-384"},RZe={ext:!0,kty:"EC",crv:"P-521"},gq=32,yq=48,bq=66;function $ve(r){let e=yu(r);return Hve(e)}function Hve(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===gq*2+1)return n=z(e.subarray(t,t+gq),"base64url"),o=z(e.subarray(t+gq),"base64url"),new Q0({..._Ze,key_ops:["verify"],x:n,y:o});if(e.byteLength===yq*2+1)return n=z(e.subarray(t,t+yq),"base64url"),o=z(e.subarray(t+yq),"base64url"),new Q0({...PZe,key_ops:["verify"],x:n,y:o});if(e.byteLength===bq*2+1)return n=z(e.subarray(t,t+bq),"base64url"),o=z(e.subarray(t+bq),"base64url"),new Q0({...RZe,key_ops:["verify"],x:n,y:o});throw new q(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function Vve(r){return Pf([hs(Uint8Array.from([1])),Pf([LZe(r.crv)],160),Pf([VR(new Y(Uint8Array.from([4]),K(r.x??"","base64url"),K(r.y??"","base64url")))],161)]).subarray()}function LZe(r){if(r==="P-256")return TZe;if(r==="P-384")return kZe;if(r==="P-521")return DZe;throw new q(`Invalid curve ${r}`)}var Q0=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=Vve(this.jwk)),this._raw}toMultihash(){return J0.digest(Rf(this))}toCID(){return Lc.createV1(114,this.toMultihash())}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}async verify(e,t,n){return zve(this.jwk,t,e,n)}};Ga();Le();var X2=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},qR=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var qve={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new qR("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 Ei=qve;var jR=32;var wq,MZe=(async()=>{try{return await Ei.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function BZe(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await Ei.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await Ei.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 OZe(r,e,t){return Ht.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function jve(r,e,t){return wq==null&&(wq=await MZe),wq?BZe(r,e,t):OZe(r,e,t)}se();Ne();Mr();me();function GR(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var WR=class{type="Ed25519";raw;constructor(e){this.raw=xq(e,jR)}toMultihash(){return J0.digest(Rf(this))}toCID(){return Lc.createV1(114,this.toMultihash())}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=jve(this.raw,t,e);return GR(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function Wve(r){return r=xq(r,jR),new WR(r)}function xq(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new q(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}kn();var un;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(un||(un={}));var vq;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(vq||(vq={}));(function(r){r.codec=()=>Pt(vq)})(un||(un={}));var bu;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),un.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=un.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(bu||(bu={}));var Eq;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),un.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=un.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Eq||(Eq={}));se();me();var J2={};W(J2,{MAX_RSA_KEY_SIZE:()=>Sq,generateRSAKeyPair:()=>Qve,jwkToJWKKeyPair:()=>eEe,jwkToPkcs1:()=>zZe,jwkToPkix:()=>Tq,jwkToRSAPrivateKey:()=>Pq,pkcs1MessageToJwk:()=>Aq,pkcs1MessageToRSAPrivateKey:()=>kq,pkcs1ToJwk:()=>KZe,pkcs1ToRSAPrivateKey:()=>Jve,pkixMessageToJwk:()=>Iq,pkixMessageToRSAPublicKey:()=>_q,pkixToJwk:()=>$Ze,pkixToRSAPublicKey:()=>Dq});se();Va();me();Le();Ne();var ew=class{type="RSA";jwk;_raw;_multihash;constructor(e,t){this.jwk=e,this._multihash=t}get raw(){return this._raw==null&&(this._raw=J2.jwkToPkix(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return Lc.createV1(114,this._multihash)}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return Zve(this.jwk,t,e,n)}},Z2=class{type="RSA";jwk;_raw;publicKey;constructor(e,t){this.jwk=e,this.publicKey=t}get raw(){return this._raw==null&&(this._raw=J2.jwkToPkcs1(this.jwk)),this._raw}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}sign(e,t){return Xve(this.jwk,e,t)}};var Sq=8192,Cq=18,UZe=1062,FZe=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function KZe(r){let e=yu(r);return Aq(e)}function Aq(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 zZe(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 q("JWK was missing components");return Pf([hs(Uint8Array.from([0])),hs(K(r.n,"base64url")),hs(K(r.e,"base64url")),hs(K(r.d,"base64url")),hs(K(r.p,"base64url")),hs(K(r.q,"base64url")),hs(K(r.dp,"base64url")),hs(K(r.dq,"base64url")),hs(K(r.qi,"base64url"))]).subarray()}function $Ze(r){let e=yu(r,{offset:0});return Iq(e)}function Iq(r){let e=yu(r[1],{offset:0});return{kty:"RSA",n:z(e[0],"base64url"),e:z(e[1],"base64url")}}function Tq(r){if(r.n==null||r.e==null)throw new q("JWK was missing components");return Pf([FZe,VR(Pf([hs(K(r.n,"base64url")),hs(K(r.e,"base64url"))]))]).subarray()}function Jve(r){let e=yu(r);return kq(e)}function kq(r){let e=Aq(r);return Pq(e)}function Dq(r,e){if(r.byteLength>=UZe)throw new zt("Key size is too large");let t=yu(r,{offset:0});return _q(t,r,e)}function _q(r,e,t){let n=Iq(r);if(t==null){let o=lt(bu.encode({Type:un.RSA,Data:e}));t=Rc(Cq,o)}return new ew(n,t)}function Pq(r){if(rEe(r)>Sq)throw new q("Key size is too large");let e=eEe(r),t=lt(bu.encode({Type:un.RSA,Data:Tq(e.publicKey)})),n=Rc(Cq,t);return new Z2(e.privateKey,new ew(e.publicKey,n))}async function Qve(r){if(r>Sq)throw new q("Key size is too large");let e=await tEe(r),t=lt(bu.encode({Type:un.RSA,Data:Tq(e.publicKey)})),n=Rc(Cq,t);return new Z2(e.privateKey,new ew(e.publicKey,n))}function eEe(r){if(r==null)throw new q("Missing key parameter");return{privateKey:r,publicKey:{kty:r.kty,n:r.n,e:r.e}}}async function tEe(r,e){let t=await Ei.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 HZe(t,e);return{privateKey:n[0],publicKey:n[1]}}async function Xve(r,e,t){let n=await Ei.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]);t?.signal?.throwIfAborted();let o=await Ei.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},n,e instanceof Uint8Array?e:e.subarray());return t?.signal?.throwIfAborted(),new Uint8Array(o,0,o.byteLength)}async function Zve(r,e,t,n){let o=await Ei.get().subtle.importKey("jwk",r,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);n?.signal?.throwIfAborted();let s=await Ei.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},o,e,t instanceof Uint8Array?t:t.subarray());return n?.signal?.throwIfAborted(),s}async function HZe(r,e){if(r.privateKey==null||r.publicKey==null)throw new q("Private and public key are required");let t=await Promise.all([Ei.get().subtle.exportKey("jwk",r.privateKey),Ei.get().subtle.exportKey("jwk",r.publicKey)]);return e?.signal?.throwIfAborted(),t}function rEe(r){if(r.kty!=="RSA")throw new q("invalid key type");if(r.n==null)throw new q("invalid key modulus");return K(r.n,"base64url").length*8}Mo();var VZe=20;function Lq({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Rq(r,e,t,n,o)}var Rq=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??VZe,this.maxDigestLength=s}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?nEe(n,this.code,t?.truncate):n.then(o=>nEe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function nEe(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 Rc(e,r)}function oEe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var sEe=Lq({name:"sha2-256",code:18,encode:oEe("SHA-256")}),Pxr=Lq({name:"sha2-512",code:19,encode:oEe("SHA-512")});function iEe(r,e,t,n){let o=sEe.digest(t instanceof Uint8Array?t:t.subarray());if(GR(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),Ie.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new X2(String(s))});try{return n?.signal?.throwIfAborted(),Ie.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new X2(String(s))}}se();Mo();Ne();var YR=class{type="secp256k1";raw;_key;constructor(e){this._key=cEe(e),this.raw=aEe(this._key)}toMultihash(){return J0.digest(Rf(this))}toCID(){return Lc.createV1(114,this.toMultihash())}toString(){return $n.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:ee(this.raw,e.raw)}verify(e,t,n){return iEe(this._key,t,e,n)}};function lEe(r){return new YR(r)}function aEe(r){return Ie.Point.fromBytes(r).toBytes()}function cEe(r){try{return Ie.Point.fromBytes(r),r}catch(e){throw new zt(String(e))}}function XR(r,e){let{Type:t,Data:n}=bu.decode(r),o=n??new Uint8Array;switch(t){case un.RSA:return Dq(o,e);case un.Ed25519:return Wve(o);case un.secp256k1:return lEe(o);case un.ECDSA:return $ve(o);default:throw new An}}function Rf(r){return bu.encode({Type:un[r.type],Data:r.raw})}se();Be();me();var ps={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function uEe(r){if(r!=null&&r.length>0)try{return Pe(r)}catch{}}async function ZR(r,e,t,n,o){if(t("received identify from %p",n.remotePeer),o==null)throw new Ds("message was null or undefined");let s={};if(o.listenAddrs.length>0&&(s.addresses=o.listenAddrs.map(c=>({isCertified:!1,multiaddr:Pe(c)}))),o.protocols.length>0&&(s.protocols=o.protocols),o.publicKey!=null){let c=XR(o.publicKey);if(!vl(c).equals(n.remotePeer))throw new Ds("public key did not match remote PeerId");s.publicKey=c}let i;if(o.signedPeerRecord!=null){t.trace("received signedPeerRecord from %p",n.remotePeer);let c=o.signedPeerRecord,l=await Ho.openAndCertify(c,Vo.DOMAIN),u=Vo.createFromProtobuf(l.payload),d=Wa(l.publicKey.toCID());if(!u.peerId.equals(d))throw new Ds("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(u.peerId))throw new Ds("signing key does not match remote PeerId");let h;try{h=await r.get(u.peerId)}catch(p){if(p.name!=="NotFoundError")throw p}if(h!=null&&(s.metadata=h.metadata,h.peerRecordEnvelope!=null)){let p=Ho.createFromProtobuf(h.peerRecordEnvelope),f=Vo.createFromProtobuf(p.payload);f.seqNumber>=u.seqNumber&&(t("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,u.seqNumber),u=f,c=h.peerRecordEnvelope)}s.peerRecordEnvelope=c,s.addresses=u.multiaddrs.map(p=>({isCertified:!0,multiaddr:p})),i={seq:u.seqNumber,addresses:u.multiaddrs}}else t("%p did not send a signed peer record",n.remotePeer);if(t.trace("patching %p with",n.remotePeer,s),await r.patch(n.remotePeer,s),o.agentVersion!=null||o.protocolVersion!=null){let c={};o.agentVersion!=null&&(c.AgentVersion=K(o.agentVersion)),o.protocolVersion!=null&&(c.ProtocolVersion=K(o.protocolVersion)),t.trace("merging %p metadata",n.remotePeer,c),await r.merge(n.remotePeer,{metadata:c})}let a={peerId:n.remotePeer,protocolVersion:o.protocolVersion,agentVersion:o.agentVersion,publicKey:o.publicKey,listenAddrs:o.listenAddrs.map(c=>Pe(c)),observedAddr:o.observedAddr==null?void 0:Pe(o.observedAddr),protocols:o.protocols,signedPeerRecord:i,connection:n};return e.safeDispatchEvent("peer:identify",{detail:a}),a}var tw=class{host;components;protocol;started;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;maxObservedAddresses;runOnLimitedConnection;log;constructor(e,t){this.protocol=t.protocol,this.started=!1,this.components=e,this.log=t.log,this.timeout=t.timeout??ps.timeout,this.maxInboundStreams=t.maxInboundStreams??ps.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??ps.maxOutboundStreams,this.maxMessageSize=t.maxMessageSize??ps.maxMessageSize,this.maxObservedAddresses=t.maxObservedAddresses??ps.maxObservedAddresses,this.runOnLimitedConnection=t.runOnLimitedConnection??ps.runOnLimitedConnection,this.host={protocolVersion:`${t.protocolPrefix??ps.protocolPrefix}/${vve}`,agentVersion:e.nodeInfo.userAgent},this.handleProtocol=this.handleProtocol.bind(this)}isStarted(){return this.started}async start(){this.started||(await this.components.peerStore.merge(this.components.peerId,{metadata:{AgentVersion:K(this.host.agentVersion),ProtocolVersion:K(this.host.protocolVersion)}}),await this.components.registrar.handle(this.protocol,this.handleProtocol,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}};var JR=class extends tw{connectionManager;concurrency;_push;constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??ps.protocolPrefix}/${Eve}/${Cve}`,log:e.logger.forComponent("libp2p:identify-push")}),this.connectionManager=e.connectionManager,this.concurrency=t.concurrency??ps.concurrency,this._push=ou(this.sendPushMessage.bind(this),t.debounce??1e3),(t.runOnSelfUpdate??ps.runOnSelfUpdate)&&e.events.addEventListener("self:peer:update",n=>{this.push().catch(o=>{this.log.error("error pushing updates to peers - %e",o)})})}[In]=["@libp2p/identify-push"];async push(){this._push()}async sendPushMessage(){if(this.isStarted())try{let e=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),t=new Vo({peerId:this.components.peerId,multiaddrs:e}),n=await Ho.seal(t,this.components.privateKey),o=this.components.registrar.getProtocols(),s=await this.components.peerStore.get(this.components.peerId),i=z(s.metadata.get("AgentVersion")??K(this.host.agentVersion)),a=z(s.metadata.get("ProtocolVersion")??K(this.host.protocolVersion)),c=this;async function*l(){for(let u of c.connectionManager.getConnections())(await c.components.peerStore.get(u.remotePeer)).protocols.includes(c.protocol)&&(yield async()=>{let h,p=AbortSignal.timeout(c.timeout);try{h=await u.newStream(c.protocol,{signal:p,runOnLimitedConnection:c.runOnLimitedConnection}),await su(h,{maxDataLength:c.maxMessageSize}).pb(Df).write({listenAddrs:e.map(g=>g.bytes),signedPeerRecord:n.marshal(),protocols:o,agentVersion:i,protocolVersion:a},{signal:p}),await h.close({signal:p})}catch(f){h?.log.newScope("identify-push")?.error("could not push identify update to peer",f),h?.abort(f)}})}await g2(T2(l(),{concurrency:this.concurrency}))}catch(e){this.log.error("error pushing updates to peers - %e",e)}}async handleProtocol(e,t){let n=e.log.newScope("identify-push");if(this.components.peerId.equals(t.remotePeer))throw new Error("received push from ourselves?");let o={signal:AbortSignal.timeout(this.timeout)},i=await su(e,{maxDataLength:this.maxMessageSize}).pb(Df).read(o);await e.close(o),await ZR(this.components.peerStore,this.components.events,n,t,i),n.trace("handled push from %p",t.remotePeer)}};se();Be();var QR=class extends tw{constructor(e,t={}){super(e,{...t,protocol:`/${t.protocolPrefix??ps.protocolPrefix}/${"id"}/${Sve}`,log:e.logger.forComponent("libp2p:identify")}),(t.runOnConnectionOpen??ps.runOnConnectionOpen)&&e.events.addEventListener("connection:open",n=>{let o=n.detail;this.identify(o).catch(()=>{})})}[In]=["@libp2p/identify"];async _identify(e,t={}){let n,o;if(t.signal==null){let s=AbortSignal.timeout(this.timeout);t={...t,signal:s}}this.log("run identify on new connection %a",e.remoteAddr);try{n=await e.newStream(this.protocol,{...t,runOnLimitedConnection:this.runOnLimitedConnection}),o=n.log.newScope("identify");let s=su(n,{maxDataLength:this.maxMessageSize}).pb(Df),i=await s.read(t);return await s.unwrap().unwrap().close(t),i}catch(s){throw o?.error("identify failed - %e",s),n?.abort(s),s}}async identify(e,t={}){let n=await this._identify(e,t),{publicKey:o,protocols:s,observedAddr:i}=n;if(o==null)throw new Ds("Public key was missing from identify message");let a=XR(o),c=Wa(a.toCID());if(!e.remotePeer.equals(c))throw new Ds("Identified peer does not match the expected peer");if(this.components.peerId.equals(c))throw new Ds("Identified peer is our own peer id?");return this.maybeAddObservedAddress(i),this.log("completed for peer %p and protocols %o",c,s),ZR(this.components.peerStore,this.components.events,this.log,e,n)}maybeAddObservedAddress(e){let t=uEe(e);if(t==null||(this.log.trace("our observed address was %a",t),da(t)))return;let n=t.getComponents();if((n[0].code===41||n[0].code===42&&n[1].code===41)&&!dbe(t)){this.log.trace("our observed address was IPv6 but not a global unicast address");return}jp.exactMatch(t)||(this.log.trace("storing the observed address"),this.components.addressManager.addObservedAddr(t))}async handleProtocol(e,t){let n=e.log.newScope("identify");n("responding to identify");let o=AbortSignal.timeout(this.timeout);let s=await this.components.peerStore.get(this.components.peerId,{signal:o}),i=this.components.addressManager.getAddresses().map(u=>u.decapsulateCode(421)),a=s.peerRecordEnvelope;if(i.length>0&&a==null){let u=new Vo({peerId:this.components.peerId,multiaddrs:i});a=(await Ho.seal(u,this.components.privateKey,{signal:o})).marshal().subarray()}let c=t.remoteAddr.bytes;Ewe.matches(t.remoteAddr)||(c=void 0);let l=su(e).pb(Df);n("send response"),await l.write({protocolVersion:this.host.protocolVersion,agentVersion:this.host.agentVersion,publicKey:Rf(this.components.privateKey.publicKey),listenAddrs:i.map(u=>u.bytes),signedPeerRecord:a,observedAddr:c,protocols:s.protocols},{signal:o}),n("close write"),await l.unwrap().unwrap().close({signal:o})}};function dEe(r={}){return e=>new QR(e,r)}function fEe(r={}){return e=>new JR(e,r)}se();Xi();function e5(r){if(isNaN(r)||r<=0)throw new q("random bytes length must be a Number bigger than 0");return ts(r)}se();ct();Ne();var hEe="1.0.0",pEe="ping",mEe="ipfs";var t5=class{protocol;components;started;timeout;maxInboundStreams;maxOutboundStreams;runOnLimitedConnection;constructor(e,t={}){this.components=e,this.started=!1,this.protocol=`/${t.protocolPrefix??mEe}/${pEe}/${hEe}`,this.timeout=t.timeout??1e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??1,this.runOnLimitedConnection=t.runOnLimitedConnection??!0,this.handlePing=this.handlePing.bind(this)}[Symbol.toStringTag]="@libp2p/ping";[In]=["@libp2p/ping"];async start(){await this.components.registrar.handle(this.protocol,this.handlePing,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:this.runOnLimitedConnection}),this.started=!0}async stop(){await this.components.registrar.unhandle(this.protocol),this.started=!1}isStarted(){return this.started}async handlePing(e,t){let n=e.log.newScope("ping");n.trace("ping from %p",t.remotePeer);let o=AbortSignal.timeout(this.timeout);o.addEventListener("abort",()=>{e.abort(new $g("Ping timed out"))});let s=Date.now();for await(let i of e){if(e.status!=="open"){n("stream status changed to %s",e.status);break}e.send(i)||(n("waiting for stream to drain"),await Bt(e,"drain",{rejectionEvents:["close"],signal:o}),n("stream drained"))}n("ping from %p complete in %dms",t.remotePeer,Date.now()-s),await e.close({signal:o})}async ping(e,t={}){let n=e5(32),o=await this.components.connectionManager.openStream(e,this.protocol,{runOnLimitedConnection:this.runOnLimitedConnection,...t}),s=o.log.newScope("ping");try{let i=Date.now(),a=Promise.withResolvers(),c=new Y,l=u=>{if(c.append(u.data),c.byteLength===32){o.removeEventListener("message",l);let d=Date.now()-i;Promise.all([o.closeRead(t)]).then(()=>{if(ee(n,c.subarray()))a.resolve(d);else throw new IT(`Received wrong ping ack after ${d}ms`)}).catch(h=>{o.abort(h),a.reject(h)})}};return o.addEventListener("message",l),o.send(n),await o.close(t),await qt(a.promise,t.signal)}catch(i){throw s.error("error while pinging %o - %e",e,i),o?.abort(i),i}finally{o?.close()}}};function yEe(r={}){return e=>new t5(e,r)}var rw=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var wu=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};_s();var bEe=Symbol.for("@libp2p/service-dependencies");function JZe(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function wEe(r){let e=JZe(r);if(e==null)throw new rw(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}var xEe=Ri(C_(),1),QZe=["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"],eJe=QZe.map(r=>new xEe.Netmask(r));function Mq(r){for(let e of eJe)if(e.contains(r))return!0;return!1}function tJe(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function rJe(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return Mq(o)}function nJe(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function oJe(r){let e=r.split(":"),t=e[e.length-1];return Mq(t)}function sJe(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 vEe(r){if(kt(r))return Mq(r);if(tJe(r))return rJe(r);if(nJe(r))return oJe(r);if(rs(r))return sJe(r)}function EEe(r){try{let e=wEe(r);switch(e.type){case"ip4":case"ip6":return vEe(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}Ne();si();Mr();me();Le();var Hn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},xu=class extends Error{static name="ValidationError";name="ValidationError"},r5=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},n5=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var GEr=new Uint8Array(0);function SEe(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 vu(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 CEe(r){return new TextEncoder().encode(r)}function AEe(r){return new TextDecoder().decode(r)}var Fq={};W(Fq,{base32:()=>Mf,base32hex:()=>mJe,base32hexpad:()=>yJe,base32hexpadupper:()=>bJe,base32hexupper:()=>gJe,base32pad:()=>hJe,base32padupper:()=>pJe,base32upper:()=>fJe,base32z:()=>wJe});function iJe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var aJe=iJe,cJe=aJe,TEe=cJe;var Bq=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")}},Oq=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 kEe(this,e)}},Nq=class{decoders;constructor(e){this.decoders=e}or(e){return kEe(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 kEe(r,e){return new Nq({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Uq=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Bq(e,t,n),this.decoder=new Oq(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function nw({name:r,prefix:e,encode:t,decode:n}){return new Uq(r,e,t,n)}function Lf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=TEe(t,r);return nw({prefix:e,name:r,encode:n,decode:s=>vu(o(s))})}function lJe(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function uJe(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function dJe(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function mr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=dJe(n);return nw({prefix:e,name:r,encode(s){return uJe(s,n,t)},decode(s){return lJe(s,o,t,r)}})}var Mf=mr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fJe=mr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),hJe=mr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pJe=mr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),mJe=mr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),gJe=mr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),yJe=mr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),bJe=mr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),wJe=mr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Kq={};W(Kq,{base36:()=>Q2,base36upper:()=>xJe});var Q2=Lf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xJe=Lf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var zq={};W(zq,{base58btc:()=>Mc,base58flickr:()=>vJe});var Mc=Lf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vJe=Lf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var EJe=PEe,DEe=128,SJe=127,CJe=~SJe,AJe=Math.pow(2,31);function PEe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=AJe;)e[t++]=r&255|DEe,r/=128;for(;r&CJe;)e[t++]=r&255|DEe,r>>>=7;return e[t]=r|0,PEe.bytes=t-n+1,e}var IJe=$q,TJe=128,_Ee=127;function $q(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw $q.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&_Ee)<<o:(i&_Ee)*Math.pow(2,o),o+=7}while(i>=TJe);return $q.bytes=s-n,t}var kJe=Math.pow(2,7),DJe=Math.pow(2,14),_Je=Math.pow(2,21),PJe=Math.pow(2,28),RJe=Math.pow(2,35),LJe=Math.pow(2,42),MJe=Math.pow(2,49),BJe=Math.pow(2,56),OJe=Math.pow(2,63),NJe=function(r){return r<kJe?1:r<DJe?2:r<_Je?3:r<PJe?4:r<RJe?5:r<LJe?6:r<MJe?7:r<BJe?8:r<OJe?9:10},UJe={encode:EJe,decode:IJe,encodingLength:NJe},FJe=UJe,eC=FJe;function tC(r,e=0){return[eC.decode(r,e),eC.decode.bytes]}function ow(r,e,t=0){return eC.encode(r,e,t),e}function sw(r){return eC.encodingLength(r)}function aw(r,e){let t=e.byteLength,n=sw(r),o=n+sw(t),s=new Uint8Array(o+t);return ow(r,s,0),ow(t,s,n),s.set(e,o),new iw(r,t,e,s)}function REe(r){let e=vu(r),[t,n]=tC(e),[o,s]=tC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new iw(t,o,i,e)}function LEe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&SEe(r.bytes,t.bytes)}}var iw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function MEe(r,e){let{bytes:t,version:n}=r;return n===0?zJe(t,Hq(r),e??Mc.encoder):$Je(t,Hq(r),e??Mf.encoder)}var BEe=new WeakMap;function Hq(r){let e=BEe.get(r);if(e==null){let t=new Map;return BEe.set(r,t),t}return e}var cw=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==nC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==HJe)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=aw(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&&LEe(e.multihash,n.multihash)}toString(e){return MEe(this,e)}toJSON(){return{"/":MEe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??OEe(n,o,s.bytes))}else if(t[VJe]===!0){let{version:n,multihash:o,code:s}=t,i=REe(o);return r.create(n,s,i)}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!==nC)throw new Error(`Version 0 CID must use dag-pb (code: ${nC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=OEe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,nC,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,o=vu(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new iw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=tC(e.subarray(t));return t+=h,d},o=n(),s=nC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=KJe(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Hq(s).set(n,e),s}};function KJe(r,e){switch(r[0]){case"Q":{let t=e??Mc;return[Mc.prefix,t.decode(`${Mc.prefix}${r}`)]}case Mc.prefix:{let t=e??Mc;return[Mc.prefix,t.decode(r)]}case Mf.prefix:{let t=e??Mf;return[Mf.prefix,t.decode(r)]}case Q2.prefix:{let t=e??Q2;return[Q2.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 zJe(r,e,t){let{prefix:n}=t;if(n!==Mc.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function $Je(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var nC=112,HJe=18;function OEe(r,e,t){let n=sw(r),o=n+sw(e),s=new Uint8Array(o+t.byteLength);return ow(r,s,0),ow(e,s,n),s.set(t,o),s}var VJe=Symbol.for("@ipld/js-cid/CID");var qJe=20;function qq({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new Vq(r,e,t,n,o)}var Vq=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??qJe,this.maxDigestLength=s}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?NEe(n,this.code,t?.truncate):n.then(o=>NEe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function NEe(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 aw(e,r)}var Gq={};W(Gq,{base64:()=>jJe,base64pad:()=>GJe,base64url:()=>jq,base64urlpad:()=>WJe});var jJe=mr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),GJe=mr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jq=mr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),WJe=mr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Wq={};W(Wq,{base10:()=>YJe});var YJe=Lf({prefix:"9",name:"base10",alphabet:"0123456789"});var Yq={};W(Yq,{base16:()=>XJe,base16upper:()=>ZJe});var XJe=mr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),ZJe=mr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Xq={};W(Xq,{base2:()=>JJe});var JJe=mr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zq={};W(Zq,{base256emoji:()=>nQe});var FEe=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}"),QJe=FEe.reduce((r,e,t)=>(r[t]=e,r),[]),eQe=FEe.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function tQe(r){return r.reduce((e,t)=>(e+=QJe[t],e),"")}function rQe(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=eQe[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var nQe=nw({prefix:"\u{1F680}",name:"base256emoji",encode:tQe,decode:rQe});var Jq={};W(Jq,{base8:()=>oQe});var oQe=mr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Qq={};W(Qq,{identity:()=>sQe});var sQe=nw({prefix:"\0",name:"identity",encode:r=>AEe(r),decode:r=>CEe(r)});var TSr=new TextEncoder,kSr=new TextDecoder;var ej={};W(ej,{identity:()=>uQe});var KEe=0,cQe="identity",zEe=vu;function lQe(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 aw(KEe,zEe(r))}var uQe={code:KEe,name:cQe,encode:zEe,digest:lQe};var tj={};W(tj,{sha256:()=>dQe,sha512:()=>fQe});function $Ee(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var dQe=qq({name:"sha2-256",code:18,encode:$Ee("SHA-256")}),fQe=qq({name:"sha2-512",code:19,encode:$Ee("SHA-512")});var HEe={...Qq,...Xq,...Jq,...Wq,...Yq,...Fq,...Kq,...zq,...Gq,...Zq},LSr={...tj,...ej};Mr();me();Le();function nj(r){return e=>z(e,r)}function oj(r){return e=>K(e,r)}function lw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function Xp(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function VEe(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=K(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 o=Xp(n);return Ye([t,o],t.length+o.length)}function qEe(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=Mf.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 o=Xp(n);return Ye([t,o],t.length+o.length)}function sj(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=lw(t);return`${n}:${o}`}var ij=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Hn("Invalid byte value in IP address");e[n]=o}),e},jEe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=kt(t[n]),i;s&&(i=ij(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Hn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},GEe=function(r){if(r.byteLength!==4)throw new Hn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},WEe=function(r){if(r.byteLength!==16)throw new Hn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Hn(`Invalid IPv6 address "${t}"`)}};function YEe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Hn(`Invalid IPv6 address "${r}"`)}}var rj=Object.values(HEe).map(r=>r.decoder),hQe=(function(){let r=rj[0].or(rj[1]);return rj.slice(2).forEach(e=>r=r.or(e)),r})();function XEe(r){return hQe.decode(r)}function ZEe(r){return e=>r.encoder.encode(e)}function pQe(r){if(parseInt(r).toString()!==r)throw new xu("Value must be an integer")}function mQe(r){if(r<0)throw new xu("Value must be a positive integer, or zero")}function gQe(r){return e=>{if(e>r)throw new xu(`Value must be smaller than or equal to ${r}`)}}function yQe(...r){return e=>{for(let t of r)t(e)}}var oC=yQe(pQe,mQe,gQe(65535));var dn=-1,aj=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 n5(`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)}))}},Su=new aj,PQe=[{code:4,name:"ip4",size:32,valueToBytes:ij,bytesToValue:GEe,validate:r=>{if(!kt(r))throw new xu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:273,name:"udp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:33,name:"dccp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:41,name:"ip6",size:128,valueToBytes:jEe,bytesToValue:WEe,stringToValue:YEe,validate:r=>{if(!rs(r))throw new xu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:dn},{code:43,name:"ipcidr",size:8,bytesToValue:nj("base10"),valueToBytes:oj("base10")},{code:53,name:"dns",size:dn},{code:54,name:"dns4",size:dn},{code:55,name:"dns6",size:dn},{code:56,name:"dnsaddr",size:dn},{code:132,name:"sctp",size:16,valueToBytes:Xp,bytesToValue:lw,validate:oC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:dn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:dn,bytesToValue:nj("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?oj("base58btc")(r):cw.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:sj,valueToBytes:VEe},{code:445,name:"onion3",size:296,bytesToValue:sj,valueToBytes:qEe},{code:446,name:"garlic64",size:dn},{code:447,name:"garlic32",size:dn},{code:448,name:"tls"},{code:449,name:"sni",size:dn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:dn,bytesToValue:ZEe(jq),valueToBytes:XEe},{code:480,name:"http"},{code:481,name:"http-path",size:dn,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:dn}];PQe.forEach(r=>{Su.addProtocol(r)});function JEe(r){let e=[],t=0;for(;t<r.length;){let n=so(r,t),o=Su.getProtocol(n),s=mt(n),i=RQe(o,r,t+s),a=0;i>0&&o.size===dn&&(a=mt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??z(d)}e.push(l),t+=c}return e}function QEe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Su.getProtocol(n.code),s=mt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===dn&&(c=mt(a)));let l=new Uint8Array(s+c+a),u=0;ul(n.code,l,u),u+=s,i!=null&&(o.size===dn&&(ul(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ye(t,e)}function eSe(r){if(r.charAt(0)!=="/")throw new Hn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Su.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Hn(`Component ${o} 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 Hn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Hn("Incomplete multiaddr");return e}function tSe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Su.getProtocol(e.code);if(t==null)throw new Hn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function RQe(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:so(e,t)}var LQe=Symbol.for("nodejs.util.inspect.custom"),Aj=Symbol.for("@multiformats/multiaddr");function MQe(r){if(r==null&&(r="/"),rSe(r))return r.getComponents();if(r instanceof Uint8Array)return JEe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),eSe(r);if(Array.isArray(r))return r;throw new Hn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Cj=class r{[Aj]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=MQe(e),t.validate!==!1&&BQe(this)}get bytes(){return this.#r==null&&(this.#r=QEe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=tSe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new r5(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return ee(this.bytes,e.bytes)}[LQe](){return`Multiaddr(${this.toString()})`}};function BQe(r){r.getComponents().forEach(e=>{let t=Su.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function rSe(r){return!!r?.[Aj]}var Ot=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),Se=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),nSe=r=>({match:e=>r.match(e)===!1?e:!1}),Ge=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),bo=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}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 Nt(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var OQe=Se(421),b1r=Nt(OQe),d5=Se(54),f5=Se(55),h5=Se(56),Tj=Se(53),w1r=Nt(d5,Ge(Se(421))),x1r=Nt(f5,Ge(Se(421))),v1r=Nt(h5,Ge(Se(421))),oSe=Nt(bo(Tj,h5,d5,f5),Ge(Se(421))),sSe=ot(Se(4),Ge(Se(43))),iSe=ot(Ge(Se(42)),Se(41),Ge(Se(43))),kj=bo(sSe,iSe),hw=bo(kj,Tj,d5,f5,h5),E1r=Nt(bo(kj,ot(bo(Tj,h5,d5,f5),Ge(Se(421))))),S1r=Nt(sSe),C1r=Nt(iSe),aSe=Nt(kj),Dj=ot(hw,Se(6)),sC=ot(hw,Se(273)),A1r=Nt(ot(Dj,Ge(Se(421)))),I1r=Nt(sC),_j=ot(sC,Ot(460),Ge(Se(421))),p5=ot(sC,Ot(461),Ge(Se(421))),NQe=bo(_j,p5),T1r=Nt(_j),k1r=Nt(p5),Ij=bo(hw,Dj,sC,_j,p5),cSe=bo(ot(Ij,Ot(477),Ge(Se(421)))),D1r=Nt(cSe),lSe=bo(ot(Ij,Ot(478),Ge(Se(421))),ot(Ij,Ot(448),Ge(Se(449)),Ot(477),Ge(Se(421)))),_1r=Nt(lSe),uSe=ot(sC,Ot(280),Ge(Se(466)),Ge(Se(466)),Ge(Se(421))),P1r=Nt(uSe),dSe=ot(p5,Ot(465),Ge(Se(466)),Ge(Se(466)),Ge(Se(421))),R1r=Nt(dSe),u5=bo(cSe,lSe,ot(Dj,Ge(Se(421))),ot(NQe,Ge(Se(421))),ot(hw,Ge(Se(421))),uSe,dSe,Se(421)),L1r=Nt(u5),UQe=ot(Ge(u5),Ot(290),nSe(Ot(281)),Ge(Se(421))),iC=Nt(UQe),FQe=bo(ot(u5,Ot(290),Ot(281),Ge(Se(421))),ot(u5,Ot(281),Ge(Se(421))),ot(Ot(281),Ge(Se(421)))),M1r=Nt(FQe),KQe=ot(hw,bo(ot(Se(6,"80")),ot(Se(6),Ot(480)),Ot(480)),Ge(Se(481)),Ge(Se(421))),B1r=Nt(KQe),zQe=ot(hw,bo(ot(Se(6,"443")),ot(Se(6,"443"),Ot(480)),ot(Se(6),Ot(443)),ot(Se(6),Ot(448),Ot(480)),ot(Ot(448),Ot(480)),Ot(448),Ot(443)),Ge(Se(481)),Ge(Se(421))),O1r=Nt(zQe),$Qe=bo(ot(Se(777),Ge(Se(421)))),N1r=Nt($Qe),HQe=bo(ot(Se(400),Ge(Se(421)))),U1r=Nt(HQe);var Jp=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};Ne();Xt();var VQe=Math.pow(2,7),qQe=Math.pow(2,14),jQe=Math.pow(2,21),Pj=Math.pow(2,28),Rj=Math.pow(2,35),Lj=Math.pow(2,42),Mj=Math.pow(2,49),er=128,wo=127;function pw(r){if(r<VQe)return 1;if(r<qQe)return 2;if(r<jQe)return 3;if(r<Pj)return 4;if(r<Rj)return 5;if(r<Lj)return 6;if(r<Mj)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Bj(r,e,t=0){switch(pw(r)){case 8:e[t++]=r&255|er,r/=128;case 7:e[t++]=r&255|er,r/=128;case 6:e[t++]=r&255|er,r/=128;case 5:e[t++]=r&255|er,r/=128;case 4:e[t++]=r&255|er,r>>>=7;case 3:e[t++]=r&255|er,r>>>=7;case 2:e[t++]=r&255|er,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function GQe(r,e){let t=r[e],n=0;if(n+=t&wo,t<er||(t=r[e+1],n+=(t&wo)<<7,t<er)||(t=r[e+2],n+=(t&wo)<<14,t<er)||(t=r[e+3],n+=(t&wo)<<21,t<er)||(t=r[e+4],n+=(t&wo)*Pj,t<er)||(t=r[e+5],n+=(t&wo)*Rj,t<er)||(t=r[e+6],n+=(t&wo)*Lj,t<er)||(t=r[e+7],n+=(t&wo)*Mj,t<er))return n;throw new RangeError("Could not decode varint")}function WQe(r,e){let t=r.get(e),n=0;if(n+=t&wo,t<er||(t=r.get(e+1),n+=(t&wo)<<7,t<er)||(t=r.get(e+2),n+=(t&wo)<<14,t<er)||(t=r.get(e+3),n+=(t&wo)<<21,t<er)||(t=r.get(e+4),n+=(t&wo)*Pj,t<er)||(t=r.get(e+5),n+=(t&wo)*Rj,t<er)||(t=r.get(e+6),n+=(t&wo)*Lj,t<er)||(t=r.get(e+7),n+=(t&wo)*Mj,t<er))return n;throw new RangeError("Could not decode varint")}function Oj(r,e=0){return r instanceof Uint8Array?GQe(r,e):WQe(r,e)}Mr();me();Le();var Vn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Cu=class extends Error{static name="ValidationError";name="ValidationError"},m5=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},g5=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var H1r=new Uint8Array(0);function fSe(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 Au(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Qp(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Qp(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function hSe(r){return new TextEncoder().encode(r)}function pSe(r){return new TextDecoder().decode(r)}function XQe(r){return r?.buffer instanceof ArrayBuffer}function Qp(r){return XQe(r)?r:r.slice()}var zj={};W(zj,{base32:()=>Of,base32hex:()=>iet,base32hexpad:()=>cet,base32hexpadupper:()=>uet,base32hexupper:()=>aet,base32pad:()=>oet,base32padupper:()=>set,base32upper:()=>net,base32z:()=>det});function ZQe(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var JQe=ZQe,QQe=JQe,gSe=QQe;var Nj=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")}},Uj=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 ySe(this,e)}},Fj=class{decoders;constructor(e){this.decoders=e}or(e){return ySe(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 ySe(r,e){return new Fj({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var Kj=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new Nj(e,t,n),this.decoder=new Uj(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function mw({name:r,prefix:e,encode:t,decode:n}){return new Kj(r,e,t,n)}function Bf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=gSe(t,r);return mw({prefix:e,name:r,encode:n,decode:s=>Au(o(s))})}function eet(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function tet(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function ret(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function gr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=ret(n);return mw({prefix:e,name:r,encode(s){return tet(s,n,t)},decode(s){return eet(s,o,t,r)}})}var Of=gr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),net=gr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),oet=gr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),set=gr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iet=gr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),aet=gr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cet=gr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),uet=gr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),det=gr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $j={};W($j,{base36:()=>aC,base36upper:()=>fet});var aC=Bf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),fet=Bf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Hj={};W(Hj,{base58btc:()=>Bc,base58flickr:()=>het});var Bc=Bf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),het=Bf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pet=xSe,bSe=128,met=127,get=~met,yet=Math.pow(2,31);function xSe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=yet;)e[t++]=r&255|bSe,r/=128;for(;r&get;)e[t++]=r&255|bSe,r>>>=7;return e[t]=r|0,xSe.bytes=t-n+1,e}var bet=Vj,wet=128,wSe=127;function Vj(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw Vj.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&wSe)<<o:(i&wSe)*Math.pow(2,o),o+=7}while(i>=wet);return Vj.bytes=s-n,t}var xet=Math.pow(2,7),vet=Math.pow(2,14),Eet=Math.pow(2,21),Cet=Math.pow(2,28),Aet=Math.pow(2,35),Iet=Math.pow(2,42),Tet=Math.pow(2,49),ket=Math.pow(2,56),Det=Math.pow(2,63),_et=function(r){return r<xet?1:r<vet?2:r<Eet?3:r<Cet?4:r<Aet?5:r<Iet?6:r<Tet?7:r<ket?8:r<Det?9:10},Pet={encode:pet,decode:bet,encodingLength:_et},Ret=Pet,cC=Ret;function lC(r,e=0){return[cC.decode(r,e),cC.decode.bytes]}function gw(r,e,t=0){return cC.encode(r,e,t),e}function yw(r){return cC.encodingLength(r)}function ww(r,e){let t=e.byteLength,n=yw(r),o=n+yw(t),s=new Uint8Array(o+t);return gw(r,s,0),gw(t,s,n),s.set(e,o),new bw(r,t,e,s)}function vSe(r){let e=Au(r),[t,n]=lC(e),[o,s]=lC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new bw(t,o,i,e)}function ESe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&fSe(r.bytes,t.bytes)}}var bw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Qp(n),this.bytes=Qp(o)}};function SSe(r,e){let{bytes:t,version:n}=r;return n===0?Met(t,qj(r),e??Bc.encoder):Bet(t,qj(r),e??Of.encoder)}var CSe=new WeakMap;function qj(r){let e=CSe.get(r);if(e==null){let t=new Map;return CSe.set(r,t),t}return e}var xw=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Qp(o),this["/"]=this.bytes}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!==dC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Oet)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=ww(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&&ESe(e.multihash,n.multihash)}toString(e){return SSe(this,e)}toJSON(){return{"/":SSe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??ASe(n,o,s.bytes))}else if(t[Net]===!0){let{version:n,multihash:o,code:s}=t,i=vSe(o);return r.create(n,s,i)}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!==dC)throw new Error(`Version 0 CID must use dag-pb (code: ${dC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=ASe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,dC,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,o=Au(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new bw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=lC(e.subarray(t));return t+=h,d},o=n(),s=dC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Let(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return qj(s).set(n,e),s}};function Let(r,e){switch(r[0]){case"Q":{let t=e??Bc;return[Bc.prefix,t.decode(`${Bc.prefix}${r}`)]}case Bc.prefix:{let t=e??Bc;return[Bc.prefix,t.decode(r)]}case Of.prefix:{let t=e??Of;return[Of.prefix,t.decode(r)]}case aC.prefix:{let t=e??aC;return[aC.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 Met(r,e,t){let{prefix:n}=t;if(n!==Bc.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Bet(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var dC=112,Oet=18;function ASe(r,e,t){let n=yw(r),o=n+yw(e),s=new Uint8Array(o+t.byteLength);return gw(r,s,0),gw(e,s,n),s.set(t,o),s}var Net=Symbol.for("@ipld/js-cid/CID");var Uet=20;function Gj({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new jj(r,e,t,n,o)}var jj=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Uet,this.maxDigestLength=s}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?ISe(n,this.code,t?.truncate):n.then(o=>ISe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function ISe(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 ww(e,r)}var Yj={};W(Yj,{base64:()=>Fet,base64pad:()=>Ket,base64url:()=>Wj,base64urlpad:()=>zet});var Fet=gr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ket=gr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Wj=gr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zet=gr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Xj={};W(Xj,{base10:()=>$et});var $et=Bf({prefix:"9",name:"base10",alphabet:"0123456789"});var Zj={};W(Zj,{base16:()=>Het,base16upper:()=>Vet});var Het=gr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Vet=gr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Jj={};W(Jj,{base2:()=>qet});var qet=gr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Qj={};W(Qj,{base256emoji:()=>Xet});var kSe=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}"),jet=kSe.reduce((r,e,t)=>(r[t]=e,r),[]),Get=kSe.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Wet(r){return r.reduce((e,t)=>(e+=jet[t],e),"")}function Yet(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Get[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Xet=mw({prefix:"\u{1F680}",name:"base256emoji",encode:Wet,decode:Yet});var eG={};W(eG,{base8:()=>Zet});var Zet=gr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var tG={};W(tG,{identity:()=>Jet});var Jet=mw({prefix:"\0",name:"identity",encode:r=>pSe(r),decode:r=>hSe(r)});var S2r=new TextEncoder,C2r=new TextDecoder;var rG={};W(rG,{identity:()=>ntt});var DSe=0,ttt="identity",_Se=Au;function rtt(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 ww(DSe,_Se(r))}var ntt={code:DSe,name:ttt,encode:_Se,digest:rtt};var nG={};W(nG,{sha256:()=>ott,sha512:()=>stt});function PSe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ott=Gj({name:"sha2-256",code:18,encode:PSe("SHA-256")}),stt=Gj({name:"sha2-512",code:19,encode:PSe("SHA-512")});var RSe={...tG,...Jj,...eG,...Xj,...Zj,...zj,...$j,...Hj,...Yj,...Qj},D2r={...nG,...rG};Mr();me();Le();function sG(r){return e=>z(e,r)}function iG(r){return e=>K(e,r)}function vw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function em(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function LSe(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=K(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 o=em(n);return Ye([t,o],t.length+o.length)}function MSe(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=Of.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 o=em(n);return Ye([t,o],t.length+o.length)}function aG(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=vw(t);return`${n}:${o}`}var cG=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Vn("Invalid byte value in IP address");e[n]=o}),e},BSe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=kt(t[n]),i;s&&(i=cG(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Vn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},OSe=function(r){if(r.byteLength!==4)throw new Vn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},NSe=function(r){if(r.byteLength!==16)throw new Vn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Vn(`Invalid IPv6 address "${t}"`)}};function USe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Vn(`Invalid IPv6 address "${r}"`)}}var oG=Object.values(RSe).map(r=>r.decoder),itt=(function(){let r=oG[0].or(oG[1]);return oG.slice(2).forEach(e=>r=r.or(e)),r})();function FSe(r){return itt.decode(r)}function KSe(r){return e=>r.encoder.encode(e)}function att(r){if(parseInt(r).toString()!==r)throw new Cu("Value must be an integer")}function ctt(r){if(r<0)throw new Cu("Value must be a positive integer, or zero")}function ltt(r){return e=>{if(e>r)throw new Cu(`Value must be smaller than or equal to ${r}`)}}function utt(...r){return e=>{for(let t of r)t(e)}}var fC=utt(att,ctt,ltt(65535));var fn=-1,lG=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 g5(`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)}))}},Iu=new lG,Xtt=[{code:4,name:"ip4",size:32,valueToBytes:cG,bytesToValue:OSe,validate:r=>{if(!kt(r))throw new Cu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:273,name:"udp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:33,name:"dccp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:41,name:"ip6",size:128,valueToBytes:BSe,bytesToValue:NSe,stringToValue:USe,validate:r=>{if(!rs(r))throw new Cu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:fn},{code:43,name:"ipcidr",size:8,bytesToValue:sG("base10"),valueToBytes:iG("base10")},{code:53,name:"dns",size:fn},{code:54,name:"dns4",size:fn},{code:55,name:"dns6",size:fn},{code:56,name:"dnsaddr",size:fn},{code:132,name:"sctp",size:16,valueToBytes:em,bytesToValue:vw,validate:fC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:fn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:fn,bytesToValue:sG("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?iG("base58btc")(r):xw.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:aG,valueToBytes:LSe},{code:445,name:"onion3",size:296,bytesToValue:aG,valueToBytes:MSe},{code:446,name:"garlic64",size:fn},{code:447,name:"garlic32",size:fn},{code:448,name:"tls"},{code:449,name:"sni",size:fn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:fn,bytesToValue:KSe(Wj),valueToBytes:FSe},{code:480,name:"http"},{code:481,name:"http-path",size:fn,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:fn}];Xtt.forEach(r=>{Iu.addProtocol(r)});function zSe(r){let e=[],t=0;for(;t<r.length;){let n=Oj(r,t),o=Iu.getProtocol(n),s=pw(n),i=Ztt(o,r,t+s),a=0;i>0&&o.size===fn&&(a=pw(i));let c=s+a+i,l={code:n,name:o.name,bytes:_n(r.subarray(t,t+c))};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??z(d)}e.push(l),t+=c}return e}function $Se(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Iu.getProtocol(n.code),s=pw(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===fn&&(c=pw(a)));let l=new Uint8Array(s+c+a),u=0;Bj(n.code,l,u),u+=s,i!=null&&(o.size===fn&&(Bj(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ye(t,e)}function HSe(r){if(r.charAt(0)!=="/")throw new Vn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Iu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Vn(`Component ${o} 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 Vn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Vn("Incomplete multiaddr");return e}function VSe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Iu.getProtocol(e.code);if(t==null)throw new Vn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Ztt(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:Oj(e,t)}var Jtt=Symbol.for("nodejs.util.inspect.custom"),dG=Symbol.for("@multiformats/multiaddr");function Qtt(r){if(r==null&&(r="/"),qSe(r))return r.getComponents();if(r instanceof Uint8Array)return zSe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),HSe(r);if(Array.isArray(r))return r;throw new Vn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var b5=class r{[dG]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Qtt(e),t.validate!==!1&&ert(this)}get bytes(){return this.#r==null&&(this.#r=$Se(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=VSe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new m5(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return ee(this.bytes,e.bytes)}[Jtt](){return`Multiaddr(${this.toString()})`}};function ert(r){r.getComponents().forEach(e=>{let t=Iu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function qSe(r){return!!r?.[dG]}function fG(r){return new b5(r)}si();ct();var trt=4194304,w5=class extends Error{static name="UnwrappedError";name="UnwrappedError"},pG=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},mG=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},gG=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function rrt(r){return typeof r?.closeRead=="function"}function nrt(r){return typeof r?.close=="function"}function hG(r){return rrt(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:nrt(r)?r.status!=="open":!1}function ort(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function srt(r,e){let t=e?.maxBufferSize??trt,n=new Y,o,s=!1;if(!ort(r))throw new rw("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new w5("Stream was unwrapped");if(hG(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Jp(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await qt(o.promise,u?.signal),hG(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(hG(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Jp(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,d){if(s===!0)throw new w5("Stream was unwrapped");r.send(u)||await Bt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function irt(r,e={}){let t=srt(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=mt(e.maxDataLength));let n=e?.lengthDecoder??so,o=e?.lengthEncoder??oi;return{async read(i){let a=-1,c=new Y;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new pG("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new gG(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new mG(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Jp(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Jp(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function yG(r,e){let t=irt(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}kn();var fa;(function(r){let e;(function(a){a.UNUSED="UNUSED",a.CONNECT="CONNECT",a.SYNC="SYNC"})(e=r.Type||(r.Type={}));let t;(function(a){a[a.UNUSED=0]="UNUSED",a[a.CONNECT=100]="CONNECT",a[a.SYNC=300]="SYNC"})(t||(t={})),(function(a){a.codec=()=>Pt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=we((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.type!=null&&(c.uint32(8),r.Type.codec().encode(a.type,c)),a.observedAddresses!=null&&a.observedAddresses.length>0)for(let u of a.observedAddresses)c.uint32(18),c.bytes(u);l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={observedAddresses:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{u.type=r.Type.codec().decode(a);break}case 2:{if(l.limits?.observedAddresses!=null&&u.observedAddresses.length===l.limits.observedAddresses)throw new lr('Decode error - repeated field "observedAddresses" had too many elements');u.observedAddresses.push(a.bytes());break}default:{a.skipType(h&7);break}}}return u},function*(a,c,l,u={}){let d={observedAddresses:0},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let p=a.uint32();switch(p>>>3){case 1:{yield{field:`${l}.type`,value:r.Type.codec().decode(a)};break}case 2:{if(u.limits?.observedAddresses!=null&&d.observedAddresses===u.limits.observedAddresses)throw new lr('Streaming decode error - repeated field "observedAddresses" had too many elements');yield{field:`${l}.observedAddresses[]`,index:d.observedAddresses,value:a.bytes()},d.observedAddresses++;break}default:{a.skipType(p&7);break}}}})),n);function o(a){return be(a,r.codec())}r.encode=o;function s(a,c){return ye(a,r.codec(),c)}r.decode=s;function i(a,c){return Ji(a,r.codec(),c)}r.stream=i})(fa||(fa={}));function bG(r,e){return iC.matches(r)||e.dialTransportForMultiaddr(r)==null?!1:oSe.matches(r)?!0:aSe.matches(r)?!EEe(r):!1}var jSe=1024*4,GSe=100,x5={timeout:5e3,retries:3,maxInboundStreams:1,maxOutboundStreams:1},v5=class{started;timeout;retries;maxInboundStreams;maxOutboundStreams;peerStore;registrar;connectionManager;addressManager;transportManager;topologyId;log;constructor(e,t){this.log=e.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=e.peerStore,this.registrar=e.registrar,this.addressManager=e.addressManager,this.connectionManager=e.connectionManager,this.transportManager=e.transportManager,this.timeout=t.timeout??x5.timeout,this.retries=t.retries??x5.retries,this.maxInboundStreams=t.maxInboundStreams??x5.maxInboundStreams,this.maxOutboundStreams=t.maxOutboundStreams??x5.maxOutboundStreams,this.handleIncomingUpgrade=this.handleIncomingUpgrade.bind(this)}[Symbol.toStringTag]="@libp2p/dcutr";[bEe]=["@libp2p/identify"];isStarted(){return this.started}async start(){this.started||(this.topologyId=await this.registrar.register(hC,{notifyOnLimitedConnection:!0,onConnect:(e,t)=>{iC.exactMatch(t.remoteAddr)&&t.direction==="inbound"&&this.upgradeInbound(t).catch(n=>{this.log.error("error during outgoing DCUtR attempt - %e",n)})}}),await this.registrar.handle(hC,this.handleIncomingUpgrade,{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){await this.registrar.unhandle(hC),this.topologyId!=null&&this.registrar.unregister(this.topologyId),this.started=!1}async upgradeInbound(e){if(await this.attemptUnilateralConnectionUpgrade(e))return;let t;for(let n=0;n<this.retries;n++){let o={signal:AbortSignal.timeout(this.timeout)};try{t=await e.newStream([hC],{signal:o.signal,runOnLimitedConnection:!0});let s=yG(t,{maxDataLength:jSe}).pb(fa);this.log("B sending connect to %p",e.remotePeer);let i=Date.now();await s.write({type:fa.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(d=>d.bytes)},o),this.log("B receiving connect from %p",e.remotePeer);let a=await s.read(o);if(a.type!==fa.Type.CONNECT)throw this.log("A sent wrong message type"),new wu("DCUtR message type was incorrect");let c=this.getDialableMultiaddrs(a.observedAddresses);if(c.length===0)throw this.log("A did not have any dialable multiaddrs"),new wu("DCUtR connect message had no multiaddrs");let l=Date.now()-i;this.log("A sending sync, rtt %dms",l),await s.write({type:fa.Type.SYNC,observedAddresses:[]},o),this.log("A waiting for half RTT"),await vbe(l/2),this.log("B dialing",c);let u=await this.connectionManager.openConnection(c,{signal:o.signal,priority:GSe,force:!0,initiator:!1});this.log("DCUtR to %p succeeded to address %a, closing relayed connection",e.remotePeer,u.remoteAddr),await e.close(o);break}catch(s){if(this.log.error("error while attempting DCUtR on attempt %d of %d - %e",n+1,this.retries,s),t?.abort(s),n===this.retries)throw s}finally{t!=null&&await t.close(o)}}}async attemptUnilateralConnectionUpgrade(e){let n=(await this.peerStore.get(e.remotePeer)).addresses.map(o=>{let s=o.multiaddr;return s.getComponents().find(i=>i.code===421)?.value==null?s.encapsulate(`/p2p/${e.remotePeer}`):s}).filter(o=>bG(o,this.transportManager));if(n.length>0){let o=AbortSignal.timeout(this.timeout);try{this.log("attempting unilateral connection upgrade to %a",n);let s=await this.connectionManager.openConnection(n,{signal:o,force:!0});if(iC.exactMatch(s.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return this.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",e.remotePeer,s.remoteAddr),await e.close({signal:o}),!0}catch(s){this.log.error("unilateral connection upgrade to %p on addresses %a failed - %e",e.remotePeer,n,s)}}else this.log("peer %p has no public addresses, not attempting unilateral connection upgrade",e.remotePeer);return!1}async handleIncomingUpgrade(e,t){let n={signal:AbortSignal.timeout(this.timeout)},o=yG(e,{maxDataLength:jSe}).pb(fa);this.log("A receiving connect");let s=await o.read(n);if(s.type!==fa.Type.CONNECT)throw this.log("B sent wrong message type"),new wu("DCUtR message type was incorrect");if(s.observedAddresses.length===0)throw this.log("B sent no multiaddrs"),new wu("DCUtR connect message had no multiaddrs");let i=this.getDialableMultiaddrs(s.observedAddresses);if(i.length===0)throw this.log("B had no dialable multiaddrs in %o",s.observedAddresses.map(l=>fG(l))),new wu("DCUtR connect message had no dialable multiaddrs");if(this.log("A sending connect"),await o.write({type:fa.Type.CONNECT,observedAddresses:this.addressManager.getAddresses().map(l=>l.bytes)}),this.log("A receiving sync"),(await o.read(n)).type!==fa.Type.SYNC)throw new wu("DCUtR message type was incorrect");this.log("A dialing",i);let c=await this.connectionManager.openConnection(i,{signal:n.signal,priority:GSe,force:!0});this.log("DCUtR to %p succeeded via %a, closing relayed connection",t.remotePeer,c.remoteAddr),await t.close(n),await e.close(n)}getDialableMultiaddrs(e){let t=[];for(let n of e)if(!(n==null||n.length===0))try{let o=fG(n);if(!bG(o,this.transportManager))continue;t.push(o)}catch{}return t}};var hC="/libp2p/dcutr";function WSe(r={}){return e=>new v5(e,r)}var Tu=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var ku=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}};var E5=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var wG=Symbol.for("@libp2p/peer-id");_s();var YSe=Symbol.for("@libp2p/service-capabilities"),XSe=Symbol.for("@libp2p/service-dependencies");var CG={};W(CG,{base58btc:()=>Go,base58flickr:()=>prt});var dAr=new Uint8Array(0);function ZSe(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 Du(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return tm(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return tm(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function JSe(r){return new TextEncoder().encode(r)}function QSe(r){return new TextDecoder().decode(r)}function art(r){return r?.buffer instanceof ArrayBuffer}function tm(r){return art(r)?r:r.slice()}function crt(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var lrt=crt,urt=lrt,t1e=urt;var xG=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")}},vG=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 r1e(this,e)}},EG=class{decoders;constructor(e){this.decoders=e}or(e){return r1e(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 r1e(r,e){return new EG({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var SG=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new xG(e,t,n),this.decoder=new vG(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Ew({name:r,prefix:e,encode:t,decode:n}){return new SG(r,e,t,n)}function Nf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=t1e(t,r);return Ew({prefix:e,name:r,encode:n,decode:s=>Du(o(s))})}function drt(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function frt(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function hrt(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function yr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=hrt(n);return Ew({prefix:e,name:r,encode(s){return frt(s,n,t)},decode(s){return drt(s,o,t,r)}})}var Go=Nf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),prt=Nf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var AG={};W(AG,{base32:()=>Uf,base32hex:()=>brt,base32hexpad:()=>xrt,base32hexpadupper:()=>vrt,base32hexupper:()=>wrt,base32pad:()=>grt,base32padupper:()=>yrt,base32upper:()=>mrt,base32z:()=>Ert});var Uf=yr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),mrt=yr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),grt=yr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),yrt=yr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),brt=yr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),wrt=yr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),xrt=yr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),vrt=yr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ert=yr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var IG={};W(IG,{base36:()=>pC,base36upper:()=>Srt});var pC=Nf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Srt=Nf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Crt=s1e,n1e=128,Art=127,Irt=~Art,Trt=Math.pow(2,31);function s1e(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Trt;)e[t++]=r&255|n1e,r/=128;for(;r&Irt;)e[t++]=r&255|n1e,r>>>=7;return e[t]=r|0,s1e.bytes=t-n+1,e}var krt=TG,Drt=128,o1e=127;function TG(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw TG.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&o1e)<<o:(i&o1e)*Math.pow(2,o),o+=7}while(i>=Drt);return TG.bytes=s-n,t}var _rt=Math.pow(2,7),Prt=Math.pow(2,14),Rrt=Math.pow(2,21),Lrt=Math.pow(2,28),Mrt=Math.pow(2,35),Brt=Math.pow(2,42),Ort=Math.pow(2,49),Nrt=Math.pow(2,56),Urt=Math.pow(2,63),Frt=function(r){return r<_rt?1:r<Prt?2:r<Rrt?3:r<Lrt?4:r<Mrt?5:r<Brt?6:r<Ort?7:r<Nrt?8:r<Urt?9:10},Krt={encode:Crt,decode:krt,encodingLength:Frt},zrt=Krt,mC=zrt;function gC(r,e=0){return[mC.decode(r,e),mC.decode.bytes]}function Sw(r,e,t=0){return mC.encode(r,e,t),e}function Cw(r){return mC.encodingLength(r)}function Iw(r,e){let t=e.byteLength,n=Cw(r),o=n+Cw(t),s=new Uint8Array(o+t);return Sw(r,s,0),Sw(t,s,n),s.set(e,o),new Aw(r,t,e,s)}function rm(r){let e=Du(r),[t,n]=gC(e),[o,s]=gC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Aw(t,o,i,e)}function i1e(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&ZSe(r.bytes,t.bytes)}}var Aw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=tm(n),this.bytes=tm(o)}};function a1e(r,e){let{bytes:t,version:n}=r;return n===0?Hrt(t,kG(r),e??Go.encoder):Vrt(t,kG(r),e??Uf.encoder)}var c1e=new WeakMap;function kG(r){let e=c1e.get(r);if(e==null){let t=new Map;return c1e.set(r,t),t}return e}var Oc=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=tm(o),this["/"]=this.bytes}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!==yC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==qrt)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=Iw(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&&i1e(e.multihash,n.multihash)}toString(e){return a1e(this,e)}toJSON(){return{"/":a1e(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??l1e(n,o,s.bytes))}else if(t[jrt]===!0){let{version:n,multihash:o,code:s}=t,i=rm(o);return r.create(n,s,i)}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!==yC)throw new Error(`Version 0 CID must use dag-pb (code: ${yC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=l1e(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,yC,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,o=Du(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Aw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=gC(e.subarray(t));return t+=h,d},o=n(),s=yC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=$rt(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return kG(s).set(n,e),s}};function $rt(r,e){switch(r[0]){case"Q":{let t=e??Go;return[Go.prefix,t.decode(`${Go.prefix}${r}`)]}case Go.prefix:{let t=e??Go;return[Go.prefix,t.decode(r)]}case Uf.prefix:{let t=e??Uf;return[Uf.prefix,t.decode(r)]}case pC.prefix:{let t=e??pC;return[pC.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 Hrt(r,e,t){let{prefix:n}=t;if(n!==Go.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Vrt(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var yC=112,qrt=18;function l1e(r,e,t){let n=Cw(r),o=n+Cw(e),s=new Uint8Array(o+t.byteLength);return Sw(r,s,0),Sw(e,s,n),s.set(t,o),s}var jrt=Symbol.for("@ipld/js-cid/CID");var DG={};W(DG,{identity:()=>bC});var u1e=0,Grt="identity",d1e=Du;function Wrt(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 Iw(u1e,d1e(r))}var bC={code:u1e,name:Grt,encode:d1e,digest:Wrt};var LG={};W(LG,{sha256:()=>RG,sha512:()=>Xrt});var Yrt=20;function PG({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new _G(r,e,t,n,o)}var _G=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Yrt,this.maxDigestLength=s}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?f1e(n,this.code,t?.truncate):n.then(o=>f1e(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function f1e(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 Iw(e,r)}function p1e(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var RG=PG({name:"sha2-256",code:18,encode:p1e("SHA-256")}),Xrt=PG({name:"sha2-512",code:19,encode:p1e("SHA-512")});Le();Ne();me();Le();var m1e=Symbol.for("nodejs.util.inspect.custom"),Zrt=114,wC=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()})`}[wG]=!0;toString(){return this.string==null&&(this.string=Go.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return Oc.createV1(Zrt,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return ee(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return ee(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[m1e](){return`PeerId(${this.toString()})`}},C5=class extends wC{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},A5=class extends wC{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},I5=class extends wC{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},Jrt=2336,T5=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=bC.digest(K(this.url))}[m1e](){return`PeerId(${this.url})`}[wG]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return Oc.createV1(Jrt,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=z(e)),e.toString()===this.toString())}};function k5(r){if(ent(r))return new C5({multihash:r});if(Qrt(r))try{let e=wle(r);if(e.type==="Ed25519")return new A5({multihash:r,publicKey:e});if(e.type==="secp256k1")return new I5({multihash:r,publicKey:e})}catch{let t=z(r.digest);return new T5(new URL(t))}throw new E5("Supplied PeerID Multihash is invalid")}function Qrt(r){return r.code===bC.code}function ent(r){return r.code===RG.code}function MG(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}function D5(r){let e=rm(Go.decode(`z${r}`));return k5(e)}var _5=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 MG(this.set.entries(),e=>{let t=D5(e[0]);return[t,t]})}forEach(e){this.set.forEach(t=>{let n=D5(t);e(n,n,this)})}has(e){return this.set.has(e.toString())}values(){return MG(this.set.values(),e=>D5(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 BG(){return new _5}me();var xC={hash:r=>Number(N1(r,{size:32})),hashV:(r,e)=>tnt(xC.hash(r,e))};function tnt(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),K(e,"base16")}me();Xt();Ne();var OG=64,ha=class{fp;h;seed;constructor(e,t,n,o=2){if(o>OG)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=Oe(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?ee(this.fp,e.fp):!1}};function nm(r,e){return Math.floor(Math.random()*(e-r))+r}var om=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof ha))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof ha))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 ha))throw new TypeError("Invalid Fingerprint");let t=nm(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof ha))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var rnt=500,vC=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??xC,this.seed=e.seed??nm(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=K(e));let t=new ha(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new om(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new om(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[nm(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new om(this.bucketSize));for(let a=0;a<rnt;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new om(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=K(e));let t=new ha(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=K(e));let t=new ha(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},nnt={1:.5,2:.84,4:.95,8:.98};function ont(r=.001){return r>.002?2:r>1e-5?4:8}function g1e(r,e=.001){let t=ont(e),n=nnt[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),OG);return{filterSize:o,bucketSize:t,fingerprintSize:s}}me();var P5=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??xC,this.seed=e.seed??nm(0,Math.pow(2,10)),this.filterSeries=[new vC({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=K(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 vC({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=K(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=K(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 NG(r,e=.001,t){return new P5({...g1e(r,e),...t??{}})}function snt(r){let e=r.getComponents(),t={},n=0;return e[n]?.name==="ip6zone"&&(t.zone=`${e[n].value}`,n++),e[n]?.name==="ip4"||e[n]?.name==="ip6"||e[n]?.name==="dns"||e[n]?.name==="dns4"||e[n]?.name==="dns6"?(t.type=e[n].name,t.host=e[n].value,n++):e[n]?.name==="dnsaddr"&&(t.type=e[n].name,t.host=`_dnsaddr.${e[n].value}`,n++),(e[n]?.name==="tcp"||e[n]?.name==="udp")&&(t.protocol=e[n].name==="tcp"?"tcp":"udp",t.port=parseInt(`${e[n].value}`),n++),e[n]?.name==="ipcidr"&&(t.type==="ip4"?t.cidr=parseInt(`${e[n].value}`):t.type==="ip6"&&(t.cidr=`${e[n].value}`),n++),t.type==null||t.host==null?null:(e[n]?.name==="tls"&&e[n+1]?.name==="sni"&&(t.sni=e[n+1].value,n+=2),t)}function pa(r){let e=snt(r);if(e==null)throw new ku(`Multiaddr ${r} was not an IPv4, IPv6, DNS, DNS4, DNS6 or DNSADDR address`);return e}function y1e(r){try{let e=pa(r);return e.type==="ip6"?S_("2000::/3",e.host):!1}catch{return!1}}var b1e=Ri(C_(),1),int=["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"],ant=int.map(r=>new b1e.Netmask(r));function UG(r){for(let e of ant)if(e.contains(r))return!0;return!1}function cnt(r){return/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(r)}function lnt(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"),o=`${parseInt(n.substring(0,2),16)}.${parseInt(n.substring(2),16)}.${parseInt(t.substring(0,2),16)}.${parseInt(t.substring(2),16)}`;return UG(o)}function unt(r){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(r)}function dnt(r){let e=r.split(":"),t=e[e.length-1];return UG(t)}function fnt(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 w1e(r){if(kt(r))return UG(r);if(cnt(r))return lnt(r);if(unt(r))return dnt(r);if(rs(r))return fnt(r)}function FG(r){try{let e=pa(r);switch(e.type){case"ip4":case"ip6":return w1e(e.host)??!1;default:return e.host==="localhost"}}catch{return!1}}_s();function EC(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var R5=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},sm=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var L5=class{deferred;signal;onProgress;constructor(e){this.signal=e?.signal,this.onProgress=e?.onProgress,this.deferred=Lr(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Tu)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function hnt(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var M5=class{id;fn;options;recipients;status;timeline;controller;dispatchingProgress;constructor(e,t){this.id=hnt(),this.status="queued",this.fn=e,this.options=t,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.dispatchingProgress=!1,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 Tu),this.cleanup())}async join(e){let t=new L5(e);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 qt(this.fn({...this.options??{},signal:this.controller.signal,onProgress:t=>{if(!this.dispatchingProgress){this.dispatchingProgress=!0;try{this.recipients.forEach(n=>{n.onProgress?.(t)})}finally{this.dispatchingProgress=!1}}}}),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 B5=class extends Lt{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=EC(this.emitEmpty.bind(this),1),this.emitIdle=EC(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;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 R5;let n=new M5(e,t);this.enqueue(n),this.safeDispatchEvent("add");let o=n.join(t).then(s=>(this.safeDispatchEvent("completed",{detail:s}),this.safeDispatchEvent("success",{detail:{job:n,result:s}}),s)).catch(s=>{if(n.status==="queued"){for(let i=0;i<this.queue.length;i++)if(this.queue[i]===n){this.queue.splice(i,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:s}}),s});return this.tryToStartAnother(),o}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Tu)}),this.clear()}async onEmpty(e){this.size!==0&&await Bt(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await Bt(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await Bt(this,"idle",e)}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=Zo({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Tu("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};Ne();Xt();var pnt=Math.pow(2,7),mnt=Math.pow(2,14),gnt=Math.pow(2,21),KG=Math.pow(2,28),zG=Math.pow(2,35),$G=Math.pow(2,42),HG=Math.pow(2,49),tr=128,xo=127;function Tw(r){if(r<pnt)return 1;if(r<mnt)return 2;if(r<gnt)return 3;if(r<KG)return 4;if(r<zG)return 5;if(r<$G)return 6;if(r<HG)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function VG(r,e,t=0){switch(Tw(r)){case 8:e[t++]=r&255|tr,r/=128;case 7:e[t++]=r&255|tr,r/=128;case 6:e[t++]=r&255|tr,r/=128;case 5:e[t++]=r&255|tr,r/=128;case 4:e[t++]=r&255|tr,r>>>=7;case 3:e[t++]=r&255|tr,r>>>=7;case 2:e[t++]=r&255|tr,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function ynt(r,e){let t=r[e],n=0;if(n+=t&xo,t<tr||(t=r[e+1],n+=(t&xo)<<7,t<tr)||(t=r[e+2],n+=(t&xo)<<14,t<tr)||(t=r[e+3],n+=(t&xo)<<21,t<tr)||(t=r[e+4],n+=(t&xo)*KG,t<tr)||(t=r[e+5],n+=(t&xo)*zG,t<tr)||(t=r[e+6],n+=(t&xo)*$G,t<tr)||(t=r[e+7],n+=(t&xo)*HG,t<tr))return n;throw new RangeError("Could not decode varint")}function bnt(r,e){let t=r.get(e),n=0;if(n+=t&xo,t<tr||(t=r.get(e+1),n+=(t&xo)<<7,t<tr)||(t=r.get(e+2),n+=(t&xo)<<14,t<tr)||(t=r.get(e+3),n+=(t&xo)<<21,t<tr)||(t=r.get(e+4),n+=(t&xo)*KG,t<tr)||(t=r.get(e+5),n+=(t&xo)*zG,t<tr)||(t=r.get(e+6),n+=(t&xo)*$G,t<tr)||(t=r.get(e+7),n+=(t&xo)*HG,t<tr))return n;throw new RangeError("Could not decode varint")}function qG(r,e=0){return r instanceof Uint8Array?ynt(r,e):bnt(r,e)}Mr();me();Le();var qn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},_u=class extends Error{static name="ValidationError";name="ValidationError"},O5=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},N5=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var GG={};W(GG,{base64:()=>xnt,base64pad:()=>vnt,base64url:()=>jG,base64urlpad:()=>Ent});var xnt=yr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),vnt=yr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jG=yr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ent=yr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var WG={};W(WG,{base10:()=>Snt});var Snt=Nf({prefix:"9",name:"base10",alphabet:"0123456789"});var YG={};W(YG,{base16:()=>Cnt,base16upper:()=>Ant});var Cnt=yr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Ant=yr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var XG={};W(XG,{base2:()=>Int});var Int=yr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var ZG={};W(ZG,{base256emoji:()=>Pnt});var x1e=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}"),Tnt=x1e.reduce((r,e,t)=>(r[t]=e,r),[]),knt=x1e.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Dnt(r){return r.reduce((e,t)=>(e+=Tnt[t],e),"")}function _nt(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=knt[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Pnt=Ew({prefix:"\u{1F680}",name:"base256emoji",encode:Dnt,decode:_nt});var JG={};W(JG,{base8:()=>Rnt});var Rnt=yr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var QG={};W(QG,{identity:()=>Lnt});var Lnt=Ew({prefix:"\0",name:"identity",encode:r=>QSe(r),decode:r=>JSe(r)});var mTr=new TextEncoder,gTr=new TextDecoder;var v1e={...QG,...XG,...JG,...WG,...YG,...AG,...IG,...CG,...GG,...ZG},wTr={...LG,...DG};Mr();me();Le();function tW(r){return e=>z(e,r)}function rW(r){return e=>K(e,r)}function kw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function im(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function E1e(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=K(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 o=im(n);return Ye([t,o],t.length+o.length)}function S1e(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=Uf.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 o=im(n);return Ye([t,o],t.length+o.length)}function nW(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=z(e,"base32"),o=kw(t);return`${n}:${o}`}var oW=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new qn("Invalid byte value in IP address");e[n]=o}),e},C1e=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=kt(t[n]),i;s&&(i=oW(t[n]),t[n]=z(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,z(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new qn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},A1e=function(r){if(r.byteLength!==4)throw new qn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},I1e=function(r){if(r.byteLength!==16)throw new qn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new qn(`Invalid IPv6 address "${t}"`)}};function T1e(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new qn(`Invalid IPv6 address "${r}"`)}}var eW=Object.values(v1e).map(r=>r.decoder),Ont=(function(){let r=eW[0].or(eW[1]);return eW.slice(2).forEach(e=>r=r.or(e)),r})();function k1e(r){return Ont.decode(r)}function D1e(r){return e=>r.encoder.encode(e)}function Nnt(r){if(parseInt(r).toString()!==r)throw new _u("Value must be an integer")}function Unt(r){if(r<0)throw new _u("Value must be a positive integer, or zero")}function Fnt(r){return e=>{if(e>r)throw new _u(`Value must be smaller than or equal to ${r}`)}}function Knt(...r){return e=>{for(let t of r)t(e)}}var SC=Knt(Nnt,Unt,Fnt(65535));var hn=-1,sW=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 N5(`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)}))}},Pu=new sW,Iot=[{code:4,name:"ip4",size:32,valueToBytes:oW,bytesToValue:A1e,validate:r=>{if(!kt(r))throw new _u(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:273,name:"udp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:33,name:"dccp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:41,name:"ip6",size:128,valueToBytes:C1e,bytesToValue:I1e,stringToValue:T1e,validate:r=>{if(!rs(r))throw new _u(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:hn},{code:43,name:"ipcidr",size:8,bytesToValue:tW("base10"),valueToBytes:rW("base10")},{code:53,name:"dns",size:hn},{code:54,name:"dns4",size:hn},{code:55,name:"dns6",size:hn},{code:56,name:"dnsaddr",size:hn},{code:132,name:"sctp",size:16,valueToBytes:im,bytesToValue:kw,validate:SC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:hn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:hn,bytesToValue:tW("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?rW("base58btc")(r):Oc.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:nW,valueToBytes:E1e},{code:445,name:"onion3",size:296,bytesToValue:nW,valueToBytes:S1e},{code:446,name:"garlic64",size:hn},{code:447,name:"garlic32",size:hn},{code:448,name:"tls"},{code:449,name:"sni",size:hn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:hn,bytesToValue:D1e(jG),valueToBytes:k1e},{code:480,name:"http"},{code:481,name:"http-path",size:hn,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:hn}];Iot.forEach(r=>{Pu.addProtocol(r)});function _1e(r){let e=[],t=0;for(;t<r.length;){let n=qG(r,t),o=Pu.getProtocol(n),s=Tw(n),i=Tot(o,r,t+s),a=0;i>0&&o.size===hn&&(a=Tw(i));let c=s+a+i,l={code:n,name:o.name,bytes:_n(r.subarray(t,t+c))};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??z(d)}e.push(l),t+=c}return e}function P1e(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Pu.getProtocol(n.code),s=Tw(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??K(n.value),a=i.byteLength,o.size===hn&&(c=Tw(a)));let l=new Uint8Array(s+c+a),u=0;VG(n.code,l,u),u+=s,i!=null&&(o.size===hn&&(VG(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return Ye(t,e)}function R1e(r){if(r.charAt(0)!=="/")throw new qn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Pu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new qn(`Component ${o} 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 qn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new qn("Incomplete multiaddr");return e}function L1e(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Pu.getProtocol(e.code);if(t==null)throw new qn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Tot(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:qG(e,t)}var kot=Symbol.for("nodejs.util.inspect.custom"),iW=Symbol.for("@multiformats/multiaddr");function Dot(r){if(r==null&&(r="/"),M1e(r))return r.getComponents();if(r instanceof Uint8Array)return _1e(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),R1e(r);if(Array.isArray(r))return r;throw new qn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var F5=class r{[iW]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Dot(e),t.validate!==!1&&_ot(this)}get bytes(){return this.#r==null&&(this.#r=P1e(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=L1e(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new O5(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return ee(this.bytes,e.bytes)}[kot](){return`Multiaddr(${this.toString()})`}};function _ot(r){r.getComponents().forEach(e=>{let t=Pu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function M1e(r){return!!r?.[iW]}function B1e(r){return new F5(r)}si();ct();var Pot=4194304,K5=class extends Error{static name="UnwrappedError";name="UnwrappedError"},cW=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},lW=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},uW=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function Rot(r){return typeof r?.closeRead=="function"}function Lot(r){return typeof r?.close=="function"}function aW(r){return Rot(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:Lot(r)?r.status!=="open":!1}function Mot(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function Bot(r,e){let t=e?.maxBufferSize??Pot,n=new Y,o,s=!1;if(!Mot(r))throw new ku("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new K5("Stream was unwrapped");if(aW(r)){if(n.byteLength===0&&u?.bytes==null)return null;if(u?.bytes!=null&&n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new sm(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await qt(o.promise,u?.signal),aW(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(aW(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new sm(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,d){if(s===!0)throw new K5("Stream was unwrapped");r.send(u)||await Bt(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.unshift(n))),r}};return l}function Oot(r,e={}){let t=Bot(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=mt(e.maxDataLength));let n=e?.lengthDecoder??so,o=e?.lengthEncoder??oi;return{async read(i){let a=-1,c=new Y;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new cW("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new uW(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new lW(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new sm(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new sm(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new Y(o(i.byteLength),i),a)},async writeV(i,a){let c=new Y(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function dW(r,e){let t=Oot(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var z5=class extends B5{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function O1e(r,e,t){let n,o,s=!1;function i(){let l={signal:o.signal},u;t?.timeout!=null&&(u=Nn([o.signal,AbortSignal.timeout(t.timeout)]),l.signal=u),s=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{u!=null&&(u.aborted?u.clear():u.addEventListener("abort",()=>{u.clear()},{once:!0})),s=!1,!o.signal.aborted&&(n=setTimeout(i,e))})}let a=EC(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var fW=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 N1e(r){let{name:e,metrics:t}=r,n;return t!=null?n=new fW({name:e,metrics:t}):n=new Map,n}var U1e="libp2p",F1e="autonat",K1e="1.0.0";kn();var Ut;(function(r){let e;(function(h){h.DIAL="DIAL",h.DIAL_RESPONSE="DIAL_RESPONSE"})(e=r.MessageType||(r.MessageType={}));let t;(function(h){h[h.DIAL=0]="DIAL",h[h.DIAL_RESPONSE=1]="DIAL_RESPONSE"})(t||(t={})),(function(h){h.codec=()=>Pt(t)})(e=r.MessageType||(r.MessageType={}));let n;(function(h){h.OK="OK",h.E_DIAL_ERROR="E_DIAL_ERROR",h.E_DIAL_REFUSED="E_DIAL_REFUSED",h.E_BAD_REQUEST="E_BAD_REQUEST",h.E_INTERNAL_ERROR="E_INTERNAL_ERROR"})(n=r.ResponseStatus||(r.ResponseStatus={}));let o;(function(h){h[h.OK=0]="OK",h[h.E_DIAL_ERROR=100]="E_DIAL_ERROR",h[h.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",h[h.E_BAD_REQUEST=200]="E_BAD_REQUEST",h[h.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"})(o||(o={})),(function(h){h.codec=()=>Pt(o)})(n=r.ResponseStatus||(r.ResponseStatus={}));let s;(function(h){let p;h.codec=()=>(p==null&&(p=we((m,w,b={})=>{if(b.lengthDelimited!==!1&&w.fork(),m.id!=null&&(w.uint32(10),w.bytes(m.id)),m.addrs!=null&&m.addrs.length>0)for(let x of m.addrs)w.uint32(18),w.bytes(x);b.lengthDelimited!==!1&&w.ldelim()},(m,w,b={})=>{let x={addrs:[]},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{x.id=m.bytes();break}case 2:{if(b.limits?.addrs!=null&&x.addrs.length===b.limits.addrs)throw new lr('Decode error - repeated field "addrs" had too many elements');x.addrs.push(m.bytes());break}default:{m.skipType(T&7);break}}}return x},function*(m,w,b,x={}){let S={addrs:0},T=w==null?m.len:m.pos+w;for(;m.pos<T;){let A=m.uint32();switch(A>>>3){case 1:{yield{field:`${b}.id`,value:m.bytes()};break}case 2:{if(x.limits?.addrs!=null&&S.addrs===x.limits.addrs)throw new lr('Streaming decode error - repeated field "addrs" had too many elements');yield{field:`${b}.addrs[]`,index:S.addrs,value:m.bytes()},S.addrs++;break}default:{m.skipType(A&7);break}}}})),p);function f(m){return be(m,h.codec())}h.encode=f;function g(m,w){return ye(m,h.codec(),w)}h.decode=g;function y(m,w){return Ji(m,h.codec(),w)}h.stream=y})(s=r.PeerInfo||(r.PeerInfo={}));let i;(function(h){let p;h.codec=()=>(p==null&&(p=we((m,w,b={})=>{b.lengthDelimited!==!1&&w.fork(),m.peer!=null&&(w.uint32(10),r.PeerInfo.codec().encode(m.peer,w)),b.lengthDelimited!==!1&&w.ldelim()},(m,w,b={})=>{let x={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?x.peer=r.PeerInfo.codec().decode(m,m.uint32(),{limits:b.limits?.peer}):m.skipType(T&7)}return x},function*(m,w,b,x={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();T>>>3===1?yield*r.PeerInfo.codec().stream(m,m.uint32(),`${b}.peer`,{limits:x.limits?.peer}):m.skipType(T&7)}})),p);function f(m){return be(m,h.codec())}h.encode=f;function g(m,w){return ye(m,h.codec(),w)}h.decode=g;function y(m,w){return Ji(m,h.codec(),w)}h.stream=y})(i=r.Dial||(r.Dial={}));let a;(function(h){let p;h.codec=()=>(p==null&&(p=we((m,w,b={})=>{b.lengthDelimited!==!1&&w.fork(),m.status!=null&&(w.uint32(8),r.ResponseStatus.codec().encode(m.status,w)),m.statusText!=null&&(w.uint32(18),w.string(m.statusText)),m.addr!=null&&(w.uint32(26),w.bytes(m.addr)),b.lengthDelimited!==!1&&w.ldelim()},(m,w,b={})=>{let x={},S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{x.status=r.ResponseStatus.codec().decode(m);break}case 2:{x.statusText=m.string();break}case 3:{x.addr=m.bytes();break}default:{m.skipType(T&7);break}}}return x},function*(m,w,b,x={}){let S=w==null?m.len:m.pos+w;for(;m.pos<S;){let T=m.uint32();switch(T>>>3){case 1:{yield{field:`${b}.status`,value:r.ResponseStatus.codec().decode(m)};break}case 2:{yield{field:`${b}.statusText`,value:m.string()};break}case 3:{yield{field:`${b}.addr`,value:m.bytes()};break}default:{m.skipType(T&7);break}}}})),p);function f(m){return be(m,h.codec())}h.encode=f;function g(m,w){return ye(m,h.codec(),w)}h.decode=g;function y(m,w){return Ji(m,h.codec(),w)}h.stream=y})(a=r.DialResponse||(r.DialResponse={}));let c;r.codec=()=>(c==null&&(c=we((h,p,f={})=>{f.lengthDelimited!==!1&&p.fork(),h.type!=null&&(p.uint32(8),r.MessageType.codec().encode(h.type,p)),h.dial!=null&&(p.uint32(18),r.Dial.codec().encode(h.dial,p)),h.dialResponse!=null&&(p.uint32(26),r.DialResponse.codec().encode(h.dialResponse,p)),f.lengthDelimited!==!1&&p.ldelim()},(h,p,f={})=>{let g={},y=p==null?h.len:h.pos+p;for(;h.pos<y;){let m=h.uint32();switch(m>>>3){case 1:{g.type=r.MessageType.codec().decode(h);break}case 2:{g.dial=r.Dial.codec().decode(h,h.uint32(),{limits:f.limits?.dial});break}case 3:{g.dialResponse=r.DialResponse.codec().decode(h,h.uint32(),{limits:f.limits?.dialResponse});break}default:{h.skipType(m&7);break}}}return g},function*(h,p,f,g={}){let y=p==null?h.len:h.pos+p;for(;h.pos<y;){let m=h.uint32();switch(m>>>3){case 1:{yield{field:`${f}.type`,value:r.MessageType.codec().decode(h)};break}case 2:{yield*r.Dial.codec().stream(h,h.uint32(),`${f}.dial`,{limits:g.limits?.dial});break}case 3:{yield*r.DialResponse.codec().stream(h,h.uint32(),`${f}.dialResponse`,{limits:g.limits?.dialResponse});break}default:{h.skipType(m&7);break}}}})),c);function l(h){return be(h,r.codec())}r.encode=l;function u(h,p){return ye(h,r.codec(),p)}r.decode=u;function d(h,p){return Ji(h,r.codec(),p)}r.stream=d})(Ut||(Ut={}));var $ot=4,Hot=8,$5=class{components;protocol;timeout;maxInboundStreams;maxOutboundStreams;maxMessageSize;started;log;topologyId;dialResults;findPeers;addressFilter;connectionThreshold;constructor(e,t){this.components=e,this.log=e.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol=`/${t.protocolPrefix??U1e}/${F1e}/${K1e}`,this.timeout=t.timeout??3e4,this.maxInboundStreams=t.maxInboundStreams??2,this.maxOutboundStreams=t.maxOutboundStreams??20,this.connectionThreshold=t.connectionThreshold??80,this.maxMessageSize=t.maxMessageSize??8192,this.dialResults=N1e({name:"libp2p_autonat_dial_results",metrics:e.metrics}),this.findPeers=O1e(this.findRandomPeers.bind(this),6e4),this.addressFilter=NG(1024)}[Symbol.toStringTag]="@libp2p/autonat";[YSe]=["@libp2p/autonat"];get[XSe](){return["@libp2p/identify"]}isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(this.protocol,(e,t)=>{this.handleIncomingAutonatStream(e,t).catch(n=>{this.log.error("error handling incoming autonat stream - %e",n)})},{maxInboundStreams:this.maxInboundStreams,maxOutboundStreams:this.maxOutboundStreams}),this.topologyId=await this.components.registrar.register(this.protocol,{onConnect:(e,t)=>{this.verifyExternalAddresses(t).catch(n=>{this.log.error("could not verify addresses - %e",n)})}}),this.findPeers.start(),this.started=!0)}async stop(){await this.components.registrar.unhandle(this.protocol),this.topologyId!=null&&await this.components.registrar.unhandle(this.topologyId),this.dialResults.clear(),this.findPeers.stop(),this.started=!1}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every(e=>e.expires>Date.now()?!0:e.verified)}async findRandomPeers(e){if(this.allAddressesAreVerified())return;let t=Nn([AbortSignal.timeout(1e4),e?.signal]);try{this.log("starting random walk to find peers to run AutoNAT");for await(let n of this.components.randomWalk.walk({signal:t})){if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable %s",n.id,n.multiaddrs.map(o=>o.toString()).join(", "));continue}try{this.log.trace("dial random peer %p",n.id),await this.components.connectionManager.openConnection(n.multiaddrs,{signal:t})}catch{}if(this.allAddressesAreVerified()){this.log("stopping random walk, all addresses are verified");return}if(!this.hasConnectionCapacity()){this.log("stopping random walk, too close to max connections");return}}}catch{}}async handleIncomingAutonatStream(e,t){let n=AbortSignal.timeout(this.timeout);try{let o=dW(e,{maxDataLength:this.maxMessageSize}).pb(Ut),s=await o.read({signal:n}),i=await this.handleAutonatMessage(s,t,{signal:n});await o.write(i,{signal:n}),await e.close({signal:n})}catch(o){this.log.error("error handling incoming autonat stream - %e",o),e.abort(o)}}async handleAutonatMessage(e,t,n){let o=this.components.addressManager.getAddresses().map(d=>pa(d).host),s=e.dial;if(s==null)return this.log.error("dial was missing from message"),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};let i,a=s.peer;if(a?.id==null)return this.log.error("peerId missing from message"),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{let d=rm(a.id);i=k5(d)}catch(d){return this.log.error("invalid PeerId - %e",d),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(this.log("incoming request from %p",i),!t.remotePeer.equals(i))return this.log("target peer %p did not equal sending peer %p",i,t.remotePeer),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};let c=a.addrs.map(d=>B1e(d)).filter(d=>{try{let h=pa(d);return FG(d)?!1:h.host!==pa(t.remoteAddr).host?(this.log.trace("not dialing %a - target host did not match remote host %a",d,t.remoteAddr),!1):o.includes(h.host)?!1:this.components.transportManager.dialTransportForMultiaddr(d)==null?(this.log.trace("not dialing %a - transport unsupported",d),!1):!0}catch{return!1}}).map(d=>(d.getComponents().find(h=>h.code===421)?.value==null&&(d=d.encapsulate(`/p2p/${i.toString()}`)),d));if(c.length===0)return this.log("refused to dial all multiaddrs for %p from message",i),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};this.log("dial multiaddrs %s for peer %p",c.map(d=>d.toString()).join(", "),i);let l="",u=c[0];for(let d of c){let h;u=d;try{if(h=await this.components.connectionManager.openConnection(d,n),!h.remoteAddr.equals(d))throw this.log.error("tried to dial %a but dialed %a",d,h.remoteAddr),new Error("Unexpected remote address");return this.log("successfully dialed %p via %a",i,d),{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.OK,addr:h.remoteAddr.decapsulateCode(421).bytes}}}catch(p){this.log.error("could not dial %p - %e",i,p),l=p.message}finally{h!=null&&await h.close()}}return{type:Ut.MessageType.DIAL_RESPONSE,dialResponse:{status:Ut.ResponseStatus.E_DIAL_ERROR,statusText:l,addr:u.bytes}}}getFirstUnverifiedMultiaddr(e,t){let n=this.components.addressManager.getAddressesWithMetadata().sort((o,s)=>o.type==="observed"&&s.type!=="observed"?1:s.type==="observed"&&o.type!=="observed"?-1:0).filter(o=>!(!(o.expires<Date.now())||pa(o.multiaddr).type==="ip6"&&(!t||!y1e(o.multiaddr))||FG(o.multiaddr)));for(let o of n){let s=o.multiaddr.toString(),i=this.dialResults.get(s);if(i!=null){if(i.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",i.multiaddr,e);continue}if(i.queue.size>10){this.log.trace("%a already has enough peers queued",i.multiaddr);continue}}if(i==null){let a=o.expires<Date.now();if(a&&this.addressFilter.remove?.(s),this.addressFilter.has(s))continue;this.addressFilter.add(s),this.log.trace("creating dial result %s %s",a?"to revalidate":"for",s),i={multiaddr:o.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:BG(),queue:new z5({concurrency:3,maxSize:50}),type:o.type,lastVerified:o.lastVerified},this.dialResults.set(s,i)}return i}}removeOutdatedMultiaddrResults(){let e=new Set(this.components.addressManager.getAddressesWithMetadata().filter(({expires:t})=>t<Date.now()).map(({multiaddr:t})=>t.toString()));for(let t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}async verifyExternalAddresses(e){if(!this.isStarted())return;this.removeOutdatedMultiaddrResults();let n=(await this.components.peerStore.get(e.remotePeer)).addresses.some(({multiaddr:i})=>pa(i).type==="ip6"),o=this.getNetworkSegment(e.remoteAddr),s=this.getFirstUnverifiedMultiaddr(o,n);if(s==null){this.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",e.remotePeer);return}if(!this.hasConnectionCapacity()){s.lastVerified!=null?(this.log("automatically re-verifying %a because we are too close to the connection limit",s.multiaddr),this.confirmAddress(s)):this.log("skipping verifying %a because we are too close to the connection limit",s.multiaddr);return}s.queue.add(async i=>{await this.askPeerToVerify(e,o,i)},{peerId:e.remotePeer,multiaddr:s.multiaddr}).catch(i=>{s?.result==null&&this.log.error("error from %p verifying address %a - %e",e.remotePeer,s?.multiaddr,i)})}async askPeerToVerify(e,t,n){let o=this.dialResults.get(n.multiaddr.toString());if(o==null){this.log("%a was verified while %p was queued",n.multiaddr,e.remotePeer);return}let s=AbortSignal.timeout(this.timeout);this.log.trace("asking %a to verify multiaddr %s",e.remoteAddr,n.multiaddr);let i=await e.newStream(this.protocol,{signal:s});try{let a=dW(i).pb(Ut),[,c]=await Promise.all([a.write({type:Ut.MessageType.DIAL,dial:{peer:{id:this.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:s}),a.read({signal:s})]);if(c.type!==Ut.MessageType.DIAL_RESPONSE||c.dialResponse==null){this.log("invalid autonat response from %p - %j",e.remotePeer,c);return}let l=c.dialResponse.status;if(this.log.trace("autonat response from %p for %a is %s",e.remotePeer,n.multiaddr,l),l!==Ut.ResponseStatus.OK&&l!==Ut.ResponseStatus.E_DIAL_ERROR)return;if(o=this.dialResults.get(n.multiaddr.toString()),o==null){this.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,c.dialResponse.status);return}if(o.networkSegments.includes(t)){this.log.trace("%a results included network segment %s",n.multiaddr,t);return}if(o.result!=null){this.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,e.remotePeer);return}if(o.verifyingPeers.has(e.remotePeer)){this.log.trace("peer %p has already verified %a, ignoring response",e.remotePeer,n.multiaddr);return}if(o.verifyingPeers.add(e.remotePeer),o.networkSegments.push(t),l===Ut.ResponseStatus.OK){if(o.success++,o.type!=="observed"){this.confirmAddress(o);return}}else l===Ut.ResponseStatus.E_DIAL_ERROR&&o.failure++;this.log("%a success %d failure %d",o.multiaddr,o.success,o.failure),o.success===$ot&&this.confirmAddress(o),o.failure===Hot&&this.unconfirmAddress(o)}finally{try{await i.close({signal:s})}catch(a){i.abort(a)}}}hasConnectionCapacity(){let t=this.components.connectionManager.getConnections().length,n=this.components.connectionManager.getMaxConnections();return t/n*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){let t=pa(e);switch(t.type){case"ip4":return t.host.split(".")[0].padStart(3,"0");case"ip6":return t.host.split(":")[0].padStart(4,"0");default:throw new ku(`Remote address ${e} was not an IPv4 or Ipv6 address`)}}};function z1e(r={}){return e=>new $5(e,r)}se();Be();_s();var Vot="bootstrap",qot=50,jot=1e3,hW=class extends Lt{static tag="bootstrap";log;timer;list;timeout;components;_init;constructor(e,t={list:[]}){if(t.list==null||t.list.length===0)throw new Error("Bootstrap requires a list of peer addresses");super(),this.components=e,this.log=e.logger.forComponent("libp2p:bootstrap"),this.timeout=t.timeout??jot,this.list=t.list.map(n=>Pe(n)).filter(n=>MP.matches(n)?n.getComponents().findLast(s=>s.code===421)?.value==null?(this.log.error("invalid bootstrap multiaddr without peer id"),!1):!0:(this.log.error("invalid multiaddr %a",n),!1)).map(n=>({id:le(n.getComponents().findLast(o=>o.code===421)?.value??""),multiaddrs:[n]})),this._init=t}[jv]=this;[Symbol.toStringTag]="@libp2p/bootstrap";[In]=["@libp2p/peer-discovery"];isStarted(){return!!this.timer}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout(()=>{this._discoverBootstrapPeers().catch(e=>{this.log.error("failed to discover bootstrap peers - %e",e)})},this.timeout))}async _discoverBootstrapPeers(){if(this.timer!=null)for(let e of this.list){if(await this.components.peerStore.merge(e.id,{tags:{[this._init.tagName??Vot]:{value:this._init.tagValue??qot,ttl:this._init.tagTTL}},multiaddrs:e.multiaddrs}),this.timer==null)return;this.safeDispatchEvent("peer",{detail:e}),this.components.connectionManager.openConnection(e.id).catch(t=>{this.log.error("could not dial bootstrap peer %p - %e",e.id,t)})}}stop(){this.timer!=null&&clearTimeout(this.timer),this.timer=void 0}};function $1e(r){return e=>new hW(e,r)}var K6r=new Uint8Array(0);function H1e(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 Dw(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 Got(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var Wot=Got,Yot=Wot,V1e=Yot;var pW=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")}},mW=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 q1e(this,e)}},gW=class{decoders;constructor(e){this.decoders=e}or(e){return q1e(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 q1e(r,e){return new gW({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var yW=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new pW(e,t,n),this.decoder=new mW(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function j1e({name:r,prefix:e,encode:t,decode:n}){return new yW(r,e,t,n)}function _w({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=V1e(t,r);return j1e({prefix:e,name:r,encode:n,decode:s=>Dw(o(s))})}function Xot(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Zot(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Jot(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function Nc({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Jot(n);return j1e({prefix:e,name:r,encode(s){return Zot(s,n,t)},decode(s){return Xot(s,o,t,r)}})}var Ru=_w({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),G6r=_w({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var CC=Nc({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),X6r=Nc({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Z6r=Nc({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),J6r=Nc({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Q6r=Nc({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ekr=Nc({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tkr=Nc({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rkr=Nc({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),nkr=Nc({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var H5=_w({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ikr=_w({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Qot=Y1e,G1e=128,est=127,tst=~est,rst=Math.pow(2,31);function Y1e(r,e,t){e=e||[],t=t||0;for(var n=t;r>=rst;)e[t++]=r&255|G1e,r/=128;for(;r&tst;)e[t++]=r&255|G1e,r>>>=7;return e[t]=r|0,Y1e.bytes=t-n+1,e}var nst=bW,ost=128,W1e=127;function bW(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw bW.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&W1e)<<o:(i&W1e)*Math.pow(2,o),o+=7}while(i>=ost);return bW.bytes=s-n,t}var sst=Math.pow(2,7),ist=Math.pow(2,14),ast=Math.pow(2,21),cst=Math.pow(2,28),lst=Math.pow(2,35),ust=Math.pow(2,42),dst=Math.pow(2,49),fst=Math.pow(2,56),hst=Math.pow(2,63),pst=function(r){return r<sst?1:r<ist?2:r<ast?3:r<cst?4:r<lst?5:r<ust?6:r<dst?7:r<fst?8:r<hst?9:10},mst={encode:Qot,decode:nst,encodingLength:pst},gst=mst,AC=gst;function IC(r,e=0){return[AC.decode(r,e),AC.decode.bytes]}function Pw(r,e,t=0){return AC.encode(r,e,t),e}function Rw(r){return AC.encodingLength(r)}function V5(r,e){let t=e.byteLength,n=Rw(r),o=n+Rw(t),s=new Uint8Array(o+t);return Pw(r,s,0),Pw(t,s,n),s.set(e,o),new Lw(r,t,e,s)}function q5(r){let e=Dw(r),[t,n]=IC(e),[o,s]=IC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Lw(t,o,i,e)}function Z1e(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&H1e(r.bytes,t.bytes)}}var Lw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};function J1e(r,e){let{bytes:t,version:n}=r;return n===0?bst(t,xW(r),e??Ru.encoder):wst(t,xW(r),e??CC.encoder)}var Q1e=new WeakMap;function xW(r){let e=Q1e.get(r);if(e==null){let t=new Map;return Q1e.set(r,t),t}return e}var vW=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==TC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==xst)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=V5(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&&Z1e(e.multihash,n.multihash)}toString(e){return J1e(this,e)}toJSON(){return{"/":J1e(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??e2e(n,o,s.bytes))}else if(t[vst]===!0){let{version:n,multihash:o,code:s}=t,i=q5(o);return r.create(n,s,i)}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!==TC)throw new Error(`Version 0 CID must use dag-pb (code: ${TC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=e2e(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,TC,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,o=Dw(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Lw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=IC(e.subarray(t));return t+=h,d},o=n(),s=TC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=yst(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return xW(s).set(n,e),s}};function yst(r,e){switch(r[0]){case"Q":{let t=e??Ru;return[Ru.prefix,t.decode(`${Ru.prefix}${r}`)]}case Ru.prefix:{let t=e??Ru;return[Ru.prefix,t.decode(r)]}case CC.prefix:{let t=e??CC;return[CC.prefix,t.decode(r)]}case H5.prefix:{let t=e??H5;return[H5.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 bst(r,e,t){let{prefix:n}=t;if(n!==Ru.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function wst(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var TC=112,xst=18;function e2e(r,e,t){let n=Rw(r),o=n+Rw(e),s=new Uint8Array(o+t.byteLength);return Pw(r,s,0),Pw(e,s,n),s.set(t,o),s}var vst=Symbol.for("@ipld/js-cid/CID");kn();var Uc;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Uc||(Uc={}));var EW;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(EW||(EW={}));(function(r){r.codec=()=>Pt(EW)})(Uc||(Uc={}));var j5;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Uc.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Uc.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(j5||(j5={}));var SW;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Uc.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Uc.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(SW||(SW={}));var Sst=20;function AW({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new CW(r,e,t,n,o)}var CW=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Sst,this.maxDigestLength=s}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?t2e(n,this.code,t?.truncate):n.then(o=>t2e(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function t2e(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 V5(e,r)}function r2e(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Cst=AW({name:"sha2-256",code:18,encode:r2e("SHA-256")}),xkr=AW({name:"sha2-512",code:19,encode:r2e("SHA-512")});function n2e(r){return j5.encode({Type:Uc[r.type],Data:r.raw})}Be();_s();se();var IW=1e3,o2e=60*IW,s2e=15,i2e=120*o2e;var TW="circuit-relay-source",Ckr=`${Gv}-circuit-relay`,a2e=2*o2e,c2e=BigInt(1<<17),kW="/libp2p/circuit/relay/0.2.0/hop",l2e="/libp2p/circuit/relay/0.2.0/stop",u2e=30*IW,Akr=30*IW,d2e=300;kn();Xt();var rr;(function(r){let e;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Pt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=we((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Mw.codec().encode(o.peer,s)),o.reservation!=null&&(s.uint32(26),G5.codec().encode(o.reservation,s)),o.limit!=null&&(s.uint32(34),Bw.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(40),Dt.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Mw.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=G5.codec().decode(o,o.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=Bw.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=Dt.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>be(o,r.codec()),r.decode=(o,s)=>ye(o,r.codec(),s)})(rr||(rr={}));var kC;(function(r){let e;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Pt(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=we((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),Mw.codec().encode(o.peer,s)),o.limit!=null&&(s.uint32(26),Bw.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(32),Dt.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=Mw.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=Bw.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=Dt.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>be(o,r.codec()),r.decode=(o,s)=>ye(o,r.codec(),s)})(kC||(kC={}));var Mw;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={id:Oe(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.id=t.bytes();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new lr('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Mw||(Mw={}));var G5;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),W5.codec().encode(t.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.expire=t.uint64();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new lr('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}case 3:{s.voucher=W5.codec().decode(t,t.uint32(),{limits:o.limits?.voucher});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(G5||(G5={}));var Bw;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.duration=t.uint32();break}case 2:{s.data=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Bw||(Bw={}));var Dt;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Dt||(Dt={}));var DW;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(DW||(DW={}));(function(r){r.codec=()=>Pt(DW)})(Dt||(Dt={}));var Ow;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={relay:Oe(0),peer:Oe(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.relay=t.bytes();break}case 2:{s.peer=t.bytes();break}case 3:{s.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(Ow||(Ow={}));var W5;(function(r){let e;r.codec=()=>(e==null&&(e=we((t,n,o={})=>{o.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&&(n.uint32(26),Ow.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:Oe(0),payloadType:Oe(0),signature:Oe(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=Ow.codec().decode(t,t.uint32(),{limits:o.limits?.payload});break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>be(t,r.codec()),r.decode=(t,n)=>ye(t,r.codec(),n)})(W5||(W5={}));var Y5=class extends Error{constructor(e="Transfer limit error"){super(e),this.name="TransferLimitError"}},X5=class extends Error{constructor(e="Duration limit error"){super(e),this.name="DurationLimitError"}};function f2e(r,e,t){let n=e.remaining,o=s=>{let i=BigInt(s.data.byteLength);e.remaining-=i,e.remaining<0&&r.abort(new Y5(`data limit of ${n} bytes exceeded`))};r.addEventListener("message",o)}function h2e(r,e,t,n,o){function s(u){r.abort(u),e.abort(u)}let i=[t,n.signal];if(n.limit?.duration!=null){o.log("limiting relayed connection duration to %dms",n.limit.duration);let u=AbortSignal.timeout(n.limit.duration);i.push(u)}let a=Nn(i);let c;n.limit?.data!=null&&(c={remaining:n.limit.data});let l=()=>{let u;t.aborted?u=t.reason:u=new X5(`duration limit of ${n.limit?.duration} ms exceeded`),s(u)};a.addEventListener("abort",l,{once:!0}),c!=null&&(f2e(e,c,o),f2e(r,c,o)),ybe(r,e,r).catch(u=>{s(u)}).finally(()=>{a.clear()})}var Fkr=Et(rt(MP.matchers[0],vt(290))),Kkr=Et(vt(290));var _W=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"}};function p2e(r,e){let t=new _W(e?.errorMessage,e?.errorCode,e?.errorName),n=new AbortController,o=()=>{n.abort(t)},s=AbortSignal.timeout(r);s.addEventListener("abort",o);let i=n.signal;return i.reset=a=>{s?.removeEventListener("abort",o),s=AbortSignal.timeout(a??r),s.addEventListener("abort",()=>{n.abort(t)})},i.clear=()=>{s?.removeEventListener("abort",o),s=void 0},i}var Z5=class{reservations;maxReservations;applyDefaultLimit;reservationTtl;defaultDurationLimit;defaultDataLimit;log;constructor(e,t={}){this.log=e.logger.forComponent("libp2p:circuit-relay:server:reservation-store"),this.maxReservations=t.maxReservations??s2e,this.applyDefaultLimit=t.applyDefaultLimit!==!1,this.reservationTtl=t.reservationTtl??i2e,this.defaultDurationLimit=t.defaultDurationLimit??a2e,this.defaultDataLimit=t.defaultDataLimit??c2e,this.reservations=j1({metrics:e.metrics,name:"libp2p_circuit_relay_server_reservations_total"})}reserve(e,t,n){let o=this.reservations.get(e);if(this.reservations.size>=this.maxReservations&&o==null)return{status:Dt.RESERVATION_REFUSED};let s=new Date(Date.now()+this.reservationTtl),i;return this.applyDefaultLimit&&(i=n??{data:this.defaultDataLimit,duration:this.defaultDurationLimit}),o!=null?(this.log("refreshing reservation for client %p",e),o.signal.reset(this.reservationTtl)):(this.log("creating new reservation for client %p",e),o={addr:t,expiry:s,limit:i,signal:p2e(this.reservationTtl)}),this.reservations.set(e,o),o.signal.addEventListener("abort",()=>{this.reservations.delete(e)}),{status:Dt.OK,expire:Math.round(s.getTime()/1e3)}}removeReservation(e){this.reservations.delete(e)}get(e){return this.reservations.get(e)}clear(){this.reservations.clear()}};var J5=class r{domain="libp2p-relay-rsvp";codec=new Uint8Array([3,2]);relay;peer;expiration;constructor({relay:e,peer:t,expiration:n}){this.relay=e,this.peer=t,this.expiration=n}marshal(){return Ow.encode({relay:this.relay.toMultihash().bytes,peer:this.peer.toMultihash().bytes,expiration:BigInt(this.expiration)})}equals(e){return!(!(e instanceof r)||!this.peer.equals(e.peer)||!this.relay.equals(e.relay)||this.expiration!==e.expiration)}};var Ast={maxOutboundStopStreams:d2e},Q5=class extends Lt{components;reservationStore;started;hopTimeout;shutdownController;maxInboundHopStreams;maxOutboundHopStreams;maxOutboundStopStreams;log;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:server"),this.components=e,this.started=!1,this.hopTimeout=t?.hopTimeout??u2e,this.maxInboundHopStreams=t.maxInboundHopStreams,this.maxOutboundHopStreams=t.maxOutboundHopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??Ast.maxOutboundStopStreams,this.reservationStore=new Z5(e,t.reservations),this.shutdownController=new AbortController,this.shutdownController.signal,this.onHop=this.onHop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-server";isStarted(){return this.started}async start(){this.started||(await this.components.registrar.handle(kW,this.onHop,{maxInboundStreams:this.maxInboundHopStreams,maxOutboundStreams:this.maxOutboundHopStreams,runOnLimitedConnection:!0}),this.started=!0)}async stop(){this.reservationStore.clear(),this.shutdownController.abort(),await this.components.registrar.unhandle(kW),this.started=!1}async onHop(e,t){this.log("received circuit v2 hop protocol stream from %p",t.remotePeer);let n=AbortSignal.timeout(this.hopTimeout);let o={signal:n},s=su(e);try{let i=await s.pb(rr).read(o);if(i?.type==null)throw new Error("request was invalid, could not read from stream");this.log("received",i.type),await this.handleHopProtocol({connection:t,stream:s,request:i},o)}catch(i){this.log.error("error while handling hop - %e",i),await s.pb(rr).write({type:rr.Type.STATUS,status:Dt.MALFORMED_MESSAGE},o),e.abort(i)}}async handleHopProtocol({stream:e,request:t,connection:n},o){switch(this.log("received hop message"),t.type){case rr.Type.RESERVE:await this.handleReserve({stream:e,request:t,connection:n},o);break;case rr.Type.CONNECT:await this.handleConnect({stream:e,request:t,connection:n},o);break;default:this.log.error("invalid hop request type %s via peer %p",t.type,n.remotePeer),await e.pb(rr).write({type:rr.Type.STATUS,status:Dt.UNEXPECTED_MESSAGE})}}async handleReserve({stream:e,connection:t},n){let o=e.pb(rr);if(this.log("hop reserve request from %p",t.remotePeer),Ac.exactMatch(t.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",t.remotePeer),await o.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},n);return}if(await this.components.connectionGater.denyInboundRelayReservation?.(t.remotePeer)===!0){this.log.error("reservation for %p denied by connection gater",t.remotePeer),await o.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},n);return}let s=this.reservationStore.reserve(t.remotePeer,t.remoteAddr);try{if(s.status!==Dt.OK){await o.write({type:rr.Type.STATUS,status:s.status},n);return}if(s.expire!=null){let i=s.expire*1e3-Date.now();await this.components.peerStore.merge(t.remotePeer,{tags:{[TW]:{value:1,ttl:i}}},n)}await o.write({type:rr.Type.STATUS,status:Dt.OK,reservation:await this.makeReservation(t.remotePeer,BigInt(s.expire??0)),limit:this.reservationStore.get(t.remotePeer)?.limit},n),this.log("sent confirmation response to %s",t.remotePeer),await o.unwrap().unwrap().close(n)}catch(i){this.log.error("failed to send confirmation response to %p - %e",t.remotePeer,i),this.reservationStore.removeReservation(t.remotePeer);try{await this.components.peerStore.merge(t.remotePeer,{tags:{[TW]:void 0}},n)}catch(a){this.log.error("failed to untag relay source peer %p - %e",t.remotePeer,a)}}}async makeReservation(e,t){let n=[];for(let s of this.components.addressManager.getAddresses())s.toString().includes("/p2p-circuit")||n.push(s.bytes);let o=await Ho.seal(new J5({peer:e,relay:this.components.peerId,expiration:t}),this.components.privateKey);return{addrs:n,expire:t,voucher:{publicKey:n2e(o.publicKey),payloadType:o.payloadType,payload:{peer:e.toMultihash().bytes,relay:this.components.peerId.toMultihash().bytes,expiration:t},signature:o.signature}}}async handleConnect({stream:e,request:t,connection:n},o){let s=e.pb(rr);if(Ac.matches(n.remoteAddr)){this.log.error("relay reservation over circuit connection denied for peer: %p",n.remotePeer),await s.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},o);return}this.log("hop connect request from %p",n.remotePeer);let i;try{if(t.peer==null)throw this.log.error("no peer info in hop connect request"),new Error("no peer info in request");t.peer.addrs.forEach(Pe),i=El(q5(t.peer.id))}catch(d){this.log.error("invalid hop connect request via peer %p - %e",n.remotePeer,d),await s.write({type:rr.Type.STATUS,status:Dt.MALFORMED_MESSAGE},o);return}let a=this.reservationStore.get(i);if(a==null){this.log.error("hop connect denied for destination peer %p not having a reservation for %p with status %s",i,n.remotePeer,Dt.NO_RESERVATION),await s.write({type:rr.Type.STATUS,status:Dt.NO_RESERVATION},o);return}if(await this.components.connectionGater.denyOutboundRelayedConnection?.(n.remotePeer,i)===!0){this.log.error("hop connect for %p to %p denied by connection gater",n.remotePeer,i),await s.write({type:rr.Type.STATUS,status:Dt.PERMISSION_DENIED},o);return}let c=this.components.connectionManager.getConnections(i);if(c.length===0){this.log("hop connect denied for destination peer %p not having a connection for %p as there is no destination connection",i,n.remotePeer),await s.write({type:rr.Type.STATUS,status:Dt.NO_RESERVATION},o);return}let l=c[0],u=await this.stopHop({connection:l,request:{type:kC.Type.CONNECT,peer:{id:n.remotePeer.toMultihash().bytes,addrs:[]},limit:a?.limit}},o);if(u==null){this.log.error("failed to open stream to destination peer %p",l?.remotePeer),await s.write({type:rr.Type.STATUS,status:Dt.CONNECTION_FAILED},o);return}await s.write({type:rr.Type.STATUS,status:Dt.OK,limit:a?.limit},o),this.log("connection from %p to %p established - merging streams",n.remotePeer,i),h2e(e.unwrap(),u,this.shutdownController.signal,a,{log:this.log})}async stopHop({connection:e,request:t},n){this.log("starting circuit relay v2 stop request to %s",e.remotePeer);let o=await e.newStream(l2e,{maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0,...n}),s=su(o),i=s.pb(kC);await i.write(t,n);let a;try{a=await i.read(n)}catch(c){this.log.error("error parsing stop message response from %p - %e",e.remotePeer,c)}if(a==null){this.log.error("could not read response from %p",e.remotePeer),await o.close(n);return}if(a.status===Dt.OK)return this.log("stop request to %p was successful",e.remotePeer),s.unwrap();this.log("stop request failed with code %d",a.status),await o.close(n)}get reservations(){return this.reservationStore.reservations}};function m2e(r={}){return e=>new Q5(e,r)}Be();var e8=class{store=new Map;async get(e){return this.store.get(e)}async set(e,t){this.store.set(e,t)}async delete(e){this.store.delete(e)}async list(e){let t=[];for(let n of this.store.keys())n.startsWith(e)&&t.push(n);return t}};async function g2e(r,e,t,n=1e3){if(typeof r.listBlockIds!="function")return;let o=0;for await(let s of r.listBlockIds()){if(t())break;e.add(s),++o%n===0&&await new Promise(i=>setTimeout(i,0))}}function y2e(r,e){let t=Object.entries(e).filter(n=>n[1]!==void 0).filter(([,n])=>n.effectiveClusterSize!==r).map(([n,o])=>`${n} resolved ${o.effectiveClusterSize}`);if(t.length>0)throw new Error(`Cluster size mismatch at node startup: resolveClusterPolicy() produced clusterSize=${r}, but ${t.join(", ")}. Every cluster-size consumer must be constructed from the SAME resolved value (see cluster/cluster-policy.ts), or the membership admission gate's yardstick can diverge from the cohort width peer selection actually assembles.`)}Be();Uo();Le();var PW=class{components;running=!1;log;cfg;readyPromise=null;coordinatorCache=new Map;clusterCache=new Map;lastEstimate=null;reputation;libp2pRef;rebalanceMonitor;spreadOnChurnMonitor;constructor(e,t={}){this.components=e,this.log=te("network-manager"),this.cfg={clusterSize:t.clusterSize??1,seedKeys:t.seedKeys??[],estimation:t.estimation??{samples:8,kth:5,timeoutMs:1e3,ttlMs:6e4},readiness:t.readiness??{minPeers:1,maxWaitMs:2e3},cacheTTLs:t.cacheTTLs??{coordinatorMs:30*6e4,clusterMs:5*6e4},expectedRemotes:t.expectedRemotes??!1,allowClusterDownsize:t.allowClusterDownsize??!0,clusterSizeTolerance:t.clusterSizeTolerance??.5}}get effectiveClusterSize(){return this.cfg.clusterSize}setLibp2p(e){this.libp2pRef=e}setReputation(e){this.reputation=e}initRebalanceMonitor(e,t,n,o,s){let i=this.getLibp2p(),a=this.getFret();if(!i||!a)throw new Error("Cannot init RebalanceMonitor: libp2p or FRET not available");return this.rebalanceMonitor=new zD({libp2p:i,fret:a,partitionDetector:e,fretAdapter:t,trackedBlocks:n,keyNetwork:o,clusterSize:this.cfg.clusterSize},s),this.rebalanceMonitor}getRebalanceMonitor(){return this.rebalanceMonitor}initSpreadOnChurnMonitor(e,t,n,o,s,i,a){let c=this.getLibp2p(),l=this.getFret();if(!c||!l)throw new Error("Cannot init SpreadOnChurnMonitor: libp2p or FRET not available");return this.spreadOnChurnMonitor=new HD({libp2p:c,fret:l,partitionDetector:e,repo:t,peerNetwork:n,clusterSize:o,protocolPrefix:s,trackedBlocks:i},a),this.spreadOnChurnMonitor}getSpreadOnChurnMonitor(){return this.spreadOnChurnMonitor}getLibp2p(){return this.libp2pRef??this.components.libp2p}getFret(){let e=this.getLibp2p();if(e)return e.services?.fret}get[Symbol.toStringTag](){return"@libp2p/network-manager"}async start(){this.running||(this.running=!0)}async stop(){this.rebalanceMonitor&&await this.rebalanceMonitor.stop(),this.spreadOnChurnMonitor&&await this.spreadOnChurnMonitor.stop(),this.running=!1}async ready(){return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{let t=(await Promise.allSettled((this.cfg.seedKeys??[]).map(n=>this.seedKey(n)))).filter(n=>n.status==="rejected");t.length>0&&this.log("Failed to seed %d keys",t.length),await new Promise(n=>setTimeout(n,50))})(),this.readyPromise)}async seedKey(e){let t=this.getFret();if(!t)throw new Error("FRET service not available for seeding keys");let n=await Jt(e);t.getNeighbors(n,"both",1)}toCacheKey(e){return z(e,"base64url")}getKnownPeers(){let e=this.getLibp2p();if(!e)return[];let t=e.peerId,n=e.peerStore?.getPeers?.()??[],o=(e.getConnections?.()??[]).map(a=>a.remotePeer),s=[...n.map(a=>a.id),...o];return s.filter((a,c)=>s.findIndex(l=>l.toString()===a.toString())===c).filter(a=>a.toString()!==t.toString())}getStatus(){let e=this.getLibp2p();if(!e)return{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0};let n=(e.peerStore?.getPeers?.()??[]).filter(o=>o.id.toString()!==e.peerId.toString()).length;return n===0?{mode:this.cfg.expectedRemotes?"degraded":"alone",connections:0}:{mode:"healthy",connections:n}}async awaitHealthy(e,t){let n=Date.now();for(;Date.now()-n<t;){let s=this.getLibp2p();if(s){let i=s.getConnections?.()??[],a=new Set(i.map(c=>c.remotePeer.toString()));if(a.size>=e)return this.log("awaitHealthy: satisfied with %d connections",a.size),!0}await new Promise(i=>setTimeout(i,100))}let o=this.getLibp2p();if(o){let s=o.getConnections?.()??[],i=new Set(s.map(c=>c.remotePeer.toString())),a=i.size>=e;return this.log("awaitHealthy: timeout - %d connections (needed %d)",i.size,e),a}return!1}reportBadPeer(e,t=Qe.ConnectionFailure){this.reputation?.reportPeer(e.toString(),t)}isBlacklisted(e){return this.reputation?.isBanned(e.toString())??!1}recordCoordinator(e,t){let n=this.toCacheKey(e);this.coordinatorCache.set(n,{id:t,expires:Date.now()+this.cfg.cacheTTLs.coordinatorMs})}async findNearestPeerToKey(e){let t=this.getFret(),n=this.getLibp2p();if(!n)throw new Error("Libp2p not initialized");if(t){let a=await Jt(e),c=t.getNeighbors(a,"both",1);if(c.length>0){let l=c[0];if(l){let u=le(l);if(!this.isBlacklisted(u))return u}}}let o=(n.getConnections?.()??[]).map(a=>a.remotePeer),s=[n.peerId,...o,...this.getKnownPeers()].filter((a,c,l)=>l.findIndex(u=>u.toString()===a.toString())===c).filter(a=>!this.isBlacklisted(a));return s.length===0?n.peerId:s.reduce((a,c)=>this.lexLess(this.xor(a.toMultihash().bytes,e),this.xor(c.toMultihash().bytes,e))?a:c,s[0])}async getCluster(e){let t=this.toCacheKey(e),n=this.clusterCache.get(t);if(n&&n.expires>Date.now())return n.ids;let o=this.getFret(),s=this.getLibp2p();if(!s)throw new Error("Libp2p not initialized");if(o){let p=await Jt(e),f=o.getDiagnostics?.()??{},g=typeof f.estimate=="number"?f.estimate:typeof f.n=="number"?f.n:void 0,y=Math.max(1,Math.min(this.cfg.clusterSize,Number.isFinite(g)?g:this.cfg.clusterSize)),w=o.assembleCohort(p,y).map(b=>{try{return le(b)}catch(x){return this.log("Invalid peer ID in cohort: %s, %o",b,x),null}}).filter(b=>b!==null&&!this.isBlacklisted(b));if(w.length>0)return this.clusterCache.set(t,{ids:w,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),this.lastEstimate=g!=null?{estimate:g,samples:f.samples??0,updated:Date.now()}:this.lastEstimate,w}let i=await this.findNearestPeerToKey(e),a=i.toMultihash().bytes,c=(s.getConnections?.()??[]).map(p=>p.remotePeer),u=[i,s.peerId,...c,...this.getKnownPeers()].filter((p,f,g)=>!this.isBlacklisted(p)&&g.findIndex(y=>y.toString()===p.toString())===f).sort((p,f)=>this.lexLess(this.xor(p.toMultihash().bytes,a),this.xor(f.toMultihash().bytes,a))?-1:1),d=Math.min(this.cfg.clusterSize,u.length),h=u.slice(0,d);return this.clusterCache.set(t,{ids:h,expires:Date.now()+this.cfg.cacheTTLs.clusterMs}),h}async getCoordinator(e){let t=this.toCacheKey(e),n=this.coordinatorCache.get(t);if(n){if(n.expires>Date.now())return n.id;this.coordinatorCache.delete(t)}let o=await this.getCluster(e),s=this.getLibp2p();if(!s)throw new Error("Libp2p not initialized");let i=o.filter(a=>!this.isBlacklisted(a)).sort((a,c)=>(this.reputation?.getScore(a.toString())??0)-(this.reputation?.getScore(c.toString())??0))[0]??s.peerId;return this.recordCoordinator(e,i),i}xor(e,t){let n=Math.max(e.length,t.length),o=new Uint8Array(n);for(let s=0;s<n;s++){let i=e[e.length-1-s]??0,a=t[t.length-1-s]??0;o[n-1-s]=i^a}return o}lexLess(e,t){let n=Math.max(e.length,t.length);for(let o=0;o<n;o++){let s=e[o]??0,i=t[o]??0;if(s<i)return!0;if(s>i)return!1}return!1}};function b2e(r={}){return e=>new PW(e,r)}Be();var Lu=te("relay-reservation"),Ist="/p2p-circuit";function x2e(r){let e=[],t=[],n=new Set;for(let o of r){let s=Tst(o);if(s===void 0){e.push(o);continue}n.has(s.peerId)||(n.add(s.peerId),t.push(s),e.push(Ist))}return{listenAddrs:e,supervisedRelays:t}}function Tst(r){let e;try{e=Pe(r).getComponents()}catch{return}let t=e.filter(i=>i.name==="p2p-circuit").length,n=e[e.length-1],o=e[e.length-2];if(t!==1||n?.name!=="p2p-circuit"||o?.name!=="p2p"||o.value===void 0)return;let s;try{s=le(o.value).toString()}catch{return}return{dialAddr:Pe(e.slice(0,-1)).toString(),peerId:s}}function v2e(r){for(let e of kst(r)){let t=e.reservationStore;if(Dst(t))return{reservationStore:t}}return null}function kst(r){let e=r.components?.transportManager;if(typeof e?.getTransports!="function")return Lu.error("no transportManager.getTransports() on this node \u2014 libp2p internals moved?"),[];try{return e.getTransports()}catch(t){return Lu.error("transportManager.getTransports() threw: %o",t),[]}}function Dst(r){if(typeof r!="object"||r===null)return!1;let e=r;return typeof e.addRelay=="function"&&typeof e.hasReservation=="function"}function E2e(r,e){if(e.length!==0&&v2e(r)===null)throw new Error(`listen address names a relay (${e[0].dialAddr}) but the node has no circuit-relay transport \u2014 add circuitRelayTransport() to transports`)}function S2e(r,e){if(!(r.length===0||e===void 0||e.length===0))throw new Error(`listen address names a relay (${r[0].dialAddr}) but announceAddrs replaces the advertised address set, so the circuit address through it could never be advertised \u2014 drop announceAddrs or use appendAnnounceAddrs`)}function _st(r,e){let t=r.relayFilter;if(typeof t?.remove!="function")return!1;try{return t.remove(e.toMultihash().bytes)}catch(n){return Lu("could not clear the relayFilter entry for %s: %o",e.toString(),n),!1}}var Pst=1e4,Rst=5e3,Lst=1e3,Mst=3e4,Bst=100;function Ost(r,e,t={}){return new MW(r,e,t)}function C2e(r,e,t={}){let n=e.map(o=>Ost(r,o,t));return{supervisors:n,async awaitFirstDrives(){let s=(await Promise.all(n.map(async i=>({relay:i.relay,reason:await i.firstDrive})))).filter(i=>i.reason!==null);if(s.length!==0)throw new Error(s.map(i=>`could not reserve a circuit on relay ${i.relay.dialAddr}: ${i.reason}`).join("; "))},stop(){for(let o of n)o.stop()}}}var w2e=Symbol("relay-reservation-deadline-passed"),RW=r=>Math.max(0,r-Date.now()),LW=r=>r instanceof Error?r.message:String(r);function t8(r){r.unref?.()}function Nst(r){return new Promise(e=>{t8(setTimeout(e,r))})}var MW=class{node;relay;firstDrive;relayPeerId;driveTimeoutMs;checkMs;minBackoffMs;maxBackoffMs;pollMs;backoffMs;timer=null;stopped=!1;inFlight=!1;nextTickAtMs=null;failure=null;dialAbort=null;slotTakenLogged=!1;settleFirstDrive=()=>{};firstDriveSettled=!1;constructor(e,t,n){this.node=e,this.relay=t,this.relayPeerId=le(t.peerId),this.driveTimeoutMs=Math.max(1,n.driveTimeoutMs??Pst),this.checkMs=Math.max(1,n.checkMs??Rst),this.minBackoffMs=Math.max(1,n.minBackoffMs??Lst),this.maxBackoffMs=Math.max(this.minBackoffMs,n.maxBackoffMs??Mst),this.pollMs=Math.max(1,n.pollMs??Bst),this.backoffMs=this.minBackoffMs,this.firstDrive=new Promise(o=>{this.settleFirstDrive=o}),e.addEventListener("self:peer:update",this.onSelfPeerUpdate),e.addEventListener("peer:connect",this.onPeerConnect),this.tick("start")}get held(){return this.node.getMultiaddrs().some(e=>qU(e.toString(),this.relay.peerId,Lu))}get driving(){return this.inFlight}get retryAtMs(){return this.nextTickAtMs}get lastError(){return this.failure}stop(){this.stopped||(this.stopped=!0,this.clearTimer(),this.nextTickAtMs=null,this.node.removeEventListener("self:peer:update",this.onSelfPeerUpdate),this.node.removeEventListener("peer:connect",this.onPeerConnect),this.dialAbort?.abort(),this.settleFirst("the relay reservation supervisor was stopped before its first drive settled"))}onSelfPeerUpdate=()=>{this.wake("self:peer:update",!1)};onPeerConnect=e=>{e.detail.equals(this.relayPeerId)&&this.wake("peer:connect",!0)};wake(e,t){this.stopped||(t&&(this.backoffMs=this.minBackoffMs),!this.inFlight&&(this.clearTimer(),this.tick(e)))}async tick(e){if(!(this.stopped||this.inFlight)){if(this.nextTickAtMs=null,this.held){this.onHeld();return}if(await this.driveOnce(e),!this.stopped){if(this.held){this.onHeld();return}this.scheduleBackoff()}}}onHeld(){this.backoffMs=this.minBackoffMs,this.failure=null,this.slotTakenLogged=!1,this.settleFirst(null),this.schedule(this.checkMs)}async driveOnce(e){this.inFlight=!0,Lu("relay-reservation:drive relay=%s trigger=%s",this.relay.dialAddr,e);try{let t=await this.drive();if(this.stopped)return;this.failure=t,t===null?Lu("relay-reservation:held relay=%s",this.relay.dialAddr):Lu.error("relay-reservation:failed relay=%s reason=%s",this.relay.dialAddr,t)}catch(t){let n=LW(t);Lu.error("relay-reservation:drive-threw relay=%s err=%s",this.relay.dialAddr,n),this.stopped||(this.failure=n)}finally{this.inFlight=!1,this.stopped||this.settleFirst(this.failure)}}async drive(){let e=v2e(this.node);if(e===null)return"the node has no circuit-relay transport \u2014 add circuitRelayTransport() to transports";let t=Date.now()+this.driveTimeoutMs;_st(e.reservationStore,this.relayPeerId);let n=await this.dialRelay(t);if(n!==null)return n;if(this.stopped)return"stopped";let o=await this.requestReservation(e.reservationStore,t);return o!==null?o:await this.waitUntilHeld(t)?null:`relay ${this.relay.dialAddr} granted a reservation but no circuit address through it was published within ${this.driveTimeoutMs}ms`}async dialRelay(e){let t=new AbortController;this.dialAbort=t;let n=setTimeout(()=>t.abort(),RW(e));t8(n);try{return await this.node.dial(Pe(this.relay.dialAddr),{signal:t.signal}),null}catch(o){return`dial to relay ${this.relay.dialAddr} failed: ${LW(o)}`}finally{clearTimeout(n),this.dialAbort=null}}async requestReservation(e,t){let n,o=new Promise(s=>{n=setTimeout(()=>s(w2e),RW(t)),t8(n)});try{return await Promise.race([e.addRelay(this.relayPeerId,"discovered"),o])===w2e?`reservation request to relay ${this.relay.dialAddr} did not complete within ${this.driveTimeoutMs}ms`:null}catch(s){return this.describeReservationFailure(s)}finally{clearTimeout(n)}}describeReservationFailure(e){switch(e instanceof Error?e.name:""){case"HadEnoughRelaysError":{this.backoffMs=this.maxBackoffMs;let n=`this node's pending circuit slot is already filled by a reservation on another relay, so relay ${this.relay.dialAddr} was not asked; retrying every ${this.maxBackoffMs}ms until that reservation drops`;return this.slotTakenLogged||(this.slotTakenLogged=!0,Lu.error("relay-reservation:slot-taken relay=%s",this.relay.dialAddr)),n}case"UnsupportedProtocolError":return`the peer at ${this.relay.dialAddr} does not serve the circuit-relay hop protocol, so it is not a relay`;default:return`reservation request to relay ${this.relay.dialAddr} failed: ${LW(e)}`}}async waitUntilHeld(e){for(;;){if(this.held)return!0;if(this.stopped||Date.now()>=e)return!1;await Nst(Math.min(this.pollMs,RW(e)))}}scheduleBackoff(){let e=this.backoffMs;this.backoffMs=Math.min(this.backoffMs*2,this.maxBackoffMs),this.schedule(e)}schedule(e){this.stopped||(this.clearTimer(),this.nextTickAtMs=Date.now()+e,this.timer=setTimeout(()=>{this.timer=null,this.tick("timer")},e),t8(this.timer))}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}settleFirst(e){this.firstDriveSettled||(this.firstDriveSettled=!0,this.settleFirstDrive(e))}};Uo();Uo();var DC=te("ring-shift"),r8=class{deps;candidateMargin;inFlight=!1;constructor(e,t={}){this.deps=e,this.candidateMargin=t.candidateMargin??2}async executeShift(e){if(this.inFlight)return{status:"skipped",reason:"shift-in-flight"};let t=this.deps.fretAdapter.getMyArachnodeInfo();if(t?.status==="moving")return{status:"skipped",reason:"already-moving"};this.inFlight=!0;try{return e.direction==="out"?await this.moveOut(e.newRingDepth,t):await this.moveIn(e.newRingDepth,t)}finally{this.inFlight=!1}}reconcileOnStart(){let e=this.deps.fretAdapter.getMyArachnodeInfo();return!e||e.status!=="moving"?{reconciled:!1}:(this.deps.fretAdapter.setArachnodeInfo(e.moveFrom?this.clearMove({...e,ringDepth:e.moveFrom.ringDepth,partition:e.moveFrom.partition,status:"active"}):this.clearMove({...e,status:"active"})),DC("reconcile:resumed-old-range ring=%d",e.moveFrom?.ringDepth??e.ringDepth),{reconciled:!0})}async moveOut(e,t){let n=t?.ringDepth??0,o=await this.deps.ringSelector.createArachnodeInfo(this.deps.selfPeerId,e),s={...o,status:"moving",moveFrom:{ringDepth:n,partition:t?.partition}};this.deps.fretAdapter.setArachnodeInfo(s),DC("phaseA:advertise from=%d to=%d",n,e);let i=await this.computeShedBlocks(t?.partition,o.partition),a=Math.max(1,this.deps.getFloor()),c=await this.confirmShedRange(i,a);return c.ok?(this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...o,status:"active"})),i.length>0&&this.deps.onRelease(i),DC("phaseC:release from=%d to=%d shed=%d",n,e,i.length),{status:"moved-out",from:n,to:e,released:i}):(this.rollback(t),DC("phaseB:abort reason=%s \u2192 rolled-back to ring=%d",c.reason,n),{status:"rolled-back",ring:n,reason:c.reason})}async confirmShedRange(e,t){if(e.length===0)return{ok:!0};if(this.deps.partitionDetector.detectPartition())return{ok:!1,reason:"partition"};let n=await this.buildOwnersMap(e,t),{confirmed:o,unconfirmed:s}=await this.deps.confirmer.confirmReplicated(e,n,t);return s.length>0?{ok:!1,reason:`unconfirmed:${s.length}`}:o.length===e.length?{ok:!0}:{ok:!1,reason:"incomplete"}}async computeShedBlocks(e,t){let n=[];for(let o of this.deps.ownedBlocks){let s=await Jt(He(o));Zb(e,s)&&!Zb(t,s)&&n.push(o)}return n}async buildOwnersMap(e,t){let n=new Map,o=t+1+this.candidateMargin;for(let s of e){let i=await Jt(He(s)),c=this.deps.fret.assembleCohort(i,o).filter(l=>{if(l===this.deps.selfPeerId)return!1;let u=this.deps.fretAdapter.getArachnodeInfo(l);return u!==void 0&&Oge(u,i)});n.set(s,c)}return n}async moveIn(e,t){let n=t?.ringDepth??0,o=await this.deps.ringSelector.createArachnodeInfo(this.deps.selfPeerId,e);return this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...o,status:"active"})),DC("moveIn:advertise from=%d to=%d",n,e),{status:"moved-in",from:n,to:e}}rollback(e){if(e){this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...e,status:"active"}));return}let t=this.deps.fretAdapter.getMyArachnodeInfo();t?this.deps.fretAdapter.setArachnodeInfo(this.clearMove({...t,ringDepth:0,partition:void 0,status:"active"})):this.deps.fretAdapter.setStatus("active")}clearMove(e){let{moveFrom:t,...n}=e;return n}};Uo();Be();Uo();var jt=512*1024;async function Mu(r,e,t,n,o=jt){let s;try{s=await E1(r,e,t),is(s,n),await s.close();let i=await fo(s,o);return i.length===0?void 0:i}finally{if(s!=null)try{await s.close()}catch{}}}var _C=class extends Error{constructor(e){super(`${e}: peer replied with no result (zero-length reply frame)`),this.name="NoResultReplyError"}};function PC(r,e){if(r===void 0)throw new _C(e);return r}async function n8(r,e,t,n){let o;try{o=await E1(r,e,t),is(o,n),await o.close()}finally{if(o!=null)try{await o.close()}catch{}}}function o8(r,e,t,n=jt){Ar(r,e,(o,s)=>{(async()=>{try{let i=await fo(o,n),a=await t(i,s.remotePeer);is(o,a??new Uint8Array(0)),await o.close()}catch{try{o.abort(new Error("cohort-topic stream handler error"))}catch{}}})()})}var RC="/optimystic/cohort-topic/1.0.0",BW=`${RC}/register`,OW=`${RC}/cohort-gossip`,Ust=`${RC}/promote`,NW=`${RC}/membership`,Fst=`${RC}/sign`,UW={register:BW,gossip:OW,promote:Ust,membership:NW,sign:Fst};function A2e(r){return[r.register,r.gossip,r.promote,r.membership,r.sign]}function Kst(r){return typeof r=="object"&&r!==null&&"commitCertificate"in r}var s8=class{node;fret;registerProtocol;ttl;maxBytes;clock;constructor(e,t,n={}){this.node=e,this.fret=t,this.registerProtocol=n.registerProtocol??BW,this.ttl=n.ttl??16,this.maxBytes=n.maxBytes??jt,this.clock=n.clock??(()=>Date.now())}async routeAndAct(e,t,n){let o=this.clock(),s={v:1,key:V(e),want_k:n.wantK,min_sigs:n.minSigs,ttl:this.ttl,activity:V(t),correlation_id:V(e)+":"+o,timestamp:o,signature:""},i=await this.fret.routeAct(s);return Kst(i)?j(i.commitCertificate):it({v:1,result:"no_state"},this.maxBytes)}async dialMember(e,t){let n=ice(e.id),o=await Mu(this.node,n,this.registerProtocol,t,this.maxBytes);return PC(o,"cohort-topic register dial")}};Be();var i8=class{node;resolver;handlers=new Set;gossipProtocol;wants;selfPeerId;constructor(e,t,n){this.node=e,this.resolver=t,this.gossipProtocol=n.gossipProtocol??OW,this.wants=n.wants??16,this.selfPeerId=n.selfPeerId}broadcast(e,t){this.broadcastOver(this.gossipProtocol,e,t)}broadcastOver(e,t,n){for(let o of this.resolver.cohortPeers(t,this.wants))o!==this.selfPeerId&&n8(this.node,le(o),e,n).catch(()=>{})}onMessage(e){return this.handlers.add(e),()=>this.handlers.delete(e)}get subscriberCount(){return this.handlers.size}deliver(e,t){let n={id:Ms(e)};for(let o of this.handlers)o(n,t)}};var a8=5e3,I2e=3e4;function T2e(){let r=new Map,e=new Map,t=new Map,n=(i,a)=>`${V(i)}|${V(a)}`,o=(i,a)=>`${V(i)}|${V(a)}`,s=(i,a,c,l)=>{let u=o(i,a),d=t.get(u);d!==void 0&&c<d.ref.effectiveAt||t.set(u,{ref:{topicId:V(i),childCohortCoord:V(a),effectiveAt:c},linked:l})};return{touch(i){let a=n(i.topicId,i.participantId),c=r.get(a);(c===void 0||i.lastPing>=c.lastPing)&&r.set(a,i),e.delete(a)},evicted(i){let a=n(i.topicId,i.participantId);e.set(a,{topicId:V(i.topicId),participantId:V(i.participantId),lastPing:i.lastPing}),r.delete(a)},childLink(i,a,c){s(i,a,c,!0)},childUnlink(i,a,c){s(i,a,c,!1)},isEmpty(){return r.size===0&&e.size===0&&t.size===0},drain(){let i=[],a=[];for(let l of t.values())(l.linked?i:a).push(l.ref);let c={records:[...r.values()].map(Xte),evicted:[...e.values()],childLinks:i,childUnlinks:a};return r.clear(),e.clear(),t.clear(),c}}}function k2e(r){let e=nre(r.profile,r.barometer);if(r.topicSummaries.length===0&&r.records.length===0&&r.evicted.length===0&&r.childLinks.length===0&&r.childUnlinks.length===0&&!(r.heartbeat&&e!==0))return;let n={v:1,fromMember:r.fromMember,coord:r.coord,cohortEpoch:r.cohortEpoch,treeTier:r.treeTier,willingnessBits:rre(e),loadBuckets:r.barometer.loadBuckets(),windowSeconds:r.windowSeconds,topicSummaries:r.topicSummaries,timestamp:r.timestamp,signature:""};return r.records.length>0&&(n.records=r.records),r.evicted.length>0&&(n.evicted=r.evicted),r.childLinks.length>0&&(n.childLinks=r.childLinks),r.childUnlinks.length>0&&(n.childUnlinks=r.childUnlinks),n}Be();var c8=class{node;resolver;byCoord=new Map;membershipProtocol;wants;maxBytes;constructor(e,t,n={}){this.node=e,this.resolver=t,this.membershipProtocol=n.membershipProtocol??NW,this.wants=n.wants??16,this.maxBytes=n.maxBytes??jt}current(e){return Promise.resolve(this.byCoord.get(V(e)))}has(e){return this.byCoord.has(V(e))}async fetch(e){let t=e;for(let n of this.resolver.cohortPeers(e,this.wants))try{let o=await Mu(this.node,le(n),this.membershipProtocol,t,this.maxBytes);if(o!==void 0)return this.cache(e,o),o}catch{}}cache(e,t){this.byCoord.set(V(e),t)}};var l8=class{latestCert;publish(e){this.latestCert=e}latest(){return this.latestCert}};var Kf=64,zst=5e3;function D2e(r,e,t){if(t.length===0||e.length!==t.length*Kf)return!1;for(let n=0;n<t.length;n++){let o=e.subarray(n*Kf,(n+1)*Kf);if(!Bo(t[n],r,o))return!1}return!0}var LC=class{deps;constructor(e){this.deps=e}async assemble(e,t){let n=new Map,o=Zt(this.deps.selfMember);if(this.deps.selfEligible?.()??!0){let l=await Bs(this.deps.privateKey,e);if(l.length!==Kf)throw new Error(`cohort threshold sign: self produced a ${l.length}-byte signature (expected ${Kf}); non-Ed25519 identity?`);n.set(V(this.deps.selfMember),{signer:this.deps.selfMember,sig:l})}let s=this.deps.cohortMembers().filter(l=>l!==o);if(s.length>0&&n.size<t){let l={v:1,kind:this.deps.kind,coord:V(this.deps.coord()),cohortEpoch:V(this.deps.cohortEpoch()),payload:V(e)},u=this.deps.collectTimeoutMs??zst;await Promise.all(s.map(d=>this.collectFrom(d,l,e,n,u)))}if(n.size<t)throw new Error(`cohort threshold sign: gathered ${n.size} of ${t} required signatures`);let i=[...n.values()].sort((l,u)=>wg(l.signer,u.signer)),a=i.map(l=>l.signer);return{thresholdSig:$st(i.map(l=>l.sig)),signers:a}}verify(e,t,n){return D2e(e,t,n)}async collectFrom(e,t,n,o,s){try{let i=await Hst(this.deps.dialSign(e,t),s);if(i===void 0||"refused"in i)return;let a=j(i.signer),c=j(i.signature);if(c.length!==Kf||!Bo(a,n,c))return;let l=V(a);if(o.has(l))return;o.set(l,{signer:a,sig:c})}catch{}}};function FW(){return{assemble:()=>Promise.reject(new Error("verify-only cohort threshold crypto cannot assemble signatures")),verify:D2e}}function $st(r){let e=new Uint8Array(r.length*Kf);for(let t=0;t<r.length;t++)e.set(r[t],t*Kf);return e}function Hst(r,e){return new Promise(t=>{let n=!1,o=setTimeout(()=>{n||(n=!0,t(void 0))},e);r.then(s=>{n||(n=!0,clearTimeout(o),t(s))},()=>{n||(n=!0,clearTimeout(o),t(void 0))})})}var Vst=2,u8=class{fret;k;selfPeerId;churnSlack;maxCommittedTier;constructor(e,t){this.fret=e,this.k=t.k,this.selfPeerId=t.selfPeerId,this.churnSlack=t.churnSlack??Vst,this.maxCommittedTier=t.maxCommittedTier??ol}directAnchor(e,t){if(t<=this.maxCommittedTier)return"unknown";try{if(this.fret.detectPartition?.()===!0)return"unknown";let n=j(e.cohortCoord),o=this.fret.assembleCohort(n,this.k);if(o.length<this.k||!o.includes(this.selfPeerId))return"unknown";let s=new Set(this.fret.assembleCohort(n,this.k+this.churnSlack)),i=e.signers.map(c=>Zt(j(c)));if(i.length===0)return"unknown";let a=0;for(let c of i)s.has(c)&&a++;return a===i.length?"anchored":a===0?"rejected":"unknown"}catch{return"unknown"}}};var MC=class{fret;constructor(e){this.fret=e}estimate(){let{size_estimate:e,confidence:t}=this.fret.getNetworkSizeEstimate();return{nEst:e,confidence:t}}};var qst=oS.deprioritize;function _2e(r){let e=r.bits??OI;return t=>{try{let n=Tv(t);if(n?.pow===void 0)return!1;let o=j(n.pow.nonce);return UI(r.hash.H(NI(t,o)),e)}catch{return!1}}}function P2e(r){let e=r.deprioritizeThreshold??qst;return t=>{try{let n=Tv(t);if(n?.reputation===void 0)return!1;let o=j(n.reputation.referee),s=j(n.reputation.sig);if(!Bo(o,Cg(t),s))return!1;let i=Zt(o);return!r.reputation.isBanned(i)&&r.reputation.getScore(i)<e}catch{return!1}}}function R2e(r){let{parentTopicView:e}=r;return t=>{try{let n=Tv(t);if(n?.parentRef===void 0)return!1;let{parentTopicId:o,sig:s}=n.parentRef;if(o===t.topicId)return!1;let i=bre(t,o);return Bo(j(t.participantCoord),i,j(s))?e.exists(j(o),t.tier):!1}catch{return!1}}}function L2e(r){let{membershipSource:e,addressing:t,committedReader:n}=r,o=r.maxNoPowTier??ol;return{exists(s,i){let a=t.coord0(s);return i<=o?n!==void 0&&n(a):e.has(a)}}}var jst=1<<24;function B2e(r){let e=r.bits??OI,t=r.maxNoPowTier??ol,n=r.maxIterations??jst;return async o=>{let s={topicId:o.topicId,tier:o.tier,participantCoord:o.participantCoord,timestamp:o.timestamp};if(o.tier<=t){if(r.endorse===void 0)return;let i=await r.endorse(Cg(s));return M2e({v:1,reputation:i})}for(let i=0;i<n;i++){let a=_6(16);if(UI(r.hash.H(NI(s,a)),e))return M2e({v:1,pow:{nonce:V(a)}})}}}function M2e(r){return j(fB(r))}var ms=te("cohort-topic");async function z2e(r,e,t={}){let n=t.profile??Rte(),o=t.protocols??UW,s=t.wantK??16,i=t.minSigs??Sv,a=t.fanout??16,c=t.maxBytes??jt,l=t.gossipIntervalMs??a8,u=t.willingnessHeartbeatMs??I2e,d=new gg,h=r.peerId.toString(),p=Ms(r.peerId),f=await Or(r.peerId),g=$i(d,a),y={cohortPeers(ce,Ke){return e.assembleCohort(ce,Ke)}},m=new s8(r,e,{registerProtocol:o.register,maxBytes:c}),w=new MC(e),b=new i8(r,y,{gossipProtocol:o.gossip,wants:s,selfPeerId:h}),x=new c8(r,y,{membershipProtocol:o.membership,wants:s,maxBytes:c}),S=new l8,T=Kte(d),A=QM(),v=Cv(FW(),i),C=async(ce,Ke)=>{let _e=await Mu(r,le(ce),o.sign,it(Ke,c),c);return SI(Yt(PC(_e,"cohort sign"),c))},P=ce=>{let Ke=e.assembleCohort(ce,s),_e=[p,...Ke.filter(bt=>bt!==h).map(bt=>Ms(bt))],yt=_e.map(V).sort().join("|"),xn=d.H(new TextEncoder().encode(yt));return{members:_e,cohortEpoch:xn}},F=Gst(t.privateKey,ms),R=t.privateKey===void 0?void 0:ce=>ce.signature.length>0&&Bo(j(ce.participantCoord),AI(ce),j(ce.signature)),k=t.privateKey===void 0?void 0:ce=>ce.signature.length>0&&Bo(j(ce.participantId),LM(ce),j(ce.signature)),I=t.privateKey,E=I===void 0?void 0:async ce=>V(await Bs(I,MM(ce))),D=I===void 0?void 0:(ce,Ke)=>{if(ce.signature.length===0)return!1;let _e=j(ce.fromMember);return Bo(_e,MM(ce),j(ce.signature))?P(Ke).members.map(Zt).includes(Zt(_e)):!1},M=iit(t.antiDos?.rateLimiter),B=(ce,Ke)=>{q2e(M,ce);let _e=it(ce,c);for(let yt of dit(ce,Ke))b.broadcastOver(o.promote,yt,_e)},L=t.antiDos?.parentTopicView??L2e({membershipSource:x,addressing:g,committedReader:t.committedParentTopicReader}),O=t.antiDos?.parentTopicView!==void 0||t.committedParentTopicReader!==void 0,U=Wst(t.antiDos,d,ms,L,O),$={hash:d,addressing:g,slots:T,barometer:A,transport:b,profile:n,selfMemberBytes:p,wantK:s,minSigs:i,maxBytes:c,willingnessHeartbeatMs:u,publishSink:S,privateKey:t.privateKey,router:m,antiDos:{rateLimiter:t.antiDos?.rateLimiter,replayGuard:t.antiDos?.replayGuard,topicBudget:t.antiDos?.topicBudget},bootstrapEvidence:U,promotionConfig:t.promotion,dialSign:C,cohortAround:P,verifyRegisterSig:R,verifyParticipantSig:k,signGossip:E,verifyGossip:D,broadcastNotice:B,onCertPublished:ce=>Fe.cache(ce),onEngineEvicted:ce=>Fe.forget(V(ce)),adoptedTransition:(ce,Ke,_e)=>M.transitions.get(H2e(V(ce),Ke,V(_e)))},J=Jst($,t.antiDos?.coordEnginesMax),X=ce=>{if(D===void 0)return;let Ke;try{Ke=CI(ce,c)}catch{return}if(Ke.treeTier!==0)return;let _e=j(Ke.coord);if(J.findByCoord(_e)===void 0&&D(Ke,_e))try{J.forCoord(_e,Ke.treeTier,p)}catch(yt){if(yt instanceof Nw)return;throw yt}},N=(ce,Ke)=>oit(ce,Ke,{privateKey:t.privateKey,selfMember:p,cohortMembersAround:_e=>P(_e).members.map(Zt),currentEpoch:_e=>P(_e).cohortEpoch,priorCohortMembersAt:(_e,yt)=>J.findByCoord(_e)?.cohortIdentityAt(yt),expectedMembershipFields:_e=>{let yt=P(_e),{cohortCoord:xn,cohortEpoch:bt,members:Ft}=RI({coord:_e,cohortEpoch:yt.cohortEpoch,members:yt.members,stabilizedAt:0});return{cohortCoord:xn,cohortEpoch:bt,members:Ft}},now:t.now??(()=>Date.now())}),H=OM(),Z=jM({transport:b,store:H,coord:f,localEpoch:()=>P(f).cohortEpoch,verifyInbound:D===void 0?void 0:ce=>D(ce,f)}),ae=x,Q=Qte({committed:ae,fret:ae}),oe=new u8(e,{k:s,selfPeerId:h}),Fe=ere({signer:v,router:Q,minSigs:i,anchor:oe,trustRoots:t.genesisTrustRoots??[]}),nr=B2e({hash:d,bits:t.antiDos?.powDifficultyBits}),fe=xre({self:p,hash:d,router:m,sizeEstimator:w,signer:F,gossipBus:Z,verifier:Fe,buildBootstrapEvidence:nr,config:{fanout:a,wantK:s,minSigs:i,maxMessageBytes:c}}),Ce=async(ce,Ke,_e)=>{let yt=j(ce.topicId),xn=j(ce.participantCoord),bt=g.coord(ce.treeTier,xn,yt),Ft;try{Ft=J.forCoord(bt,ce.treeTier,xn)}catch(Es){if(Es instanceof Nw)return ms("cohort-topic: register refused \u2014 coord-engine registry full"),{v:1,result:"unwilling_cohort",retryAfterMs:MI,reason:"coord-engine registry full"};throw Es}Ke!==void 0&&fit(e,s,bt,Ke);let nh=ce.treeTier>0?g.coord(ce.treeTier-1,xn,yt):void 0,Rr=ce.followOn===!0;return Ft.engine.handleRegister(ce,{followOn:Rr,treeTier:ce.treeTier,parentCoord:nh},_e)},Ve=t.privateKey===void 0?void 0:async(ce,Ke)=>{if(ce.thresholdSig.length===0)return!1;let _e,yt;try{_e=ce.signers.map(j),yt=j(ce.thresholdSig)}catch{return!1}return await Fe.verifyMessage(_e,j(ce.childCohortCoord),ce.childTier,GM(ce),yt,{minRefetchIntervalMs:d8,now:Ke})==="verified"},Er={coord:(ce,Ke,_e)=>g.coord(ce,Ke,_e),resolveParent:(ce,Ke,_e)=>J.forCoord(ce,Ke,_e),verifyChildLinkSig:Ve};await git(r,o,J,Ce,Er,i,N,Fe,M,b,X,S,x,f,c),e.setActivityHandler(async(ce,Ke)=>{let _e=Yt(j(ce),c),yt=BC(()=>vv(_e,i)),xn=yt!==void 0?await $2e(yt,Er,Date.now()):await Ce(xv(_e),Ke,Date.now());return{commitCertificate:V(it(xn,c))}});let Rt=!1,Sr=!1,or=async()=>{if(!(Rt||Sr)){Sr=!0;try{let ce=Date.now();for(let Ke of J.all()){if(Rt)break;try{await Ke.gossipRound(ce),await Ke.pumpMembership(ce),await Ke.demotionTick(ce)}catch(_e){ms("cohort-topic: gossip tick failed for a coord engine: %o",_e)}}M.rateLimiter.sweep(ce)}finally{Sr=!1}}},Co=setInterval(()=>{or()},l);return Co.unref?.(),{service:fe,registry:J,protocols:o,profile:n,gossipTransport:b,promoteGate:M,membershipSource:x,stop:async()=>{Rt=!0,clearInterval(Co),J.close(),Z.close(),await r.unhandle(A2e(o))}}}function Gst(r,e){if(r===void 0){let t=!1,n=()=>{t||(t=!0,e("no privateKey supplied to createCohortTopicHost; participant RegisterV1/RenewV1 bodies are UNSIGNED (interim \u2014 supply options.privateKey for peer-key signing)"))};return{signRegister:()=>(n(),Promise.resolve("")),signRenew:()=>(n(),Promise.resolve(""))}}return{signRegister:async t=>V(await Bs(r,AI(t))),signRenew:async t=>V(await Bs(r,LM(t)))}}function Wst(r,e,t,n,o){let s=r?.bootstrapEvidence,i=r?.reputation,a=s!==void 0||i!==void 0,c=s?.config?.maxNoPowTier??ol,l=_2e({hash:e,bits:r?.powDifficultyBits}),u=i===void 0?void 0:P2e({reputation:i,deprioritizeThreshold:r?.deprioritizeThreshold}),d=R2e({parentTopicView:n}),h=()=>!1,p=!1,f=w=>b=>(p||(p=!0,t("cohort-topic anti-DoS: bootstrap-evidence %s verifier is PERMISSIVE \u2014 no PoW/reputation view wired, so cold-root bootstrap is NOT cryptographically gated (interim; inject antiDos.bootstrapEvidence/reputation, see cohort-topic-bootstrap-evidence-scheme)",w)),!0),g=w=>a?h:f(w),y=f("parent-reference (T0/T1, no committed backing)"),m=w=>w.tier<=c&&!o?y(w):d(w);return yre({verifyPoW:s?.verifyPoW??(a?l:g("proof-of-work")),verifyReputation:s?.verifyReputation??u??g("reputation"),verifyParentReference:s?.verifyParentReference??(a?m:g("parent-reference")),config:s?.config})}async function Yst(r,e){let t=e.treeTier,n={v:1,topicId:V(e.topicId),childCohortCoord:V(e.childCohortCoord),childParticipantCoord:V(e.participantCoord),childTier:t,tier:Xst(e.opTier??0),effectiveAt:Date.now(),thresholdSig:"",signers:[],cohortEpoch:V(e.cohortEpoch())};if(e.signChildLink!==void 0){let{thresholdSig:i,signers:a}=await e.signChildLink.thresholdSign(GM(n));n.thresholdSig=V(i),n.signers=a.map(V)}let o=await r.router.routeAndAct(e.parentCoord,it(n,r.maxBytes),{wantK:r.wantK,minSigs:r.minSigs}),s=vI(Yt(o,r.maxBytes));if(s.result!=="linked")throw new Error(`cohort-topic child-link rejected by parent${s.reason!==void 0?`: ${s.reason}`:""}`)}function Xst(r){return!Number.isInteger(r)||r<0?0:r>3?3:r}var Zst=2048,Nw=class extends Error{constructor(e){super(`cohort-topic coord-engine registry full (max=${e}) \u2014 every slot holds a live cohort`),this.name="CoordEngineRegistryFullError"}},O2e={records:"pinned",forwarders:"pinned",children:1,promotion:1};function Jst(r,e=Zst){if(!Number.isInteger(e)||e<=0)throw new RangeError(`coordEnginesMax must be a positive integer, got ${e}`);let t=new Map,n=new Map,o=0,s=c=>{n.set(c,++o)},i=c=>{let l=c.liveness(),u=0;for(let d of Object.keys(O2e)){if(!l[d])continue;let h=O2e[d];if(h==="pinned")return;h>u&&(u=h)}return u},a=()=>{let c,l=1/0,u=1/0;for(let[h,p]of t){let f=i(p);if(f===void 0)continue;let g=n.get(h)??0;(f<l||f===l&&g<u)&&(l=f,u=g,c=h)}if(c===void 0)return!1;let d=t.get(c);return d.close(),t.delete(c),n.delete(c),r.onEngineEvicted?.(d.servedCoord),!0};return{forCoord(c,l,u){let d=V(c),h=t.get(d);if(h===void 0){if(t.size>=e&&!a())throw ms("cohort-topic: coord-engine registry full (max=%d) \u2014 refusing new coord %s",e,d),new Nw(e);h=eit(r,c,l,u),t.set(d,h)}return s(d),h},findByCoord(c){let l=V(c),u=t.get(l);return u!==void 0&&s(l),u},findHolder(c,l){for(let[u,d]of t)if(d.holds(c,l))return s(u),d},findServing(c,l){for(let[u,d]of t)if(d.treeTier===l&&d.servesTopic(c))return s(u),d},all(){return[...t.values()]},close(){for(let c of t.values())c.close();t.clear(),n.clear()}}}var zW=class{current;prior;lastPublished;observe(e,t){if(this.current?.epochKey===e)return;let n=t();this.prior=this.current,this.current=n}recordPublished(e){this.lastPublished=e}predecessor(){return this.lastPublished}membersAt(e){if(this.current?.epochKey===e)return this.current.memberStrs;if(this.prior?.epochKey===e)return this.prior.memberStrs}};function Qst(){let r=new Map,e=(t,n,o,s)=>{let i=V(t),a=r.get(i);a===void 0&&(a=new Map,r.set(i,a));let c=V(n),l=a.get(c);if(l===void 0)return a.set(c,{linked:s,lastEffectiveAt:o,topicId:t,childCohortCoord:n}),!0;if(o<=l.lastEffectiveAt)return!1;let u=l.linked!==s;return l.linked=s,l.lastEffectiveAt=o,u};return{recordChild(t,n,o){return e(t,n,o,!0)},unrecordChild(t,n,o){return e(t,n,o,!1)},count(t){let n=r.get(V(t));if(n===void 0)return 0;let o=0;for(let s of n.values())s.linked&&o++;return o},hasLinkedChildren(){for(let t of r.values())for(let n of t.values())if(n.linked)return!0;return!1},linkedChildren(){let t=[];for(let n of r.values())for(let o of n.values())o.linked&&t.push({topicId:o.topicId,childCohortCoord:o.childCohortCoord,effectiveAt:o.lastEffectiveAt});return t}}}function eit(r,e,t,n){let o=OM(),s=Qst(),i=new zW,a=N=>{let H=[...N.members];return{epoch:N.cohortEpoch,epochKey:V(N.cohortEpoch),memberBytes:H,memberStrs:H.map(Zt)}},c=()=>{let N=r.cohortAround(e);return i.observe(V(N.cohortEpoch),()=>a(N)),N},l=()=>c().cohortEpoch,u=jM({transport:r.transport,store:o,coord:e,localEpoch:l,verifyInbound:r.verifyGossip===void 0?void 0:N=>r.verifyGossip(N,e),onRecordsEvicted:N=>{for(let H of N)D.touch(H,o.directParticipants(H))},onChildDeltas:(N,H)=>{for(let Z of N)s.recordChild(j(Z.topicId),j(Z.childCohortCoord),Z.effectiveAt);for(let Z of H)s.unrecordChild(j(Z.topicId),j(Z.childCohortCoord),Z.effectiveAt)}}),d=u.view(),h=V(r.selfMemberBytes),p=T2e(),f=N=>{if(r.privateKey===void 0)return Cv(FW(),r.minSigs);let H=new LC({kind:N,privateKey:r.privateKey,selfMember:r.selfMemberBytes,coord:()=>e,cohortEpoch:l,cohortMembers:()=>c().members.map(Zt),dialSign:r.dialSign});return Cv(H,r.minSigs)},g=f("promotion"),y=f("membership"),m=f("childlink"),w=tre({signer:y,sink:r.publishSink,minSigs:r.minSigs,maxMessageBytes:r.maxBytes}),b=N=>{let{members:H,cohortEpoch:Z}=c();return{coord:e,cohortEpoch:Z,members:H,stabilizedAt:N}},x=r.privateKey!==void 0,S=(N,H)=>N.epochKey!==H.epochKey,T=async(N,H)=>{let Z=vh(RI(N)),ae=Zt(r.selfMemberBytes),Q=new LC({kind:"rotation",privateKey:r.privateKey,selfMember:r.selfMemberBytes,coord:()=>e,cohortEpoch:()=>H.epoch,cohortMembers:()=>[...H.memberStrs],dialSign:r.dialSign,selfEligible:()=>H.memberStrs.includes(ae)}),oe=Cv(Q,r.minSigs);try{let{thresholdSig:Fe,signers:nr}=await oe.thresholdSign(Z);return{prevEpoch:H.epoch,rotationSig:Fe,rotationSigners:nr}}catch(Fe){ms("cohort-topic: rotation attestation skipped at coord %s \u2014 predecessor quorum unavailable: %o",V(e),Fe);return}},A=!1,v=async(N,H)=>{if(A||!x)return;let Z=b(N),ae=a(Z),Q=i.predecessor(),oe=Q!==void 0&&S(Q,ae),Fe;if(oe){let nr=await T(Z,Q);Fe=await w.onStabilized(Z,N,nr)}else Fe=await(H?w.tick(Z,N):w.onStabilized(Z,N));return Fe!==void 0&&(i.recordPublished(ae),r.onCertPublished?.(Fe)),Fe},C=ore({barometer:r.barometer,view:d,selfMember:h,primaryTopicCount:N=>mit(o,r.selfMemberBytes,N),config:{cohortSize:r.wantK}}),P=ire({view:d,store:o,selfMember:h,childCohortCount:N=>s.count(N)}),F=ure({store:o,loadBucket:N=>r.barometer.bucket(F2e(o,N)),childCohortCount:N=>s.count(N),treeTier:()=>t,parentCoord:N=>r.addressing.coord(Math.max(0,t-1),n,N),cohortCoord:()=>e,cohortEpoch:l,signer:g,seedTransition:N=>r.adoptedTransition?.(e,t,N),config:r.promotionConfig??{capPromote:void 0}}),R=fre({parentRegistrar:{registerWithParent:(N,H,Z,ae)=>Yst(r,{topicId:N,parentCoord:H,treeTier:Z,opTier:ae,participantCoord:n,childCohortCoord:e,cohortEpoch:l,signChildLink:x?m:void 0})}}),k=BI(r.antiDos.rateLimiter),I=BI(r.antiDos.rateLimiter),E=DI(r.antiDos.replayGuard),D=mre({...r.antiDos.topicBudget,onEvict:N=>{R.remove(N),P.forget(N)}}),M=Yte({store:o,self:r.selfMemberBytes,slots:r.slots,cohort:c,gossip:{touch:N=>p.touch(N),evicted:N=>p.evicted(N)},verifyParticipantSig:r.verifyParticipantSig,freshness:r.antiDos.replayGuard}),B=wre({self:r.selfMemberBytes,profile:r.profile,hash:r.hash,store:o,slots:r.slots,willingness:C,promotion:F,coldStart:R,traffic:P,renewal:M,cohort:c,quorumWilling:N=>r.profile.willingTiers.has(N),rateLimiter:k,probeRateLimiter:I,replayGuard:E,topicBudget:D,bootstrapEvidence:r.bootstrapEvidence,verifyRegisterSig:r.verifyRegisterSig,onAdmit:N=>p.touch(N),onNotice:N=>r.broadcastNotice?.(N,e),log:ms}),L=()=>{let N=new Map;for(let H of o.listAll())N.set(V(H.topicId),H.topicId);return[...N.values()]},O,U,$=async N=>{if(A)return;B.sweepStale(N);let H=L().map(Ce=>are(Ce,P.publish(Ce,N),{tier:F2e(o,Ce),directParticipants:o.directParticipants(Ce),promoted:F.isPromoted(Ce),childCohortCount:s.count(Ce)}));if(U===void 0||N-U>=r.willingnessHeartbeatMs){let Ce=s.linkedChildren();for(let Ve of Ce)p.childLink(Ve.topicId,Ve.childCohortCoord,Ve.effectiveAt);Ce.length>0&&(U=N)}let{records:Z,evicted:ae,childLinks:Q,childUnlinks:oe}=p.drain(),nr=H.length===0&&Z.length===0&&ae.length===0&&Q.length===0&&oe.length===0&&(O===void 0||N-O>=r.willingnessHeartbeatMs),fe=k2e({fromMember:h,coord:V(e),cohortEpoch:V(l()),treeTier:t,heartbeat:nr,profile:r.profile,barometer:r.barometer,windowSeconds:rB,topicSummaries:H,records:Z,evicted:ae,childLinks:Q,childUnlinks:oe,timestamp:N});if(fe!==void 0)return O=N,r.signGossip!==void 0&&(fe.signature=await r.signGossip(fe)),u.broadcast(fe),fe},J=async N=>{if(!(A||!x))for(let H of L()){let Z;try{Z=await F.maybeDemote(H,N)}catch(ae){ms("cohort-topic: demotion sign/broadcast failed for topic %s: %o",V(H),ae);continue}Z!==void 0&&r.broadcastNotice?.(Z,e)}},X=()=>({records:o.listAll().length>0,forwarders:R.hasForwarders(),children:s.hasLinkedChildren(),promotion:F.hasAdoptedState()});return{servedCoord:e,treeTier:t,engine:B,cohort:c,cohortIdentityAt:N=>i.membersAt(V(N)),liveness:X,hasState:()=>X().records,hasForwarders:()=>X().forwarders,holds:(N,H)=>o.getByParticipant(N,H)!==void 0,records:N=>o.listByTopic(N),topicTraffic:N=>P.snapshot(N),recordQuery:(N,H)=>P.recordQuery(N,H),cohortView:()=>d,servesTopic:N=>o.directParticipants(N)>0||R.get(N)!==void 0,budgetHasTopic:N=>D.has(N),budgetParticipantCount:N=>D.participantCount(N),forwarder:N=>R.get(N),recordChild:(N,H,Z)=>{s.recordChild(N,H,Z)&&p.childLink(N,H,Z)},unrecordChild:(N,H,Z)=>{s.unrecordChild(N,H,Z)&&p.childUnlink(N,H,Z)},childCohortCount:N=>s.count(N),isPromoted:N=>F.isPromoted(N),applyPromotionNotice:(N,H)=>F.applyPromotionNotice(N,H),applyDemotionNotice:(N,H)=>F.applyDemotionNotice(N,H),onStabilized:N=>v(N,!1),pumpMembership:N=>v(N,!0),gossipRound:$,demotionTick:J,close:()=>{A=!0,u.close()}}}function tit(r,e,t){let n=j(e.topicId),o=j(e.participantId),s=r.findHolder(n,o);return s===void 0?{v:1,result:"unknown_registration"}:s.engine.handleRenew(e,t)}async function $2e(r,e,t){let n=j(r.topicId),o=j(r.childParticipantCoord),s=j(r.childCohortCoord),i=e.coord(r.childTier,o,n);if(!to(i,s))return{v:1,result:"rejected",reason:"coord mismatch"};let a=e.coord(r.childTier-1,o,n);if(e.verifyChildLinkSig!==void 0&&!await e.verifyChildLinkSig(r,t))return{v:1,result:"rejected",reason:"child cohort signature not verified"};let c;try{c=e.resolveParent(a,r.childTier-1,o)}catch(l){if(l instanceof Nw)return{v:1,result:"rejected",reason:"parent cohort capacity"};throw l}return c.recordChild(n,s,r.effectiveAt),{v:1,result:"linked"}}var rit=5e3,N2e={membership:"MembershipCertV1",promotion:"PromotionNoticeV1",demotion:"DemotionNoticeV1",childlink:"ChildLinkV1"};function U2e(r){try{let e=JSON.parse(new TextDecoder().decode(j(r)));return Array.isArray(e)?e:void 0}catch{return}}function nit(r,e){return Array.isArray(r)&&hit(r,e)}async function oit(r,e,t){if(t.privateKey===void 0)return{v:1,refused:!0,reason:"node has no signing key"};let n=j(r.coord),o=Zt(t.selfMember);if(r.kind==="rotation"){let d=j(r.cohortEpoch),h=t.priorCohortMembersAt?.(n,d);if(h===void 0)return{v:1,refused:!0,reason:"not a member of the prior cohort at prevEpoch"};if(!h.includes(o))return{v:1,refused:!0,reason:"self not in the prior cohort"};if(!h.includes(e))return{v:1,refused:!0,reason:"requester not in the prior cohort"};let p=U2e(r.payload);if(p===void 0||p[0]!==N2e.membership)return{v:1,refused:!0,reason:"rotation payload is not a MembershipCertV1 image"};let f=await Bs(t.privateKey,j(r.payload));return{v:1,signer:V(t.selfMember),signature:V(f)}}let s=t.cohortMembersAround(n);if(!s.includes(o))return{v:1,refused:!0,reason:"not a cohort member for coord"};if(!s.includes(e))return{v:1,refused:!0,reason:"requester not in cohort"};if(!to(j(r.cohortEpoch),t.currentEpoch(n)))return{v:1,refused:!0,reason:"cohort epoch mismatch"};let i=U2e(r.payload);if(i===void 0)return{v:1,refused:!0,reason:"payload is not a decodable signable image"};let a=N2e[r.kind];if(i[0]!==a)return{v:1,refused:!0,reason:`payload kind tag mismatch (expected ${a})`};let c=V(t.currentEpoch(n));if((r.kind==="membership"?i[2]:i[i.length-1])!==c)return{v:1,refused:!0,reason:"payload cohortEpoch does not match endorser view"};if(r.kind==="membership"){let d=t.expectedMembershipFields?.(n);if(d===void 0)return{v:1,refused:!0,reason:"no membership view to bind the cert against"};if(i[1]!==d.cohortCoord)return{v:1,refused:!0,reason:"payload cohortCoord does not match endorser view"};if(!nit(i[3],d.members))return{v:1,refused:!0,reason:"payload members do not match endorser view"};let h=i[4];if(typeof h!="number"||!Number.isFinite(h))return{v:1,refused:!0,reason:"payload stabilizedAt is not a finite number"};if(t.now!==void 0&&h>t.now()+rit)return{v:1,refused:!0,reason:"payload stabilizedAt is far-future"}}let u=await Bs(t.privateKey,j(r.payload));return{v:1,signer:V(t.selfMember),signature:V(u)}}var sit=8192;function iit(r){return{rateLimiter:BI(r),transitions:new Wr(sit)}}function H2e(r,e,t){return`${r}|${e}|${t}`}function V2e(r){return H2e(r.cohortCoord,"parentCohortCoord"in r?r.tier:r.fromTier,r.topicId)}function q2e(r,e){let t=V2e(e),n=r.transitions.get(t);(n===void 0||e.effectiveAt>n.effectiveAt)&&r.transitions.set(t,{effectiveAt:e.effectiveAt,promoted:!("parentCohortCoord"in e)})}function ait(r,e){let t=Yt(r,e),n=BC(()=>wI(t));if(n!==void 0)return{kind:"promotion",notice:n};let o=BC(()=>xI(t));if(o!==void 0)return{kind:"demotion",notice:o}}var d8=6e4;async function cit(r,e,t,n){if(e===void 0)return"dropped";let o,s;try{o=r.notice.signers.map(j),s=j(r.notice.thresholdSig)}catch{return"untrusted"}if(r.kind==="promotion"){let c=PI(r.notice);return await t.verifyMessage(o,e.servedCoord,r.notice.fromTier,c,s,{minRefetchIntervalMs:d8,now:n})!=="verified"?"untrusted":(e.applyPromotionNotice(r.notice,n),"applied")}let i=Ev(r.notice);return await t.verifyMessage(o,e.servedCoord,r.notice.tier,i,s,{minRefetchIntervalMs:d8,now:n})!=="verified"?"untrusted":(e.applyDemotionNotice(r.notice,n),"applied")}async function lit(r,e,t,n){let o=e.findByCoord(j(r.parentCohortCoord));if(o===void 0)return"no-parent";let s,i;try{s=r.signers.map(j),i=j(r.thresholdSig)}catch{return"untrusted"}let a=Ev(r);return await t.verifyMessage(s,j(r.cohortCoord),r.tier,a,i,{minRefetchIntervalMs:d8,now:n})!=="verified"?"untrusted":(o.unrecordChild(j(r.topicId),j(r.cohortCoord),r.effectiveAt),"unlinked")}async function uit(r,e,t,n,o,s,i){let a=ait(r,i);if(a===void 0)return ms("promote: dropped an undecodable notice frame"),"undecodable";let c=a.kind==="promotion"?a.notice.fromTier:a.notice.tier,l=j(a.notice.topicId);if(o.rateLimiter.check(e,l,s).ok===!1)return ms("promote: rate-limited %s notice for topic %s tier %d",a.kind,a.notice.topicId,c),"rate-limited";let u=t.findByCoord(j(a.notice.cohortCoord)),d;if(u===void 0)d="dropped";else{let p=o.transitions.get(V2e(a.notice));p!==void 0&&a.notice.effectiveAt<=p.effectiveAt?(ms("promote: stale %s notice for topic %s tier %d (effectiveAt %d <= last adopted %d)",a.kind,a.notice.topicId,c,a.notice.effectiveAt,p.effectiveAt),d="stale"):(d=await cit(a,u,n,s),d==="applied"?q2e(o,a.notice):ms("promote: %s %s notice for topic %s tier %d",d,a.kind,a.notice.topicId,c))}if(a.kind!=="demotion")return d;let h=await lit(a.notice,t,n,s);return d==="applied"?"applied":h==="unlinked"?"unlinked":h==="untrusted"?(ms("promote: untrusted demotion notice at parent for topic %s tier %d",a.notice.topicId,c),"untrusted"):d}function dit(r,e){return"parentCohortCoord"in r?[e,j(r.parentCohortCoord)]:[e]}function fit(r,e,t,n){let o=r.assembleCohort(t,e);pit(n,o)||ms("cohort cross-check mismatch at coord %s: FRET-routed=%o assembled=%o; trusting the recomputed assembly",V(t),n,o)}function hit(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function pit(r,e){if(r.length!==e.length)return!1;let t=new Set(r);return e.every(n=>t.has(n))}function mit(r,e,t){let n=new Set;for(let o of r.listAll())o.tier===t&&V(o.primary)===V(e)&&n.add(V(o.topicId));return n.size}function F2e(r,e){let t=r.listByTopic(e);return t.length>0?t[0].tier:0}async function git(r,e,t,n,o,s,i,a,c,l,u,d,h,p,f){await Promise.all([Ar(r,e.register,KW(async g=>{let y=Yt(g,f),m=BC(()=>bI(y));if(m!==void 0)return it(tit(t,m,Date.now()),f);let w=BC(()=>vv(y,s));if(w!==void 0)return it(await $2e(w,o,Date.now()),f);let b=xv(y),x=await n(b,void 0,Date.now());return it(x,f)},f)),Ar(r,e.gossip,K2e(async(g,y)=>{u(g),l.deliver(y.toString(),g)},f)),Ar(r,e.promote,K2e(async(g,y)=>{await uit(g,Ms(y),t,a,c,Date.now(),f)},f)),Ar(r,e.membership,KW(async g=>{let y=d.latest();return y!==void 0&&h.cache(p,y),y??new Uint8Array(0)},f)),Ar(r,e.sign,KW(async(g,y)=>{let m=EI(Yt(g,f)),w=await i(m,y.toString());return it(w,f)},f))])}function KW(r,e){return j2e(r,e)}function K2e(r,e){return j2e(async(t,n)=>{await r(t,n)},e)}function j2e(r,e){return(t,n)=>{(async()=>{try{let o=await fo(t,e),s=await r(o,n.remotePeer);s!==void 0&&is(t,s),await t.close()}catch{try{t.abort(new Error("cohort-topic handler error"))}catch{}}})()}}function BC(r){try{return r()}catch{return}}var yit=te("cohort-change-bridge");function bit(r){let e=r.source.onAnyCollectionChange(n=>wit(r,n));return{notifier:{onCollectionChange:(n,o)=>r.source.onCollectionChange(n,o)},unsubscribe:e}}function wit(r,e){try{if(!r.selfIsCohortMember(e))return;let t=r.service.onLocalCommit;if(!t)return;let n=r.extractCommitCert(e);if(!n)return;t(e,n)}catch(t){yit("origination hook threw for collection=%s rev=%d: %o",e.collectionId,e.rev,t)}}function G2e(r,e){let t=bit(e);return r.blockChangeNotifier=t.notifier,t}function OC(r){return He(r)}function W2e(r){let e=r.anchor??Ure(),t=r.addressing??$i(Cn());return n=>{if(n.tailId===void 0)return!1;let o=e.topicId(OC(n.tailId)),s=t.coord0(o);return r.fret.assembleCohort(s,r.wantK).includes(r.selfPeerId)}}Be();Uo();var $W="/optimystic/reactivity/1.0.0",HW=`${$W}/notify`,VW=`${$W}/push-state-gossip`,qW=`${$W}/recover`,Y2e={notify:HW,pushStateGossip:VW,recover:qW};function X2e(r){return[r.notify,r.pushStateGossip,r.recover]}var jW=te("reactivity-notify"),f8=class{node;handlers=new Set;notifyProtocol;maxBytes;selfPeerId;constructor(e,t={}){this.node=e,this.notifyProtocol=t.notifyProtocol??HW,this.maxBytes=t.maxBytes??jt,this.selfPeerId=t.selfPeerId}send(e,t){if(this.selfPeerId!==void 0&&e===this.selfPeerId)return Promise.resolve();try{let n=Kre(t);return n8(this.node,le(e),this.notifyProtocol,n).catch(o=>{jW("send to %s failed (swallowed): %o",e,o)})}catch(n){return jW("dropped a send to %s: %o",e,n),Promise.resolve()}}onNotification(e){return this.handlers.add(e),()=>this.handlers.delete(e)}deliver(e,t){let n;try{n=zre(t,this.maxBytes)}catch(s){jW("dropped an undecodable inbound frame from %s: %o",e,s);return}let o={id:Ms(e)};for(let s of this.handlers)s(o,n)}};function Z2e(r,e,t,n=jt){Ar(r,e,(o,s)=>{(async()=>{try{let i=await fo(o,n);t.deliver(s.remotePeer.toString(),i),await o.close()}catch{try{o.abort(new Error("reactivity notify stream handler error"))}catch{}}})()})}Be();var Uw=te("reactivity-recover");function xit(r){return Zt(j(r))}function Q2e(r){return{signBackfill:e=>V(GU(r,OB(e))),signResume:e=>V(GU(r,FB(e)))}}var h8=class extends Error{redirect;constructor(e){super(`reactivity recover: cohort rotated to tail ${e.newTailId} (effectiveAtRevision ${e.effectiveAtRevision})`),this.name="RotationRedirectError",this.redirect=e}};function eCe(r,e=qW,t=jt){return{exchange:(n,o)=>Mu(r,le(n),e,o,t)}}var p8=class{dialer;selfPeerId;cohortHintCache;resolveCohort;maxBytes;constructor(e){this.dialer=e.dialer,this.selfPeerId=e.selfPeerId,this.cohortHintCache=e.cohortHintCache,this.resolveCohort=e.resolveCohort,this.maxBytes=e.maxBytes??jt}backfillTransport(e,t){return async n=>{let o=zB({v:1,kind:"backfill",backfill:n},this.maxBytes),s=await this.exchange("backfill",o,e,t);if(s.backfillReply===void 0)throw new Error("reactivity recover: backfill reply missing its body");return s.backfillReply}}resumeTransport(e,t){return async n=>{let o=zB({v:1,kind:"resume",resume:n},this.maxBytes),s=await this.exchange("resume",o,e,t);if(s.resumeReply===void 0)throw new Error("reactivity recover: resume reply missing its body");return s.resumeReply}}async exchange(e,t,n,o){let s=this.selectTargets(n,o);if(s.length===0)throw new Error("reactivity recover: no serving cohort target resolved");let i;for(let a of s){let c;try{c=await this.dialer.exchange(a,t)}catch(u){i=u,Uw("recover dial to %s failed, trying next target: %o",a,u);continue}if(c===void 0){i=new _C(`reactivity recover ${e} from ${a}`),Uw("recover %s declined by %s, trying next target",e,a);continue}let l=fne(c,this.maxBytes);if(l.kind==="rotated")throw new h8(l.rotated);if(l.kind!==e)throw new Error(`reactivity recover: reply kind "${l.kind}" does not match request kind "${e}"`);return l}throw i??new Error("reactivity recover: all targets failed")}selectTargets(e,t){let n=new Set,o=[],s=a=>{a===void 0||a===this.selfPeerId||n.has(a)||(n.add(a),o.push(a))},i=this.cohortHintCache.get(t);if(i?.primary!==void 0)try{s(xit(i.primary))}catch(a){Uw("recover: malformed sticky primary for %s, skipping to cohort-walk: %o",t,a)}for(let a of this.resolveCohort(e))s(a);return o}};function J2e(r,e,t,n,o,s){let i=j(n);return Bo(e,t,i)?r.replayGuard.accept(i,Ms(e),o,s)?!0:(Uw("recover serve: replay/stale request from %s (declined)",e),!1):(Uw("recover serve: signature verification failed for %s (declined)",e),!1)}function vit(r,e,t){let n=r.maxBytes??jt,o=r.rotationFor?.({collectionId:e.collectionId},t);if(o!==void 0)return Kv({v:1,kind:"rotated",rotated:o},n);let s=r.pushStateForCollection(e.collectionId);if(s===void 0)return;let i=rne(s.replayBuffer,e,s.collectionId);return Kv({v:1,kind:"backfill",backfillReply:i},n)}function Eit(r,e,t){let n=r.maxBytes??jt,o=ri(j(e.latestKnownTailId)),s=r.rotationFor?.({topicId:o,collectionId:e.collectionId},t);if(s!==void 0)return Kv({v:1,kind:"rotated",rotated:s},n);let i=r.pushStateFor(o)??r.pushStateForCollection(e.collectionId);if(i===void 0)return;let a=cne(e,{buffer:i.replayBuffer,checkpoint:i.checkpoint,inheritedCheckpoint:i.inheritedCheckpoint,currentTailId:i.tailIdAtJoin,currentRevision:i.lastRevision,rotationRevision:i.lastRevision,expectedCollectionId:i.collectionId});return Kv({v:1,kind:"resume",resumeReply:a},n)}function Sit(r){let e=r.maxBytes??jt,t=r.clock??(()=>Date.now());return(n,o)=>{try{let s=dne(n,e),i=o.toString(),a=t();if(s.kind==="backfill"){let l=s.backfill;return l===void 0||!J2e(r,i,OB(l),l.signature,l.timestamp,a)?Promise.resolve(void 0):Promise.resolve(vit(r,l,a))}let c=s.resume;return c===void 0||!J2e(r,i,FB(c),c.signature,c.timestamp,a)?Promise.resolve(void 0):Promise.resolve(Eit(r,c,a))}catch(s){return Uw("recover serve: dropping request (declined): %o",s),Promise.resolve(void 0)}}}function tCe(r,e,t){let n=t.maxBytes??jt;o8(r,e,Sit(t),n)}var NC=te("reactivity-forwarder-host");function GW(r){return ri(j(r.tailId))}function rCe(r,e){let t=[];for(let n of r.records(e))if(n.appState!==void 0){try{Fre(n.appState)}catch{continue}t.push(Zt(n.participantId))}return t}var m8=class{transport;selfPeerId;profile;pushStateInit;verifierFor;directSubscribers;resolveChildPrimary;deliverLocal;clock;served=new Map;ingestTails=new Map;rotationGates=new Map;constructor(e){this.transport=e.transport,this.selfPeerId=e.selfPeerId,this.profile=e.profile,this.pushStateInit=e.pushStateInit,this.verifierFor=e.verifierFor,this.directSubscribers=e.directSubscribers,this.resolveChildPrimary=e.resolveChildPrimary,this.deliverLocal=e.deliverLocal,this.clock=e.clock??(()=>Date.now())}ingest(e,t){let n=this.topicKey(e),s=(this.ingestTails.get(n)??Promise.resolve()).then(()=>this.ingestSerialized(e,t,n),()=>this.ingestSerialized(e,t,n));return this.ingestTails.set(n,s),s}async ingestSerialized(e,t,n){try{let o=this.resolveServed(e,t,n);if(o===null||await o.forwarder.receive(t,this.clock())!=="forward")return;this.fanOut(e,o.pushState,t)}catch(o){NC("ingest failed for topic=%s rev=%d (isolated): %o",n,t.revision,o)}}async onInbound(e,t){let n;try{n=GW(t)}catch(o){NC("onInbound: undecodable tailId on rev=%d (dropped): %o",t.revision,o);return}this.deliverInProcess(n,t),await this.ingest(n,t)}pushStateFor(e){let t=this.served.get(this.topicKey(e));return t?.pushState}livePushStates(){let e=[];for(let t of this.served.values())t!==null&&e.push(t.pushState);return e}pushStateForCollection(e){let t;for(let n of this.served.values())n===null||n.pushState.collectionId!==e||(t===void 0||n.pushState.lastRevision>t.lastRevision)&&(t=n.pushState);return t}markRotated(e,t,n){let o=this.topicKey(e),s=this.rotationGates.get(o);s!==void 0&&t.effectiveAtRevision<=s.rotationRedirect.effectiveAtRevision||this.rotationGates.set(o,new eT({rotatedAt:n,newTailId:t.newTailId,effectiveAtRevision:t.effectiveAtRevision}))}rotationRedirectFor(e,t){let n=this.topicKey(e),o=this.rotationGates.get(n);if(o!==void 0){if(o.isDraining(t))return o.rotationRedirect;this.rotationGates.delete(n),this.served.delete(n),this.ingestTails.delete(n)}}fanOut(e,t,n){let o=this.directSubscribers(e);this.reconcileQueues(t,o),t.enqueueForSubscribers(o,n);for(let s of o){let i=t.perSubscriberQueue.peekQueue(s);if(i!==void 0)for(let a of i.drain())this.deliverTo(e,s,a)}for(let s of t.childCohorts){let i=s.primary??this.resolveChildPrimary?.(s);i!==void 0&&i!==this.selfPeerId&&this.dispatch(i,n)}}reconcileQueues(e,t){let n=new Set(t);for(let o of[...e.perSubscriberQueue.subscribers()])n.has(o)||e.perSubscriberQueue.remove(o)}deliverTo(e,t,n){t===this.selfPeerId?this.deliverInProcess(e,n):this.dispatch(t,n)}deliverInProcess(e,t){if(this.deliverLocal!==void 0)try{this.deliverLocal(e,t)}catch(n){NC("local delivery threw (isolated) for rev=%d: %o",t.revision,n)}}dispatch(e,t){let n;try{n=this.transport.send(e,t)}catch(o){NC("notify send to %s threw synchronously (isolated): %o",e,o);return}n.catch(o=>{NC("notify send to %s rejected (isolated): %o",e,o)})}resolveServed(e,t,n){let o=this.served.get(n);if(o!==void 0)return o;let s=pne(this.profile,this.pushStateInit(e,t));if(s===void 0)return this.served.set(n,null),null;let i={pushState:s,forwarder:Qre({state:s,verifier:this.verifierFor(e)})};return this.served.set(n,i),i}topicKey(e){return V(e)}};var g8=te("reactivity-origination"),y8=class{service;resolveContext;emit;markRotated;blockFill;clock;lastSeenTail=new Map;fillTrackers=new Map;constructor(e){this.service=e.service,this.resolveContext=e.resolveContext,this.emit=e.emit,this.markRotated=e.markRotated,this.blockFill=e.blockFill,this.clock=e.clock??(()=>Date.now())}install(){this.service.onLocalCommit=(e,t)=>this.originate(e,t)}originate(e,t){try{let n=this.resolveContext(e);if(n===void 0)return;this.observeTail(e,n);let o=$re(e,t,{tailId:V(n.tailId),timestamp:this.clock(),deltaMaxBytes:n.deltaMaxBytes,delta:n.delta,rotationHint:n.rotationHint,encodeSigner:s=>V(Ms(s))});this.emit(o)}catch(n){g8("origination failed for collection=%s rev=%d: %o",e.collectionId,e.rev,n)}}observeTail(e,t){try{this.trackBlockFill(e),this.detectTailRotation(e,t)}catch(n){g8("rotation/warm-up observation failed for collection=%s rev=%d (isolated): %o",e.collectionId,e.rev,n)}}trackBlockFill(e){let t=e.collectionId,n=this.fillTrackers.get(t);n===void 0&&(n=new QI(this.blockFill),this.fillTrackers.set(t,n));let o=n.onCommit();o.kind==="warmup"?g8("block-fill warm-up for collection=%s (%d committed, %d remaining) \u2014 anticipatory pre-dial is signal-only on a live node (successor tail not knowable; gated on 6.5-block-id-derivation)",t,o.count,o.remaining):o.kind==="filling"&&g8("block-fill filling commit for collection=%s (%d committed) \u2014 no live pre-announce (successor tail id not knowable; rotation observed on the next commit's tail-id change)",t,o.count)}detectTailRotation(e,t){let n=e.collectionId,o=V(t.tailId),s=this.lastSeenTail.get(n);if(s!==void 0&&s!==o){let i=ri(j(s));this.markRotated?.(i,{newTailId:o,effectiveAtRevision:e.rev},this.clock())}this.lastSeenTail.set(n,o)}};Uo();var UC=te("reactivity-push-state-gossip"),nCe=Number.MAX_SAFE_INTEGER,b8=class{gossipTransport;liveCollections;pushStateForGossip;isCohortMember;intervalMs;maxBytes;onTruncate;timer;stopped=!1;rounding=!1;constructor(e){this.gossipTransport=e.gossipTransport,this.liveCollections=e.liveCollections,this.pushStateForGossip=e.pushStateForGossip,this.isCohortMember=e.isCohortMember,this.intervalMs=e.intervalMs??a8,this.maxBytes=e.maxBytes??jt,this.onTruncate=e.onTruncate}start(){if(this.stopped||this.timer!==void 0)return;let e=setInterval(()=>{this.round()},this.intervalMs);e.unref?.(),this.timer=e}round(){if(!(this.stopped||this.rounding)){this.rounding=!0;try{for(let{pushState:e,cohortCoord:t}of this.liveCollections()){if(this.stopped)break;try{this.broadcastOne(e,t)}catch(n){UC("push-state gossip round failed for a collection (isolated): %o",n)}}}finally{this.rounding=!1}}}deliver(e,t){let n;try{n=Jre(t,this.maxBytes)}catch(s){UC("dropped an undecodable push-state gossip frame from %s: %o",e,s);return}if(this.isCohortMember!==void 0&&!this.isCohortMember(e,n)){UC("dropped push-state gossip from non-member %s for collection=%s topic=%s",e,n.collectionId,n.topicId);return}let o=this.pushStateForGossip(n);if(o!==void 0)try{o.mergeGossip(n)}catch(s){UC("push-state mergeGossip threw (isolated) for collection=%s: %o",n.collectionId,s)}}stop(){this.stopped=!0,this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0)}broadcastOne(e,t){let n=e.serializeGossip(),{frame:o,kept:s,total:i}=this.boundedFrame(n);s<i&&(UC("push-state gossip frame clipped for collection=%s: kept %d/%d most-recent replay entries to fit maxBytes=%d",n.collectionId,s,i,this.maxBytes),this.onTruncate?.({collectionId:n.collectionId,topicId:n.topicId,kept:s,total:i,frameBytes:o.length,maxBytes:this.maxBytes})),this.gossipTransport.broadcastOver(VW,t,o)}boundedFrame(e){let t=e.replayBuffer.entries.length,n=RB(e,nCe);if(n.length<=this.maxBytes)return{frame:n,kept:t,total:t};let o=0,s=t,i=0,a=this.encodeSlice(e,0);for(;o<=s;){let c=o+s>>>1,l=this.encodeSlice(e,c);l.length<=this.maxBytes?(i=c,a=l,o=c+1):s=c-1}return{frame:a,kept:i,total:t}}encodeSlice(e,t){let n=e.replayBuffer.entries,o=t>=n.length?n:n.slice(n.length-t),s={...e,replayBuffer:{capacity:e.replayBuffer.capacity,entries:o}};return RB(s,nCe)}};function oCe(r,e,t,n=jt){Ar(r,e,(o,s)=>{(async()=>{try{let i=await fo(o,n);t.deliver(s.remotePeer.toString(),i),await o.close()}catch{try{o.abort(new Error("reactivity push-state gossip stream handler error"))}catch{}}})()})}var FC=te("reactivity-rotation-rereg"),sCe=1024;function Cit(r,e){let t=setTimeout(r,e);return t.unref?.(),()=>clearTimeout(t)}var w8=class{reRegister;setTimer;now;pending=new Map;seen=new Set;stopped=!1;constructor(e){this.reRegister=e.reRegister,this.setTimer=e.setTimer??Cit,this.now=e.now??(()=>Date.now())}get pendingCount(){return this.pending.size}get seenCount(){return this.seen.size}schedule(e){if(this.stopped)return;let t=V(e.plan.newTopicId);if(this.seen.has(t)){FC("rotation re-registration already scheduled/fired for successor topic=%s \u2014 ignoring duplicate notice (preAnnounced=%s)",t,e.preAnnounced);return}this.seen.add(t);let n=Math.max(0,e.plan.fireAt-this.now()),o=e.plan,s=this.setTimer(()=>{this.fire(t,o)},n);this.pending.set(t,s),this.evictSeenOverCap(),FC("scheduled rotation re-registration for successor topic=%s in %dms (preAnnounced=%s)",t,n,e.preAnnounced)}cancel(e){if(e===void 0){for(let o of this.pending.values())o();this.pending.clear(),this.seen.clear();return}let t=V(e),n=this.pending.get(t);n!==void 0&&(n(),this.pending.delete(t)),this.seen.delete(t)}stop(){this.stopped=!0;for(let e of this.pending.values())e();this.pending.clear(),this.seen.clear()}evictSeenOverCap(){for(;this.seen.size>sCe;){let e=!1;for(let t of this.seen)if(!this.pending.has(t)){this.seen.delete(t),FC("rotation re-registration ledger at cap (%d) \u2014 evicted oldest fired successor topic=%s",sCe,t),e=!0;break}if(!e)break}}fire(e,t){if(this.pending.delete(e),!this.stopped)try{this.reRegister(t).catch(n=>{FC("rotation re-registration rejected for successor topic=%s (isolated, not retried): %o",e,n)})}catch(n){FC("rotation re-registration threw synchronously for successor topic=%s (isolated): %o",e,n)}}};var iCe=te("reactivity-subscribers"),x8=class{byTopic=new Map;register(e,t){let n=V(e),o=this.byTopic.get(n);return o===void 0&&(o=new Set,this.byTopic.set(n,o)),o.add(t),()=>this.unregister(e,t)}unregister(e,t){let n=V(e),o=this.byTopic.get(n);o!==void 0&&(o.delete(t),o.size===0&&this.byTopic.delete(n))}deliver(e,t){let n=this.byTopic.get(V(e));if(n!==void 0)for(let o of[...n])try{let s=o(t);s instanceof Promise&&s.catch(i=>iCe("subscriber delivery rejected (isolated) for rev=%d: %o",t.revision,i))}catch(s){iCe("subscriber handler threw (isolated) for rev=%d: %o",t.revision,s)}}get topicCount(){return this.byTopic.size}has(e){return this.byTopic.has(V(e))}};async function aCe(r,e){let t=[],n=[];for(let a of e.records){if(a.appState===void 0)continue;let c=Zt(a.participantId),l;try{l=_re(a.appState)}catch(u){e.log?.("matchmaking query handler: skipping undecodable record for %s: %o",c,u);continue}l.kind==="match-provider"?t.push({participantId:c,attachedAt:a.attachedAt,payload:l}):n.push({participantId:c,attachedAt:a.attachedAt,payload:l})}let o=Mre(r,t,n),s={v:1,truncated:o.truncated,cohortEpoch:V(e.cohortEpoch),topicTraffic:e.topicTraffic};o.providers!==void 0&&(s.providers=o.providers),o.seekers!==void 0&&(s.seekers=o.seekers);let i=await e.sign(Lre(s));return{...s,signature:i}}var Ait="/optimystic/matchmaking/1.0.0",WW=`${Ait}/query`,YW={query:WW};function cCe(r){return[r.query]}var XW=te("matchmaking-query");function kit(r){let e=r.maxBytes??jt;return async(t,n)=>{try{let o=Pre(t,e),s=j(o.topicId);if(r.gate!==void 0&&!r.gate(n,s)){XW("matchmaking query serve: rate-limited query from %s (no reply)",n.toString());return}let i=r.addressing.coord0(s),a=r.registry.findServing(s,0)??r.registry.findByCoord(i);if(a===void 0)return;a.recordQuery(s,(r.clock??Date.now)());let c=await aCe(o,{records:a.records(s),topicTraffic:a.topicTraffic(s),cohortEpoch:a.cohort().cohortEpoch,sign:r.sign,log:XW});return Rre(c,e)}catch(o){XW("matchmaking query serve: dropping query (no reply): %o",o);return}}}function lCe(r,e=WW,t){let n=t.maxBytes??jt;o8(r,e,kit(t),n)}var v8=class{peerStatuses=new Map;unreachableThreshold=3;rapidChurnThreshold=5;rapidChurnWindow=1e4;peerTimeoutMs=6e4;recordSuccess(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastSeen=t,n.consecutiveFailures=0):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:0}),this.cleanupOldPeers()}recordFailure(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.consecutiveFailures++,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,consecutiveFailures:1})}recordGoodbye(e){let t=Date.now(),n=this.peerStatuses.get(e);n?(n.lastGoodbye=t,n.lastSeen=t):this.peerStatuses.set(e,{peerId:e,lastSeen:t,lastGoodbye:t,consecutiveFailures:0})}detectPartition(){let e=this.getRecentGoodbyes(this.rapidChurnWindow),t=Array.from(this.peerStatuses.values()).filter(o=>o.consecutiveFailures>=this.unreachableThreshold&&!o.lastGoodbye);return e.length+t.length>=this.rapidChurnThreshold}getUnreachablePeers(){return Array.from(this.peerStatuses.values()).filter(e=>e.consecutiveFailures>=this.unreachableThreshold&&!e.lastGoodbye).map(e=>e.peerId)}getRecentGoodbyes(e){let t=Date.now()-e;return Array.from(this.peerStatuses.values()).filter(n=>n.lastGoodbye&&n.lastGoodbye>t)}cleanupOldPeers(){let e=Date.now()-this.peerTimeoutMs;for(let[t,n]of this.peerStatuses.entries())n.lastSeen<e&&this.peerStatuses.delete(t)}getStatistics(){let e=this.getUnreachablePeers().length,t=this.getRecentGoodbyes(this.rapidChurnWindow).length;return{totalPeers:this.peerStatuses.size,unreachable:e,recentGoodbyes:t}}reset(){this.peerStatuses.clear()}};function uCe(r,e){let t=r.effectiveSuperMajorityThreshold,n=e.effectiveSuperMajorityThreshold;if(t!==n)throw new Error(`Super-majority threshold mismatch at node startup: cluster member resolved ${t} but coordinator resolved ${n}. Both derive from consensusConfig.superMajorityThreshold (options.clusterPolicy?.superMajorityThreshold ?? DEFAULT_SUPER_MAJORITY_THRESHOLD=${yd}); they must be equal or the coordinator would declare transactions committed on a super-majority the member rejects as final.`)}var E8=te("peer-reputation"),KC=class{peers=new Map;halfLifeMs;thresholds;weights;maxPenaltiesPerPeer;maxPeers;selfPeerId;selfReportsRefused=0;newRecordsRefused=0;constructor(e){this.halfLifeMs=e?.halfLifeMs??30*6e4,this.thresholds={...oS,...e?.thresholds},this.weights={...SF,...e?.weights},this.maxPenaltiesPerPeer=e?.maxPenaltiesPerPeer??100,this.maxPeers=e?.maxPeers??1024,this.selfPeerId=e?.selfPeerId}reportPeer(e,t,n){if(this.refuseSelfReport(e,t,n))return;let o=this.getOrCreateRecord(e);if(!o)return;let s=this.weights[t],i={reason:t,weight:s,timestamp:Date.now(),context:n};o.penalties.push(i),o.lastPenalty=i.timestamp,this.pruneRecord(o);let a=this.computeScore(o);E8("report peerId=%s reason=%s weight=%d score=%d context=%s",e.substring(0,12),t,s,Math.round(a),n??"")}recordSuccess(e){if(this.isSelf(e))return;let t=this.getOrCreateRecord(e);t&&(t.successCount++,t.lastSuccess=Date.now())}getScore(e){let t=this.peers.get(e);return t?this.computeScore(t):0}isBanned(e){return this.getScore(e)>=this.thresholds.ban}isDeprioritized(e){return this.getScore(e)>=this.thresholds.deprioritize}getReputation(e){let t=this.getScore(e),n=this.peers.get(e);return{peerId:e,effectiveScore:t,isBanned:t>=this.thresholds.ban,isDeprioritized:t>=this.thresholds.deprioritize,penaltyCount:n?.penalties.length??0,successCount:n?.successCount??0,lastPenalty:n?.lastPenalty??0,lastSuccess:n?.lastSuccess??0}}getAllReputations(){let e=new Map;for(let t of this.peers.keys())e.set(t,this.getReputation(t));return e}resetPeer(e){this.peers.delete(e),E8("reset peerId=%s",e.substring(0,12))}isSelf(e){return this.selfPeerId!==void 0&&e===this.selfPeerId}refuseSelfReport(e,t,n){return this.isSelf(e)?(this.selfReportsRefused++,E8("refused self-report peerId=%s reason=%s context=%s refused=%d",e.substring(0,12),t,n??"",this.selfReportsRefused),!0):!1}getOrCreateRecord(e){let t=this.peers.get(e);if(t)return t;if(this.peers.size>=this.maxPeers&&!this.evictOne()){this.refuseNewRecord(e);return}let n={penalties:[],successCount:0,lastSuccess:0,lastPenalty:0};return this.peers.set(e,n),n}evictOne(){let e=this.pickEvictionVictim();return e===void 0?!1:(this.peers.delete(e),!0)}pickEvictionVictim(){let e,t=1/0,n=1/0;for(let[o,s]of this.peers){let i=this.computeScore(s);if(i>=this.thresholds.ban)continue;let a=Math.max(s.lastPenalty,s.lastSuccess);(i<t||i===t&&a<n)&&(e=o,t=i,n=a)}return e}refuseNewRecord(e){this.newRecordsRefused++,E8("refused new record, table full of banned peers peerId=%s maxPeers=%d refused=%d",e.substring(0,12),this.maxPeers,this.newRecordsRefused)}computeScore(e){let t=Date.now(),n=0;for(let o of e.penalties)n+=o.weight*this.decayFactor(t,o.timestamp);return n}decayFactor(e,t){let n=e-t;return n<=0?1:Math.pow(.5,n/this.halfLifeMs)}pruneRecord(e){let t=Date.now(),n=this.halfLifeMs*7;e.penalties=e.penalties.filter(o=>t-o.timestamp<n),e.penalties.length>this.maxPenaltiesPerPeer&&(e.penalties=e.penalties.slice(-this.maxPenaltiesPerPeer))}};var Dit=hCe,dCe=128,_it=127,Pit=~_it,Rit=Math.pow(2,31);function hCe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Rit;)e[t++]=r&255|dCe,r/=128;for(;r&Pit;)e[t++]=r&255|dCe,r>>>=7;return e[t]=r|0,hCe.bytes=t-n+1,e}var Lit=ZW,Mit=128,fCe=127;function ZW(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw ZW.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&fCe)<<o:(i&fCe)*Math.pow(2,o),o+=7}while(i>=Mit);return ZW.bytes=s-n,t}var Bit=Math.pow(2,7),Oit=Math.pow(2,14),Nit=Math.pow(2,21),Uit=Math.pow(2,28),Fit=Math.pow(2,35),Kit=Math.pow(2,42),zit=Math.pow(2,49),$it=Math.pow(2,56),Hit=Math.pow(2,63),Vit=function(r){return r<Bit?1:r<Oit?2:r<Nit?3:r<Uit?4:r<Fit?5:r<Kit?6:r<zit?7:r<$it?8:r<Hit?9:10},qit={encode:Dit,decode:Lit,encodingLength:Vit},jit=qit,JW=jit;function QW(r,e,t=0){return JW.encode(r,e,t),e}function eY(r){return JW.encodingLength(r)}function pCe(r,e){let t=e.byteLength,n=eY(r),o=n+eY(t),s=new Uint8Array(o+t);return QW(r,s,0),QW(t,s,n),s.set(e,o),new tY(r,t,e,s)}var tY=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var Yit=20;function nY({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new rY(r,e,t,n,o)}var rY=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??Yit,this.maxDigestLength=s}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?mCe(n,this.code,t?.truncate):n.then(o=>mCe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function mCe(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 pCe(e,r)}function gCe(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var oY=nY({name:"sha2-256",code:18,encode:gCe("SHA-256")}),BRr=nY({name:"sha2-512",code:19,encode:gCe("SHA-512")});var Fw={disputeEnabled:!1,disputeArbitrationTimeoutMs:6e4,engineHealthDisputeThreshold:3,engineHealthWindowMs:6e5};var sY=te("engine-health"),zC=class{state={disputesLost:0,recentLosses:[],unhealthy:!1};threshold;windowMs;constructor(e){this.threshold=e?.engineHealthDisputeThreshold??Fw.engineHealthDisputeThreshold,this.windowMs=e?.engineHealthWindowMs??Fw.engineHealthWindowMs}recordDisputeLoss(){let e=Date.now();this.state.recentLosses.push(e),this.pruneOldLosses(e),this.state.disputesLost=this.state.recentLosses.length,sY("dispute-loss-recorded",{recentLosses:this.state.recentLosses.length,threshold:this.threshold,wasUnhealthy:this.state.unhealthy}),this.state.recentLosses.length>=this.threshold&&!this.state.unhealthy&&(this.state.unhealthy=!0,this.state.unhealthySince=e,sY("engine-marked-unhealthy",{disputesLost:this.state.recentLosses.length,threshold:this.threshold,windowMs:this.windowMs}))}isUnhealthy(){return this.pruneOldLosses(Date.now()),this.state.unhealthy&&this.state.recentLosses.length<this.threshold&&(this.state.unhealthy=!1,this.state.unhealthySince=void 0,sY("engine-auto-recovered",{recentLosses:this.state.recentLosses.length,threshold:this.threshold})),this.state.unhealthy}getState(){return this.pruneOldLosses(Date.now()),{...this.state}}reset(){this.state={disputesLost:0,recentLosses:[],unhealthy:!1}}pruneOldLosses(e){let t=e-this.windowMs;this.state.recentLosses=this.state.recentLosses.filter(n=>n>t),this.state.disputesLost=this.state.recentLosses.length}};var jn=te("dispute"),$C=class r{peerId;privateKey;createDisputeClient;reputation;revalidate;config;engineHealth;selectArbitrators;onInvalidation;activeDisputes=new Map;resolvedDisputes=new Map;resolvedChallenges=new Map;disputedTransactions=new Set;invalidatedTransactions=new Set;constructor(e){this.peerId=e.peerId,this.privateKey=e.privateKey,this.createDisputeClient=e.createDisputeClient,this.reputation=e.reputation,this.revalidate=e.revalidate,this.config={...Fw,...e.config},this.engineHealth=new zC(this.config),this.selectArbitrators=e.selectArbitrators,this.onInvalidation=e.onInvalidation}getEngineHealth(){return this.engineHealth}isEnabled(){return this.config.disputeEnabled}getDisputeStatus(e){for(let[,t]of this.activeDisputes)if(t.originalMessageHash===e)return"committed-disputed";for(let[,t]of this.resolvedDisputes){let n=this.findChallengeForDispute(t.disputeId);if(n&&n.originalMessageHash===e)return t.outcome==="challenger-wins"?"committed-invalidated":t.outcome==="majority-wins"?"committed-validated":"committed-disputed"}}async initiateDispute(e,t){if(!this.config.disputeEnabled){jn("dispute-disabled",{messageHash:e.messageHash});return}if(this.disputedTransactions.has(e.messageHash)){jn("dispute-already-initiated",{messageHash:e.messageHash});return}if(this.engineHealth.isUnhealthy()){jn("dispute-skipped-unhealthy",{messageHash:e.messageHash});return}this.disputedTransactions.add(e.messageHash);let n=Date.now(),o=await this.computeDisputeId(e.messageHash,this.peerId.toString(),n),s=await this.signDispute(o),i=e.message.expiration?(e.message.expiration-Date.now())*2:this.config.disputeArbitrationTimeoutMs*2,a=n+Math.max(i,this.config.disputeArbitrationTimeoutMs),l=(e.message.coordinatingBlockIds??[])[0]??e.messageHash,u=Object.keys(e.peers),d=this.config.arbitratorCount??u.length,h=0,p=await this.computeEpochBytes(u),f;try{f=await this.selectArbitrators(l,u,d,h,p)}catch(b){jn("dispute-arbitrator-selection-failed",{disputeId:o,error:b instanceof Error?b.message:String(b)});return}if(f.length===0){jn("dispute-no-arbitrators",{disputeId:o});return}let g=f.map(b=>b.toString()),y={disputeId:o,originalMessageHash:e.messageHash,originalRecord:e,challengerPeerId:this.peerId.toString(),challengerEvidence:t,signature:s,timestamp:n,expiration:a,arbitratorSet:g};this.activeDisputes.set(o,y),jn("dispute-initiated",{disputeId:o,messageHash:e.messageHash});let m=await this.collectVotes(y,f),w=await this.resolveDispute(y,m);return this.resolvedChallenges.set(o,y),this.activeDisputes.delete(o),this.resolvedDisputes.set(o,w),this.applyReputationEffects(w,e),await this.maybeInvalidate(w,e,g),await this.broadcastResolution(w,f,u),jn("dispute-resolved",{disputeId:o,outcome:w.outcome,votes:m.length,affectedPeers:w.affectedPeers.length}),w}async handleChallenge(e){jn("dispute-handle-challenge",{disputeId:e.disputeId});let t=await this.computeChallengeTargetHash(e),n=await zE(e.arbitratorSet??[]);if(!await this.verifyDisputeSignature(e.disputeId,e.signature,e.challengerPeerId,e.originalRecord.peers[e.challengerPeerId]?.publicKey))return jn("dispute-invalid-challenge-signature",{disputeId:e.disputeId}),this.makeVote(e.disputeId,"inconclusive",{computedHash:"",engineId:"unknown",schemaHash:"",blockStateHashes:{}},t,n);let s;if(this.revalidate)try{s=await this.revalidate(e.originalRecord)}catch(a){jn("dispute-revalidation-failed",{disputeId:e.disputeId,error:a instanceof Error?a.message:String(a)})}if(!s)return this.makeVote(e.disputeId,"inconclusive",{computedHash:"",engineId:"unknown",schemaHash:"",blockStateHashes:{}},t,n);let i;return s.computedHash===e.challengerEvidence.computedHash?i="agree-with-challenger":i="agree-with-majority",this.makeVote(e.disputeId,i,s,t,n)}async computeChallengeTargetHash(e){let t=r.extractInvalidationTarget(e.originalRecord),n=t?{invalidatedActionId:t.actionId,blockIds:t.blockIds}:{invalidatedActionId:"",blockIds:[]};return KE(e.originalRecord.messageHash,n)}handleResolution(e){this.resolvedDisputes.set(e.disputeId,e),jn("dispute-resolution-received",{disputeId:e.disputeId,outcome:e.outcome});let t=this.peerId.toString(),n=e.affectedPeers.find(o=>o.peerId===t);n&&n.reason==="false-approval"&&this.engineHealth.recordDisputeLoss()}async collectVotes(e,t){let n=this.config.disputeArbitrationTimeoutMs,o=[],s=t.map(async a=>{try{return await this.createDisputeClient(a).sendChallenge(e,n)}catch(c){jn("dispute-vote-collection-failed",{disputeId:e.disputeId,arbitrator:a.toString(),error:c instanceof Error?c.message:String(c)});return}}),i=await Promise.allSettled(s);for(let a of i)a.status==="fulfilled"&&a.value&&o.push(a.value);return o}async resolveDispute(e,t){let n=t.filter(l=>l.vote==="agree-with-challenger").length,o=t.filter(l=>l.vote==="agree-with-majority").length,s=n+o,i=Math.ceil(s*2/3),a,c=[];if(s===0)a="inconclusive";else if(n>=i){a="challenger-wins";let l=e.originalRecord,u=await this.computePromiseHash(l);for(let[d,h]of Object.entries(l.promises))h.type==="approve"&&d!==e.challengerPeerId&&(await this.verifyPromiseSignature(l,d,u,h)?c.push({peerId:d,reason:"false-approval"}):jn("dispute-skip-unverified-approval",{disputeId:e.disputeId,peerId:d}))}else o>=i?(a="majority-wins",c.push({peerId:e.challengerPeerId,reason:"dispute-lost"})):a="inconclusive";return{disputeId:e.disputeId,outcome:a,votes:t,affectedPeers:c,timestamp:Date.now()}}applyReputationEffects(e,t){if(this.reputation){for(let n of e.affectedPeers)n.reason==="false-approval"?this.reputation.reportPeer(n.peerId,Qe.FalseApproval,`dispute:false-approval:${e.disputeId}`):n.reason==="dispute-lost"&&this.reputation.reportPeer(n.peerId,Qe.DisputeLost,`dispute:dispute-lost:${e.disputeId}`);if(e.outcome==="challenger-wins"){let n=this.peerId.toString();e.affectedPeers.some(o=>o.peerId===n)&&this.engineHealth.recordDisputeLoss()}}}async maybeInvalidate(e,t,n){if(e.outcome!=="challenger-wins"||!this.onInvalidation||this.invalidatedTransactions.has(t.messageHash))return;let o=r.extractInvalidationTarget(t);if(!o){jn("dispute-invalidation-no-target",{disputeId:e.disputeId,messageHash:t.messageHash});return}let s={invalidatedActionId:o.actionId,blockIds:o.blockIds},i=await KE(t.messageHash,s),a=await zE(n),c=await this.signArbitratorSet(e.disputeId,i,a);this.invalidatedTransactions.add(t.messageHash);let l={invalidatedActionId:o.actionId,invalidatedRev:o.rev,blockIds:o.blockIds,collectionId:o.collectionId,resolution:WU(e,t.messageHash,{arbitratorSet:n,challengerPeerId:this.peerId.toString(),arbitratorSetSignature:c})};try{await this.onInvalidation(l),jn("dispute-invalidation-originated",{disputeId:e.disputeId,invalidatedActionId:o.actionId,blockCount:o.blockIds.length})}catch(u){this.invalidatedTransactions.delete(t.messageHash),jn("dispute-invalidation-originate-failed",{disputeId:e.disputeId,error:u instanceof Error?u.message:String(u)})}}static extractInvalidationTarget(e){for(let t of e.message.operations)if("commit"in t){let n=t.commit;return{actionId:n.actionId,rev:n.rev,blockIds:n.blockIds,collectionId:n.headerId??e.message.coordinatingBlockIds?.[0]??n.blockIds[0]}}for(let t of e.message.operations)if("pend"in t){let n=t.pend,o=It(n.transforms);return{actionId:n.actionId,rev:n.rev??0,blockIds:o,collectionId:e.message.coordinatingBlockIds?.[0]??o[0]}}}async broadcastResolution(e,t,n){let o=new Set;for(let i of t)o.add(i.toString());for(let i of n)o.add(i);o.delete(this.peerId.toString());let s=Array.from(o).map(async i=>{try{let{peerIdFromString:a}=await Promise.resolve().then(()=>(Be(),bae));await this.createDisputeClient(a(i)).sendResolution(e)}catch(a){jn("dispute-broadcast-failed",{disputeId:e.disputeId,peer:i,error:a instanceof Error?a.message:String(a)})}});await Promise.allSettled(s)}async makeVote(e,t,n,o,s){let i=E6(e,t,n.computedHash,o,s),a=await this.privateKey.sign(i);return{version:Oy,disputeId:e,arbitratorPeerId:this.peerId.toString(),vote:t,evidence:n,signature:z(a,"base64url")}}async computeEpochBytes(e){let t=[...e].sort().join(",");return(await oY.digest(new TextEncoder().encode(t))).digest}async computeDisputeId(e,t,n){let o=`${e}+${t}+${n}`,s=new TextEncoder().encode(o),i=await oY.digest(s);return gT.encode(i.digest)}async signDispute(e){let t=new TextEncoder().encode(e),n=await this.privateKey.sign(t);return z(n,"base64url")}async signArbitratorSet(e,t,n){let o=await this.privateKey.sign(S6(e,t,n));return z(o,"base64url")}async verifyDisputeSignature(e,t,n,o){if(!o?.length)return!1;try{let s=typeof o=="string"?K(o,"base64url"):o;if(!nS(n,s))return!1;let i=np(s),a=new TextEncoder().encode(e),c=K(t,"base64url");return i.verify(a,c)}catch{return!1}}async computePromiseHash(e){return bh(e.messageHash,e.message,mg(e))}async verifyPromiseSignature(e,t,n,o){let s=e.peers[t]?.publicKey;if(!s?.length)return!1;try{let i=typeof s=="string"?K(s,"base64url"):s;if(!nS(t,i))return!1;let a=np(i),c=pg(n,o),l=K(o.signature,"base64url");return a.verify(c,l)}catch{return!1}}findChallengeForDispute(e){return this.activeDisputes.get(e)??this.resolvedChallenges.get(e)}};var HC=class r extends ai{protocol;constructor(e,t,n){super(e,t),this.protocol=(n??"/db-p2p")+"/dispute/1.0.0"}static create(e,t,n){return new r(e,t,n)}async sendChallenge(e,t){let n={type:"challenge",challenge:e},o=t?new AbortController:void 0,s=o?setTimeout(()=>o.abort(),t):void 0;try{return(await this.processMessage(n,this.protocol,{signal:o?.signal,dialTimeoutMs:3e3,maxDataLength:1048576})).vote}finally{s&&clearTimeout(s)}}async sendResolution(e,t){let n={type:"resolution",resolution:e};await this.processMessage(n,this.protocol,{...Ry(t),maxDataLength:1048576})}};function yCe(r){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,r>>>0,!0),e}function Zit(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}function bCe(r,e,t,n){return Zit([r,yCe(e),t,yCe(n)])}async function iY(r,e,t){let{blockId:n,round:o,epoch:s,count:i,exclude:a}=r,c=[];if(i<=0)return c;let l=new Set(a);for(let u=0;c.length<i;u++){let d=await t(bCe(n,o,s,u)),h=l.size+1,p=-1,f,g=!1;for(;;){let y=await e(d,h),m=y.find(w=>!l.has(w));if(m!==void 0){f=m;break}if(y.length<h||y.length<=p){g=!0;break}p=y.length,h*=2}if(f!==void 0)c.push(f),l.add(f);else if(g)break}return c}var Jit=te("reactivity-node-wiring"),Kw=te("node-wiring");function Qit(r,e){if(!r)return{storage:new Vs,lease:void 0};let t=typeof r=="function"?r():r;return r_(t,`node:${e}`)}function eat(r){return r!==void 0?typeof r=="function"?r():r:(Kw("WARN: no kvStore supplied \u2014 using an in-memory store. The under-replication ledger (blocks this node acknowledged before every cohort member held them) will NOT survive a restart, so copies owed at shutdown are never sent. Supply NodeOptions.kvStore (e.g. FileKVStore) to keep it."),new e8)}function tat(r){if(!r)return;let e=r;return typeof e.ensure=="function"?e.ensure():r}function rat(r,e){let t=r.pushStateForCollection(e);return t===void 0?void 0:j(t.topicId)}async function wCe(r,e){let{storage:t,lease:n}=Qit(r.storage,r.networkName),o=eat(r.kvStore),s=new YD(o),i=async(R,k)=>{},a=new Dl(R=>new mc(R,t,i)),c,l,u,d={async update(R){if(!c)throw new Error("ClusterMember not initialized");return await c.update(R)}},h=Dge(a,()=>l),p={...r.authorizeInboundStream?{authorizeInboundStream:r.authorizeInboundStream}:{},...r.authorizeInboundStreamTimeoutMs!==void 0?{authorizeInboundStreamTimeoutMs:r.authorizeInboundStreamTimeoutMs}:{}},f=r.privateKey??await L6("Ed25519"),g=x2e(r.listenAddrs??e.listenAddrs);S2e(g.supervisedRelays,r.announceAddrs);let y=g.listenAddrs,m=r.transports??e.transports,w=r.cohortTopic?.enabled===!0,b=r.cohortTopic?.wantK??16,x=w?pce():void 0,S=x?(R,k)=>{x.put(R,k),r.onCommitCertificate?.(R,k)}:r.onCommitCertificate,T=X6(r),A,v=R=>A?.(R),C={start:!1,privateKey:f,addresses:{listen:y,...r.announceAddrs?{announce:r.announceAddrs}:{},...r.appendAnnounceAddrs?{appendAnnounce:r.appendAnnounceAddrs}:{}},connectionManager:{maxConnections:16,inboundUpgradeTimeout:r.connectionManager?.inboundUpgradeTimeout??1e4,...r.connectionManager?.dialTimeout!==void 0?{dialTimeout:r.connectionManager.dialTimeout}:{}},...r.connectionGater?{connectionGater:r.connectionGater}:{},transports:m,connectionEncrypters:[fve({crypto:r.noiseCrypto})],connectionMonitor:r.connectionMonitor,streamMuxers:[xve()],services:{identify:dEe({protocolPrefix:`optimystic/${r.networkName}`}),identifyPush:fEe({protocolPrefix:`optimystic/${r.networkName}`}),ping:yEe(),dcutr:WSe(),autoNAT:z1e(),...r.relay?{relay:m2e(r.relayServerInit)}:{},cluster:R=>{let k=te("peer-address-book",R.peerId?.toString());return Xle({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1,...p})({registrar:R.registrar,cluster:d,peerId:R.peerId,getConnectionAddrs:async E=>{if(!u)return[];let D=u.getConnections?.(E)??[];return await Py(u,D,E,k)},recordPeerAddresses:(E,D)=>{u&&w6(u,E,D,k)}})},repo:R=>_ge({protocolPrefix:`/optimystic/${r.networkName}`,responsibilityK:r.responsibilityK??1,...p})({registrar:R.registrar,repo:h}),sync:R=>Nge({protocolPrefix:`/optimystic/${r.networkName}`,...p})({registrar:R.registrar,repo:h}),blockTransfer:R=>vge({protocolPrefix:`/optimystic/${r.networkName}`,...r.blockTransfer?.requirePushCertificate!==void 0?{requirePushCertificate:r.blockTransfer.requirePushCertificate}:{},...p})({registrar:R.registrar,repo:a,superMajorityThreshold:T.superMajorityThreshold,onBlockHolders:v}),networkManager:R=>{let I=b2e({clusterSize:T.clusterSize,expectedRemotes:(r.bootstrapNodes?.length??0)>0,allowClusterDownsize:r.clusterPolicy?.allowDownsize??!0,clusterSizeTolerance:r.clusterPolicy?.sizeTolerance??.5})(R);try{I.setLibp2p(R.libp2p)}catch(E){Kw("networkManager in-factory setLibp2p failed (proxy); real node injected post-construction: %o",E)}return I},fret:R=>{let I=KD({k:15,m:8,capacity:2048,profile:r.fretProfile??((r.bootstrapNodes?.length??0)>0?"core":"edge"),networkName:r.networkName,bootstraps:r.bootstrapNodes??[]})(R);try{I.setLibp2p(R.libp2p)}catch(E){Kw("fret in-factory setLibp2p failed (proxy); real node injected post-construction: %o",E)}return I}},peerDiscovery:[...r.bootstrapNodes?.length?[$1e({list:r.bootstrapNodes})]:[]]},P=await nxe(C);if(u=P,n){let R=P.stop.bind(P);P.stop=async()=>{try{await R()}finally{await n.release()}}}let F=P.services;F.fret.setLibp2p(P),F.networkManager.setLibp2p(P),F.repo.setLibp2p(P),E2e(P,g.supervisedRelays),await P.start();try{if(g.supervisedRelays.length>0){let fe=C2e(P,g.supervisedRelays),Ce=P.stop.bind(P);P.stop=async()=>{try{fe.stop()}finally{await Ce()}},await fe.awaitFirstDrives()}let R=new KC({selfPeerId:P.peerId.toString()}),k=(r.bootstrapNodes?.length??0)>0?"joining":"forming",I=`/optimystic/${r.networkName}`,E=new Qb(P,T.clusterSize,void 0,k,r.persistence,R,I);await E.initFromPersistedState();let D=fe=>Ly.create(fe,E,I);F.networkManager.setReputation(R);let M=new v8,B=P.services?.fret,L=async(fe,Ce)=>{let Ve;try{Ve=le(fe)}catch{return}if(Ve.equals(P.peerId))return;let Er=new _p(Ve,E,I),Rt;try{let Sr=await Promise.race([Er.requestBlock({blockId:Ce,rev:void 0}),new Promise(or=>{Rt=setTimeout(()=>or({success:!1}),T.cohortQueryTimeoutMs),Rt.unref()})]);return Sr.success?Sr.archive:void 0}catch{return}finally{Rt!==void 0&&clearTimeout(Rt)}},O=W6({selfPeerId:P.peerId.toString(),fetchArchive:L,saveReplicatedBlock:(fe,Ce,Ve,Er)=>a.saveReplicatedBlock(fe,Ce,Ve,Er),simpleMajorityThreshold:T.simpleMajorityThreshold,superMajorityThreshold:T.superMajorityThreshold,repairCorroborationClusterSize:T.repairCorroborationClusterSize,reputation:R,onBlockHolders:v}),U=async fe=>{let Ce=await E.findCluster(He(fe)),Ve=0;if(B)try{Ve=B.getNetworkSizeEstimate().confidence}catch{}return{peers:Ce??{},confidence:Ve}};c=J6({storageRepo:a,peerNetwork:E,peerId:P.peerId,privateKey:f,protocolPrefix:I,partitionDetector:M,fretService:B,validator:r.validator,reputation:R,consensusConfig:T,stateStore:r.transactionStateStore,reconcileBlock:O,onCommitCertificate:S,onBlockHolders:v,deriveExpectedCluster:U});{let fe=P.stop.bind(P);P.stop=async()=>{try{c.dispose()}finally{await fe()}}}let $=WD(E,D,{...T},B,R,r.transactionStateStore),J=async(fe,Ce,Ve)=>{if(fe.equals(P.peerId))try{let or=(await a.get({blockIds:[Ce],context:Ve}))[Ce]?.state?.latest;if(!or)return;let Co=await sp(a,Ce,or);return Co?{...or,proof:Co}:or}catch{return}let Rt=await new _p(fe,E,I).requestBlock({blockId:Ce,rev:void 0});if(Rt.success&&Rt.archive){let Sr=Hle(Rt.archive);if(Sr)return Sr}};l=$({storageRepo:a,localCluster:c,localPeerId:P.peerId,clusterLatestCallback:J,acquireBlockFromCohort:O,underReplicationLedger:s,onBlockHolders:v}),uCe(c,l),r.transactionStateStore&&(await c.recoverTransactions(),await l.recoverTransactions());let X=P.services?.networkManager;y2e(T.clusterSize,{keyNetwork:E,networkManager:X});let N=new Set,H,Z=()=>{H||(H=a.onAnyCollectionChange(fe=>{for(let Ce of fe.blockIds)N.add(Ce)}))};{let fe=P.stop.bind(P);P.stop=async()=>{try{H?.()}finally{await fe()}}}let ae;if(X&&(r.spreadOnChurn?.enabled??!0)!==!1)try{ae=X.initSpreadOnChurnMonitor(M,a,E,T.clusterSize,I,N,r.spreadOnChurn),await ae.start(),Z()}catch(fe){Kw("spread-on-churn init failed: %o",fe)}P.spreadOnChurnMonitor=ae;{let fe=P.stop.bind(P);P.stop=async()=>{try{ae&&await ae.stop()}finally{await fe()}}}let Q;if((r.underReplicationDrain?.enabled??!0)!==!1){let{enabled:fe,pushDialTimeoutMs:Ce,pushResponseTimeoutMs:Ve,...Er}=r.underReplicationDrain??{};Q=new XD({libp2p:P,ledger:s,keyNetwork:E,partitionDetector:M,protocolPrefix:I,pushBlock:(Sr,or)=>qb(a,E,Sr,or,{reason:"replication",protocolPrefix:I,dialTimeoutMs:Ce??3e3,responseTimeoutMs:Ve??1e4}),emit:Sr=>a.emitBlockDurabilityReached(Sr)},Er),await Q.start();let Rt=P.stop.bind(P);P.stop=async()=>{try{await Q.stop()}finally{await Rt()}}}if(P.underReplicationDrain=Q,P.underReplicationLedger=s,r.arachnode?.enableRingZulu??!0){let fe=te("node-wiring:arachnode"),Ce=P.services?.fret;if(Ce){let Ve=new a_(Ce,P.peerId.toString()),Er=new Set;P.gcEligibleBlocks=Er;let Rt,Sr=new i_(t,r.arachnode?.storage??{}),or=new s_(Ve,Sr,{minCapacity:100*1024*1024,thresholds:{moveOut:.85,moveIn:.4},smoothingAlpha:.2,deadband:.5,minDwellMs:600*1e3}),Co=P.peerId.toString(),ce=await or.createArachnodeInfo(Co);Ve.setArachnodeInfo(ce),fe("Announced Arachnode membership: Ring %d",ce.ringDepth);let Ke=new o_(Ve,E,`/optimystic/${r.networkName}`,P.peerId.toString()),_e=async(bt,Ft)=>await Ke.restore(bt,Ft);if(a.createBlockStorage=bt=>new mc(bt,t,_e),X&&(r.rebalance?.enabled??!0)!==!1)try{let bt=new VD(a,E,M,I),Ft=X.initRebalanceMonitor(M,Ve,N,E,r.rebalance);await Ft.start(),A=Rr=>Ft.recordBlockHolders(Rr),Ft.onRebalance(Rr=>{bt.handleRebalanceEvent(Rr).then(Es=>{for(let Ta of Es.released)Ft.untrackBlock(Ta),Er.add(Ta);for(let[Ta,x3]of Es.growth)Ft.recordGrowthOutcome(Ta,x3);if(Es.underReplicated.length>0){let Ta=Ft.getGrowthDiagnostics();fe("cohort-growth: %d of %d grown blocks not confirmed on new peers this pass (awaiting-confirmation=%d given-up-pairs=%d)",Es.underReplicated.length,Rr.grown.size,Ta.blocksAwaitingConfirmation,Ta.abandonedPairs)}}).catch(Es=>{fe("rebalance reaction failed: %o",Es)})}),Rt=new r8({fretAdapter:Ve,ringSelector:or,fret:Ce,partitionDetector:M,confirmer:bt,ownedBlocks:N,selfPeerId:Co,getFloor:()=>Ft.getCohortSize(),onRelease:Rr=>{for(let Es of Rr)Ft.untrackBlock(Es),Er.add(Es)}}),Rt.reconcileOnStart(),Z(),P.rebalanceMonitor=Ft,P.blockTransferCoordinator=bt,P.ringShiftCoordinator=Rt;let nh=P.stop.bind(P);P.stop=async()=>{try{await Ft.stop()}finally{await nh()}}}catch(bt){fe("rebalance wiring init failed: %o",bt)}let yt=setInterval(async()=>{if(!Rt)return;let bt=await or.shouldTransition();if(bt.shouldMove&&bt.direction&&bt.newRingDepth!==void 0){fe("Ring transition needed: moving %s to Ring %d",bt.direction,bt.newRingDepth);try{let Ft=await Rt.executeShift({direction:bt.direction,newRingDepth:bt.newRingDepth});fe("Ring shift outcome: %o",Ft)}catch(Ft){fe("Ring shift failed: %o",Ft)}finally{or.recordShiftSettled()}}},6e4),xn=P.stop.bind(P);P.stop=async()=>{clearInterval(yt),await xn()}}else fe("FRET service not available, Arachnode disabled")}if(H&&typeof t.listBlockIds=="function"){let fe=!1,Ce=P.stop.bind(P);P.stop=async()=>{fe=!0,await Ce()},g2e(t,N,()=>fe).catch(Ve=>{Kw("owned-block-seed seed failed: %o",Ve)})}let Fe;if(r.dispute?.disputeEnabled){let fe=Ce=>HC.create(Ce,E,I);Fe=new $C({peerId:P.peerId,privateKey:f,peerNetwork:E,createDisputeClient:fe,reputation:R,validator:r.validator,config:r.dispute,selectArbitrators:async(Ce,Ve,Er,Rt,Sr)=>{let{hashKey:or}=await Promise.resolve().then(()=>(Uo(),wge)),Co=P.services?.fret;if(!Co)return[];let ce=new Set(Ve);return ce.add(P.peerId.toString()),(await iY({blockId:new TextEncoder().encode(Ce),round:Rt,epoch:Sr,count:Er,exclude:ce},(_e,yt)=>Co.assembleCohort(_e,yt),or)).map(_e=>le(_e))}})}if(Object.assign(P,{coordinatedRepo:l,storageRepo:a,blockChangeNotifier:a,keyNetwork:E,reputation:R,disputeService:Fe,peerPrivateKey:f}),w){let fe=tat(B);if(!fe)throw new Error("cohortTopic enabled but the FRET service is unavailable on the node");let Ce=await z2e(P,fe,{...r.cohortTopic.host??{},antiDos:{reputation:R,...r.cohortTopic.host?.antiDos},privateKey:f,wantK:b}),Ve=Y2e,Er=YW,Rt,Sr,or,Co;{let qe=P.stop.bind(P);P.stop=async()=>{try{Co?.stop(),or?.stop(),Sr?.(),await P.unhandle(X2e(Ve)),await P.unhandle(cCe(Er)),Rt?.(),await Ce.stop()}finally{await qe()}}}let ce=W2e({fret:fe,selfPeerId:P.peerId.toString(),wantK:b});Rt=G2e(P,{source:a,service:Ce.service,selfIsCohortMember:ce,extractCommitCert:mce(x)}).unsubscribe,P.cohortTopicHost=Ce;let Ke=P.peerId.toString(),_e=Ce.profile,yt=mne(_e),xn=$i(Cn()),bt=0,Ft=new x8;P.reactivitySubscribers=Ft;let nh=new f8(P,{selfPeerId:Ke}),Rr=new m8({transport:nh,selfPeerId:Ke,profile:_e,pushStateInit:(qe,Hr)=>({collectionId:Hr.collectionId,topicId:V(qe),tailIdAtJoin:Hr.tailId,deltaMaxBytes:yt.deltaMaxBytes}),verifierFor:()=>MB({verifier:Ce.service.verifier(),tier:Qn.T3}),directSubscribers:qe=>{let Hr=Ce.registry.findServing(qe,bt);return Hr===void 0?[]:rCe(Hr,qe)},resolveChildPrimary:qe=>{let Hr=fe.assembleCohort(j(qe.coord),b);return Hr.length>0?Hr[0]:void 0},deliverLocal:(qe,Hr)=>Ft.deliver(qe,Hr)});Z2e(P,Ve.notify,nh),Sr=nh.onNotification((qe,Hr)=>{Rr.onInbound(qe,Hr)}),new y8({service:Ce.service,resolveContext:qe=>{if(qe.tailId!==void 0)return{tailId:OC(qe.tailId),deltaMaxBytes:yt.deltaMaxBytes}},emit:qe=>{Rr.ingest(GW(qe),qe)},markRotated:(qe,Hr,BA)=>Rr.markRotated(qe,Hr,BA)}).install(),or=new b8({gossipTransport:Ce.gossipTransport,liveCollections:()=>Rr.livePushStates().map(qe=>({pushState:qe,cohortCoord:xn.coord0(j(qe.topicId))})),pushStateForGossip:qe=>Rr.pushStateFor(j(qe.topicId)),isCohortMember:(qe,Hr)=>fe.assembleCohort(xn.coord0(j(Hr.topicId)),b).includes(qe)}),oCe(P,Ve.pushStateGossip,or),or.start();let Ta=KB(),x3=qe=>fe.assembleCohort(xn.coord0(qe),b),kke=new p8({dialer:eCe(P,Ve.recover),selfPeerId:Ke,cohortHintCache:Ta,resolveCohort:x3});tCe(P,Ve.recover,{pushStateFor:Rr.pushStateFor.bind(Rr),pushStateForCollection:Rr.pushStateForCollection.bind(Rr),replayGuard:DI(),rotationFor:(qe,Hr)=>{let BA=qe.topicId??rat(Rr,qe.collectionId);return BA===void 0?void 0:Rr.rotationRedirectFor(BA,Hr)}});let Dke=Q2e(f);P.reactivityRecover=kke,P.reactivityRecoverSigners=Dke,P.reactivityCohortHintCache=Ta,Co=new w8({reRegister:qe=>(Jit("reactivity rotation re-registration fired for successor topic=%s (lastRevision=%d) but no subscribe factory is wired yet \u2014 deferred to optimystic-network-reactive-watch-integration-test",V(qe.newTopicId),qe.lastRevision),Promise.resolve())}),P.reactivityRotation=Co,lCe(P,Er.query,{registry:Ce.registry,addressing:xn,sign:async qe=>V(await Bs(f,qe))})}return P}catch(R){try{await P.stop()}catch(k){Kw("rollback stop failed after startup error: %o",k)}throw R}}async function S8(r){let e=r.transports;if(!e||e.length===0)throw new Error("createLibp2pNode (RN) requires options.transports. Provide an RN-compatible transport (e.g. WebSockets) and any required listenAddrs.");return await wCe(r,{listenAddrs:[],transports:e})}var T8r=te("network:get-manager");var K8r=te("cascade");var GLr=te("reactivity-subscription");var Bu=class extends Error{static name="AbortError";constructor(e="The operation was aborted"){super(e),this.name="AbortError"}};var Si=class extends Error{static name="InvalidParametersError";constructor(e="Invalid parameters"){super(e),this.name="InvalidParametersError"}},C8=class extends Error{static name="InvalidPublicKeyError";constructor(e="Invalid public key"){super(e),this.name="InvalidPublicKeyError"}};var A8=class extends Error{static name="ConnectionFailedError";constructor(e="Connection failed"){super(e),this.name="ConnectionFailedError"}};var I8=class extends Error{static name="StreamResetError";constructor(e="The stream has been reset"){super(e),this.name="StreamResetError"}};var zf=class extends Error{static name="StreamStateError";constructor(e="The stream is in an invalid state"){super(e),this.name="StreamStateError"}},VC=class extends Error{static name="StreamBufferError";constructor(e="The stream buffer was full"){super(e),this.name="StreamBufferError"}};var T8=class extends Error{static name="InvalidCIDError";constructor(e="Invalid CID"){super(e),this.name="InvalidCIDError"}},k8=class extends Error{static name="InvalidMultihashError";constructor(e="Invalid Multihash"){super(e),this.name="InvalidMultihashError"}};var D8=class extends Error{static name="InvalidMessageError";constructor(e="Invalid message"){super(e),this.name="InvalidMessageError"}};var _8=class extends Error{static name="DialError";constructor(e="Dial error"){super(e),this.name="DialError"}},am=class extends Error{static name="ListenError";constructor(e="Listen error"){super(e),this.name="ListenError"}};var qC=class extends Error{static name="UnsupportedKeyTypeError";constructor(e="Unsupported key type"){super(e),this.name="UnsupportedKeyTypeError"}};var P8=class extends Event{data;constructor(e,t){super("message",t),this.data=e}},zw=class extends Event{error;local;constructor(e,t,n){super("close",n),this.error=t,this.local=e}},R8=class extends zw{constructor(e,t){super(!0,e,t)}},L8=class extends zw{constructor(e,t){super(!1,e,t)}};var aY=Symbol.for("@libp2p/peer-id");var xCe="keep-alive";function vCe(r){return r!=null&&typeof r.start=="function"&&typeof r.stop=="function"}async function ECe(...r){let e=[];for(let t of r)vCe(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 SCe(...r){let e=[];for(let t of r)vCe(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 M8=Symbol.for("@libp2p/transport");var CCe;(function(r){r[r.FATAL_ALL=0]="FATAL_ALL",r[r.NO_FATAL=1]="NO_FATAL"})(CCe||(CCe={}));var Ci=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 o=this.#e.get(e);o==null&&(o=[],this.#e.set(e,o)),o.push({callback:t,once:(n!==!0&&n!==!1&&n?.once)??!1})}removeEventListener(e,t,n){super.removeEventListener(e.toString(),t??null,n);let o=this.#e.get(e);o!=null&&(o=o.filter(({callback:s})=>s!==t),this.#e.set(e,o))}dispatchEvent(e){let t=super.dispatchEvent(e),n=this.#e.get(e.type);return n==null||(n=n.filter(({once:o})=>!o),this.#e.set(e.type,n)),t}safeDispatchEvent(e,t={}){return this.dispatchEvent(new CustomEvent(e,t))}};var B8=Symbol.for("@libp2p/service-capabilities"),ACe=Symbol.for("@libp2p/service-dependencies");function zr(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 pn(r=0){return new Uint8Array(r)}function gs(r=0){return new Uint8Array(r)}var iat=Math.pow(2,7),aat=Math.pow(2,14),cat=Math.pow(2,21),cY=Math.pow(2,28),lY=Math.pow(2,35),uY=Math.pow(2,42),dY=Math.pow(2,49),dt=128,vo=127;function Gt(r){if(r<iat)return 1;if(r<aat)return 2;if(r<cat)return 3;if(r<cY)return 4;if(r<lY)return 5;if(r<uY)return 6;if(r<dY)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Ai(r,e,t=0){switch(Gt(r)){case 8:e[t++]=r&255|dt,r/=128;case 7:e[t++]=r&255|dt,r/=128;case 6:e[t++]=r&255|dt,r/=128;case 5:e[t++]=r&255|dt,r/=128;case 4:e[t++]=r&255|dt,r>>>=7;case 3:e[t++]=r&255|dt,r>>>=7;case 2:e[t++]=r&255|dt,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function lat(r,e,t=0){switch(Gt(r)){case 8:e.set(t++,r&255|dt),r/=128;case 7:e.set(t++,r&255|dt),r/=128;case 6:e.set(t++,r&255|dt),r/=128;case 5:e.set(t++,r&255|dt),r/=128;case 4:e.set(t++,r&255|dt),r>>>=7;case 3:e.set(t++,r&255|dt),r>>>=7;case 2:e.set(t++,r&255|dt),r>>>=7;case 1:{e.set(t++,r&255),r>>>=7;break}default:throw new Error("unreachable")}return e}function fY(r,e){let t=r[e],n=0;if(n+=t&vo,t<dt||(t=r[e+1],n+=(t&vo)<<7,t<dt)||(t=r[e+2],n+=(t&vo)<<14,t<dt)||(t=r[e+3],n+=(t&vo)<<21,t<dt)||(t=r[e+4],n+=(t&vo)*cY,t<dt)||(t=r[e+5],n+=(t&vo)*lY,t<dt)||(t=r[e+6],n+=(t&vo)*uY,t<dt)||(t=r[e+7],n+=(t&vo)*dY,t<dt))return n;throw new RangeError("Could not decode varint")}function uat(r,e){let t=r.get(e),n=0;if(n+=t&vo,t<dt||(t=r.get(e+1),n+=(t&vo)<<7,t<dt)||(t=r.get(e+2),n+=(t&vo)<<14,t<dt)||(t=r.get(e+3),n+=(t&vo)<<21,t<dt)||(t=r.get(e+4),n+=(t&vo)*cY,t<dt)||(t=r.get(e+5),n+=(t&vo)*lY,t<dt)||(t=r.get(e+6),n+=(t&vo)*uY,t<dt)||(t=r.get(e+7),n+=(t&vo)*dY,t<dt))return n;throw new RangeError("Could not decode varint")}function ICe(r,e,t=0){return e==null&&(e=gs(Gt(r))),e instanceof Uint8Array?Ai(r,e,t):lat(r,e,t)}function ma(r,e=0){return r instanceof Uint8Array?fY(r,e):uat(r,e)}function $r(r,e){e==null&&(e=r.reduce((o,s)=>o+s.length,0));let t=gs(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var yY={};W(yY,{base10:()=>yat});var aMr=new Uint8Array(0);function TCe(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 Ou(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 kCe(r){return new TextEncoder().encode(r)}function DCe(r){return new TextDecoder().decode(r)}function dat(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var fat=dat,hat=fat,PCe=hat;var hY=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")}},pY=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 RCe(this,e)}},mY=class{decoders;constructor(e){this.decoders=e}or(e){return RCe(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 RCe(r,e){return new mY({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var gY=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new hY(e,t,n),this.decoder=new pY(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function $w({name:r,prefix:e,encode:t,decode:n}){return new gY(r,e,t,n)}function $f({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=PCe(t,r);return $w({prefix:e,name:r,encode:n,decode:s=>Ou(o(s))})}function pat(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function mat(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function gat(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function br({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=gat(n);return $w({prefix:e,name:r,encode(s){return mat(s,n,t)},decode(s){return pat(s,o,t,r)}})}var yat=$f({prefix:"9",name:"base10",alphabet:"0123456789"});var bY={};W(bY,{base16:()=>bat,base16upper:()=>wat});var bat=br({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),wat=br({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var wY={};W(wY,{base2:()=>xat});var xat=br({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var xY={};W(xY,{base256emoji:()=>Aat});var LCe=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}"),vat=LCe.reduce((r,e,t)=>(r[t]=e,r),[]),Eat=LCe.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Sat(r){return r.reduce((e,t)=>(e+=vat[t],e),"")}function Cat(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Eat[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Aat=$w({prefix:"\u{1F680}",name:"base256emoji",encode:Sat,decode:Cat});var vY={};W(vY,{base32:()=>Ii,base32hex:()=>Dat,base32hexpad:()=>Pat,base32hexpadupper:()=>Rat,base32hexupper:()=>_at,base32pad:()=>Tat,base32padupper:()=>kat,base32upper:()=>Iat,base32z:()=>Lat});var Ii=br({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Iat=br({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Tat=br({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kat=br({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dat=br({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),_at=br({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Pat=br({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Rat=br({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Lat=br({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var EY={};W(EY,{base36:()=>jC,base36upper:()=>Mat});var jC=$f({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Mat=$f({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var SY={};W(SY,{base58btc:()=>_r,base58flickr:()=>Bat});var _r=$f({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Bat=$f({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var CY={};W(CY,{base64:()=>Oat,base64pad:()=>Nat,base64url:()=>cm,base64urlpad:()=>Uat});var Oat=br({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Nat=br({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),cm=br({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Uat=br({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var AY={};W(AY,{base8:()=>Fat});var Fat=br({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var IY={};W(IY,{identity:()=>Kat});var Kat=$w({prefix:"\0",name:"identity",encode:r=>DCe(r),decode:r=>kCe(r)});var SMr=new TextEncoder,CMr=new TextDecoder;var kY={};W(kY,{identity:()=>ga});var Hat=OCe,MCe=128,Vat=127,qat=~Vat,jat=Math.pow(2,31);function OCe(r,e,t){e=e||[],t=t||0;for(var n=t;r>=jat;)e[t++]=r&255|MCe,r/=128;for(;r&qat;)e[t++]=r&255|MCe,r>>>=7;return e[t]=r|0,OCe.bytes=t-n+1,e}var Gat=TY,Wat=128,BCe=127;function TY(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw TY.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&BCe)<<o:(i&BCe)*Math.pow(2,o),o+=7}while(i>=Wat);return TY.bytes=s-n,t}var Yat=Math.pow(2,7),Xat=Math.pow(2,14),Zat=Math.pow(2,21),Jat=Math.pow(2,28),Qat=Math.pow(2,35),ect=Math.pow(2,42),tct=Math.pow(2,49),rct=Math.pow(2,56),nct=Math.pow(2,63),oct=function(r){return r<Yat?1:r<Xat?2:r<Zat?3:r<Jat?4:r<Qat?5:r<ect?6:r<tct?7:r<rct?8:r<nct?9:10},sct={encode:Hat,decode:Gat,encodingLength:oct},ict=sct,GC=ict;function WC(r,e=0){return[GC.decode(r,e),GC.decode.bytes]}function Hw(r,e,t=0){return GC.encode(r,e,t),e}function Vw(r){return GC.encodingLength(r)}function jw(r,e){let t=e.byteLength,n=Vw(r),o=n+Vw(t),s=new Uint8Array(o+t);return Hw(r,s,0),Hw(t,s,n),s.set(e,o),new qw(r,t,e,s)}function Hf(r){let e=Ou(r),[t,n]=WC(e),[o,s]=WC(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new qw(t,o,i,e)}function NCe(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&TCe(r.bytes,t.bytes)}}var qw=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=n,this.bytes=o}};var UCe=0,act="identity",FCe=Ou;function cct(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 jw(UCe,FCe(r))}var ga={code:UCe,name:act,encode:FCe,digest:cct};var PY={};W(PY,{sha256:()=>Gw,sha512:()=>uct});var lct=20;function _Y({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new DY(r,e,t,n,o)}var DY=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??lct,this.maxDigestLength=s}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?KCe(n,this.code,t?.truncate):n.then(o=>KCe(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function KCe(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 jw(e,r)}function $Ce(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var Gw=_Y({name:"sha2-256",code:18,encode:$Ce("SHA-256")}),uct=_Y({name:"sha2-512",code:19,encode:$Ce("SHA-512")});function HCe(r,e){let{bytes:t,version:n}=r;return n===0?fct(t,RY(r),e??_r.encoder):hct(t,RY(r),e??Ii.encoder)}var VCe=new WeakMap;function RY(r){let e=VCe.get(r);if(e==null){let t=new Map;return VCe.set(r,t),t}return e}var wr=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==YC)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==pct)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=jw(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&&NCe(e.multihash,n.multihash)}toString(e){return HCe(this,e)}toJSON(){return{"/":HCe(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??qCe(n,o,s.bytes))}else if(t[mct]===!0){let{version:n,multihash:o,code:s}=t,i=Hf(o);return r.create(n,s,i)}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!==YC)throw new Error(`Version 0 CID must use dag-pb (code: ${YC}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=qCe(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,YC,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,o=Ou(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new qw(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=WC(e.subarray(t));return t+=h,d},o=n(),s=YC;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=dct(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return RY(s).set(n,e),s}};function dct(r,e){switch(r[0]){case"Q":{let t=e??_r;return[_r.prefix,t.decode(`${_r.prefix}${r}`)]}case _r.prefix:{let t=e??_r;return[_r.prefix,t.decode(r)]}case Ii.prefix:{let t=e??Ii;return[Ii.prefix,t.decode(r)]}case jC.prefix:{let t=e??jC;return[jC.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 fct(r,e,t){let{prefix:n}=t;if(n!==_r.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function hct(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var YC=112,pct=18;function qCe(r,e,t){let n=Vw(r),o=n+Vw(e),s=new Uint8Array(o+t.byteLength);return Hw(r,s,0),Hw(e,s,n),s.set(t,o),s}var mct=Symbol.for("@ipld/js-cid/CID");var Nu={...IY,...wY,...AY,...yY,...bY,...vY,...EY,...SY,...CY,...xY},jMr={...PY,...kY};function GCe(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var jCe=GCe("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),LY=GCe("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=gs(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),gct={utf8:jCe,"utf-8":jCe,hex:Nu.base16,latin1:LY,ascii:LY,binary:LY,...Nu},U8=gct;function Ze(r,e="utf8"){let t=U8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}function We(r,e="utf8"){let t=U8[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}var Gn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Uu=class extends Error{static name="ValidationError";name="ValidationError"},F8=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},K8=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};var z8=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,o){return this.readAtomically(()=>{let s=0,i=0,a=this.peekChar();if(a===void 0)return;let c=a==="0",l=2**(8*o)-1;for(;;){let u=this.readAtomically(()=>{let d=this.readChar();if(d===void 0)return;let h=Number.parseInt(d,e);if(!Number.isNaN(h))return h});if(u===void 0)break;if(s*=e,s+=u,s>l||(i+=1,t!==void 0&&i>t))return}if(i!==0)return!n&&c&&i>1?void 0:s})}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 o=n*2;if(n<t.length-3){let i=this.readSeparator(":",n,()=>this.readIPv4Addr());if(i!==void 0)return t[o]=i[0],t[o+1]=i[1],t[o+2]=i[2],t[o+3]=i[3],[o+4,!0]}let s=this.readSeparator(":",n,()=>this.readNumber(16,4,!0,2));if(s===void 0)return[o,!1];t[o]=s>>8,t[o+1]=s&255}return[t.length,!1]};return this.readAtomically(()=>{let t=new Uint8Array(16),[n,o]=e(t);if(n===16)return t;if(o||this.readGivenChar(":")===void 0||this.readGivenChar(":")===void 0)return;let s=new Uint8Array(14),i=16-(n+2),[a]=e(s.subarray(0,i));return t.set(s.subarray(0,a),16-a),t})}readIPAddr(){return this.readIPv4Addr()??this.readIPv6Addr()}};var yct=45,bct=15,$8=new z8;function WCe(r){if(!(r.length>bct))return $8.new(r).parseWith(()=>$8.readIPv4Addr())}function YCe(r){if(r.includes("%")&&(r=r.split("%")[0]),!(r.length>yct))return $8.new(r).parseWith(()=>$8.readIPv6Addr())}function Ti(r){return!!WCe(r)}function Ww(r){return!!YCe(r)}function BY(r){return e=>We(e,r)}function OY(r){return e=>Ze(e,r)}function Yw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function lm(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function XCe(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=Ze(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 o=lm(n);return $r([t,o],t.length+o.length)}function ZCe(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=Ii.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 o=lm(n);return $r([t,o],t.length+o.length)}function NY(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=We(e,"base32"),o=Yw(t);return`${n}:${o}`}var UY=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Gn("Invalid byte value in IP address");e[n]=o}),e},JCe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ti(t[n]),i;s&&(i=UY(t[n]),t[n]=We(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,We(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Gn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},QCe=function(r){if(r.byteLength!==4)throw new Gn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},eAe=function(r){if(r.byteLength!==16)throw new Gn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Gn(`Invalid IPv6 address "${t}"`)}};function tAe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Gn(`Invalid IPv6 address "${r}"`)}}var MY=Object.values(Nu).map(r=>r.decoder),wct=(function(){let r=MY[0].or(MY[1]);return MY.slice(2).forEach(e=>r=r.or(e)),r})();function rAe(r){return wct.decode(r)}function nAe(r){return e=>r.encoder.encode(e)}function xct(r){if(parseInt(r).toString()!==r)throw new Uu("Value must be an integer")}function vct(r){if(r<0)throw new Uu("Value must be a positive integer, or zero")}function Ect(r){return e=>{if(e>r)throw new Uu(`Value must be smaller than or equal to ${r}`)}}function Sct(...r){return e=>{for(let t of r)t(e)}}var XC=Sct(xct,vct,Ect(65535));var mn=-1,FY=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 K8(`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)}))}},Fu=new FY,Uct=[{code:4,name:"ip4",size:32,valueToBytes:UY,bytesToValue:QCe,validate:r=>{if(!Ti(r))throw new Uu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:273,name:"udp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:33,name:"dccp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:41,name:"ip6",size:128,valueToBytes:JCe,bytesToValue:eAe,stringToValue:tAe,validate:r=>{if(!Ww(r))throw new Uu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:mn},{code:43,name:"ipcidr",size:8,bytesToValue:BY("base10"),valueToBytes:OY("base10")},{code:53,name:"dns",size:mn},{code:54,name:"dns4",size:mn},{code:55,name:"dns6",size:mn},{code:56,name:"dnsaddr",size:mn},{code:132,name:"sctp",size:16,valueToBytes:lm,bytesToValue:Yw,validate:XC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:mn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:mn,bytesToValue:BY("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?OY("base58btc")(r):wr.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:NY,valueToBytes:XCe},{code:445,name:"onion3",size:296,bytesToValue:NY,valueToBytes:ZCe},{code:446,name:"garlic64",size:mn},{code:447,name:"garlic32",size:mn},{code:448,name:"tls"},{code:449,name:"sni",size:mn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:mn,bytesToValue:nAe(cm),valueToBytes:rAe},{code:480,name:"http"},{code:481,name:"http-path",size:mn,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:mn}];Uct.forEach(r=>{Fu.addProtocol(r)});function oAe(r){let e=[],t=0;for(;t<r.length;){let n=ma(r,t),o=Fu.getProtocol(n),s=Gt(n),i=Fct(o,r,t+s),a=0;i>0&&o.size===mn&&(a=Gt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??We(d)}e.push(l),t+=c}return e}function sAe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Fu.getProtocol(n.code),s=Gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Ze(n.value),a=i.byteLength,o.size===mn&&(c=Gt(a)));let l=new Uint8Array(s+c+a),u=0;Ai(n.code,l,u),u+=s,i!=null&&(o.size===mn&&(Ai(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return $r(t,e)}function iAe(r){if(r.charAt(0)!=="/")throw new Gn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Fu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Gn(`Component ${o} 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 Gn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Gn("Incomplete multiaddr");return e}function aAe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Fu.getProtocol(e.code);if(t==null)throw new Gn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Fct(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ma(e,t)}var Kct=Symbol.for("nodejs.util.inspect.custom"),nX=Symbol.for("@multiformats/multiaddr");function zct(r){if(r==null&&(r="/"),cAe(r))return r.getComponents();if(r instanceof Uint8Array)return oAe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),iAe(r);if(Array.isArray(r))return r;throw new Gn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var rX=class r{[nX]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=zct(e),t.validate!==!1&&$ct(this)}get bytes(){return this.#r==null&&(this.#r=sAe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=aAe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new F8(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return zr(this.bytes,e.bytes)}[Kct](){return`Multiaddr(${this.toString()})`}};function $ct(r){r.getComponents().forEach(e=>{let t=Fu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function cAe(r){return!!r?.[nX]}var Ct=r=>({match:e=>{let t=e[0];return t==null||t.code!==r||t.value!=null?!1:e.slice(1)}}),ke=(r,e)=>({match:t=>{let n=t[0];return n?.code!==r||n.value==null||e!=null&&n.value!==e?!1:t.slice(1)}}),lAe=r=>({match:e=>r.match(e)===!1?e:!1}),Je=r=>({match:e=>{let t=r.match(e);return t===!1?e:t}}),Eo=(...r)=>({match:e=>{let t;for(let n of r){let o=n.match(e);o!==!1&&(t==null||o.length<t.length)&&(t=o)}return t??!1}}),st=(...r)=>({match:e=>{for(let t of r){let n=t.match(e);if(n===!1)return!1;e=n}return e}});function At(...r){function e(o){if(o==null)return!1;let s=o.getComponents();for(let i of r){let a=i.match(s);if(a===!1)return!1;s=a}return s}function t(o){return e(o)!==!1}function n(o){let s=e(o);return s===!1?!1:s.length===0}return{matchers:r,matches:t,exactMatch:n}}var Hct=ke(421),jBr=At(Hct),W8=ke(54),Y8=ke(55),X8=ke(56),sX=ke(53),GBr=At(W8,Je(ke(421))),WBr=At(Y8,Je(ke(421))),YBr=At(X8,Je(ke(421))),XBr=At(Eo(sX,X8,W8,Y8),Je(ke(421))),uAe=st(ke(4),Je(ke(43))),dAe=st(Je(ke(42)),ke(41),Je(ke(43))),iX=Eo(uAe,dAe),fm=Eo(iX,sX,W8,Y8,X8),ZBr=At(Eo(iX,st(Eo(sX,X8,W8,Y8),Je(ke(421))))),JBr=At(uAe),QBr=At(dAe),eOr=At(iX),aX=st(fm,ke(6)),ZC=st(fm,ke(273)),tOr=At(st(aX,Je(ke(421)))),rOr=At(ZC),cX=st(ZC,Ct(460),Je(ke(421))),Z8=st(ZC,Ct(461),Je(ke(421))),Vct=Eo(cX,Z8),nOr=At(cX),oOr=At(Z8),oX=Eo(fm,aX,ZC,cX,Z8),fAe=Eo(st(oX,Ct(477),Je(ke(421)))),hAe=At(fAe),pAe=Eo(st(oX,Ct(478),Je(ke(421))),st(oX,Ct(448),Je(ke(449)),Ct(477),Je(ke(421)))),mAe=At(pAe),gAe=st(ZC,Ct(280),Je(ke(466)),Je(ke(466)),Je(ke(421))),sOr=At(gAe),yAe=st(Z8,Ct(465),Je(ke(466)),Je(ke(466)),Je(ke(421))),iOr=At(yAe),G8=Eo(fAe,pAe,st(aX,Je(ke(421))),st(Vct,Je(ke(421))),st(fm,Je(ke(421))),gAe,yAe,ke(421)),bAe=At(G8),qct=st(Je(G8),Ct(290),lAe(Ct(281)),Je(ke(421))),J8=At(qct),jct=Eo(st(G8,Ct(290),Ct(281),Je(ke(421))),st(G8,Ct(281),Je(ke(421))),st(Ct(281),Je(ke(421)))),aOr=At(jct),Gct=Eo(st(fm,ke(6),Ct(480),Je(ke(421))),st(fm,Ct(480),Je(ke(421)))),cOr=At(Gct),Wct=st(fm,Eo(st(ke(6,"443"),Ct(480)),st(ke(6),Ct(443)),st(ke(6),Ct(448),Ct(480)),st(Ct(448),Ct(480)),Ct(448),Ct(443)),Je(ke(421))),lOr=At(Wct),Yct=Eo(st(ke(777),Je(ke(421)))),uOr=At(Yct),Xct=Eo(st(ke(400),Je(ke(421)))),dOr=At(Xct);var Wn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Ku=class extends Error{static name="ValidationError";name="ValidationError"},Q8=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},eL=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function uX(r){return e=>We(e,r)}function dX(r){return e=>Ze(e,r)}function Qw(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function hm(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function wAe(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=Ze(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 o=hm(n);return $r([t,o],t.length+o.length)}function xAe(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=Ii.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 o=hm(n);return $r([t,o],t.length+o.length)}function fX(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=We(e,"base32"),o=Qw(t);return`${n}:${o}`}var hX=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Wn("Invalid byte value in IP address");e[n]=o}),e},vAe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ti(t[n]),i;s&&(i=hX(t[n]),t[n]=We(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,We(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Wn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},EAe=function(r){if(r.byteLength!==4)throw new Wn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},SAe=function(r){if(r.byteLength!==16)throw new Wn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Wn(`Invalid IPv6 address "${t}"`)}};function CAe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Wn(`Invalid IPv6 address "${r}"`)}}var lX=Object.values(Nu).map(r=>r.decoder),Zct=(function(){let r=lX[0].or(lX[1]);return lX.slice(2).forEach(e=>r=r.or(e)),r})();function AAe(r){return Zct.decode(r)}function IAe(r){return e=>r.encoder.encode(e)}function Jct(r){if(parseInt(r).toString()!==r)throw new Ku("Value must be an integer")}function Qct(r){if(r<0)throw new Ku("Value must be a positive integer, or zero")}function elt(r){return e=>{if(e>r)throw new Ku(`Value must be smaller than or equal to ${r}`)}}function tlt(...r){return e=>{for(let t of r)t(e)}}var JC=tlt(Jct,Qct,elt(65535));var gn=-1,pX=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 eL(`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)}))}},zu=new pX,Blt=[{code:4,name:"ip4",size:32,valueToBytes:hX,bytesToValue:EAe,validate:r=>{if(!Ti(r))throw new Ku(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:273,name:"udp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:33,name:"dccp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:41,name:"ip6",size:128,valueToBytes:vAe,bytesToValue:SAe,stringToValue:CAe,validate:r=>{if(!Ww(r))throw new Ku(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:gn},{code:43,name:"ipcidr",size:8,bytesToValue:uX("base10"),valueToBytes:dX("base10")},{code:53,name:"dns",size:gn},{code:54,name:"dns4",size:gn},{code:55,name:"dns6",size:gn},{code:56,name:"dnsaddr",size:gn},{code:132,name:"sctp",size:16,valueToBytes:hm,bytesToValue:Qw,validate:JC},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:gn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:gn,bytesToValue:uX("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?dX("base58btc")(r):wr.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:fX,valueToBytes:wAe},{code:445,name:"onion3",size:296,bytesToValue:fX,valueToBytes:xAe},{code:446,name:"garlic64",size:gn},{code:447,name:"garlic32",size:gn},{code:448,name:"tls"},{code:449,name:"sni",size:gn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:gn,bytesToValue:IAe(cm),valueToBytes:AAe},{code:480,name:"http"},{code:481,name:"http-path",size:gn,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:gn}];Blt.forEach(r=>{zu.addProtocol(r)});function TAe(r){let e=[],t=0;for(;t<r.length;){let n=ma(r,t),o=zu.getProtocol(n),s=Gt(n),i=Olt(o,r,t+s),a=0;i>0&&o.size===gn&&(a=Gt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??We(d)}e.push(l),t+=c}return e}function kAe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=zu.getProtocol(n.code),s=Gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Ze(n.value),a=i.byteLength,o.size===gn&&(c=Gt(a)));let l=new Uint8Array(s+c+a),u=0;Ai(n.code,l,u),u+=s,i!=null&&(o.size===gn&&(Ai(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return $r(t,e)}function DAe(r){if(r.charAt(0)!=="/")throw new Wn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=zu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Wn(`Component ${o} 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 Wn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Wn("Incomplete multiaddr");return e}function _Ae(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=zu.getProtocol(e.code);if(t==null)throw new Wn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function Olt(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ma(e,t)}var Nlt=Symbol.for("nodejs.util.inspect.custom"),EX=Symbol.for("@multiformats/multiaddr");function Ult(r){if(r==null&&(r="/"),PAe(r))return r.getComponents();if(r instanceof Uint8Array)return TAe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),DAe(r);if(Array.isArray(r))return r;throw new Wn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var tL=class r{[EX]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=Ult(e),t.validate!==!1&&Flt(this)}get bytes(){return this.#r==null&&(this.#r=kAe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=_Ae(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new Q8(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return zr(this.bytes,e.bytes)}[Nlt](){return`Multiaddr(${this.toString()})`}};function Flt(r){r.getComponents().forEach(e=>{let t=zu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function PAe(r){return!!r?.[EX]}function RAe(r){return new tL(r)}var Klt=[6,53,56,54,55];function LAe(r){return OAe("sni",r)?.value}function MAe(r){let e=OAe("tcp",r)?.value;return e==null?"":`:${e}`}function OAe(r,e){return e.find(t=>t.name===r)}function BAe(r){return r.some(({code:e})=>e===448)}function ya(r,e){let t=NAe[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 NAe={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://${ya(t,e)}:${r.value}`},udp:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`udp://${ya(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`${ya(t,e)}`},p2p:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return`${ya(t,e)}`},http:(r,e)=>{let t=BAe(e),n=LAe(e),o=MAe(e);if(t&&n!=null)return`https://${n}${o}`;let s=t?"https://":"http://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ya(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},"http-path":(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ya(t,e),o=decodeURIComponent(r.value??"");return`${n}${o}`},tls:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ya(t,e)},sni:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");return ya(t,e)},https:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ya(t,e);return n=n?.replace("tcp://",""),`https://${n}`},ws:(r,e)=>{let t=BAe(e),n=LAe(e),o=MAe(e);if(t&&n!=null)return`wss://${n}${o}`;let s=t?"wss://":"ws://",i=e.pop();if(i==null)throw new Error("Unexpected end of multiaddr");let a=ya(i,e);return a=a?.replace("tcp://",""),`${s}${a}`},wss:(r,e)=>{let t=e.pop();if(t==null)throw new Error("Unexpected end of multiaddr");let n=ya(t,e);return n=n?.replace("tcp://",""),`wss://${n}`}};function UAe(r,e){let n=RAe(r).getComponents(),o=n.pop();if(o==null)throw new Error("Unexpected end of multiaddr");let s=NAe[o.name];if(s==null)throw new Error(`No interpreter found for ${o.name}`);let i=s(o,n)??"";return e?.assumeHttp!==!1&&Klt.includes(o.code)&&(i=i.replace(/^.*:\/\//,""),o.value==="443"?i=`https://${i}`:i=`http://${i}`),(i.startsWith("http://")||i.startsWith("https://")||i.startsWith("ws://")||i.startsWith("wss://"))&&(i=new URL(i).toString(),i.endsWith("/")&&(i=i.substring(0,i.length-1))),i}var SX=class r extends Error{name="TimeoutError";constructor(e,t){super(e,t),Error.captureStackTrace?.(this,r)}},FAe=r=>r.reason??new DOMException("This operation was aborted.","AbortError");function CX(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout},signal:i}=e,a,c,u=new Promise((d,h)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(i?.aborted){h(FAe(i));return}if(i&&(c=()=>{h(FAe(i))},i.addEventListener("abort",c,{once:!0})),r.then(d,h),t===Number.POSITIVE_INFINITY)return;let p=new SX;a=s.setTimeout.call(void 0,()=>{if(n){try{d(n())}catch(f){h(f)}return}typeof r.cancel=="function"&&r.cancel(),o===!1?d():o instanceof Error?h(o):(p.message=o??`Promise timed out after ${t} milliseconds`,h(p))},t)}).finally(()=>{u.clear(),c&&i&&i.removeEventListener("abort",c)});return u.clear=()=>{s.clearTimeout.call(void 0,a),a=void 0},u}var zlt=r=>{let e=r.addEventListener||r.on||r.addListener,t=r.removeEventListener||r.off||r.removeListener;if(!e||!t)throw new TypeError("Emitter is not compatible");return{addListener:e.bind(r),removeListener:t.bind(r)}};function $lt(r,e,t){let n,o=new Promise((s,i)=>{if(t={rejectionEvents:["error"],multiArgs:!1,rejectionMultiArgs:!1,resolveImmediately:!1,...t},!(t.count>=0&&(t.count===Number.POSITIVE_INFINITY||Number.isInteger(t.count))))throw new TypeError("The `count` option should be at least 0 or more");t.signal?.throwIfAborted();let a=[e].flat(),c=[],{addListener:l,removeListener:u}=zlt(r),d=async(...p)=>{let f=t.multiArgs?p:p[0];if(t.filter)try{if(!await t.filter(f))return}catch(g){n(),i(g);return}c.push(f),t.count===c.length&&(n(),s(c))},h=(...p)=>{n(),i(t.rejectionMultiArgs?p:p[0])};n=()=>{for(let p of a)u(p,d);for(let p of t.rejectionEvents)a.includes(p)||u(p,h)};for(let p of a)l(p,d);for(let p of t.rejectionEvents)a.includes(p)||l(p,h);t.signal&&t.signal.addEventListener("abort",()=>{h(t.signal.reason)},{once:!0}),t.resolveImmediately&&s(c)});if(o.cancel=n,typeof t.timeout=="number"){let s=CX(o,{milliseconds:t.timeout});return s.cancel=()=>{n(),s.clear()},s}return o}function ba(r,e,t){typeof t=="function"&&(t={filter:t}),t={...t,count:1,resolveImmediately:!1};let n=$lt(r,e,t),o=n.then(s=>s[0]);return o.cancel=n.cancel,o}var Fc=class extends Event{type;detail;constructor(e,t){super(e),this.type=e,this.detail=t}};function KAe(){throw new Error("WebSocket Servers can not be created in the browser!")}var QC=class extends Error{constructor(e="An error occurred while verifying a message"){super(e),this.name="VerificationError"}},rL=class extends Error{constructor(e="Missing Web Crypto API"){super(e),this.name="WebCryptoMissingError"}};var zAe={get(r=globalThis){let e=r.crypto;if(e?.subtle==null)throw new rL("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 nL=zAe;var HAe=Symbol.for("@achingbrain/uint8arraylist");function $Ae(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let o=t+n.byteLength;if(e<o)return{buf:n,index:e-t};t=o}throw new RangeError("index is out of bounds")}function oL(r){return!!r?.[HAe]}var xr=class r{bufs;length;[HAe]=!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(oL(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(oL(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=$Ae(this.bufs,e);return t.buf[t.index]}set(e,t){let n=$Ae(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(oL(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:o}=this._subList(e,t);return $r(n,o)}subarray(e,t){let{bufs:n,length:o}=this._subList(e,t);return n.length===1?n[0]:$r(n,o)}sublist(e,t){let{bufs:n,length:o}=this._subList(e,t),s=new r;return s.length=o,s.bufs=[...n],s}_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=[],o=0;for(let s=0;s<this.bufs.length;s++){let i=this.bufs[s],a=o,c=a+i.byteLength;if(o=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(i);break}let d=e-a;n.push(i.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(i);continue}n.push(i.subarray(e-a));continue}if(u){if(t===c){n.push(i);break}n.push(i.subarray(0,t-a));break}n.push(i)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!oL(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 o=n.byteLength;if(o===0)throw new TypeError("search must be at least 1 byte long");let s=256,i=new Int32Array(s);for(let d=0;d<s;d++)i[d]=-1;for(let d=0;d<o;d++)i[n[d]]=d;let a=i,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let h=l;h>=0;h--){let p=this.get(d+h);if(n[h]!==p){u=Math.max(1,h-a[p]);break}}if(u===0)return d}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=gs(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 o=pn(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt16(0,t,n),this.write(o,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 o=pn(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setInt32(0,t,n),this.write(o,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 o=pn(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigInt64(0,t,n),this.write(o,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=gs(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 o=pn(2);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint16(0,t,n),this.write(o,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 o=pn(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setUint32(0,t,n),this.write(o,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 o=pn(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setBigUint64(0,t,n),this.write(o,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 o=pn(4);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat32(0,t,n),this.write(o,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 o=pn(8);new DataView(o.buffer,o.byteOffset,o.byteLength).setFloat64(0,t,n),this.write(o,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(!zr(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((o,s)=>o+s.byteLength,0)),n.length=t,n}};var Hlt=parseInt("11111",2),AX=parseInt("10000000",2),Vlt=parseInt("01111111",2),VAe={0:eA,1:eA,2:qlt,3:Wlt,4:Ylt,5:Glt,6:jlt,16:eA,22:eA,48:eA};function IX(r,e={offset:0}){let t=r[e.offset]&Hlt;if(e.offset++,VAe[t]!=null)return VAe[t](r,e);throw new Error("No decoder for tag "+t)}function tA(r,e){let t=0;if((r[e.offset]&AX)===AX){let n=r[e.offset]&Vlt,o="0x";e.offset++;for(let s=0;s<n;s++,e.offset++)o+=r[e.offset].toString(16).padStart(2,"0");t=parseInt(o,16)}else t=r[e.offset],e.offset++;return t}function eA(r,e){tA(r,e);let t=[];for(;!(e.offset>=r.byteLength);){let n=IX(r,e);if(n===null)break;t.push(n)}return t}function qlt(r,e){let t=tA(r,e),n=e.offset,o=e.offset+t,s=[];for(let i=n;i<o;i++)i===n&&r[i]===0||s.push(r[i]);return e.offset+=t,Uint8Array.from(s)}function jlt(r,e){let t=tA(r,e),n=e.offset+t,o=r[e.offset];e.offset++;let s=0,i=0;o<40?(s=0,i=o):o<80?(s=1,i=o-40):(s=2,i=o-80);let a=`${s}.${i}`,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 d=0;d<c.length;d++)u+=c[d]<<d*7;a+=`.${u}`,c=[]}}return a}function Glt(r,e){return e.offset++,null}function Wlt(r,e){let t=tA(r,e),n=r[e.offset];e.offset++;let o=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 o}function Ylt(r,e){let t=tA(r,e),n=r.subarray(e.offset,e.offset+t);return e.offset+=t,n}function Xlt(r){let e=r.toString(16);e.length%2===1&&(e="0"+e);let t=new xr;for(let n=0;n<e.length;n+=2)t.append(Uint8Array.from([parseInt(`${e[n]}${e[n+1]}`,16)]));return t}function TX(r){if(r.byteLength<128)return Uint8Array.from([r.byteLength]);let e=Xlt(r.byteLength);return new xr(Uint8Array.from([e.byteLength|AX]),e)}function qAe(r){let e=new xr,t=128;return(r.subarray()[0]&t)===t&&e.append(Uint8Array.from([0])),e.append(r),new xr(Uint8Array.from([2]),TX(e),e)}function jAe(r){let e=Uint8Array.from([0]),t=new xr(e,r);return new xr(Uint8Array.from([3]),TX(t),t)}function sL(r,e=48){let t=new xr;for(let n of r)t.append(n);return new xr(Uint8Array.from([e]),TX(t),t)}async function GAe(r,e,t,n){let o=await crypto.subtle.importKey("jwk",r,{name:"ECDSA",namedCurve:r.crv??"P-256"},!1,["verify"]);n?.signal?.throwIfAborted();let s=await crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},o,e,t.subarray());return n?.signal?.throwIfAborted(),s}var Zlt=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),Jlt=Uint8Array.from([6,5,43,129,4,0,34]),Qlt=Uint8Array.from([6,5,43,129,4,0,35]),eut={ext:!0,kty:"EC",crv:"P-256"},tut={ext:!0,kty:"EC",crv:"P-384"},rut={ext:!0,kty:"EC",crv:"P-521"},kX=32,DX=48,_X=66;function WAe(r){let e=IX(r);return YAe(e)}function YAe(r){let e=r[1][1][0],t=1,n,o;if(e.byteLength===kX*2+1)return n=We(e.subarray(t,t+kX),"base64url"),o=We(e.subarray(t+kX),"base64url"),new ex({...eut,key_ops:["verify"],x:n,y:o});if(e.byteLength===DX*2+1)return n=We(e.subarray(t,t+DX),"base64url"),o=We(e.subarray(t+DX),"base64url"),new ex({...tut,key_ops:["verify"],x:n,y:o});if(e.byteLength===_X*2+1)return n=We(e.subarray(t,t+_X),"base64url"),o=We(e.subarray(t+_X),"base64url"),new ex({...rut,key_ops:["verify"],x:n,y:o});throw new Si(`coordinates were wrong length, got ${e.byteLength}, expected 65, 97 or 133`)}function XAe(r){return sL([qAe(Uint8Array.from([1])),sL([nut(r.crv)],160),sL([jAe(new xr(Uint8Array.from([4]),Ze(r.x??"","base64url"),Ze(r.y??"","base64url")))],161)]).subarray()}function nut(r){if(r==="P-256")return Zlt;if(r==="P-384")return Jlt;if(r==="P-521")return Qlt;throw new Si(`Invalid curve ${r}`)}var ex=class{type="ECDSA";jwk;_raw;constructor(e){this.jwk=e}get raw(){return this._raw==null&&(this._raw=XAe(this.jwk)),this._raw}toMultihash(){return ga.digest(tx(this))}toCID(){return wr.createV1(114,this.toMultihash())}toString(){return _r.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:zr(this.raw,e.raw)}async verify(e,t,n){return GAe(this.jwk,t,e,n)}};function pm(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Kc(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function $e(r,e,t=""){let n=pm(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function iL(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Kc(r.outputLen),Kc(r.blockLen)}function rx(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 JAe(r,e){$e(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function Hu(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function aL(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function wa(r,e){return r<<32-e|r>>>e}var QAe=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",out=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Vu(r){if($e(r),QAe)return r.toHex();let e="";for(let t=0;t<r.length;t++)e+=out[r[t]];return e}var $u={_0:48,_9:57,A:65,F:70,a:97,f:102};function ZAe(r){if(r>=$u._0&&r<=$u._9)return r-$u._0;if(r>=$u.A&&r<=$u.F)return r-($u.A-10);if(r>=$u.a&&r<=$u.f)return r-($u.a-10)}function qu(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(QAe)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 o=0,s=0;o<t;o++,s+=2){let i=ZAe(r.charCodeAt(s)),a=ZAe(r.charCodeAt(s+1));if(i===void 0||a===void 0){let c=r[s]+r[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function ys(...r){let e=0;for(let n=0;n<r.length;n++){let o=r[n];$e(o),e+=o.length}let t=new Uint8Array(e);for(let n=0,o=0;n<r.length;n++){let s=r[n];t.set(s,o),o+=s.length}return t}function PX(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function nx(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var RX=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function eIe(r,e,t){return r&e^~r&t}function tIe(r,e,t){return r&e^r&t^e&t}var rA=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=aL(this.buffer)}update(e){rx(this),$e(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=aL(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){rx(this),JAe(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,Hu(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=aL(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must 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 d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},ju=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Yn=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var cL=BigInt(4294967295),rIe=BigInt(32);function sut(r,e=!1){return e?{h:Number(r&cL),l:Number(r>>rIe&cL)}:{h:Number(r>>rIe&cL)|0,l:Number(r&cL)|0}}function nIe(r,e=!1){let t=r.length,n=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:i,l:a}=sut(r[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var LX=(r,e,t)=>r>>>t,MX=(r,e,t)=>r<<32-t|e>>>t,mm=(r,e,t)=>r>>>t|e<<32-t,gm=(r,e,t)=>r<<32-t|e>>>t,nA=(r,e,t)=>r<<64-t|e>>>t-32,oA=(r,e,t)=>r>>>t-32|e<<64-t;function zc(r,e,t,n){let o=(e>>>0)+(n>>>0);return{h:r+t+(o/2**32|0)|0,l:o|0}}var oIe=(r,e,t)=>(r>>>0)+(e>>>0)+(t>>>0),sIe=(r,e,t,n)=>e+t+n+(r/2**32|0)|0,iIe=(r,e,t,n)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0),aIe=(r,e,t,n,o)=>e+t+n+o+(r/2**32|0)|0,cIe=(r,e,t,n,o)=>(r>>>0)+(e>>>0)+(t>>>0)+(n>>>0)+(o>>>0),lIe=(r,e,t,n,o,s)=>e+t+n+o+s+(r/2**32|0)|0;var aut=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]),qf=new Uint32Array(64),BX=class extends rA{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)qf[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=qf[d-15],p=qf[d-2],f=wa(h,7)^wa(h,18)^h>>>3,g=wa(p,17)^wa(p,19)^p>>>10;qf[d]=g+qf[d-7]+f+qf[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=wa(a,6)^wa(a,11)^wa(a,25),p=u+h+eIe(a,c,l)+aut[d]+qf[d]|0,g=(wa(n,2)^wa(n,13)^wa(n,22))+tIe(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){Hu(qf)}destroy(){this.set(0,0,0,0,0,0,0,0),Hu(this.buffer)}},OX=class extends BX{A=ju[0]|0;B=ju[1]|0;C=ju[2]|0;D=ju[3]|0;E=ju[4]|0;F=ju[5]|0;G=ju[6]|0;H=ju[7]|0;constructor(){super(32)}};var uIe=nIe(["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))),cut=uIe[0],lut=uIe[1],jf=new Uint32Array(80),Gf=new Uint32Array(80),NX=class extends rA{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:l,El:u,Fh:d,Fl:h,Gh:p,Gl:f,Hh:g,Hl:y}=this;return[e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y]}set(e,t,n,o,s,i,a,c,l,u,d,h,p,f,g,y){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=d|0,this.Fl=h|0,this.Gh=p|0,this.Gl=f|0,this.Hh=g|0,this.Hl=y|0}process(e,t){for(let b=0;b<16;b++,t+=4)jf[b]=e.getUint32(t),Gf[b]=e.getUint32(t+=4);for(let b=16;b<80;b++){let x=jf[b-15]|0,S=Gf[b-15]|0,T=mm(x,S,1)^mm(x,S,8)^LX(x,S,7),A=gm(x,S,1)^gm(x,S,8)^MX(x,S,7),v=jf[b-2]|0,C=Gf[b-2]|0,P=mm(v,C,19)^nA(v,C,61)^LX(v,C,6),F=gm(v,C,19)^oA(v,C,61)^MX(v,C,6),R=iIe(A,F,Gf[b-7],Gf[b-16]),k=aIe(R,T,P,jf[b-7],jf[b-16]);jf[b]=k|0,Gf[b]=R|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:l,Dl:u,Eh:d,El:h,Fh:p,Fl:f,Gh:g,Gl:y,Hh:m,Hl:w}=this;for(let b=0;b<80;b++){let x=mm(d,h,14)^mm(d,h,18)^nA(d,h,41),S=gm(d,h,14)^gm(d,h,18)^oA(d,h,41),T=d&p^~d&g,A=h&f^~h&y,v=cIe(w,S,A,lut[b],Gf[b]),C=lIe(v,m,x,T,cut[b],jf[b]),P=v|0,F=mm(n,o,28)^nA(n,o,34)^nA(n,o,39),R=gm(n,o,28)^oA(n,o,34)^oA(n,o,39),k=n&s^n&a^s&a,I=o&i^o&c^i&c;m=g|0,w=y|0,g=p|0,y=f|0,p=d|0,f=h|0,{h:d,l:h}=zc(l|0,u|0,C|0,P|0),l=a|0,u=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let E=oIe(P,R,I);n=sIe(E,C,F,k),o=E|0}({h:n,l:o}=zc(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=zc(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=zc(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=zc(this.Dh|0,this.Dl|0,l|0,u|0),{h:d,l:h}=zc(this.Eh|0,this.El|0,d|0,h|0),{h:p,l:f}=zc(this.Fh|0,this.Fl|0,p|0,f|0),{h:g,l:y}=zc(this.Gh|0,this.Gl|0,g|0,y|0),{h:m,l:w}=zc(this.Hh|0,this.Hl|0,m|0,w|0),this.set(n,o,s,i,a,c,l,u,d,h,p,f,g,y,m,w)}roundClean(){Hu(jf,Gf)}destroy(){Hu(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},UX=class extends NX{Ah=Yn[0]|0;Al=Yn[1]|0;Bh=Yn[2]|0;Bl=Yn[3]|0;Ch=Yn[4]|0;Cl=Yn[5]|0;Dh=Yn[6]|0;Dl=Yn[7]|0;Eh=Yn[8]|0;El=Yn[9]|0;Fh=Yn[10]|0;Fl=Yn[11]|0;Gh=Yn[12]|0;Gl=Yn[13]|0;Hh=Yn[14]|0;Hl=Yn[15]|0;constructor(){super(64)}};var dIe=PX(()=>new OX,RX(1));var fIe=PX(()=>new UX,RX(3));var KX=BigInt(0),FX=BigInt(1);function Gu(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function hIe(r){if(typeof r=="bigint"){if(!lL(r))throw new Error("positive bigint expected, got "+r)}else Kc(r);return r}function sA(r){let e=hIe(r).toString(16);return e.length&1?"0"+e:e}function pIe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?KX:BigInt("0x"+r)}function ox(r){return pIe(Vu(r))}function ym(r){return pIe(Vu(dL($e(r)).reverse()))}function uL(r,e){Kc(e),r=hIe(r);let t=qu(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function zX(r,e){return uL(r,e).reverse()}function dL(r){return Uint8Array.from(r)}var lL=r=>typeof r=="bigint"&&KX<=r;function uut(r,e,t){return lL(r)&&lL(e)&&lL(t)&&e<=r&&r<t}function iA(r,e,t,n){if(!uut(e,t,n))throw new Error("expected valid "+r+": "+t+" <= n < "+n+", got "+e)}function $X(r){let e;for(e=0;r>KX;r>>=FX,e+=1);return e}var aA=r=>(FX<<BigInt(r))-FX;function mIe(r,e,t){if(Kc(r,"hashLen"),Kc(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");let n=y=>new Uint8Array(y),o=Uint8Array.of(),s=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3,c=n(r),l=n(r),u=0,d=()=>{c.fill(1),l.fill(0),u=0},h=(...y)=>t(l,ys(c,...y)),p=(y=o)=>{l=h(s,y),c=h(),y.length!==0&&(l=h(i,y),c=h())},f=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,m=[];for(;y<e;){c=h();let w=c.slice();m.push(w),y+=c.length}return ys(...m)};return(y,m)=>{d(),p(y);let w;for(;!(w=m(f()));)p();return d(),w}}function Wf(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(s,i,a){let c=r[s];if(a&&c===void 0)return;let l=typeof c;if(l!==i||c===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${l}`)}let o=(s,i)=>Object.entries(s).forEach(([a,c])=>n(a,c,i));o(e,!1),o(t,!0)}function sx(r){let e=new WeakMap;return(t,...n)=>{let o=e.get(t);if(o!==void 0)return o;let s=r(t,...n);return e.set(t,s),s}}var Wo=BigInt(0),yn=BigInt(1),bm=BigInt(2),bIe=BigInt(3),wIe=BigInt(4),xIe=BigInt(5),dut=BigInt(7),vIe=BigInt(8),fut=BigInt(9),EIe=BigInt(16);function Pr(r,e){let t=r%e;return t>=Wo?t:e+t}function Wt(r,e,t){let n=r;for(;e-- >Wo;)n*=n,n%=t;return n}function gIe(r,e){if(r===Wo)throw new Error("invert: expected non-zero number");if(e<=Wo)throw new Error("invert: expected positive modulus, got "+e);let t=Pr(r,e),n=e,o=Wo,s=yn,i=yn,a=Wo;for(;t!==Wo;){let l=n/t,u=n%t,d=o-i*l,h=s-a*l;n=t,t=u,o=i,s=a,i=d,a=h}if(n!==yn)throw new Error("invert: does not exist");return Pr(o,e)}function VX(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function SIe(r,e){let t=(r.ORDER+yn)/wIe,n=r.pow(e,t);return VX(r,n,e),n}function hut(r,e){let t=(r.ORDER-xIe)/vIe,n=r.mul(e,bm),o=r.pow(n,t),s=r.mul(e,o),i=r.mul(r.mul(s,bm),o),a=r.mul(s,r.sub(i,r.ONE));return VX(r,a,e),a}function put(r){let e=ix(r),t=CIe(r),n=t(e,e.neg(e.ONE)),o=t(e,n),s=t(e,e.neg(n)),i=(r+dut)/EIe;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,n),d=a.mul(l,o),h=a.mul(l,s),p=a.eql(a.sqr(u),c),f=a.eql(a.sqr(d),c);l=a.cmov(l,u,p),u=a.cmov(h,d,f);let g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return VX(a,y,c),y}}function CIe(r){if(r<bIe)throw new Error("sqrt is not defined for small field");let e=r-yn,t=0;for(;e%bm===Wo;)e/=bm,t++;let n=bm,o=ix(r);for(;yIe(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return SIe;let s=o.pow(n,e),i=(e+yn)/bm;return function(c,l){if(c.is0(l))return l;if(yIe(c,l)!==1)throw new Error("Cannot find square root");let u=t,d=c.mul(c.ONE,s),h=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let f=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(f++,g=c.sqr(g),f===u)throw new Error("Cannot find square root");let y=yn<<BigInt(u-f-1),m=c.pow(d,y);u=f,d=c.sqr(m),h=c.mul(h,d),p=c.mul(p,m)}return p}}function mut(r){return r%wIe===bIe?SIe:r%vIe===xIe?hut:r%EIe===fut?put(r):CIe(r)}var AIe=(r,e)=>(Pr(r,e)&yn)===yn,gut=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qX(r){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=gut.reduce((n,o)=>(n[o]="function",n),e);return Wf(r,t),r}function yut(r,e,t){if(t<Wo)throw new Error("invalid exponent, negatives unsupported");if(t===Wo)return r.ONE;if(t===yn)return e;let n=r.ONE,o=e;for(;t>Wo;)t&yn&&(n=r.mul(n,o)),o=r.sqr(o),t>>=yn;return n}function cA(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(n[c]=i,r.mul(i,a)),r.ONE),s=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(n[c]=r.mul(i,n[c]),r.mul(i,a)),s),n}function yIe(r,e){let t=(r.ORDER-yn)/bm,n=r.pow(e,t),o=r.eql(n,r.ONE),s=r.eql(n,r.ZERO),i=r.eql(n,r.neg(r.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function but(r,e){e!==void 0&&Kc(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var HX=class{ORDER;BITS;BYTES;isLE;ZERO=Wo;ONE=yn;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Wo)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=but(e,n);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Pr(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Wo<=e&&e<this.ORDER}is0(e){return e===Wo}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&yn)===yn}neg(e){return Pr(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Pr(e*e,this.ORDER)}add(e,t){return Pr(e+t,this.ORDER)}sub(e,t){return Pr(e-t,this.ORDER)}mul(e,t){return Pr(e*t,this.ORDER)}pow(e,t){return yut(this,e,t)}div(e,t){return Pr(e*gIe(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return gIe(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=mut(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?zX(e,this.BYTES):uL(e,this.BYTES)}fromBytes(e,t=!1){$e(e);let{_lengths:n,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(n){if(!n.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=s?ym(e):ox(e);if(a&&(c=Pr(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return cA(this,e)}cmov(e,t,n){return n?t:e}};function ix(r,e={}){return new HX(r,e)}function IIe(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 jX(r){let e=IIe(r);return e+Math.ceil(e/2)}function GX(r,e,t=!1){$e(r);let n=r.length,o=IIe(e),s=jX(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=t?ym(r):ox(r),a=Pr(i,e-yn)+yn;return t?zX(a,o):uL(a,o)}var ax=BigInt(0),wm=BigInt(1);function lA(r,e){let t=e.negate();return r?t:e}function xm(r,e){let t=cA(r.Fp,e.map(n=>n.Z));return e.map((n,o)=>r.fromAffine(n.toAffine(t[o])))}function _Ie(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function WX(r,e){_Ie(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),o=2**r,s=aA(r),i=BigInt(r);return{windows:t,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function TIe(r,e,t){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=t,a=Number(r&o),c=r>>i;a>n&&(a-=s,c+=wm);let l=e*n,u=l+Math.abs(a)-1,d=a===0,h=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:p,offsetF:l}}var YX=new WeakMap,PIe=new WeakMap;function XX(r){return PIe.get(r)||1}function kIe(r){if(r!==ax)throw new Error("invalid wNAF")}var cx=class{BASE;ZERO;Fn;bits;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 o=e;for(;t>ax;)t&wm&&(n=n.add(o)),o=o.double(),t>>=wm;return n}precomputeWindow(e,t){let{windows:n,windowSize:o}=WX(t,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let l=1;l<o;l++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=WX(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:l,isZero:u,isNeg:d,isNegF:h,offsetF:p}=TIe(n,a,i);n=c,u?s=s.add(lA(h,t[p])):o=o.add(lA(d,t[l]))}return kIe(n),{p:o,f:s}}wNAFUnsafe(e,t,n,o=this.ZERO){let s=WX(e,this.bits);for(let i=0;i<s.windows&&n!==ax;i++){let{nextN:a,offset:c,isZero:l,isNeg:u}=TIe(n,i,s);if(n=a,!l){let d=t[c];o=o.add(u?d.negate():d)}}return kIe(n),o}getPrecomputes(e,t,n){let o=YX.get(t);return o||(o=this.precomputeWindow(t,e),e!==1&&(typeof n=="function"&&(o=n(o)),YX.set(t,o))),o}cached(e,t,n){let o=XX(e);return this.wNAF(o,this.getPrecomputes(o,e,n),t)}unsafe(e,t,n,o){let s=XX(e);return s===1?this._unsafeLadder(e,t,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),t,o)}createCache(e,t){_Ie(t,this.bits),PIe.set(e,t),YX.delete(e)}hasCache(e){return XX(e)!==1}};function RIe(r,e,t,n){let o=e,s=r.ZERO,i=r.ZERO;for(;t>ax||n>ax;)t&wm&&(s=s.add(o)),n&wm&&(i=i.add(o)),o=o.double(),t>>=wm,n>>=wm;return{p1:s,p2:i}}function DIe(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return qX(e),e}else return ix(r,{isLE:t})}function fL(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>ax))throw new Error(`CURVE.${c} must be positive bigint`)}let o=DIe(e.p,t.Fp,n),s=DIe(e.n,t.Fn,n),a=["Gx","Gy","a",r==="weierstrass"?"b":"d"];for(let c of a)if(!o.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:o,Fn:s}}function hL(r,e){return function(n){let o=r(n);return{secretKey:o,publicKey:e(o)}}}var Yf=BigInt(0),bn=BigInt(1),ZX=BigInt(2),wut=BigInt(8);function xut(r,e,t,n){let o=r.sqr(t),s=r.sqr(n),i=r.add(r.mul(e.a,o),s),a=r.add(r.ONE,r.mul(e.d,r.mul(o,s)));return r.eql(i,a)}function LIe(r,e={}){let t=fL("edwards",r,e,e.FpFnLE),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i}=s;Wf(e,{},{uvRatio:"function"});let a=ZX<<BigInt(o.BYTES*8)-bn,c=y=>n.create(y),l=e.uvRatio||((y,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,m))}}catch{return{isValid:!1,value:Yf}}});if(!xut(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function u(y,m,w=!1){let b=w?bn:Yf;return iA("coordinate "+y,m,b,a),m}function d(y){if(!(y instanceof f))throw new Error("EdwardsPoint expected")}let h=sx((y,m)=>{let{X:w,Y:b,Z:x}=y,S=y.is0();m==null&&(m=S?wut:n.inv(x));let T=c(w*m),A=c(b*m),v=n.mul(x,m);if(S)return{x:Yf,y:bn};if(v!==bn)throw new Error("invZ was invalid");return{x:T,y:A}}),p=sx(y=>{let{a:m,d:w}=s;if(y.is0())throw new Error("bad point: ZERO");let{X:b,Y:x,Z:S,T}=y,A=c(b*b),v=c(x*x),C=c(S*S),P=c(C*C),F=c(A*m),R=c(C*c(F+v)),k=c(P+c(w*c(A*v)));if(R!==k)throw new Error("bad point: equation left != right (1)");let I=c(b*x),E=c(S*T);if(I!==E)throw new Error("bad point: equation left != right (2)");return!0});class f{static BASE=new f(s.Gx,s.Gy,bn,c(s.Gx*s.Gy));static ZERO=new f(Yf,bn,bn,Yf);static Fp=n;static Fn=o;X;Y;Z;T;constructor(m,w,b,x){this.X=u("x",m),this.Y=u("y",w),this.Z=u("z",b,!0),this.T=u("t",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(m){if(m instanceof f)throw new Error("extended point not allowed");let{x:w,y:b}=m||{};return u("x",w),u("y",b),new f(w,b,bn,c(w*b))}static fromBytes(m,w=!1){let b=n.BYTES,{a:x,d:S}=s;m=dL($e(m,b,"point")),Gu(w,"zip215");let T=dL(m),A=m[b-1];T[b-1]=A&-129;let v=ym(T),C=w?a:n.ORDER;iA("point.y",v,Yf,C);let P=c(v*v),F=c(P-bn),R=c(S*P-x),{isValid:k,value:I}=l(F,R);if(!k)throw new Error("bad point: invalid y coordinate");let E=(I&bn)===bn,D=(A&128)!==0;if(!w&&I===Yf&&D)throw new Error("bad point: x=0 and x_0=1");return D!==E&&(I=c(-I)),f.fromAffine({x:I,y:v})}static fromHex(m,w=!1){return f.fromBytes(qu(m),w)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return g.createCache(this,m),w||this.multiply(ZX),this}assertValidity(){p(this)}equals(m){d(m);let{X:w,Y:b,Z:x}=this,{X:S,Y:T,Z:A}=m,v=c(w*A),C=c(S*x),P=c(b*A),F=c(T*x);return v===C&&P===F}is0(){return this.equals(f.ZERO)}negate(){return new f(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=s,{X:w,Y:b,Z:x}=this,S=c(w*w),T=c(b*b),A=c(ZX*c(x*x)),v=c(m*S),C=w+b,P=c(c(C*C)-S-T),F=v+T,R=F-A,k=v-T,I=c(P*R),E=c(F*k),D=c(P*k),M=c(R*F);return new f(I,E,M,D)}add(m){d(m);let{a:w,d:b}=s,{X:x,Y:S,Z:T,T:A}=this,{X:v,Y:C,Z:P,T:F}=m,R=c(x*v),k=c(S*C),I=c(A*b*F),E=c(T*P),D=c((x+S)*(v+C)-R-k),M=E-I,B=E+I,L=c(k-w*R),O=c(D*M),U=c(B*L),$=c(D*L),J=c(M*B);return new f(O,U,J,$)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:w,f:b}=g.cached(this,m,x=>xm(f,x));return xm(f,[w,b])[0]}multiplyUnsafe(m,w=f.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===Yf?f.ZERO:this.is0()||m===bn?this:g.unsafe(this,m,b=>xm(f,b),w)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,s.n).is0()}toAffine(m){return h(this,m)}clearCofactor(){return i===bn?this:this.multiplyUnsafe(i)}toBytes(){let{x:m,y:w}=this.toAffine(),b=n.toBytes(w);return b[b.length-1]|=m&bn?128:0,b}toHex(){return Vu(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let g=new cx(f,o.BITS);return f.BASE.precompute(8),f}function MIe(r,e,t={}){if(typeof e!="function")throw new Error('"hash" function param is required');Wf(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:o,Fp:s,Fn:i}=r,a=t.randomBytes||nx,c=t.adjustScalarBytes||(v=>v),l=t.domain||((v,C,P)=>{if(Gu(P,"phflag"),C.length||P)throw new Error("Contexts/pre-hash are not supported");return v});function u(v){return i.create(ym(v))}function d(v){let C=b.secretKey;$e(v,b.secretKey,"secretKey");let P=$e(e(v),2*C,"hashedSecretKey"),F=c(P.slice(0,C)),R=P.slice(C,2*C),k=u(F);return{head:F,prefix:R,scalar:k}}function h(v){let{head:C,prefix:P,scalar:F}=d(v),R=o.multiply(F),k=R.toBytes();return{head:C,prefix:P,scalar:F,point:R,pointBytes:k}}function p(v){return h(v).pointBytes}function f(v=Uint8Array.of(),...C){let P=ys(...C);return u(e(l(P,$e(v,void 0,"context"),!!n)))}function g(v,C,P={}){v=$e(v,void 0,"message"),n&&(v=n(v));let{prefix:F,scalar:R,pointBytes:k}=h(C),I=f(P.context,F,v),E=o.multiply(I).toBytes(),D=f(P.context,E,k,v),M=i.create(I+D*R);if(!i.isValid(M))throw new Error("sign failed: invalid s");let B=ys(E,i.toBytes(M));return $e(B,b.signature,"result")}let y={zip215:!0};function m(v,C,P,F=y){let{context:R,zip215:k}=F,I=b.signature;v=$e(v,I,"signature"),C=$e(C,void 0,"message"),P=$e(P,b.publicKey,"publicKey"),k!==void 0&&Gu(k,"zip215"),n&&(C=n(C));let E=I/2,D=v.subarray(0,E),M=ym(v.subarray(E,I)),B,L,O;try{B=r.fromBytes(P,k),L=r.fromBytes(D,k),O=o.multiplyUnsafe(M)}catch{return!1}if(!k&&B.isSmallOrder())return!1;let U=f(R,L.toBytes(),B.toBytes(),C);return L.add(B.multiplyUnsafe(U)).subtract(O).clearCofactor().is0()}let w=s.BYTES,b={secretKey:w,publicKey:w,signature:2*w,seed:w};function x(v=a(b.seed)){return $e(v,b.seed,"seed")}function S(v){return pm(v)&&v.length===i.BYTES}function T(v,C){try{return!!r.fromBytes(v,C)}catch{return!1}}let A={getExtendedPublicKey:h,randomSecretKey:x,isValidSecretKey:S,isValidPublicKey:T,toMontgomery(v){let{y:C}=r.fromBytes(v),P=b.publicKey,F=P===32;if(!F&&P!==57)throw new Error("only defined for 25519 and 448");let R=F?s.div(bn+C,bn-C):s.div(C-bn,C+bn);return s.toBytes(R)},toMontgomerySecret(v){let C=b.secretKey;$e(v,C);let P=e(v.subarray(0,C));return c(P).subarray(0,C)}};return Object.freeze({keygen:hL(x,p),getPublicKey:p,sign:g,verify:m,utils:A,Point:r,lengths:b})}var vut=BigInt(1),BIe=BigInt(2);var Eut=BigInt(5),Sut=BigInt(8),JX=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Cut={p:JX,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Sut,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Aut(r){let e=BigInt(10),t=BigInt(20),n=BigInt(40),o=BigInt(80),s=JX,a=r*r%s*r%s,c=Wt(a,BIe,s)*a%s,l=Wt(c,vut,s)*r%s,u=Wt(l,Eut,s)*l%s,d=Wt(u,e,s)*u%s,h=Wt(d,t,s)*d%s,p=Wt(h,n,s)*h%s,f=Wt(p,o,s)*p%s,g=Wt(f,o,s)*p%s,y=Wt(g,e,s)*u%s;return{pow_p_5_8:Wt(y,BIe,s)*r%s,b2:a}}function Iut(r){return r[0]&=248,r[31]&=127,r[31]|=64,r}var OIe=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Tut(r,e){let t=JX,n=Pr(e*e*e,t),o=Pr(n*n*e,t),s=Aut(r*o).pow_p_5_8,i=Pr(r*n*s,t),a=Pr(e*i*i,t),c=i,l=Pr(i*OIe,t),u=a===r,d=a===Pr(-r,t),h=a===Pr(-r*OIe,t);return u&&(i=c),(d||h)&&(i=l),AIe(i,t)&&(i=Pr(-i,t)),{isValid:u||d,value:i}}var kut=LIe(Cut,{uvRatio:Tut});function Dut(r){return MIe(kut,fIe,Object.assign({adjustScalarBytes:Iut},r))}var NIe=Dut({});var pL=32;var QX,_ut=(async()=>{try{return await nL.get().subtle.generateKey({name:"Ed25519"},!0,["sign","verify"]),!0}catch{return!1}})();async function Put(r,e,t){if(r.buffer instanceof ArrayBuffer){let n=await nL.get().subtle.importKey("raw",r.buffer,{name:"Ed25519"},!1,["verify"]);return await nL.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 Rut(r,e,t){return NIe.verify(e,t instanceof Uint8Array?t:t.subarray(),r)}async function UIe(r,e,t){return QX==null&&(QX=await _ut),QX?Put(r,e,t):Rut(r,e,t)}function mL(r){return r==null?!1:typeof r.then=="function"&&typeof r.catch=="function"&&typeof r.finally=="function"}var gL=class{type="Ed25519";raw;constructor(e){this.raw=eZ(e,pL)}toMultihash(){return ga.digest(tx(this))}toCID(){return wr.createV1(114,this.toMultihash())}toString(){return _r.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:zr(this.raw,e.raw)}verify(e,t,n){n?.signal?.throwIfAborted();let o=UIe(this.raw,t,e);return mL(o)?o.then(s=>(n?.signal?.throwIfAborted(),s)):o}};function KIe(r){return r=eZ(r,pL),new gL(r)}function eZ(r,e){if(r=Uint8Array.from(r??[]),r.length!==e)throw new Si(`Key must be a Uint8Array of length ${e}, got ${r.length}`);return r}var tZ=new Float32Array([-0]),Xf=new Uint8Array(tZ.buffer);function zIe(r,e,t){tZ[0]=r,e[t]=Xf[0],e[t+1]=Xf[1],e[t+2]=Xf[2],e[t+3]=Xf[3]}function $Ie(r,e){return Xf[0]=r[e],Xf[1]=r[e+1],Xf[2]=r[e+2],Xf[3]=r[e+3],tZ[0]}var rZ=new Float64Array([-0]),So=new Uint8Array(rZ.buffer);function HIe(r,e,t){rZ[0]=r,e[t]=So[0],e[t+1]=So[1],e[t+2]=So[2],e[t+3]=So[3],e[t+4]=So[4],e[t+5]=So[5],e[t+6]=So[6],e[t+7]=So[7]}function VIe(r,e){return So[0]=r[e],So[1]=r[e+1],So[2]=r[e+2],So[3]=r[e+3],So[4]=r[e+4],So[5]=r[e+5],So[6]=r[e+6],So[7]=r[e+7],rZ[0]}var Mut=BigInt(Number.MAX_SAFE_INTEGER),But=BigInt(Number.MIN_SAFE_INTEGER),Ws=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 vm;if(e<Mut&&e>But)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,o=e-(n<<32n);return t&&(n=~n|0n,o=~o|0n,++o>qIe&&(o=0n,++n>qIe&&(n=0n))),new r(Number(o),Number(n))}static fromNumber(e){if(e===0)return vm;let t=e<0;t&&(e=-e);let n=e>>>0,o=(e-n)/4294967296>>>0;return t&&(o=~o>>>0,n=~n>>>0,++n>4294967295&&(n=0,++o>4294967295&&(o=0))),new r(n,o)}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):vm}},vm=new Ws(0,0);vm.toBigInt=function(){return 0n};vm.zzEncode=vm.zzDecode=function(){return this};vm.length=function(){return 1};var qIe=4294967296n;function jIe(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 GIe(r,e,t){if(t-e<1)return"";let o,s=[],i=0,a;for(;e<t;)a=r[e++],a<128?s[i++]=a:a>191&&a<224?s[i++]=(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,s[i++]=55296+(a>>10),s[i++]=56320+(a&1023)):s[i++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,i>8191&&((o??(o=[])).push(String.fromCharCode.apply(String,s)),i=0);return o!=null?(i>0&&o.push(String.fromCharCode.apply(String,s.slice(0,i))),o.join("")):String.fromCharCode.apply(String,s.slice(0,i))}function nZ(r,e,t){let n=t,o,s;for(let i=0;i<r.length;++i)o=r.charCodeAt(i),o<128?e[t++]=o:o<2048?(e[t++]=o>>6|192,e[t++]=o&63|128):(o&64512)===55296&&((s=r.charCodeAt(i+1))&64512)===56320?(o=65536+((o&1023)<<10)+(s&1023),++i,e[t++]=o>>18|240,e[t++]=o>>12&63|128,e[t++]=o>>6&63|128,e[t++]=o&63|128):(e[t++]=o>>12|224,e[t++]=o>>6&63|128,e[t++]=o&63|128);return t-n}function xa(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function yL(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}var oZ=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,xa(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 xa(this,4);return yL(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw xa(this,4);return yL(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw xa(this,4);let e=$Ie(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw xa(this,4);let e=VIe(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 xa(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return GIe(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw xa(this,e);this.pos+=e}else do if(this.pos>=this.len)throw xa(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 Ws(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 xa(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 xa(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 xa(this,8);let e=yL(this.buf,this.pos+=4),t=yL(this.buf,this.pos+=4);return new Ws(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=fY(this.buf,this.pos);return this.pos+=Gt(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 sZ(r){return new oZ(r instanceof Uint8Array?r:r.subarray())}function ki(r,e,t){let n=sZ(r);return e.decode(n,void 0,t)}function iZ(r){let e=r??8192,t=e>>>1,n,o=e;return function(i){if(i<1||i>t)return gs(i);o+i>e&&(n=gs(e),o=0);let a=n.subarray(o,o+=i);return(o&7)!==0&&(o=(o|7)+1),a}}var Em=class{fn;len;next;val;constructor(e,t,n){this.fn=e,this.len=t,this.next=void 0,this.val=n}};function aZ(){}var lZ=class{head;tail;len;next;constructor(e){this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Out=iZ();function Nut(r){return globalThis.Buffer!=null?gs(r):Out(r)}var dA=class{len;head;tail;states;constructor(){this.len=0,this.head=new Em(aZ,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new Em(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new uZ((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(bL,10,Ws.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=Ws.fromBigInt(e);return this._push(bL,t.length(),t)}uint64Number(e){return this._push(Ai,Gt(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=Ws.fromBigInt(e).zzEncode();return this._push(bL,t.length(),t)}sint64Number(e){let t=Ws.fromNumber(e).zzEncode();return this._push(bL,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(cZ,1,e?1:0)}fixed32(e){return this._push(uA,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=Ws.fromBigInt(e);return this._push(uA,4,t.lo)._push(uA,4,t.hi)}fixed64Number(e){let t=Ws.fromNumber(e);return this._push(uA,4,t.lo)._push(uA,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(zIe,4,e)}double(e){return this._push(HIe,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(cZ,1,0):this.uint32(t)._push(Fut,t,e)}string(e){let t=jIe(e);return t!==0?this.uint32(t)._push(nZ,t,e):this._push(cZ,1,0)}fork(){return this.states=new lZ(this),this.head=this.tail=new Em(aZ,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 Em(aZ,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=Nut(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};function cZ(r,e,t){e[t]=r&255}function Uut(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}var uZ=class extends Em{next;constructor(e,t){super(Uut,e,t),this.next=void 0}};function bL(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 uA(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 Fut(r,e,t){e.set(r,t)}globalThis.Buffer!=null&&(dA.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Kut,e,r),this},dA.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(zut,e,r),this});function Kut(r,e,t){e.set(r,t)}function zut(r,e,t){r.length<40?nZ(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Ze(r),t)}function dZ(){return new dA}function Di(r,e){let t=dZ();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var lx;(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"})(lx||(lx={}));function wL(r,e,t,n){return{name:r,type:e,encode:t,decode:n}}function Sm(r){function e(o){if(r[o.toString()]==null)throw new Error("Invalid enum value");return r[o]}let t=function(s,i){let a=e(s);i.int32(a)},n=function(s){let i=s.int32();return e(i)};return wL("enum",lx.VARINT,t,n)}function _i(r,e){return wL("message",lx.LENGTH_DELIMITED,r,e)}var fA=class extends Error{code="ERR_MAX_LENGTH";name="MaxLengthError"};var Ys;(function(r){r.RSA="RSA",r.Ed25519="Ed25519",r.secp256k1="secp256k1",r.ECDSA="ECDSA"})(Ys||(Ys={}));var fZ;(function(r){r[r.RSA=0]="RSA",r[r.Ed25519=1]="Ed25519",r[r.secp256k1=2]="secp256k1",r[r.ECDSA=3]="ECDSA"})(fZ||(fZ={}));(function(r){r.codec=()=>Sm(fZ)})(Ys||(Ys={}));var hA;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ys.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Ys.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(hA||(hA={}));var hZ;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.Type!=null&&(n.uint32(8),Ys.codec().encode(t.Type,n)),t.Data!=null&&(n.uint32(18),n.bytes(t.Data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.Type=Ys.codec().decode(t);break}case 2:{s.Data=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(hZ||(hZ={}));var xL=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(iL(e),$e(t,void 0,"key"),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 n=this.blockLen,o=new Uint8Array(n);o.set(t.length>n?e.create().update(t).digest():t);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),Hu(o)}update(e){return rx(this),this.iHash.update(e),this}digestInto(e){rx(this),$e(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,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()}},pZ=(r,e,t)=>new xL(r,e).update(t).digest();pZ.create=(r,e)=>new xL(r,e);var YIe=(r,e)=>(r+(r>=0?e:-e)/XIe)/e;function Hut(r,e,t){let[[n,o],[s,i]]=e,a=YIe(i*r,t),c=YIe(-o*r,t),l=r-a*n-c*s,u=-a*o-c*i,d=l<Wu,h=u<Wu;d&&(l=-l),h&&(u=-u);let p=aA(Math.ceil($X(t)/2))+ux;if(l<Wu||l>=p||u<Wu||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:d,k1:l,k2neg:h,k2:u}}function gZ(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function mZ(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Gu(t.lowS,"lowS"),Gu(t.prehash,"prehash"),t.format!==void 0&&gZ(t.format),t}var yZ=class extends Error{constructor(e=""){super(e)}},Zf={Err:yZ,_tlv:{encode:(r,e)=>{let{Err:t}=Zf;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,o=sA(n);if(o.length/2&128)throw new t("tlv.encode: long form length too big");let s=n>127?sA(o.length/2|128):"";return sA(r)+s+o+e},decode(r,e){let{Err:t}=Zf,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 o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&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)i=i<<8|u;if(n+=c,i<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(r){let{Err:e}=Zf;if(r<Wu)throw new e("integer: negative integers are not allowed");let t=sA(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}=Zf;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 ox(r)}},toSig(r){let{Err:e,_int:t,_tlv:n}=Zf,o=$e(r,void 0,"signature"),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:l,l:u}=n.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(l)}},hexFromSig(r){let{_tlv:e,_int:t}=Zf,n=e.encode(2,t.encode(r.r)),o=e.encode(2,t.encode(r.s)),s=n+o;return e.encode(48,s)}},Wu=BigInt(0),ux=BigInt(1),XIe=BigInt(2),vL=BigInt(3),Vut=BigInt(4);function ZIe(r,e={}){let t=fL("weierstrass",r,e),{Fp:n,Fn:o}=t,s=t.CURVE,{h:i,n:a}=s;Wf(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=QIe(n,o);function u(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(R,k,I){let{x:E,y:D}=k.toAffine(),M=n.toBytes(E);if(Gu(I,"isCompressed"),I){u();let B=!n.isOdd(D);return ys(JIe(B),M)}else return ys(Uint8Array.of(4),M,n.toBytes(D))}function h(R){$e(R,void 0,"Point");let{publicKey:k,publicKeyUncompressed:I}=l,E=R.length,D=R[0],M=R.subarray(1);if(E===k&&(D===2||D===3)){let B=n.fromBytes(M);if(!n.isValid(B))throw new Error("bad point: is not on curve, wrong x");let L=g(B),O;try{O=n.sqrt(L)}catch(J){let X=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}u();let U=n.isOdd(O);return(D&1)===1!==U&&(O=n.neg(O)),{x:B,y:O}}else if(E===I&&D===4){let B=n.BYTES,L=n.fromBytes(M.subarray(0,B)),O=n.fromBytes(M.subarray(B,B*2));if(!y(L,O))throw new Error("bad point: is not on curve");return{x:L,y:O}}else throw new Error(`bad point: got length ${E}, expected compressed=${k} or uncompressed=${I}`)}let p=e.toBytes||d,f=e.fromBytes||h;function g(R){let k=n.sqr(R),I=n.mul(k,R);return n.add(n.add(I,n.mul(R,s.a)),s.b)}function y(R,k){let I=n.sqr(k),E=g(R);return n.eql(I,E)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(s.a,vL),Vut),w=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(m,w)))throw new Error("bad curve params: a or b");function b(R,k,I=!1){if(!n.isValid(k)||I&&n.is0(k))throw new Error(`bad point coordinate ${R}`);return k}function x(R){if(!(R instanceof C))throw new Error("Weierstrass Point expected")}function S(R){if(!c||!c.basises)throw new Error("no endo");return Hut(R,c.basises,o.ORDER)}let T=sx((R,k)=>{let{X:I,Y:E,Z:D}=R;if(n.eql(D,n.ONE))return{x:I,y:E};let M=R.is0();k==null&&(k=M?n.ONE:n.inv(D));let B=n.mul(I,k),L=n.mul(E,k),O=n.mul(D,k);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(O,n.ONE))throw new Error("invZ was invalid");return{x:B,y:L}}),A=sx(R=>{if(R.is0()){if(e.allowInfinityPoint&&!n.is0(R.Y))return;throw new Error("bad point: ZERO")}let{x:k,y:I}=R.toAffine();if(!n.isValid(k)||!n.isValid(I))throw new Error("bad point: x or y not field elements");if(!y(k,I))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(R,k,I,E,D){return I=new C(n.mul(I.X,R),I.Y,I.Z),k=lA(E,k),I=lA(D,I),k.add(I)}class C{static BASE=new C(s.Gx,s.Gy,n.ONE);static ZERO=new C(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=o;X;Y;Z;constructor(k,I,E){this.X=b("x",k),this.Y=b("y",I,!0),this.Z=b("z",E),Object.freeze(this)}static CURVE(){return s}static fromAffine(k){let{x:I,y:E}=k||{};if(!k||!n.isValid(I)||!n.isValid(E))throw new Error("invalid affine point");if(k instanceof C)throw new Error("projective point not allowed");return n.is0(I)&&n.is0(E)?C.ZERO:new C(I,E,n.ONE)}static fromBytes(k){let I=C.fromAffine(f($e(k,void 0,"point")));return I.assertValidity(),I}static fromHex(k){return C.fromBytes(qu(k))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(k=8,I=!0){return F.createCache(this,k),I||this.multiply(vL),this}assertValidity(){A(this)}hasEvenY(){let{y:k}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(k)}equals(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.eql(n.mul(I,L),n.mul(M,D)),U=n.eql(n.mul(E,L),n.mul(B,D));return O&&U}negate(){return new C(this.X,n.neg(this.Y),this.Z)}double(){let{a:k,b:I}=s,E=n.mul(I,vL),{X:D,Y:M,Z:B}=this,L=n.ZERO,O=n.ZERO,U=n.ZERO,$=n.mul(D,D),J=n.mul(M,M),X=n.mul(B,B),N=n.mul(D,M);return N=n.add(N,N),U=n.mul(D,B),U=n.add(U,U),L=n.mul(k,U),O=n.mul(E,X),O=n.add(L,O),L=n.sub(J,O),O=n.add(J,O),O=n.mul(L,O),L=n.mul(N,L),U=n.mul(E,U),X=n.mul(k,X),N=n.sub($,X),N=n.mul(k,N),N=n.add(N,U),U=n.add($,$),$=n.add(U,$),$=n.add($,X),$=n.mul($,N),O=n.add(O,$),X=n.mul(M,B),X=n.add(X,X),$=n.mul(X,N),L=n.sub(L,$),U=n.mul(X,J),U=n.add(U,U),U=n.add(U,U),new C(L,O,U)}add(k){x(k);let{X:I,Y:E,Z:D}=this,{X:M,Y:B,Z:L}=k,O=n.ZERO,U=n.ZERO,$=n.ZERO,J=s.a,X=n.mul(s.b,vL),N=n.mul(I,M),H=n.mul(E,B),Z=n.mul(D,L),ae=n.add(I,E),Q=n.add(M,B);ae=n.mul(ae,Q),Q=n.add(N,H),ae=n.sub(ae,Q),Q=n.add(I,D);let oe=n.add(M,L);return Q=n.mul(Q,oe),oe=n.add(N,Z),Q=n.sub(Q,oe),oe=n.add(E,D),O=n.add(B,L),oe=n.mul(oe,O),O=n.add(H,Z),oe=n.sub(oe,O),$=n.mul(J,Q),O=n.mul(X,Z),$=n.add(O,$),O=n.sub(H,$),$=n.add(H,$),U=n.mul(O,$),H=n.add(N,N),H=n.add(H,N),Z=n.mul(J,Z),Q=n.mul(X,Q),H=n.add(H,Z),Z=n.sub(N,Z),Z=n.mul(J,Z),Q=n.add(Q,Z),N=n.mul(H,Q),U=n.add(U,N),N=n.mul(oe,Q),O=n.mul(ae,O),O=n.sub(O,N),N=n.mul(ae,H),$=n.mul(oe,$),$=n.add($,N),new C(O,U,$)}subtract(k){return this.add(k.negate())}is0(){return this.equals(C.ZERO)}multiply(k){let{endo:I}=e;if(!o.isValidNot0(k))throw new Error("invalid scalar: out of range");let E,D,M=B=>F.cached(this,B,L=>xm(C,L));if(I){let{k1neg:B,k1:L,k2neg:O,k2:U}=S(k),{p:$,f:J}=M(L),{p:X,f:N}=M(U);D=J.add(N),E=v(I.beta,$,X,B,O)}else{let{p:B,f:L}=M(k);E=B,D=L}return xm(C,[E,D])[0]}multiplyUnsafe(k){let{endo:I}=e,E=this;if(!o.isValid(k))throw new Error("invalid scalar: out of range");if(k===Wu||E.is0())return C.ZERO;if(k===ux)return E;if(F.hasCache(this))return this.multiply(k);if(I){let{k1neg:D,k1:M,k2neg:B,k2:L}=S(k),{p1:O,p2:U}=RIe(C,E,M,L);return v(I.beta,O,U,D,B)}else return F.unsafe(E,k)}toAffine(k){return T(this,k)}isTorsionFree(){let{isTorsionFree:k}=e;return i===ux?!0:k?k(C,this):F.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:k}=e;return i===ux?this:k?k(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(k=!0){return Gu(k,"isCompressed"),this.assertValidity(),p(C,this,k)}toHex(k=!0){return Vu(this.toBytes(k))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let P=o.BITS,F=new cx(C,e.endo?Math.ceil(P/2):P);return C.BASE.precompute(8),C}function JIe(r){return Uint8Array.of(r?2:3)}function QIe(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function qut(r,e={}){let{Fn:t}=r,n=e.randomBytes||nx,o=Object.assign(QIe(r.Fp,t),{seed:jX(t.ORDER)});function s(p){try{let f=t.fromBytes(p);return t.isValidNot0(f)}catch{return!1}}function i(p,f){let{publicKey:g,publicKeyUncompressed:y}=o;try{let m=p.length;return f===!0&&m!==g||f===!1&&m!==y?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=n(o.seed)){return GX($e(p,o.seed,"seed"),t.ORDER)}function c(p,f=!0){return r.BASE.multiply(t.fromBytes(p)).toBytes(f)}function l(p){let{secretKey:f,publicKey:g,publicKeyUncompressed:y}=o;if(!pm(p)||"_lengths"in t&&t._lengths||f===g)return;let m=$e(p,void 0,"key").length;return m===g||m===y}function u(p,f,g=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(f)===!1)throw new Error("second arg must be public key");let y=t.fromBytes(p);return r.fromBytes(f).multiply(y).toBytes(g)}let d={isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a},h=hL(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:h,Point:r,utils:d,lengths:o})}function eTe(r,e,t={}){iL(e),Wf(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||nx,o=t.hmac||((I,E)=>pZ(e,I,E)),{Fp:s,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p}=qut(r,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},g=a*XIe<s.ORDER;function y(I){let E=a>>ux;return I>E}function m(I,E){if(!i.isValidNot0(E))throw new Error(`invalid signature ${I}: out of range 1..Point.Fn.ORDER`);return E}function w(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function b(I,E){gZ(E);let D=p.signature,M=E==="compact"?D:E==="recovered"?D+1:void 0;return $e(I,M)}class x{r;s;recovery;constructor(E,D,M){if(this.r=m("r",E),this.s=m("s",D),M!=null){if(w(),![0,1,2,3].includes(M))throw new Error("invalid recovery id");this.recovery=M}Object.freeze(this)}static fromBytes(E,D=f.format){b(E,D);let M;if(D==="der"){let{r:U,s:$}=Zf.toSig($e(E));return new x(U,$)}D==="recovered"&&(M=E[0],D="compact",E=E.subarray(1));let B=p.signature/2,L=E.subarray(0,B),O=E.subarray(B,B*2);return new x(i.fromBytes(L),i.fromBytes(O),M)}static fromHex(E,D){return this.fromBytes(qu(E),D)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new x(this.r,this.s,E)}recoverPublicKey(E){let{r:D,s:M}=this,B=this.assertRecovery(),L=B===2||B===3?D+a:D;if(!s.isValid(L))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let O=s.toBytes(L),U=r.fromBytes(ys(JIe((B&1)===0),O)),$=i.inv(L),J=T($e(E,void 0,"msgHash")),X=i.create(-J*$),N=i.create(M*$),H=r.BASE.multiplyUnsafe(X).add(U.multiplyUnsafe(N));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(E=f.format){if(gZ(E),E==="der")return qu(Zf.hexFromSig(this));let{r:D,s:M}=this,B=i.toBytes(D),L=i.toBytes(M);return E==="recovered"?(w(),ys(Uint8Array.of(this.assertRecovery()),B,L)):ys(B,L)}toHex(E){return Vu(this.toBytes(E))}}let S=t.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let D=ox(E),M=E.length*8-c;return M>0?D>>BigInt(M):D},T=t.bits2int_modN||function(E){return i.create(S(E))},A=aA(c);function v(I){return iA("num < 2^"+c,I,Wu,A),i.toBytes(I)}function C(I,E){return $e(I,void 0,"message"),E?$e(e(I),void 0,"prehashed message"):I}function P(I,E,D){let{lowS:M,prehash:B,extraEntropy:L}=mZ(D,f);I=C(I,B);let O=T(I),U=i.fromBytes(E);if(!i.isValidNot0(U))throw new Error("invalid private key");let $=[v(U),v(O)];if(L!=null&&L!==!1){let H=L===!0?n(p.secretKey):L;$.push($e(H,void 0,"extraEntropy"))}let J=ys(...$),X=O;function N(H){let Z=S(H);if(!i.isValidNot0(Z))return;let ae=i.inv(Z),Q=r.BASE.multiply(Z).toAffine(),oe=i.create(Q.x);if(oe===Wu)return;let Fe=i.create(ae*i.create(X+oe*U));if(Fe===Wu)return;let nr=(Q.x===oe?0:2)|Number(Q.y&ux),fe=Fe;return M&&y(Fe)&&(fe=i.neg(Fe),nr^=1),new x(oe,fe,g?void 0:nr)}return{seed:J,k2sig:N}}function F(I,E,D={}){let{seed:M,k2sig:B}=P(I,E,D);return mIe(e.outputLen,i.BYTES,o)(M,B).toBytes(D.format)}function R(I,E,D,M={}){let{lowS:B,prehash:L,format:O}=mZ(M,f);if(D=$e(D,void 0,"publicKey"),E=C(E,L),!pm(I)){let U=I instanceof x?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+U)}b(I,O);try{let U=x.fromBytes(I,O),$=r.fromBytes(D);if(B&&U.hasHighS())return!1;let{r:J,s:X}=U,N=T(E),H=i.inv(X),Z=i.create(N*H),ae=i.create(J*H),Q=r.BASE.multiplyUnsafe(Z).add($.multiplyUnsafe(ae));return Q.is0()?!1:i.create(Q.x)===J}catch{return!1}}function k(I,E,D={}){let{prehash:M}=mZ(D,f);return E=C(E,M),x.fromBytes(I,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:d,utils:h,lengths:p,Point:r,sign:F,verify:R,recoverPublicKey:k,Signature:x,hash:e})}var wZ={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},jut={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]};var tTe=BigInt(2);function Gut(r){let e=wZ.p,t=BigInt(3),n=BigInt(6),o=BigInt(11),s=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,d=Wt(u,t,e)*u%e,h=Wt(d,t,e)*u%e,p=Wt(h,tTe,e)*l%e,f=Wt(p,o,e)*p%e,g=Wt(f,s,e)*f%e,y=Wt(g,a,e)*g%e,m=Wt(y,c,e)*y%e,w=Wt(m,a,e)*g%e,b=Wt(w,t,e)*u%e,x=Wt(b,i,e)*f%e,S=Wt(x,n,e)*l%e,T=Wt(S,tTe,e);if(!bZ.eql(bZ.sqr(T),r))throw new Error("Cannot find square root");return T}var bZ=ix(wZ.p,{sqrt:Gut}),Wut=ZIe(wZ,{Fp:bZ,endo:jut}),dx=eTe(Wut,dIe);function rTe(r,e,t,n){let o=Gw.digest(t instanceof Uint8Array?t:t.subarray());if(mL(o))return o.then(({digest:s})=>(n?.signal?.throwIfAborted(),dx.verify(e,s,r,{prehash:!1,format:"der"}))).catch(s=>{throw s.name==="AbortError"?s:new QC(String(s))});try{return n?.signal?.throwIfAborted(),dx.verify(e,o.digest,r,{prehash:!1,format:"der"})}catch(s){throw new QC(String(s))}}var EL=class{type="secp256k1";raw;_key;constructor(e){this._key=oTe(e),this.raw=nTe(this._key)}toMultihash(){return ga.digest(tx(this))}toCID(){return wr.createV1(114,this.toMultihash())}toString(){return _r.encode(this.toMultihash().bytes).substring(1)}equals(e){return e==null||!(e.raw instanceof Uint8Array)?!1:zr(this.raw,e.raw)}verify(e,t,n){return rTe(this._key,t,e,n)}};function sTe(r){return new EL(r)}function nTe(r){return dx.Point.fromBytes(r).toBytes()}function oTe(r){try{return dx.Point.fromBytes(r),r}catch(e){throw new C8(String(e))}}function iTe(r){let{Type:e,Data:t}=hA.decode(r.digest),n=t??new Uint8Array;switch(e){case Ys.Ed25519:return KIe(n);case Ys.secp256k1:return sTe(n);case Ys.ECDSA:return WAe(n);default:throw new qC}}function tx(r){return hA.encode({Type:Ys[r.type],Data:r.raw})}var xZ={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},aTe={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},cTe=new globalThis.TextEncoder;function Yut(r,e){let t=xZ[e],n=aTe[e];for(let o=0;o<r.length;o++)n^=BigInt(r[o]),n=BigInt.asUintN(e,n*t);return n}function Xut(r,e,t){if(t.length===0)throw new Error("The `utf8Buffer` option must have a length greater than zero");let n=xZ[e],o=aTe[e],s=r;for(;s.length>0;){let i=cTe.encodeInto(s,t);s=s.slice(i.read);for(let a=0;a<i.written;a++)o^=BigInt(t[a]),o=BigInt.asUintN(e,o*n)}return o}function vZ(r,{size:e=32,utf8Buffer:t}={}){if(!xZ[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 Xut(r,e,t);r=cTe.encode(r)}return Yut(r,e)}var pA={hash:r=>Number(vZ(r,{size:32})),hashV:(r,e)=>Zut(pA.hash(r,e))};function Zut(r){let e=r.toString(16);return e.length%2===1&&(e=`0${e}`),Ze(e,"base16")}var EZ=64,va=class{fp;h;seed;constructor(e,t,n,o=2){if(o>EZ)throw new TypeError("Invalid Fingerprint Size");let s=t.hashV(e,n),i=pn(o);for(let a=0;a<i.length;a++)i[a]=s[a];i.length===0&&(i[0]=7),this.fp=i,this.h=t,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return e?.fp instanceof Uint8Array?zr(this.fp,e.fp):!1}};function Cm(r,e){return Math.floor(Math.random()*(e-r))+r}var Am=class{contents;constructor(e){this.contents=new Array(e).fill(null)}has(e){if(!(e instanceof va))throw new TypeError("Invalid Fingerprint");return this.contents.some(t=>e.equals(t))}add(e){if(!(e instanceof va))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 va))throw new TypeError("Invalid Fingerprint");let t=Cm(0,this.contents.length-1),n=this.contents[t];return this.contents[t]=e,n}remove(e){if(!(e instanceof va))throw new TypeError("Invalid Fingerprint");let t=this.contents.findIndex(n=>e.equals(n));return t>-1?(this.contents[t]=null,!0):!1}};var Jut=500,mA=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??pA,this.seed=e.seed??Cm(0,Math.pow(2,10))}add(e){typeof e=="string"&&(e=Ze(e));let t=new va(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=(n^t.hash())%this.filterSize;if(this.buckets[n]==null&&(this.buckets[n]=new Am(this.bucketSize)),this.buckets[o]==null&&(this.buckets[o]=new Am(this.bucketSize)),this.buckets[n].add(t)||this.buckets[o].add(t))return this.count++,!0;let s=[n,o],i=s[Cm(0,s.length-1)];this.buckets[i]==null&&(this.buckets[i]=new Am(this.bucketSize));for(let a=0;a<Jut;a++){let c=this.buckets[i].swap(t);if(c!=null&&(i=(i^c.hash())%this.filterSize,this.buckets[i]==null&&(this.buckets[i]=new Am(this.bucketSize)),this.buckets[i].add(c)))return this.count++,!0}return!1}has(e){typeof e=="string"&&(e=Ze(e));let t=new va(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.has(t)??!1;if(o)return o;let s=(n^t.hash())%this.filterSize;return this.buckets[s]?.has(t)??!1}remove(e){typeof e=="string"&&(e=Ze(e));let t=new va(e,this.hash,this.seed,this.fingerprintSize),n=this.hash.hash(e,this.seed)%this.filterSize,o=this.buckets[n]?.remove(t)??!1;if(o)return this.count--,o;let s=(n^t.hash())%this.filterSize,i=this.buckets[s]?.remove(t)??!1;return i&&this.count--,i}get reliable(){return Math.floor(100*(this.count/this.filterSize))<=90}},Qut={1:.5,2:.84,4:.95,8:.98};function edt(r=.001){return r>.002?2:r>1e-5?4:8}function lTe(r,e=.001){let t=edt(e),n=Qut[t],o=Math.round(r/n),s=Math.min(Math.ceil(Math.log2(1/e)+Math.log2(2*t)),EZ);return{filterSize:o,bucketSize:t,fingerprintSize:s}}var SL=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??pA,this.seed=e.seed??Cm(0,Math.pow(2,10)),this.filterSeries=[new mA({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if(typeof e=="string"&&(e=Ze(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 mA({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=Ze(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=Ze(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 fx(r,e=.001,t){return new SL({...lTe(r,e),...t??{}})}function hx(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var CL=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}},px=class{size;hwm;head;tail;constructor(e={}){this.hwm=e.splitLimit??16,this.head=new CL(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 CL(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 SZ=class extends Error{type;code;constructor(e,t){super(e??"The operation was aborted"),this.type="aborted",this.code=t??"ABORT_ERR"}};function mx(r={}){return tdt(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 tdt(r,e){e=e??{};let t=e.onEnd,n=new px,o,s,i,a=hx(),c=async()=>{try{return n.isEmpty()?i?{done:!0}:await new Promise((y,m)=>{s=w=>{s=null,n.push(w);try{y(r(n))}catch(b){m(b)}return o}}):r(n)}finally{n.isEmpty()&&queueMicrotask(()=>{a.resolve(),a=hx()})}},l=y=>s!=null?s(y):(n.push(y),o),u=y=>(n=new px,s!=null?s({error:y}):(n.push({error:y}),o)),d=y=>{if(i)return o;if(e?.objectMode!==!0&&y?.byteLength==null)throw new Error("objectMode was not true but tried to push non-Uint8Array value");return l({done:!1,value:y})},h=y=>i?o:(i=!0,y!=null?u(y):l({done:!0})),p=()=>(n=new px,h(),{done:!0}),f=y=>(h(y),{done:!0});if(o={[Symbol.asyncIterator](){return this},next:c,return:p,throw:f,push:d,end:h,get readableLength(){return n.size},onEmpty:async y=>{let m=y?.signal;if(m?.throwIfAborted(),n.isEmpty())return;let w,b;m!=null&&(w=new Promise((x,S)=>{b=()=>{S(new SZ)},m.addEventListener("abort",b)}));try{await Promise.race([a.promise,w])}finally{b!=null&&m!=null&&m?.removeEventListener("abort",b)}}},t==null)return o;let g=o;return o={[Symbol.asyncIterator](){return this},next(){return g.next()},throw(y){return g.throw(y),t!=null&&(t(y),t=void 0),{done:!0}},return(){return g.return(),t!=null&&(t(),t=void 0),{done:!0}},push:d,end(y){return g.end(y),t!=null&&(t(y),t=void 0),o},get readableLength(){return g.readableLength},onEmpty:y=>g.onEmpty(y)},o}function gA(r,e){let t,n=function(){let o=function(){t=void 0,r()};clearTimeout(t),t=setTimeout(o,e)};return n.start=()=>{},n.stop=()=>{clearTimeout(t)},n}var AL=class extends Error{static name="QueueFullError";constructor(e="The queue was full"){super(e),this.name="QueueFullError"}},Im=class extends Error{static name="UnexpectedEOFError";name="UnexpectedEOFError"};var IL=class extends Error{static name="StreamClosedError";name="StreamClosedError"};function rdt(r){return r.reason}async function Tm(r,e,t){if(e==null)return r;let n=t?.translateError??rdt;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let o;try{return await Promise.race([r,new Promise((s,i)=>{o=()=>{i(n(e))},e.addEventListener("abort",o)})])}finally{o!=null&&e.removeEventListener("abort",o)}}var TL=class{deferred;signal;constructor(e){this.signal=e,this.deferred=hx(),this.onAbort=this.onAbort.bind(this),this.signal?.addEventListener("abort",this.onAbort)}onAbort(){this.deferred.reject(this.signal?.reason??new Bu)}cleanup(){this.signal?.removeEventListener("abort",this.onAbort)}};function ndt(){return`${parseInt(String(Math.random()*1e9),10).toString()}${Date.now()}`}var kL=class{id;fn;options;recipients;status;timeline;controller;constructor(e,t){this.id=ndt(),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 Bu),this.cleanup())}async join(e={}){let t=new TL(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 Tm(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 DL=class extends Ci{concurrency;maxSize;queue;pending;sort;paused;constructor(e={}){super(),this.concurrency=e.concurrency??Number.POSITIVE_INFINITY,this.maxSize=e.maxSize??Number.POSITIVE_INFINITY,this.pending=0,this.paused=!1,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=gA(this.emitEmpty.bind(this),1),this.emitIdle=gA(this.emitIdle.bind(this),1)}emitEmpty(){this.size===0&&this.safeDispatchEvent("empty")}emitIdle(){this.running===0&&this.safeDispatchEvent("idle")}pause(){this.paused=!0}resume(){this.paused&&(this.paused=!1,this.tryToStartAnother())}tryToStartAnother(){if(this.paused)return!1;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 AL;let n=new kL(e,t);return this.enqueue(n),this.safeDispatchEvent("add"),this.tryToStartAnother(),n.join(t).then(o=>(this.safeDispatchEvent("completed",{detail:o}),this.safeDispatchEvent("success",{detail:{job:n,result:o}}),o)).catch(o=>{if(n.status==="queued"){for(let s=0;s<this.queue.length;s++)if(this.queue[s]===n){this.queue.splice(s,1);break}}throw this.safeDispatchEvent("failure",{detail:{job:n,error:o}}),o})}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach(e=>{e.abort(new Bu)}),this.clear()}async onEmpty(e){this.size!==0&&await ba(this,"empty",e)}async onSizeLessThan(e,t){this.size<e||await ba(this,"next",{...t,filter:()=>this.size<e})}async onIdle(e){this.pending===0&&this.size===0||await ba(this,"idle",e)}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=mx({objectMode:!0}),n=c=>{c!=null?this.abort():this.clear(),t.end(c)},o=c=>{c.detail!=null&&t.push(c.detail)},s=c=>{n(c.detail.error)},i=()=>{n()},a=()=>{n(new Bu("Queue aborted"))};this.addEventListener("completed",o),this.addEventListener("failure",s),this.addEventListener("idle",i),e?.signal?.addEventListener("abort",a);try{yield*t}finally{this.removeEventListener("completed",o),this.removeEventListener("failure",s),this.removeEventListener("idle",i),e?.signal?.removeEventListener("abort",a),n()}}};var odt=Math.pow(2,20)*4,_L=class extends Ci{status;timeline;inactivityTimeout;maxReadBufferLength;maxWriteBufferLength;log;direction;maxMessageSize;readStatus;writeStatus;remoteReadStatus;remoteWriteStatus;writableNeedsDrain;readBuffer;writeBuffer;sendingData;onDrainPromise;constructor(e){super(),this.status="open",this.log=e.log,this.direction=e.direction??"outbound",this.inactivityTimeout=e.inactivityTimeout??12e4,this.maxReadBufferLength=e.maxReadBufferLength??odt,this.maxWriteBufferLength=e.maxWriteBufferLength,this.maxMessageSize=e.maxMessageSize,this.readBuffer=new xr,this.writeBuffer=new xr,this.readStatus="readable",this.remoteReadStatus="readable",this.writeStatus="writable",this.remoteWriteStatus="writable",this.sendingData=!1,this.writableNeedsDrain=!1,this.timeline={open:Date.now()},this.processSendQueue=this.processSendQueue.bind(this);let t=()=>{this.writableNeedsDrain&&(this.log.trace("drain event received, continue sending data"),this.writableNeedsDrain=!1,this.processSendQueue()),this.onDrainPromise?.resolve()};this.addEventListener("drain",t);let n=o=>{this.onDrainPromise?.reject(o.error??new IL)};this.addEventListener("close",n)}get readBufferLength(){return this.readBuffer.byteLength}get writeBufferLength(){return this.writeBuffer.byteLength}async onDrain(e){return this.writableNeedsDrain!==!0?Promise.resolve():(this.onDrainPromise==null&&(this.onDrainPromise=Promise.withResolvers()),Tm(this.onDrainPromise.promise,e?.signal))}async*[Symbol.asyncIterator](){if(this.readStatus!=="readable"&&this.readStatus!=="paused")return;let e=mx(),t=s=>{e.push(s.data)};this.addEventListener("message",t);let n=s=>{e.end(s.error)};this.addEventListener("close",n);let o=()=>{e.end()};this.addEventListener("remoteCloseWrite",o);try{yield*e}finally{this.removeEventListener("message",t),this.removeEventListener("close",n),this.removeEventListener("remoteCloseWrite",o)}}isReadable(){return this.status==="open"}send(e){if(this.writeStatus==="closed"||this.writeStatus==="closing")throw new zf(`Cannot write to a stream that is ${this.writeStatus}`);return this.log.trace("append %d bytes to write buffer",e.byteLength),this.writeBuffer.append(e),this.processSendQueue()}abort(e){if(!(this.status==="aborted"||this.status==="reset"||this.status==="closed")){this.log.error("abort with error - %e",e),this.status="aborted",this.readBuffer.byteLength>0&&this.readBuffer.consume(this.readBuffer.byteLength),this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle")),this.writeStatus="closed",this.remoteWriteStatus="closed",this.readStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now();try{this.sendReset(e)}catch(t){this.log("failed to send reset to remote - %e",t)}this.dispatchEvent(new R8(e))}}pause(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf("Cannot pause a stream that is closing/closed");this.readStatus!=="paused"&&(this.readStatus="paused",this.sendPause())}resume(){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf("Cannot resume a stream that is closing/closed");this.readStatus!=="readable"&&(this.readStatus="readable",this.dispatchReadBuffer(),this.sendResume())}push(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.append(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}unshift(e){if(this.readStatus==="closed"||this.readStatus==="closing")throw new zf(`Cannot push data onto a stream that is ${this.readStatus}`);if(e.byteLength!==0){if(this.readBuffer.prepend(e),this.readStatus==="paused"||this.listenerCount("message")===0){this.checkReadBufferLength();return}setTimeout(()=>{this.dispatchReadBuffer()},0)}}onData(e){if(e.byteLength!==0){if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("ignoring data - read status %s",this.readStatus);return}this.readBuffer.append(e),this.dispatchReadBuffer()}}addEventListener(...e){super.addEventListener.apply(this,e),e[0]==="message"&&this.readBuffer.byteLength>0&&queueMicrotask(()=>{this.dispatchReadBuffer()})}onRemoteReset(){this.log("remote reset"),this.status="reset",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.timeline.close=Date.now(),this.readBuffer.byteLength===0&&(this.readStatus="closed");let e=new I8;this.dispatchEvent(new L8(e))}onTransportClosed(e){this.log("transport closed"),this.readStatus==="readable"&&this.readBuffer.byteLength===0&&(this.log("close readable end after transport closed and read buffer is empty"),this.readStatus="closed"),this.remoteReadStatus!=="closed"&&(this.remoteReadStatus="closed"),this.remoteWriteStatus!=="closed"&&(this.remoteWriteStatus="closed"),this.writeStatus!=="closed"&&(this.writeStatus="closed"),e!=null?this.abort(e):(this.status==="open"||this.status==="closing")&&(this.timeline.close=Date.now(),this.status="closed",this.writeStatus="closed",this.remoteWriteStatus="closed",this.remoteReadStatus="closed",this.dispatchEvent(new zw))}onRemoteCloseWrite(){this.remoteWriteStatus!=="closed"&&(this.log.trace("on remote close write"),this.remoteWriteStatus="closed",this.safeDispatchEvent("remoteCloseWrite"),this.writeStatus==="closed"&&this.onTransportClosed())}onRemoteCloseRead(){this.log.trace("on remote close read"),this.remoteReadStatus="closed",this.writeBuffer.byteLength>0&&(this.writeBuffer.consume(this.writeBuffer.byteLength),this.safeDispatchEvent("idle"))}processSendQueue(){if(this.writableNeedsDrain)return this.log.trace("not processing send queue as drain is required"),this.checkWriteBufferLength(),!1;if(this.writeBuffer.byteLength===0)return this.log.trace("not processing send queue as no bytes to send"),!0;if(this.sendingData)return this.log.trace("not processing send queue as already sending data"),!0;this.sendingData=!0,this.log.trace("processing send queue with %d queued bytes",this.writeBuffer.byteLength);try{let e=!0,t=this.writeBuffer.byteLength,n=0;for(;this.writeBuffer.byteLength>0;){let o=Math.min(this.maxMessageSize??this.writeBuffer.byteLength,this.writeBuffer.byteLength);if(o===0){e=!1;break}let s=this.writeBuffer.sublist(0,o),i=new xr(s);this.writeBuffer.consume(s.byteLength);let a=this.sendData(s);if(e=a.canSendMore,n+=a.sentBytes,a.sentBytes!==i.byteLength&&(i.consume(a.sentBytes),this.writeBuffer.prepend(i)),!e)break}return e||(this.log.trace("sent %d/%d bytes, pausing sending because underlying stream is full, %d bytes left in the write buffer",n,t,this.writeBuffer.byteLength),this.writableNeedsDrain=!0,this.checkWriteBufferLength()),this.writeBuffer.byteLength===0&&this.safeDispatchEvent("idle"),e}finally{this.sendingData=!1}}dispatchReadBuffer(){try{if(this.listenerCount("message")===0){this.log.trace("not dispatching pause buffer as there are no listeners for the message event");return}if(this.readBuffer.byteLength===0){this.log.trace("not dispatching pause buffer as there is no data to dispatch");return}if(this.readStatus==="paused"){this.log.trace("not dispatching pause buffer we are paused");return}if(this.readStatus==="closing"||this.readStatus==="closed"){this.log("dropping %d bytes because the readable end is %s",this.readBuffer.byteLength,this.readStatus),this.readBuffer.consume(this.readBuffer.byteLength);return}let e=this.readBuffer.sublist();this.readBuffer.consume(e.byteLength),this.dispatchEvent(new P8(e))}finally{this.readBuffer.byteLength===0&&this.remoteWriteStatus==="closed"&&(this.log("close readable end after dispatching read buffer and remote writable end is closed"),this.readStatus="closed"),this.checkReadBufferLength()}}checkReadBufferLength(){this.readBuffer.byteLength>this.maxReadBufferLength&&this.abort(new VC(`Read buffer length of ${this.readBuffer.byteLength} exceeded limit of ${this.maxReadBufferLength}, read status is ${this.readStatus}`))}checkWriteBufferLength(){this.maxWriteBufferLength!=null&&this.writeBuffer.byteLength>this.maxWriteBufferLength&&this.abort(new VC(`Write buffer length of ${this.writeBuffer.byteLength} exceeded limit of ${this.maxWriteBufferLength}, write status is ${this.writeStatus}`))}onMuxerNeedsDrain(){this.writableNeedsDrain=!0}onMuxerDrain(){this.safeDispatchEvent("drain")}};var gx=class extends _L{remoteAddr;metricPrefix;metrics;constructor(e){super(e),this.metricPrefix=e.metricPrefix??"",this.metrics=e.metrics,this.remoteAddr=e.remoteAddr,this.addEventListener("close",t=>{this.metrics?.increment({[`${this.metricPrefix}end`]:!0}),t.error!=null?t.local?this.metrics?.increment({[`${this.metricPrefix}abort`]:!0}):this.metrics?.increment({[`${this.metricPrefix}reset`]:!0}):t.local?this.metrics?.increment({[`${this.metricPrefix}_local_close`]:!0}):this.metrics?.increment({[`${this.metricPrefix}_remote_close`]:!0})})}async close(e){this.status==="open"&&(this.status="closing",this.writeStatus="closing",this.remoteWriteStatus="closing",this.remoteReadStatus="closing",(this.sendingData||this.writeBuffer.byteLength>0)&&(this.log("waiting for write queue to become idle before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ba(this,"idle",{...e,rejectionEvents:["close"]})),this.writableNeedsDrain&&(this.log("waiting for write queue to drain before closing writable end of stream, %d unsent bytes",this.writeBuffer.byteLength),await ba(this,"drain",{...e,rejectionEvents:["close"]})),await this.sendClose(e),this.onTransportClosed())}};function yA(r){let e=new globalThis.AbortController;function t(){let s=r.filter(i=>i?.aborted===!0).map(i=>i?.reason).pop();e.abort(s);for(let i of r)i?.removeEventListener!=null&&i.removeEventListener("abort",t)}for(let s of r){if(s?.aborted===!0){t();break}s?.addEventListener!=null&&s.addEventListener("abort",t)}function n(){for(let s of r)s?.removeEventListener!=null&&s.removeEventListener("abort",t)}let o=e.signal;return o.clear=n,o}var sdt=4194304,PL=class extends Error{static name="UnwrappedError";name="UnwrappedError"},AZ=class extends Error{name="InvalidMessageLengthError";code="ERR_INVALID_MSG_LENGTH"},IZ=class extends Error{name="InvalidDataLengthError";code="ERR_MSG_DATA_TOO_LONG"},TZ=class extends Error{name="InvalidDataLengthLengthError";code="ERR_MSG_LENGTH_TOO_LONG"};function idt(r){return typeof r?.closeRead=="function"}function adt(r){return typeof r?.close=="function"}function CZ(r){return idt(r)?r.remoteWriteStatus!=="writable"&&r.readBufferLength===0:adt(r)?r.status!=="open":!1}function cdt(r){return r?.addEventListener!=null&&r?.removeEventListener!=null&&r?.send!=null&&r?.push!=null&&r?.log!=null}function ldt(r,e){let t=e?.maxBufferSize??sdt,n=new xr,o,s=!1;if(!cdt(r))throw new Si("Argument should be a Stream or a Multiaddr");let i=u=>{if(n.append(u.data),n.byteLength>t){let d=n.byteLength;n.consume(n.byteLength),o?.reject(new Error(`Read buffer overflow - ${d} > ${t}`))}o?.resolve()};r.addEventListener("message",i);let a=u=>{u.error!=null?o?.reject(u.error):o?.resolve()};r.addEventListener("close",a);let c=()=>{o?.resolve()};r.addEventListener("remoteCloseWrite",c);let l={readBuffer:n,async read(u){if(s===!0)throw new PL("Stream was unwrapped");if(CZ(r)){if(u?.bytes==null)return null;if(n.byteLength<u.bytes)throw r.log.error("closed after reading %d/%d bytes",n.byteLength,u.bytes),new Im(`Unexpected EOF - stream closed after reading ${n.byteLength}/${u.bytes} bytes`)}let d=u?.bytes??1;for(o=Promise.withResolvers();;){if(n.byteLength>=d){o.resolve();break}if(await Tm(o.promise,u?.signal),CZ(r)){if(n.byteLength===0&&u?.bytes==null)return null;break}o=Promise.withResolvers()}let h=u?.bytes??n.byteLength;if(n.byteLength<h){if(CZ(r))throw r.log.error("closed while reading %d/%d bytes",n.byteLength,h),new Im(`Unexpected EOF - stream closed while reading ${n.byteLength}/${h} bytes`);return l.read(u)}let p=n.sublist(0,h);return n.consume(h),p},async write(u,d){if(s===!0)throw new PL("Stream was unwrapped");r.send(u)||await ba(r,"drain",{signal:d?.signal,rejectionEvents:["close"]})},unwrap(){return s||(s=!0,r.removeEventListener("message",i),r.removeEventListener("close",a),r.removeEventListener("remoteCloseWrite",c),n.byteLength>0&&(r.log("stream unwrapped with %d unread bytes",n.byteLength),r.push(n))),r}};return l}function udt(r,e={}){let t=ldt(r,e);e.maxDataLength!=null&&e.maxLengthLength==null&&(e.maxLengthLength=Gt(e.maxDataLength));let n=e?.lengthDecoder??ma,o=e?.lengthEncoder??ICe;return{async read(i){let a=-1,c=new xr;for(;;){let u=await t.read({...i,bytes:1});if(u==null)break;c.append(u);try{a=n(c)}catch(d){if(d instanceof RangeError)continue;throw d}if(a<0)throw new AZ("Invalid message length");if(e?.maxLengthLength!=null&&c.byteLength>e.maxLengthLength)throw new TZ(`Message length length too long - ${c.byteLength} > ${e.maxLengthLength}`);if(a>-1)break}if(e?.maxDataLength!=null&&a>e.maxDataLength)throw new IZ(`Message length too long - ${a} > ${e.maxDataLength}`);let l=await t.read({...i,bytes:a});if(l==null)throw r.log.error("tried to read %d bytes but the stream closed",a),new Im(`Unexpected EOF - tried to read ${a} bytes but the stream closed`);if(l.byteLength!==a)throw r.log.error("read %d/%d bytes before the stream closed",l.byteLength,a),new Im(`Unexpected EOF - read ${l.byteLength}/${a} bytes before the stream closed`);return l},async write(i,a){await t.write(new xr(o(i.byteLength),i),a)},async writeV(i,a){let c=new xr(...i.flatMap(l=>[o(l.byteLength),l]));await t.write(c,a)},unwrap(){return t.unwrap()}}}function bA(r,e){let t=udt(r,e),n={read:async(o,s)=>{let i=await t.read(s);return o.decode(i)},write:async(o,s,i)=>{await t.write(s.encode(o),i)},writeV:async(o,s,i)=>{await t.writeV(o.map(a=>s.encode(a)),i)},pb:o=>({read:async s=>n.read(o,s),write:async(s,i)=>n.write(s,o,i),writeV:async(s,i)=>n.writeV(s,o,i),unwrap:()=>n}),unwrap:()=>t.unwrap()};return n}var yx=class extends DL{has(e){return this.find(e)!=null}find(e){return this.queue.find(t=>e.equals(t.options.peerId))}};function uTe(r,e,t){let n,o,s=!1;function i(){let l={signal:o.signal};if(t?.timeout!=null){let u=yA([o.signal,AbortSignal.timeout(t.timeout)]);l.signal=u}s=!0,Promise.resolve().then(async()=>{await r(l)}).catch(()=>{}).finally(()=>{s=!1,!o.signal.aborted&&(n=setTimeout(i,e))})}let a=gA(i,t?.debounce??100),c=!1;return{setInterval:l=>{e!==l&&(e=l,n!=null&&(clearTimeout(n),n=setTimeout(i,e)))},setTimeout:l=>{t??={},t.timeout=l},run:()=>{s||(clearTimeout(n),a())},start:()=>{c||(c=!0,o=new AbortController,o.signal,t?.runImmediately===!0?queueMicrotask(()=>{i()}):n=setTimeout(i,e))},stop:()=>{clearTimeout(n),o?.abort(),c=!1}}}var ddt=1024*1024*4,fdt=10,kZ=class extends gx{websocket;maxBufferedAmount;checkBufferedAmountTask;constructor(e){super(e),this.websocket=e.websocket,this.maxBufferedAmount=e.maxBufferedAmount??ddt,this.checkBufferedAmountTask=uTe(this.checkBufferedAmount.bind(this),e.bufferedAmountPollInterval??fdt),this.websocket.addEventListener("close",t=>{if(this.log('closed - code %d, reason "%s", wasClean %s',t.code,t.reason,t.wasClean),this.checkBufferedAmountTask.stop(),!t.wasClean){this.onRemoteReset();return}this.onTransportClosed()},{once:!0}),this.websocket.addEventListener("message",t=>{try{let n;if(typeof t.data=="string")n=Ze(t.data);else if(t.data instanceof ArrayBuffer)n=new Uint8Array(t.data,0,t.data.byteLength);else{this.abort(new Error("Incorrect binary type"));return}this.onData(n)}catch(n){this.log.error("error receiving data - %e",n)}})}sendData(e){for(let n of e)this.websocket.send(n);let t=this.websocket.bufferedAmount<this.maxBufferedAmount;return t||this.checkBufferedAmountTask.start(),{sentBytes:e.byteLength,canSendMore:t}}sendReset(){this.websocket.close(1006)}async sendClose(e){this.websocket.close(),e?.signal?.throwIfAborted()}sendPause(){}sendResume(){}checkBufferedAmount(){this.log("buffered amount now %d",this.websocket.bufferedAmount),this.websocket.bufferedAmount===0&&(this.checkBufferedAmountTask.stop(),this.safeDispatchEvent("drain"))}};function dTe(r){return new kZ(r)}var DZ=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"})})}[M8]=!0;[Symbol.toStringTag]="@libp2p/websockets";[B8]=["@libp2p/transport"];async dial(e,t){this.log("dialing %s",e),t=t??{};let n=dTe({websocket:await this._connect(e,t),remoteAddr:e,metrics:this.metrics?.dialerEvents,direction:"outbound",log:this.components.logger.forComponent("libp2p:websockets:connection"),maxBufferedAmount:this.init.maxBufferedAmount,bufferedAmountPollInterval:this.init.bufferedAmountPollInterval});this.log("new outbound connection %s",n.remoteAddr);let o=await t.upgrader.upgradeOutbound(n,t);return this.log("outbound connection %s upgraded",n.remoteAddr),o}async _connect(e,t){t?.signal?.throwIfAborted();let n=UAe(e);this.log("create websocket connection to %s",n);let o=new WebSocket(n);o.binaryType="arraybuffer";try{t.onProgress?.(new Fc("websockets:open-connection")),await ba(o,"open",t)}catch(s){if(t.signal?.aborted)throw this.metrics?.dialerEvents.increment({abort:!0}),new A8(`Could not connect to ${n}`);this.metrics?.dialerEvents.increment({error:!0});try{o.close()}catch{}throw s}return this.log("connected %s",e),this.metrics?.dialerEvents.increment({connect:!0}),o}createListener(e){return KAe({logger:this.logger,events:this.components.events,metrics:this.components.metrics},{...this.init,...e})}listenFilter(e){return e.filter(t=>hAe.exactMatch(t)||mAe.exactMatch(t))}dialFilter(e){return this.listenFilter(e)}};function fTe(r={}){return e=>new DZ(e,r)}var hTe=Symbol.for("nodejs.util.inspect.custom"),hdt=114,wA=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()})`}[aY]=!0;toString(){return this.string==null&&(this.string=_r.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return wr.createV1(hdt,this.multihash)}toJSON(){return this.toString()}equals(e){if(e==null)return!1;if(e instanceof Uint8Array)return zr(this.multihash.bytes,e);if(typeof e=="string")return this.toString()===e;if(e?.toMultihash()?.bytes!=null)return zr(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[hTe](){return`PeerId(${this.toString()})`}},RL=class extends wA{type="RSA";publicKey;constructor(e){super({...e,type:"RSA"}),this.publicKey=e.publicKey}},LL=class extends wA{type="Ed25519";publicKey;constructor(e){super({...e,type:"Ed25519"}),this.publicKey=e.publicKey}},ML=class extends wA{type="secp256k1";publicKey;constructor(e){super({...e,type:"secp256k1"}),this.publicKey=e.publicKey}},pdt=2336,xA=class{type="url";multihash;publicKey;url;constructor(e){this.url=e.toString(),this.multihash=ga.digest(Ze(this.url))}[hTe](){return`PeerId(${this.url})`}[aY]=!0;toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return wr.createV1(pdt,this.toMultihash())}toJSON(){return this.toString()}equals(e){return e==null?!1:(e instanceof Uint8Array&&(e=We(e)),e.toString()===this.toString())}};var mdt=114,pTe=2336;function _Z(r,e){let t;if(r.charAt(0)==="1"||r.charAt(0)==="Q")t=Hf(_r.decode(`z${r}`));else{if(r.startsWith("k51qzi5uqu5")||r.startsWith("kzwfwjn5ji4")||r.startsWith("k2k4r8")||r.startsWith("bafz"))return gdt(wr.parse(r));if(e==null)throw new Si('Please pass a multibase decoder for strings that do not start with "1" or "Q"');t=Hf(e.decode(r))}return BL(t)}function BL(r){if(bdt(r))return new RL({multihash:r});if(ydt(r))try{let e=iTe(r);if(e.type==="Ed25519")return new LL({multihash:r,publicKey:e});if(e.type==="secp256k1")return new ML({multihash:r,publicKey:e})}catch{let t=We(r.digest);return new xA(new URL(t))}throw new k8("Supplied PeerID Multihash is invalid")}function gdt(r){if(r?.multihash==null||r.version==null||r.version===1&&r.code!==mdt&&r.code!==pTe)throw new T8("Supplied PeerID CID is invalid");if(r.code===pTe){let e=We(r.multihash.digest);return new xA(new URL(e))}return BL(r.multihash)}function ydt(r){return r.code===ga.code}function bdt(r){return r.code===Gw.code}var Xn=class extends Error{static name="InvalidMultiaddrError";name="InvalidMultiaddrError"},Yu=class extends Error{static name="ValidationError";name="ValidationError"},OL=class extends Error{static name="InvalidParametersError";name="InvalidParametersError"},NL=class extends Error{static name="UnknownProtocolError";name="UnknownProtocolError"};function RZ(r){return e=>We(e,r)}function LZ(r){return e=>Ze(e,r)}function bx(r){return new DataView(r.buffer).getUint16(r.byteOffset).toString()}function km(r){let e=new ArrayBuffer(2);return new DataView(e).setUint16(0,typeof r=="string"?parseInt(r):r),new Uint8Array(e)}function mTe(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=Ze(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 o=km(n);return $r([t,o],t.length+o.length)}function gTe(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=Ii.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 o=km(n);return $r([t,o],t.length+o.length)}function MZ(r){let e=r.subarray(0,r.length-2),t=r.subarray(r.length-2),n=We(e,"base32"),o=bx(t);return`${n}:${o}`}var BZ=function(r){r=r.toString().trim();let e=new Uint8Array(4);return r.split(/\./g).forEach((t,n)=>{let o=parseInt(t,10);if(isNaN(o)||o<0||o>255)throw new Xn("Invalid byte value in IP address");e[n]=o}),e},yTe=function(r){let e=0;r=r.toString().trim();let t=r.split(":",8),n;for(n=0;n<t.length;n++){let s=Ti(t[n]),i;s&&(i=BZ(t[n]),t[n]=We(i.subarray(0,2),"base16")),i!=null&&++n<8&&t.splice(n,0,We(i.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 s=[n,1];for(n=9-t.length;n>0;n--)s.push("0");t.splice.apply(t,s)}let o=new Uint8Array(e+16);for(n=0;n<t.length;n++){t[n]===""&&(t[n]="0");let s=parseInt(t[n],16);if(isNaN(s)||s<0||s>65535)throw new Xn("Invalid byte value in IP address");o[e++]=s>>8&255,o[e++]=s&255}return o},bTe=function(r){if(r.byteLength!==4)throw new Xn("IPv4 address was incorrect length");let e=[];for(let t=0;t<r.byteLength;t++)e.push(r[t]);return e.join(".")},wTe=function(r){if(r.byteLength!==16)throw new Xn("IPv6 address was incorrect length");let e=[];for(let n=0;n<r.byteLength;n+=2){let o=r[n],s=r[n+1],i=`${o.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}`;e.push(i)}let t=e.join(":");try{let n=new URL(`http://[${t}]`);return n.hostname.substring(1,n.hostname.length-1)}catch{throw new Xn(`Invalid IPv6 address "${t}"`)}};function xTe(r){try{let e=new URL(`http://[${r}]`);return e.hostname.substring(1,e.hostname.length-1)}catch{throw new Xn(`Invalid IPv6 address "${r}"`)}}var PZ=Object.values(Nu).map(r=>r.decoder),wdt=(function(){let r=PZ[0].or(PZ[1]);return PZ.slice(2).forEach(e=>r=r.or(e)),r})();function vTe(r){return wdt.decode(r)}function ETe(r){return e=>r.encoder.encode(e)}function xdt(r){if(parseInt(r).toString()!==r)throw new Yu("Value must be an integer")}function vdt(r){if(r<0)throw new Yu("Value must be a positive integer, or zero")}function Edt(r){return e=>{if(e>r)throw new Yu(`Value must be smaller than or equal to ${r}`)}}function Sdt(...r){return e=>{for(let t of r)t(e)}}var vA=Sdt(xdt,vdt,Edt(65535));var wn=-1,OZ=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 NL(`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)}))}},Xu=new OZ,cft=[{code:4,name:"ip4",size:32,valueToBytes:BZ,bytesToValue:bTe,validate:r=>{if(!Ti(r))throw new Yu(`Invalid IPv4 address "${r}"`)}},{code:6,name:"tcp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:273,name:"udp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:33,name:"dccp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:41,name:"ip6",size:128,valueToBytes:yTe,bytesToValue:wTe,stringToValue:xTe,validate:r=>{if(!Ww(r))throw new Yu(`Invalid IPv6 address "${r}"`)}},{code:42,name:"ip6zone",size:wn},{code:43,name:"ipcidr",size:8,bytesToValue:RZ("base10"),valueToBytes:LZ("base10")},{code:53,name:"dns",size:wn},{code:54,name:"dns4",size:wn},{code:55,name:"dns6",size:wn},{code:56,name:"dnsaddr",size:wn},{code:132,name:"sctp",size:16,valueToBytes:km,bytesToValue:bx,validate:vA},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:wn,stringToValue:r=>decodeURIComponent(r),valueToString:r=>encodeURIComponent(r)},{code:421,name:"p2p",aliases:["ipfs"],size:wn,bytesToValue:RZ("base58btc"),valueToBytes:r=>r.startsWith("Q")||r.startsWith("1")?LZ("base58btc")(r):wr.parse(r).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:MZ,valueToBytes:mTe},{code:445,name:"onion3",size:296,bytesToValue:MZ,valueToBytes:gTe},{code:446,name:"garlic64",size:wn},{code:447,name:"garlic32",size:wn},{code:448,name:"tls"},{code:449,name:"sni",size:wn},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:wn,bytesToValue:ETe(cm),valueToBytes:vTe},{code:480,name:"http"},{code:481,name:"http-path",size:wn,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:wn}];cft.forEach(r=>{Xu.addProtocol(r)});function STe(r){let e=[],t=0;for(;t<r.length;){let n=ma(r,t),o=Xu.getProtocol(n),s=Gt(n),i=lft(o,r,t+s),a=0;i>0&&o.size===wn&&(a=Gt(i));let c=s+a+i,l={code:n,name:o.name,bytes:r.subarray(t,t+c)};if(i>0){let u=t+s+a,d=r.subarray(u,u+i);l.value=o.bytesToValue?.(d)??We(d)}e.push(l),t+=c}return e}function CTe(r){let e=0,t=[];for(let n of r){if(n.bytes==null){let o=Xu.getProtocol(n.code),s=Gt(n.code),i,a=0,c=0;n.value!=null&&(i=o.valueToBytes?.(n.value)??Ze(n.value),a=i.byteLength,o.size===wn&&(c=Gt(a)));let l=new Uint8Array(s+c+a),u=0;Ai(n.code,l,u),u+=s,i!=null&&(o.size===wn&&(Ai(a,l,u),u+=c),l.set(i,u)),n.bytes=l}t.push(n.bytes),e+=n.bytes.byteLength}return $r(t,e)}function ATe(r){if(r.charAt(0)!=="/")throw new Xn('String multiaddr must start with "/"');let e=[],t="protocol",n="",o="";for(let s=1;s<r.length;s++){let i=r.charAt(s);i!=="/"&&(t==="protocol"?o+=r.charAt(s):n+=r.charAt(s));let a=s===r.length-1;if(i==="/"||a){let c=Xu.getProtocol(o);if(t==="protocol"){if(c.size==null||c.size===0){e.push({code:c.code,name:c.name}),n="",o="",t="protocol";continue}else if(a)throw new Xn(`Component ${o} 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 Xn(`Component ${o} was missing value`);l.value=c.stringToValue?.(n)??n}e.push(l),n="",o="",t="protocol"}}}if(o!==""&&n!=="")throw new Xn("Incomplete multiaddr");return e}function ITe(r){return`/${r.flatMap(e=>{if(e.value==null)return e.name;let t=Xu.getProtocol(e.code);if(t==null)throw new Xn(`Unknown protocol code ${e.code}`);return[e.name,t.valueToString?.(e.value)??e.value]}).join("/")}`}function lft(r,e,t){return r.size==null||r.size===0?0:r.size>0?r.size/8:ma(e,t)}var uft=Symbol.for("nodejs.util.inspect.custom"),NZ=Symbol.for("@multiformats/multiaddr");function dft(r){if(r==null&&(r="/"),TTe(r))return r.getComponents();if(r instanceof Uint8Array)return STe(r);if(typeof r=="string")return r=r.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""),r===""&&(r="/"),ATe(r);if(Array.isArray(r))return r;throw new Xn("Must be a string, Uint8Array, Component[], or another Multiaddr")}var FL=class r{[NZ]=!0;#e;#t;#r;constructor(e="/",t={}){this.#e=dft(e),t.validate!==!1&&fft(this)}get bytes(){return this.#r==null&&(this.#r=CTe(this.#e)),this.#r}toString(){return this.#t==null&&(this.#t=ITe(this.#e)),this.#t}toJSON(){return this.toString()}getComponents(){return[...this.#e.map(e=>({...e}))]}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(),o=n.lastIndexOf(t);if(o<0)throw new OL(`Address ${this.toString()} does not contain subaddress: ${t}`);return new r(n.slice(0,o),{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})}equals(e){return zr(this.bytes,e.bytes)}[uft](){return`Multiaddr(${this.toString()})`}};function fft(r){r.getComponents().forEach(e=>{let t=Xu.getProtocol(e.code);e.value!=null&&t.validate?.(e.value)})}function TTe(r){return!!r?.[NZ]}function Ea(r){return new FL(r)}var UZ=1e3,kTe=60*UZ;var K7r=120*kTe,DTe=1,KL=5e3,_Te=100;var EA=`${xCe}-circuit-relay`,z7r=2*kTe,$7r=BigInt(1<<17),Dm="/libp2p/circuit/relay/0.2.0/hop",FZ="/libp2p/circuit/relay/0.2.0/stop",H7r=30*UZ,V7r=30*UZ,KZ=300,PTe=4096,RTe=.001;var Jf;(function(r){let e;(function(o){o.RESERVE="RESERVE",o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.RESERVE=0]="RESERVE",o[o.CONNECT=1]="CONNECT",o[o.STATUS=2]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Sm(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=_i((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),xx.codec().encode(o.peer,s)),o.reservation!=null&&(s.uint32(26),zL.codec().encode(o.reservation,s)),o.limit!=null&&(s.uint32(34),vx.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(40),Zn.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=xx.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.reservation=zL.codec().decode(o,o.uint32(),{limits:i.limits?.reservation});break}case 4:{a.limit=vx.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 5:{a.status=Zn.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Di(o,r.codec()),r.decode=(o,s)=>ki(o,r.codec(),s)})(Jf||(Jf={}));var $c;(function(r){let e;(function(o){o.CONNECT="CONNECT",o.STATUS="STATUS"})(e=r.Type||(r.Type={}));let t;(function(o){o[o.CONNECT=0]="CONNECT",o[o.STATUS=1]="STATUS"})(t||(t={})),(function(o){o.codec=()=>Sm(t)})(e=r.Type||(r.Type={}));let n;r.codec=()=>(n==null&&(n=_i((o,s,i={})=>{i.lengthDelimited!==!1&&s.fork(),o.type!=null&&(s.uint32(8),r.Type.codec().encode(o.type,s)),o.peer!=null&&(s.uint32(18),xx.codec().encode(o.peer,s)),o.limit!=null&&(s.uint32(26),vx.codec().encode(o.limit,s)),o.status!=null&&(s.uint32(32),Zn.codec().encode(o.status,s)),i.lengthDelimited!==!1&&s.ldelim()},(o,s,i={})=>{let a={},c=s==null?o.len:o.pos+s;for(;o.pos<c;){let l=o.uint32();switch(l>>>3){case 1:{a.type=r.Type.codec().decode(o);break}case 2:{a.peer=xx.codec().decode(o,o.uint32(),{limits:i.limits?.peer});break}case 3:{a.limit=vx.codec().decode(o,o.uint32(),{limits:i.limits?.limit});break}case 4:{a.status=Zn.codec().decode(o);break}default:{o.skipType(l&7);break}}}return a})),n),r.encode=o=>Di(o,r.codec()),r.decode=(o,s)=>ki(o,r.codec(),s)})($c||($c={}));var xx;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.id!=null&&t.id.byteLength>0&&(n.uint32(10),n.bytes(t.id)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={id:pn(0),addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.id=t.bytes();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new fA('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(xx||(xx={}));var zL;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{if(o.lengthDelimited!==!1&&n.fork(),t.expire!=null&&t.expire!==0n&&(n.uint32(8),n.uint64(t.expire)),t.addrs!=null)for(let s of t.addrs)n.uint32(18),n.bytes(s);t.voucher!=null&&(n.uint32(26),HL.codec().encode(t.voucher,n)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={expire:0n,addrs:[]},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.expire=t.uint64();break}case 2:{if(o.limits?.addrs!=null&&s.addrs.length===o.limits.addrs)throw new fA('Decode error - map field "addrs" had too many elements');s.addrs.push(t.bytes());break}case 3:{s.voucher=HL.codec().decode(t,t.uint32(),{limits:o.limits?.voucher});break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(zL||(zL={}));var vx;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.duration!=null&&(n.uint32(8),n.uint32(t.duration)),t.data!=null&&(n.uint32(16),n.uint64(t.data)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.duration=t.uint32();break}case 2:{s.data=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(vx||(vx={}));var Zn;(function(r){r.UNUSED="UNUSED",r.OK="OK",r.RESERVATION_REFUSED="RESERVATION_REFUSED",r.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",r.PERMISSION_DENIED="PERMISSION_DENIED",r.CONNECTION_FAILED="CONNECTION_FAILED",r.NO_RESERVATION="NO_RESERVATION",r.MALFORMED_MESSAGE="MALFORMED_MESSAGE",r.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"})(Zn||(Zn={}));var zZ;(function(r){r[r.UNUSED=0]="UNUSED",r[r.OK=100]="OK",r[r.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",r[r.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",r[r.PERMISSION_DENIED=202]="PERMISSION_DENIED",r[r.CONNECTION_FAILED=203]="CONNECTION_FAILED",r[r.NO_RESERVATION=204]="NO_RESERVATION",r[r.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",r[r.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"})(zZ||(zZ={}));(function(r){r.codec=()=>Sm(zZ)})(Zn||(Zn={}));var $L;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.lengthDelimited!==!1&&n.fork(),t.relay!=null&&t.relay.byteLength>0&&(n.uint32(10),n.bytes(t.relay)),t.peer!=null&&t.peer.byteLength>0&&(n.uint32(18),n.bytes(t.peer)),t.expiration!=null&&t.expiration!==0n&&(n.uint32(24),n.uint64(t.expiration)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={relay:pn(0),peer:pn(0),expiration:0n},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.relay=t.bytes();break}case 2:{s.peer=t.bytes();break}case 3:{s.expiration=t.uint64();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})($L||($L={}));var HL;(function(r){let e;r.codec=()=>(e==null&&(e=_i((t,n,o={})=>{o.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&&(n.uint32(26),$L.codec().encode(t.payload,n)),t.signature!=null&&t.signature.byteLength>0&&(n.uint32(42),n.bytes(t.signature)),o.lengthDelimited!==!1&&n.ldelim()},(t,n,o={})=>{let s={publicKey:pn(0),payloadType:pn(0),signature:pn(0)},i=n==null?t.len:t.pos+n;for(;t.pos<i;){let a=t.uint32();switch(a>>>3){case 1:{s.publicKey=t.bytes();break}case 2:{s.payloadType=t.bytes();break}case 3:{s.payload=$L.codec().decode(t,t.uint32(),{limits:o.limits?.payload});break}case 5:{s.signature=t.bytes();break}default:{t.skipType(a&7);break}}}return s})),e),r.encode=t=>Di(t,r.codec()),r.decode=(t,n)=>ki(t,r.codec(),n)})(HL||(HL={}));var SA=class extends Error{static name="HadEnoughRelaysError";name="HadEnoughRelaysError"},VL=class extends Error{static name="DoubleRelayError";name="DoubleRelayError"},qL=class extends Error{static name="RelayQueueFullError";name="RelayQueueFullError"};function $Z(r){let e=r*BigInt(1e3),t=new Date().getTime();return Number(e-BigInt(t))}var CA=class{expires;bytes;constructor(e){e?.duration!=null&&e?.duration!==0&&(this.expires=Date.now()+e.duration*1e3),this.bytes=e?.data,this.bytes===0n&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){this.bytes!=null&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(this.expires==null&&this.bytes==null)return;let e={};if(this.bytes!=null){let t=this;Object.defineProperty(e,"bytes",{get(){return t.bytes}})}if(this.expires!=null){let t=this;Object.defineProperty(e,"seconds",{get(){return Math.round(((t.expires??0)-Date.now())/1e3)}})}return e}},jL=At(st(bAe.matchers[0],Ct(290))),GL=At(Ct(290));function WL(r,e){let t={[Symbol.iterator]:()=>t,next:()=>{let n=r.next(),o=n.value;return n.done===!0||o==null?{done:!0,value:void 0}:{done:!1,value:e(o)}}};return t}var AA=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 WL(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 WL(this.map.values(),e=>e.key)}values(){return WL(this.map.values(),e=>e.value)}get size(){return this.map.size}};var YL=class{filter;constructor(e,t){this.filter=fx(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 HZ(r,e=.001){return new YL(r,e)}var XL=class extends Ci{components;started;running;topologyId;log;discoveryController;filter;queue;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.components=e,this.started=!1,this.running=!1,this.filter=t.filter,this.discoveryController=new AbortController,this.discoveryController.signal,this.dialPeer=this.dialPeer.bind(this),this.onPeer=this.onPeer.bind(this)}isStarted(){return this.started}async start(){this.topologyId=await this.components.registrar.register(Dm,{filter:this.filter,onConnect:e=>{this.log.trace("discovered relay %p queue (length: %d, active %d)",e,this.queue?.size,this.queue?.running),this.safeDispatchEvent("relay:discover",{detail:e})}}),this.started=!0}stop(){this.topologyId!=null&&this.components.registrar.unregister(this.topologyId),this.running&&this.stopDiscovery(),this.started=!1}startDiscovery(){this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,this.components.events.addEventListener("peer:discovery",this.onPeer),Promise.resolve().then(async()=>{this.log("searching peer store for relays");let e=await this.components.peerStore.all({filters:[n=>n.protocols.includes(Dm)],orders:[()=>Math.random()<.5?1:-1,(n,o)=>{let s=LTe(n),i=LTe(o);return s>i?-1:i>s?1:0}]});for(let n of e)this.log.trace("found relay peer %p in peer store",n.id),this.safeDispatchEvent("relay:discover",{detail:n.id});this.log("found %d relay peers in peer store",e.length);let t=this.queue=new yx({concurrency:5});this.log("start random walk");for await(let n of this.components.randomWalk.walk({signal:this.discoveryController.signal})){if(this.log.trace("found random peer %p",n.id),t.has(n.id)){this.log.trace("random peer %p was already in queue",n.id);continue}if(this.components.connectionManager.getConnections(n.id)?.length>0){this.log.trace("random peer %p was already connected",n.id);continue}if(!await this.components.connectionManager.isDialable(n.multiaddrs)){this.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map(o=>o.toString()));continue}t.queued>10&&(this.log.trace("wait for space in queue for %p",n.id),await t.onSizeLessThan(10,{signal:this.discoveryController.signal})),this.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,t.size,t.running),t.add(this.dialPeer,{peerId:n.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to random peer %p - %e",n.id,o)})}this.log("stop random walk"),await t.onIdle()}).catch(e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network - %e",e)}))}stopDiscovery(){this.log("stop discovery"),this.running=!1,this.discoveryController?.abort(),this.queue?.clear(),this.components.events.removeEventListener("peer:discovery",this.onPeer)}onPeer(e){this.log.trace("maybe dialing discovered peer %p",e.detail.id),this.maybeDialPeer(e).catch(t=>{this.log.trace("error dialing discovered peer %p - %e",e.detail.id,t)})}async maybeDialPeer(e){if(this.queue==null)return;let t=e.detail.id,n=e.detail.multiaddrs;if(this.queue.has(t)){this.log.trace("random peer %p was already in queue",t);return}if(this.components.connectionManager.getConnections(t)?.length>0){this.log.trace("random peer %p was already connected",t);return}if(!await this.components.connectionManager.isDialable(n)){this.log.trace("random peer %p was not dialable",t);return}this.queue?.add(this.dialPeer,{peerId:e.detail.id,signal:this.discoveryController.signal}).catch(o=>{this.log.error("error opening connection to discovered peer %p - %e",e.detail.id,o)})}async dialPeer({peerId:e,signal:t}){let n=yA([AbortSignal.timeout(5e3),t]);try{await this.components.connectionManager.openConnection(e,{signal:n})}finally{n.clear()}}};function LTe(r){let e=r.metadata.get("last-dial-success");return e==null?0:new Date(We(e)).getTime()}var VZ=class extends Ci{connectionManager;addressManager;reservationStore;listeningAddrs;log;listenTimeout;reservationId;relay;constructor(e,t={}){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=e.connectionManager,this.addressManager=e.addressManager,this.reservationStore=e.reservationStore,this.listeningAddrs=[],this.listenTimeout=t.listenTimeout??KL,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}_onRemoveRelayPeer=e=>{this.log("relay removed %p our relay %p",e.detail.relay,this.relay,this.relay?.equals(e.detail.relay)),this.relay?.equals(e.detail.relay)===!0&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach(t=>{this.addressManager.removeObservedAddr(t)}),this.listeningAddrs=[],this.safeDispatchEvent("listening"))};_onAddRelayPeer=e=>{let{details:t}=e.detail;t.type!=="configured"&&t.id===this.reservationId&&this.addedRelay(e.detail)};async listen(e){if(GL.exactMatch(e))this.log("searching for circuit relay servers"),this.reservationId=this.reservationStore.reserveRelay();else if(jL.exactMatch(e)){this.log("listen on specific relay server %a",e);let t=AbortSignal.timeout(this.listenTimeout);let n=e.decapsulate("/p2p-circuit"),o=await this.connectionManager.openConnection(n,{signal:t});if(!this.reservationStore.hasReservation(o.remotePeer)){this.log("making reservation on peer %p",o.remotePeer);let s=await this.reservationStore.addRelay(o.remotePeer,"configured");this.addedRelay(s)}}else throw new am(`Could not listen on p2p-circuit address "${e}"`)}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}async close(){this.reservationStore.cancelReservations(),this.listeningAddrs=[],this.reservationStore.removeEventListener("relay:removed",this._onRemoveRelayPeer),queueMicrotask(()=>{this.safeDispatchEvent("close")})}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map(t=>Ea(t).encapsulate("/p2p-circuit")),this.listeningAddrs.forEach(t=>{this.addressManager.confirmObservedAddr(t,{type:"transport"})}),queueMicrotask(()=>{this.safeDispatchEvent("listening")})}};function BTe(r){return new VZ(r)}var OTe="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var NTe=(r=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=OTe[t[r]&63];return e};var hft=60*1e3*10,pft=60*1e3*5,mft=30*1e3,ZL=class extends Ci{peerId;connectionManager;peerStore;events;reserveQueue;reservations;pendingReservations;maxReservationQueueLength;reservationCompletionTimeout;started;log;relayFilter;constructor(e,t){super(),this.log=e.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=e.peerId,this.connectionManager=e.connectionManager,this.peerStore=e.peerStore,this.events=e.events,this.reservations=new AA,this.pendingReservations=[],this.maxReservationQueueLength=t?.maxReservationQueueLength??_Te,this.reservationCompletionTimeout=t?.reservationCompletionTimeout??KL,this.started=!1,this.relayFilter=fx(100),this.reserveQueue=new yx({concurrency:t?.reservationConcurrency??DTe,metricName:"libp2p_relay_reservation_queue",metrics:e.metrics}),this.events.addEventListener("connection:close",n=>{[...this.reservations.values()].find(s=>s.connection===n.detail.id)!=null&&this.#t(n.detail.remotePeer).catch(s=>{this.log("could not remove relay %p - %e",n.detail,s)})})}isStarted(){return this.started}start(){this.started=!0}afterStart(){Promise.resolve().then(async()=>{let e=await this.peerStore.all({filters:[t=>t.tags.has(EA)]});this.log("removing tag from %d old relays",e.length),await Promise.all(e.map(async t=>{await this.peerStore.merge(t.id,{tags:{[EA]:void 0}})})),this.log("redialing %d old relays",e.length),await Promise.all(e.map(async t=>this.addRelay(t.id,"discovered"))),this.#r()}).catch(e=>{this.log.error("failed to clean up and redial old relays during afterStart - %e",e)})}stop(){this.reserveQueue.clear(),this.reservations.forEach(({timeout:e})=>{clearTimeout(e)}),this.reservations.clear(),this.started=!1}reserveRelay(){let e=NTe();return this.pendingReservations.push(e),this.#r(),e}async addRelay(e,t){if(this.peerId.equals(e))throw this.log.trace("not trying to use self as relay"),new am("Cannot use self as relay");if(this.reserveQueue.size>this.maxReservationQueueLength)throw new qL("The reservation queue is full");let n=this.reserveQueue.find(e);if(n!=null)return this.log.trace("potential relay peer %p is already in the reservation queue",e),n.join();if(this.relayFilter.has(e.toMultihash().bytes))throw new am("The relay was previously invalid");return this.log.trace("try to reserve relay slot with %p",e),this.reserveQueue.add(async()=>{let o=Date.now();try{let s=this.reservations.get(e);if(s!=null){let f=this.connectionManager.getConnections(e),g=!1;if(f.length===0&&this.log("already have relay reservation with %p but we are no longer connected",e),f.map(y=>y.id).includes(s.connection)&&(this.log("already have relay reservation with %p and the original connection is still open",e),g=!0),g&&$Z(s.reservation.expire)>hft)return this.log("already have relay reservation with %p but we are still connected and it does not expire soon",e),{relay:e,details:s};await this.#t(e)}if(t==="discovered"&&this.pendingReservations.length===0)throw new SA("Not making reservation on discovered relay because we do not need any more relays");let i=AbortSignal.timeout(this.reservationCompletionTimeout);let a=await this.connectionManager.openConnection(e,{signal:i});if(J8.matches(a.remoteAddr))throw new VL("not creating reservation over relayed connection");let c=await this.#e(a,{signal:i}),l=$Z(c.expire);this.log("created reservation on relay peer %p, expiry date is %s",e,new Date(Date.now()+l).toString());let u=Math.min(Math.max(l-pft,mft),Math.pow(2,31)-1),d=setTimeout(()=>{this.log("refresh reservation to relay %p",e),this.addRelay(e,t).catch(async f=>{this.log.error("could not refresh reservation to relay %p - %e",e,f),await this.#t(e)}).catch(f=>{this.log.error("could not remove expired reservation to relay %p - %e",e,f)})},u),h;if(t==="discovered"){let f=this.pendingReservations.pop();if(f==null)throw new SA("Made reservation on relay but did not need any more discovered relays");h={timeout:d,reservation:c,type:t,connection:a.id,id:f}}else h={timeout:d,reservation:c,type:t,connection:a.id};this.reservations.set(e,h),await this.peerStore.merge(e,{tags:{[EA]:{value:1,ttl:l}}}),this.#r();let p={relay:e,details:h};return this.safeDispatchEvent("relay:created-reservation",{detail:p}),p}catch(s){throw t==="discovered"&&s.name==="HadEnoughRelaysError"||this.log.error("could not reserve slot on %p after %dms - %e",e,Date.now()-o,s),(s.name==="DialError"||s.name==="UnsupportedProtocolError")&&this.relayFilter.add(e.toMultihash().bytes),this.#t(e).catch(i=>{this.log.error("could not remove reservation on %p after reserving slot failed - %e",e,i)}),s}},{peerId:e})}hasReservation(e){return this.reservations.has(e)}getReservation(e){return this.reservations.get(e)?.reservation}reservationCount(e){return e==null?this.reservations.size:[...this.reservations.values()].reduce((t,n)=>(n.type===e&&t++,t),0)}cancelReservations(){[...this.reservations.values()].forEach(e=>{clearTimeout(e.timeout)}),this.reservations.clear()}async#e(e,t){t.signal?.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);let n=await e.newStream(Dm,t),s=bA(n).pb(Jf);this.log.trace("send RESERVE to %p",e.remotePeer),await s.write({type:Jf.Type.RESERVE},t);let i;try{this.log.trace("reading response from %p",e.remotePeer),i=await s.read(t)}catch(c){throw n.abort(c),c}finally{n.status!=="closed"&&await n.close(t)}if(this.log.trace("read response %s",i.status),i.status===Zn.OK&&i.reservation!=null){let c=new Set;c.add(e.remoteAddr.toString());for(let l of i.reservation.addrs){let u=Ea(l);u.getComponents().find(d=>d.code===421)==null&&(u=u.encapsulate(`/p2p/${e.remotePeer}`)),u=Ea(u.toString().replace(`/p2p/${e.remotePeer}/p2p/${e.remotePeer}`,`/p2p/${e.remotePeer}`)),c.add(u.toString())}return i.reservation.addrs=[...c].map(l=>Ea(l).bytes),i.reservation}let a=`reservation failed with status ${i.status??"undefined"}`;throw this.log.error(a),new Error(a)}async#t(e){let t=this.reservations.get(e);t!=null&&(this.log("removing relay reservation with %p from local store",e),clearTimeout(t.timeout),this.reservations.delete(e),t.type==="discovered"&&this.pendingReservations.push(t.id),await this.peerStore.merge(e,{tags:{[EA]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:e,details:t}}),this.#r())}#r(){if(this.pendingReservations.length===0){this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),this.safeDispatchEvent("relay:found-enough-relays");return}this.relayFilter=fx(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}};var qZ=class extends gx{stream;init;constructor(e){super({...e,direction:e.stream.direction}),this.init=e,this.stream=e.stream,this.stream.addEventListener("close",t=>{this.onTransportClosed(t.error)}),this.stream.addEventListener("remoteCloseWrite",t=>{this.onRemoteCloseWrite(),this.close().catch(n=>{this.abort(n)})}),this.stream.addEventListener("message",t=>{e.onDataRead?.(t.data),this.onData(t.data)}),this.stream.addEventListener("drain",()=>{this.safeDispatchEvent("drain")})}sendData(e){return this.init.onDataWrite?.(e),{sentBytes:e.byteLength,canSendMore:this.stream.send(e)}}async sendClose(e){await this.stream.close(e)}sendReset(){this.stream.abort(new Error("An error occurred"))}sendPause(){this.stream.pause()}sendResume(){this.stream.resume()}};function jZ(r){return new qZ(r)}var gft=r=>{if(r.peer==null)return!1;try{r.peer.addrs.forEach(Ea)}catch{return!1}return!0},UTe={maxInboundStopStreams:KZ,maxOutboundStopStreams:KZ,stopTimeout:3e4},JL=class{components;discovery;reservationStore;maxInboundStopStreams;maxOutboundStopStreams;started;log;shutdownController;constructor(e,t={}){this.components=e,this.log=e.logger.forComponent("libp2p:circuit-relay:transport"),this.maxInboundStopStreams=t.maxInboundStopStreams??UTe.maxInboundStopStreams,this.maxOutboundStopStreams=t.maxOutboundStopStreams??UTe.maxOutboundStopStreams,this.shutdownController=new AbortController,this.discovery=new XL(e,{filter:t.discoveryFilter??HZ(PTe,RTe)}),this.discovery.addEventListener("relay:discover",n=>{this.reservationStore.addRelay(n.detail,"discovered").catch(o=>{o.name!=="HadEnoughRelaysError"&&o.name!=="RelayQueueFullError"&&this.log.error("could not add discovered relay %p - %e",n.detail,o)})}),this.reservationStore=new ZL(e,t),this.reservationStore.addEventListener("relay:not-enough-relays",()=>{this.discovery?.startDiscovery()}),this.reservationStore.addEventListener("relay:found-enough-relays",()=>{this.discovery?.stopDiscovery()}),this.started=!1,this.onStop=this.onStop.bind(this)}[Symbol.toStringTag]="@libp2p/circuit-relay-v2-transport";[B8]=["@libp2p/transport","@libp2p/circuit-relay-v2-transport"];get[ACe](){return this.discovery!=null?["@libp2p/identify"]:[]}[M8]=!0;isStarted(){return this.started}async start(){this.shutdownController=new AbortController,this.shutdownController.signal,await this.components.registrar.handle(FZ,this.onStop,{maxInboundStreams:this.maxInboundStopStreams,maxOutboundStreams:this.maxOutboundStopStreams,runOnLimitedConnection:!0}),await ECe(this.discovery,this.reservationStore),this.started=!0}async stop(){this.shutdownController.abort(),await SCe(this.discovery,this.reservationStore),await this.components.registrar.unhandle(FZ),this.started=!1}async dial(e,t){let n=e.toString().split("/p2p-circuit"),o=Ea(n[0]),s=Ea(n[n.length-1]),i=o.getComponents().find(p=>p.code===421)?.value,a=s.getComponents().find(p=>p.code===421)?.value;if(i==null||a==null){let p=`ircuit relay dial to ${e.toString()} failed as address did not have both relay and destination PeerIDs`;throw this.log.error(`c${p}`),new _8(`C${p}`)}let c=_Z(i),l=_Z(a),d=this.components.connectionManager.getConnections(c)[0];d==null?(await this.components.peerStore.merge(c,{multiaddrs:[o]}),t.onProgress?.(new Fc("circuit-relay:open-connection")),d=await this.components.connectionManager.openConnection(c,t)):t.onProgress?.(new Fc("circuit-relay:reuse-connection"));let h;try{t.onProgress?.(new Fc("circuit-relay:open-hop-stream")),h=await d.newStream(Dm,t);let p=bA(h).pb(Jf);t.onProgress?.(new Fc("circuit-relay:write-connect-message")),await p.write({type:Jf.Type.CONNECT,peer:{id:l.toMultihash().bytes,addrs:[Ea(s).bytes]}},t),t.onProgress?.(new Fc("circuit-relay:read-connect-response"));let f=await p.read(t);if(f.status!==Zn.OK)throw new D8(`failed to connect via relay with status ${f?.status?.toString()??"undefined"}`);let g=new CA(f.limit),y=jZ({stream:p.unwrap().unwrap(),remoteAddr:e,localAddr:o.encapsulate(`/p2p-circuit/p2p/${this.components.peerId.toString()}`),onDataRead:g.onData,onDataWrite:g.onData,log:h.log.newScope("circuit-relay:connection")}),m=await this.components.upgrader.upgradeOutbound(y,{...t,limits:g.getLimits()});return m.log("outbound relayed connection established to %p with limits %o, over connection %s",m.remotePeer,f.limit??"none",d.id),m}catch(p){throw this.log.error("circuit relay dial to destination %p via relay %p failed - %e",l,c,p),h?.abort(p),p}}createListener(e){return BTe({peerId:this.components.peerId,connectionManager:this.components.connectionManager,addressManager:this.components.addressManager,reservationStore:this.reservationStore,logger:this.components.logger})}listenFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>jL.exactMatch(t)||GL.exactMatch(t))}dialFilter(e){return e=Array.isArray(e)?e:[e],e.filter(t=>J8.exactMatch(t))}async onStop(e,t){let n=this.components.upgrader.createInboundAbortSignal(this.shutdownController.signal);try{if(!this.reservationStore.hasReservation(t.remotePeer))try{this.log("dialed via relay we did not have a reservation on, start listening on that relay address"),await this.components.transportManager.listen([t.remoteAddr.encapsulate("/p2p-circuit")])}catch(d){this.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on - %e",d)}let o=bA(e).pb($c),s=await o.read({signal:n});if(this.log("new circuit relay v2 stop stream from %p with type %s",t.remotePeer,s.type),s?.type===void 0){this.log.error("type was missing from circuit v2 stop protocol request from %s",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(s.type!==$c.Type.CONNECT){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.UNEXPECTED_MESSAGE},{signal:n}),await e.close({signal:n});return}if(!gft(s)){this.log.error("invalid stop connect request via peer %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.MALFORMED_MESSAGE},{signal:n}),await e.close({signal:n});return}let i=BL(Hf(s.peer.id));if(await this.components.connectionGater.denyInboundRelayedConnection?.(t.remotePeer,i)===!0){this.log.error("connection gater denied inbound relayed connection from %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.PERMISSION_DENIED},{signal:n}),await e.close({signal:n});return}this.log.trace("sending success response to %p",t.remotePeer),await o.write({type:$c.Type.STATUS,status:Zn.OK},{signal:n});let a=new CA(s.limit),c=t.remoteAddr.encapsulate(`/p2p-circuit/p2p/${i.toString()}`),l=this.components.addressManager.getAddresses()[0],u=jZ({stream:o.unwrap().unwrap(),remoteAddr:c,localAddr:l,onDataRead:a.onData,onDataWrite:a.onData,log:e.log.newScope("circuit-relay:connection")});await this.components.upgrader.upgradeInbound(u,{limits:a.getLimits(),signal:n}),u.log("inbound relayed connection established to %p with limits %o, over connection %s",i,s.limit??"none",t.id)}finally{n?.clear()}}};function FTe(r={}){return e=>new JL(e,r)}var YZ=(r,e)=>e.some(t=>r instanceof t),KTe,zTe;function yft(){return KTe||(KTe=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bft(){return zTe||(zTe=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var XZ=new WeakMap,GZ=new WeakMap,QL=new WeakMap;function wft(r){let e=new Promise((t,n)=>{let o=()=>{r.removeEventListener("success",s),r.removeEventListener("error",i)},s=()=>{t(_m(r.result)),o()},i=()=>{n(r.error),o()};r.addEventListener("success",s),r.addEventListener("error",i)});return QL.set(e,r),e}function xft(r){if(XZ.has(r))return;let e=new Promise((t,n)=>{let o=()=>{r.removeEventListener("complete",s),r.removeEventListener("error",i),r.removeEventListener("abort",i)},s=()=>{t(),o()},i=()=>{n(r.error||new DOMException("AbortError","AbortError")),o()};r.addEventListener("complete",s),r.addEventListener("error",i),r.addEventListener("abort",i)});XZ.set(r,e)}var ZZ={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return XZ.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return _m(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};function qTe(r){ZZ=r(ZZ)}function vft(r){return bft().includes(r)?function(...e){return r.apply(JZ(this),e),_m(this.request)}:function(...e){return _m(r.apply(JZ(this),e))}}function Eft(r){return typeof r=="function"?vft(r):(r instanceof IDBTransaction&&xft(r),YZ(r,yft())?new Proxy(r,ZZ):r)}function _m(r){if(r instanceof IDBRequest)return wft(r);if(GZ.has(r))return GZ.get(r);let e=Eft(r);return e!==r&&(GZ.set(r,e),QL.set(e,r)),e}var JZ=r=>QL.get(r);function jTe(r,e,{blocked:t,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(r,e),a=_m(i);return n&&i.addEventListener("upgradeneeded",c=>{n(_m(i.result),c.oldVersion,c.newVersion,_m(i.transaction),c)}),t&&i.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}var Sft=["get","getKey","getAll","getAllKeys","count"],Cft=["put","add","delete","clear"],WZ=new Map;function $Te(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(WZ.get(e))return WZ.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,o=Cft.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Sft.includes(t)))return;let s=async function(i,...a){let c=this.transaction(i,o?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),o&&c.done]))[0]};return WZ.set(e,s),s}qTe(r=>({...r,get:(e,t,n)=>$Te(e,t)||r.get(e,t,n),has:(e,t)=>!!$Te(e,t)||r.has(e,t)}));var Aft=["continue","continuePrimaryKey","advance"],HTe={},QZ=new WeakMap,GTe=new WeakMap,Ift={get(r,e){if(!Aft.includes(e))return r[e];let t=HTe[e];return t||(t=HTe[e]=function(...n){QZ.set(this,GTe.get(this)[e](...n))}),t}};async function*Tft(...r){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...r)),!e)return;e=e;let t=new Proxy(e,Ift);for(GTe.set(t,e),QL.set(t,JZ(e));e;)yield t,e=await(QZ.get(t)||e.continue()),QZ.delete(t)}function VTe(r,e){return e===Symbol.asyncIterator&&YZ(r,[IDBIndex,IDBObjectStore,IDBCursor])||e==="iterate"&&YZ(r,[IDBIndex,IDBObjectStore])}qTe(r=>({...r,get(e,t,n){return VTe(e,t)?Tft:r.get(e,t,n)},has(e,t){return VTe(e,t)||r.has(e,t)}}));var kft="optimystic",Dft=2;async function WTe(r=kft,e=Dft){return jTe(r,e,{upgrade(t){t.objectStoreNames.contains("metadata")||t.createObjectStore("metadata"),t.objectStoreNames.contains("revisions")||t.createObjectStore("revisions"),t.objectStoreNames.contains("pending")||t.createObjectStore("pending"),t.objectStoreNames.contains("transactions")||t.createObjectStore("transactions"),t.objectStoreNames.contains("proofs")||t.createObjectStore("proofs"),t.objectStoreNames.contains("materialized")||t.createObjectStore("materialized"),t.objectStoreNames.contains("kv")||t.createObjectStore("kv")}})}var eJ=Ri(QTe(),1);var $ft="optimystic:db-p2p-storage-web";vd("db-p2p-storage-web",eJ.default);function e6e(r){return(0,eJ.default)(`${$ft}:${r}`)}var Hft=e6e("storage:indexeddb"),tJ=class{db;identity;constructor(e){this.db=e,this.identity=Rge("idb-handle",e)}storeIdentity(){return this.identity}async getMetadata(e){return this.db.get("metadata",e)}async putMetadata(e,t){await this.db.put("metadata",t,e)}async getRevision(e,t){return this.db.get("revisions",[e,t])}async putRevision(e,t,n){await this.db.put("revisions",n,[e,t])}async*rangeRevisions(e,t,n,o){let s=IDBKeyRange.bound([e,t],[e,n]),i=this.db.transaction("revisions","readonly"),a=i.objectStore("revisions"),c=[],l=await a.openCursor(s,o?"prev":"next");for(;l;)c.push([l.key[1],l.value]),l=await l.continue();await i.done;for(let u of c)yield u}async getPending(e,t){return this.db.get("pending",[e,t])}async putPending(e,t,n){await this.db.put("pending",n,[e,t])}async deletePending(e,t){await this.db.delete("pending",[e,t])}async*listPendingActionIds(e){let t=IDBKeyRange.bound([e],[e,[]]),n=this.db.transaction("pending","readonly"),o=n.objectStore("pending"),s=[],i=await o.openKeyCursor(t);for(;i;)s.push(i.key[1]),i=await i.continue();await n.done;for(let a of s)yield a}async getTransaction(e,t){return this.db.get("transactions",[e,t])}async putTransaction(e,t,n){await this.db.put("transactions",n,[e,t])}async getProof(e,t){return this.db.get("proofs",[e,t])}async putProof(e,t,n){await this.db.put("proofs",n,[e,t])}async getMaterialized(e,t){return this.db.get("materialized",[e,t])}async putMaterialized(e,t,n){await this.db.put("materialized",n,[e,t])}async deleteMaterialized(e,t){await this.db.delete("materialized",[e,t])}async promote(e,t){let n=[e,t],o=this.db.transaction(["pending","transactions"],"readwrite"),s=o.objectStore("pending"),i=o.objectStore("transactions"),a=await s.get(n);if(!a)throw await o.done.catch(()=>{}),new Error(`Pending action ${t} not found for block ${e}`);await i.put(a,n),await s.delete(n),await o.done}async*listBlockIds(){let e=await this.db.getAllKeys("metadata");for(let t of e)yield t}async approximateBytesUsed(){try{return(await navigator.storage?.estimate?.())?.usage??0}catch(e){return Hft("navigator.storage.estimate() failed: %o",e),0}}},r3=class extends gf{constructor(e){super(new tJ(e))}};var $J=Ri(s6e(),1);import{QuereusError as Aa,StatusCode as Ia,builtinCollationResolver as _pt,BINARY_COLLATION as Ppt,compareSqlValues as Rpt,VirtualTable as Q6e,ConflictResolution as Bm,buildCheckConstraintSchema as Lpt,collectTableConstraintNames as Mpt,PhysicalType as Bpt,TEXT_TYPE as Opt,buildColumnIndexMap as eke,inferType as Npt,getTypeOrDefault as $6e,ConstraintError as Upt}from"@quereus/quereus";function rht(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function rJ(r,e,t=""){let n=rht(r),o=r?.length,s=e!==void 0;if(!n||s&&o!==e){let i=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function nJ(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 i6e(r,e){rJ(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function IA(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function s3(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function Sa(r,e){return r<<32-e|r>>>e}function a6e(r,e={}){let t=(o,s)=>r(s).update(o).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=o=>r(o),Object.assign(t,e),Object.freeze(t)}function i3(r=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}var c6e=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});Uo();Be();var oJ=class{async connect(e,t){return{}}},sJ=class{nodes;responsibilityK;failures;ring;constructor(e,t,n={}){this.nodes=e,this.responsibilityK=t,this.failures=n}async findCoordinator(e,t){let n=new Set((t?.excludedPeers??[]).map(s=>s.toString())),o=(await this.nearest(e,this.nodes.length)).find(s=>!n.has(s.peerId.toString()));if(!o)throw new Error("No coordinator available for key (all candidates excluded)");return o.peerId}async findCluster(e){if(this.failures.findClusterFails)return{};let t={};for(let n of await this.nearest(e,this.responsibilityK))t[n.peerId.toString()]={multiaddrs:["/ip4/127.0.0.1/tcp/8000"],publicKey:z(n.peerId.publicKey.raw,"base64url")};return t}async nearest(e,t){let{store:n,byId:o}=await this.ringStore();return Tp(n,await Jt(e),Math.min(t,o.size)).map(i=>o.get(i))}ringStore(){if(this.ring?.size!==this.nodes.length){let e=[...this.nodes];this.ring={size:e.length,ready:(async()=>{let t=new tf,n=new Map;for(let o of e)t.upsert(o.peerId.toString(),await Or(o.peerId)),n.set(o.peerId.toString(),o);return{store:t,byId:n}})()}}return this.ring.ready}},nht=(r,e,t)=>async(n,o)=>{if(n===e||t.silentPeers?.has(n))return;let s=r.find(i=>i.peerId.toString()===n);if(s)return await q6(s.storageRepo,o)};function oht(r){return X6({clusterSize:r.clusterSize,clusterPolicy:{...r.clusterPolicy,superMajorityThreshold:r.clusterPolicy?.superMajorityThreshold??r.superMajorityThreshold,allowDownsize:r.clusterPolicy?.allowDownsize??r.allowClusterDownsize}})}function sht(r,e){let t=new Uint8Array(32),n=new DataView(t.buffer);return n.setUint32(0,r),n.setUint32(4,e),t}async function l6e(r,e){let t={},n=oht(e),o=await Promise.all(Array.from({length:r},async(m,w)=>{let b=e.keySeed===void 0?await L6("Ed25519"):await ble("Ed25519",sht(e.keySeed,w));return{peerId:RE(b),privateKey:b}})),s=[],i=new oJ,a=new Map,c=new Map,l=new Map,u=new sJ(s,e.responsibilityK,t),d=e.wrapKeyNetwork?e.wrapKeyNetwork(u):u,h=m=>{let w=m.toString();return{findCoordinator:(b,x)=>d.findCoordinator(b,x),async findCluster(b){let x=await d.findCluster(b),S=t.partitionSides?.find(T=>T.has(w));if(S)for(let T of Object.keys(x))S.has(T)||delete x[T];return x}}},p=(m,w)=>{let{peerId:b,privateKey:x}=m,{rawStorage:S,index:T}=c.get(b.toString()),A=new Dl(R=>new mc(R,S)),v=nht(s,b.toString(),t),C=W6({selfPeerId:b.toString(),fetchArchive:async(R,k)=>w.stopped?void 0:await v(R,k),saveReplicatedBlock:(R,k,I,E)=>A.saveReplicatedBlock(R,k,I,E),simpleMajorityThreshold:n.simpleMajorityThreshold,superMajorityThreshold:n.superMajorityThreshold,repairCorroborationClusterSize:n.repairCorroborationClusterSize,onBlockHolders:e.onBlockHolders&&(R=>e.onBlockHolders(m,R))});a.set(b.toString(),C);let P=m.keyNetwork,F=e.deriveExpectedCluster?R=>e.deriveExpectedCluster(m,R):async R=>({peers:await P.findCluster(He(R))??{},confidence:e.meshConfidence?.(m)??1});m.storageRepo=A,m.clusterMember=J6({storageRepo:A,peerNetwork:i,peerId:b,privateKey:x,consensusConfig:n,reconcileBlock:C,deriveExpectedCluster:F,validator:e.validatorFactory?.(T,b),onBlockHolders:e.onBlockHolders&&(R=>e.onBlockHolders(m,R))})},f=m=>{let w=s.find(b=>b.peerId.equals(m));if(!w)throw new Error(`Unknown peer: ${m.toString()}`);return{async update(b){if(t.onClusterDelivery?.(m.toString(),b),t.failingPeers?.has(m.toString()))throw new Error(`Peer ${m.toString()} is unreachable`);return w.clusterMember.update(b)}}},g=(m,w)=>{let b=()=>new Error(`${m.peerId.toString()} was restarted; this instance is stopped`),x=async(A,v,C)=>{if(w.stopped)throw b();if(t.silentPeers?.has(A.toString()))throw new Error(`Peer ${A.toString()} is silent`);let P=s.find(I=>I.peerId.equals(A));if(!P)return;let R=(await P.storageRepo.get({blockIds:[v],context:C},{skipClusterFetch:!0}))[v]?.state?.latest;if(!R)return;let k=await sp(P.storageRepo,v,R);return k?{...R,proof:k}:R},S=m.keyNetwork,T=WD(S,A=>{let v=f(A);return{async update(C){if(w.stopped)throw b();return await v.update(C)}}},{...n});m.coordinatorRepo=T({storageRepo:m.storageRepo,localCluster:m.clusterMember,localPeerId:m.peerId,clusterLatestCallback:x,acquireBlockFromCohort:a.get(m.peerId.toString()),onBlockHolders:e.onBlockHolders&&(A=>e.onBlockHolders(m,A))})};for(let[m,{peerId:w,privateKey:b}]of o.entries()){let x=w.toString();c.set(x,{rawStorage:e.rawStorageFactory?e.rawStorageFactory(m):new Vs,index:m});let S={stopped:!1};l.set(x,S);let T={peerId:w,privateKey:b,keyNetwork:h(w),storageRepo:void 0,clusterMember:void 0,coordinatorRepo:void 0};p(T,S),s.push(T)}for(let m of s)g(m,l.get(m.peerId.toString()));return{nodes:s,failures:t,keyNetwork:d,restart:m=>{let w=m.peerId.toString();if(!s.includes(m))throw new Error(`restart: ${w} is not a node of this mesh`);l.get(w).stopped=!0,m.clusterMember.dispose();let b={stopped:!1};l.set(w,b),p(m,b),g(m,b)}}}var u6e=(r,e={})=>iht(r,e,void 0);function iht(r,e,t){let n=new Map;for(let o of r.nodes){let s=o.coordinatorRepo;n.set(o.peerId.toString(),e.wrapRepo?e.wrapRepo(s,o):s)}return new Mg({timeoutMs:e.timeoutMs??5e3,abortOrCancelTimeoutMs:e.abortOrCancelTimeoutMs??5e3,keyNetwork:r.keyNetwork,getRepo:o=>{let s=n.get(o.toString());if(!s)throw new Error(`Unknown peer ${o.toString()}`);return s},localPeerId:t?.peerId})}var NJ=Ri(m6e(),1);var uJ={};W(uJ,{base10:()=>Iht});var j$r=new Uint8Array(0);function g6e(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 Zu(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return Mm(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return Mm(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function y6e(r){return new TextEncoder().encode(r)}function b6e(r){return new TextDecoder().decode(r)}function wht(r){return r?.buffer instanceof ArrayBuffer}function Mm(r){return wht(r)?r:r.slice()}function xht(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 o=0;o<r.length;o++){var s=r.charAt(o),i=s.charCodeAt(0);if(t[i]!==255)throw new TypeError(s+" is ambiguous");t[i]=o}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,y=0,m=0,w=f.length;m!==w&&f[m]===0;)m++,g++;for(var b=(w-m)*u+1>>>0,x=new Uint8Array(b);m!==w;){for(var S=f[m],T=0,A=b-1;(S!==0||T<y)&&A!==-1;A--,T++)S+=256*x[A]>>>0,x[A]=S%a>>>0,S=S/a>>>0;if(S!==0)throw new Error("Non-zero carry");y=T,m++}for(var v=b-y;v!==b&&x[v]===0;)v++;for(var C=c.repeat(g);v<b;++v)C+=r.charAt(x[v]);return C}function h(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var y=0,m=0;f[g]===c;)y++,g++;for(var w=(f.length-g)*l+1>>>0,b=new Uint8Array(w);f[g];){var x=t[f.charCodeAt(g)];if(x===255)return;for(var S=0,T=w-1;(x!==0||S<m)&&T!==-1;T--,S++)x+=a*b[T]>>>0,b[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");m=S,g++}if(f[g]!==" "){for(var A=w-m;A!==w&&b[A]===0;)A++;for(var v=new Uint8Array(y+(w-A)),C=y;A!==w;)v[C++]=b[A++];return v}}}function p(f){var g=h(f);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var vht=xht,Eht=vht,x6e=Eht;var iJ=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")}},aJ=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,t,n){this.name=e,this.prefix=t;let o=t.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,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 v6e(this,e)}},cJ=class{decoders;constructor(e){this.decoders=e}or(e){return v6e(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 v6e(r,e){return new cJ({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}var lJ=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,t,n,o){this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=o,this.encoder=new iJ(e,t,n),this.decoder=new aJ(e,t,o)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Px({name:r,prefix:e,encode:t,decode:n}){return new lJ(r,e,t,n)}function Qf({name:r,prefix:e,alphabet:t}){let{encode:n,decode:o}=x6e(t,r);return Px({prefix:e,name:r,encode:n,decode:s=>Zu(o(s))})}function Sht(r,e,t,n){let o=r.length;for(;r[o-1]==="=";)--o;let s=new Uint8Array(o*t/8|0),i=0,a=0,c=0;for(let l=0;l<o;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,i+=t,i>=8&&(i-=8,s[c++]=255&a>>i)}if(i>=t||(255&a<<8-i)!==0)throw new SyntaxError("Unexpected end of data");return s}function Cht(r,e,t){let n=e[e.length-1]==="=",o=(1<<t)-1,s="",i=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],i+=8;i>t;)i-=t,s+=e[o&a>>i];if(i!==0&&(s+=e[o&a<<t-i]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Aht(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function vr({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let o=Aht(n);return Px({prefix:e,name:r,encode(s){return Cht(s,n,t)},decode(s){return Sht(s,o,t,r)}})}var Iht=Qf({prefix:"9",name:"base10",alphabet:"0123456789"});var dJ={};W(dJ,{base16:()=>Tht,base16upper:()=>kht});var Tht=vr({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),kht=vr({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var fJ={};W(fJ,{base2:()=>Dht});var Dht=vr({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var hJ={};W(hJ,{base256emoji:()=>Mht});var E6e=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}"),_ht=E6e.reduce((r,e,t)=>(r[t]=e,r),[]),Pht=E6e.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);function Rht(r){return r.reduce((e,t)=>(e+=_ht[t],e),"")}function Lht(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let o=Pht[n];if(o==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(o)}return new Uint8Array(e)}var Mht=Px({prefix:"\u{1F680}",name:"base256emoji",encode:Rht,decode:Lht});var pJ={};W(pJ,{base32:()=>Rx,base32hex:()=>Uht,base32hexpad:()=>Kht,base32hexpadupper:()=>zht,base32hexupper:()=>Fht,base32pad:()=>Oht,base32padupper:()=>Nht,base32upper:()=>Bht,base32z:()=>$ht});var Rx=vr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bht=vr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Oht=vr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nht=vr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Uht=vr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Fht=vr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kht=vr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zht=vr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),$ht=vr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var mJ={};W(mJ,{base36:()=>TA,base36upper:()=>Hht});var TA=Qf({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Hht=Qf({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gJ={};W(gJ,{base58btc:()=>Hc,base58flickr:()=>Vht});var Hc=Qf({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vht=Qf({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var yJ={};W(yJ,{base64:()=>qht,base64pad:()=>jht,base64url:()=>Ght,base64urlpad:()=>Wht});var qht=vr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jht=vr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ght=vr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Wht=vr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var bJ={};W(bJ,{base8:()=>Yht});var Yht=vr({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var wJ={};W(wJ,{identity:()=>Xht});var Xht=Px({prefix:"\0",name:"identity",encode:r=>b6e(r),decode:r=>y6e(r)});var cHr=new TextEncoder,lHr=new TextDecoder;var vJ={};W(vJ,{identity:()=>wpt});var Qht=A6e,S6e=128,ept=127,tpt=~ept,rpt=Math.pow(2,31);function A6e(r,e,t){e=e||[],t=t||0;for(var n=t;r>=rpt;)e[t++]=r&255|S6e,r/=128;for(;r&tpt;)e[t++]=r&255|S6e,r>>>=7;return e[t]=r|0,A6e.bytes=t-n+1,e}var npt=xJ,opt=128,C6e=127;function xJ(r,n){var t=0,n=n||0,o=0,s=n,i,a=r.length;do{if(s>=a)throw xJ.bytes=0,new RangeError("Could not decode varint");i=r[s++],t+=o<28?(i&C6e)<<o:(i&C6e)*Math.pow(2,o),o+=7}while(i>=opt);return xJ.bytes=s-n,t}var spt=Math.pow(2,7),ipt=Math.pow(2,14),apt=Math.pow(2,21),cpt=Math.pow(2,28),lpt=Math.pow(2,35),upt=Math.pow(2,42),dpt=Math.pow(2,49),fpt=Math.pow(2,56),hpt=Math.pow(2,63),ppt=function(r){return r<spt?1:r<ipt?2:r<apt?3:r<cpt?4:r<lpt?5:r<upt?6:r<dpt?7:r<fpt?8:r<hpt?9:10},mpt={encode:Qht,decode:npt,encodingLength:ppt},gpt=mpt,kA=gpt;function DA(r,e=0){return[kA.decode(r,e),kA.decode.bytes]}function Lx(r,e,t=0){return kA.encode(r,e,t),e}function Mx(r){return kA.encodingLength(r)}function Ox(r,e){let t=e.byteLength,n=Mx(r),o=n+Mx(t),s=new Uint8Array(o+t);return Lx(r,s,0),Lx(t,s,n),s.set(e,o),new Bx(r,t,e,s)}function I6e(r){let e=Zu(r),[t,n]=DA(e),[o,s]=DA(e.subarray(n)),i=e.subarray(n+s);if(i.byteLength!==o)throw new Error("Incorrect length");return new Bx(t,o,i,e)}function T6e(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&g6e(r.bytes,t.bytes)}}var Bx=class{code;size;digest;bytes;constructor(e,t,n,o){this.code=e,this.size=t,this.digest=Mm(n),this.bytes=Mm(o)}};var k6e=0,ypt="identity",D6e=Zu;function bpt(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 Ox(k6e,D6e(r))}var wpt={code:k6e,name:ypt,encode:D6e,digest:bpt};var CJ={};W(CJ,{sha256:()=>vpt,sha512:()=>Ept});var xpt=20;function SJ({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:o}){return new EJ(r,e,t,n,o)}var EJ=class{name;code;encode;minDigestLength;maxDigestLength;constructor(e,t,n,o,s){this.name=e,this.code=t,this.encode=n,this.minDigestLength=o??xpt,this.maxDigestLength=s}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?_6e(n,this.code,t?.truncate):n.then(o=>_6e(o,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}};function _6e(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 Ox(e,r)}function R6e(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var vpt=SJ({name:"sha2-256",code:18,encode:R6e("SHA-256")}),Ept=SJ({name:"sha2-512",code:19,encode:R6e("SHA-512")});function L6e(r,e){let{bytes:t,version:n}=r;return n===0?Cpt(t,AJ(r),e??Hc.encoder):Apt(t,AJ(r),e??Rx.encoder)}var M6e=new WeakMap;function AJ(r){let e=M6e.get(r);if(e==null){let t=new Map;return M6e.set(r,t),t}return e}var u3=class r{code;version;multihash;bytes;"/";constructor(e,t,n,o){this.code=t,this.version=e,this.multihash=n,this.bytes=Mm(o),this["/"]=this.bytes}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!==PA)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ipt)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=Ox(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&&T6e(e.multihash,n.multihash)}toString(e){return L6e(this,e)}toJSON(){return{"/":L6e(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:o,multihash:s,bytes:i}=t;return new r(n,o,s,i??B6e(n,o,s.bytes))}else if(t[Tpt]===!0){let{version:n,multihash:o,code:s}=t,i=I6e(o);return r.create(n,s,i)}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!==PA)throw new Error(`Version 0 CID must use dag-pb (code: ${PA}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let o=B6e(e,t,n.bytes);return new r(e,t,n,o)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,PA,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,o=Zu(e.subarray(n,n+t.multihashSize));if(o.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=o.subarray(t.multihashSize-t.digestSize),i=new Bx(t.multihashCode,t.digestSize,s,o);return[t.version===0?r.createV0(i):r.createV1(t.codec,i),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=DA(e.subarray(t));return t+=h,d},o=n(),s=PA;if(o===18?(o=0,t=0):s=n(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let i=t,a=n(),c=n(),l=t+c,u=l-i;return{version:o,codec:s,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,o]=Spt(e,t),s=r.decode(o);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return AJ(s).set(n,e),s}};function Spt(r,e){switch(r[0]){case"Q":{let t=e??Hc;return[Hc.prefix,t.decode(`${Hc.prefix}${r}`)]}case Hc.prefix:{let t=e??Hc;return[Hc.prefix,t.decode(r)]}case Rx.prefix:{let t=e??Rx;return[Rx.prefix,t.decode(r)]}case TA.prefix:{let t=e??TA;return[TA.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 Cpt(r,e,t){let{prefix:n}=t;if(n!==Hc.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let o=e.get(n);if(o==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return o}function Apt(r,e,t){let{prefix:n}=t,o=e.get(n);if(o==null){let s=t.encode(r);return e.set(n,s),s}else return o}var PA=112,Ipt=18;function B6e(r,e,t){let n=Mx(r),o=n+Mx(e),s=new Uint8Array(o+t.byteLength);return Lx(r,s,0),Lx(e,s,n),s.set(t,o),s}var Tpt=Symbol.for("@ipld/js-cid/CID");var IJ={...wJ,...fJ,...bJ,...uJ,...dJ,...pJ,...mJ,...gJ,...yJ,...hJ},PHr={...CJ,...vJ};function O6e(r=0){return new Uint8Array(r)}function U6e(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var N6e=U6e("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),TJ=U6e("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=O6e(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),kpt={utf8:N6e,"utf-8":N6e,hex:IJ.base16,latin1:TJ,ascii:TJ,binary:TJ,...IJ},d3=kpt;function RA(r,e="utf8"){let t=d3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.encoder.encode(r).substring(1)}function F6e(r,e,t){return r&e^~r&t}function K6e(r,e,t){return r&e^r&t^e&t}var f3=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,o){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=s3(this.buffer)}update(e){nJ(this),rJ(e);let{view:t,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=s3(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){nJ(this),i6e(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;t[i++]=128,IA(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let d=i;d<o;d++)t[d]=0;n.setBigUint64(o-8,BigInt(this.length*8),s),this.process(n,0);let a=s3(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must 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 d=0;d<l;d++)a.setUint32(4*d,u[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Ju=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Dpt=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]),eh=new Uint32Array(64),kJ=class extends f3{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,t,n,o,s,i,a,c]}set(e,t,n,o,s,i,a,c){this.A=e|0,this.B=t|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,t){for(let d=0;d<16;d++,t+=4)eh[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=eh[d-15],p=eh[d-2],f=Sa(h,7)^Sa(h,18)^h>>>3,g=Sa(p,17)^Sa(p,19)^p>>>10;eh[d]=g+eh[d-7]+f+eh[d-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let h=Sa(a,6)^Sa(a,11)^Sa(a,25),p=u+h+F6e(a,c,l)+Dpt[d]+eh[d]|0,g=(Sa(n,2)^Sa(n,13)^Sa(n,22))+K6e(n,o,s)|0;u=l,l=c,c=a,a=i+p|0,i=s,s=o,o=n,n=p+g|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,o,s,i,a,c,l,u)}roundClean(){IA(eh)}destroy(){this.set(0,0,0,0,0,0,0,0),IA(this.buffer)}},DJ=class extends kJ{A=Ju[0]|0;B=Ju[1]|0;C=Ju[2]|0;D=Ju[3]|0;E=Ju[4]|0;F=Ju[5]|0;G=Ju[6]|0;H=Ju[7]|0;constructor(){super(32)}};var z6e=a6e(()=>new DJ,c6e(1));function _J(r,e="utf8"){let t=d3[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Fpt="optimystic:quereus-plugin";vd("quereus-plugin",NJ.default);function b3(r){return(0,NJ.default)(`${Fpt}:${r}`)}function tke(r,e){return`${r}@${e.replace(/[\s%@,]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)}`}var H6e=b3("collection-factory");function Kpt(){return V(i3(4))}var zpt=class{nodeTagValue=Kpt();transactors=new Map;libp2pNodes=new Map;customTransactorCtors=new Map;customKeyNetworkCtors=new Map;readCacheLeases=[];async createOrGetCollection(r,e){let t=this.getCachedCollection(r,e);if(t)return t;let{transactor:n,collectionId:o,keyExtractor:s,compare:i}=await this.resolveTreeArgs(r),a=await Bv.createOrOpen(n,o,s,i);return this.cacheCollection(r,e,a),a}async getCollection(r,e){let t=this.getCachedCollection(r,e);if(t)return t;let{transactor:n,collectionId:o,keyExtractor:s,compare:i}=await this.resolveTreeArgs(r),a=await Bv.open(n,o,s,i);if(a)return this.cacheCollection(r,e,a),a}async resolveTreeArgs(r){let e=await this.getOrCreateTransactor(r),t=this.parseCollectionId(r.collectionUri);return{transactor:e,collectionId:t,keyExtractor:s=>this.extractKeyFromEntry(s),compare:(s,i)=>s<i?-1:s>i?1:0}}getCachedCollection(r,e){let t=this.getCollectionKey(r);return e?.isActive?e.collections.get(t):void 0}cacheCollection(r,e,t){e?.isActive&&e.collections.set(this.getCollectionKey(r),t)}async createTransactor(r){switch(r.transactor){case"network":return await this.createNetworkTransactor(r);case"local":return await this.createLocalTransactor(r);case"test":return await this.createTestTransactor();case"mesh-test":return await this.createMeshTestTransactor();default:return await this.createCustomTransactor(r.transactor)}}async getOrCreateTransactor(r){let e=this.getTransactorKey(r);if(this.transactors.has(e))return this.transactors.get(e);let t=await this.createTransactor(r);return this.transactors.set(e,t),t}async subscribeToCollectionChanges(r,e,t){let n=await this.getOrCreateTransactor(r);return wne(n)?n.onCollectionChange(e,t):(H6e(`[optimystic] transactor '${r.transactor}' does not support change notifications; reactive watch is a no-op for collection '${e}'`),()=>{})}async createNetworkTransactor(r){var e,t,n,o;let s=this.getNodeKey(r),i=this.libp2pNodes.get(s);if(!i){let p=await S8({port:((e=r.libp2pOptions)==null?void 0:e.port)??0,networkName:((t=r.libp2pOptions)==null?void 0:t.networkName)??"optimystic",bootstrapNodes:((n=r.libp2pOptions)==null?void 0:n.bootstrapNodes)??[],fretProfile:"edge",clusterSize:1,clusterPolicy:{allowDownsize:!0,sizeTolerance:1},arachnode:{enableRingZulu:!0}}),f=p.coordinatedRepo,g=p.blockChangeNotifier;i={node:p,coordinatedRepo:f,blockChangeNotifier:g},this.libp2pNodes.set(s,i)}let{node:a,coordinatedRepo:c,blockChangeNotifier:l}=i,u=`/optimystic/${((o=r.libp2pOptions)==null?void 0:o.networkName)??"optimystic"}`,d=this.resolveKeyNetwork(r.keyNetwork,a,u),h=p=>p.toString()===a.peerId.toString()?c:qD.create(p,d,u);return new Mg({timeoutMs:3e4,abortOrCancelTimeoutMs:5e3,dialTimeoutMs:3e3,keyNetwork:d,getRepo:h,localChangeNotifier:l,localPeerId:a.peerId})}async createLocalTransactor(r){var e;let{storage:t,lease:n}=r_(((e=r.rawStorageFactory)==null?void 0:e.call(r))??new Vs,"quereus:local");n&&this.readCacheLeases.push(n);let o=new Dl(i=>new mc(i,t));return{async get(i){return await o.get(i)},async getStatus(i){throw new Error("getStatus not implemented in local transactor")},async pend(i){return await o.pend(i)},async commit(i){return await o.commit(i)},async cancel(i){return await o.cancel(i)},onCollectionChange:o.onCollectionChange.bind(o)}}async createTestTransactor(){let r=new Vs,e=new Dl(n=>new mc(n,r));return{async get(n){return await e.get(n)},async getStatus(n){throw new Error("getStatus not implemented in test transactor")},async pend(n){return await e.pend(n)},async commit(n){return await e.commit(n)},async cancel(n){return await e.cancel(n)},onCollectionChange:e.onCollectionChange.bind(e)}}async createMeshTestTransactor(){let r=await l6e(1,{responsibilityK:1,clusterSize:1,superMajorityThreshold:.51});return u6e(r)}async createCustomTransactor(r){let e=this.customTransactorCtors.get(r);if(!e)throw new Error(`Custom transactor '${r}' not found. Register it first using collectionFactory.registerCustomTransactor().`);return new e}resolveKeyNetwork(r,e,t){switch(r){case"libp2p":{let n=e.keyNetwork;return n||new Qb(e,uS,void 0,void 0,void 0,void 0,t)}default:{let n=this.customKeyNetworkCtors.get(r);if(!n)throw new Error(`Custom key network '${r}' not found. Register it first using collectionFactory.registerCustomKeyNetwork().`);return new n}}}parseCollectionId(r){if(!r)throw new Error("Collection URI is required");return r.startsWith("tree://")?r.substring(7):r}getCollectionId(r){return this.parseCollectionId(r.collectionUri)}extractKeyFromEntry(r){return r[0]}getCollectionKey(r){return`${r.collectionUri}:${r.transactor}:${r.keyNetwork}`}getTransactorKey(r){return`${r.transactor}:${r.keyNetwork}`}getPeerId(r){let e=this.getNodeKey(r),t=this.libp2pNodes.get(e);return t?.node.peerId.toString()}getSigner(r){let e=this.getNodeKey(r),t=this.libp2pNodes.get(e),n=t?.node.peerPrivateKey;if(n)return async o=>V(await Bs(n,o))}registerLibp2pNode(r,e,t){let n=`${r}:0`;this.libp2pNodes.set(n,{node:e,coordinatedRepo:t})}nodeTag(){return this.nodeTagValue}setNodeTag(r){if(!/^\S+$/.test(r))throw new Error(`Node tag must be a single non-empty run of non-whitespace characters; got ${JSON.stringify(r)}`);this.nodeTagValue=r}registerTransactor(r,e){this.transactors.set(r,e)}registerCustomTransactor(r,e){this.customTransactorCtors.set(r,e)}registerCustomKeyNetwork(r,e){this.customKeyNetworkCtors.set(r,e)}getNodeKey(r){var e,t;let n=((e=r.libp2pOptions)==null?void 0:e.networkName)??"optimystic",o=((t=r.libp2pOptions)==null?void 0:t.port)??0;return`${n}:${o}`}clearCache(){this.transactors.clear()}async dispose(){let r=this.readCacheLeases;this.readCacheLeases=[],this.transactors.clear();for(let e of r)await e.release()}async shutdown(){for(let[r,{node:e}]of this.libp2pNodes.entries())H6e("Stopping libp2p node: %s",r),await e.stop();this.libp2pNodes.clear(),await this.dispose()}};function $pt(r){let e=i3(16);if(r){let n=new TextEncoder().encode(r),s=z6e(n).slice(0,16),i=new Uint8Array(32);return i.set(s,0),i.set(e,16),RA(i,"base64url")}let t=new Uint8Array(32);return t.set(e,0),t.set(i3(16),16),RA(t,"base64url")}var PJ=b3("txn-bridge"),V6e=(r,e)=>{var t;return((t=r.describe)==null?void 0:t.call(r))??`tree#${e}`},Hpt=r=>r.committedRevision===void 0?"unknown":r.committedRevision()??"none",Vpt=r=>r.committedActionId===void 0?"unknown":r.committedActionId()??"none",BJ=class extends Error{constructor(r,e,t){super(`Legacy multi-tree commit was not atomic: ${r.length} tree(s) were durably committed to storage before the commit failed and CANNOT be rolled back. Persisted (now out of sync with the unpersisted trees): [${r.join(", ")}]. Not persisted (reverted in-memory only): [${e.join(", ")}]. Underlying failure: ${t instanceof Error?t.message:String(t)}`),this.persisted=r,this.unpersisted=e,this.reason=t,this.name="PartialCommitError"}},rke=class nke extends Aa{constructor(e,t){super(e,Ia.BUSY,t),this.name="ConcurrentModificationError",Object.setPrototypeOf(this,nke.prototype)}},qpt="legacy",jpt=5*6e4,Gpt=class{currentTransaction=null;peerId;degradedReason=null;collectionFactory;accumulatedStatements=[];dirtyTrees=new Map;collectionRegistry=new Map;keyTakenMessages=new Map;entryChangedRenderers=new Map;savepoints=new Map;session=null;coordinator=null;engine=null;schemaHashProvider=null;constructor(r){this.collectionFactory=r}configureTransactionMode(r,e,t){this.coordinator=r,this.engine=e,this.schemaHashProvider=t}isTransactionModeEnabled(){return this.coordinator!==null&&this.engine!==null}registerCollection(r){let e=this.collectionRegistry.get(r.id);if(this.collectionRegistry.set(r.id,r),e!==r)for(let t of this.savepoints.values())t.has(r)||t.set(r,r.snapshotPending())}getCollectionRegistry(){return this.collectionRegistry}registerKeyTakenMessage(r,e){this.keyTakenMessages.set(r,e)}registerEntryChangedRenderer(r,e){this.entryChangedRenderers.set(r,e)}mapCommitRefusal(r){for(let e=r;e instanceof Error;e=e.cause)if(e instanceof Pg){let t=this.mapRefusal(e);return t===void 0||!(r instanceof Error)||r.message===t.message?r:t.raise(r)}return r}mapRefusal(r){var e;if(r instanceof Th){let t=this.keyTakenMessages.get(r.collectionId);return t===void 0?void 0:{message:t,raise:n=>new Upt(t,Ia.CONSTRAINT,n)}}if(r instanceof Rg){let t=(e=this.entryChangedRenderers.get(r.collectionId))==null?void 0:e(String(r.key));return t===void 0?void 0:{message:t,raise:n=>new rke(t,n)}}}async beginTransaction(r){var e;if((e=this.currentTransaction)!=null&&e.isActive)return this.currentTransaction;let t=await this.collectionFactory.getOrCreateTransactor(r),n=this.collectionFactory.getPeerId(r);if(this.peerId=n,this.accumulatedStatements=[],this.dirtyTrees.clear(),this.savepoints.clear(),this.coordinator&&this.engine&&this.schemaHashProvider){let s=await this.schemaHashProvider(),i=this.collectionFactory.getSigner(r);this.session=await $v.create(this.coordinator,this.engine,n,s,void 0,i)}else this.session=null;let o=this.session?this.session.getStampId():$pt(n);return this.currentTransaction={transactor:t,isActive:!0,collections:new Map,stampId:o},this.currentTransaction}async commitTransaction(){var r;if(!((r=this.currentTransaction)!=null&&r.isActive))throw new Error("No active transaction to commit");try{if(this.session){PJ.enabled&&this.logCommitCollections("session",[...this.collectionRegistry].map(([t,n])=>({id:String(t),staged:n.hasUnsyncedChanges(),rev:n.committedRevision()??"none",action:n.committedActionId()??"none"})));let e=await this.session.commit();if(!e.success)throw new Error(e.error||"Transaction commit failed")}else await this.commitDirtyTreesLegacy();this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,this.dirtyTrees.clear(),this.savepoints.clear(),this.degradedReason=null}catch(e){throw e instanceof BJ?(this.degradedReason=e.message,e):e instanceof ni?(this.degradedReason=e.message,this.currentTransaction.collections.clear(),this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,this.dirtyTrees.clear(),this.savepoints.clear(),e):(await this.rollbackTransaction(),this.mapCommitRefusal(e))}}logCommitCollections(r,e){let t=[...e].sort((o,s)=>o.id<s.id?-1:o.id>s.id?1:0),n=t.map(o=>`${o.id}=${o.staged===void 0?"unknown":o.staged?"staged":"clean"}`).join(" ");PJ("commit:collections mode=%s count=%d%s revs=%s node=%s",r,t.length,n?` ${n}`:"",t.map(o=>`${o.id}:${tke(o.rev,o.action)}`).join(","),this.collectionFactory.nodeTag())}async commitDirtyTreesLegacy(){let r=[...this.dirtyTrees.keys()];PJ.enabled&&this.logCommitCollections("legacy",r.map((t,n)=>{var o;return{id:V6e(t,n),staged:(o=t.hasUnsyncedChanges)==null?void 0:o.call(t),rev:Hpt(t),action:Vpt(t)}}));let e=this.legacyBatch(r);if(e===void 0){await this.sweepDirtyTreesLegacy(r);return}await this.commitBatchLegacy(e)}legacyBatch(r){var e;let t=r.filter(s=>{var i;return((i=s.hasUnsyncedChanges)==null?void 0:i.call(s))!==!1});if(t.length<2)return;let n=[];for(let s of t){let i=(e=s.getCollection)==null?void 0:e.call(s);if(i===void 0)return;n.push(i)}let o=n[0].transactor;if(!n.some(s=>s.transactor!==o)&&new Set(n.map(s=>s.id)).size===n.length)return{collections:n,transactor:o}}async commitBatchLegacy({collections:r,transactor:e}){let t=new zv(e,new Map(r.map(n=>[n.id,n])),{pendValidation:"none"});try{await t.commit(await this.legacyTransaction())}catch(n){throw n instanceof ni&&this.restoreUncommittedTrees(new Set(n.committedCollections)),n}}async legacyTransaction(){let r=await Rv(this.peerId??"local",Date.now(),"",qpt,jpt);return{stamp:r,statements:[],reads:[],id:await Lv(r.id,[],[])}}restoreUncommittedTrees(r){var e,t;for(let[n,o]of this.dirtyTrees){let s=(t=(e=n.getCollection)==null?void 0:e.call(n))==null?void 0:t.id;(s===void 0||!r.has(s))&&n.restore(o)}}async sweepDirtyTreesLegacy(r){var e;let t=[];if(r.length>1){for(let n of r)if(n.update!==void 0&&((e=n.hasUnsyncedChanges)==null?void 0:e.call(n))!==!1)try{await n.update()}catch(o){throw this.mapCommitRefusal(o)}}for(let n of r)try{await n.sync(),t.push(n)}catch(o){let s=this.mapCommitRefusal(o);if(t.length===0)throw s;let i=r.filter(u=>!t.includes(u));for(let u of i)u.restore(this.dirtyTrees.get(u));let a=u=>V6e(u,r.indexOf(u)),c=t.map(a),l=i.map(a);throw this.dirtyTrees.clear(),this.savepoints.clear(),this.currentTransaction.collections.clear(),this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,new BJ(c,l,s)}}async rollbackTransaction(){var r;if(!((r=this.currentTransaction)!=null&&r.isActive))throw new Error("No active transaction to rollback");if(this.session&&!this.session.isRolledBack())try{await this.session.rollback()}catch{}if(!this.session)for(let[e,t]of this.dirtyTrees)e.restore(t);this.dirtyTrees.clear(),this.savepoints.clear(),this.currentTransaction.collections.clear(),this.currentTransaction.isActive=!1,this.accumulatedStatements=[],this.session=null,this.degradedReason=null}getCurrentTransaction(){return this.currentTransaction}isDegraded(){return this.degradedReason!==null}getDegradedReason(){return this.degradedReason??void 0}getSession(){return this.session}isTransactionActive(){var r;return((r=this.currentTransaction)==null?void 0:r.isActive)??!1}markDirty(r){this.dirtyTrees.has(r)||this.dirtyTrees.set(r,r.snapshot())}forgetTree(r){var e;this.dirtyTrees.delete(r);let t=(e=r.getCollection)==null?void 0:e.call(r);t&&this.collectionRegistry.get(t.id)===t&&this.collectionRegistry.delete(t.id)}getDirtySnapshot(r){return this.dirtyTrees.get(r)}async addStatement(r){var e;if((e=this.currentTransaction)!=null&&e.isActive&&(this.accumulatedStatements.push(r),this.session)){let t=await this.session.execute(r,[]);if(!t.success)throw new Error(`Failed to record statement in transaction: ${t.error}`)}}getStatements(){return this.accumulatedStatements}getStatementCount(){return this.accumulatedStatements.length}createSavepoint(r){if(this.session||this.savepoints.has(r))return;let e=new Map;for(let t of this.collectionRegistry.values())e.set(t,t.snapshotPending());this.savepoints.set(r,e)}rollbackToSavepoint(r){let e=this.savepoints.get(r);if(e){for(let[t,n]of e)t.restorePending(n);for(let t of this.savepoints.keys())t>r&&this.savepoints.delete(t)}}releaseSavepoint(r){for(let e of this.savepoints.keys())e>=r&&this.savepoints.delete(e)}async cleanup(){var r;(r=this.currentTransaction)!=null&&r.isActive&&await this.rollbackTransaction(),this.currentTransaction=null}},Wpt=0,RJ=class{connectionId;tableName;txnBridge;options;constructor(r,e,t){this.connectionId=`optimystic-${r}-${++Wpt}`,this.tableName=r,this.txnBridge=e,this.options=t}async begin(){await this.txnBridge.beginTransaction(this.options)}async commit(){let r=this.txnBridge.getCurrentTransaction();r?.isActive||await this.txnBridge.beginTransaction(this.options),await this.txnBridge.commitTransaction()}async rollback(){await this.txnBridge.rollbackTransaction()}createSavepoint(r){this.txnBridge.createSavepoint(r)}releaseSavepoint(r){this.txnBridge.releaseSavepoint(r)}rollbackToSavepoint(r){this.txnBridge.rollbackToSavepoint(r)}async disconnect(){let r=this.txnBridge.getCurrentTransaction();r?.isActive&&await this.txnBridge.rollbackTransaction()}},oke="\0",Ypt="",ske="\0",Xpt="\xFF",ike="";function Zpt(r){return r.includes("\0")?r.replace(/\x00/g,"\0\xFF"):r}function Jpt(r){return r===null?oke:Ypt+Zpt(r)+ske}function MA(r){let e="";for(let t of r)e+=Jpt(t);return e}function m3(r){let e=[],t=0,n=r.length;for(;t<n;){if(r[t]===oke){e.push({isNull:!0,payload:""}),t+=1;continue}t+=1;let s="";for(;t<n;){let i=r[t];if(i===ske){if(r[t+1]===Xpt){s+="\0",t+=2;continue}t+=1;break}s+=i,t+=1}e.push({isNull:!1,payload:s})}return e}var ake=new Set(["transactor","keyNetwork","port","networkName","cache"]);function Qpt(r){let e=cke(r,t=>!ake.has(t));return Object.keys(e).length>0?e:void 0}function emt(r){return cke(r,e=>ake.has(e))}function cke(r,e){let t={};for(let[n,o]of Object.entries(r??{}))e(n)&&(t[n]=o);return t}function lke(r,e){return`tree://default/${r}/${e}`}function th(r,e){return MA([r,e])}function tmt(r){let e=m3(r);if(!(e.length!==2||e.some(t=>t.isNull))&&th(e[0].payload,e[1].payload)===r)return{schemaName:e[0].payload,tableName:e[1].payload}}function q6e(r){return new Map([...r].map(([e,t])=>[e,new Set(t)]))}function LA(r){let e=r;return e&&e.length>=2&&e[1]?e[1]:void 0}function uke(r){var e;return((e=r.vtabArgs)==null?void 0:e[0])||lke(r.schemaName,r.name)}var rmt=class{constructor(r,e){this.openTree=r,this.mergeLatest=e}tree;transactor;pending=new Map;removedIndexes=new Map;committedRecords;async catalogExists(r){return await this.committedTree(r)!==null}hasPending(r){return this.pending.has(r)}async readEntry(r,e){if(this.pending.has(r))return this.pending.get(r);let t=await this.committedTree(e);if(!t)return;let n=await t.find(r);return t.isValid(n)?t.at(n):void 0}write(r,e){this.pending.set(r,e)}excludeIndexAtCommit(r,e){let t=this.removedIndexes.get(r)??new Set;t.add(e.toLowerCase()),this.removedIndexes.set(r,t)}async recordForUri(r,e){let t=new Map(await this.committed(e));for(let[o,s]of this.pending){let i=LA(s);i?t.set(o,i):t.delete(o)}let n;for(let o of t.values())if(uke(o)===r){if(!o.droppedAt)return o;n=n??o}return n}checkpoint(){return{pending:new Map(this.pending),removedIndexes:q6e(this.removedIndexes)}}restore(r){this.pending=new Map(r.pending),this.removedIndexes=q6e(r.removedIndexes)}async commit(){let r=new Map;if(this.pending.size===0)return r;let e=await this.writableTree();await e.update();for(let[t,n]of this.pending){let o=LA(n);if(o&&!o.droppedAt){let s=await e.find(t),i=e.isValid(s)?LA(e.at(s)):void 0,a=i&&!i.droppedAt?i:void 0;r.set(t,[t,this.mergeLatest(o,this.withoutRemovedIndexes(t,a))])}else r.set(t,n)}return await e.stage([...r.entries()]),await e.sync(),r}withoutRemovedIndexes(r,e){let t=this.removedIndexes.get(r);return!e||!t?e:{...e,indexes:e.indexes.filter(n=>!t.has(n.name.toLowerCase()))}}async committedTree(r){if(this.tree===void 0){this.transactor=this.transactor??r;let e=await this.openTree(this.transactor,!1);e&&await e.update(),this.tree=e??null}return this.tree}async writableTree(){let r=await this.committedTree();if(r)return r;let e=await this.openTree(this.transactor,!0);if(!e)throw new Error("Schema catalog tree unavailable: create-on-missing resolved to nothing");return this.tree=e,e}async committed(r){if(!this.committedRecords){let e=new Map,t=await this.committedTree(r);if(t)for await(let n of t.range({isAscending:!0})){if(!t.isValid(n))continue;let o=t.at(n),s=LA(o);o&&s&&e.set(o[0],s)}this.committedRecords=e}return this.committedRecords}};function rh(r){return[...r].sort((e,t)=>e-t).join("_")}function nmt(r){return`_uniq_${r.map(t=>t.toLowerCase()).sort().map(t=>`${t.length}.${t}`).join("_")}`}function Kx(r){return r.predicate===void 0?`cols:${rh(r.columns)}`:`partial:${r.derivedFromIndex??rh(r.columns)}`}function g3(r,e){let t=[...r],n=new Map(r.map((o,s)=>[o.name,s]));for(let o of e){let s=n.get(o.name);s===void 0?t.push(o):o.unique&&!t[s].unique&&(t[s]={...t[s],unique:!0,predicate:t[s].predicate??o.predicate})}return t}function omt(r,e){return r===e?0:r===void 0?-1:e===void 0?1:r<e?-1:1}function LJ(r){return r.map((e,t)=>({item:e,position:t})).sort((e,t)=>omt(e.item.name,t.item.name)||e.position-t.position).map(({item:e})=>e)}function UJ(r){return{...r,indexes:LJ(r.indexes),...r.orphanedIndexes?{orphanedIndexes:LJ(r.orphanedIndexes)}:{},...r.checkConstraints?{checkConstraints:LJ(r.checkConstraints)}:{}}}function dke(r){return new Map(r.map((e,t)=>[e.name.toLowerCase(),t]))}function FJ(r){return`[${r.map(e=>e.name).join(", ")}]`}function fke(r){let e=dke(r.columns),t=[];for(let n of r.indexes)for(let o of n.columns)e.has(o.name.toLowerCase())||t.push({index:n.name,column:o.name});return t}function hke(r){let e=r.columns.length,t=(n,o)=>{if(!Number.isInteger(n)||n<0||n>=e)throw new Error(`Cannot persist table '${r.name}': ${o} position ${n} is out of range for its column list ${FJ(r.columns)}`)};for(let n of r.primaryKeyDefinition)t(n.index,"primary key");for(let n of r.uniqueConstraints??[])for(let o of n.columns)t(o,`unique constraint ${n.name?`'${n.name}' `:""}column`);for(let n of r.foreignKeys??[])for(let o of n.columns)t(o,`foreign key ${n.name?`'${n.name}' `:""}column`);for(let[n,o]of r.generatedColumnDependencies??[]){t(n,"generated column");for(let s of o)t(s,`generated column ${n} dependency`)}for(let n of r.generatedColumnTopoOrder??[])t(n,"generated column order")}function Om(r){if(Array.isArray(r))return r.map(Om);if(r===null||typeof r!="object"||r instanceof Uint8Array)return r;let e={};for(let t of Object.keys(r).sort()){if(t==="loc")continue;let n=r[t];n!==void 0&&(e[t]=Om(n))}return e}function Nx(r){return r&&r.length>0?[...r]:void 0}function Pi(r){return r&&Object.keys(r).length>0?{...r}:void 0}function h3(r){let e=r.indexes.map(t=>({...t,columns:t.columns.map(n=>{let o=r.columns[n.index];if(o===void 0)throw new Error(`Cannot persist table '${r.name}': index '${t.name}' addresses column position ${n.index}, which is out of range for its column list ${FJ(r.columns)}`);let{index:s,...i}=n;return{...i,name:o.name}})}));return{...r,indexes:e}}function Qu(r){let e=fke(r);if(e.length>0){let[o]=e;throw new Error(`Persisted catalog record for table '${r.name}' is unresolvable: index '${o.index}' names column '${o.column}', which is absent from its column list ${FJ(r.columns)}`)}hke(r);let t=dke(r.columns),n=r.indexes.map(o=>({...o,columns:o.columns.map(s=>{let{name:i,...a}=s;return{...a,index:t.get(i.toLowerCase())}})}));return{...r,indexes:n}}function j6e(r,e){let t=e.toLowerCase(),n=r.indexes.find(o=>o.name.toLowerCase()===t);if(n)return UJ({...r,indexes:r.indexes.filter(o=>o!==n),orphanedIndexes:g3([n],r.orphanedIndexes??[])})}function p3(r,e){let t=e?{...r,indexes:g3(r.indexes,e.indexes)}:r,n=g3(r.orphanedIndexes??[],e?.orphanedIndexes??[]);n.length>0&&(t={...t,orphanedIndexes:n}),t=UJ(t);let[o]=fke(t);if(o)throw new Error(`Cannot re-declare table '${t.name}' without column '${o.column}': persisted index '${o.index}' covers it. Drop the index or the table first.`);return hke(t),t}var smt=class{constructor(r){this.getSchemaTree=r}schemaCache=new Map;batch;beginBatch(){if(this.batch)throw new Error("A catalog batch is already open on this SchemaManager");this.batch=new rmt(this.getSchemaTree,p3)}async commitBatch(){let r=this.batch;if(!r)throw new Error("No catalog batch is open on this SchemaManager");this.batch=void 0;let e=await r.commit();for(let[t,n]of e)this.resolveAndCache(n)===void 0&&this.schemaCache.delete(t)}discardBatch(){this.batch=void 0}checkpointBatch(){var r;return(r=this.batch)==null?void 0:r.checkpoint()}restoreBatch(r){if(!this.batch)throw new Error("No catalog batch is open on this SchemaManager");this.batch.restore(r)}async requireSchemaTree(r){let e=await this.getSchemaTree(r,!0);if(!e)throw new Error("Schema catalog tree unavailable: create-on-missing resolved to nothing");return e}async storeSchema(r,e){await this.storeStoredSchema(this.tableSchemaToStored(r),e)}async storeStoredSchema(r,e){if(this.batch)return this.storeInBatch(this.batch,r,e);let t=await this.requireSchemaTree(e),n=th(r.schemaName,r.name);await t.update();let o=await t.find(n),s=t.isValid(o)?this.livePersistedEntry(t.at(o)):void 0,i=p3(h3(r),s),a=Qu(i);return await t.replace([[n,[n,i]]]),this.schemaCache.set(n,a),a}async storeInBatch(r,e,t){let n=th(e.schemaName,e.name),o=this.livePersistedEntry(await r.readEntry(n,t)),s=p3(h3(e),o);return r.write(n,[n,s]),Qu(s)}async readLiveInBatch(r,e,t){let n=this.livePersistedEntry(await r.readEntry(e,t));return n?Qu(n):void 0}mergeWithPersisted(r,e){return Qu(p3(h3(r),h3(e)))}anyPersistedEntry(r){return LA(r)}livePersistedEntry(r){let e=this.anyPersistedEntry(r);return e&&!e.droppedAt?e:void 0}droppedPersistedEntry(r){let e=this.anyPersistedEntry(r);return e&&e.droppedAt?e:void 0}resolveAndCache(r){let e=this.livePersistedEntry(r);if(!e)return;let t=Qu(e);return this.schemaCache.set(r[0],t),t}async getSchema(r,e,t){let n=th(r,e);if(this.batch)return this.readLiveInBatch(this.batch,n,t);let o=this.schemaCache.get(n);return o||await this.readSchemaFromCatalog(n,t)}async getSchemaFresh(r,e,t){let n=th(r,e),o=this.batch?await this.readLiveInBatch(this.batch,n,t):await this.readSchemaFromCatalog(n,t);return o||this.schemaCache.get(n)}async readSchemaFromCatalog(r,e){let t=await this.getSchemaTree(e);if(!t)return;await t.update();let n=await t.find(r);if(t.isValid(n))return this.resolveAndCache(t.at(n))}async deleteSchema(r,e,t){let n=th(r,e);if(this.schemaCache.delete(n),this.batch)return this.deleteInBatch(this.batch,n,t);let o=await this.getSchemaTree(t);if(!o)return;let s;try{await o.update();let i=await o.find(n),a=o.isValid(i)?this.anyPersistedEntry(o.at(i)):void 0;a&&(s={...a,droppedAt:a.droppedAt??new Date().toISOString()})}catch{s=void 0}await o.replace([[n,s?[n,s]:void 0]])}async deleteInBatch(r,e,t){if(!r.hasPending(e)&&!await r.catalogExists(t))return;let n;try{let o=this.anyPersistedEntry(await r.readEntry(e,t));o&&(n={...o,droppedAt:o.droppedAt??new Date().toISOString()})}catch{n=void 0}r.write(e,n?[e,n]:void 0)}async removeIndex(r,e,t,n){let o=th(r,e);if(this.batch)return this.removeIndexInBatch(this.batch,o,t,n);let s=await this.getSchemaTree(n);if(!s)return;await s.update();let i=await s.find(o),a=s.isValid(i)?this.livePersistedEntry(s.at(i)):void 0;if(!a)return;let c=j6e(a,t);if(!c)return Qu(a);await s.replace([[o,[o,c]]]);let l=Qu(c);return this.schemaCache.set(o,l),l}async removeIndexInBatch(r,e,t,n){let o=this.livePersistedEntry(await r.readEntry(e,n));if(!o)return;let s=j6e(o,t);return s?(r.write(e,[e,s]),r.excludeIndexAtCommit(e,t),Qu(s)):Qu(o)}async*catalogEntries(r){let e=await this.getSchemaTree(r);if(e){await e.update();for await(let t of e.range({isAscending:!0})){if(!e.isValid(t))continue;let n=e.at(t);n&&n.length>=1&&(yield n)}}}async listTables(r){let e=[];for await(let t of this.catalogEntries(r)){let n=tmt(t[0]);n&&(this.resolveAndCache(t),e.push(n))}return e}async findRecordForUri(r,e){if(this.batch)return this.batch.recordForUri(r,e);let t;for await(let n of this.catalogEntries(e)){let o=this.anyPersistedEntry(n);if(o&&uke(o)===r){if(!o.droppedAt)return o;t=t??o}}return t}async getDroppedSchemaRecord(r,e,t){let n=th(r,e);if(this.batch)return this.droppedPersistedEntry(await this.batch.readEntry(n,t));let o=await this.getSchemaTree(t);if(!o)return;await o.update();let s=await o.find(n);return o.isValid(s)?this.droppedPersistedEntry(o.at(s)):void 0}clearCache(){this.schemaCache.clear()}storedToTableSchema(r,e,t,n={}){var o,s;let i=r.columns.map(c=>this.storedToColumnSchema(c)),a=r.primaryKeyDefinition.map(c=>({index:c.index,desc:c.desc,collation:c.collation}));return{name:r.name,schemaName:r.schemaName,columns:i,columnIndexMap:eke(i),primaryKeyDefinition:a,primaryKeyDefaultConflict:r.primaryKeyDefaultConflict,synthesizedPrimaryKey:r.synthesizedPrimaryKey,checkConstraints:(r.checkConstraints??[]).map(c=>this.storedToCheckConstraint(c)),foreignKeys:(o=r.foreignKeys)==null?void 0:o.map(c=>this.storedToForeignKey(c)),vtabModule:e,vtabAuxData:t,vtabArgs:{...emt(n),...r.vtabArgs},vtabModuleName:r.vtabModuleName,isView:!1,indexes:r.indexes.length>0?this.storedIndexesToIndexSchemas(r.indexes):void 0,uniqueConstraints:this.storedToUniqueConstraints(r),mutationContext:(s=r.mutationContext)==null?void 0:s.map(c=>this.storedToMutationContextVar(c)),generatedColumnDependencies:r.generatedColumnDependencies?new Map(r.generatedColumnDependencies.map(([c,l])=>[c,[...l]])):void 0,generatedColumnTopoOrder:r.generatedColumnTopoOrder?[...r.generatedColumnTopoOrder]:void 0,tags:Pi(r.tags)}}storedToColumnSchema(r){return{name:r.name,logicalType:r.declaredType!==void 0?Npt(r.declaredType):$6e(r.affinity),declaredType:r.declaredType,notNull:r.notNull,primaryKey:r.primaryKey,pkOrder:r.pkOrder,defaultValue:r.defaultValue??null,collation:r.collation,collationExplicit:r.collationExplicit,generated:r.generated,generatedExpr:r.generatedExpr,generatedStored:r.generatedStored,pkDirection:r.pkDirection,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}storedToCheckConstraint(r){return{name:r.name,expr:r.expr,operations:r.operations,deferrable:r.deferrable,initiallyDeferred:r.initiallyDeferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}storedToForeignKey(r){return{name:r.name,columns:[...r.columns],referencedTable:r.referencedTable,referencedSchema:r.referencedSchema,referencedColumnNames:r.referencedColumnNames?[...r.referencedColumnNames]:void 0,onDelete:r.onDelete,onUpdate:r.onUpdate,deferred:r.deferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}storedToMutationContextVar(r){return{name:r.name,logicalType:$6e(r.type),notNull:r.notNull}}storedIndexesToIndexSchemas(r){return r.map(e=>({name:e.name,columns:e.columns.map(t=>({index:t.index,desc:t.desc,collation:t.collation})),unique:e.unique?!0:void 0,predicate:e.predicate,tags:Pi(e.tags)}))}storedToUniqueConstraints(r){let e=(r.uniqueConstraints??[]).map(n=>({name:n.name,columns:[...n.columns],defaultConflict:n.defaultConflict,predicate:n.predicate,tags:Pi(n.tags)})),t=new Set(e.map(Kx));for(let n of r.indexes){if(!n.unique)continue;let o={name:n.name,columns:n.columns.map(i=>i.index),predicate:n.predicate,derivedFromIndex:n.name},s=Kx(o);t.has(s)||(t.add(s),e.push(o))}return e.length>0?e:void 0}tableSchemaToStored(r){var e,t;let n=(r.uniqueConstraints??[]).filter(s=>s.derivedFromIndex===void 0).map(s=>({name:s.name,columns:[...s.columns],defaultConflict:s.defaultConflict,predicate:s.predicate?Om(s.predicate):void 0,tags:Pi(s.tags)})),o=r.generatedColumnDependencies?[...r.generatedColumnDependencies.entries()].sort(([s],[i])=>s-i).map(([s,i])=>[s,[...i]]):void 0;return UJ({name:r.name,schemaName:r.schemaName,columns:r.columns.map(s=>this.columnSchemaToStored(s)),primaryKeyDefinition:r.primaryKeyDefinition.map(s=>({index:s.index,desc:s.desc,collation:s.collation})),primaryKeyDefaultConflict:r.primaryKeyDefaultConflict,indexes:(r.indexes||[]).map(s=>this.indexSchemaToStored(s)),vtabModuleName:r.vtabModuleName,vtabArgs:Qpt(r.vtabArgs),uniqueConstraints:Nx(n),checkConstraints:Nx(r.checkConstraints.map(s=>this.checkConstraintToStored(s))),foreignKeys:Nx((e=r.foreignKeys)==null?void 0:e.map(s=>this.foreignKeyToStored(s))),mutationContext:Nx((t=r.mutationContext)==null?void 0:t.map(s=>({name:s.name,type:s.logicalType.name,notNull:s.notNull}))),tags:Pi(r.tags),synthesizedPrimaryKey:r.synthesizedPrimaryKey,generatedColumnDependencies:Nx(o),generatedColumnTopoOrder:Nx(r.generatedColumnTopoOrder)})}columnSchemaToStored(r){return{name:r.name,affinity:r.logicalType.name,declaredType:r.declaredType,notNull:r.notNull,primaryKey:r.primaryKey,pkOrder:r.pkOrder,defaultValue:r.defaultValue?Om(r.defaultValue):void 0,collation:r.collation,collationExplicit:r.collationExplicit?!0:void 0,generated:r.generated,generatedExpr:r.generatedExpr?Om(r.generatedExpr):void 0,generatedStored:r.generatedStored,pkDirection:r.pkDirection,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}withCheckConstraint(r,e){var t;let n=(t=e.name)==null?void 0:t.toLowerCase(),o=(r.checkConstraints??[]).filter(s=>{var i;return n===void 0||((i=s.name)==null?void 0:i.toLowerCase())!==n});return{...r,checkConstraints:[...o,this.checkConstraintToStored(e)]}}checkConstraintToStored(r){return{name:r.name,expr:Om(r.expr),operations:r.operations,deferrable:r.deferrable,initiallyDeferred:r.initiallyDeferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}foreignKeyToStored(r){return{name:r.name,columns:[...r.columns],referencedTable:r.referencedTable,referencedSchema:r.referencedSchema,referencedColumnNames:r.referencedColumnNames?[...r.referencedColumnNames]:void 0,onDelete:r.onDelete,onUpdate:r.onUpdate,deferred:r.deferred,defaultConflict:r.defaultConflict,tags:Pi(r.tags)}}indexSchemaToStored(r){return{name:r.name,columns:r.columns.map(e=>({index:e.index,desc:e.desc,collation:e.collation})),unique:r.unique?!0:void 0,predicate:r.predicate?Om(r.predicate):void 0,tags:Pi(r.tags)}}},imt=class{constructor(r,e="json"){this.schema=r,this.encoding=e}encodeRow(r){let e={};for(let t=0;t<this.schema.columns.length;t++){let n=this.schema.columns[t];if(!n)continue;let o=r[t];e[n.name]=this.normalizeValue(o??null)}if(this.encoding==="msgpack")throw new Error("msgpack encoding not yet implemented");return JSON.stringify(e)}decodeRow(r){let e;if(this.encoding==="msgpack")throw new Error("msgpack decoding not yet implemented");e=JSON.parse(r);let t=[];for(let n=0;n<this.schema.columns.length;n++){let o=this.schema.columns[n];o&&(t[n]=this.denormalizeValue(e[o.name],o))}return t}asPrimaryKeyTuple(r){if(r.length!==this.schema.primaryKeyDefinition.length)throw new Error(`Primary key requires ${this.schema.primaryKeyDefinition.length} values, got ${r.length}`);return r}extractPrimaryKey(r){if(r.length!==this.schema.columns.length)throw new Error(`extractPrimaryKey requires a full row of ${this.schema.columns.length} columns, got ${r.length} \u2014 did you pass a compact key tuple (one cell per primary-key column) instead? Use createPrimaryKey for that.`);let e=this.schema.primaryKeyDefinition.map(t=>this.serializeKeyPart(r[t.index]??null));return MA(e)}createPrimaryKey(r){if(r.length!==this.schema.primaryKeyDefinition.length)throw new Error(`Primary key requires ${this.schema.primaryKeyDefinition.length} values, got ${r.length}`);return MA(r.map(e=>this.serializeKeyPart(e??null)))}decodePrimaryKey(r){let e=m3(r);return this.schema.primaryKeyDefinition.map((t,n)=>{var o;return this.keyElementToValue(e[n],(o=this.schema.columns[t.index])==null?void 0:o.affinity)})}getPrimaryKeyIndices(){return this.schema.primaryKeyDefinition.map(r=>r.index)}getColumnCount(){return this.schema.columns.length}getColumnName(r){var e;return((e=this.schema.columns[r])==null?void 0:e.name)||""}getColumnIndex(r){return this.schema.columns.findIndex(e=>e.name.toLowerCase()===r.toLowerCase())}serializeKeyPart(r){return r==null?null:typeof r=="string"?r:typeof r=="number"||typeof r=="bigint"?r.toString():typeof r=="boolean"?r?"1":"0":r instanceof Uint8Array?RA(r,"base64"):String(r)}normalizeValue(r){return typeof r=="bigint"?r>=Number.MIN_SAFE_INTEGER&&r<=Number.MAX_SAFE_INTEGER?Number(r):{$bigint:r.toString()}:r instanceof Uint8Array&&this.encoding==="json"?RA(r,"base64"):r}denormalizeValue(r,e){return r==null?null:typeof r=="object"&&r!==null&&"$bigint"in r?BigInt(r.$bigint):e.affinity==="BLOB"&&typeof r=="string"?_J(r,"base64"):r}isColumnInPrimaryKey(r){return this.schema.primaryKeyDefinition.some(e=>e.index===r)}getSchema(){return this.schema}createPrimaryKeyComparator(){let r=this.schema.primaryKeyDefinition;if(r.length===0)return()=>0;let e=r.map(o=>_pt(o.collation||"BINARY")??Ppt),t=r.map(o=>o.desc||!1),n=r.map(o=>{var s;return(s=this.schema.columns[o.index])==null?void 0:s.affinity});return(o,s)=>{let i=this.decodeKeyForCompare(o),a=this.decodeKeyForCompare(s);for(let c=0;c<r.length;c++){let l=this.keyElementToValue(i[c],n[c]),u=this.keyElementToValue(a[c],n[c]),d=this.compareValues(l,u,e[c]);if(d!==0){let h=t[c]?-1:1;return d*h}}return 0}}decodeKeyForCompare(r){let e=r[0];return e==="\0"||e===""?m3(r):[{isNull:!1,payload:r}]}keyElementToValue(r,e){return!r||r.isNull?null:this.deserializeKeyPart(r.payload,e)}deserializeKeyPart(r,e){let t=(e||"").toUpperCase();if(t==="INTEGER"||t==="REAL"||t==="NUMERIC"){let n=Number(r);return!isNaN(n)&&r.trim()!==""?n:r}return t==="BLOB"?_J(r,"base64"):r}compareValues(r,e,t){return r===null&&e===null?0:r===null?-1:e===null?1:typeof r=="string"&&typeof e=="string"?t(r,e):typeof r=="number"&&typeof e=="number"?r<e?-1:r>e?1:0:Rpt(r,e)}};function amt(r){return r==null?null:typeof r=="string"?r:typeof r=="bigint"?Number(r).toExponential(15):typeof r=="number"?r.toExponential(15):r instanceof Uint8Array?btoa(String.fromCharCode(...r)):String(r)}function y3(r){return MA(r.map(e=>amt(e??null)))}function ed(r,e){return r+e}function pke(r,e,t){let[n,o]=e;return n===ed(t(r),o)}function mke(r,e){return r.columns.some(t=>e[t.index]===null||e[t.index]===void 0)}function gke(r){return new rl({key:r,inclusive:!0},{key:r+ike,inclusive:!1},!0)}function cmt(r){return{kind:"absentRange",range:gke(r)}}var lmt=class{constructor(r,e){this.schema=r,this.indexTreeFactory=e}indexTrees=new Map;uniqueEnforcementIndexes=[];async initialize(r){for(let e of this.schema.indexes){let t=await this.indexTreeFactory(e.name,r);this.indexTrees.set(e.name,t)}}getDeclaredIndexes(){return[...this.schema.indexes]}async setUniqueEnforcementIndexes(r,e){this.uniqueEnforcementIndexes=r;for(let t of r)if(!this.indexTrees.has(t.name)){let n=await this.indexTreeFactory(t.name,e);this.indexTrees.set(t.name,n)}}getAllMaintainedIndexes(){return[...this.schema.indexes,...this.uniqueEnforcementIndexes]}getIndexTree(r){return this.indexTrees.get(r)}getIndexTrees(){return[...this.indexTrees.values()]}registerIndexTree(r,e){this.indexTrees.set(r,e)}unregisterIndex(r){let e=r.toLowerCase(),t=this.schema.indexes.find(o=>o.name.toLowerCase()===e);if(!t)return;this.schema={...this.schema,indexes:this.schema.indexes.filter(o=>o!==t)};let n=this.indexTrees.get(t.name);return this.indexTrees.delete(t.name),n}setSchema(r){this.schema=r}createIndexKey(r,e){return y3(r.columns.map(t=>e[t.index]??null))}asIndexColumnTuple(r,e){if(e.length===0||e.length>r.columns.length)throw new Error(`Index '${r.name}' key tuple requires 1 to ${r.columns.length} values (a leading prefix is allowed), got ${e.length}`);return e}createIndexKeyFromTuple(r){return y3(r)}async insertIndexEntries(r,e,t,n){for(let o of this.getAllMaintainedIndexes()){let s=this.createIndexKey(o,r),i=this.indexTrees.get(o.name);if(!i)throw new Error(`Index tree not found: ${o.name}`);let a=ed(s,e);await i.stage([[a,[a,e],this.guardFor(o,s,n)]])}}guardFor(r,e,t){return t?.has(r.name)?cmt(e):void 0}async deleteIndexEntries(r,e,t){for(let n of this.getAllMaintainedIndexes()){let o=this.createIndexKey(n,r),s=this.indexTrees.get(n.name);if(!s)throw new Error(`Index tree not found: ${n.name}`);let i=ed(o,e);await s.stage([[i,void 0]])}}async updateIndexEntries(r,e,t,n,o,s){for(let i of this.getAllMaintainedIndexes()){let a=this.createIndexKey(i,r),c=this.createIndexKey(i,e),l=this.indexTrees.get(i.name);if(!l)throw new Error(`Index tree not found: ${i.name}`);let u=ed(a,t),d=ed(c,n);u!==d&&await l.stage([[u,void 0],[d,[d,n],this.guardFor(i,c,s)]])}}async*findByIndex(r,e){let t=this.indexTrees.get(r);if(!t)throw new Error(`Index tree not found: ${r}`);await t.update(),yield*this.findByIndexIn(t,e)}async*findByIndexIn(r,e){for await(let t of this.findEntriesIn(r,e))yield t[1]}async*findEntriesIn(r,e){for await(let t of r.range(gke(e))){if(!r.isValid(t))continue;let n=r.at(t);n!=null&&(yield n)}}async*allEntriesIn(r){for await(let e of r.range(new rl(void 0,void 0,!0))){if(!r.isValid(e))continue;let t=r.at(e);t!=null&&(yield t)}}async*scanIndexRange(r,e,t,n=!0){let o=this.indexTrees.get(r);if(!o)throw new Error(`Index tree not found: ${r}`);await o.update();let s=e!==void 0?{key:e,inclusive:!0}:void 0,i=t!==void 0?{key:t+ike,inclusive:!1}:void 0,a=new rl(s,i,n);for await(let c of o.range(a)){if(!o.isValid(c))continue;let l=o.at(c);l!=null&&(yield l[1])}}getIndexSchema(r){return this.schema.indexes.find(e=>e.name===r)}};function umt(r){let{index:e,kind:t,rows:n}=r,o=e.columns.length,s=new Map,i=new Set;for(let[u,d]of n){let h=ed(r.indexKeyOf(d),u);s.set(h,{primaryKey:u,row:d}),dmt(e,t,d)&&i.add(h)}let a=new Set,c=[];for(let[u,d]of r.entries){a.add(u);let h=fmt(u,d,o,r.indexKeyOf,n);h&&c.push(h)}let l=[];for(let[u,{primaryKey:d,row:h}]of s)a.has(u)||i.has(u)||l.push({expectedTreeKey:u,primaryKey:d,row:h,...yke(u,o)});return{table:r.table,index:e.name,kind:t,rowCount:n.size,entryCount:r.entries.length,missing:l,orphaned:c}}function dmt(r,e,t){return e==="unique-enforcement"&&mke(r,t)}function fmt(r,e,t,n,o){let s=o.get(e);if(s!==void 0&&pke(s,[r,e],n))return;let i=yke(r,t),a={treeKey:r,primaryKey:e,...i};return r!==ed(MA(i.indexPayloads),e)?{...a,reason:"malformed"}:s===void 0?{...a,reason:"no-row"}:{...a,reason:"stale-value",currentRow:s}}function yke(r,e){let t=m3(r).map(n=>n.isNull?null:n.payload);return{indexPayloads:t.slice(0,e),primaryKeyPayloads:t.slice(e)}}var Ca=b3("module"),G6e=new Set;function Ux(r,e){let t=`${r}: ${e instanceof Error?e.message:String(e)}`;return new Error(t,{cause:e})}var hmt=/[^A-Za-z0-9._-]/g,pmt=r=>r.replace(hmt,e=>{let t=e.charCodeAt(0);return t<=255?`%${t.toString(16).toUpperCase().padStart(2,"0")}`:`%u${t.toString(16).toUpperCase().padStart(4,"0")}`});async function*MJ(r,e){for await(let t of r.ascending(await r.first())){if(!r.isValid(t))continue;let n=r.at(t);if(!n||n.length<2)continue;let o=e.decodeRow(n[1]);yield{row:o,primaryKey:e.extractPrimaryKey(o)}}}async function W6e(r,e,t){let n=await r.find(t);if(!r.isValid(n))return;let o=r.at(n);if(!(!o||o.length<2))return e.decodeRow(o[1])}function Fx(r){return{kind:"unchanged",expected:r}}function OJ(r,e,t){return`Table '${r}' does not maintain index '${e}': ${t}, so reading through it would silently return incomplete results. Re-declare the index on this connection (CREATE INDEX) to re-attach it \u2014 DROP INDEX it first if this connection still lists it.`}function mmt(r,e,t){let n=r.columnIndexMap.get(e.toLowerCase()),o=r.columns.map((s,i)=>i===n?{...s,name:t}:s);return{...r,columns:Object.freeze(o),columnIndexMap:eke(o)}}function Y6e(r,e){let t=r.transactor||e.default_transactor||"network",n=r.keyNetwork||e.default_key_network||"libp2p",o=typeof r.port=="number"?r.port:typeof e.default_port=="number"?e.default_port:0,s=r.networkName||e.default_network_name||"optimystic",i=typeof e.rawStorageFactory=="function"?e.rawStorageFactory:void 0;return{transactor:t,keyNetwork:n,libp2pOptions:{port:o,networkName:s,bootstrapNodes:[]},rawStorageFactory:i}}function gmt(r,e){return X6e(r)===X6e(e)}function X6e(r){return JSON.stringify(r,(e,t)=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let n={};for(let o of Object.keys(t).sort())n[o]=t[o];return n}return t})}function Z6e(r){return`(${r.map(t=>t==null?"null":typeof t=="string"?JSON.stringify(t):t instanceof Uint8Array?`<blob ${t.length} bytes>`:String(t)).join(", ")})`}function ymt(r){return`(${r.map(e=>e.name).join(", ")})`}function J6e(r){return`(${r.primaryKeyDefinition.map(t=>{var n;let o=((n=r.columns[t.index])==null?void 0:n.name)??`#${t.index}`;return t.desc?`${o} desc`:o}).join(", ")})`}var bmt=class extends Q6e{collection;isInitialized=!1;initializationPromise;isProvisionallyInitialized=!1;provisionalInitPromise;declaredColumns;txnBridge;collectionFactory;options;schemaManager;rowCodec;indexManager;uniqueEnforcementIndexes=[];populatedUniqueTrees=new Set;connection;changeUnsubscribe;changeSubscribed=!1;tableSchema;constructor(r,e,t,n,o,s,i,a,c){super(r,e,t,n),this.tableSchema=o,this.declaredColumns=o.columns.length>0,this.options=s,this.collectionFactory=i,this.txnBridge=a,this.schemaManager=c,this.wantStatements=!0}async initialize(){if(this.isInitialized)return;if(this.initializationPromise)return this.initializationPromise;let r=(async()=>{if(this.provisionalInitPromise)try{await this.provisionalInitPromise}catch{}await this.doInitialize(!1)})().finally(()=>{this.initializationPromise===r&&(this.initializationPromise=void 0)});return this.initializationPromise=r,r}async initializeForCommittedRead(){if(this.isInitialized)return;if(this.initializationPromise)return this.initializationPromise;if(this.provisionalInitPromise)return this.provisionalInitPromise;if(!this.txnBridge.isTransactionActive())return this.initialize();if(this.isProvisionallyInitialized)return;let r=this.doInitialize(!0).finally(()=>{this.provisionalInitPromise=void 0});return this.provisionalInitPromise=r,r}async doInitialize(r){try{this.setErrorMessage(void 0);let e=r?null:this.txnBridge.getCurrentTransaction(),t=await this.collectionFactory.createOrGetCollection(this.options,e||void 0),n=await this.schemaManager.getSchema(this.schemaName,this.tableName,e?.transactor),o;if(this.declaredColumns){let c=this.schemaManager.tableSchemaToStored(this.tableSchema),l=n?this.schemaManager.mergeWithPersisted(c,n):c;if(!n){let u=await this.guardStorageAdoption(c,t,e?.transactor);u&&(l={...l,orphanedIndexes:u})}n&&gmt(l,n)?o=n:r?o=l:(!n&&c.indexes.length===0&&Ca("doInitialize(%s): persisting local DDL schema with no persisted catalog entry visible; if an entry exists but was unreadable, the write-time index union preserves its indexes",this.tableName),o=await this.schemaManager.storeStoredSchema(l,e?.transactor))}else if(n)this.tableSchema.columns=n.columns.map((c,l)=>({...this.schemaManager.storedToColumnSchema(c),affinity:c.affinity,index:l})),this.tableSchema.columnIndexMap=new Map(n.columns.map((c,l)=>[c.name.toLowerCase(),l])),this.tableSchema.primaryKeyDefinition=n.primaryKeyDefinition.map(c=>({index:c.index,desc:c.desc,collation:c.collation})),this.tableSchema.primaryKeyDefaultConflict=n.primaryKeyDefaultConflict,o=n;else throw new Error("Cannot create table without column definitions");this.attachPersistedUniqueConstraints(o);let s=new imt(o,this.options.encoding),i=new lmt(o,(c,l)=>this.openIndexTree(c,l));await i.initialize(e?.transactor);let a=this.buildUniqueEnforcementIndexes(o);if(await i.setUniqueEnforcementIndexes(a,e?.transactor),this.collection=t,this.rowCodec=s,this.indexManager=i,this.uniqueEnforcementIndexes=a,r){this.isProvisionallyInitialized=!0;return}this.registerCollections(),this.isProvisionallyInitialized=!1,this.isInitialized=!0,await this.ensureChangeSubscription()}catch(e){let t=Ux("Failed to initialize Optimystic table",e);throw this.setErrorMessage(t.message),t}}async guardStorageAdoption(r,e,t){let n=await this.schemaManager.getDroppedSchemaRecord(this.schemaName,this.tableName,t)??await this.schemaManager.findRecordForUri(this.options.collectionUri,t);if(!n)return;let o=g3(n.indexes,n.orphanedIndexes??[]),s=o.length>0?o:void 0;if(await this.hasNoRowsToBackfill(e))return s;let i=n.droppedAt?"a dropped table":`live table '${n.name}'`,a=new Map(n.columns.map(h=>[h.name.toLowerCase(),h])),c=r.columns.filter(h=>!a.has(h.name.toLowerCase()));if(c.length>0){let h=c.length===1?"column":"columns",p=c.map(f=>`'${f.name}'`).join(", ");throw new Error(`Cannot create table '${r.name}' over '${this.options.collectionUri}': that collection still holds rows from ${i} declared as ${ymt(n.columns)}, and this declaration adds ${h} ${p}, which those rows cannot supply. Use a different collection URI, or re-declare the columns the stored rows were written under.`)}let l=r.columns.filter(h=>{let p=a.get(h.name.toLowerCase());return p!==void 0&&p.affinity!==h.affinity});if(l.length>0){let h=l.length===1?"column":"columns",p=l.map(f=>{let g=a.get(f.name.toLowerCase());return`'${f.name}' as ${f.affinity} where the stored rows were written as ${g.affinity}`}).join(", ");throw new Error(`Cannot create table '${r.name}' over '${this.options.collectionUri}': that collection still holds rows from ${i}, and this declaration re-types ${h} ${p} \u2014 stored values are untagged, so they would be decoded as something other than what was written. Use a different collection URI, or re-declare the column types the stored rows were written under.`)}let u=J6e(r),d=J6e(n);if(u.toLowerCase()!==d.toLowerCase())throw new Error(`Cannot create table '${r.name}' over '${this.options.collectionUri}': that collection still holds rows from ${i} keyed on ${d}, and this declaration keys on ${u} \u2014 rows written under the old key can never be reached through the new one. Use a different collection URI, or re-declare the primary key the stored rows were written under.`);return s}async ensureChangeSubscription(){if(!this.changeSubscribed&&this.options.collectionUri!=="tree://optimystic/schema"){this.changeSubscribed=!0;try{let r=this.collectionFactory.getCollectionId(this.options);this.changeUnsubscribe=await this.collectionFactory.subscribeToCollectionChanges(this.options,r,e=>this.handleCollectionChange(e))}catch(r){this.changeSubscribed=!1,Ca(`WARN: failed to subscribe '${this.tableName}' to collection changes: ${r instanceof Error?r.message:String(r)}`)}}}handleCollectionChange(r){try{let e=this.db.notifyExternalChange(this.tableName,this.schemaName);e&&typeof e.catch=="function"&&e.catch(t=>{Ca(`WARN: notifyExternalChange failed for '${this.tableName}': ${t instanceof Error?t.message:String(t)}`)})}catch(e){Ca(`WARN: notifyExternalChange threw for '${this.tableName}': ${e instanceof Error?e.message:String(e)}`)}}teardownChangeSubscription(){if(this.changeUnsubscribe){try{this.changeUnsubscribe()}catch(r){Ca(`WARN: error tearing down change subscription for '${this.tableName}': ${r instanceof Error?r.message:String(r)}`)}this.changeUnsubscribe=void 0}this.changeSubscribed=!1}async disconnect(){}async ensureConnectionRegistered(){if(!this.connection){let r=this.db,e=r.getConnectionsForTable(this.tableName);e.length>0&&e[0]instanceof RJ?this.connection=e[0]:(this.connection=new RJ(this.tableName,this.txnBridge,this.options),await r.registerConnection(this.connection))}return this.connection}createConnection(){return new RJ(this.tableName,this.txnBridge,this.options)}getConnection(){return this.connection}async*query(r){yield*this.runQuery(r,!1)}async*queryCommitted(r){yield*this.runQuery(r,!0)}async*runQuery(r,e){if(e){let t=this.txnBridge.getDegradedReason();if(t!==void 0)throw new Aa(`Committed read refused: storage is in a partially-committed state and no coherent committed snapshot exists until the next successful commit or rollback. ${t}`,Ia.ERROR);await this.initializeForCommittedRead()}else await this.ensureConnectionRegistered(),this.isInitialized||await this.initialize();if(!this.collection||!this.rowCodec||!this.indexManager)throw new Error("Table not initialized");try{let t=this.parsePlanType(r.idxStr),n=this.parseIndexName(r.idxStr),o=n!=null&&n!=="_primary_",s;if(o&&r.args.length>0)s=n;else if(r.idxNum>=10&&!(t===2&&r.args.length>0)&&t!==3){if(!r.idxStr||typeof r.idxStr!="string")throw new Error("Index name not provided for index scan");s=r.idxStr}let i=this.collection,a=s!==void 0?this.resolveIndexTarget(s):void 0,c,l;if(e?(c=this.committedTreeView(i),l=a!==void 0?{...a,read:this.committedTreeView(a.tree)}:void 0):(await i.update(),c=i,a!==void 0&&(await a.tree.update(),l={...a,read:a.tree})),l!==void 0){let u=Ca.enabled?{matched:0,rejected:0}:void 0;try{yield*this.executeIndexScan(c,l,r.args,u)}finally{u!==void 0&&this.logIndexSeek(l,i,e,u)}}else t===2&&r.args.length>0?yield*this.executePointLookup(c,r.args):t===3?yield*this.executeRangeQuery(c,r):r.idxNum===1?yield*this.executePointLookup(c,r.args):r.idxNum===2?yield*this.executeRangeQuery(c,r):yield*this.executeTableScan(c)}catch(t){let n=Ux("Query failed",t);throw this.setErrorMessage(n.message),n}}resolveIndexTarget(r){if(!this.indexManager)throw new Error("Table not initialized");let e=this.indexManager.getIndexSchema(r);if(!e)throw new Aa(OJ(this.tableName,r,"it has no descriptor in this table instance's maintained index set, so writes skip it"),Ia.ERROR);let t=this.indexManager.getIndexTree(r);if(!t)throw new Aa(OJ(this.tableName,r,"its tree is not open on this table instance, so writes have nowhere to stage into"),Ia.ERROR);return{schema:e,tree:t}}logIndexSeek(r,e,t,n){let o=s=>tke(s.committedRevision()??"none",s.committedActionId()??"none");Ca("index:seek table=%s index=%s collection=%s main=%s arm=%s rev=%s main_rev=%s seek=%s matched=%d rejected=%d node=%s",this.tableName,r.schema.name,String(r.tree.getCollection().id),String(e.getCollection().id),t?"committed":"live",o(r.tree),o(e),n.key===void 0?"unset":pmt(n.key),n.matched,n.rejected,this.collectionFactory.nodeTag())}committedTreeView(r){let t=this.txnBridge.getDirtySnapshot(r)??r.snapshot();return r.readView(t)}parsePlanType(r){if(!r)return;let e=r.match(/plan=(\d+)/);return e?.[1]?parseInt(e[1],10):void 0}parseIndexName(r){if(!r)return;let e=r.match(/idx=([^(;]+)/);return e?.[1]||void 0}async*executePointLookup(r,e){if(!this.rowCodec||e.some(o=>o==null))return;let t=this.rowCodec.createPrimaryKey(this.rowCodec.asPrimaryKeyTuple(e)),n=await W6e(r,this.rowCodec,t);n!==void 0&&(yield n)}async*executeRangeQuery(r,e){yield*this.executeTableScan(r)}async*executeIndexScan(r,e,t,n){let o=this.rowCodec,s=this.indexManager;if(!o||!s||t.some(l=>l==null))return;let i=Math.min(t.length,e.schema.columns.length),a=i===0?y3([]):s.createIndexKeyFromTuple(s.asIndexColumnTuple(e.schema,t.slice(0,i)));n!==void 0&&(n.key=String(a));let c=l=>s.createIndexKey(e.schema,l);for await(let l of s.findEntriesIn(e.read,a)){n!==void 0&&n.matched++;let u=await W6e(r,o,l[1]);if(u===void 0||!pke(u,l,c)){n!==void 0&&n.rejected++;continue}yield u}}async*executeTableScan(r){if(!this.rowCodec)return;let e=5,t=0,n,o=new Set;for(;t<e;)try{let s=n?new rl({key:n,inclusive:!1},void 0,!0):new rl(void 0,void 0,!0),i=r.range(s);for await(let a of i){if(!r.isValid(a))continue;let c=r.at(a);if(c&&Array.isArray(c)&&c.length>=2){let l=c[0];if(o.has(l)){n=l;continue}let u=c[1],d=this.rowCodec.decodeRow(u);o.add(l),n=l,yield d}}return}catch(s){if((s instanceof Error?s.message:String(s)).includes("Path is invalid due to mutation")){if(t++,t>=e)throw new Error(`Table scan failed after ${e} retries due to concurrent mutations`);await new Promise(a=>setTimeout(a,50));continue}throw s}}markDirtyTrees(){if(this.collection&&this.txnBridge.markDirty(this.collection),this.indexManager)for(let r of this.indexManager.getIndexTrees())this.txnBridge.markDirty(r)}registerCollections(){if(this.collection&&(this.txnBridge.registerCollection(this.collection.getCollection()),this.txnBridge.registerKeyTakenMessage(this.collection.getCollection().id,this.uniqueConstraintMessage()),this.txnBridge.registerEntryChangedRenderer(this.collection.getCollection().id,r=>this.concurrentModificationMessage(r))),this.indexManager)for(let r of this.indexManager.getIndexTrees())this.txnBridge.registerCollection(r.getCollection());this.registerUniqueKeyTakenMessages()}registerUniqueKeyTakenMessages(){let r=this.tableSchema.uniqueConstraints;if(!(!r||r.length===0))for(let e of r){if(e.predicate!==void 0||e.columns.length===0)continue;let t=this.resolveEnforcingIndex(e);t&&this.txnBridge.registerKeyTakenMessage(t.tree.getCollection().id,this.uniqueConstraintMessage(e.columns))}}guardedUniqueIndexes(r){let e=this.tableSchema.uniqueConstraints;if(!e||e.length===0)return G6e;let t=new Set;for(let n of e){if(n.predicate!==void 0||n.columns.length===0||!n.columns.every(s=>r[s]!==null&&r[s]!==void 0))continue;let o=this.resolveEnforcingIndex(n);o&&t.add(o.descriptor.name)}return t.size===0?G6e:t}uniqueConstraintMessage(r){return`UNIQUE constraint failed: ${(r??this.tableSchema.primaryKeyDefinition.map(n=>n.index)).map(n=>{var o;return`${this.tableName}.${((o=this.tableSchema.columns[n])==null?void 0:o.name)??`col${n}`}`}).join(", ")}`}concurrentModificationMessage(r){var e;let t=((e=this.rowCodec)==null?void 0:e.decodePrimaryKey(r))??[];return`concurrent modification: another writer changed or removed the row in ${this.tableName} at primary key ${Z6e(t)}`}uniqueKeyFor(r,e){return y3(r.map(t=>e[t]??null))}attachPersistedUniqueConstraints(r){let e=this.schemaManager.storedToUniqueConstraints(r);if(!e)return;let t=this.tableSchema.uniqueConstraints??[],n=new Set(t.map(Kx)),o=e.filter(s=>!n.has(Kx(s)));o.length!==0&&(this.tableSchema={...this.tableSchema,uniqueConstraints:[...t,...o]})}buildUniqueEnforcementIndexes(r){let e=this.tableSchema.uniqueConstraints;if(!e||e.length===0)return[];let t=rh(r.primaryKeyDefinition.map(i=>i.index)),n=new Set(r.indexes.map(i=>rh(i.columns.map(a=>a.index)))),o=[],s=new Set;for(let i of e){if(i.predicate!==void 0||i.columns.length===0)continue;let a=rh(i.columns);a!==t&&(n.has(a)||s.has(a)||(s.add(a),o.push({name:nmt(i.columns.map(c=>this.columnNameAt(r,c))),columns:i.columns.map(c=>({index:c}))})))}return o}columnNameAt(r,e){let t=r.columns[e];if(t===void 0)throw new Error(`Table '${this.tableName}': unique constraint addresses column position ${e}, which is out of range for its ${r.columns.length} columns`);return t.name}resolveEnforcingIndex(r){if(!this.indexManager)return;let e=rh(r.columns);for(let t of this.indexManager.getDeclaredIndexes())if(rh(t.columns.map(n=>n.index))===e){let n=this.indexManager.getIndexTree(t.name);if(n)return{descriptor:t,tree:n,synthesized:!1}}for(let t of this.uniqueEnforcementIndexes)if(rh(t.columns.map(n=>n.index))===e){let n=this.indexManager.getIndexTree(t.name);if(n)return{descriptor:t,tree:n,synthesized:!0}}}async ensureUniquePopulated(r,e){if(this.populatedUniqueTrees.has(r.name)||!this.collection||!this.rowCodec||!this.indexManager||await this.hasNoRowsToBackfill())return;await e.update(),e.at(await e.first())===void 0&&await this.populateUniqueTree(r,e),this.populatedUniqueTrees.add(r.name)}async populateUniqueTree(r,e){if(!(!this.collection||!this.rowCodec||!this.indexManager)){await this.collection.update();for await(let{row:t,primaryKey:n}of MJ(this.collection,this.rowCodec)){if(mke(r,t))continue;let o=ed(this.indexManager.createIndexKey(r,t),n);await e.stage([[o,[o,n]]])}await e.sync()}}async scanUniqueConstraint(r,e,t){if(!this.collection||!this.rowCodec)return[];let n=this.uniqueKeyFor(r.columns,e),o=[];for await(let s of this.collection.range(new rl(void 0,void 0,!0))){if(!this.collection.isValid(s))continue;let i=this.collection.at(s);if(!i||i.length<2||t?.has(i[0]))continue;let a=this.rowCodec.decodeRow(i[1]);this.uniqueKeyFor(r.columns,a)===n&&o.push({pk:i[0],row:a,entry:i})}return o}async probeUniqueConstraint(r,e,t){if(!this.collection||!this.rowCodec||!this.indexManager)return[];let n=this.resolveEnforcingIndex(r);if(!n)return Ca(`WARN: no enforcing index for UNIQUE(${r.columns.join(",")}) on '${this.tableName}'; falling back to full scan`),this.scanUniqueConstraint(r,e,t);let{descriptor:o,tree:s,synthesized:i}=n;i&&await this.ensureUniquePopulated(o,s),await s.update();let a=this.indexManager.createIndexKey(o,e),c=[];for await(let l of this.indexManager.findByIndexIn(s,a)){if(t?.has(l))continue;let u=await this.collection.get(l);!u||u.length<2||c.push({pk:l,row:this.rowCodec.decodeRow(u[1]),entry:u})}return c}resolveConflictAction(r,e){return r??e??Bm.ABORT}pkDeclaredConflict(){if(this.tableSchema.primaryKeyDefaultConflict!==void 0)return this.tableSchema.primaryKeyDefaultConflict;for(let r of this.tableSchema.primaryKeyDefinition){let e=this.tableSchema.columns[r.index];if(e?.defaultConflict!==void 0)return e.defaultConflict}}async resolvePkMoveDecision(r,e){if(!this.collection||!this.rowCodec)throw new Error("Table not initialized");let t=await this.collection.get(r);if(t===void 0)return{kind:"clear"};let n=this.rowCodec.decodeRow(t[1]),o=this.resolveConflictAction(e,this.pkDeclaredConflict());return o===Bm.IGNORE?{kind:"swallow"}:o===Bm.REPLACE?{kind:"displace",row:n,entry:t}:{kind:"blocked",result:{status:"constraint",constraint:"unique",message:this.uniqueConstraintMessage(),existingRow:n}}}async resolveSecondaryUniqueDecision(r,e,t){let n=this.tableSchema.uniqueConstraints;if(!n||n.length===0)return{kind:"clear"};if(!this.collection||!this.rowCodec||!this.indexManager)return{kind:"clear"};let o=n.filter(i=>i.predicate===void 0&&i.columns.length>0&&i.columns.every(a=>r[a]!==null&&r[a]!==void 0)),s=new Map;for(let i of o){let a=await this.probeUniqueConstraint(i,r,t);if(a.length===0)continue;let c=this.resolveConflictAction(e,i.defaultConflict);if(c===Bm.IGNORE)return{kind:"swallow"};if(c===Bm.REPLACE){for(let l of a)s.set(l.pk,l);continue}return{kind:"blocked",result:{status:"constraint",constraint:"unique",message:this.uniqueConstraintMessage(i.columns),existingRow:a[0].row}}}return s.size>0?{kind:"evict",collisions:[...s.values()]}:{kind:"clear"}}async applyUniqueEvictions(r,e){if(!this.collection||!this.indexManager)throw new Error("Table not initialized");let t=[];for(let{pk:n,row:o,entry:s}of r)await this.collection.stage([[n,void 0,Fx(s)]]),await this.indexManager.deleteIndexEntries(o,n,e),t.push(o);return t}async requirePreWriteRow(r,e,t){if(!this.collection||!this.rowCodec)throw new Error("Table not initialized");let n=await this.collection.get(e);if(!n)throw new Aa(`${r} could not find the pre-write row in table ${this.tableSchema.name} at primary key ${Z6e(t)} \u2014 the engine and the collection disagree about what exists.`,Ia.ERROR);return{row:this.rowCodec.decodeRow(n[1]),entry:n}}async update(r){let{operation:e,values:t,mutationStatement:n}=r;if(await this.ensureConnectionRegistered(),this.isInitialized||await this.initialize(),!this.collection||!this.rowCodec||!this.indexManager)throw new Error("Table not initialized");n&&await this.txnBridge.addStatement(n);let o=this.txnBridge.getCurrentTransaction();try{switch(e){case"insert":if(!t)throw new Error("INSERT requires values");{let s=this.rowCodec.extractPrimaryKey(t),i=await this.collection.get(s);if(i!==void 0){let u=this.rowCodec.decodeRow(i[1]),d=this.resolveConflictAction(r.onConflict,this.pkDeclaredConflict());if(d===Bm.IGNORE)return{status:"ok"};if(d===Bm.REPLACE){let h=await this.resolveSecondaryUniqueDecision(t,r.onConflict,new Set([s]));if(h.kind==="blocked")return h.result;if(h.kind==="swallow")return{status:"ok"};let p=this.rowCodec.encodeRow(t);this.markDirtyTrees();let f=h.kind==="evict"?await this.applyUniqueEvictions(h.collisions,o?.transactor):[];return await this.collection.stage([[s,[s,p],Fx(i)]]),await this.indexManager.updateIndexEntries(u,t,s,s,o?.transactor,this.guardedUniqueIndexes(t)),{status:"ok",row:t,replacedRow:u,...f.length>0?{evictedRows:f}:{}}}return{status:"constraint",constraint:"unique",message:this.uniqueConstraintMessage(),existingRow:u}}let a=await this.resolveSecondaryUniqueDecision(t,r.onConflict);if(a.kind==="blocked")return a.result;if(a.kind==="swallow")return{status:"ok"};let c=this.rowCodec.encodeRow(t);this.markDirtyTrees();let l=a.kind==="evict"?await this.applyUniqueEvictions(a.collisions,o?.transactor):[];return await this.collection.stage([[s,[s,c],{kind:"absent"}]]),await this.indexManager.insertIndexEntries(t,s,o?.transactor,this.guardedUniqueIndexes(t)),{status:"ok",row:t,...l.length>0?{evictedRows:l}:{}}}case"update":if(!t)throw new Error("UPDATE requires values");if(!r.oldKeyValues)throw new Error("UPDATE requires old key values");{let s=this.rowCodec.asPrimaryKeyTuple(r.oldKeyValues),i=this.rowCodec.createPrimaryKey(s),a=this.rowCodec.extractPrimaryKey(t),c=this.rowCodec.encodeRow(t),{row:l,entry:u}=await this.requirePreWriteRow("UPDATE",i,s),d=i!==a?await this.resolvePkMoveDecision(a,r.onConflict):{kind:"clear"};if(d.kind==="blocked")return d.result;if(d.kind==="swallow")return{status:"ok"};let h=new Set([i]);d.kind==="displace"&&h.add(a);let p=await this.resolveSecondaryUniqueDecision(t,r.onConflict,h);if(p.kind==="blocked")return p.result;if(p.kind==="swallow")return{status:"ok"};this.markDirtyTrees();let f=p.kind==="evict"?await this.applyUniqueEvictions(p.collisions,o?.transactor):[],g=d.kind==="displace"?Fx(d.entry):{kind:"absent"};return await this.collection.stage(i!==a?[[i,void 0,Fx(u)],[a,[a,c],g]]:[[a,[a,c],Fx(u)]]),d.kind==="displace"&&await this.indexManager.deleteIndexEntries(d.row,a,o?.transactor),await this.indexManager.updateIndexEntries(l,t,i,a,o?.transactor,this.guardedUniqueIndexes(t)),{status:"ok",row:t,...d.kind==="displace"?{replacedRow:d.row}:{},...f.length>0?{evictedRows:f}:{}}}case"delete":if(!r.oldKeyValues)throw new Error("DELETE requires old key values");{let s=this.rowCodec.asPrimaryKeyTuple(r.oldKeyValues),i=this.rowCodec.createPrimaryKey(s),{row:a,entry:c}=await this.requirePreWriteRow("DELETE",i,s);return this.markDirtyTrees(),await this.collection.stage([[i,void 0,Fx(c)]]),await this.indexManager.deleteIndexEntries(a,i,o?.transactor),{status:"ok"}}default:throw new Error(`Unsupported operation: ${e}`)}}catch(s){if(s instanceof Aa)throw s;let i=this.txnBridge.mapCommitRefusal(s);if(i!==s&&i instanceof Error)throw this.setErrorMessage(i.message),i;let a=Ux(`${e} failed`,s);throw this.setErrorMessage(a.message),a}}mirrorDerivedUniqueConstraint(r){if(!r.unique)return;let e={columns:r.columns.map(o=>o.index),predicate:r.predicate,derivedFromIndex:r.name},t=Kx(e);(this.tableSchema.uniqueConstraints??[]).some(o=>o.derivedFromIndex===r.name||Kx(o)===t)||(this.tableSchema={...this.tableSchema,uniqueConstraints:[...this.tableSchema.uniqueConstraints??[],e]})}async addIndex(r,e){if(this.isInitialized||await this.initialize(),!this.schemaManager||!this.indexManager)throw new Error("Table not initialized");let t=await this.schemaManager.getSchemaFresh(this.schemaName,this.tableName);if(!t)throw new Error("Schema not found");let n=this.txnBridge.getCurrentTransaction(),o=t.indexes.find(l=>l.name===r.name);if(o||await this.guardIndexAdoption(r,t,n?.transactor),this.mirrorDerivedUniqueConstraint(r),o){let l=t;if(r.unique&&!o.unique){let{unique:d,predicate:h}=this.schemaManager.indexSchemaToStored(r),p={...t,indexes:t.indexes.map(f=>f.name===r.name?{...f,unique:d,predicate:h}:f)};l=await this.schemaManager.storeStoredSchema(p,n?.transactor)}let u=await this.reconcileMaintainedIndexes(l,n?.transactor);l!==t&&this.indexManager.setSchema(l),await this.backfillIndexTrees(u,e),this.registerUniqueKeyTakenMessages();return}let s={...t,indexes:[...t.indexes,this.schemaManager.indexSchemaToStored(r)]},i=await this.schemaManager.storeStoredSchema(s,n?.transactor),a=await this.openIndexTree(r.name,n?.transactor);this.indexManager.registerIndexTree(r.name,a);let c=await this.reconcileMaintainedIndexes(i,n?.transactor);await this.backfillIndexTrees(c,e),this.registerUniqueKeyTakenMessages()}async removeIndex(r){if(this.isInitialized||await this.initialize(),!this.schemaManager||!this.indexManager)throw new Error("Table not initialized");let e=this.txnBridge.getCurrentTransaction();await this.schemaManager.removeIndex(this.schemaName,this.tableName,r,e?.transactor);let t=this.indexManager.unregisterIndex(r);t&&this.txnBridge.forgetTree(t);let n=r.toLowerCase(),o=(this.tableSchema.uniqueConstraints??[]).filter(s=>{var i;return((i=s.derivedFromIndex)==null?void 0:i.toLowerCase())!==n});this.tableSchema={...this.tableSchema,indexes:(this.tableSchema.indexes??[]).filter(s=>s.name.toLowerCase()!==n),uniqueConstraints:o.length>0?o:void 0},await this.reassignUniqueEnforcement(e?.transactor)}async reassignUniqueEnforcement(r){if(!this.indexManager||!this.schemaManager)return;let e={...this.schemaManager.tableSchemaToStored(this.tableSchema),indexes:this.indexManager.getDeclaredIndexes()},t=new Set(this.uniqueEnforcementIndexes.map(o=>o.name)),n=this.buildUniqueEnforcementIndexes(e).filter(o=>!t.has(o.name));if(n.length!==0){await this.indexManager.setUniqueEnforcementIndexes([...this.uniqueEnforcementIndexes,...n],r);for(let o of n){let s=this.indexManager.getIndexTree(o.name);if(!s)throw new Error(`Index tree not found: ${o.name}`);this.txnBridge.registerCollection(s.getCollection()),await this.populateUniqueTree(o,s),this.populatedUniqueTrees.add(o.name),this.uniqueEnforcementIndexes=[...this.uniqueEnforcementIndexes,o]}this.registerUniqueKeyTakenMessages()}}async addCheckConstraint(r){var e;this.isInitialized||await this.initialize();let t=this.txnBridge.getCurrentTransaction(),n=await this.schemaManager.getSchemaFresh(this.schemaName,this.tableName,t?.transactor);if(!n)throw new Error(`Schema not found for Optimystic table '${this.schemaName}.${this.tableName}'. Cannot add CHECK constraint.`);await this.schemaManager.storeStoredSchema(this.schemaManager.withCheckConstraint(n,r),t?.transactor);let o=(e=r.name)==null?void 0:e.toLowerCase();this.tableSchema={...this.tableSchema,checkConstraints:[...this.tableSchema.checkConstraints.filter(s=>{var i;return o===void 0||((i=s.name)==null?void 0:i.toLowerCase())!==o}),r]}}async guardIndexAdoption(r,e,t){let n=(e.orphanedIndexes??[]).find(c=>c.name===r.name);if(!n)return;let o=r.columns.map(c=>{var l;return((l=this.tableSchema.columns[c.index])==null?void 0:l.name)??`#${c.index}`}),s=n.columns.map(c=>c.name);if(o.length===s.length&&o.every((c,l)=>c.toLowerCase()===s[l].toLowerCase()))return;let a=await this.openIndexTree(r.name,t);if(a.at(await a.first())!==void 0)throw new Error(`Cannot create index '${r.name}' over '${this.options.collectionUri}/index/${r.name}': that collection still holds entries from a dropped index of the same name declared on (${s.join(", ")}), not (${o.join(", ")}). Use a different index name, or a different collection URI for the table.`)}async backfillIndexTrees(r,e){if(r.length===0||!this.collection||!this.rowCodec||!this.indexManager)return;let t=this.indexManager,n=this.collection,o=this.rowCodec,s=r.map(a=>{let c=t.getIndexSchema(a),l=t.getIndexTree(a);if(!c||!l)throw new Error(`Cannot populate index '${a}' on '${this.tableName}': ${c?"tree":"descriptor"} not registered`);return{name:a,descriptor:c,tree:l}}),i=!1;if(!await this.hasNoRowsToBackfill()){await n.update();for await(let{row:a,primaryKey:c}of MJ(n,o)){for(let{descriptor:l,tree:u}of s){let d=ed(t.createIndexKey(l,a),c);await u.stage([[d,[d,c]]])}i=!0}}if(e){for(let{name:a,tree:c}of s)!i&&c.committedRevision()===void 0||c.hasUnsyncedChanges()&&e(a,c);return}await this.flushDirtyTrees(s)}async hasNoRowsToBackfill(r=this.collection){return r?r.at(await r.first())===void 0:!0}async verifyIndexes(){if(!this.collection||!this.rowCodec||!this.indexManager)throw new Error("Table not initialized");let r=this.indexManager,e=new Set(r.getDeclaredIndexes().map(s=>s.name)),t=r.getAllMaintainedIndexes().map(s=>{let i=r.getIndexTree(s.name);if(!i)throw new Error(`Index tree not found: ${s.name}`);return{index:s,tree:i}});await this.collection.update();for(let{tree:s}of t)await s.update();let n=new Map;for await(let{row:s,primaryKey:i}of MJ(this.collection,this.rowCodec))n.set(i,s);let o=[];for(let{index:s,tree:i}of t){let a=[];for await(let c of r.allEntriesIn(i))a.push(c);o.push(umt({table:this.tableName,index:s,kind:e.has(s.name)?"declared":"unique-enforcement",rows:n,entries:a,indexKeyOf:c=>r.createIndexKey(s,c)}))}return o}async flushDirtyTrees(r){for(let{tree:e}of r)e.hasUnsyncedChanges()&&await e.sync()}async openIndexTree(r,e){let t=`${this.options.collectionUri}/index/${r}`,n={...this.options,collectionUri:t},o=await this.collectionFactory.createOrGetCollection(n,e?{transactor:e,isActive:!0,collections:new Map,stampId:""}:void 0);return Ca("index:tree-open table=%s index=%s uri=%s collection=%s node=%s",this.tableName,r,t,String(o.getCollection().id),this.collectionFactory.nodeTag()),o}async reconcileMaintainedIndexes(r,e){if(!this.indexManager)throw new Error("Table not initialized");let t=this.indexManager,n=r.indexes.filter(o=>t.getIndexSchema(o.name)===void 0||t.getIndexTree(o.name)===void 0).map(o=>o.name);r.indexes.some(o=>t.getIndexSchema(o.name)===void 0)&&t.setSchema(r);for(let o of r.indexes){let s=t.getIndexTree(o.name);s||(s=await this.openIndexTree(o.name,e),t.registerIndexTree(o.name,s)),this.txnBridge.registerCollection(s.getCollection())}return n}indexMaintenanceState(r){return!this.indexManager||!this.isInitialized&&!this.isProvisionallyInitialized?"unknown":this.indexManager.getIndexSchema(r)===void 0||this.indexManager.getIndexTree(r)===void 0?"unmaintained":"maintained"}async begin(){try{await this.ensureConnectionRegistered(),await this.txnBridge.beginTransaction(this.options)}catch(r){let e=Ux("Begin transaction failed",r);throw this.setErrorMessage(e.message),e}}async commit(){try{await this.txnBridge.commitTransaction()}catch(r){let e=Ux("Commit transaction failed",r);throw this.setErrorMessage(e.message),e}}async rollback(){try{await this.txnBridge.rollbackTransaction()}catch(r){let e=Ux("Rollback transaction failed",r);throw this.setErrorMessage(e.message),e}}async deleteOwnSchema(){let r=this.txnBridge.getCurrentTransaction();await this.schemaManager.deleteSchema(this.schemaName,this.tableName,r?.transactor)}get catalogManager(){return this.schemaManager}markSchemaUnpersisted(r=new Set){if(this.indexManager){let e=this.indexManager.getDeclaredIndexes().filter(t=>!r.has(t.name));this.tableSchema={...this.tableSchema,indexes:this.schemaManager.storedIndexesToIndexSchemas(e)},r.size>0&&this.tableSchema.uniqueConstraints&&(this.tableSchema={...this.tableSchema,uniqueConstraints:this.tableSchema.uniqueConstraints.filter(t=>t.derivedFromIndex===void 0||!r.has(t.derivedFromIndex))})}this.isInitialized=!1,this.isProvisionallyInitialized=!1}},wmt=class extends Q6e{constructor(r){super(r.db,r.module,r.schemaName,r.tableName),this.inner=r,this.tableSchema=r.tableSchema}async*query(r){yield*this.inner.queryCommitted(r)}async update(){throw new Aa("Cannot modify committed-state snapshot",Ia.ERROR)}createConnection(){throw new Aa("A committed-read (_readCommitted) table cannot create a transaction connection",Ia.MISUSE)}getConnection(){}async disconnect(){}},xmt=class{constructor(r,e){this.collectionFactory=r,this.txnBridge=e}concurrencyMode="reentrant-reads";readCommittedSnapshot=!0;tables=new Map;schemaManagers=new Map;schemaBatch;createSchemaManager(r){var e,t;let n=[r.transactor??"",r.keyNetwork??"",((e=r.libp2pOptions)==null?void 0:e.networkName)??"",((t=r.libp2pOptions)==null?void 0:t.port)??0,r.rawStorageFactory?"1":"0"].join("|"),o=this.schemaManagers.get(n);if(o)return o;let s=new smt(async(i,a)=>{let c={collectionUri:"tree://optimystic/schema",transactor:r.transactor,keyNetwork:r.keyNetwork,libp2p:r.libp2p,libp2pOptions:r.libp2pOptions,cache:!0,encoding:"json",rawStorageFactory:r.rawStorageFactory},l=i?{transactor:i,isActive:!0,collections:new Map,stampId:""}:void 0;return a?await this.collectionFactory.createOrGetCollection(c,l):await this.collectionFactory.getCollection(c,l)});return this.schemaManagers.set(n,s),this.schemaBatch&&(s.beginBatch(),this.schemaBatch.managers.add(s)),s}async beginSchemaBatch(r,e){if(this.schemaBatch)throw new Error("Optimystic schema batch already open: beginSchemaBatch without a matching endSchemaBatch");let t=new Set;for(let n of this.schemaManagers.values())n.beginBatch(),t.add(n);this.schemaBatch={managers:t,written:new Map,dropped:new Map,deferred:new Map}}async endSchemaBatch(r,e,t){var n;let o=this.schemaBatch;if(!o)throw new Error("Optimystic schema batch is not open: endSchemaBatch without a matching beginSchemaBatch");this.schemaBatch=void 0;let s=!1,i;for(let a of o.managers){let c=new Map(o.deferred.get(a)),l="index-tree flush";try{for(let u of[...c.keys()])u.hasUnsyncedChanges()&&await u.sync(),c.delete(u);l="catalog commit",await a.commitBatch()}catch(u){a.discardBatch();let d=new Map;for(let{tableKey:f,indexName:g}of c.values())d.set(f,(d.get(f)??new Set).add(g));let h=[...o.written.get(a)??[]],p=[...o.dropped.get(a)??[]];for(let f of h)(n=this.tables.get(f))==null||n.markSchemaUnpersisted(d.get(f));Ca("endSchemaBatch: %s failed: %s. The catalog batch was not committed. %d table(s) will re-persist their schema on next touch (%s), without the %d index(es) whose tree did not land (%s); %d dropped table(s) keep a live catalog record past their DROP \u2014 the next hydrate resurrects them and a later CREATE over the same URI is not checked against them (%s)",l,u,h.length,h.join(", "),c.size,[...c.values()].map(({tableKey:f,indexName:g})=>`${f}.${g}`).join(", "),p.length,p.join(", ")),s||(s=!0,i=u)}}if(s)throw i}async underBatchCheckpoint(r,e,t,n){let o=this.schemaBatch;if(!o)return n();let s=r.catalogManager,i=s.checkpointBatch();try{let a=await n(),c=o[e].get(s)??new Set;return c.add(t),o[e].set(s,c),a}catch(a){throw i&&s.restoreBatch(i),a}}parseTableSchema(r){let e=r.vtabArgs||{},t=r.vtabAuxData??{};return{collectionUri:e[0]||lke(r.schemaName,r.name),...Y6e(e,t),cache:e.cache!==!1,encoding:e.encoding||"json"}}async instantiateTable(r,e,t){let n=`${e.schemaName}.${e.name}`.toLowerCase(),o=this.tables.get(n);if(o)return o;let s=t??this.parseTableSchema(e),i=this.createSchemaManager(s),a=new bmt(r,this,e.schemaName||"main",e.name,e,s,this.collectionFactory,this.txnBridge,i);return this.tables.set(n,a),a}async create(r,e){let t=`${e.schemaName}.${e.name}`.toLowerCase();if(this.tables.has(t))throw new Error(`Optimystic table '${e.name}' already exists in schema '${e.schemaName}'.`);let n=await this.instantiateTable(r,e);try{await this.underBatchCheckpoint(n,"written",t,async()=>{await n.initialize(),await n.ensureConnectionRegistered()})}catch(o){throw this.tables.delete(t),n.teardownChangeSubscription(),o}return n}async connect(r,e,t,n,o,s,i){let a=s?._readCommitted===!0,c=await this.resolveConnectedTable(r,n,o,a,i);return a?new wmt(c):c}async verifyIndexes(r,e,t="main"){var n;let o=r.schemaManager.findTable(e,t);if(o&&(o.vtabModule??((n=r.schemaManager.getModule(o.vtabModuleName))==null?void 0:n.module))!==this)throw new Error(`Cannot verify indexes of '${t}.${e}': it is not an Optimystic table (module '${o.vtabModuleName}').`);return await(await this.resolveConnectedTable(r,t,e,!1)).verifyIndexes()}async resolveConnectedTable(r,e,t,n,o){let s=await this.lookupOrInstantiate(r,e,t,o);if(!s)throw new Error(`Optimystic table definition for '${t}' not found. Cannot connect.`);let{table:i,fresh:a}=s;return n?await i.initializeForCommittedRead():(await i.initialize(),a&&await i.ensureConnectionRegistered()),i}async lookupOrInstantiate(r,e,t,n){let o=`${e}.${t}`.toLowerCase(),s=this.tables.get(o);if(s)return{table:s,fresh:!1};let i=n??r.schemaManager.findTable(t,e);if(i)return{table:await this.instantiateTable(r,i),fresh:!0}}async hydrateCatalog(r,e={},t){var n;let o=this.sessionDefaultVtabArgs(r),s=this.deriveDefaultOptions(e,o),i=this.createSchemaManager(s),a;try{a=await i.listTables()}catch(u){let d=u instanceof Error?u.message:String(u);if(/not found|missing|empty/i.test(d))return{tables:0,indexes:0};throw u}let c=0,l=0;for(let{schemaName:u,tableName:d}of a){let h=r.schemaManager.getSchema(u);if(h?.getTable(d))continue;let p=await i.getSchema(u,d);if(!p)continue;let f=i.storedToTableSchema(p,this,t,o);(h??r.schemaManager.addSchema(u)).addTable(f),c++,l+=((n=f.indexes)==null?void 0:n.length)??0}return{tables:c,indexes:l}}sessionDefaultVtabArgs(r){var e;let{name:t,args:n}=r.schemaManager.getDefaultVTabModule();return((e=r.schemaManager.getModule(t))==null?void 0:e.module)===this?n:{}}deriveDefaultOptions(r,e={}){return{collectionUri:"tree://optimystic/schema",...Y6e(e,r),cache:!0,encoding:"json"}}async createIndex(r,e,t,n){let o=`${e}.${t}`.toLowerCase(),s=await this.lookupOrInstantiate(r,e,t);if(!s)throw new Error(`Optimystic table '${t}' not found in schema '${e}'. Cannot create index.`);let{table:i,fresh:a}=s,c=this.schemaBatch,l=c?(u,d)=>{let h=i.catalogManager,p=c.deferred.get(h)??new Map;c.deferred.set(h,p.set(d,{tableKey:o,indexName:u}))}:void 0;await this.underBatchCheckpoint(i,"written",o,async()=>{a&&(await i.initialize(),await i.ensureConnectionRegistered()),await i.addIndex(n,l)})}async dropIndex(r,e,t,n){var o;let s=`${e}.${t}`.toLowerCase(),i=await this.lookupOrInstantiate(r,e,t);if(!i)throw new Error(`Optimystic table '${t}' not found in schema '${e}'. Cannot drop index.`);let{table:a,fresh:c}=i;await this.underBatchCheckpoint(a,"written",s,async()=>{c&&(await a.initialize(),await a.ensureConnectionRegistered()),await a.removeIndex(n)});let l=(o=this.schemaBatch)==null?void 0:o.deferred.get(a.catalogManager);if(l){let u=n.toLowerCase();for(let[d,h]of l)h.tableKey===s&&h.indexName.toLowerCase()===u&&l.delete(d)}}async alterTable(r,e,t,n){let o=r.schemaManager.findTable(t,e);if(!o)throw new Aa(`Optimystic table '${t}' not found in schema '${e}'. Cannot alter.`,Ia.ERROR);let s=i=>{throw new Aa(`Module for table '${o.name}' does not support ${i}`,Ia.UNSUPPORTED)};switch(n.type){case"addConstraint":return n.constraint.type==="check"?await this.addCheckConstraint(r,o,n.constraint):s("ADD CONSTRAINT");case"renameColumn":return mmt(o,n.oldName,n.newName);case"addColumn":return s("ALTER TABLE ADD COLUMN");case"dropColumn":return s("ALTER TABLE DROP COLUMN");case"dropConstraint":return s("ALTER TABLE DROP CONSTRAINT");case"renameConstraint":return s("ALTER TABLE RENAME CONSTRAINT");case"alterColumn":return s("ALTER COLUMN");case"alterPrimaryKey":return s("ALTER PRIMARY KEY")}}async addCheckConstraint(r,e,t){let n=Lpt(t,e.checkConstraints.length,Mpt(e)),{schemaName:o,name:s}=e,i=`${o}.${s}`.toLowerCase(),a=await this.lookupOrInstantiate(r,o,s,e);if(!a)throw new Error(`Optimystic table '${s}' not found in schema '${o}'. Cannot add CHECK constraint.`);let{table:c,fresh:l}=a;return await this.underBatchCheckpoint(c,"written",i,async()=>{l&&(await c.initialize(),await c.ensureConnectionRegistered()),await c.addCheckConstraint(n)}),{...e,checkConstraints:Object.freeze([...e.checkConstraints,n])}}getBestAccessPlan(r,e,t){let n=t.estimatedRows||1e6,s=Math.max(1e3,n),i=n,a=t.filters.map(()=>!1),c,l=!1,u=`Full table scan (${n} rows)`,d,h,p=e.primaryKeyDefinition.map(g=>g.index),f=p.length>0&&p.every(g=>t.filters.some(y=>y&&y.usable&&y.op==="="&&y.columnIndex===g));for(let g=0;g<t.filters.length;g++){let y=t.filters[g];if(!y||!y.usable)continue;let m=p.includes(y.columnIndex);if(m&&y.op==="="&&f){let w=Math.log2(Math.max(2,n))*2;s=w,i=1,a=t.filters.map(b=>b!=null&&b.usable&&b.op==="="&&p.includes(b.columnIndex)),l=!0,d="_primary_",h=[...p],u=`Primary key equality seek (cost: ${w.toFixed(2)})`,t.requiredOrdering&&t.requiredOrdering.length>0&&(c=[...t.requiredOrdering]);break}else if(m&&y.op==="="&&!f){let w=n*.3;w<s&&(s=w,i=Math.max(1,Math.floor(n*.3)),a=t.filters.map(()=>!1),l=!1,u=`Partial primary key scan (cost: ${w.toFixed(2)})`)}else if(m&&[">",">=","<","<="].includes(y.op)){let b=Math.log2(Math.max(2,n))*2+n*.25,x=Math.floor(n*.25);b<s&&(s=b,i=x,a=t.filters.map(()=>!1),u=`Primary key range scan (selectivity: ${.25.toFixed(2)}, cost: ${b.toFixed(2)})`)}}if(s>10&&e.indexes&&e.indexes.length>0)for(let g of e.indexes){let y=g.columns.map(b=>b.index),m=1,w=[];for(let b=0;b<y.length;b++){let x=y[b],S=!1;for(let T=0;T<t.filters.length;T++){let A=t.filters[T];if(!(!A||!A.usable)&&A.columnIndex===x&&A.op==="="){w.push(T),S=!0,m*=.1;break}}if(!S)break}if(w.length>0){let b=Math.log2(Math.max(2,n))*2+n*m,x=Math.max(1,Math.floor(n*m));b<s&&(s=b,i=x,a=t.filters.map((S,T)=>w.includes(T)),l=!1,d=g.name,h=w.map(S=>t.filters[S].columnIndex),u=`Index seek on ${g.name} (selectivity: ${m.toFixed(4)}, cost: ${b.toFixed(2)})`,t.requiredOrdering&&this.orderingMatchesIndex(t.requiredOrdering,g,e)&&(c=[...t.requiredOrdering]))}}return d!==void 0&&d!=="_primary_"&&this.assertIndexMaintained(e,d),{handledFilters:a,cost:s,rows:i,providesOrdering:c,indexName:d,seekColumnIndexes:h,isSet:l,explains:u}}assertIndexMaintained(r,e){var t;let n=`${r.schemaName}.${r.name}`.toLowerCase();if((((t=this.tables.get(n))==null?void 0:t.indexMaintenanceState(e))??"unknown")==="unmaintained")throw new Aa(OJ(r.name,e,"the catalog offers it to query planning, but this table instance's writes do not keep it up to date"),Ia.ERROR)}orderingMatchesIndex(r,e,t){if(r.length>e.columns.length)return!1;for(let n=0;n<r.length;n++){let o=r[n],s=e.columns[n];if(!o||!s||o.columnIndex!==s.index||!this.treeDeliversOrdering(o,t))return!1}return!0}treeDeliversOrdering(r,e){var t;if(r.desc)return!1;let n=e.columns[r.columnIndex];return!(!n||((t=n.logicalType)==null?void 0:t.physicalType)!==Bpt.TEXT||(n.collation||"BINARY").toUpperCase()!=="BINARY")}async destroy(r,e,t,n,o){let s=`${n}.${o}`.toLowerCase(),i=this.tables.get(s)??await this.instantiateForTeardown(r,n,o);if(i){i.teardownChangeSubscription();try{await this.underBatchCheckpoint(i,"dropped",s,()=>i.deleteOwnSchema())}catch(a){Ca("destroy(%s.%s): gravestone write failed; the catalog record outlives its DROP and a later CREATE over the same URI will not be checked against it: %s",n,o,a)}}this.tables.delete(s)}async instantiateForTeardown(r,e,t){let n=r.schemaManager.findTable(t,e);if(n)try{return await this.instantiateTable(r,n)}catch{return}}};function vmt(r){return function(){let t=r.getCurrentTransaction();return!t||!t.isActive?null:t.stampId}}var Emt=b3("plugin");function KJ(r,e={}){e.debug&&Emt("Optimystic plugin loading with config: %o",e);let t=new zpt,n=new Gpt(t),o=new xmt(t,n),s=vmt(n);return{vtables:[{name:"optimystic",module:o,auxData:e}],functions:[{schema:{name:"StampId",numArgs:0,flags:1,returnType:{typeClass:"scalar",logicalType:Opt,nullable:!0,isReadOnly:!0},implementation:s}}],collations:[],collectionFactory:t,txnBridge:n,hydrate:i=>o.hydrateCatalog(i,e,e),verifyIndexes:(i,a,c)=>o.verifyIndexes(i,a,c),dispose:()=>t.dispose()}}var bke=` table Header (
47
47
  Id text, -- UUID of this network - generated at inception - immutable
48
48
 
49
49
  -- Types: 'o' = Open, 'c' = Closed