@did-btcr2/method 0.59.0 → 0.60.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.
package/dist/browser.mjs CHANGED
@@ -1,6 +1,6 @@
1
- var sB=Object.create;var ty=Object.defineProperty;var cB=Object.getOwnPropertyDescriptor;var aB=Object.getOwnPropertyNames;var uB=Object.getPrototypeOf,dB=Object.prototype.hasOwnProperty;var fB=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Sf=(t,e)=>{for(var r in e)ty(t,r,{get:e[r],enumerable:!0})},lB=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of aB(e))!dB.call(t,i)&&i!==r&&ty(t,i,{get:()=>e[i],enumerable:!(n=cB(e,i))||n.enumerable});return t};var Pn=(t,e,r)=>(r=t!=null?sB(uB(t)):{},lB(e||!t||!t.__esModule?ty(r,"default",{value:t,enumerable:!0}):r,t));var ox=oe(Af=>{"use strict";l();Af.byteLength=pB;Af.toByteArray=gB;Af.fromByteArray=bB;var Mn=[],Wr=[],hB=typeof Uint8Array<"u"?Uint8Array:Array,ry="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(hs=0,nx=ry.length;hs<nx;++hs)Mn[hs]=ry[hs],Wr[ry.charCodeAt(hs)]=hs;var hs,nx;Wr[45]=62;Wr[95]=63;function ix(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function pB(t){var e=ix(t),r=e[0],n=e[1];return(r+n)*3/4-n}function yB(t,e,r){return(e+r)*3/4-r}function gB(t){var e,r=ix(t),n=r[0],i=r[1],o=new hB(yB(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Wr[t.charCodeAt(a)]<<18|Wr[t.charCodeAt(a+1)]<<12|Wr[t.charCodeAt(a+2)]<<6|Wr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Wr[t.charCodeAt(a)]<<2|Wr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Wr[t.charCodeAt(a)]<<10|Wr[t.charCodeAt(a+1)]<<4|Wr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function mB(t){return Mn[t>>18&63]+Mn[t>>12&63]+Mn[t>>6&63]+Mn[t&63]}function wB(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(mB(n));return i.join("")}function bB(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(wB(t,s,s+o>c?c:s+o));return n===1?(e=t[r-1],i.push(Mn[e>>2]+Mn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Mn[e>>10]+Mn[e>>4&63]+Mn[e<<2&63]+"=")),i.join("")}});var sx=oe(ny=>{l();ny.read=function(t,e,r,n,i){var o,s,c=i*8-n-1,a=(1<<c)-1,u=a>>1,d=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,o=p&(1<<-d)-1,p>>=-d,d+=c;d>0;o=o*256+t[e+f],f+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=n;d>0;s=s*256+t[e+f],f+=h,d-=8);if(o===0)o=1-u;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-u}return(p?-1:1)*s*Math.pow(2,o-n)};ny.write=function(t,e,r,n,i,o){var s,c,a,u=o*8-i-1,d=(1<<u)-1,f=d>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,g=n?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(c=isNaN(e)?1:0,s=d):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),s+f>=1?e+=h/a:e+=h*Math.pow(2,1-f),e*a>=2&&(s++,a/=2),s+f>=d?(c=0,s=d):s+f>=1?(c=(e*a-1)*Math.pow(2,i),s=s+f):(c=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=c&255,p+=g,c/=256,i-=8);for(s=s<<i|c,u+=i;u>0;t[r+p]=s&255,p+=g,s/=256,u-=8);t[r+p-g]|=y*128}});var Ar=oe(Bc=>{"use strict";l();var iy=ox(),Ic=sx(),cx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Bc.Buffer=F;Bc.SlowBuffer=TB;Bc.INSPECT_MAX_BYTES=50;var Tf=2147483647;Bc.kMaxLength=Tf;F.TYPED_ARRAY_SUPPORT=xB();!F.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function xB(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(F.prototype,"parent",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.buffer}});Object.defineProperty(F.prototype,"offset",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.byteOffset}});function mi(t){if(t>Tf)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,F.prototype),e}function F(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return ay(t)}return dx(t,e,r)}F.poolSize=8192;function dx(t,e,r){if(typeof t=="string")return vB(t,e);if(ArrayBuffer.isView(t))return SB(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Kn(t,ArrayBuffer)||t&&Kn(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Kn(t,SharedArrayBuffer)||t&&Kn(t.buffer,SharedArrayBuffer)))return sy(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return F.from(n,e,r);var i=AB(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return F.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}F.from=function(t,e,r){return dx(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function fx(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function EB(t,e,r){return fx(t),t<=0?mi(t):e!==void 0?typeof r=="string"?mi(t).fill(e,r):mi(t).fill(e):mi(t)}F.alloc=function(t,e,r){return EB(t,e,r)};function ay(t){return fx(t),mi(t<0?0:uy(t)|0)}F.allocUnsafe=function(t){return ay(t)};F.allocUnsafeSlow=function(t){return ay(t)};function vB(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=lx(t,e)|0,n=mi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function oy(t){for(var e=t.length<0?0:uy(t.length)|0,r=mi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function SB(t){if(Kn(t,Uint8Array)){var e=new Uint8Array(t);return sy(e.buffer,e.byteOffset,e.byteLength)}return oy(t)}function sy(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');var n;return e===void 0&&r===void 0?n=new Uint8Array(t):r===void 0?n=new Uint8Array(t,e):n=new Uint8Array(t,e,r),Object.setPrototypeOf(n,F.prototype),n}function AB(t){if(F.isBuffer(t)){var e=uy(t.length)|0,r=mi(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||dy(t.length)?mi(0):oy(t);if(t.type==="Buffer"&&Array.isArray(t.data))return oy(t.data)}function uy(t){if(t>=Tf)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Tf.toString(16)+" bytes");return t|0}function TB(t){return+t!=t&&(t=0),F.alloc(+t)}F.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==F.prototype};F.compare=function(e,r){if(Kn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),Kn(r,Uint8Array)&&(r=F.from(r,r.offset,r.byteLength)),!F.isBuffer(e)||!F.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,o=0,s=Math.min(n,i);o<s;++o)if(e[o]!==r[o]){n=e[o],i=r[o];break}return n<i?-1:i<n?1:0};F.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};F.concat=function(e,r){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return F.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=F.allocUnsafe(r),o=0;for(n=0;n<e.length;++n){var s=e[n];if(Kn(s,Uint8Array))o+s.length>i.length?F.from(s).copy(i,o):Uint8Array.prototype.set.call(i,s,o);else if(F.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function lx(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Kn(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return cy(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return wx(t).length;default:if(i)return n?-1:cy(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=lx;function _B(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return LB(this,e,r);case"utf8":case"utf-8":return px(this,e,r);case"ascii":return NB(this,e,r);case"latin1":case"binary":return CB(this,e,r);case"base64":return DB(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return PB(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function ps(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}F.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)ps(this,r,r+1);return this};F.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)ps(this,r,r+3),ps(this,r+1,r+2);return this};F.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)ps(this,r,r+7),ps(this,r+1,r+6),ps(this,r+2,r+5),ps(this,r+3,r+4);return this};F.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?px(this,0,e):_B.apply(this,arguments)};F.prototype.toLocaleString=F.prototype.toString;F.prototype.equals=function(e){if(!F.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:F.compare(this,e)===0};F.prototype.inspect=function(){var e="",r=Bc.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};cx&&(F.prototype[cx]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,o){if(Kn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),!F.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),r<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&r>=n)return 0;if(i>=o)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,o>>>=0,this===e)return 0;for(var s=o-i,c=n-r,a=Math.min(s,c),u=this.slice(i,o),d=e.slice(r,n),f=0;f<a;++f)if(u[f]!==d[f]){s=u[f],c=d[f];break}return s<c?-1:c<s?1:0};function hx(t,e,r,n,i){if(t.length===0)return-1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,dy(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=F.from(e,n)),F.isBuffer(e))return e.length===0?-1:ax(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):ax(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function ax(t,e,r,n,i){var o=1,s=t.length,c=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;o=2,s/=2,c/=2,r/=2}function a(p,g){return o===1?p[g]:p.readUInt16BE(g*o)}var u;if(i){var d=-1;for(u=r;u<s;u++)if(a(t,u)===a(e,d===-1?0:u-d)){if(d===-1&&(d=u),u-d+1===c)return d*o}else d!==-1&&(u-=u-d),d=-1}else for(r+c>s&&(r=s-c),u=r;u>=0;u--){for(var f=!0,h=0;h<c;h++)if(a(t,u+h)!==a(e,h)){f=!1;break}if(f)return u}return-1}F.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};F.prototype.indexOf=function(e,r,n){return hx(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return hx(this,e,r,n,!1)};function IB(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=e.length;n>o/2&&(n=o/2);for(var s=0;s<n;++s){var c=parseInt(e.substr(s*2,2),16);if(dy(c))return s;t[r+s]=c}return s}function BB(t,e,r,n){return _f(cy(e,t.length-r),t,r,n)}function RB(t,e,r,n){return _f($B(e),t,r,n)}function UB(t,e,r,n){return _f(wx(e),t,r,n)}function OB(t,e,r,n){return _f(HB(e,t.length-r),t,r,n)}F.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var o=this.length-r;if((n===void 0||n>o)&&(n=o),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return IB(this,e,r,n);case"utf8":case"utf-8":return BB(this,e,r,n);case"ascii":case"latin1":case"binary":return RB(this,e,r,n);case"base64":return UB(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return OB(this,e,r,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};F.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function DB(t,e,r){return e===0&&r===t.length?iy.fromByteArray(t):iy.fromByteArray(t.slice(e,r))}function px(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var o=t[i],s=null,c=o>239?4:o>223?3:o>191?2:1;if(i+c<=r){var a,u,d,f;switch(c){case 1:o<128&&(s=o);break;case 2:a=t[i+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(s=f));break;case 3:a=t[i+1],u=t[i+2],(a&192)===128&&(u&192)===128&&(f=(o&15)<<12|(a&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:a=t[i+1],u=t[i+2],d=t[i+3],(a&192)===128&&(u&192)===128&&(d&192)===128&&(f=(o&15)<<18|(a&63)<<12|(u&63)<<6|d&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,c=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),i+=c}return kB(n)}var ux=4096;function kB(t){var e=t.length;if(e<=ux)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=ux));return r}function NB(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function CB(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function LB(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",o=e;o<r;++o)i+=VB[t[o]];return i}function PB(t,e,r){for(var n=t.slice(e,r),i="",o=0;o<n.length-1;o+=2)i+=String.fromCharCode(n[o]+n[o+1]*256);return i}F.prototype.slice=function(e,r){var n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);var i=this.subarray(e,r);return Object.setPrototypeOf(i,F.prototype),i};function Ut(t,e,r){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}F.prototype.readUintLE=F.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return i};F.prototype.readUintBE=F.prototype.readUIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e+--r],o=1;r>0&&(o*=256);)i+=this[e+--r]*o;return i};F.prototype.readUint8=F.prototype.readUInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};F.prototype.readUint32BE=F.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};F.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*r)),i};F.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=r,o=1,s=this[e+--i];i>0&&(o*=256);)s+=this[e+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*r)),s};F.prototype.readInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};F.prototype.readInt16BE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};F.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};F.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};F.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),Ic.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),Ic.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Ic.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Ic.read(this,e,!1,52,8)};function dr(t,e,r,n,i,o){if(!F.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}F.prototype.writeUintLE=F.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;dr(this,e,r,n,o,0)}var s=1,c=0;for(this[r]=e&255;++c<n&&(s*=256);)this[r+c]=e/s&255;return r+n};F.prototype.writeUintBE=F.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;dr(this,e,r,n,o,0)}var s=n-1,c=1;for(this[r+s]=e&255;--s>=0&&(c*=256);)this[r+s]=e/c&255;return r+n};F.prototype.writeUint8=F.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,1,255,0),this[r]=e&255,r+1};F.prototype.writeUint16LE=F.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeUint16BE=F.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeUint32LE=F.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};F.prototype.writeUint32BE=F.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};F.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);dr(this,e,r,n,o-1,-o)}var s=0,c=1,a=0;for(this[r]=e&255;++s<n&&(c*=256);)e<0&&a===0&&this[r+s-1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);dr(this,e,r,n,o-1,-o)}var s=n-1,c=1,a=0;for(this[r+s]=e&255;--s>=0&&(c*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};F.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};F.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||dr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function yx(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function gx(t,e,r,n,i){return e=+e,r=r>>>0,i||yx(t,e,r,4,34028234663852886e22,-34028234663852886e22),Ic.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return gx(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return gx(this,e,r,!1,n)};function mx(t,e,r,n,i){return e=+e,r=r>>>0,i||yx(t,e,r,8,17976931348623157e292,-17976931348623157e292),Ic.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return mx(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return mx(this,e,r,!1,n)};F.prototype.copy=function(e,r,n,i){if(!F.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r<i-n&&(i=e.length-r+n);var o=i-n;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),r),o};F.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!F.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(e.length===1){var o=e.charCodeAt(0);(i==="utf8"&&o<128||i==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var s;if(typeof e=="number")for(s=r;s<n;++s)this[s]=e;else{var c=F.isBuffer(e)?e:F.from(e,i),a=c.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-r;++s)this[s+r]=c[s%a]}return this};var MB=/[^+/0-9A-Za-z-_]/g;function KB(t){if(t=t.split("=")[0],t=t.trim().replace(MB,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function cy(t,e){e=e||1/0;for(var r,n=t.length,i=null,o=[],s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return o}function $B(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function HB(t,e){for(var r,n,i,o=[],s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}function wx(t){return iy.toByteArray(KB(t))}function _f(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Kn(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function dy(t){return t!==t}var VB=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var xi=oe((WL,vx)=>{l();var ut=vx.exports={},$n,Hn;function fy(){throw new Error("setTimeout has not been defined")}function ly(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?$n=setTimeout:$n=fy}catch{$n=fy}try{typeof clearTimeout=="function"?Hn=clearTimeout:Hn=ly}catch{Hn=ly}})();function bx(t){if($n===setTimeout)return setTimeout(t,0);if(($n===fy||!$n)&&setTimeout)return $n=setTimeout,setTimeout(t,0);try{return $n(t,0)}catch{try{return $n.call(null,t,0)}catch{return $n.call(this,t,0)}}}function qB(t){if(Hn===clearTimeout)return clearTimeout(t);if((Hn===ly||!Hn)&&clearTimeout)return Hn=clearTimeout,clearTimeout(t);try{return Hn(t)}catch{try{return Hn.call(null,t)}catch{return Hn.call(this,t)}}}var wi=[],Rc=!1,ys,If=-1;function FB(){!Rc||!ys||(Rc=!1,ys.length?wi=ys.concat(wi):If=-1,wi.length&&xx())}function xx(){if(!Rc){var t=bx(FB);Rc=!0;for(var e=wi.length;e;){for(ys=wi,wi=[];++If<e;)ys&&ys[If].run();If=-1,e=wi.length}ys=null,Rc=!1,qB(t)}}ut.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];wi.push(new Ex(t,e)),wi.length===1&&!Rc&&bx(xx)};function Ex(t,e){this.fun=t,this.array=e}Ex.prototype.run=function(){this.fun.apply(null,this.array)};ut.title="browser";ut.browser=!0;ut.env={};ut.argv=[];ut.version="";ut.versions={};function bi(){}ut.on=bi;ut.addListener=bi;ut.once=bi;ut.off=bi;ut.removeListener=bi;ut.removeAllListeners=bi;ut.emit=bi;ut.prependListener=bi;ut.prependOnceListener=bi;ut.listeners=function(t){return[]};ut.binding=function(t){throw new Error("process.binding is not supported")};ut.cwd=function(){return"/"};ut.chdir=function(t){throw new Error("process.chdir is not supported")};ut.umask=function(){return 0}});var b,w,zL,l=fB(()=>{b=Pn(Ar()),w=Pn(xi()),zL=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object)});var zv=oe((BH,Gv)=>{l();var i6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Ll=()=>i6.now(),o6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),q0=t=>t===1/0||o6(t),F0=class t{constructor({max:e=1/0,ttl:r,updateAgeOnGet:n=!1,checkAgeOnGet:i=!1,noUpdateTTL:o=!1,dispose:s,noDisposeOnSet:c=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,r!==void 0&&!q0(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!q0(e))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=r,this.max=e,this.updateAgeOnGet=!!n,this.checkAgeOnGet=!!i,this.noUpdateTTL=!!o,this.noDisposeOnSet=!!c,s!==void 0){if(typeof s!="function")throw new TypeError("dispose must be function if set");this.dispose=s}this.timer=void 0,this.timerExpiration=void 0}setTimer(e,r){if(this.timerExpiration<e)return;this.timer&&clearTimeout(this.timer);let n=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let i in this.expirations){this.setTimer(i,i-Ll());break}},r);n.unref&&n.unref(),this.timerExpiration=e,this.timer=n}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return w.default.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let e=this.dispose!==t.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[r,n]of e)this.dispose(n,r,"delete")}setTTL(e,r=this.ttl){let n=this.expirationMap.get(e);if(n!==void 0){let i=this.expirations[n];!i||i.length<=1?delete this.expirations[n]:this.expirations[n]=i.filter(o=>o!==e)}if(r!==1/0){let i=Math.floor(Ll()+r);this.expirationMap.set(e,i),this.expirations[i]||(this.expirations[i]=[],this.setTimer(i,r)),this.expirations[i].push(e)}else this.expirationMap.set(e,1/0)}set(e,r,{ttl:n=this.ttl,noUpdateTTL:i=this.noUpdateTTL,noDisposeOnSet:o=this.noDisposeOnSet}={}){if(!q0(n))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(e)){i||this.setTTL(e,n);let s=this.data.get(e);s!==r&&(this.data.set(e,r),o||this.dispose(s,e,"set"))}else this.setTTL(e,n),this.data.set(e,r);for(;this.size>this.max;)this.purgeToCapacity();return this}has(e){return this.data.has(e)}getRemainingTTL(e){let r=this.expirationMap.get(e);return r===1/0?r:r!==void 0?Math.max(0,Math.ceil(r-Ll())):0}get(e,{updateAgeOnGet:r=this.updateAgeOnGet,ttl:n=this.ttl,checkAgeOnGet:i=this.checkAgeOnGet}={}){let o=this.data.get(e);if(i&&this.getRemainingTTL(e)===0){this.delete(e);return}return r&&this.setTTL(e,n),o}dispose(e,r){}delete(e){let r=this.expirationMap.get(e);if(r!==void 0){let n=this.data.get(e);this.data.delete(e),this.expirationMap.delete(e);let i=this.expirations[r];return i&&(i.length<=1?delete this.expirations[r]:this.expirations[r]=i.filter(o=>o!==e)),this.dispose(n,e,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let e in this.expirations){let r=this.expirations[e];if(this.size-r.length>=this.max){delete this.expirations[e];let n=[];for(let i of r)n.push([i,this.data.get(i)]),this.data.delete(i),this.expirationMap.delete(i);for(let[i,o]of n)this.dispose(o,i,"evict")}else{let n=this.size-this.max,i=[];for(let o of r.splice(0,n))i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"evict");return}}}get size(){return this.data.size}purgeStale(){let e=Math.ceil(Ll());for(let r in this.expirations){if(r==="Infinity"||r>e)return;let n=[...this.expirations[r]||[]],i=[];delete this.expirations[r];for(let o of n)i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let e in this.expirations)for(let r of this.expirations[e])yield[r,this.data.get(r)]}*keys(){for(let e in this.expirations)for(let r of this.expirations[e])yield r}*values(){for(let e in this.expirations)for(let r of this.expirations[e])yield this.data.get(r)}[Symbol.iterator](){return this.entries()}};Gv.exports=F0});var f1=oe(d1=>{"use strict";l();d1.supports=function(...e){let r=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}});var En=oe((XV,l1)=>{"use strict";l();l1.exports=class extends Error{constructor(e,r){super(e||""),typeof r=="object"&&r!==null&&(r.code&&(this.code=String(r.code)),r.expected&&(this.expected=!0),r.transient&&(this.transient=!0),r.cause&&(this.cause=r.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var og=oe((eq,h1)=>{"use strict";l();var ig=null;h1.exports=function(){return ig===null&&(ig={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),ig}});var ag=oe(p1=>{"use strict";l();var sg=En(),M6=new Set(["buffer","view","utf8"]),cg=class{constructor(e){if(this.encode=e.encode||this.encode,this.decode=e.decode||this.decode,this.name=e.name||this.name,this.format=e.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!M6.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");e.createViewTranscoder&&(this.createViewTranscoder=e.createViewTranscoder),e.createBufferTranscoder&&(this.createBufferTranscoder=e.createBufferTranscoder),e.createUTF8Transcoder&&(this.createUTF8Transcoder=e.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new sg(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new sg(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new sg(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};p1.Encoding=cg});var lg=oe(Ml=>{"use strict";l();var{Buffer:dg}=Ar()||{},{Encoding:fg}=ag(),K6=og(),nd=class extends fg{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new id({encode:this.encode,decode:e=>this.decode(dg.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},id=class extends fg{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new nd({encode:e=>{let r=this.encode(e);return dg.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},ug=class extends fg{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new nd({encode:e=>dg.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:r}=K6();return new id({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Ml.BufferFormat=nd;Ml.ViewFormat=id;Ml.UTF8Format=ug});var w1=oe(Ms=>{"use strict";l();var{Buffer:Jt}=Ar()||{Buffer:{isBuffer:()=>!1}},{textEncoder:g1,textDecoder:y1}=og()(),{BufferFormat:od,ViewFormat:hg,UTF8Format:m1}=lg(),Kl=t=>t;Ms.utf8=new m1({encode:function(t){return Jt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?y1.decode(t):String(t)},decode:Kl,name:"utf8",createViewTranscoder(){return new hg({encode:function(t){return ArrayBuffer.isView(t)?t:g1.encode(t)},decode:function(t){return y1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new od({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Ms.json=new m1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Ms.buffer=new od({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:Kl,name:"buffer",createViewTranscoder(){return new hg({encode:function(t){return ArrayBuffer.isView(t)?t:Jt.from(String(t),"utf8")},decode:function(t){return Jt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Ms.view=new hg({encode:function(t){return ArrayBuffer.isView(t)?t:g1.encode(t)},decode:Kl,name:"view",createBufferTranscoder(){return new od({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:Kl,name:`${this.name}+buffer`})}});Ms.hex=new od({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Ms.base64=new od({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var E1=oe(x1=>{"use strict";l();var b1=En(),Hl=w1(),{Encoding:$6}=ag(),{BufferFormat:H6,ViewFormat:V6,UTF8Format:q6}=lg(),sd=Symbol("formats"),$l=Symbol("encodings"),F6=new Set(["buffer","view","utf8"]),pg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>F6.has(r)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[$l]=new Map,this[sd]=new Set(e);for(let r in Hl)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[$l].values()))}encoding(e){let r=this[$l].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=z6[e],!r)throw new b1(`Encoding '${e}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof e!="object"||e===null)throw new TypeError("First argument 'encoding' must be a string or object");r=j6(e)}let{name:n,format:i}=r;if(!this[sd].has(i))if(this[sd].has("view"))r=r.createViewTranscoder();else if(this[sd].has("buffer"))r=r.createBufferTranscoder();else if(this[sd].has("utf8"))r=r.createUTF8Transcoder();else throw new b1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[$l].set(o,r)}return r}};x1.Transcoder=pg;function j6(t){if(t instanceof $6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${Y6++}`;switch(W6(t)){case"view":return new V6({...t,name:r});case"utf8":return new q6({...t,name:r});case"buffer":return new H6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function W6(t){return"format"in t&&t.format!==void 0?t.format:"buffer"in t&&typeof t.buffer=="boolean"?t.buffer?"buffer":"utf8":"code"in t&&Number.isInteger(t.code)?"view":"buffer"}var G6={binary:Hl.buffer,"utf-8":Hl.utf8},z6={...Hl,...G6},Y6=0});var aa=oe((dq,yg)=>{"use strict";l();var ca=typeof Reflect=="object"?Reflect:null,v1=ca&&typeof ca.apply=="function"?ca.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Vl;ca&&typeof ca.ownKeys=="function"?Vl=ca.ownKeys:Object.getOwnPropertySymbols?Vl=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Vl=function(e){return Object.getOwnPropertyNames(e)};function J6(t){console&&console.warn&&console.warn(t)}var A1=Number.isNaN||function(e){return e!==e};function Pe(){Pe.init.call(this)}yg.exports=Pe;yg.exports.once=eU;Pe.EventEmitter=Pe;Pe.prototype._events=void 0;Pe.prototype._eventsCount=0;Pe.prototype._maxListeners=void 0;var S1=10;function ql(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Pe,"defaultMaxListeners",{enumerable:!0,get:function(){return S1},set:function(t){if(typeof t!="number"||t<0||A1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");S1=t}});Pe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Pe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||A1(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function T1(t){return t._maxListeners===void 0?Pe.defaultMaxListeners:t._maxListeners}Pe.prototype.getMaxListeners=function(){return T1(this)};Pe.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(r.length>0&&(s=r[0]),s instanceof Error)throw s;var c=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw c.context=s,c}var a=o[e];if(a===void 0)return!1;if(typeof a=="function")v1(a,this,r);else for(var u=a.length,d=U1(a,u),n=0;n<u;++n)v1(d[n],this,r);return!0};function _1(t,e,r,n){var i,o,s;if(ql(r),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),o=t._events),s=o[e]),s===void 0)s=o[e]=r,++t._eventsCount;else if(typeof s=="function"?s=o[e]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),i=T1(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=s.length,J6(c)}return t}Pe.prototype.addListener=function(e,r){return _1(this,e,r,!1)};Pe.prototype.on=Pe.prototype.addListener;Pe.prototype.prependListener=function(e,r){return _1(this,e,r,!0)};function Z6(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function I1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=Z6.bind(n);return i.listener=r,n.wrapFn=i,i}Pe.prototype.once=function(e,r){return ql(r),this.on(e,I1(this,e,r)),this};Pe.prototype.prependOnceListener=function(e,r){return ql(r),this.prependListener(e,I1(this,e,r)),this};Pe.prototype.removeListener=function(e,r){var n,i,o,s,c;if(ql(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===r||n[s].listener===r){c=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():X6(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Pe.prototype.off=Pe.prototype.removeListener;Pe.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function B1(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?Q6(i):U1(i,i.length)}Pe.prototype.listeners=function(e){return B1(this,e,!0)};Pe.prototype.rawListeners=function(e){return B1(this,e,!1)};Pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):R1.call(t,e)};Pe.prototype.listenerCount=R1;function R1(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Pe.prototype.eventNames=function(){return this._eventsCount>0?Vl(this._events):[]};function U1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function X6(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Q6(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function eU(t,e){return new Promise(function(r,n){function i(s){t.removeListener(e,o),n(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}O1(t,e,o,{once:!0}),e!=="error"&&tU(t,i,{once:!0})})}function tU(t,e,r){typeof t.on=="function"&&O1(t,"error",e,r)}function O1(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){n.once&&t.removeEventListener(e,i),r(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}});var k1=oe((lq,D1)=>{l();D1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var cd=oe(gg=>{"use strict";l();var N1=k1();gg.fromCallback=function(t,e){if(t===void 0){var r=new Promise(function(n,i){t=function(o,s){o?i(o):n(s)}});t[e!==void 0?e:"promise"]=r}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t};gg.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){N1(()=>e(null,r))}).catch(function(r){N1(()=>e(r))})}});var Fl=oe(mg=>{"use strict";l();mg.getCallback=function(t,e){return typeof t=="function"?t:e};mg.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Po=oe(zl=>{"use strict";l();var{fromCallback:wg}=cd(),Dr=En(),{getOptions:bg,getCallback:C1}=Fl(),Ks=Symbol("promise"),ua=Symbol("callback"),Zn=Symbol("working"),$s=Symbol("handleOne"),Mi=Symbol("handleMany"),xg=Symbol("autoClose"),Co=Symbol("finishWork"),Xn=Symbol("returnMany"),Do=Symbol("closing"),ad=Symbol("handleClose"),jl=Symbol("closed"),ud=Symbol("closeCallbacks"),No=Symbol("keyEncoding"),Hs=Symbol("valueEncoding"),Eg=Symbol("abortOnClose"),Wl=Symbol("legacy"),vg=Symbol("keys"),Sg=Symbol("values"),ko=Symbol("limit"),Zr=Symbol("count"),Gl=Object.freeze({}),rU=()=>{},L1=!1,dd=class{constructor(e,r,n){if(typeof e!="object"||e===null){let i=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof r!="object"||r===null)throw new TypeError("The second argument must be an options object");this[jl]=!1,this[ud]=[],this[Zn]=!1,this[Do]=!1,this[xg]=!1,this[ua]=null,this[$s]=this[$s].bind(this),this[Mi]=this[Mi].bind(this),this[ad]=this[ad].bind(this),this[No]=r[No],this[Hs]=r[Hs],this[Wl]=n,this[ko]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[Zr]=0,this[Eg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[Zr]}get limit(){return this[ko]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[Wl]?s===void 0&&c===void 0?n():n([s,c]):n(s)}});else if(typeof e!="function")throw new TypeError("Callback must be a function");return this[Do]?this.nextTick(e,new Dr("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Zn]?this.nextTick(e,new Dr("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Zn]=!0,this[ua]=e,this[Zr]>=this[ko]?this.nextTick(this[$s],null):this._next(this[$s])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=C1(r,n),n=wg(n,Ks),r=bg(r,Gl),Number.isInteger(e)?(this[Do]?this.nextTick(n,new Dr("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Zn]?this.nextTick(n,new Dr("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[ko]<1/0&&(e=Math.min(e,this[ko]-this[Zr])),this[Zn]=!0,this[ua]=n,e<=0?this.nextTick(this[Mi],null,[]):this._nextv(e,r,this[Mi])),n[Ks]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[Ks])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[Wl]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[Wl]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=C1(e,r),r=wg(r,Ks),e=bg(e,Gl),this[Do]?this.nextTick(r,new Dr("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Zn]?this.nextTick(r,new Dr("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Zn]=!0,this[ua]=r,this[xg]=!0,this[Zr]>=this[ko]?this.nextTick(this[Mi],null,[]):this._all(e,this[Mi])),r[Ks]}_all(e,r){let n=this[Zr],i=[],o=()=>{let c=this[ko]<1/0?Math.min(1e3,this[ko]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,Gl,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Co](){let e=this[ua];return this[Eg]&&e===null?rU:(this[Zn]=!1,this[ua]=null,this[Do]&&this._close(this[ad]),e)}[Xn](e,r,n){this[xg]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=bg(r,Gl),!this[Do]){if(this[Zn])throw new Dr("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[No]),i=n.format;r.keyEncoding!==i&&(r={...r,keyEncoding:i});let o=this.db.prefixKey(n.encode(e),i);this._seek(o,r)}}}_seek(e,r){throw new Dr("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=wg(e,Ks),this[jl]?this.nextTick(e):this[Do]?this[ud].push(e):(this[Do]=!0,this[ud].push(e),this[Zn]?this[Eg]&&this[Co]()(new Dr("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[ad])),e[Ks]}_close(e){this.nextTick(e)}[ad](){this[jl]=!0,this.db.detachResource(this);let e=this[ud];this[ud]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[jl]||await this.close()}}},da=class extends dd{constructor(e,r){super(e,r,!0),this[vg]=r.keys!==!1,this[Sg]=r.values!==!1}[$s](e,r,n){let i=this[Co]();if(e)return i(e);try{r=this[vg]&&r!==void 0?this[No].decode(r):void 0,n=this[Sg]&&n!==void 0?this[Hs].decode(n):void 0}catch(o){return i(new Lo("entry",o))}r===void 0&&n===void 0||this[Zr]++,i(null,r,n)}[Mi](e,r){let n=this[Co]();if(e)return this[Xn](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[vg]&&o!==void 0?this[No].decode(o):void 0,i[1]=this[Sg]&&s!==void 0?this[Hs].decode(s):void 0}}catch(i){return this[Xn](n,new Lo("entries",i))}this[Zr]+=r.length,this[Xn](n,null,r)}end(e){return!L1&&typeof console<"u"&&(L1=!0,console.warn(new Dr("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(e)}},Ag=class extends dd{constructor(e,r){super(e,r,!1)}[$s](e,r){let n=this[Co]();if(e)return n(e);try{r=r!==void 0?this[No].decode(r):void 0}catch(i){return n(new Lo("key",i))}r!==void 0&&this[Zr]++,n(null,r)}[Mi](e,r){let n=this[Co]();if(e)return this[Xn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[No].decode(o):void 0}}catch(i){return this[Xn](n,new Lo("keys",i))}this[Zr]+=r.length,this[Xn](n,null,r)}},Tg=class extends dd{constructor(e,r){super(e,r,!1)}[$s](e,r){let n=this[Co]();if(e)return n(e);try{r=r!==void 0?this[Hs].decode(r):void 0}catch(i){return n(new Lo("value",i))}r!==void 0&&this[Zr]++,n(null,r)}[Mi](e,r){let n=this[Co]();if(e)return this[Xn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Hs].decode(o):void 0}}catch(i){return this[Xn](n,new Lo("values",i))}this[Zr]+=r.length,this[Xn](n,null,r)}},Lo=class extends Dr{constructor(e,r){super(`Iterator could not decode ${e}`,{code:"LEVEL_DECODE_ERROR",cause:r})}};for(let t of["_ended property","_nexting property","_end method"])Object.defineProperty(da.prototype,t.split(" ")[0],{get(){throw new Dr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new Dr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});da.keyEncoding=No;da.valueEncoding=Hs;zl.AbstractIterator=da;zl.AbstractKeyIterator=Ag;zl.AbstractValueIterator=Tg});var P1=oe(_g=>{"use strict";l();var{AbstractKeyIterator:nU,AbstractValueIterator:iU}=Po(),Vs=Symbol("iterator"),fd=Symbol("callback"),fa=Symbol("handleOne"),qs=Symbol("handleMany"),ld=class extends nU{constructor(e,r){super(e,r),this[Vs]=e.iterator({...r,keys:!0,values:!1}),this[fa]=this[fa].bind(this),this[qs]=this[qs].bind(this)}},Yl=class extends iU{constructor(e,r){super(e,r),this[Vs]=e.iterator({...r,keys:!1,values:!0}),this[fa]=this[fa].bind(this),this[qs]=this[qs].bind(this)}};for(let t of[ld,Yl]){let e=t===ld,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[fd]=n,this[Vs].next(this[fa])},t.prototype[fa]=function(n,i,o){let s=this[fd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[fd]=o,this[Vs].nextv(n,i,this[qs])},t.prototype._all=function(n,i){this[fd]=i,this[Vs].all(n,this[qs])},t.prototype[qs]=function(n,i){let o=this[fd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[Vs].seek(n,i)},t.prototype._close=function(n){this[Vs].close(n)}}_g.DefaultKeyIterator=ld;_g.DefaultValueIterator=Yl});var M1=oe(th=>{"use strict";l();var{AbstractIterator:oU,AbstractKeyIterator:sU,AbstractValueIterator:cU}=Po(),Ig=En(),pr=Symbol("nut"),Ql=Symbol("undefer"),eh=Symbol("factory"),Jl=class extends oU{constructor(e,r){super(e,r),this[pr]=null,this[eh]=()=>e.iterator(r),this.db.defer(()=>this[Ql]())}},Zl=class extends sU{constructor(e,r){super(e,r),this[pr]=null,this[eh]=()=>e.keys(r),this.db.defer(()=>this[Ql]())}},Xl=class extends cU{constructor(e,r){super(e,r),this[pr]=null,this[eh]=()=>e.values(r),this.db.defer(()=>this[Ql]())}};for(let t of[Jl,Zl,Xl])t.prototype[Ql]=function(){this.db.status==="open"&&(this[pr]=this[eh]())},t.prototype._next=function(e){this[pr]!==null?this[pr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new Ig("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[pr]!==null?this[pr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new Ig("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[pr]!==null?this[pr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new Ig("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[pr]!==null?this[pr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[pr]!==null?this[pr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};th.DeferredIterator=Jl;th.DeferredKeyIterator=Zl;th.DeferredValueIterator=Xl});var Rg=oe($1=>{"use strict";l();var{fromCallback:K1}=cd(),rh=En(),{getCallback:aU,getOptions:uU}=Fl(),nh=Symbol("promise"),Xr=Symbol("status"),la=Symbol("operations"),hd=Symbol("finishClose"),ha=Symbol("closeCallbacks"),Bg=class{constructor(e){if(typeof e!="object"||e===null){let r=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${r}`)}this[la]=[],this[ha]=[],this[Xr]="open",this[hd]=this[hd].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[la].length}put(e,r,n){if(this[Xr]!=="open")throw new rh("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(e)||this.db._checkValue(r);if(i)throw i;let o=n&&n.sublevel!=null?n.sublevel:this.db,s=n,c=o.keyEncoding(n&&n.keyEncoding),a=o.valueEncoding(n&&n.valueEncoding),u=c.format;n={...n,keyEncoding:u,valueEncoding:a.format},o!==this.db&&(n.sublevel=null);let d=o.prefixKey(c.encode(e),u),f=a.encode(r);return this._put(d,f,n),this[la].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[Xr]!=="open")throw new rh("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let n=this.db._checkKey(e);if(n)throw n;let i=r&&r.sublevel!=null?r.sublevel:this.db,o=r,s=i.keyEncoding(r&&r.keyEncoding),c=s.format;return r={...r,keyEncoding:c},i!==this.db&&(r.sublevel=null),this._del(i.prefixKey(s.encode(e),c),r),this[la].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[Xr]!=="open")throw new rh("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[la]=[],this}_clear(){}write(e,r){return r=aU(e,r),r=K1(r,nh),e=uU(e),this[Xr]!=="open"?this.nextTick(r,new rh("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[Xr]="writing",this._write(e,n=>{this[Xr]="closing",this[ha].push(()=>r(n)),n||this.db.emit("batch",this[la]),this._close(this[hd])})),r[nh]}_write(e,r){}close(e){return e=K1(e,nh),this[Xr]==="closing"?this[ha].push(e):this[Xr]==="closed"?this.nextTick(e):(this[ha].push(e),this[Xr]!=="writing"&&(this[Xr]="closing",this._close(this[hd]))),e[nh]}_close(e){this.nextTick(e)}[hd](){this[Xr]="closed",this.db.detachResource(this);let e=this[ha];this[ha]=[];for(let r of e)r()}};$1.AbstractChainedBatch=Bg});var V1=oe(H1=>{"use strict";l();var{AbstractChainedBatch:dU}=Rg(),fU=En(),pa=Symbol("encoded"),Ug=class extends dU{constructor(e){super(e),this[pa]=[]}_put(e,r,n){this[pa].push({...n,type:"put",key:e,value:r})}_del(e,r){this[pa].push({...r,type:"del",key:e})}_clear(){this[pa]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[pa].length===0?this.nextTick(r):this.db._batch(this[pa],e,r):this.nextTick(r,new fU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};H1.DefaultChainedBatch=Ug});var j1=oe((Bq,F1)=>{"use strict";l();var q1=En(),lU=Object.prototype.hasOwnProperty,hU=new Set(["lt","lte","gt","gte"]);F1.exports=function(t,e){let r={};for(let n in t)if(lU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new q1(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new q1("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});hU.has(n)?r[n]=e.encode(t[n]):r[n]=t[n]}return r.reverse=!!r.reverse,r.limit=Number.isInteger(r.limit)&&r.limit>=0?r.limit:-1,r}});var Og=oe((Uq,G1)=>{l();var W1;G1.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(W1||(W1=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var J1=oe((Dq,Y1)=>{"use strict";l();var z1=Og();Y1.exports=function(t,...e){e.length===0?z1(t):z1(()=>t(...e))}});var Z1=oe(ih=>{"use strict";l();var{AbstractIterator:pU,AbstractKeyIterator:yU,AbstractValueIterator:gU}=Po(),ya=Symbol("unfix"),vn=Symbol("iterator"),Fs=Symbol("handleOne"),Mo=Symbol("handleMany"),Ki=Symbol("callback"),pd=class extends pU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ya]=i,this[Fs]=this[Fs].bind(this),this[Mo]=this[Mo].bind(this),this[Ki]=null}[Fs](e,r,n){let i=this[Ki];if(e)return i(e);r!==void 0&&(r=this[ya](r)),i(e,r,n)}[Mo](e,r){let n=this[Ki];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[ya](o))}n(e,r)}},yd=class extends yU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ya]=i,this[Fs]=this[Fs].bind(this),this[Mo]=this[Mo].bind(this),this[Ki]=null}[Fs](e,r){let n=this[Ki];if(e)return n(e);r!==void 0&&(r=this[ya](r)),n(e,r)}[Mo](e,r){let n=this[Ki];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[ya](o))}n(e,r)}},gd=class extends gU{constructor(e,r,n){super(e,r),this[vn]=n}};for(let t of[pd,yd])t.prototype._next=function(e){this[Ki]=e,this[vn].next(this[Fs])},t.prototype._nextv=function(e,r,n){this[Ki]=n,this[vn].nextv(e,r,this[Mo])},t.prototype._all=function(e,r){this[Ki]=r,this[vn].all(e,this[Mo])};for(let t of[gd])t.prototype._next=function(e){this[vn].next(e)},t.prototype._nextv=function(e,r,n){this[vn].nextv(e,r,n)},t.prototype._all=function(e,r){this[vn].all(e,r)};for(let t of[pd,yd,gd])t.prototype._seek=function(e,r){this[vn].seek(e,r)},t.prototype._close=function(e){this[vn].close(e)};ih.AbstractSublevelIterator=pd;ih.AbstractSublevelKeyIterator=yd;ih.AbstractSublevelValueIterator=gd});var t2=oe((Lq,e2)=>{"use strict";l();var Dg=En(),{Buffer:Cg}=Ar()||{},{AbstractSublevelIterator:mU,AbstractSublevelKeyIterator:wU,AbstractSublevelValueIterator:bU}=Z1(),$i=Symbol("prefix"),X1=Symbol("upperBound"),md=Symbol("prefixRange"),kr=Symbol("parent"),kg=Symbol("unfix"),Q1=new TextEncoder,xU={separator:"!"};e2.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new Dg("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new Dg("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?xU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=vU(i,s);let u=s.charCodeAt(0)+1,d=n[kr]||n;if(!Q1.encode(i).every(p=>p>u&&p<127))throw new Dg(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(EU(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[kr]=d,this[$i]=new oh(f),this[X1]=new oh(h),this[kg]=new Lg,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[$i].utf8+n;if(n.byteLength===0)return this[$i][i];if(i==="view"){let o=this[$i].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[$i].buffer;return Cg.concat([o,n],o.byteLength+n.byteLength)}}[md](n,i){n.gte!==void 0?n.gte=this.prefixKey(n.gte,i):n.gt!==void 0?n.gt=this.prefixKey(n.gt,i):n.gte=this[$i][i],n.lte!==void 0?n.lte=this.prefixKey(n.lte,i):n.lt!==void 0?n.lt=this.prefixKey(n.lt,i):n.lte=this[X1][i]}get prefix(){return this[$i].utf8}get db(){return this[kr]}_open(n,i){this[kr].open({passive:!0},i)}_put(n,i,o,s){this[kr].put(n,i,o,s)}_get(n,i,o){this[kr].get(n,i,o)}_getMany(n,i,o){this[kr].getMany(n,i,o)}_del(n,i,o){this[kr].del(n,i,o)}_batch(n,i,o){this[kr].batch(n,i,o)}_clear(n,i){this[md](n,n.keyEncoding),this[kr].clear(n,i)}_iterator(n){this[md](n,n.keyEncoding);let i=this[kr].iterator(n),o=this[kg].get(this[$i].utf8.length,n.keyEncoding);return new mU(this,n,i,o)}_keys(n){this[md](n,n.keyEncoding);let i=this[kr].keys(n),o=this[kg].get(this[$i].utf8.length,n.keyEncoding);return new wU(this,n,i,o)}_values(n){this[md](n,n.keyEncoding);let i=this[kr].values(n);return new bU(this,n,i)}}return{AbstractSublevel:e}};var EU=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:Ng(t,"utf8"),buffer:Ng(t,"buffer"),view:Ng(t,"view")}}},Ng=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},oh=class{constructor(e){this.utf8=e,this.view=Q1.encode(e),this.buffer=Cg?Cg.from(this.view.buffer,0,this.view.byteLength):{}}},Lg=class{constructor(){this.cache=new Map}get(e,r){let n=this.cache.get(r);return n===void 0&&(r==="view"?n=(function(i,o){return o.subarray(i)}).bind(null,e):n=(function(i,o){return o.slice(i)}).bind(null,e),this.cache.set(r,n)),n}},vU=function(t,e){let r=0,n=t.length;for(;r<n&&t[r]===e;)r++;for(;n>r&&t[n-1]===e;)n--;return t.slice(r,n)}});var Hg=oe($g=>{"use strict";l();var{supports:SU}=f1(),{Transcoder:AU}=E1(),{EventEmitter:TU}=aa(),{fromCallback:Ko}=cd(),Sn=En(),{AbstractIterator:js}=Po(),{DefaultKeyIterator:_U,DefaultValueIterator:IU}=P1(),{DeferredIterator:BU,DeferredKeyIterator:RU,DeferredValueIterator:UU}=M1(),{DefaultChainedBatch:r2}=V1(),{getCallback:Ws,getOptions:$o}=Fl(),sh=j1(),pe=Symbol("promise"),Hi=Symbol("landed"),Gs=Symbol("resources"),Pg=Symbol("closeResources"),wd=Symbol("operations"),bd=Symbol("undefer"),ch=Symbol("deferOpen"),n2=Symbol("options"),be=Symbol("status"),zs=Symbol("defaultOptions"),ga=Symbol("transcoder"),ah=Symbol("keyEncoding"),Mg=Symbol("valueEncoding"),OU=()=>{},xd=class extends TU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=$o(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[Gs]=new Set,this[wd]=[],this[ch]=!0,this[n2]=s,this[be]="opening",this.supports=SU(e,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:e.snapshots!==!1,permanence:e.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:e.encodings||{},events:Object.assign({},e.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[ga]=new AU(DU(this)),this[ah]=this[ga].encoding(n||"utf8"),this[Mg]=this[ga].encoding(i||"utf8");for(let c of this[ga].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[zs]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[ah].commonName,valueEncoding:this[Mg].commonName}),key:Object.freeze({keyEncoding:this[ah].commonName})},this.nextTick(()=>{this[ch]&&this.open({passive:!1},OU)})}get status(){return this[be]}keyEncoding(e){return this[ga].encoding(e??this[ah])}valueEncoding(e){return this[ga].encoding(e??this[Mg])}open(e,r){r=Ws(e,r),r=Ko(r,pe),e={...this[n2],...$o(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[be]==="closing"||this[be]==="opening"?this.once(Hi,i?()=>n(i):n):this[be]!=="open"?r(new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[be]==="opening"?this.once(Hi,n):this.nextTick(n):this[be]==="closed"||this[ch]?(this[ch]=!1,this[be]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[be]="closed",this[Pg](()=>{this.emit(Hi),n(i)}),this[bd]();return}this[be]="open",this[bd](),this.emit(Hi),this[be]==="open"&&this.emit("open"),this[be]==="open"&&this.emit("ready"),n()})):this[be]==="open"?this.nextTick(n):this.once(Hi,()=>this.open(e,r)),r[pe]}_open(e,r){this.nextTick(r)}close(e){e=Ko(e,pe);let r=n=>{this[be]==="opening"||this[be]==="closing"?this.once(Hi,n?r(n):r):this[be]!=="closed"?e(new Sn("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[be]==="open"){this[be]="closing",this.emit("closing");let n=i=>{this[be]="open",this[bd](),this.emit(Hi),r(i)};this[Pg](()=>{this._close(i=>{if(i)return n(i);this[be]="closed",this[bd](),this.emit(Hi),this[be]==="closed"&&this.emit("closed"),r()})})}else this[be]==="closed"?this.nextTick(r):this.once(Hi,()=>this.close(e));return e[pe]}[Pg](e){if(this[Gs].size===0)return this.nextTick(e);let r=this[Gs].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[Gs])o.close(i);n=!1,this[Gs].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].entry),this[be]==="opening")return this.defer(()=>this.get(e,r,n)),n[pe];if(ma(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=this.valueEncoding(r.valueEncoding),c=o.format,a=s.format;return(r.keyEncoding!==c||r.valueEncoding!==a)&&(r=Object.assign({},r,{keyEncoding:c,valueEncoding:a})),this._get(this.prefixKey(o.encode(e),c),r,(u,d)=>{if(u)return(u.code==="LEVEL_NOT_FOUND"||u.notFound||/NotFound/i.test(u))&&(u.code||(u.code="LEVEL_NOT_FOUND"),u.notFound||(u.notFound=!0),u.status||(u.status=404)),n(u);try{d=s.decode(d)}catch(f){return n(new Sn("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_get(e,r,n){this.nextTick(n,new Error("NotFound"))}getMany(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].entry),this[be]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[pe];if(ma(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[pe];if(e.length===0)return this.nextTick(n,null,[]),n[pe];let i=this.keyEncoding(r.keyEncoding),o=this.valueEncoding(r.valueEncoding),s=i.format,c=o.format;(r.keyEncoding!==s||r.valueEncoding!==c)&&(r=Object.assign({},r,{keyEncoding:s,valueEncoding:c}));let a=new Array(e.length);for(let u=0;u<e.length;u++){let d=e[u],f=this._checkKey(d);if(f)return this.nextTick(n,f),n[pe];a[u]=this.prefixKey(i.encode(d),s)}return this._getMany(a,r,(u,d)=>{if(u)return n(u);try{for(let f=0;f<d.length;f++)d[f]!==void 0&&(d[f]=o.decode(d[f]))}catch(f){return n(new Sn(`Could not decode one or more of ${d.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_getMany(e,r,n){this.nextTick(n,null,new Array(e.length).fill(void 0))}put(e,r,n,i){if(i=Ws(n,i),i=Ko(i,pe),n=$o(n,this[zs].entry),this[be]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[pe];if(ma(this,i))return i[pe];let o=this._checkKey(e)||this._checkValue(r);if(o)return this.nextTick(i,o),i[pe];let s=this.keyEncoding(n.keyEncoding),c=this.valueEncoding(n.valueEncoding),a=s.format,u=c.format;(n.keyEncoding!==a||n.valueEncoding!==u)&&(n=Object.assign({},n,{keyEncoding:a,valueEncoding:u}));let d=this.prefixKey(s.encode(e),a),f=c.encode(r);return this._put(d,f,n,h=>{if(h)return i(h);this.emit("put",e,r),i()}),i[pe]}_put(e,r,n,i){this.nextTick(i)}del(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].key),this[be]==="opening")return this.defer(()=>this.del(e,r,n)),n[pe];if(ma(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=o.format;return r.keyEncoding!==s&&(r=Object.assign({},r,{keyEncoding:s})),this._del(this.prefixKey(o.encode(e),s),r,c=>{if(c)return n(c);this.emit("del",e),n()}),n[pe]}_del(e,r,n){this.nextTick(n)}batch(e,r,n){if(!arguments.length){if(this[be]==="opening")return new r2(this);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].empty),this[be]==="opening")return this.defer(()=>this.batch(e,r,n)),n[pe];if(ma(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[pe];if(e.length===0)return this.nextTick(n),n[pe];let i=new Array(e.length),{keyEncoding:o,valueEncoding:s,...c}=r;for(let a=0;a<e.length;a++){if(typeof e[a]!="object"||e[a]===null)return this.nextTick(n,new TypeError("A batch operation must be an object")),n[pe];let u=Object.assign({},e[a]);if(u.type!=="put"&&u.type!=="del")return this.nextTick(n,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),n[pe];let d=this._checkKey(u.key);if(d)return this.nextTick(n,d),n[pe];let f=u.sublevel!=null?u.sublevel:this,h=f.keyEncoding(u.keyEncoding||o),p=h.format;if(u.key=f.prefixKey(h.encode(u.key),p),u.keyEncoding=p,u.type==="put"){let g=this._checkValue(u.value);if(g)return this.nextTick(n,g),n[pe];let y=f.valueEncoding(u.valueEncoding||s);u.value=y.encode(u.value),u.valueEncoding=y.format}f!==this&&(u.sublevel=null),i[a]=u}return this._batch(i,c,a=>{if(a)return n(a);this.emit("batch",e),n()}),n[pe]}_batch(e,r,n){this.nextTick(n)}sublevel(e,r){return this._sublevel(e,Kg.defaults(r))}_sublevel(e,r){return new Kg(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=Ws(e,r),r=Ko(r,pe),e=$o(e,this[zs].empty),this[be]==="opening")return this.defer(()=>this.clear(e,r)),r[pe];if(ma(this,r))return r[pe];let n=e,i=this.keyEncoding(e.keyEncoding);return e=sh(e,i),e.keyEncoding=i.format,e.limit===0?this.nextTick(r):this._clear(e,o=>{if(o)return r(o);this.emit("clear",n),r()}),r[pe]}_clear(e,r){this.nextTick(r)}iterator(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new BU(this,e);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new js(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sh(e,r),e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new RU(this,e);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new _U(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=sh(e,r),e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new UU(this,e);if(this[be]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new IU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[wd].push(e)}[bd](){if(this[wd].length===0)return;let e=this[wd];this[wd]=[];for(let r of e)r()}attachResource(e){if(typeof e!="object"||e===null||typeof e.close!="function")throw new TypeError("The first argument must be a resource object");this[Gs].add(e)}detachResource(e){this[Gs].delete(e)}_chainedBatch(){return new r2(this)}_checkKey(e){if(e==null)return new Sn("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new Sn("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};xd.prototype.nextTick=J1();var{AbstractSublevel:Kg}=t2()({AbstractLevel:xd});$g.AbstractLevel=xd;$g.AbstractSublevel=Kg;var ma=function(t,e){return t[be]!=="open"?(t.nextTick(e,new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},DU=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var Vg=oe(Ys=>{"use strict";l();Ys.AbstractLevel=Hg().AbstractLevel;Ys.AbstractSublevel=Hg().AbstractSublevel;Ys.AbstractIterator=Po().AbstractIterator;Ys.AbstractKeyIterator=Po().AbstractKeyIterator;Ys.AbstractValueIterator=Po().AbstractValueIterator;Ys.AbstractChainedBatch=Rg().AbstractChainedBatch});var o2=oe((Vq,i2)=>{l();i2.exports=NU;var kU=Og();function NU(t,e,r){if(typeof e!="number")throw new Error("second argument must be a Number");let n,i,o,s,c,a=!0,u;Array.isArray(t)?(n=[],o=i=t.length):(s=Object.keys(t),n={},o=i=s.length);function d(h){function p(){r&&r(h,n),r=null}a?kU(p):p()}function f(h,p,g){if(n[h]=g,p&&(c=!0),--o===0||p)d(p);else if(!c&&u<i){let y;s?(y=s[u],u+=1,t[y](function(E,S){f(y,E,S)})):(y=u,u+=1,t[y](function(E,S){f(y,E,S)}))}}u=e,o?s?s.some(function(h,p){return t[h](function(g,y){f(h,g,y)}),p===e-1}):t.some(function(h,p){return h(function(g,y){f(p,g,y)}),p===e-1}):d(null),a=!1}});var qg=oe((Fq,s2)=>{"use strict";l();s2.exports=function(e){let r=e.gte!==void 0?e.gte:e.gt!==void 0?e.gt:void 0,n=e.lte!==void 0?e.lte:e.lt!==void 0?e.lt:void 0,i=e.gte===void 0,o=e.lte===void 0;return r!==void 0&&n!==void 0?IDBKeyRange.bound(r,n,i,o):r!==void 0?IDBKeyRange.lowerBound(r,i):n!==void 0?IDBKeyRange.upperBound(n,o):null}});var Fg=oe((Wq,c2)=>{"use strict";l();var CU=new TextEncoder;c2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):CU.encode(t)}});var l2=oe(f2=>{"use strict";l();var{AbstractIterator:LU}=Vg(),a2=qg(),uh=Fg(),Qn=Symbol("cache"),Vi=Symbol("finished"),Nr=Symbol("options"),qi=Symbol("currentOptions"),Js=Symbol("position"),jg=Symbol("location"),wa=Symbol("first"),u2={},Wg=class extends LU{constructor(e,r,n){super(e,n),this[Qn]=[],this[Vi]=this.limit===0,this[Nr]=n,this[qi]={...n},this[Js]=void 0,this[jg]=r,this[wa]=!0}_nextv(e,r,n){if(this[wa]=!1,this[Vi])return this.nextTick(n,null,[]);if(this[Qn].length>0)return e=Math.min(e,this[Qn].length),this.nextTick(n,null,this[Qn].splice(0,e));this[Js]!==void 0&&(this[Nr].reverse?(this[qi].lt=this[Js],this[qi].lte=void 0):(this[qi].gt=this[Js],this[qi].gte=void 0));let i;try{i=a2(this[qi])}catch{return this[Vi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[jg]],"readonly"),s=o.objectStore(this[jg]),c=[];if(this[Nr].reverse){let a=!this[Nr].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[a](i,"prev").onsuccess=u=>{let d=u.target.result;if(d){let{key:f,value:h}=d;this[Js]=f,c.push([this[Nr].keys&&f!==void 0?uh(f):void 0,this[Nr].values&&h!==void 0?uh(h):void 0]),c.length<e?d.continue():d2(o)}else this[Vi]=!0}}else{let a,u,d=()=>{if(a===void 0||u===void 0)return;let f=Math.max(a.length,u.length);f===0||e===1/0?this[Vi]=!0:this[Js]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[Nr].keys&&p!==void 0?uh(p):void 0,this[Nr].values&&g!==void 0?uh(g):void 0]}d2(o)};this[Nr].keys||e<1/0?s.getAllKeys(i,e<1/0?e:void 0).onsuccess=f=>{a=f.target.result,d()}:(a=[],this.nextTick(d)),this[Nr].values?s.getAll(i,e<1/0?e:void 0).onsuccess=f=>{u=f.target.result,d()}:(u=[],this.nextTick(d))}o.onabort=()=>{n(o.error||new Error("aborted by user")),n=null},o.oncomplete=()=>{n(null,c),n=null}}_next(e){if(this[Qn].length>0){let[r,n]=this[Qn].shift();this.nextTick(e,null,r,n)}else if(this[Vi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[wa]&&(this[wa]=!1,r=1),this._nextv(r,u2,(n,i)=>{if(n)return e(n);this[Qn]=i,this._next(e)})}}_all(e,r){this[wa]=!1;let n=this[Qn].splice(0,this[Qn].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(r,null,n);this._nextv(i,u2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[wa]=!0,this[Qn]=[],this[Vi]=!1,this[Js]=void 0,this[qi]={...this[Nr]};let n;try{n=a2(this[Nr])}catch{this[Vi]=!0;return}n!==null&&!n.includes(e)?this[Vi]=!0:this[Nr].reverse?this[qi].lte=e:this[qi].gte=e}};f2.Iterator=Wg;function d2(t){typeof t.commit=="function"&&t.commit()}});var p2=oe((Jq,h2)=>{"use strict";l();h2.exports=function(e,r,n,i,o){if(i.limit===0)return e.nextTick(o);let s=e.db.transaction([r],"readwrite"),c=s.objectStore(r),a=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let u=c.openKeyCursor?"openKeyCursor":"openCursor",d=i.reverse?"prev":"next";c[u](n,d).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(i.limit<=0||++a<i.limit)&&h.continue()})}}});var x2=oe(b2=>{"use strict";l();var{AbstractLevel:PU}=Vg(),y2=En(),MU=o2(),{fromCallback:KU}=cd(),{Iterator:$U}=l2(),g2=Fg(),HU=p2(),VU=qg(),w2="level-js-",Ed=Symbol("idb"),Gg=Symbol("namePrefix"),Fi=Symbol("location"),zg=Symbol("version"),Zs=Symbol("store"),vd=Symbol("onComplete"),m2=Symbol("promise"),dh=class extends PU{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new y2("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=r||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof e!="string")throw new Error("constructor requires a location string argument");this[Fi]=e,this[Gg]=i??w2,this[zg]=parseInt(o||1,10),this[Ed]=null}get location(){return this[Fi]}get namePrefix(){return this[Gg]}get version(){return this[zg]}get db(){return this[Ed]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[Gg]+this[Fi],this[zg]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[Ed]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[Fi])||o.createObjectStore(this[Fi])}}[Zs](e){return this[Ed].transaction([this[Fi]],e).objectStore(this[Fi])}[vd](e,r){let n=e.transaction;n.onabort=function(){r(n.error||new Error("aborted by user"))},n.oncomplete=function(){r(null,e.result)}}_get(e,r,n){let i=this[Zs]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[vd](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new y2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,g2(c))})}_getMany(e,r,n){let i=this[Zs]("readonly"),o=e.map(s=>c=>{let a;try{a=i.get(s)}catch(u){return c(u)}a.onsuccess=()=>{let u=a.result;c(null,u===void 0?u:g2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});MU(o,16,n)}_del(e,r,n){let i=this[Zs]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[vd](o,n)}_put(e,r,n,i){let o=this[Zs]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[vd](s,i)}_iterator(e){return new $U(this,this[Fi],e)}_batch(e,r,n){let i=this[Zs]("readwrite"),o=i.transaction,s=0,c;o.onabort=function(){n(c||o.error||new Error("aborted by user"))},o.oncomplete=function(){n()};function a(){let u=e[s++],d=u.key,f;try{f=u.type==="del"?i.delete(d):i.put(u.value,d)}catch(h){c=h,o.abort();return}s<e.length?f.onsuccess=a:typeof o.commit=="function"&&o.commit()}a()}_clear(e,r){let n,i;try{n=VU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return HU(this,this[Fi],n,e,r);try{let o=this[Zs]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[vd](i,r)}_close(e){this[Ed].close(),this.nextTick(e)}};dh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=w2),r=KU(r,m2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[m2]};b2.BrowserLevel=dh});var Yg=oe(E2=>{l();E2.Level=x2().BrowserLevel});var nt=oe((cF,v2)=>{"use strict";l();v2.exports={ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var ba=oe((uF,lh)=>{"use strict";l();var{AbortController:S2,AbortSignal:FU}=typeof self<"u"?self:typeof window<"u"?window:void 0;lh.exports=S2;lh.exports.AbortSignal=FU;lh.exports.default=S2});var Zt=oe((fF,Zg)=>{"use strict";l();var jU=Ar(),{kResistStopPropagation:WU,SymbolDispose:GU}=nt(),zU=globalThis.AbortSignal||ba().AbortSignal,YU=globalThis.AbortController||ba().AbortController,JU=Object.getPrototypeOf(async function(){}).constructor,A2=globalThis.Blob||jU.Blob,ZU=typeof A2<"u"?function(e){return e instanceof A2}:function(e){return!1},T2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},XU=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},Jg=class extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError(`Expected input to be an Array, got ${typeof e}`);let r="";for(let n=0;n<e.length;n++)r+=` ${e[n].stack}
2
- `;super(r),this.name="AggregateError",this.errors=e}};Zg.exports={AggregateError:Jg,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...i)=>n?r(n):e(...i))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let i=e.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof JU},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:ZU,deprecate(t,e){return t},addAbortListener:aa().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);T2(e,"signal"),XU(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[WU]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[GU](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:zU.any||function(e){if(e.length===1)return e[0];let r=new YU,n=()=>r.abort();return e.forEach(i=>{T2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};Zg.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var or=oe((hF,B2)=>{"use strict";l();var{format:QU,inspect:hh,AggregateError:eO}=Zt(),tO=globalThis.AggregateError||eO,rO=Symbol("kIsNodeError"),nO=["string","function","number","object","Function","Object","boolean","bigint","symbol"],iO=/^([A-Z][a-z0-9]*)+$/,oO="__node_internal_",ph={};function Qs(t,e){if(!t)throw new ph.ERR_INTERNAL_ASSERTION(e)}function _2(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function sO(t,e,r){if(typeof e=="function")return Qs(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return Qs(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:QU(e,...r)}function Kt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(sO(t,e,o))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[rO]=!0,ph[t]=n}function I2(t){let e=oO+t.name;return Object.defineProperty(t,"name",{value:e}),t}function cO(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new tO([e,t],e.message);return r.code=e.code,r}return t||e}var Xg=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new ph.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Kt("ERR_ASSERTION","%s",Error);Kt("ERR_INVALID_ARG_TYPE",(t,e,r)=>{Qs(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let i=[],o=[],s=[];for(let a of e)Qs(typeof a=="string","All expected entries have to be of type string"),nO.includes(a)?i.push(a.toLowerCase()):iO.test(a)?o.push(a):(Qs(a!=="object",'The value "object" should be written as "Object"'),s.push(a));if(o.length>0){let a=i.indexOf("object");a!==-1&&(i.splice(i,a,1),o.push("Object"))}if(i.length>0){switch(i.length){case 1:n+=`of type ${i[0]}`;break;case 2:n+=`one of type ${i[0]} or ${i[1]}`;break;default:{let a=i.pop();n+=`one of type ${i.join(", ")}, or ${a}`}}(o.length>0||s.length>0)&&(n+=" or ")}if(o.length>0){switch(o.length){case 1:n+=`an instance of ${o[0]}`;break;case 2:n+=`an instance of ${o[0]} or ${o[1]}`;break;default:{let a=o.pop();n+=`an instance of ${o.join(", ")}, or ${a}`}}s.length>0&&(n+=" or ")}switch(s.length){case 0:break;case 1:s[0].toLowerCase()!==s[0]&&(n+="an "),n+=`${s[0]}`;break;case 2:n+=`one of ${s[0]} or ${s[1]}`;break;default:{let a=s.pop();n+=`one of ${s.join(", ")}, or ${a}`}}if(r==null)n+=`. Received ${r}`;else if(typeof r=="function"&&r.name)n+=`. Received function ${r.name}`;else if(typeof r=="object"){var c;if((c=r.constructor)!==null&&c!==void 0&&c.name)n+=`. Received an instance of ${r.constructor.name}`;else{let a=hh(r,{depth:-1});n+=`. Received ${a}`}}else{let a=hh(r,{colors:!1});a.length>25&&(a=`${a.slice(0,25)}...`),n+=`. Received type ${typeof r} (${a})`}return n},TypeError);Kt("ERR_INVALID_ARG_VALUE",(t,e,r="is invalid")=>{let n=hh(e);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${t.includes(".")?"property":"argument"} '${t}' ${r}. Received ${n}`},TypeError);Kt("ERR_INVALID_RETURN_VALUE",(t,e,r)=>{var n;let i=r!=null&&(n=r.constructor)!==null&&n!==void 0&&n.name?`instance of ${r.constructor.name}`:`type ${typeof r}`;return`Expected ${t} to be returned from the "${e}" function but got ${i}.`},TypeError);Kt("ERR_MISSING_ARGS",(...t)=>{Qs(t.length>0,"At least one arg needs to be specified");let e,r=t.length;switch(t=(Array.isArray(t)?t:[t]).map(n=>`"${n}"`).join(" or "),r){case 1:e+=`The ${t[0]} argument`;break;case 2:e+=`The ${t[0]} and ${t[1]} arguments`;break;default:{let n=t.pop();e+=`The ${t.join(", ")}, and ${n} arguments`}break}return`${e} must be specified`},TypeError);Kt("ERR_OUT_OF_RANGE",(t,e,r)=>{Qs(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=_2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=_2(n)),n+="n"):n=hh(r),`The value of "${t}" is out of range. It must be ${e}. Received ${n}`},RangeError);Kt("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Kt("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Kt("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Kt("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Kt("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Kt("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Kt("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Kt("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Kt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Kt("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Kt("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);B2.exports={AbortError:Xg,aggregateTwoErrors:I2(cO),hideStackFrames:I2,codes:ph}});var Ea=oe((yF,M2)=>{"use strict";l();var{ArrayIsArray:em,ArrayPrototypeIncludes:D2,ArrayPrototypeJoin:k2,ArrayPrototypeMap:aO,NumberIsInteger:tm,NumberIsNaN:uO,NumberMAX_SAFE_INTEGER:dO,NumberMIN_SAFE_INTEGER:fO,NumberParseInt:lO,ObjectPrototypeHasOwnProperty:hO,RegExpPrototypeExec:N2,String:pO,StringPrototypeToUpperCase:yO,StringPrototypeTrim:gO}=nt(),{hideStackFrames:Qr,codes:{ERR_SOCKET_BAD_PORT:mO,ERR_INVALID_ARG_TYPE:Xt,ERR_INVALID_ARG_VALUE:xa,ERR_OUT_OF_RANGE:ec,ERR_UNKNOWN_SIGNAL:R2}}=or(),{normalizeEncoding:wO}=Zt(),{isAsyncFunction:bO,isArrayBufferView:xO}=Zt().types,U2={};function EO(t){return t===(t|0)}function vO(t){return t===t>>>0}var SO=/^[0-7]+$/,AO="must be a 32-bit unsigned integer or an octal string";function TO(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(N2(SO,t)===null)throw new xa(e,t,AO);t=lO(t,8)}return C2(t,e),t}var _O=Qr((t,e,r=fO,n=dO)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!tm(t))throw new ec(e,"an integer",t);if(t<r||t>n)throw new ec(e,`>= ${r} && <= ${n}`,t)}),IO=Qr((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!tm(t))throw new ec(e,"an integer",t);if(t<r||t>n)throw new ec(e,`>= ${r} && <= ${n}`,t)}),C2=Qr((t,e,r=!1)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!tm(t))throw new ec(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new ec(e,`>= ${n} && <= ${i}`,t)});function rm(t,e){if(typeof t!="string")throw new Xt(e,"string",t)}function BO(t,e,r=void 0,n){if(typeof t!="number")throw new Xt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&uO(t))throw new ec(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var RO=Qr((t,e,r)=>{if(!D2(r,t)){let i="must be one of: "+k2(aO(r,o=>typeof o=="string"?`'${o}'`:pO(o)),", ");throw new xa(e,t,i)}});function L2(t,e){if(typeof t!="boolean")throw new Xt(e,"boolean",t)}function Qg(t,e,r){return t==null||!hO(t,e)?r:t[e]}var UO=Qr((t,e,r=null)=>{let n=Qg(r,"allowArray",!1),i=Qg(r,"allowFunction",!1);if(!Qg(r,"nullable",!1)&&t===null||!n&&em(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new Xt(e,"Object",t)}),OO=Qr((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Xt(e,"a dictionary",t)}),yh=Qr((t,e,r=0)=>{if(!em(t))throw new Xt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new xa(e,t,n)}});function DO(t,e){yh(t,e);for(let r=0;r<t.length;r++)rm(t[r],`${e}[${r}]`)}function kO(t,e){yh(t,e);for(let r=0;r<t.length;r++)L2(t[r],`${e}[${r}]`)}function NO(t,e){yh(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Xt(i,"AbortSignal",n);P2(n,i)}}function CO(t,e="signal"){if(rm(t,e),U2[t]===void 0)throw U2[yO(t)]!==void 0?new R2(t+" (signals must use all capital letters)"):new R2(t)}var LO=Qr((t,e="buffer")=>{if(!xO(t))throw new Xt(e,["Buffer","TypedArray","DataView"],t)});function PO(t,e){let r=wO(e),n=t.length;if(r==="hex"&&n%2!==0)throw new xa("encoding",e,`is invalid for data of length ${n}`)}function MO(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&gO(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new mO(e,t,r);return t|0}var P2=Qr((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Xt(e,"AbortSignal",t)}),KO=Qr((t,e)=>{if(typeof t!="function")throw new Xt(e,"Function",t)}),$O=Qr((t,e)=>{if(typeof t!="function"||bO(t))throw new Xt(e,"Function",t)}),HO=Qr((t,e)=>{if(t!==void 0)throw new Xt(e,"undefined",t)});function VO(t,e,r){if(!D2(r,t))throw new Xt(e,`('${k2(r,"|")}')`,t)}var qO=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function O2(t,e){if(typeof t>"u"||!N2(qO,t))throw new xa(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function FO(t){if(typeof t=="string")return O2(t,"hints"),t;if(em(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];O2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new xa("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}M2.exports={isInt32:EO,isUint32:vO,parseFileMode:TO,validateArray:yh,validateStringArray:DO,validateBooleanArray:kO,validateAbortSignalArray:NO,validateBoolean:L2,validateBuffer:LO,validateDictionary:OO,validateEncoding:PO,validateFunction:KO,validateInt32:IO,validateInteger:_O,validateNumber:BO,validateObject:UO,validateOneOf:RO,validatePlainFunction:$O,validatePort:MO,validateSignalName:CO,validateString:rm,validateUint32:C2,validateUndefined:HO,validateUnion:VO,validateAbortSignal:P2,validateLinkHeaderValue:FO}});var ti=oe((mF,Q2)=>{"use strict";l();var{SymbolAsyncIterator:K2,SymbolIterator:$2,SymbolFor:tc}=nt(),H2=tc("nodejs.stream.destroyed"),V2=tc("nodejs.stream.errored"),nm=tc("nodejs.stream.readable"),im=tc("nodejs.stream.writable"),q2=tc("nodejs.stream.disturbed"),jO=tc("nodejs.webstream.isClosedPromise"),WO=tc("nodejs.webstream.controllerErrorFunction");function gh(t,e=!1){var r;return!!(t&&typeof t.pipe=="function"&&typeof t.on=="function"&&(!e||typeof t.pause=="function"&&typeof t.resume=="function")&&(!t._writableState||((r=t._readableState)===null||r===void 0?void 0:r.readable)!==!1)&&(!t._writableState||t._readableState))}function mh(t){var e;return!!(t&&typeof t.write=="function"&&typeof t.on=="function"&&(!t._readableState||((e=t._writableState)===null||e===void 0?void 0:e.writable)!==!1))}function GO(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function ei(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function F2(t){return!!(t&&!ei(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function j2(t){return!!(t&&!ei(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function W2(t){return!!(t&&!ei(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function zO(t){return F2(t)||j2(t)||W2(t)}function YO(t,e){return t==null?!1:e===!0?typeof t[K2]=="function":e===!1?typeof t[$2]=="function":typeof t[K2]=="function"||typeof t[$2]=="function"}function wh(t){if(!ei(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[H2]||n!=null&&n.destroyed)}function G2(t){if(!mh(t))return null;if(t.writableEnded===!0)return!0;let e=t._writableState;return e!=null&&e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function JO(t,e){if(!mh(t))return null;if(t.writableFinished===!0)return!0;let r=t._writableState;return r!=null&&r.errored?!1:typeof r?.finished!="boolean"?null:!!(r.finished||e===!1&&r.ended===!0&&r.length===0)}function ZO(t){if(!gh(t))return null;if(t.readableEnded===!0)return!0;let e=t._readableState;return!e||e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function z2(t,e){if(!gh(t))return null;let r=t._readableState;return r!=null&&r.errored?!1:typeof r?.endEmitted!="boolean"?null:!!(r.endEmitted||e===!1&&r.ended===!0&&r.length===0)}function Y2(t){return t&&t[nm]!=null?t[nm]:typeof t?.readable!="boolean"?null:wh(t)?!1:gh(t)&&t.readable&&!z2(t)}function J2(t){return t&&t[im]!=null?t[im]:typeof t?.writable!="boolean"?null:wh(t)?!1:mh(t)&&t.writable&&!G2(t)}function XO(t,e){return ei(t)?wh(t)?!0:!(e?.readable!==!1&&Y2(t)||e?.writable!==!1&&J2(t)):null}function QO(t){var e,r;return ei(t)?t.writableErrored?t.writableErrored:(e=(r=t._writableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function e5(t){var e,r;return ei(t)?t.readableErrored?t.readableErrored:(e=(r=t._readableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function t5(t){if(!ei(t))return null;if(typeof t.closed=="boolean")return t.closed;let e=t._writableState,r=t._readableState;return typeof e?.closed=="boolean"||typeof r?.closed=="boolean"?e?.closed||r?.closed:typeof t._closed=="boolean"&&Z2(t)?t._closed:null}function Z2(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function X2(t){return typeof t._sent100=="boolean"&&Z2(t)}function r5(t){var e;return typeof t._consuming=="boolean"&&typeof t._dumped=="boolean"&&((e=t.req)===null||e===void 0?void 0:e.upgradeOrConnect)===void 0}function n5(t){if(!ei(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&X2(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function i5(t){var e;return!!(t&&((e=t[q2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function o5(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[V2])!==null&&s!==void 0?s:t.readableErrored)!==null&&o!==void 0?o:t.writableErrored)!==null&&i!==void 0?i:(c=t._readableState)===null||c===void 0?void 0:c.errorEmitted)!==null&&n!==void 0?n:(a=t._writableState)===null||a===void 0?void 0:a.errorEmitted)!==null&&r!==void 0?r:(u=t._readableState)===null||u===void 0?void 0:u.errored)!==null&&e!==void 0?e:!((d=t._writableState)===null||d===void 0)&&d.errored))}Q2.exports={isDestroyed:wh,kIsDestroyed:H2,isDisturbed:i5,kIsDisturbed:q2,isErrored:o5,kIsErrored:V2,isReadable:Y2,kIsReadable:nm,kIsClosedPromise:jO,kControllerErrorFunction:WO,kIsWritable:im,isClosed:t5,isDuplexNodeStream:GO,isFinished:XO,isIterable:YO,isReadableNodeStream:gh,isReadableStream:F2,isReadableEnded:ZO,isReadableFinished:z2,isReadableErrored:e5,isNodeStream:ei,isWebStream:zO,isWritable:J2,isWritableNodeStream:mh,isWritableStream:j2,isWritableEnded:G2,isWritableFinished:JO,isWritableErrored:QO,isServerRequest:r5,isServerResponse:X2,willEmitClose:n5,isTransformStream:W2}});var ji=oe((bF,um)=>{l();var Ho=xi(),{AbortError:aS,codes:s5}=or(),{ERR_INVALID_ARG_TYPE:c5,ERR_STREAM_PREMATURE_CLOSE:eS}=s5,{kEmptyObject:sm,once:cm}=Zt(),{validateAbortSignal:a5,validateFunction:u5,validateObject:d5,validateBoolean:f5}=Ea(),{Promise:l5,PromisePrototypeThen:h5,SymbolDispose:uS}=nt(),{isClosed:p5,isReadable:tS,isReadableNodeStream:om,isReadableStream:y5,isReadableFinished:rS,isReadableErrored:nS,isWritable:iS,isWritableNodeStream:oS,isWritableStream:g5,isWritableFinished:sS,isWritableErrored:cS,isNodeStream:m5,willEmitClose:w5,kIsClosedPromise:b5}=ti(),va;function x5(t){return t.setHeader&&typeof t.abort=="function"}var am=()=>{};function dS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=sm):e==null?e=sm:d5(e,"options"),u5(r,"callback"),a5(e.signal,"options.signal"),r=cm(r),y5(t)||g5(t))return E5(t,e,r);if(!m5(t))throw new c5("stream",["ReadableStream","WritableStream","Stream"],t);let o=(n=e.readable)!==null&&n!==void 0?n:om(t),s=(i=e.writable)!==null&&i!==void 0?i:oS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=w5(t)&&om(t)===o&&oS(t)===s,f=sS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=rS(t,!1),g=()=>{p=!0,t.destroyed&&(d=!1),!(d&&(!t.writable||s))&&(!s||f)&&r.call(t)},y=T=>{r.call(t,T)},E=p5(t),S=()=>{E=!0;let T=cS(t)||nS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&om(t,!0)&&!rS(t,!1))return r.call(t,new eS);if(s&&!f&&!sS(t,!1))return r.call(t,new eS);r.call(t)},I=()=>{E=!0;let T=cS(t)||nS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};x5(t)?(t.on("complete",h),d||t.on("abort",S),t.req?A():t.on("request",A)):s&&!c&&(t.on("end",u),t.on("close",u)),!d&&typeof t.aborted=="boolean"&&t.on("aborted",S),t.on("end",g),t.on("finish",h),e.error!==!1&&t.on("error",y),t.on("close",S),E?Ho.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||Ho.nextTick(I):(!o&&(!d||tS(t))&&(f||iS(t)===!1)||!s&&(!d||iS(t))&&(p||tS(t)===!1)||a&&t.req&&t.aborted)&&Ho.nextTick(I);let O=()=>{r=am,t.removeListener("aborted",S),t.removeListener("complete",h),t.removeListener("abort",S),t.removeListener("request",A),t.req&&t.req.removeListener("finish",h),t.removeListener("end",u),t.removeListener("close",u),t.removeListener("finish",h),t.removeListener("end",g),t.removeListener("error",y),t.removeListener("close",S)};if(e.signal&&!E){let T=()=>{let M=r;O(),M.call(t,new aS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)Ho.nextTick(T);else{va=va||Zt().addAbortListener;let M=va(e.signal,T),q=r;r=cm((...j)=>{M[uS](),q.apply(t,j)})}}return O}function E5(t,e,r){let n=!1,i=am;if(e.signal)if(i=()=>{n=!0,r.call(t,new aS(void 0,{cause:e.signal.reason}))},e.signal.aborted)Ho.nextTick(i);else{va=va||Zt().addAbortListener;let s=va(e.signal,i),c=r;r=cm((...a)=>{s[uS](),c.apply(t,a)})}let o=(...s)=>{n||Ho.nextTick(()=>r.apply(t,s))};return h5(t[b5].promise,o,o),am}function v5(t,e){var r;let n=!1;return e===null&&(e=sm),(r=e)!==null&&r!==void 0&&r.cleanup&&(f5(e.cleanup,"cleanup"),n=e.cleanup),new l5((i,o)=>{let s=dS(t,e,c=>{n&&s(),c?o(c):i()})})}um.exports=dS;um.exports.finished=v5});var rc=oe((EF,wS)=>{"use strict";l();var ri=xi(),{aggregateTwoErrors:S5,codes:{ERR_MULTIPLE_CALLBACK:A5},AbortError:T5}=or(),{Symbol:hS}=nt(),{kIsDestroyed:_5,isDestroyed:I5,isFinished:B5,isServerRequest:R5}=ti(),pS=hS("kDestroy"),dm=hS("kConstruct");function yS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function U5(t,e){let r=this._readableState,n=this._writableState,i=n||r;return n!=null&&n.destroyed||r!=null&&r.destroyed?(typeof e=="function"&&e(),this):(yS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?fS(this,t,e):this.once(pS,function(o){fS(this,S5(o,t),e)}),this)}function fS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;yS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ri.nextTick(O5,t,o):ri.nextTick(gS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function O5(t,e){fm(t,e),gS(t)}function gS(t){let e=t._readableState,r=t._writableState;r&&(r.closeEmitted=!0),e&&(e.closeEmitted=!0),(r!=null&&r.emitClose||e!=null&&e.emitClose)&&t.emit("close")}function fm(t,e){let r=t._readableState,n=t._writableState;n!=null&&n.errorEmitted||r!=null&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),t.emit("error",e))}function D5(){let t=this._readableState,e=this._writableState;t&&(t.constructed=!0,t.closed=!1,t.closeEmitted=!1,t.destroyed=!1,t.errored=null,t.errorEmitted=!1,t.reading=!1,t.ended=t.readable===!1,t.endEmitted=t.readable===!1),e&&(e.constructed=!0,e.destroyed=!1,e.closed=!1,e.closeEmitted=!1,e.errored=null,e.errorEmitted=!1,e.finalCalled=!1,e.prefinished=!1,e.ended=e.writable===!1,e.ending=e.writable===!1,e.finished=e.writable===!1)}function lm(t,e,r){let n=t._readableState,i=t._writableState;if(i!=null&&i.destroyed||n!=null&&n.destroyed)return this;n!=null&&n.autoDestroy||i!=null&&i.autoDestroy?t.destroy(e):e&&(e.stack,i&&!i.errored&&(i.errored=e),n&&!n.errored&&(n.errored=e),r?ri.nextTick(fm,t,e):fm(t,e))}function k5(t,e){if(typeof t._construct!="function")return;let r=t._readableState,n=t._writableState;r&&(r.constructed=!1),n&&(n.constructed=!1),t.once(dm,e),!(t.listenerCount(dm)>1)&&ri.nextTick(N5,t)}function N5(t){let e=!1;function r(n){if(e){lm(t,n??new A5);return}e=!0;let i=t._readableState,o=t._writableState,s=o||i;i&&(i.constructed=!0),o&&(o.constructed=!0),s.destroyed?t.emit(pS,n):n?lm(t,n,!0):ri.nextTick(C5,t)}try{t._construct(n=>{ri.nextTick(r,n)})}catch(n){ri.nextTick(r,n)}}function C5(t){t.emit(dm)}function lS(t){return t?.setHeader&&typeof t.abort=="function"}function mS(t){t.emit("close")}function L5(t,e){t.emit("error",e),ri.nextTick(mS,t)}function P5(t,e){!t||I5(t)||(!e&&!B5(t)&&(e=new T5),R5(t)?(t.socket=null,t.destroy(e)):lS(t)?t.abort():lS(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ri.nextTick(L5,t,e):ri.nextTick(mS,t),t.destroyed||(t[_5]=!0))}wS.exports={construct:k5,destroyer:P5,destroy:U5,undestroy:D5,errorOrDestroy:lm}});var Eh=oe((SF,xS)=>{"use strict";l();var{ArrayIsArray:M5,ObjectSetPrototypeOf:bS}=nt(),{EventEmitter:bh}=aa();function xh(t){bh.call(this,t)}bS(xh.prototype,bh.prototype);bS(xh,bh);xh.prototype.pipe=function(t,e){let r=this;function n(d){t.writable&&t.write(d)===!1&&r.pause&&r.pause()}r.on("data",n);function i(){r.readable&&r.resume&&r.resume()}t.on("drain",i),!t._isStdio&&(!e||e.end!==!1)&&(r.on("end",s),r.on("close",c));let o=!1;function s(){o||(o=!0,t.end())}function c(){o||(o=!0,typeof t.destroy=="function"&&t.destroy())}function a(d){u(),bh.listenerCount(this,"error")===0&&this.emit("error",d)}hm(r,"error",a),hm(t,"error",a);function u(){r.removeListener("data",n),t.removeListener("drain",i),r.removeListener("end",s),r.removeListener("close",c),r.removeListener("error",a),t.removeListener("error",a),r.removeListener("end",u),r.removeListener("close",u),t.removeListener("close",u)}return r.on("end",u),r.on("close",u),t.on("close",u),t.emit("pipe",r),t};function hm(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):M5(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}xS.exports={Stream:xh,prependListener:hm}});var Sd=oe((TF,vh)=>{"use strict";l();var{SymbolDispose:K5}=nt(),{AbortError:ES,codes:$5}=or(),{isNodeStream:vS,isWebStream:H5,kControllerErrorFunction:V5}=ti(),q5=ji(),{ERR_INVALID_ARG_TYPE:SS}=$5,pm,F5=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new SS(e,"AbortSignal",t)};vh.exports.addAbortSignal=function(e,r){if(F5(e,"signal"),!vS(r)&&!H5(r))throw new SS("stream",["ReadableStream","WritableStream","Stream"],r);return vh.exports.addAbortSignalNoValidate(e,r)};vh.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=vS(e)?()=>{e.destroy(new ES(void 0,{cause:t.reason}))}:()=>{e[V5](new ES(void 0,{cause:t.reason}))};if(t.aborted)r();else{pm=pm||Zt().addAbortListener;let n=pm(t,r);q5(e,n[K5])}return e}});var _S=oe((BF,TS)=>{"use strict";l();var{StringPrototypeSlice:AS,SymbolIterator:j5,TypedArrayPrototypeSet:Sh,Uint8Array:W5}=nt(),{Buffer:ym}=Ar(),{inspect:G5}=Zt();TS.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){let r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length}unshift(e){let r={data:e,next:this.head};this.length===0&&(this.tail=r),this.head=r,++this.length}shift(){if(this.length===0)return;let e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(this.length===0)return"";let r=this.head,n=""+r.data;for(;(r=r.next)!==null;)n+=e+r.data;return n}concat(e){if(this.length===0)return ym.alloc(0);let r=ym.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)Sh(r,n.data,i),i+=n.data.length,n=n.next;return r}consume(e,r){let n=this.head.data;if(e<n.length){let i=n.slice(0,e);return this.head.data=n.slice(e),i}return e===n.length?this.shift():r?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[j5](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let r="",n=this.head,i=0;do{let o=n.data;if(e>o.length)r+=o,e-=o.length;else{e===o.length?(r+=o,++i,n.next?this.head=n.next:this.head=this.tail=null):(r+=AS(o,0,e),this.head=n,n.data=AS(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=ym.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)Sh(r,s,n-e),e-=s.length;else{e===s.length?(Sh(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Sh(r,new W5(s.buffer,s.byteOffset,e),n-e),this.head=i,i.data=s.slice(e));break}++o}while((i=i.next)!==null);return this.length-=o,r}[Symbol.for("nodejs.util.inspect.custom")](e,r){return G5(this,{...r,depth:0,customInspect:!1})}}});var Ad=oe((UF,US)=>{"use strict";l();var{MathFloor:z5,NumberIsInteger:Y5}=nt(),{validateInteger:J5}=Ea(),{ERR_INVALID_ARG_VALUE:Z5}=or().codes,IS=16*1024,BS=16;function X5(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function RS(t){return t?BS:IS}function Q5(t,e){J5(e,"value",0),t?BS=e:IS=e}function e3(t,e,r,n){let i=X5(e,n,r);if(i!=null){if(!Y5(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new Z5(o,i)}return z5(i)}return RS(t.objectMode)}US.exports={getHighWaterMark:e3,getDefaultHighWaterMark:RS,setDefaultHighWaterMark:Q5}});var kS=oe((gm,DS)=>{l();var Ah=Ar(),ni=Ah.Buffer;function OS(t,e){for(var r in t)e[r]=t[r]}ni.from&&ni.alloc&&ni.allocUnsafe&&ni.allocUnsafeSlow?DS.exports=Ah:(OS(Ah,gm),gm.Buffer=nc);function nc(t,e,r){return ni(t,e,r)}nc.prototype=Object.create(ni.prototype);OS(ni,nc);nc.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ni(t,e,r)};nc.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=ni(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};nc.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ni(t)};nc.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Ah.SlowBuffer(t)}});var LS=oe(CS=>{"use strict";l();var wm=kS().Buffer,NS=wm.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function t3(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function r3(t){var e=t3(t);if(typeof e!="string"&&(wm.isEncoding===NS||!NS(t)))throw new Error("Unknown encoding: "+t);return e||t}CS.StringDecoder=Td;function Td(t){this.encoding=r3(t);var e;switch(this.encoding){case"utf16le":this.text=a3,this.end=u3,e=4;break;case"utf8":this.fillLast=o3,e=4;break;case"base64":this.text=d3,this.end=f3,e=3;break;default:this.write=l3,this.end=h3;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=wm.allocUnsafe(e)}Td.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||""};Td.prototype.end=c3;Td.prototype.text=s3;Td.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};function mm(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function n3(t,e,r){var n=e.length-1;if(n<r)return 0;var i=mm(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=mm(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=mm(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function i3(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function o3(t){var e=this.lastTotal-this.lastNeed,r=i3(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function s3(t,e){var r=n3(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function c3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function a3(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function u3(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function d3(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function f3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function l3(t){return t.toString(this.encoding)}function h3(t){return t&&t.length?this.write(t):""}});var bm=oe((CF,$S)=>{"use strict";l();var PS=xi(),{PromisePrototypeThen:p3,SymbolAsyncIterator:MS,SymbolIterator:KS}=nt(),{Buffer:y3}=Ar(),{ERR_INVALID_ARG_TYPE:g3,ERR_STREAM_NULL_VALUES:m3}=or().codes;function w3(t,e,r){let n;if(typeof e=="string"||e instanceof y3)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[MS])i=!0,n=e[MS]();else if(e&&e[KS])i=!1,n=e[KS]();else throw new g3("iterable",["Iterable"],e);let o=new t({objectMode:!0,highWaterMark:1,...r}),s=!1;o._read=function(){s||(s=!0,a())},o._destroy=function(u,d){p3(c(u),()=>PS.nextTick(d,u),f=>PS.nextTick(d,f||u))};async function c(u){let d=u!=null,f=typeof n.throw=="function";if(d&&f){let{value:h,done:p}=await n.throw(u);if(await h,p)return}if(typeof n.return=="function"){let{value:h}=await n.return();await h}}async function a(){for(;;){try{let{value:u,done:d}=i?await n.next():n.next();if(d)o.push(null);else{let f=u&&typeof u.then=="function"?await u:u;if(f===null)throw s=!1,new m3;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}$S.exports=w3});var Id=oe((PF,iA)=>{l();var An=xi(),{ArrayPrototypeIndexOf:b3,NumberIsInteger:x3,NumberIsNaN:E3,NumberParseInt:v3,ObjectDefineProperties:Im,ObjectKeys:S3,ObjectSetPrototypeOf:qS,Promise:FS,SafeSet:A3,SymbolAsyncDispose:T3,SymbolAsyncIterator:_3,Symbol:I3}=nt();iA.exports=ye;ye.ReadableState=Bh;var{EventEmitter:B3}=aa(),{Stream:Vo,prependListener:R3}=Eh(),{Buffer:xm}=Ar(),{addAbortSignal:U3}=Sd(),jS=ji(),xe=Zt().debuglog("stream",t=>{xe=t}),O3=_S(),Ta=rc(),{getHighWaterMark:D3,getDefaultHighWaterMark:k3}=Ad(),{aggregateTwoErrors:HS,codes:{ERR_INVALID_ARG_TYPE:N3,ERR_METHOD_NOT_IMPLEMENTED:C3,ERR_OUT_OF_RANGE:L3,ERR_STREAM_PUSH_AFTER_EOF:P3,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:M3},AbortError:K3}=or(),{validateObject:$3}=Ea(),ic=I3("kPaused"),{StringDecoder:WS}=LS(),H3=bm();qS(ye.prototype,Vo.prototype);qS(ye,Vo);var Em=()=>{},{errorOrDestroy:Sa}=Ta,Aa=1,V3=2,GS=4,_d=8,zS=16,Th=32,_h=64,YS=128,q3=256,F3=512,j3=1024,Tm=2048,_m=4096,W3=8192,G3=16384,z3=32768,JS=65536,Y3=1<<17,J3=1<<18;function At(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Im(Bh.prototype,{objectMode:At(Aa),ended:At(V3),endEmitted:At(GS),reading:At(_d),constructed:At(zS),sync:At(Th),needReadable:At(_h),emittedReadable:At(YS),readableListening:At(q3),resumeScheduled:At(F3),errorEmitted:At(j3),emitClose:At(Tm),autoDestroy:At(_m),destroyed:At(W3),closed:At(G3),closeEmitted:At(z3),multiAwaitDrain:At(JS),readingMore:At(Y3),dataEmitted:At(J3)});function Bh(t,e,r){typeof r!="boolean"&&(r=e instanceof ii()),this.state=Tm|_m|zS|Th,t&&t.objectMode&&(this.state|=Aa),r&&t&&t.readableObjectMode&&(this.state|=Aa),this.highWaterMark=t?D3(this,t,"readableHighWaterMark",r):k3(!1),this.buffer=new O3,this.length=0,this.pipes=[],this.flowing=null,this[ic]=null,t&&t.emitClose===!1&&(this.state&=~Tm),t&&t.autoDestroy===!1&&(this.state&=~_m),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new WS(t.encoding),this.encoding=t.encoding)}function ye(t){if(!(this instanceof ye))return new ye(t);let e=this instanceof ii();this._readableState=new Bh(t,this,e),t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&!e&&U3(t.signal,this)),Vo.call(this,t),Ta.construct(this,()=>{this._readableState.needReadable&&Ih(this,this._readableState)})}ye.prototype.destroy=Ta.destroy;ye.prototype._undestroy=Ta.undestroy;ye.prototype._destroy=function(t,e){e(t)};ye.prototype[B3.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[T3]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new K3,this.destroy(t)),new FS((e,r)=>jS(this,n=>n&&n!==t?r(n):e(null)))};ye.prototype.push=function(t,e){return ZS(this,t,e,!1)};ye.prototype.unshift=function(t,e){return ZS(this,t,e,!0)};function ZS(t,e,r,n){xe("readableAddChunk",e);let i=t._readableState,o;if(i.state&Aa||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=xm.from(e,r).toString(i.encoding):(e=xm.from(e,r),r=""))):e instanceof xm?r="":Vo._isUint8Array(e)?(e=Vo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new N3("chunk",["string","Buffer","Uint8Array"],e))),o)Sa(t,o);else if(e===null)i.state&=~_d,Q3(t,i);else if(i.state&Aa||e&&e.length>0)if(n)if(i.state&GS)Sa(t,new M3);else{if(i.destroyed||i.errored)return!1;vm(t,i,e,!0)}else if(i.ended)Sa(t,new P3);else{if(i.destroyed||i.errored)return!1;i.state&=~_d,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?vm(t,i,e,!1):Ih(t,i)):vm(t,i,e,!1)}else n||(i.state&=~_d,Ih(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function vm(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&JS?e.awaitDrainWriters.clear():e.awaitDrainWriters=null,e.dataEmitted=!0,t.emit("data",r)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.state&_h&&Rh(t)),Ih(t,e)}ye.prototype.isPaused=function(){let t=this._readableState;return t[ic]===!0||t.flowing===!1};ye.prototype.setEncoding=function(t){let e=new WS(t);this._readableState.decoder=e,this._readableState.encoding=this._readableState.decoder.encoding;let r=this._readableState.buffer,n="";for(let i of r)n+=e.write(i);return r.clear(),n!==""&&r.push(n),this._readableState.length=n.length,this};var Z3=1073741824;function X3(t){if(t>Z3)throw new L3("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function VS(t,e){return t<=0||e.length===0&&e.ended?0:e.state&Aa?1:E3(t)?e.flowing&&e.length?e.buffer.first().length:e.length:t<=e.length?t:e.ended?e.length:0}ye.prototype.read=function(t){xe("read",t),t===void 0?t=NaN:x3(t)||(t=v3(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=X3(t)),t!==0&&(e.state&=~YS),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return xe("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Sm(this):Rh(this),null;if(t=VS(t,e),t===0&&e.ended)return e.length===0&&Sm(this),null;let n=(e.state&_h)!==0;if(xe("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,xe("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,xe("reading, ended or constructing",n);else if(n){xe("do read"),e.state|=_d|Th,e.length===0&&(e.state|=_h);try{this._read(e.highWaterMark)}catch(o){Sa(this,o)}e.state&=~Th,e.reading||(t=VS(r,e))}let i;return t>0?i=rA(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.multiAwaitDrain?e.awaitDrainWriters.clear():e.awaitDrainWriters=null),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Sm(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function Q3(t,e){if(xe("onEofChunk"),!e.ended){if(e.decoder){let r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?Rh(t):(e.needReadable=!1,e.emittedReadable=!0,XS(t))}}function Rh(t){let e=t._readableState;xe("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(xe("emitReadable",e.flowing),e.emittedReadable=!0,An.nextTick(XS,t))}function XS(t){let e=t._readableState;xe("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&!e.errored&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,eA(t)}function Ih(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,An.nextTick(eD,t,e))}function eD(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(xe("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}ye.prototype._read=function(t){throw new C3("_read()")};ye.prototype.pipe=function(t,e){let r=this,n=this._readableState;n.pipes.length===1&&(n.multiAwaitDrain||(n.multiAwaitDrain=!0,n.awaitDrainWriters=new A3(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),xe("pipe count=%d opts=%j",n.pipes.length,e);let o=(!e||e.end!==!1)&&t!==An.stdout&&t!==An.stderr?c:E;n.endEmitted?An.nextTick(o):r.once("end",o),t.on("unpipe",s);function s(S,I){xe("onunpipe"),S===r&&I&&I.hasUnpiped===!1&&(I.hasUnpiped=!0,d())}function c(){xe("onend"),t.end()}let a,u=!1;function d(){xe("cleanup"),t.removeListener("close",g),t.removeListener("finish",y),a&&t.removeListener("drain",a),t.removeListener("error",p),t.removeListener("unpipe",s),r.removeListener("end",c),r.removeListener("end",E),r.removeListener("data",h),u=!0,a&&n.awaitDrainWriters&&(!t._writableState||t._writableState.needDrain)&&a()}function f(){u||(n.pipes.length===1&&n.pipes[0]===t?(xe("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(xe("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=tD(r,t),t.on("drain",a))}r.on("data",h);function h(S){xe("ondata");let I=t.write(S);xe("dest.write",I),I===!1&&f()}function p(S){if(xe("onerror",S),E(),t.removeListener("error",p),t.listenerCount("error")===0){let I=t._writableState||t._readableState;I&&!I.errorEmitted?Sa(t,S):t.emit("error",S)}}R3(t,"error",p);function g(){t.removeListener("finish",y),E()}t.once("close",g);function y(){xe("onfinish"),t.removeListener("close",g),E()}t.once("finish",y);function E(){xe("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(xe("pipe resume"),r.resume()),t};function tD(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(xe("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(xe("pipeOnDrain",n.awaitDrainWriters.size),n.awaitDrainWriters.delete(e)),(!n.awaitDrainWriters||n.awaitDrainWriters.size===0)&&t.listenerCount("data")&&t.resume()}}ye.prototype.unpipe=function(t){let e=this._readableState,r={hasUnpiped:!1};if(e.pipes.length===0)return this;if(!t){let i=e.pipes;e.pipes=[],this.pause();for(let o=0;o<i.length;o++)i[o].emit("unpipe",this,{hasUnpiped:!1});return this}let n=b3(e.pipes,t);return n===-1?this:(e.pipes.splice(n,1),e.pipes.length===0&&this.pause(),t.emit("unpipe",this,r),this)};ye.prototype.on=function(t,e){let r=Vo.prototype.on.call(this,t,e),n=this._readableState;return t==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,xe("on readable",n.length,n.reading),n.length?Rh(this):n.reading||An.nextTick(rD,this)),r};ye.prototype.addListener=ye.prototype.on;ye.prototype.removeListener=function(t,e){let r=Vo.prototype.removeListener.call(this,t,e);return t==="readable"&&An.nextTick(QS,this),r};ye.prototype.off=ye.prototype.removeListener;ye.prototype.removeAllListeners=function(t){let e=Vo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&An.nextTick(QS,this),e};function QS(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[ic]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function rD(t){xe("readable nexttick read 0"),t.read(0)}ye.prototype.resume=function(){let t=this._readableState;return t.flowing||(xe("resume"),t.flowing=!t.readableListening,nD(this,t)),t[ic]=!1,this};function nD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,An.nextTick(iD,t,e))}function iD(t,e){xe("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),eA(t),e.flowing&&!e.reading&&t.read(0)}ye.prototype.pause=function(){return xe("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(xe("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[ic]=!0,this};function eA(t){let e=t._readableState;for(xe("flow",e.flowing);e.flowing&&t.read()!==null;);}ye.prototype.wrap=function(t){let e=!1;t.on("data",n=>{!this.push(n)&&t.pause&&(e=!0,t.pause())}),t.on("end",()=>{this.push(null)}),t.on("error",n=>{Sa(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=S3(t);for(let n=1;n<r.length;n++){let i=r[n];this[i]===void 0&&typeof t[i]=="function"&&(this[i]=t[i].bind(t))}return this};ye.prototype[_3]=function(){return tA(this)};ye.prototype.iterator=function(t){return t!==void 0&&$3(t,"options"),tA(this,t)};function tA(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=oD(t,e);return r.stream=t,r}async function*oD(t,e){let r=Em;function n(s){this===t?(r(),r=Em):r=s}t.on("readable",n);let i,o=jS(t,{writable:!1},s=>{i=s?HS(i,s):null,r(),r=Em});try{for(;;){let s=t.destroyed?null:t.read();if(s!==null)yield s;else{if(i)throw i;if(i===null)return;await new FS(n)}}}catch(s){throw i=HS(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Ta.destroyer(t,null):(t.off("readable",n),o())}}Im(ye.prototype,{readable:{__proto__:null,get(){let t=this._readableState;return!!t&&t.readable!==!1&&!t.destroyed&&!t.errorEmitted&&!t.endEmitted},set(t){this._readableState&&(this._readableState.readable=!!t)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(t){this._readableState&&(this._readableState.destroyed=t)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});Im(Bh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[ic]!==!1},set(t){this[ic]=!!t}}});ye._fromList=rA;function rA(t,e){if(e.length===0)return null;let r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Sm(t){let e=t._readableState;xe("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,An.nextTick(sD,e,t))}function sD(t,e){if(xe("endReadableNT",t.endEmitted,t.length),!t.errored&&!t.closeEmitted&&!t.endEmitted&&t.length===0){if(t.endEmitted=!0,e.emit("end"),e.writable&&e.allowHalfOpen===!1)An.nextTick(cD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function cD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return H3(ye,t,e)};var Am;function nA(){return Am===void 0&&(Am={}),Am}ye.fromWeb=function(t,e){return nA().newStreamReadableFromReadableStream(t,e)};ye.toWeb=function(t,e){return nA().newReadableStreamFromStreamReadable(t,e)};ye.wrap=function(t,e){var r,n;return new ye({objectMode:(r=(n=t.readableObjectMode)!==null&&n!==void 0?n:t.objectMode)!==null&&r!==void 0?r:!0,...e,destroy(i,o){Ta.destroyer(t,i),o(i)}}).wrap(t)}});var Nh=oe((KF,gA)=>{l();var oc=xi(),{ArrayPrototypeSlice:cA,Error:aD,FunctionPrototypeSymbolHasInstance:aA,ObjectDefineProperty:uA,ObjectDefineProperties:uD,ObjectSetPrototypeOf:dA,StringPrototypeToLowerCase:dD,Symbol:fD,SymbolHasInstance:lD}=nt();gA.exports=it;it.WritableState=Ud;var{EventEmitter:hD}=aa(),Bd=Eh().Stream,{Buffer:Uh}=Ar(),kh=rc(),{addAbortSignal:pD}=Sd(),{getHighWaterMark:yD,getDefaultHighWaterMark:gD}=Ad(),{ERR_INVALID_ARG_TYPE:mD,ERR_METHOD_NOT_IMPLEMENTED:wD,ERR_MULTIPLE_CALLBACK:fA,ERR_STREAM_CANNOT_PIPE:bD,ERR_STREAM_DESTROYED:Rd,ERR_STREAM_ALREADY_FINISHED:xD,ERR_STREAM_NULL_VALUES:ED,ERR_STREAM_WRITE_AFTER_END:vD,ERR_UNKNOWN_ENCODING:lA}=or().codes,{errorOrDestroy:_a}=kh;dA(it.prototype,Bd.prototype);dA(it,Bd);function Um(){}var Ia=fD("kOnFinished");function Ud(t,e,r){typeof r!="boolean"&&(r=e instanceof ii()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?yD(this,t,"writableHighWaterMark",r):gD(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let n=!!(t&&t.decodeStrings===!1);this.decodeStrings=!n,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=AD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,Dh(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!t||t.emitClose!==!1,this.autoDestroy=!t||t.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[Ia]=[]}function Dh(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Ud.prototype.getBuffer=function(){return cA(this.buffered,this.bufferedIndex)};uA(Ud.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function it(t){let e=this instanceof ii();if(!e&&!aA(it,this))return new it(t);this._writableState=new Ud(t,this,e),t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&pD(t.signal,this)),Bd.call(this,t),kh.construct(this,()=>{let r=this._writableState;r.writing||Dm(this,r),km(this,r)})}uA(it,lD,{__proto__:null,value:function(t){return aA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Ud}});it.prototype.pipe=function(){_a(this,new bD)};function hA(t,e,r,n){let i=t._writableState;if(typeof r=="function")n=r,r=i.defaultEncoding;else{if(!r)r=i.defaultEncoding;else if(r!=="buffer"&&!Uh.isEncoding(r))throw new lA(r);typeof n!="function"&&(n=Um)}if(e===null)throw new ED;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Uh.from(e,r),r="buffer");else if(e instanceof Uh)r="buffer";else if(Bd._isUint8Array(e))e=Bd._uint8ArrayToBuffer(e),r="buffer";else throw new mD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new vD:i.destroyed&&(o=new Rd("write")),o?(oc.nextTick(n,o),_a(t,o,!0),o):(i.pendingcb++,SD(t,i,e,r,n))}it.prototype.write=function(t,e,r){return hA(this,t,e,r)===!0};it.prototype.cork=function(){this._writableState.corked++};it.prototype.uncork=function(){let t=this._writableState;t.corked&&(t.corked--,t.writing||Dm(this,t))};it.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=dD(e)),!Uh.isEncoding(e))throw new lA(e);return this._writableState.defaultEncoding=e,this};function SD(t,e,r,n,i){let o=e.objectMode?1:r.length;e.length+=o;let s=e.length<e.highWaterMark;return s||(e.needDrain=!0),e.writing||e.corked||e.errored||!e.constructed?(e.buffered.push({chunk:r,encoding:n,callback:i}),e.allBuffers&&n!=="buffer"&&(e.allBuffers=!1),e.allNoop&&i!==Um&&(e.allNoop=!1)):(e.writelen=o,e.writecb=i,e.writing=!0,e.sync=!0,t._write(r,n,e.onwrite),e.sync=!1),s&&!e.errored&&!e.destroyed}function oA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new Rd("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function sA(t,e,r,n){--e.pendingcb,n(r),Om(e),_a(t,r)}function AD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){_a(t,new fA);return}r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,e?(e.stack,r.errored||(r.errored=e),t._readableState&&!t._readableState.errored&&(t._readableState.errored=e),n?oc.nextTick(sA,t,r,e,i):sA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&Dm(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},oc.nextTick(TD,r.afterWriteTickInfo)):pA(t,r,1,i))}function TD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,pA(t,e,r,n)}function pA(t,e,r,n){for(!e.ending&&!t.destroyed&&e.length===0&&e.needDrain&&(e.needDrain=!1,t.emit("drain"));r-- >0;)e.pendingcb--,n();e.destroyed&&Om(e),km(t,e)}function Om(t){if(t.writing)return;for(let i=t.bufferedIndex;i<t.buffered.length;++i){var e;let{chunk:o,callback:s}=t.buffered[i],c=t.objectMode?1:o.length;t.length-=c,s((e=t.errored)!==null&&e!==void 0?e:new Rd("write"))}let r=t[Ia].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new Rd("end"))}Dh(t)}function Dm(t,e){if(e.corked||e.bufferProcessing||e.destroyed||!e.constructed)return;let{buffered:r,bufferedIndex:n,objectMode:i}=e,o=r.length-n;if(!o)return;let s=n;if(e.bufferProcessing=!0,o>1&&t._writev){e.pendingcb-=o-1;let c=e.allNoop?Um:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:cA(r,s);a.allBuffers=e.allBuffers,oA(t,e,!0,e.length,a,"",c),Dh(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;oA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?Dh(e):s>256?(r.splice(0,s),e.bufferedIndex=0):e.bufferedIndex=s}e.bufferProcessing=!1}it.prototype._write=function(t,e,r){if(this._writev)this._writev([{chunk:t,encoding:e}],r);else throw new wD("_write()")};it.prototype._writev=null;it.prototype.end=function(t,e,r){let n=this._writableState;typeof t=="function"?(r=t,t=null,e=null):typeof e=="function"&&(r=e,e=null);let i;if(t!=null){let o=hA(this,t,e);o instanceof aD&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,km(this,n,!0),n.ended=!0):n.finished?i=new xD("end"):n.destroyed&&(i=new Rd("end"))),typeof r=="function"&&(i||n.finished?oc.nextTick(r,i):n[Ia].push(r)),this};function Oh(t){return t.ending&&!t.destroyed&&t.constructed&&t.length===0&&!t.errored&&t.buffered.length===0&&!t.finished&&!t.writing&&!t.errorEmitted&&!t.closeEmitted}function _D(t,e){let r=!1;function n(i){if(r){_a(t,i??fA());return}if(r=!0,e.pendingcb--,i){let o=e[Ia].splice(0);for(let s=0;s<o.length;s++)o[s](i);_a(t,i,e.sync)}else Oh(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,oc.nextTick(Rm,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function ID(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,_D(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function km(t,e,r){Oh(e)&&(ID(t,e),e.pendingcb===0&&(r?(e.pendingcb++,oc.nextTick((n,i)=>{Oh(i)?Rm(n,i):i.pendingcb--},t,e)):Oh(e)&&(e.pendingcb++,Rm(t,e))))}function Rm(t,e){e.pendingcb--,e.finished=!0;let r=e[Ia].splice(0);for(let n=0;n<r.length;n++)r[n]();if(t.emit("finish"),e.autoDestroy){let n=t._readableState;(!n||n.autoDestroy&&(n.endEmitted||n.readable===!1))&&t.destroy()}}uD(it.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(t){this._writableState&&(this._writableState.destroyed=t)}},writable:{__proto__:null,get(){let t=this._writableState;return!!t&&t.writable!==!1&&!t.destroyed&&!t.errored&&!t.ending&&!t.ended},set(t){this._writableState&&(this._writableState.writable=!!t)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let t=this._writableState;return t?!t.destroyed&&!t.ending&&t.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var BD=kh.destroy;it.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[Ia].length)&&oc.nextTick(Om,r),BD.call(this,t,e),this};it.prototype._undestroy=kh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[hD.captureRejectionSymbol]=function(t){this.destroy(t)};var Bm;function yA(){return Bm===void 0&&(Bm={}),Bm}it.fromWeb=function(t,e){return yA().newStreamWritableFromWritableStream(t,e)};it.toWeb=function(t){return yA().newWritableStreamFromStreamWritable(t)}});var OA=oe((HF,UA)=>{l();var Nm=xi(),RD=Ar(),{isReadable:UD,isWritable:OD,isIterable:mA,isNodeStream:DD,isReadableNodeStream:wA,isWritableNodeStream:bA,isDuplexNodeStream:kD,isReadableStream:xA,isWritableStream:EA}=ti(),vA=ji(),{AbortError:BA,codes:{ERR_INVALID_ARG_TYPE:ND,ERR_INVALID_RETURN_VALUE:SA}}=or(),{destroyer:Ra}=rc(),CD=ii(),RA=Id(),LD=Nh(),{createDeferredPromise:AA}=Zt(),TA=bm(),_A=globalThis.Blob||RD.Blob,PD=typeof _A<"u"?function(e){return e instanceof _A}:function(e){return!1},MD=globalThis.AbortController||ba().AbortController,{FunctionPrototypeCall:IA}=nt(),qo=class extends CD{constructor(e){super(e),e?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),e?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};UA.exports=function t(e,r){if(kD(e))return e;if(wA(e))return Ba({readable:e});if(bA(e))return Ba({writable:e});if(DD(e))return Ba({writable:!1,readable:!1});if(xA(e))return Ba({readable:RA.fromWeb(e)});if(EA(e))return Ba({writable:LD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=KD(e);if(mA(i))return TA(qo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=IA(a,i,f=>{if(f!=null)throw new SA("nully","body",f)},f=>{Ra(u,f)});return u=new qo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,Nm.nextTick(f,null)}catch(h){Nm.nextTick(f,h)}})},destroy:c})}throw new SA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(PD(e))return t(e.arrayBuffer());if(mA(e))return TA(qo,e,{objectMode:!0,writable:!1});if(xA(e?.readable)&&EA(e?.writable))return qo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?wA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?bA(e?.writable)?e?.writable:t(e.writable):void 0;return Ba({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return IA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{Ra(i,o)}),i=new qo({objectMode:!0,writable:!1,read(){}})}throw new ND(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function KD(t){let{promise:e,resolve:r}=AA(),n=new MD,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(Nm.nextTick(u),a)return;if(i.aborted)throw new BA(void 0,{cause:i.reason});({promise:e,resolve:r}=AA()),yield c}}(),{signal:i}),write(s,c,a){let u=r;r=null,u({chunk:s,done:!1,cb:a})},final(s){let c=r;r=null,c({done:!0,cb:s})},destroy(s,c){n.abort(),c(s)}}}function Ba(t){let e=t.readable&&typeof t.readable.read!="function"?RA.wrap(t.readable):t.readable,r=t.writable,n=!!UD(e),i=!!OD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new qo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(vA(r,f=>{i=!1,f&&Ra(e,f),d(f)}),u._write=function(f,h,p){r.write(f,h)?p():o=p},u._final=function(f){r.end(),s=f},r.on("drain",function(){if(o){let f=o;o=null,f()}}),r.on("finish",function(){if(s){let f=s;s=null,f()}})),n&&(vA(e,f=>{n=!1,f&&Ra(e,f),d(f)}),e.on("readable",function(){if(c){let f=c;c=null,f()}}),e.on("end",function(){u.push(null)}),u._read=function(){for(;;){let f=e.read();if(f===null){c=u._read;return}if(!u.push(f))return}}),u._destroy=function(f,h){!f&&a!==null&&(f=new BA),c=null,o=null,s=null,a===null?h(f):(a=h,Ra(r,f),Ra(e,f))},u}});var ii=oe((qF,NA)=>{"use strict";l();var{ObjectDefineProperties:$D,ObjectGetOwnPropertyDescriptor:Wi,ObjectKeys:HD,ObjectSetPrototypeOf:DA}=nt();NA.exports=Tn;var Pm=Id(),en=Nh();DA(Tn.prototype,Pm.prototype);DA(Tn,Pm);{let t=HD(en.prototype);for(let e=0;e<t.length;e++){let r=t[e];Tn.prototype[r]||(Tn.prototype[r]=en.prototype[r])}}function Tn(t){if(!(this instanceof Tn))return new Tn(t);Pm.call(this,t),en.call(this,t),t?(this.allowHalfOpen=t.allowHalfOpen!==!1,t.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),t.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}$D(Tn.prototype,{writable:{__proto__:null,...Wi(en.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Wi(en.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Wi(en.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Wi(en.prototype,"writableBuffer")},writableLength:{__proto__:null,...Wi(en.prototype,"writableLength")},writableFinished:{__proto__:null,...Wi(en.prototype,"writableFinished")},writableCorked:{__proto__:null,...Wi(en.prototype,"writableCorked")},writableEnded:{__proto__:null,...Wi(en.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Wi(en.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(t){this._readableState&&this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}});var Cm;function kA(){return Cm===void 0&&(Cm={}),Cm}Tn.fromWeb=function(t,e){return kA().newStreamDuplexFromReadableWritablePair(t,e)};Tn.toWeb=function(t){return kA().newReadableWritablePairFromDuplex(t)};var Lm;Tn.from=function(t){return Lm||(Lm=OA()),Lm(t,"body")}});var $m=oe((jF,LA)=>{"use strict";l();var{ObjectSetPrototypeOf:CA,Symbol:VD}=nt();LA.exports=Gi;var{ERR_METHOD_NOT_IMPLEMENTED:qD}=or().codes,Km=ii(),{getHighWaterMark:FD}=Ad();CA(Gi.prototype,Km.prototype);CA(Gi,Km);var Od=VD("kCallback");function Gi(t){if(!(this instanceof Gi))return new Gi(t);let e=t?FD(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),Km.call(this,t),this._readableState.sync=!1,this[Od]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",jD)}function Mm(t){typeof this._flush=="function"&&!this.destroyed?this._flush((e,r)=>{if(e){t?t(e):this.destroy(e);return}r!=null&&this.push(r),this.push(null),t&&t()}):(this.push(null),t&&t())}function jD(){this._final!==Mm&&Mm.call(this)}Gi.prototype._final=Mm;Gi.prototype._transform=function(t,e,r){throw new qD("_transform()")};Gi.prototype._write=function(t,e,r){let n=this._readableState,i=this._writableState,o=n.length;this._transform(t,e,(s,c)=>{if(s){r(s);return}c!=null&&this.push(c),i.ended||o===n.length||n.length<n.highWaterMark?r():this[Od]=r})};Gi.prototype._read=function(){if(this[Od]){let t=this[Od];this[Od]=null,t()}}});var Vm=oe((GF,MA)=>{"use strict";l();var{ObjectSetPrototypeOf:PA}=nt();MA.exports=Ua;var Hm=$m();PA(Ua.prototype,Hm.prototype);PA(Ua,Hm);function Ua(t){if(!(this instanceof Ua))return new Ua(t);Hm.call(this,t)}Ua.prototype._transform=function(t,e,r){r(null,t)}});var Mh=oe((YF,qA)=>{l();var Dd=xi(),{ArrayIsArray:WD,Promise:GD,SymbolAsyncIterator:zD,SymbolDispose:YD}=nt(),Ph=ji(),{once:JD}=Zt(),ZD=rc(),KA=ii(),{aggregateTwoErrors:XD,codes:{ERR_INVALID_ARG_TYPE:Zm,ERR_INVALID_RETURN_VALUE:qm,ERR_MISSING_ARGS:QD,ERR_STREAM_DESTROYED:e4,ERR_STREAM_PREMATURE_CLOSE:t4},AbortError:r4}=or(),{validateFunction:n4,validateAbortSignal:i4}=Ea(),{isIterable:sc,isReadable:Fm,isReadableNodeStream:Lh,isNodeStream:$A,isTransformStream:Oa,isWebStream:o4,isReadableStream:jm,isReadableFinished:s4}=ti(),c4=globalThis.AbortController||ba().AbortController,Wm,Gm,zm;function HA(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Ph(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,ZD.destroyer(t,o||new e4("pipe")))},cleanup:i}}function a4(t){return n4(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function Ym(t){if(sc(t))return t;if(Lh(t))return u4(t);throw new Zm("val",["Readable","Iterable","AsyncIterable"],t)}async function*u4(t){Gm||(Gm=Id()),yield*Gm.prototype[zD].call(t)}async function Ch(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new GD((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Ph(e,{readable:!1},s);try{e.writableNeedDrain&&await c();for await(let u of t)e.write(u)||await c();n&&(e.end(),await c()),r()}catch(u){r(i!==u?XD(i,u):u)}finally{a(),e.off("drain",s)}}async function Jm(t,e,r,{end:n}){Oa(e)&&(e=e.writable);let i=e.getWriter();try{for await(let o of t)await i.ready,i.write(o).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(o){try{await i.abort(o),r(o)}catch(s){r(s)}}}function d4(...t){return VA(t,JD(a4(t)))}function VA(t,e,r){if(t.length===1&&WD(t[0])&&(t=t[0]),t.length<2)throw new QD("streams");let n=new c4,i=n.signal,o=r?.signal,s=[];i4(o,"options.signal");function c(){g(new r4)}zm=zm||Zt().addAbortListener;let a;o&&(a=zm(o,c));let u,d,f=[],h=0;function p(A){g(A,--h===0)}function g(A,O){var T;if(A&&(!u||u.code==="ERR_STREAM_PREMATURE_CLOSE")&&(u=A),!(!u&&!O)){for(;f.length;)f.shift()(u);(T=a)===null||T===void 0||T[YD](),n.abort(),O&&(u||s.forEach(M=>M()),Dd.nextTick(e,u,d))}}let y;for(let A=0;A<t.length;A++){let O=t[A],T=A<t.length-1,M=A>0,q=T||r?.end!==!1,j=A===t.length-1;if($A(O)){let $=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(X)};var I=$;if(q){let{destroy:X,cleanup:Q}=HA(O,T,M);f.push(X),Fm(O)&&j&&s.push(Q)}O.on("error",$),Fm(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!sc(y))throw new qm("Iterable, AsyncIterable or Stream","source",y)}else sc(O)||Lh(O)||Oa(O)?y=O:y=KA.from(O);else if(typeof O=="function"){if(Oa(y)){var E;y=Ym((E=y)===null||E===void 0?void 0:E.readable)}else y=Ym(y);if(y=O(y,{signal:i}),T){if(!sc(y,!0))throw new qm("AsyncIterable",`transform[${A-1}]`,y)}else{var S;Wm||(Wm=Vm());let $=new Wm({objectMode:!0}),X=(S=y)===null||S===void 0?void 0:S.then;if(typeof X=="function")h++,X.call(y,_=>{d=_,_!=null&&$.write(_),q&&$.end(),Dd.nextTick(p)},_=>{$.destroy(_),Dd.nextTick(p,_)});else if(sc(y,!0))h++,Ch(y,$,p,{end:q});else if(jm(y)||Oa(y)){let _=y.readable||y;h++,Ch(_,$,p,{end:q})}else throw new qm("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=HA(y,!1,!0);f.push(Q),j&&s.push(G)}}else if($A(O)){if(Lh(y)){h+=2;let $=f4(y,O,p,{end:q});Fm(O)&&j&&s.push($)}else if(Oa(y)||jm(y)){let $=y.readable||y;h++,Ch($,O,p,{end:q})}else if(sc(y))h++,Ch(y,O,p,{end:q});else throw new Zm("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(o4(O)){if(Lh(y))h++,Jm(Ym(y),O,p,{end:q});else if(jm(y)||sc(y))h++,Jm(y,O,p,{end:q});else if(Oa(y))h++,Jm(y.readable,O,p,{end:q});else throw new Zm("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=KA.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&Dd.nextTick(c),y}function f4(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new t4)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;s4(t)?Dd.nextTick(s):t.once("end",s)}else r();return Ph(t,{readable:!0,writable:!1},s=>{let c=t._readableState;s&&s.code==="ERR_STREAM_PREMATURE_CLOSE"&&c&&c.ended&&!c.errored&&!c.errorEmitted?t.once("end",r).once("error",r):r(s)}),Ph(e,{readable:!1,writable:!0},r)}qA.exports={pipelineImpl:VA,pipeline:d4}});var Qm=oe((ZF,YA)=>{"use strict";l();var{pipeline:l4}=Mh(),Kh=ii(),{destroyer:h4}=rc(),{isNodeStream:$h,isReadable:FA,isWritable:jA,isWebStream:Xm,isTransformStream:cc,isWritableStream:WA,isReadableStream:GA}=ti(),{AbortError:p4,codes:{ERR_INVALID_ARG_VALUE:zA,ERR_MISSING_ARGS:y4}}=or(),g4=ji();YA.exports=function(...e){if(e.length===0)throw new y4("streams");if(e.length===1)return Kh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=Kh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=Kh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!$h(e[p])&&!Xm(e[p]))){if(p<e.length-1&&!(FA(e[p])||GA(e[p])||cc(e[p])))throw new zA(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(jA(e[p])||WA(e[p])||cc(e[p])))throw new zA(`streams[${p}]`,r[p],"must be writable")}let n,i,o,s,c;function a(p){let g=s;s=null,g?g(p):p?c.destroy(p):!h&&!f&&c.destroy()}let u=e[0],d=l4(e,a),f=!!(jA(u)||WA(u)||cc(u)),h=!!(FA(d)||GA(d)||cc(d));if(c=new Kh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if($h(u))c._write=function(g,y,E){u.write(g,y)?E():n=E},c._final=function(g){u.end(),i=g},u.on("drain",function(){if(n){let g=n;n=null,g()}});else if(Xm(u)){let y=(cc(u)?u.writable:u).getWriter();c._write=async function(E,S,I){try{await y.ready,y.write(E).catch(()=>{}),I()}catch(A){I(A)}},c._final=async function(E){try{await y.ready,y.close().catch(()=>{}),i=E}catch(S){E(S)}}}let p=cc(d)?d.readable:d;g4(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if($h(d))d.on("readable",function(){if(o){let p=o;o=null,p()}}),d.on("end",function(){c.push(null)}),c._read=function(){for(;;){let p=d.read();if(p===null){o=c._read;return}if(!c.push(p))return}};else if(Xm(d)){let g=(cc(d)?d.readable:d).getReader();c._read=async function(){for(;;)try{let{value:y,done:E}=await g.read();if(!c.push(y))return;if(E){c.push(null);return}}catch{return}}}}return c._destroy=function(p,g){!p&&s!==null&&(p=new p4),o=null,n=null,i=null,s===null?g(p):(s=g,$h(d)&&h4(d,p))},c}});var oT=oe((QF,rw)=>{"use strict";l();var m4=globalThis.AbortController||ba().AbortController,{codes:{ERR_INVALID_ARG_VALUE:w4,ERR_INVALID_ARG_TYPE:kd,ERR_MISSING_ARGS:b4,ERR_OUT_OF_RANGE:x4},AbortError:oi}=or(),{validateAbortSignal:ac,validateInteger:JA,validateObject:uc}=Ea(),E4=nt().Symbol("kWeak"),v4=nt().Symbol("kResistStopPropagation"),{finished:S4}=ji(),A4=Qm(),{addAbortSignalNoValidate:T4}=Sd(),{isWritable:_4,isNodeStream:I4}=ti(),{deprecate:B4}=Zt(),{ArrayPrototypePush:R4,Boolean:U4,MathFloor:ZA,Number:O4,NumberIsNaN:D4,Promise:XA,PromiseReject:QA,PromiseResolve:k4,PromisePrototypeThen:eT,Symbol:rT}=nt(),Hh=rT("kEmpty"),tT=rT("kEof");function N4(t,e){if(e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),I4(t)&&!_4(t))throw new w4("stream",t,"must be writable");let r=A4(this,t);return e!=null&&e.signal&&T4(e.signal,r),r}function Vh(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=ZA(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=ZA(e.highWaterMark)),JA(r,"options.concurrency",1),JA(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Zt().AbortSignalAny([e?.signal].filter(U4)),s=this,c=[],a={signal:o},u,d,f=!1,h=0;function p(){f=!0,g()}function g(){h-=1,y()}function y(){d&&!f&&h<r&&c.length<n&&(d(),d=null)}async function E(){try{for await(let S of s){if(f)return;if(o.aborted)throw new oi;try{if(S=t(S,a),S===Hh)continue;S=k4(S)}catch(I){S=QA(I)}h+=1,eT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new XA(I=>{d=I})}c.push(tT)}catch(S){let I=QA(S);eT(I,g,p),c.push(I)}finally{f=!0,u&&(u(),u=null)}}E();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===tT)return;if(o.aborted)throw new oi;S!==Hh&&(yield S),c.shift(),y()}await new XA(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function C4(t=void 0){return t!=null&&uc(t,"options"),t?.signal!=null&&ac(t.signal,"options.signal"),(async function*(){let r=0;for await(let i of this){var n;if(t!=null&&(n=t.signal)!==null&&n!==void 0&&n.aborted)throw new oi({cause:t.signal.reason});yield[r++,i]}}).call(this)}async function nT(t,e=void 0){for await(let r of tw.call(this,t,e))return!0;return!1}async function L4(t,e=void 0){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);return!await nT.call(this,async(...r)=>!await t(...r),e)}async function P4(t,e){for await(let r of tw.call(this,t,e))return r}async function M4(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),Hh}for await(let n of Vh.call(this,r,e));}function tw(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:Hh}return Vh.call(this,r,e)}var ew=class extends b4{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function K4(t,e,r){var n;if(typeof t!="function")throw new kd("reducer",["Function","AsyncFunction"],t);r!=null&&uc(r,"options"),r?.signal!=null&&ac(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let u=new oi(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await S4(this.destroy(u)),u}let o=new m4,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[E4]:this,[v4]:!0};r.signal.addEventListener("abort",()=>o.abort(),u)}let c=!1;try{for await(let u of this){var a;if(c=!0,r!=null&&(a=r.signal)!==null&&a!==void 0&&a.aborted)throw new oi;i?e=await t(e,u,{signal:s}):(e=u,i=!0)}if(!c&&!i)throw new ew}finally{o.abort()}return e}async function $4(t){t!=null&&uc(t,"options"),t?.signal!=null&&ac(t.signal,"options.signal");let e=[];for await(let n of this){var r;if(t!=null&&(r=t.signal)!==null&&r!==void 0&&r.aborted)throw new oi(void 0,{cause:t.signal.reason});R4(e,n)}return e}function H4(t,e){let r=Vh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function iT(t){if(t=O4(t),D4(t))return 0;if(t<0)throw new x4("number",">= 0",t);return t}function V4(t,e=void 0){return e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),t=iT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new oi;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new oi;t--<=0&&(yield o)}}).call(this)}function q4(t,e=void 0){return e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),t=iT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new oi;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new oi;if(t-- >0&&(yield o),t<=0)return}}).call(this)}rw.exports.streamReturningOperators={asIndexedPairs:B4(C4,"readable.asIndexedPairs will be removed in a future version."),drop:V4,filter:tw,flatMap:H4,map:Vh,take:q4,compose:N4};rw.exports.promiseReturningOperators={every:L4,forEach:M4,reduce:K4,toArray:$4,some:nT,find:P4}});var nw=oe((tj,sT)=>{"use strict";l();var{ArrayPrototypePop:F4,Promise:j4}=nt(),{isIterable:W4,isNodeStream:G4,isWebStream:z4}=ti(),{pipelineImpl:Y4}=Mh(),{finished:J4}=ji();iw();function Z4(...t){return new j4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!G4(o)&&!W4(o)&&!z4(o)){let s=F4(t);n=s.signal,i=s.end}Y4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}sT.exports={finished:J4,pipeline:Z4}});var iw=oe((nj,yT)=>{l();var{Buffer:X4}=Ar(),{ObjectDefineProperty:zi,ObjectKeys:uT,ReflectApply:dT}=nt(),{promisify:{custom:fT}}=Zt(),{streamReturningOperators:cT,promiseReturningOperators:aT}=oT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:lT}}=or(),Q4=Qm(),{setDefaultHighWaterMark:ek,getDefaultHighWaterMark:tk}=Ad(),{pipeline:hT}=Mh(),{destroyer:rk}=rc(),pT=ji(),ow=nw(),Nd=ti(),We=yT.exports=Eh().Stream;We.isDestroyed=Nd.isDestroyed;We.isDisturbed=Nd.isDisturbed;We.isErrored=Nd.isErrored;We.isReadable=Nd.isReadable;We.isWritable=Nd.isWritable;We.Readable=Id();for(let t of uT(cT)){let r=function(...n){if(new.target)throw lT();return We.Readable.from(dT(e,this,n))};sw=r;let e=cT[t];zi(r,"name",{__proto__:null,value:e.name}),zi(r,"length",{__proto__:null,value:e.length}),zi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var sw;for(let t of uT(aT)){let r=function(...i){if(new.target)throw lT();return dT(e,this,i)};sw=r;let e=aT[t];zi(r,"name",{__proto__:null,value:e.name}),zi(r,"length",{__proto__:null,value:e.length}),zi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var sw;We.Writable=Nh();We.Duplex=ii();We.Transform=$m();We.PassThrough=Vm();We.pipeline=hT;var{addAbortSignal:nk}=Sd();We.addAbortSignal=nk;We.finished=pT;We.destroy=rk;We.compose=Q4;We.setDefaultHighWaterMark=ek;We.getDefaultHighWaterMark=tk;zi(We,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return ow}});zi(hT,fT,{__proto__:null,enumerable:!0,get(){return ow.pipeline}});zi(pT,fT,{__proto__:null,enumerable:!0,get(){return ow.finished}});We.Stream=We;We._isUint8Array=function(e){return e instanceof Uint8Array};We._uint8ArrayToBuffer=function(e){return X4.from(e.buffer,e.byteOffset,e.byteLength)}});var cw=oe((oj,ht)=>{"use strict";l();var Tt=iw(),ik=nw(),ok=Tt.Readable.destroy;ht.exports=Tt.Readable;ht.exports._uint8ArrayToBuffer=Tt._uint8ArrayToBuffer;ht.exports._isUint8Array=Tt._isUint8Array;ht.exports.isDisturbed=Tt.isDisturbed;ht.exports.isErrored=Tt.isErrored;ht.exports.isReadable=Tt.isReadable;ht.exports.Readable=Tt.Readable;ht.exports.Writable=Tt.Writable;ht.exports.Duplex=Tt.Duplex;ht.exports.Transform=Tt.Transform;ht.exports.PassThrough=Tt.PassThrough;ht.exports.addAbortSignal=Tt.addAbortSignal;ht.exports.finished=Tt.finished;ht.exports.destroy=Tt.destroy;ht.exports.destroy=ok;ht.exports.pipeline=Tt.pipeline;ht.exports.compose=Tt.compose;Object.defineProperty(Tt,"promises",{configurable:!0,enumerable:!0,get(){return ik}});ht.exports.Stream=Tt.Stream;ht.exports.default=ht.exports});var P_=oe((Up,L_)=>{l();(function(t,e){typeof Up=="object"&&typeof L_<"u"?e(Up):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Up,function(t){"use strict";function e(){for(var B=arguments.length,v=Array(B),k=0;k<B;k++)v[k]=arguments[k];if(v.length>1){v[0]=v[0].slice(0,-1);for(var K=v.length-1,H=1;H<K;++H)v[H]=v[H].slice(1,-1);return v[K]=v[K].slice(1),v.join("")}else return v[0]}function r(B){return"(?:"+B+")"}function n(B){return B===void 0?"undefined":B===null?"null":Object.prototype.toString.call(B).split(" ").pop().split("]").shift().toLowerCase()}function i(B){return B.toUpperCase()}function o(B){return B!=null?B instanceof Array?B:typeof B.length!="number"||B.split||B.setInterval||B.call?[B]:Array.prototype.slice.call(B):[]}function s(B,v){var k=B;if(v)for(var K in v)k[K]=v[K];return k}function c(B){var v="[A-Za-z]",k="[\\x0D]",K="[0-9]",H="[\\x22]",te=e(K,"[A-Fa-f]"),fe="[\\x0A]",ve="[\\x20]",Oe=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),yt="[\\:\\/\\?\\#\\[\\]\\@]",Ee="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",tt=e(yt,Ee),gt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Ze=B?"[\\uE000-\\uF8FF]":"[]",Ae=e(v,K,"[\\-\\.\\_\\~]",gt),rt=r(v+e(v,K,"[\\+\\-\\.]")+"*"),Ne=r(r(Oe+"|"+e(Ae,Ee,"[\\:]"))+"*"),ds=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),vr=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),Fr=r(vr+"\\."+vr+"\\."+vr+"\\."+vr),$e=r(te+"{1,4}"),Sr=r(r($e+"\\:"+$e)+"|"+Fr),jr=r(r($e+"\\:")+"{6}"+Sr),Ln=r("\\:\\:"+r($e+"\\:")+"{5}"+Sr),fs=r(r($e)+"?\\:\\:"+r($e+"\\:")+"{4}"+Sr),pi=r(r(r($e+"\\:")+"{0,1}"+$e)+"?\\:\\:"+r($e+"\\:")+"{3}"+Sr),lu=r(r(r($e+"\\:")+"{0,2}"+$e)+"?\\:\\:"+r($e+"\\:")+"{2}"+Sr),xf=r(r(r($e+"\\:")+"{0,3}"+$e)+"?\\:\\:"+$e+"\\:"+Sr),Ef=r(r(r($e+"\\:")+"{0,4}"+$e)+"?\\:\\:"+Sr),Ec=r(r(r($e+"\\:")+"{0,5}"+$e)+"?\\:\\:"+$e),vc=r(r(r($e+"\\:")+"{0,6}"+$e)+"?\\:\\:"),yi=r([jr,Ln,fs,pi,lu,xf,Ef,Ec,vc].join("|")),Sc=r(r(Ae+"|"+Oe)+"+"),Qp=r(yi+"\\%25"+Sc),ls=r(yi+r("\\%25|\\%(?!"+te+"{2})")+Sc),QI=r("[vV]"+te+"+\\."+e(Ae,Ee,"[\\:]")+"+"),eB=r("\\["+r(ls+"|"+yi+"|"+QI)+"\\]"),Qb=r(r(Oe+"|"+e(Ae,Ee))+"*"),hu=r(eB+"|"+Fr+"(?!"+Qb+")|"+Qb),pu=r(K+"*"),ex=r(r(Ne+"@")+"?"+hu+r("\\:"+pu)+"?"),yu=r(Oe+"|"+e(Ae,Ee,"[\\:\\@]")),tB=r(yu+"*"),tx=r(yu+"+"),rB=r(r(Oe+"|"+e(Ae,Ee,"[\\@]"))+"+"),gi=r(r("\\/"+tB)+"*"),Ac=r("\\/"+r(tx+gi)+"?"),ey=r(rB+gi),vf=r(tx+gi),Tc="(?!"+yu+")",OL=r(gi+"|"+Ac+"|"+ey+"|"+vf+"|"+Tc),_c=r(r(yu+"|"+e("[\\/\\?]",Ze))+"*"),gu=r(r(yu+"|[\\/\\?]")+"*"),rx=r(r("\\/\\/"+ex+gi)+"|"+Ac+"|"+vf+"|"+Tc),nB=r(rt+"\\:"+rx+r("\\?"+_c)+"?"+r("\\#"+gu)+"?"),iB=r(r("\\/\\/"+ex+gi)+"|"+Ac+"|"+ey+"|"+Tc),oB=r(iB+r("\\?"+_c)+"?"+r("\\#"+gu)+"?"),DL=r(nB+"|"+oB),kL=r(rt+"\\:"+rx+r("\\?"+_c)+"?"),NL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+gi+"|"+Ac+"|"+vf+"|"+Tc+")")+r("\\?("+_c+")")+"?"+r("\\#("+gu+")")+"?$",CL="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+gi+"|"+Ac+"|"+ey+"|"+Tc+")")+r("\\?("+_c+")")+"?"+r("\\#("+gu+")")+"?$",LL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+gi+"|"+Ac+"|"+vf+"|"+Tc+")")+r("\\?("+_c+")")+"?$",PL="^"+r("\\#("+gu+")")+"?$",ML="^"+r("("+Ne+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Ae,Ee),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Ae,Ee),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Ae,Ee),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Ae,Ee),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Ae,Ee,"[\\:\\@\\/\\?]",Ze),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Ae,Ee,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Ae,Ee),"g"),UNRESERVED:new RegExp(Ae,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Ae,tt),"g"),PCT_ENCODED:new RegExp(Oe,"g"),IPV4ADDRESS:new RegExp("^("+Fr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+yi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+Sc+")")+"?\\]?$")}}var a=c(!1),u=c(!0),d=function(){function B(v,k){var K=[],H=!0,te=!1,fe=void 0;try{for(var ve=v[Symbol.iterator](),Oe;!(H=(Oe=ve.next()).done)&&(K.push(Oe.value),!(k&&K.length===k));H=!0);}catch(yt){te=!0,fe=yt}finally{try{!H&&ve.return&&ve.return()}finally{if(te)throw fe}}return K}return function(v,k){if(Array.isArray(v))return v;if(Symbol.iterator in Object(v))return B(v,k);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=function(B){if(Array.isArray(B)){for(var v=0,k=Array(B.length);v<B.length;v++)k[v]=B[v];return k}else return Array.from(B)},h=2147483647,p=36,g=1,y=26,E=38,S=700,I=72,A=128,O="-",T=/^xn--/,M=/[^\0-\x7E]/,q=/[\x2E\u3002\uFF0E\uFF61]/g,j={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},$=p-g,X=Math.floor,Q=String.fromCharCode;function G(B){throw new RangeError(j[B])}function _(B,v){for(var k=[],K=B.length;K--;)k[K]=v(B[K]);return k}function D(B,v){var k=B.split("@"),K="";k.length>1&&(K=k[0]+"@",B=k[1]),B=B.replace(q,".");var H=B.split("."),te=_(H,v).join(".");return K+te}function x(B){for(var v=[],k=0,K=B.length;k<K;){var H=B.charCodeAt(k++);if(H>=55296&&H<=56319&&k<K){var te=B.charCodeAt(k++);(te&64512)==56320?v.push(((H&1023)<<10)+(te&1023)+65536):(v.push(H),k--)}else v.push(H)}return v}var U=function(v){return String.fromCodePoint.apply(String,f(v))},L=function(v){return v-48<10?v-22:v-65<26?v-65:v-97<26?v-97:p},N=function(v,k){return v+22+75*(v<26)-((k!=0)<<5)},R=function(v,k,K){var H=0;for(v=K?X(v/S):v>>1,v+=X(v/k);v>$*y>>1;H+=p)v=X(v/$);return X(H+($+1)*v/(v+E))},C=function(v){var k=[],K=v.length,H=0,te=A,fe=I,ve=v.lastIndexOf(O);ve<0&&(ve=0);for(var Oe=0;Oe<ve;++Oe)v.charCodeAt(Oe)>=128&&G("not-basic"),k.push(v.charCodeAt(Oe));for(var yt=ve>0?ve+1:0;yt<K;){for(var Ee=H,tt=1,gt=p;;gt+=p){yt>=K&&G("invalid-input");var Ze=L(v.charCodeAt(yt++));(Ze>=p||Ze>X((h-H)/tt))&&G("overflow"),H+=Ze*tt;var Ae=gt<=fe?g:gt>=fe+y?y:gt-fe;if(Ze<Ae)break;var rt=p-Ae;tt>X(h/rt)&&G("overflow"),tt*=rt}var Ne=k.length+1;fe=R(H-Ee,Ne,Ee==0),X(H/Ne)>h-te&&G("overflow"),te+=X(H/Ne),H%=Ne,k.splice(H++,0,te)}return String.fromCodePoint.apply(String,k)},P=function(v){var k=[];v=x(v);var K=v.length,H=A,te=0,fe=I,ve=!0,Oe=!1,yt=void 0;try{for(var Ee=v[Symbol.iterator](),tt;!(ve=(tt=Ee.next()).done);ve=!0){var gt=tt.value;gt<128&&k.push(Q(gt))}}catch(ls){Oe=!0,yt=ls}finally{try{!ve&&Ee.return&&Ee.return()}finally{if(Oe)throw yt}}var Ze=k.length,Ae=Ze;for(Ze&&k.push(O);Ae<K;){var rt=h,Ne=!0,ds=!1,vr=void 0;try{for(var Fr=v[Symbol.iterator](),$e;!(Ne=($e=Fr.next()).done);Ne=!0){var Sr=$e.value;Sr>=H&&Sr<rt&&(rt=Sr)}}catch(ls){ds=!0,vr=ls}finally{try{!Ne&&Fr.return&&Fr.return()}finally{if(ds)throw vr}}var jr=Ae+1;rt-H>X((h-te)/jr)&&G("overflow"),te+=(rt-H)*jr,H=rt;var Ln=!0,fs=!1,pi=void 0;try{for(var lu=v[Symbol.iterator](),xf;!(Ln=(xf=lu.next()).done);Ln=!0){var Ef=xf.value;if(Ef<H&&++te>h&&G("overflow"),Ef==H){for(var Ec=te,vc=p;;vc+=p){var yi=vc<=fe?g:vc>=fe+y?y:vc-fe;if(Ec<yi)break;var Sc=Ec-yi,Qp=p-yi;k.push(Q(N(yi+Sc%Qp,0))),Ec=X(Sc/Qp)}k.push(Q(N(Ec,0))),fe=R(te,jr,Ae==Ze),te=0,++Ae}}}catch(ls){fs=!0,pi=ls}finally{try{!Ln&&lu.return&&lu.return()}finally{if(fs)throw pi}}++te,++H}return k.join("")},V=function(v){return D(v,function(k){return T.test(k)?C(k.slice(4).toLowerCase()):k})},J=function(v){return D(v,function(k){return M.test(k)?"xn--"+P(k):k})},z={version:"2.1.0",ucs2:{decode:x,encode:U},decode:C,encode:P,toASCII:J,toUnicode:V},W={};function Y(B){var v=B.charCodeAt(0),k=void 0;return v<16?k="%0"+v.toString(16).toUpperCase():v<128?k="%"+v.toString(16).toUpperCase():v<2048?k="%"+(v>>6|192).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase():k="%"+(v>>12|224).toString(16).toUpperCase()+"%"+(v>>6&63|128).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase(),k}function Z(B){for(var v="",k=0,K=B.length;k<K;){var H=parseInt(B.substr(k+1,2),16);if(H<128)v+=String.fromCharCode(H),k+=3;else if(H>=194&&H<224){if(K-k>=6){var te=parseInt(B.substr(k+4,2),16);v+=String.fromCharCode((H&31)<<6|te&63)}else v+=B.substr(k,6);k+=6}else if(H>=224){if(K-k>=9){var fe=parseInt(B.substr(k+4,2),16),ve=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(fe&63)<<6|ve&63)}else v+=B.substr(k,9);k+=9}else v+=B.substr(k,3),k+=3}return v}function ue(B,v){function k(K){var H=Z(K);return H.match(v.UNRESERVED)?H:K}return B.scheme&&(B.scheme=String(B.scheme).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_SCHEME,"")),B.userinfo!==void 0&&(B.userinfo=String(B.userinfo).replace(v.PCT_ENCODED,k).replace(v.NOT_USERINFO,Y).replace(v.PCT_ENCODED,i)),B.host!==void 0&&(B.host=String(B.host).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_HOST,Y).replace(v.PCT_ENCODED,i)),B.path!==void 0&&(B.path=String(B.path).replace(v.PCT_ENCODED,k).replace(B.scheme?v.NOT_PATH:v.NOT_PATH_NOSCHEME,Y).replace(v.PCT_ENCODED,i)),B.query!==void 0&&(B.query=String(B.query).replace(v.PCT_ENCODED,k).replace(v.NOT_QUERY,Y).replace(v.PCT_ENCODED,i)),B.fragment!==void 0&&(B.fragment=String(B.fragment).replace(v.PCT_ENCODED,k).replace(v.NOT_FRAGMENT,Y).replace(v.PCT_ENCODED,i)),B}function ee(B){return B.replace(/^0*(.*)/,"$1")||"0"}function ce(B,v){var k=B.match(v.IPV4ADDRESS)||[],K=d(k,2),H=K[1];return H?H.split(".").map(ee).join("."):B}function Ue(B,v){var k=B.match(v.IPV6ADDRESS)||[],K=d(k,3),H=K[1],te=K[2];if(H){for(var fe=H.toLowerCase().split("::").reverse(),ve=d(fe,2),Oe=ve[0],yt=ve[1],Ee=yt?yt.split(":").map(ee):[],tt=Oe.split(":").map(ee),gt=v.IPV4ADDRESS.test(tt[tt.length-1]),Ze=gt?7:8,Ae=tt.length-Ze,rt=Array(Ze),Ne=0;Ne<Ze;++Ne)rt[Ne]=Ee[Ne]||tt[Ae+Ne]||"";gt&&(rt[Ze-1]=ce(rt[Ze-1],v));var ds=rt.reduce(function(jr,Ln,fs){if(!Ln||Ln==="0"){var pi=jr[jr.length-1];pi&&pi.index+pi.length===fs?pi.length++:jr.push({index:fs,length:1})}return jr},[]),vr=ds.sort(function(jr,Ln){return Ln.length-jr.length})[0],Fr=void 0;if(vr&&vr.length>1){var $e=rt.slice(0,vr.index),Sr=rt.slice(vr.index+vr.length);Fr=$e.join(":")+"::"+Sr.join(":")}else Fr=rt.join(":");return te&&(Fr+="%"+te),Fr}else return B}var Ke=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".match(/(){0}/)[1]===void 0;function bt(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k={},K=v.iri!==!1?u:a;v.reference==="suffix"&&(B=(v.scheme?v.scheme+":":"")+"//"+B);var H=B.match(Ke);if(H){Je?(k.scheme=H[1],k.userinfo=H[3],k.host=H[4],k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=H[7],k.fragment=H[8],isNaN(k.port)&&(k.port=H[5])):(k.scheme=H[1]||void 0,k.userinfo=B.indexOf("@")!==-1?H[3]:void 0,k.host=B.indexOf("//")!==-1?H[4]:void 0,k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=B.indexOf("?")!==-1?H[7]:void 0,k.fragment=B.indexOf("#")!==-1?H[8]:void 0,isNaN(k.port)&&(k.port=B.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?H[4]:void 0)),k.host&&(k.host=Ue(ce(k.host,K),K)),k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&!k.path&&k.query===void 0?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",v.reference&&v.reference!=="suffix"&&v.reference!==k.reference&&(k.error=k.error||"URI is not a "+v.reference+" reference.");var te=W[(v.scheme||k.scheme||"").toLowerCase()];if(!v.unicodeSupport&&(!te||!te.unicodeSupport)){if(k.host&&(v.domainHost||te&&te.domainHost))try{k.host=z.toASCII(k.host.replace(K.PCT_ENCODED,Z).toLowerCase())}catch(fe){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+fe}ue(k,a)}else ue(k,K);te&&te.parse&&te.parse(k,v)}else k.error=k.error||"URI can not be parsed.";return k}function hi(B,v){var k=v.iri!==!1?u:a,K=[];return B.userinfo!==void 0&&(K.push(B.userinfo),K.push("@")),B.host!==void 0&&K.push(Ue(ce(String(B.host),k),k).replace(k.IPV6ADDRESS,function(H,te,fe){return"["+te+(fe?"%25"+fe:"")+"]"})),(typeof B.port=="number"||typeof B.port=="string")&&(K.push(":"),K.push(String(B.port))),K.length?K.join(""):void 0}var uo=/^\.\.?\//,au=/^\/\.(\/|$)/,pf=/^\/\.\.(\/|$)/,Jp=/^\/?(?:.|\n)*?(?=\/|$)/;function fo(B){for(var v=[];B.length;)if(B.match(uo))B=B.replace(uo,"");else if(B.match(au))B=B.replace(au,"/");else if(B.match(pf))B=B.replace(pf,"/"),v.pop();else if(B==="."||B==="..")B="";else{var k=B.match(Jp);if(k){var K=k[0];B=B.slice(K.length),v.push(K)}else throw new Error("Unexpected dot segment condition")}return v.join("")}function Vr(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=v.iri?u:a,K=[],H=W[(v.scheme||B.scheme||"").toLowerCase()];if(H&&H.serialize&&H.serialize(B,v),B.host&&!k.IPV6ADDRESS.test(B.host)){if(v.domainHost||H&&H.domainHost)try{B.host=v.iri?z.toUnicode(B.host):z.toASCII(B.host.replace(k.PCT_ENCODED,Z).toLowerCase())}catch(ve){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+ve}}ue(B,k),v.reference!=="suffix"&&B.scheme&&(K.push(B.scheme),K.push(":"));var te=hi(B,v);if(te!==void 0&&(v.reference!=="suffix"&&K.push("//"),K.push(te),B.path&&B.path.charAt(0)!=="/"&&K.push("/")),B.path!==void 0){var fe=B.path;!v.absolutePath&&(!H||!H.absolutePath)&&(fe=fo(fe)),te===void 0&&(fe=fe.replace(/^\/\//,"/%2F")),K.push(fe)}return B.query!==void 0&&(K.push("?"),K.push(B.query)),B.fragment!==void 0&&(K.push("#"),K.push(B.fragment)),K.join("")}function uu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=bt(Vr(B,k),k),v=bt(Vr(v,k),k)),k=k||{},!k.tolerant&&v.scheme?(H.scheme=v.scheme,H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=fo(v.path||""),H.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=fo(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=fo(v.path):((B.userinfo!==void 0||B.host!==void 0||B.port!==void 0)&&!B.path?H.path="/"+v.path:B.path?H.path=B.path.slice(0,B.path.lastIndexOf("/")+1)+v.path:H.path=v.path,H.path=fo(H.path)),H.query=v.query):(H.path=B.path,v.query!==void 0?H.query=v.query:H.query=B.query),H.userinfo=B.userinfo,H.host=B.host,H.port=B.port),H.scheme=B.scheme),H.fragment=v.fragment,H}function yf(B,v,k){var K=s({scheme:"null"},k);return Vr(uu(bt(B,K),bt(v,K),K,!0),K)}function du(B,v){return typeof B=="string"?B=Vr(bt(B,v),v):n(B)==="object"&&(B=bt(Vr(B,v),v)),B}function gf(B,v,k){return typeof B=="string"?B=Vr(bt(B,k),k):n(B)==="object"&&(B=Vr(B,k)),typeof v=="string"?v=Vr(bt(v,k),k):n(v)==="object"&&(v=Vr(v,k)),B===v}function mf(B,v){return B&&B.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function qr(B,v){return B&&B.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,Z)}var lo={scheme:"http",domainHost:!0,parse:function(v,k){return v.host||(v.error=v.error||"HTTP URIs must have a host."),v},serialize:function(v,k){var K=String(v.scheme).toLowerCase()==="https";return(v.port===(K?443:80)||v.port==="")&&(v.port=void 0),v.path||(v.path="/"),v}},fu={scheme:"https",domainHost:lo.domainHost,parse:lo.parse,serialize:lo.serialize};function wf(B){return typeof B.secure=="boolean"?B.secure:String(B.scheme).toLowerCase()==="wss"}var us={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=wf(K),K.resourceName=(K.path||"/")+(K.query?"?"+K.query:""),K.path=void 0,K.query=void 0,K},serialize:function(v,k){if((v.port===(wf(v)?443:80)||v.port==="")&&(v.port=void 0),typeof v.secure=="boolean"&&(v.scheme=v.secure?"wss":"ws",v.secure=void 0),v.resourceName){var K=v.resourceName.split("?"),H=d(K,2),te=H[0],fe=H[1];v.path=te&&te!=="/"?te:void 0,v.query=fe,v.resourceName=void 0}return v.fragment=void 0,v}},bf={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},Zp={},VI=!0,zb="[A-Za-z0-9\\-\\.\\_\\~"+(VI?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Cn="[0-9A-Fa-f]",qI=r(r("%[EFef]"+Cn+"%"+Cn+Cn+"%"+Cn+Cn)+"|"+r("%[89A-Fa-f]"+Cn+"%"+Cn+Cn)+"|"+r("%"+Cn+Cn)),FI="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",jI="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",WI=e(jI,'[\\"\\\\]'),GI="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",zI=new RegExp(zb,"g"),xc=new RegExp(qI,"g"),YI=new RegExp(e("[^]",FI,"[\\.]",'[\\"]',WI),"g"),Yb=new RegExp(e("[^]",zb,GI),"g"),JI=Yb;function Xp(B){var v=Z(B);return v.match(zI)?v:B}var Jb={scheme:"mailto",parse:function(v,k){var K=v,H=K.to=K.path?K.path.split(","):[];if(K.path=void 0,K.query){for(var te=!1,fe={},ve=K.query.split("&"),Oe=0,yt=ve.length;Oe<yt;++Oe){var Ee=ve[Oe].split("=");switch(Ee[0]){case"to":for(var tt=Ee[1].split(","),gt=0,Ze=tt.length;gt<Ze;++gt)H.push(tt[gt]);break;case"subject":K.subject=qr(Ee[1],k);break;case"body":K.body=qr(Ee[1],k);break;default:te=!0,fe[qr(Ee[0],k)]=qr(Ee[1],k);break}}te&&(K.headers=fe)}K.query=void 0;for(var Ae=0,rt=H.length;Ae<rt;++Ae){var Ne=H[Ae].split("@");if(Ne[0]=qr(Ne[0]),k.unicodeSupport)Ne[1]=qr(Ne[1],k).toLowerCase();else try{Ne[1]=z.toASCII(qr(Ne[1],k).toLowerCase())}catch(ds){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ds}H[Ae]=Ne.join("@")}return K},serialize:function(v,k){var K=v,H=o(v.to);if(H){for(var te=0,fe=H.length;te<fe;++te){var ve=String(H[te]),Oe=ve.lastIndexOf("@"),yt=ve.slice(0,Oe).replace(xc,Xp).replace(xc,i).replace(YI,Y),Ee=ve.slice(Oe+1);try{Ee=k.iri?z.toUnicode(Ee):z.toASCII(qr(Ee,k).toLowerCase())}catch(Ae){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Ae}H[te]=yt+"@"+Ee}K.path=H.join(",")}var tt=v.headers=v.headers||{};v.subject&&(tt.subject=v.subject),v.body&&(tt.body=v.body);var gt=[];for(var Ze in tt)tt[Ze]!==Zp[Ze]&&gt.push(Ze.replace(xc,Xp).replace(xc,i).replace(Yb,Y)+"="+tt[Ze].replace(xc,Xp).replace(xc,i).replace(JI,Y));return gt.length&&(K.query=gt.join("&")),K}},ZI=/^([^\:]+)\:(.*)/,Zb={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(ZI),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),ve=K[2],Oe=te+":"+(k.nid||fe),yt=W[Oe];H.nid=fe,H.nss=ve,H.path=void 0,yt&&(H=yt.parse(H,k))}else H.error=H.error||"URN can not be parsed.";return H},serialize:function(v,k){var K=k.scheme||v.scheme||"urn",H=v.nid,te=K+":"+(k.nid||H),fe=W[te];fe&&(v=fe.serialize(v,k));var ve=v,Oe=v.nss;return ve.path=(H||k.nid)+":"+Oe,ve}},XI=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Xb={scheme:"urn:uuid",parse:function(v,k){var K=v;return K.uuid=K.nss,K.nss=void 0,!k.tolerant&&(!K.uuid||!K.uuid.match(XI))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[lo.scheme]=lo,W[fu.scheme]=fu,W[us.scheme]=us,W[bf.scheme]=bf,W[Jb.scheme]=Jb,W[Zb.scheme]=Zb,W[Xb.scheme]=Xb,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=bt,t.removeDotSegments=fo,t.serialize=Vr,t.resolveComponents=uu,t.resolve=yf,t.normalize=du,t.equal=gf,t.escapeComponent=mf,t.unescapeComponent=qr,Object.defineProperty(t,"__esModule",{value:!0})})});var K_=oe((OZ,M_)=>{"use strict";l();M_.exports=function t(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?t(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,o,s)=>`${i}${s===0?"":","}${t(o===void 0||typeof o=="symbol"?null:o)}`,"")}]`:`{${Object.keys(e).sort().reduce((n,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return n;let o=n.length===0?"":",";return`${n}${o}${t(i)}:${t(e[i])}`},"")}}`}});var X_=oe((NQ,Z_)=>{l();var Za=1e3,Xa=Za*60,Qa=Xa*60,gc=Qa*24,$C=gc*7,HC=gc*365.25;Z_.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return VC(t);if(r==="number"&&isFinite(t))return e.long?FC(t):qC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function VC(t){if(t=String(t),!(t.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(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*HC;case"weeks":case"week":case"w":return r*$C;case"days":case"day":case"d":return r*gc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Qa;case"minutes":case"minute":case"mins":case"min":case"m":return r*Xa;case"seconds":case"second":case"secs":case"sec":case"s":return r*Za;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function qC(t){var e=Math.abs(t);return e>=gc?Math.round(t/gc)+"d":e>=Qa?Math.round(t/Qa)+"h":e>=Xa?Math.round(t/Xa)+"m":e>=Za?Math.round(t/Za)+"s":t+"ms"}function FC(t){var e=Math.abs(t);return e>=gc?Cp(t,e,gc,"day"):e>=Qa?Cp(t,e,Qa,"hour"):e>=Xa?Cp(t,e,Xa,"minute"):e>=Za?Cp(t,e,Za,"second"):t+" ms"}function Cp(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});l();l();l();l();var gs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ms(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function mu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function hn(t,...e){if(!ms(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Bf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mu(t.outputLen),mu(t.blockLen)}function Oc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ax(t,e){hn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Vn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Rf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function pn(t,e){return t<<32-e|t>>>e}function wu(t,e){return t<<e|t>>>32-e>>>0}var Tx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jB=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Lt(t){if(hn(t),Tx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=jB[t[r]];return e}var Ei={_0:48,_9:57,A:65,F:70,a:97,f:102};function Sx(t){if(t>=Ei._0&&t<=Ei._9)return t-Ei._0;if(t>=Ei.A&&t<=Ei.F)return t-(Ei.A-10);if(t>=Ei.a&&t<=Ei.f)return t-(Ei.a-10)}function Tr(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Tx)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Sx(t.charCodeAt(o)),c=Sx(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function ws(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function bu(t){return typeof t=="string"&&(t=ws(t)),hn(t),t}function dt(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];hn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Uc=class{};function Uf(t){let e=n=>t().update(bu(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function _r(t=32){if(gs&&typeof gs.getRandomValues=="function")return gs.getRandomValues(new Uint8Array(t));if(gs&&typeof gs.randomBytes=="function")return Uint8Array.from(gs.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}l();l();l();l();l();function WB(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}function hy(t,e,r){return t&e^~t&r}function py(t,e,r){return t&e^t&r^e&r}var Dc=class extends Uc{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Rf(this.buffer)}update(e){Oc(this),e=bu(e),hn(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Rf(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Oc(this),Ax(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Vn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;WB(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Rf(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},vi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var GB=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]),ho=new Uint32Array(64),yy=class extends Dc{constructor(e=32){super(64,e,8,!1),this.A=vi[0]|0,this.B=vi[1]|0,this.C=vi[2]|0,this.D=vi[3]|0,this.E=vi[4]|0,this.F=vi[5]|0,this.G=vi[6]|0,this.H=vi[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)ho[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ho[f-15],p=ho[f-2],g=pn(h,7)^pn(h,18)^h>>>3,y=pn(p,17)^pn(p,19)^p>>>10;ho[f]=y+ho[f-7]+g+ho[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=pn(c,6)^pn(c,11)^pn(c,25),p=d+h+hy(c,a,u)+GB[f]+ho[f]|0,y=(pn(n,2)^pn(n,13)^pn(n,22))+py(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Vn(ho)}destroy(){this.set(0,0,0,0,0,0,0,0),Vn(this.buffer)}};var ke=Uf(()=>new yy);l();l();l();var Of=class extends Uc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Bf(e);let n=bu(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),Vn(o)}update(e){return Oc(this),this.iHash.update(e),this}digestInto(e){Oc(this),hn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._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=(t,e,r)=>new Of(t,e).update(r).digest();gy.create=(t,e)=>new Of(t,e);l();var by=BigInt(0),wy=BigInt(1);function xu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function po(t,e,r=""){let n=ms(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function Eu(t){let e=t.toString(16);return e.length&1?"0"+e:e}function _x(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?by:BigInt("0x"+t)}function Si(t){return _x(Lt(t))}function xy(t){return hn(t),_x(Lt(Uint8Array.from(t).reverse()))}function kc(t,e){return Tr(t.toString(16).padStart(e*2,"0"))}function Ey(t,e){return kc(t,e).reverse()}function ot(t,e,r){let n;if(typeof e=="string")try{n=Tr(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(ms(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function vu(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var my=t=>typeof t=="bigint"&&by<=t;function Su(t,e,r){return my(t)&&my(e)&&my(r)&&e<=t&&t<r}function Ix(t,e,r,n){if(!Su(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Df(t){let e;for(e=0;t>by;t>>=wy,e+=1);return e}var yo=t=>(wy<<BigInt(t))-wy;function Bx(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p),o=n(t),s=n(t),c=0,a=()=>{o.fill(1),s.fill(0),c=0},u=(...p)=>r(s,o,...p),d=(p=n(0))=>{s=u(i(0),p),o=u(),p.length!==0&&(s=u(i(1),p),o=u())},f=()=>{if(c++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,g=[];for(;p<e;){o=u();let y=o.slice();g.push(y),p+=o.length}return dt(...g)};return(p,g)=>{a(),d(p);let y;for(;!(y=g(f()));)d();return a(),y}}function Au(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,o,s){let c=t[i];if(s&&c===void 0)return;let a=typeof c;if(a!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${a}`)}Object.entries(e).forEach(([i,o])=>n(i,o,!1)),Object.entries(r).forEach(([i,o])=>n(i,o,!0))}function vy(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}l();l();var tr=BigInt(0),Ft=BigInt(1),bs=BigInt(2),Ox=BigInt(3),Dx=BigInt(4),kx=BigInt(5),zB=BigInt(7),Nx=BigInt(8),YB=BigInt(9),Cx=BigInt(16);function Ir(t,e){let r=t%e;return r>=tr?r:e+r}function Br(t,e,r){let n=t;for(;e-- >tr;)n*=n,n%=r;return n}function Rx(t,e){if(t===tr)throw new Error("invert: expected non-zero number");if(e<=tr)throw new Error("invert: expected positive modulus, got "+e);let r=Ir(t,e),n=e,i=tr,o=Ft,s=Ft,c=tr;for(;r!==tr;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==Ft)throw new Error("invert: does not exist");return Ir(i,e)}function Sy(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Lx(t,e){let r=(t.ORDER+Ft)/Dx,n=t.pow(e,r);return Sy(t,n,e),n}function JB(t,e){let r=(t.ORDER-kx)/Nx,n=t.mul(e,bs),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,bs),i),c=t.mul(o,t.sub(s,t.ONE));return Sy(t,c,e),c}function ZB(t){let e=go(t),r=Px(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+zB)/Cx;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),E=c.cmov(u,d,y);return Sy(c,E,a),E}}function Px(t){if(t<Ox)throw new Error("sqrt is not defined for small field");let e=t-Ft,r=0;for(;e%bs===tr;)e/=bs,r++;let n=bs,i=go(t);for(;Ux(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Lx;let o=i.pow(n,e),s=(e+Ft)/bs;return function(a,u){if(a.is0(u))return u;if(Ux(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let E=Ft<<BigInt(d-g-1),S=a.pow(f,E);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function XB(t){return t%Dx===Ox?Lx:t%Nx===kx?JB:t%Cx===YB?ZB(t):Px(t)}var QB=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ay(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=QB.reduce((n,i)=>(n[i]="function",n),e);return Au(t,r),t}function e8(t,e,r){if(r<tr)throw new Error("invalid exponent, negatives unsupported");if(r===tr)return t.ONE;if(r===Ft)return e;let n=t.ONE,i=e;for(;r>tr;)r&Ft&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Ft;return n}function kf(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function Ux(t,e){let r=(t.ORDER-Ft)/bs,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Nf(t,e){e!==void 0&&mu(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function go(t,e,r=!1,n={}){if(t<=tr)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s=!1,c;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(i=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(s=h.modFromBytes),c=h.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(o=n.sqrt);let{nBitLength:a,nByteLength:u}=Nf(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:t,isLE:r,BITS:a,BYTES:u,MASK:yo(a),ZERO:tr,ONE:Ft,allowedLengths:c,create:h=>Ir(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return tr<=h&&h<t},is0:h=>h===tr,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ft)===Ft,neg:h=>Ir(-h,t),eql:(h,p)=>h===p,sqr:h=>Ir(h*h,t),add:(h,p)=>Ir(h+p,t),sub:(h,p)=>Ir(h-p,t),mul:(h,p)=>Ir(h*p,t),pow:(h,p)=>e8(f,h,p),div:(h,p)=>Ir(h*Rx(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Rx(h,t),sqrt:o||(h=>(d||(d=XB(t)),d(f,h))),toBytes:h=>r?Ey(h,u):kc(h,u),fromBytes:(h,p=!0)=>{if(c){if(!c.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+h.length);let y=new Uint8Array(u);y.set(h,r?0:y.length-h.length),h=y}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let g=r?xy(h):Si(h);if(s&&(g=Ir(g,t)),!p&&!f.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>kf(f,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(f)}function Mx(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ty(t){let e=Mx(t);return e+Math.ceil(e/2)}function Cf(t,e,r=!1){let n=t.length,i=Mx(e),o=Ty(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?xy(t):Si(t),c=Ir(s,e-Ft)+Ft;return r?Ey(c,i):kc(c,i)}var Nc=BigInt(0),xs=BigInt(1);function Tu(t,e){let r=e.negate();return t?r:e}function Pf(t,e){let r=kf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function Vx(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function _y(t,e){Vx(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=yo(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function Kx(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=xs);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}function t8(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function r8(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}var Iy=new WeakMap,qx=new WeakMap;function By(t){return qx.get(t)||1}function $x(t){if(t!==Nc)throw new Error("invalid wNAF")}var Lf=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>Nc;)r&xs&&(n=n.add(i)),i=i.double(),r>>=xs;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=_y(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=_y(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=Kx(n,c,s);n=a,d?o=o.add(Tu(h,r[p])):i=i.add(Tu(f,r[u]))}return $x(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=_y(e,this.bits);for(let s=0;s<o.windows&&n!==Nc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=Kx(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return $x(n),i}getPrecomputes(e,r,n){let i=Iy.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Iy.set(r,i))),i}cached(e,r,n){let i=By(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=By(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){Vx(r,this.bits),qx.set(e,r),Iy.delete(e)}hasCache(e){return By(e)!==1}};function Fx(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>Nc||n>Nc;)r&xs&&(o=o.add(i)),n&xs&&(s=s.add(i)),i=i.double(),r>>=xs,n>>=xs;return{p1:o,p2:s}}function jx(t,e,r,n){t8(r,t),r8(n,e);let i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,c=Df(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=yo(a),d=new Array(Number(u)+1).fill(s),f=Math.floor((e.BITS-1)/a)*a,h=s;for(let p=f;p>=0;p-=a){d.fill(s);for(let y=0;y<o;y++){let E=n[y],S=Number(E>>BigInt(p)&u);d[S]=d[S].add(r[y])}let g=s;for(let y=d.length-1,E=s;y>0;y--)E=E.add(d[y]),g=g.add(E);if(h=h.add(g),p!==0)for(let y=0;y<a;y++)h=h.double()}return h}function Hx(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ay(e),e}else return go(t,{isLE:r})}function Wx(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>Nc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=Hx(e.p,r.Fp,n),o=Hx(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var Gx=(t,e)=>(t+(t>=0?e:-e)/zx)/e;function n8(t,e,r){let[[n,i],[o,s]]=e,c=Gx(s*t,r),a=Gx(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<Ti,h=d<Ti;f&&(u=-u),h&&(d=-d);let p=yo(Math.ceil(Df(r)/2))+Cc;if(u<Ti||u>=p||d<Ti||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Uy(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ry(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return xu(r.lowS,"lowS"),xu(r.prehash,"prehash"),r.format!==void 0&&Uy(r.format),r}var Oy=class extends Error{constructor(e=""){super(e)}},Ai={Err:Oy,_tlv:{encode:(t,e)=>{let{Err:r}=Ai;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=Eu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Eu(i.length/2|128):"";return Eu(t)+o+i+e},decode(t,e){let{Err:r}=Ai,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=Ai;if(t<Ti)throw new e("integer: negative integers are not allowed");let r=Eu(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ai;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Si(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ai,i=ot("signature",t),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Ai,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},Ti=BigInt(0),Cc=BigInt(1),zx=BigInt(2),Mf=BigInt(3),i8=BigInt(4);function mo(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=ot("private key",e);try{n=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function o8(t,e={}){let r=Wx("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Au(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Jx(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,_,D){let{x,y:U}=_.toAffine(),L=n.toBytes(x);if(xu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return dt(Yx(N),L)}else return dt(Uint8Array.of(4),L,n.toBytes(U))}function h(G){po(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,x=G.length,U=G[0],L=G.subarray(1);if(x===_&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(x===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!E(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${x}, expected compressed=${_} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let _=n.sqr(G),D=n.mul(_,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function E(G,_){let D=n.sqr(_),x=y(G);return n.eql(D,x)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Mf),i8),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,I)))throw new Error("bad curve params: a or b");function A(G,_,D=!1){if(!n.isValid(_)||D&&n.is0(_))throw new Error(`bad point coordinate ${G}`);return _}function O(G){if(!(G instanceof $))throw new Error("ProjectivePoint expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return n8(G,a.basises,i.ORDER)}let M=vy((G,_)=>{let{X:D,Y:x,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:x};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(x,_),C=n.mul(U,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=vy(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:_,y:D}=G.toAffine();if(!n.isValid(_)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(_,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,_,D,x,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=Tu(x,_),D=Tu(U,D),_.add(D)}class ${constructor(_,D,x){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:x}=_||{};if(!_||!n.isValid(D)||!n.isValid(x))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(x)?$.ZERO:new $(D,x,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(po(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ot("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Mf),this}assertValidity(){q(this)}hasEvenY(){let{y:_}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(_)}equals(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(x,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:_,b:D}=o,x=n.mul(D,Mf),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(_,P),C=n.mul(x,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(x,P),z=n.mul(_,z),W=n.sub(V,z),W=n.mul(_,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Mf),W=n.mul(D,L),Y=n.mul(x,N),Z=n.mul(U,R),ue=n.add(D,x),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(x,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(_){return this.add(_.negate())}is0(){return this.equals($.ZERO)}multiply(_){let{endo:D}=e;if(!i.isValidNot0(_))throw new Error("invalid scalar: out of range");let x,U,L=N=>Q.cached(this,N,R=>Pf($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(_),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),x=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);x=N,U=R}return Pf($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===Ti||x.is0())return $.ZERO;if(_===Cc)return x;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=Fx($,x,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(x,_)}multiplyAndAddUnsafe(_,D,x){let U=this.multiplyUnsafe(D).add(_.multiplyUnsafe(x));return U.is0()?void 0:U}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===Cc?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===Cc?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return xu(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Lt(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(_=!0){return this.toBytes(_)}_setWindowSize(_){this.precompute(_)}static normalizeZ(_){return Pf($,_)}static msm(_,D){return jx($,i,_,D)}static fromPrivateKey(_){return $.BASE.multiply(mo(i,_))}}$.BASE=new $(o.Gx,o.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;let X=i.BITS,Q=new Lf($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function Yx(t){return Uint8Array.of(t?2:3)}function Jx(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function s8(t,e={}){let{Fn:r}=t,n=e.randomBytes||_r,i=Object.assign(Jx(t.Fp,r),{seed:Ty(r.ORDER)});function o(p){try{return!!mo(r,p)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:E}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==E?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Cf(po(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(mo(r,p)).toBytes(g)}function u(p){let g=c(p);return{secretKey:g,publicKey:a(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:g,publicKey:y,publicKeyUncompressed:E}=i;if(r.allowedLengths||g===y)return;let S=ot("key",p).length;return S===y||S===E}function f(p,g,y=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");let E=mo(r,p);return t.fromHex(g).multiply(E).toBytes(y)}return Object.freeze({getPublicKey:a,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c,isValidPrivateKey:o,randomPrivateKey:c,normPrivateKeyToScalar:p=>mo(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function c8(t,e,r={}){Bf(e),Au(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||_r,i=r.hmac||((D,...x)=>gy(e,D,dt(...x))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=s8(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function E(D){let x=c>>Cc;return D>x}function S(D,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return x}function I(D,x){Uy(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return po(D,L,`${x} signature`)}class A{constructor(x,U,L){this.r=S("r",x),this.s=S("s",U),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(x,U=y){I(x,U);let L;if(U==="der"){let{r:P,s:V}=Ai.toSig(po(x));return new A(P,V)}U==="recovered"&&(L=x[0],U="compact",x=x.subarray(1));let N=s.BYTES,R=x.subarray(0,N),C=x.subarray(N,N*2);return new A(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(x,U){return this.fromBytes(Tr(x),U)}addRecoveryBit(x){return new A(this.r,this.s,x)}recoverPublicKey(x){let U=o.ORDER,{r:L,s:N,recovery:R}=this;if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");if(c*zx<U&&R>1)throw new Error("recovery id is ambiguous for h>1 curve");let P=R===2||R===3?L+c:L;if(!o.isValid(P))throw new Error("recovery id 2 or 3 invalid");let V=o.toBytes(P),J=t.fromBytes(dt(Yx((R&1)===0),V)),z=s.inv(P),W=T(ot("msgHash",x)),Y=s.create(-W*z),Z=s.create(N*z),ue=t.BASE.multiplyUnsafe(Y).add(J.multiplyUnsafe(Z));if(ue.is0())throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return E(this.s)}toBytes(x=y){if(Uy(x),x==="der")return Tr(Ai.hexFromSig(this));let U=s.toBytes(this.r),L=s.toBytes(this.s);if(x==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return dt(Uint8Array.of(this.recovery),U,L)}return dt(U,L)}toHex(x){return Lt(this.toBytes(x))}assertValidity(){}static fromCompact(x){return A.fromBytes(ot("sig",x),"compact")}static fromDER(x){return A.fromBytes(ot("sig",x),"der")}normalizeS(){return this.hasHighS()?new A(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Lt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Lt(this.toBytes("compact"))}}let O=r.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let U=Si(x),L=x.length*8-a;return L>0?U>>BigInt(L):U},T=r.bits2int_modN||function(x){return s.create(O(x))},M=yo(a);function q(D){return Ix("num < 2^"+a,D,Ti,M),s.toBytes(D)}function j(D,x){return po(D,void 0,"message"),x?po(e(D),void 0,"prehashed message"):D}function $(D,x,U){if(["recovered","canonical"].some(Y=>Y in U))throw new Error("sign() legacy options not supported");let{lowS:L,prehash:N,extraEntropy:R}=Ry(U,g);D=j(D,N);let C=T(D),P=mo(s,x),V=[q(P),q(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ot("extraEntropy",Y))}let J=dt(...V),z=C;function W(Y){let Z=O(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===Ti)return;let Ue=s.create(ue*s.create(z+ce*P));if(Ue===Ti)return;let Ke=(ee.x===ce?0:2)|Number(ee.y&Cc),Je=Ue;return L&&E(Ue)&&(Je=s.neg(Ue),Ke^=1),new A(ce,Je,Ke)}return{seed:J,k2sig:W}}function X(D,x,U={}){D=ot("message",D);let{seed:L,k2sig:N}=$(D,x,U);return Bx(e.outputLen,s.BYTES,i)(L,N)}function Q(D){let x,U=typeof D=="string"||ms(D),L=!U&&D!==null&&typeof D=="object"&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!U&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(L)x=new A(D.r,D.s);else if(U){try{x=A.fromBytes(ot("sig",D),"der")}catch(N){if(!(N instanceof Ai.Err))throw N}if(!x)try{x=A.fromBytes(ot("sig",D),"compact")}catch{return!1}}return x||!1}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=Ry(L,g);if(U=ot("publicKey",U),x=j(ot("message",x),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(ot("sig",D),C);if(P===!1)return!1;try{let V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=T(x),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,x,U={}){let{prehash:L}=Ry(U,g);return x=j(x,L),A.fromBytes(D,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:X,verify:G,recoverPublicKey:_,Signature:A,hash:e})}function a8(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=go(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),o={Fp:r,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:o}}function u8(t){let{CURVE:e,curveOpts:r}=a8(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function d8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Nf(r.Fn.ORDER,r.Fn.BITS))})}function Zx(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=u8(t),o=o8(e,r),s=c8(o,n,i);return d8(t,s)}function Xx(t,e){let r=n=>Zx({...t,hash:n});return{...r(e),create:r}}var Lc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},f8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},l8=BigInt(0),Qx=BigInt(1),Dy=BigInt(2);function h8(t){let e=Lc.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=Br(d,r,e)*d%e,h=Br(f,r,e)*d%e,p=Br(h,Dy,e)*u%e,g=Br(p,i,e)*p%e,y=Br(g,o,e)*g%e,E=Br(y,c,e)*y%e,S=Br(E,a,e)*E%e,I=Br(S,c,e)*y%e,A=Br(I,r,e)*d%e,O=Br(A,s,e)*g%e,T=Br(O,n,e)*u%e,M=Br(T,Dy,e);if(!Kf.eql(Kf.sqr(M),t))throw new Error("Cannot find square root");return M}var Kf=go(Lc.p,{sqrt:h8}),wo=Xx({...Lc,Fp:Kf,lowS:!0,endo:f8},ke),eE={};function $f(t,...e){let r=eE[t];if(r===void 0){let n=ke(ws(t));r=dt(n,n),eE[t]=r}return ke(dt(r,...e))}var Ny=t=>t.toBytes(!0).slice(1),Pc=wo.Point,Cy=t=>t%Dy===l8;function ky(t){let{Fn:e,BASE:r}=Pc,n=mo(e,t),i=r.multiply(n);return{scalar:Cy(i.y)?n:e.neg(n),bytes:Ny(i)}}function rE(t){let e=Kf;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Cy(i)||(i=e.neg(i));let o=Pc.fromAffine({x:t,y:i});return o.assertValidity(),o}var _u=Si;function nE(...t){return Pc.Fn.create(_u($f("BIP0340/challenge",...t)))}function tE(t){return ky(t).bytes}function p8(t,e,r=_r(32)){let{Fn:n}=Pc,i=ot("message",t),{bytes:o,scalar:s}=ky(e),c=ot("auxRand",r,32),a=n.toBytes(s^_u($f("BIP0340/aux",c))),u=$f("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=ky(u),h=nE(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!iE(p,i,o))throw new Error("sign: Invalid signature produced");return p}function iE(t,e,r){let{Fn:n,BASE:i}=Pc,o=ot("signature",t,64),s=ot("message",e),c=ot("publicKey",r,32);try{let a=rE(_u(c)),u=_u(o.subarray(0,32));if(!Su(u,Qx,Lc.p))return!1;let d=_u(o.subarray(32,64));if(!Su(d,Qx,Lc.n))return!1;let f=nE(n.toBytes(u),Ny(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!Cy(g)||p!==u)}catch{return!1}}var Rr=(()=>{let r=(i=_r(48))=>Cf(i,Lc.n);wo.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:tE(o)}}return{keygen:n,getPublicKey:tE,sign:p8,verify:iE,Point:Pc,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:$f,lift_x:rE,pointToBytes:Ny,numberToBytesBE:kc,bytesToNumberBE:Si,mod:Ir},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var y8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),sE=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),g8=sE.map(t=>(9*t+5)%16),cE=(()=>{let r=[[sE],[g8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>y8[o]));return r})(),aE=cE[0],uE=cE[1],dE=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),m8=aE.map((t,e)=>t.map(r=>dE[e][r])),w8=uE.map((t,e)=>t.map(r=>dE[e][r])),b8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),x8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function oE(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}var Hf=new Uint32Array(16),Ly=class extends Dc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:r,h2:n,h3:i,h4:o}=this;return[e,r,n,i,o]}set(e,r,n,i,o){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=o|0}process(e,r){for(let p=0;p<16;p++,r+=4)Hf[p]=e.getUint32(r,!0);let n=this.h0|0,i=n,o=this.h1|0,s=o,c=this.h2|0,a=c,u=this.h3|0,d=u,f=this.h4|0,h=f;for(let p=0;p<5;p++){let g=4-p,y=b8[p],E=x8[p],S=aE[p],I=uE[p],A=m8[p],O=w8[p];for(let T=0;T<16;T++){let M=wu(n+oE(p,o,c,u)+Hf[S[T]]+y,A[T])+f|0;n=f,f=u,u=wu(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=wu(i+oE(g,s,a,d)+Hf[I[T]]+E,O[T])+h|0;i=h,h=d,d=wu(a,10)|0,a=s,s=M}}this.set(this.h1+c+d|0,this.h2+u+h|0,this.h3+f+i|0,this.h4+n+s|0,this.h0+o+a|0)}roundClean(){Vn(Hf)}destroy(){this.destroyed=!0,Vn(this.buffer),this.set(0,0,0,0,0)}},fE=Uf(()=>new Ly);l();l();function Mc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function E8(t,...e){if(!Mc(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function gE(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Ky(t){if(typeof t!="function")throw new Error("function expected");return!0}function Kc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Bu(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function qf(t){if(!Array.isArray(t))throw new Error("array expected")}function mE(t,e){if(!gE(!0,e))throw new Error(`${t}: array of strings expected`)}function $y(t,e){if(!gE(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ru(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function jf(t){let e=typeof t=="string"?t.split(""):t,r=e.length;mE("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(qf(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(qf(i),i.map(o=>{Kc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function Wf(t=""){return Kc("join",t),{encode:e=>(mE("join.decode",e),e.join(t)),decode:e=>(Kc("join.decode",e),e.split(t))}}function v8(t){return Ky(t),{encode:e=>e,decode:e=>t(e)}}function lE(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(qf(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Bu(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}var wE=(t,e)=>e===0?t:wE(e,t%e),Ff=(t,e)=>t+(e-wE(t,e)),Vf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Py(t,e,r,n){if(qf(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Ff(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Ff(e,r)}`);let i=0,o=0,s=Vf[e],c=Vf[r]-1,a=[];for(let u of t){if(Bu(u),u>=s)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=r;o-=r)a.push((i>>o-r&c)>>>0);let d=Vf[o];if(d===void 0)throw new Error("invalid carry");i&=d-1}if(i=i<<r-o&c,!n&&o>=e)throw new Error("Excess padding");if(!n&&i>0)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&a.push(i>>>0),a}function S8(t){Bu(t);let e=2**8;return{encode:r=>{if(!Mc(r))throw new Error("radix.encode input should be Uint8Array");return lE(Array.from(r),e,t)},decode:r=>($y("radix.decode",r),Uint8Array.from(lE(r,t,e)))}}function Hy(t,e=!1){if(Bu(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ff(8,t)>32||Ff(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Mc(r))throw new Error("radix2.encode input should be Uint8Array");return Py(Array.from(r),8,t,!e)},decode:r=>($y("radix2.decode",r),Uint8Array.from(Py(r,t,8,e)))}}function hE(t){return Ky(t),function(...e){try{return t.apply(null,e)}catch{}}}function A8(t,e){return Bu(t),Ky(e),{encode(r){if(!Mc(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!Mc(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=r.slice(-t),o=e(n).slice(0,t);for(let s=0;s<t;s++)if(o[s]!==i[s])throw new Error("Invalid checksum");return n}}}var $c=Ru(Hy(6),jf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Wf("")),T8=t=>Ru(S8(58),jf(t),Wf("")),Gf=T8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var bE=t=>Ru(A8(4,e=>t(t(e))),Gf);var My=Ru(jf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Wf("")),pE=[996825010,642813549,513874426,1027748829,705979059];function Iu(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<pE.length;n++)(e>>n&1)===1&&(r^=pE[n]);return r}function yE(t,e,r=1){let n=t.length,i=1;for(let o=0;o<n;o++){let s=t.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);i=Iu(i)^s>>5}i=Iu(i);for(let o=0;o<n;o++)i=Iu(i)^t.charCodeAt(o)&31;for(let o of e)i=Iu(i)^o;for(let o=0;o<6;o++)i=Iu(i);return i^=r,My.encode(Py([i%Vf[30]],30,5,!1))}function xE(t){let e=t==="bech32"?1:734539939,r=Hy(5),n=r.decode,i=r.encode,o=hE(n);function s(f,h,p=90){Kc("bech32.encode prefix",f),Mc(h)&&(h=Array.from(h)),$y("bech32.encode",h);let g=f.length;if(g===0)throw new TypeError(`Invalid prefix length ${g}`);let y=g+7+h.length;if(p!==!1&&y>p)throw new TypeError(`Length ${y} exceeds limit ${p}`);let E=f.toLowerCase(),S=yE(E,h,e);return`${E}1${My.encode(h)}${S}`}function c(f,h=90){Kc("bech32.decode input",f);let p=f.length;if(p<8||h!==!1&&p>h)throw new TypeError(`invalid string length: ${p} (${f}). Expected (8..${h})`);let g=f.toLowerCase();if(f!==g&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");let y=g.lastIndexOf("1");if(y===0||y===-1)throw new Error('Letter "1" must be present between prefix and data only');let E=g.slice(0,y),S=g.slice(y+1);if(S.length<6)throw new Error("Data must be at least 6 characters long");let I=My.decode(S).slice(0,-6),A=yE(E,I,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:E,words:I}}let a=hE(c);function u(f){let{prefix:h,words:p}=c(f,!1);return{prefix:h,words:p,bytes:n(p)}}function d(f,h){return s(f,i(h))}return{encode:s,decode:c,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:a,fromWords:n,fromWordsUnsafe:o,toWords:i}}var zf=xE("bech32"),Hc=xE("bech32m"),EE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},_8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",I8={encode(t){return E8(t),t.toHex()},decode(t){return Kc("hex",t),Uint8Array.fromHex(t)}},Te=_8?I8:Ru(Hy(4),jf("0123456789abcdef"),Wf(""),v8(t=>{if(typeof t!="string"||t.length%2!==0)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));var Ve=new Uint8Array,jy=new Uint8Array([0]);function Vc(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Gr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function B8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!Gr(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Wy=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function qc(t){return Object.prototype.toString.call(t)==="[object Object]"}function qn(t){return Number.isSafeInteger(t)}var Yf={equalBytes:Vc,isBytes:Gr,isCoder:Ur,checkBounds:SE,concatBytes:B8,createView:Wy,isPlainObject:qc},vE=t=>{if(t!==null&&typeof t!="string"&&!Ur(t)&&!Gr(t)&&!qn(t))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${t} (${typeof t})`);return{encodeStream(e,r){if(t===null)return;if(Ur(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=_i.resolve(e.stack,t)),typeof n=="bigint"&&(n=Number(n)),n===void 0||n!==r)throw e.err(`Wrong length: ${n} len=${t} exp=${r} (${typeof r})`)},decodeStream(e){let r;if(Ur(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=_i.resolve(e.stack,t)),typeof r=="bigint"&&(r=Number(r)),typeof r!="number")throw e.err(`Wrong length: ${r}`);return r}}},Ot={BITS:32,FULL_MASK:-1>>>0,len:t=>Math.ceil(t/32),create:t=>new Uint32Array(Ot.len(t)),clean:t=>t.fill(0),debug:t=>Array.from(t).map(e=>(e>>>0).toString(2).padStart(32,"0")),checkLen:(t,e)=>{if(Ot.len(e)!==t.length)throw new Error(`wrong length=${t.length}. Expected: ${Ot.len(e)}`)},chunkLen:(t,e,r)=>{if(e<0)throw new Error(`wrong pos=${e}`);if(e+r>t)throw new Error(`wrong range=${e}/${r} of ${t}`)},set:(t,e,r,n=!0)=>!n&&t[e]&r?!1:(t[e]|=r,!0),pos:(t,e)=>({chunk:Math.floor((t+e)/32),mask:1<<32-(t+e)%32-1}),indices:(t,e,r=!1)=>{Ot.checkLen(t,e);let{FULL_MASK:n,BITS:i}=Ot,o=i-e%i,s=o?n>>>o<<o:n,c=[];for(let a=0;a<t.length;a++){let u=t[a];if(r&&(u=~u),a===t.length-1&&(u&=s),u!==0)for(let d=0;d<i;d++){let f=1<<i-d-1;u&f&&c.push(a*i+d)}}return c},range:t=>{let e=[],r;for(let n of t)r===void 0||n!==r.pos+r.length?e.push(r={pos:n,length:1}):r.length+=1;return e},rangeDebug:(t,e,r=!1)=>`[${Ot.range(Ot.indices(t,e,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(t,e,r,n,i=!0)=>{Ot.chunkLen(e,r,n);let{FULL_MASK:o,BITS:s}=Ot,c=r%s?Math.floor(r/s):void 0,a=r+n,u=a%s?Math.floor(a/s):void 0;if(c!==void 0&&c===u)return Ot.set(t,c,o>>>s-n<<s-n-r,i);if(c!==void 0&&!Ot.set(t,c,o>>>r%s,i))return!1;let d=c!==void 0?c+1:r/s,f=u!==void 0?u:a/s;for(let h=d;h<f;h++)if(!Ot.set(t,h,o,i))return!1;return!(u!==void 0&&c!==u&&!Ot.set(t,u,o<<s-a%s,i))}},_i={pushObj:(t,e,r)=>{let n={obj:e};t.push(n),r((i,o)=>{n.field=i,o(),n.field=void 0}),t.pop()},path:t=>{let e=[];for(let r of t)r.field!==void 0&&e.push(r.field);return e.join("/")},err:(t,e,r)=>{let n=new Error(`${t}(${_i.path(e)}): ${typeof r=="string"?r:r.message}`);return r instanceof Error&&r.stack&&(n.stack=r.stack),n},resolve:(t,e)=>{let r=e.split("/"),n=t.map(s=>s.obj),i=0;for(;i<r.length&&r[i]==="..";i++)n.pop();let o=n.pop();for(;i<r.length;i++){if(!o||o[r[i]]===void 0)return;o=o[r[i]]}return o}},Vy=class t{constructor(e,r={},n=[],i=void 0,o=0){this.pos=0,this.bitBuf=0,this.bitPos=0,this.data=e,this.opts=r,this.stack=n,this.parent=i,this.parentOffset=o,this.view=Wy(e)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=Ot.create(this.data.length),Ot.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(e,r){return this.parent?this.parent.markBytesBS(this.parentOffset+e,r):!r||!this.bs?!0:Ot.setRange(this.bs,this.data.length,e,r,!1)}markBytes(e){let r=this.pos;this.pos+=e;let n=this.markBytesBS(r,e);if(!this.opts.allowMultipleReads&&!n)throw this.err(`multiple read pos=${this.pos} len=${e}`);return n}pushObj(e,r){return _i.pushObj(this.stack,e,r)}readView(e,r){if(!Number.isFinite(e))throw this.err(`readView: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readView: Unexpected end of buffer");let n=r(this.view,this.pos);return this.markBytes(e),n}absBytes(e){if(e>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(e)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${Te.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){let e=Ot.indices(this.bs,this.data.length,!0);if(e.length){let r=Ot.range(e).map(({pos:n,length:i})=>`(${n}/${i})[${Te.encode(this.data.subarray(n,n+i))}]`).join(", ");throw this.err(`unread byte ranges: ${r} (total=${this.data.length})`)}else return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${Te.encode(this.data.slice(this.pos))}`)}}err(e){return _i.err("Reader",this.stack,e)}offsetReader(e){if(e>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new t(this.absBytes(e),this.opts,this.stack,this,e)}bytes(e,r=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(e))throw this.err(`readBytes: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let n=this.data.subarray(this.pos,this.pos+e);return r||this.markBytes(e),n}byte(e=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let r=this.data[this.pos];return e||this.markBytes(1),r}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}bits(e){if(e>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let r=0;for(;e;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);let n=Math.min(e,this.bitPos);this.bitPos-=n,r=r<<n|this.bitBuf>>this.bitPos&2**n-1,this.bitBuf&=2**this.bitPos-1,e-=n}return r>>>0}find(e,r=this.pos){if(!Gr(e))throw this.err(`find: needle is not bytes! ${e}`);if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!e.length)throw this.err("find: needle is empty");for(let n=r;(n=this.data.indexOf(e[0],n))!==-1;n++){if(n===-1||this.data.length-n<e.length)return;if(Vc(e,this.data.subarray(n,n+e.length)))return n}}},qy=class{constructor(e=[]){this.pos=0,this.buffers=[],this.ptrs=[],this.bitBuf=0,this.bitPos=0,this.viewBuf=new Uint8Array(8),this.finished=!1,this.stack=e,this.view=Wy(this.viewBuf)}pushObj(e,r){return _i.pushObj(this.stack,e,r)}writeView(e,r){if(this.finished)throw this.err("buffer: finished");if(!qn(e)||e>8)throw new Error(`wrong writeView length=${e}`);r(this.view),this.bytes(this.viewBuf.slice(0,e)),this.viewBuf.fill(0)}err(e){if(this.finished)throw this.err("buffer: finished");return _i.err("Reader",this.stack,e)}bytes(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(e),this.pos+=e.length}byte(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([e])),this.pos++}finish(e=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");let r=this.buffers.concat(this.ptrs.map(o=>o.buffer)),n=r.map(o=>o.length).reduce((o,s)=>o+s,0),i=new Uint8Array(n);for(let o=0,s=0;o<r.length;o++){let c=r[o];i.set(c,s),s+=c.length}for(let o=this.pos,s=0;s<this.ptrs.length;s++){let c=this.ptrs[s];i.set(c.ptr.encode(o),c.pos),o+=c.buffer.length}if(e){this.buffers=[];for(let o of this.ptrs)o.buffer.fill(0);this.ptrs=[],this.finished=!0,this.bitBuf=0}return i}bits(e,r){if(r>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(e>=2**r)throw this.err(`writeBits: value (${e}) >= 2**bits (${r})`);for(;r;){let n=Math.min(r,8-this.bitPos);this.bitBuf=this.bitBuf<<n|e>>r-n,this.bitPos+=n,r-=n,e&=2**r-1,this.bitPos===8&&(this.bitPos=0,this.buffers.push(new Uint8Array([this.bitBuf])),this.pos++)}}},Fy=t=>Uint8Array.from(t).reverse();function SE(t,e,r){if(r){let n=2n**(e-1n);if(t<-n||t>=n)throw new Error(`value out of signed bounds. Expected ${-n} <= ${t} < ${n}`)}else if(0n>t||t>=2n**e)throw new Error(`value out of unsigned bounds. Expected 0 <= ${t} < ${2n**e}`)}function AE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new qy;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new Vy(e,r),i=t.decodeStream(n);return n.finish(),i}}}function jt(t,e){if(!Ur(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return AE({size:t.size,encodeStream:(r,n)=>{let i;try{i=e(n)}catch(o){throw r.err(o)}t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e(n)}catch(i){throw r.err(i)}}})}var Wt=t=>{let e=AE(t);return t.validate?jt(e,t.validate):e},Jf=t=>qc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Ur(t){return qc(t)&&Jf(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||qn(t.size))}function R8(){return{encode:t=>{if(!Array.isArray(t))throw new Error("array expected");let e={};for(let r of t){if(!Array.isArray(r)||r.length!==2)throw new Error("array of two elements expected");let n=r[0],i=r[1];if(e[n]!==void 0)throw new Error(`key(${n}) appears twice in struct`);e[n]=i}return e},decode:t=>{if(!qc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var U8={encode:t=>{if(typeof t!="bigint")throw new Error(`expected bigint, got ${typeof t}`);if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${t}`);return Number(t)},decode:t=>{if(!qn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function O8(t){if(!qc(t))throw new Error("plain object expected");return{encode:e=>{if(!qn(e)||!(e in t))throw new Error(`wrong value ${e}`);return t[e]},decode:e=>{if(typeof e!="string")throw new Error(`wrong value ${typeof e}`);return t[e]}}}function D8(t,e=!1){if(!qn(t))throw new Error(`decimal/precision: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`decimal/round: expected boolean, got ${typeof e}`);let r=10n**BigInt(t);return{encode:n=>{if(typeof n!="bigint")throw new Error(`expected bigint, got ${typeof n}`);let i=(n<0n?-n:n).toString(10),o=i.length-t;o<0&&(i=i.padStart(i.length-o,"0"),o=0);let s=i.length-1;for(;s>=o&&i[s]==="0";s--);let c=i.slice(0,o),a=i.slice(o,s+1);return c||(c="0"),n<0n&&(c="-"+c),a?`${c}.${a}`:c},decode:n=>{if(typeof n!="string")throw new Error(`expected string, got ${typeof n}`);if(n==="-0")throw new Error("negative zero is not allowed");let i=!1;if(n.startsWith("-")&&(i=!0,n=n.slice(1)),!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))throw new Error(`wrong string value=${n}`);let o=n.indexOf(".");o=o===-1?n.length:o;let s=n.slice(0,o),c=n.slice(o+1).replace(/0+$/,""),a=BigInt(s)*r;if(!e&&c.length>t)throw new Error(`fractional part cannot be represented with this precision (num=${n}, prec=${t})`);let u=Math.min(c.length,t),d=BigInt(c.slice(0,u))*10n**BigInt(t-u),f=a+d;return i?-f:f}}}function k8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!Jf(e))throw new Error(`wrong base coder ${e}`);return{encode:e=>{for(let r of t){let n=r.encode(e);if(n!==void 0)return n}throw new Error(`match/encode: cannot find match in ${e}`)},decode:e=>{for(let r of t){let n=r.decode(e);if(n!==void 0)return n}throw new Error(`match/decode: cannot find match in ${e}`)}}}var TE=t=>{if(!Jf(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Ii={dict:R8,numberBigint:U8,tsEnum:O8,decimal:D8,match:k8,reverse:TE};var Gy=(t,e=!1,r=!1,n=!0)=>{if(!qn(t))throw new Error(`bigint/size: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`bigint/le: expected boolean, got ${typeof e}`);if(typeof r!="boolean")throw new Error(`bigint/signed: expected boolean, got ${typeof r}`);if(typeof n!="boolean")throw new Error(`bigint/sized: expected boolean, got ${typeof n}`);let i=BigInt(t),o=2n**(8n*i-1n);return Wt({size:n?t:void 0,encodeStream:(s,c)=>{r&&c<0&&(c=c|o);let a=[];for(let d=0;d<t;d++)a.push(Number(c&255n)),c>>=8n;let u=new Uint8Array(a).reverse();if(!n){let d=0;for(d=0;d<u.length&&u[d]===0;d++);u=u.subarray(d)}s.bytes(e?u.reverse():u)},decodeStream:s=>{let c=s.bytes(n?t:Math.min(t,s.leftBytes)),a=e?c:Fy(c),u=0n;for(let d=0;d<a.length;d++)u|=BigInt(a[d])<<8n*BigInt(d);return r&&u&o&&(u=(u^o)-o),u},validate:s=>{if(typeof s!="bigint")throw new Error(`bigint: invalid value: ${s}`);return SE(s,8n*i,!!r),s}})};var _E=Gy(32,!1);var Fc=Gy(8,!0);var IE=Gy(8,!0,!0);var N8=(t,e)=>Wt({size:t,encodeStream:(r,n)=>r.writeView(t,i=>e.write(i,n)),decodeStream:r=>r.readView(t,e.read),validate:r=>{if(typeof r!="number")throw new Error(`viewCoder: expected number, got ${typeof r}`);return e.validate&&e.validate(r),r}}),Uu=(t,e,r)=>{let n=t*8,i=2**(n-1),o=a=>{if(!qn(a))throw new Error(`sintView: value is not safe integer: ${a}`);if(a<-i||a>=i)throw new Error(`sintView: value out of bounds. Expected ${-i} <= ${a} < ${i}`)},s=2**n,c=a=>{if(!qn(a))throw new Error(`uintView: value is not safe integer: ${a}`);if(0>a||a>=s)throw new Error(`uintView: value out of bounds. Expected 0 <= ${a} < ${s}`)};return N8(t,{write:r.write,read:r.read,validate:e?o:c})},_e=Uu(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),BE=Uu(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),bo=Uu(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var zy=Uu(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var gn=Uu(1,!1,{read:(t,e)=>t.getUint8(e),write:(t,e)=>t.setUint8(0,e)});var Fe=(t,e=!1)=>{if(typeof e!="boolean")throw new Error(`bytes/le: expected boolean, got ${typeof e}`);let r=vE(t),n=Gr(t);return Wt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?Fy(o):o),n&&i.bytes(t)},decodeStream:i=>{let o;if(n){let s=i.find(t);if(!s)throw i.err("bytes: cannot find terminator");o=i.bytes(s-i.pos),i.bytes(t.length)}else o=i.bytes(t===null?i.leftBytes:r.decodeStream(i));return e?Fy(o):o},validate:i=>{if(!Gr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function RE(t,e){if(!Ur(e))throw new Error(`prefix: invalid inner value ${e}`);return yn(Fe(t),TE(e))}var Zf=(t,e=!1)=>jt(yn(Fe(t,e),EE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var UE=(t,e={isLE:!1,with0x:!1})=>{let r=yn(Fe(t,e.isLE),Te),n=e.with0x;if(typeof n!="boolean")throw new Error(`hex/with0x: expected boolean, got ${typeof n}`);return n&&(r=yn(r,{encode:i=>`0x${i}`,decode:i=>{if(!i.startsWith("0x"))throw new Error("hex(with0x=true).encode input should start with 0x");return i.slice(2)}})),r};function yn(t,e){if(!Ur(t))throw new Error(`apply: invalid inner value ${t}`);if(!Jf(e))throw new Error(`apply: invalid base value ${t}`);return Wt({size:t.size,encodeStream:(r,n)=>{let i;try{i=e.decode(n)}catch(o){throw r.err(""+o)}return t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e.encode(n)}catch(i){throw r.err(""+i)}}})}var OE=(t,e=!1)=>{if(!Gr(t))throw new Error(`flag/flagValue: expected Uint8Array, got ${typeof t}`);if(typeof e!="boolean")throw new Error(`flag/xor: expected boolean, got ${typeof e}`);return Wt({size:t.length,encodeStream:(r,n)=>{!!n!==e&&r.bytes(t)},decodeStream:r=>{let n=r.leftBytes>=t.length;return n&&(n=Vc(r.bytes(t.length,!0),t),n&&r.bytes(t.length)),n!==e},validate:r=>{if(r!==void 0&&typeof r!="boolean")throw new Error(`flag: expected boolean value or undefined, got ${typeof r}`);return r}})};function DE(t,e,r){if(!Ur(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Ur(e))throw new Error(`flagged: wrong path=${t}`);return Wt({encodeStream:(n,i)=>{typeof t=="string"?_i.resolve(n.stack,t)?e.encodeStream(n,i):r&&e.encodeStream(n,r):(t.encodeStream(n,!!i),i?e.encodeStream(n,i):r&&e.encodeStream(n,r))},decodeStream:n=>{let i=!1;if(typeof t=="string"?i=!!_i.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function Xf(t,e,r=!0){if(!Ur(t))throw new Error(`magic: invalid inner value ${t}`);if(typeof r!="boolean")throw new Error(`magic: expected boolean, got ${typeof r}`);return Wt({size:t.size,encodeStream:(n,i)=>t.encodeStream(n,e),decodeStream:n=>{let i=t.decodeStream(n);if(r&&typeof i!="object"&&i!==e||Gr(e)&&!Vc(e,i))throw n.err(`magic: invalid value: ${i} !== ${e}`)},validate:n=>{if(n!==void 0)throw new Error(`magic: wrong value=${typeof n}`);return n}})}function kE(t){let e=0;for(let r of t){if(r.size===void 0)return;if(!qn(r.size))throw new Error(`sizeof: wrong element size=${e}`);e+=r.size}return e}function xt(t){if(!qc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Ur(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return Wt({size:kE(Object.values(t)),encodeStream:(e,r)=>{e.pushObj(r,n=>{for(let i in t)n(i,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r={};return e.pushObj(r,n=>{for(let i in t)n(i,()=>r[i]=t[i].decodeStream(e))}),r},validate:e=>{if(typeof e!="object"||e===null)throw new Error(`struct: invalid value ${e}`);return e}})}function NE(t){if(!Array.isArray(t))throw new Error(`Packed.Tuple: got ${typeof t} instead of array`);for(let e=0;e<t.length;e++)if(!Ur(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return Wt({size:kE(t),encodeStream:(e,r)=>{if(!Array.isArray(r))throw e.err(`tuple: invalid value ${r}`);e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r=[];return e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>r.push(t[i].decodeStream(e)))}),r},validate:e=>{if(!Array.isArray(e))throw new Error(`tuple: invalid value ${e}`);if(e.length!==t.length)throw new Error(`tuple: wrong length=${e.length}, expected ${t.length}`);return e}})}function Gt(t,e){if(!Ur(e))throw new Error(`array: invalid inner value ${e}`);let r=vE(typeof t=="string"?`../${t}`:t);return Wt({size:typeof t=="number"&&e.size?t*e.size:void 0,encodeStream:(n,i)=>{let o=n;o.pushObj(i,s=>{Gr(t)||r.encodeStream(n,i.length);for(let c=0;c<i.length;c++)s(`${c}`,()=>{let a=i[c],u=n.pos;if(e.encodeStream(n,a),Gr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(Vc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),Gr(t)&&n.bytes(t)},decodeStream:n=>{let i=[];return n.pushObj(i,o=>{if(t===null)for(let s=0;!n.isEnd()&&(o(`${s}`,()=>i.push(e.decodeStream(n))),!(e.size&&n.leftBytes<e.size));s++);else if(Gr(t))for(let s=0;;s++){if(Vc(n.bytes(t.length,!0),t)){n.bytes(t.length);break}o(`${s}`,()=>i.push(e.decodeStream(n)))}else{let s;o("arrayLen",()=>s=r.decodeStream(n));for(let c=0;c<s;c++)o(`${c}`,()=>i.push(e.decodeStream(n)))}}),i},validate:n=>{if(!Array.isArray(n))throw new Error(`array: invalid value ${n}`);return n}})}var tl=wo.ProjectivePoint,el=wo.CURVE.n,Ce=Yf.isBytes,Fn=Yf.concatBytes,st=Yf.equalBytes;var jc=t=>fE(ke(t)),Bi=(...t)=>ke(ke(Fn(...t))),iM=Rr.utils.randomPrivateKey,rl=Rr.getPublicKey,Yy=wo.getPublicKey,CE=t=>t.r<el/2n;function LE(t,e,r=!1){let n=wo.sign(t,e);if(r&&!CE(n)){let i=new Uint8Array(32),o=0;for(;!CE(n);)if(i.set(_e.encode(o++)),n=wo.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var Jy=Rr.sign,Ou=Rr.utils.taggedHash,Et;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(Et||(Et={}));function xo(t,e){let r=t.length;if(e===Et.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return tl.fromHex(t),t}else if(e===Et.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Rr.utils.lift_x(Rr.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function PE(t,e){let r=Rr.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=el)throw new Error("tweak higher than curve order");return i}function ME(t,e=Uint8Array.of()){let r=Rr.utils,n=r.bytesToNumberBE(t),i=tl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,el),s=r.pointToBytes(i),c=PE(s,e);return r.numberToBytesBE(r.mod(o+c,el),32)}function Du(t,e){let r=Rr.utils,n=PE(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(tl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var nl=ke(tl.BASE.toRawBytes(!1)),zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},Zy={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function ku(t,e){if(!Ce(t)||!Ce(e))throw new Error(`cmp: wrong type a=${typeof t} b=${typeof e}`);let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!=e[n])return Math.sign(t[n]-e[n]);return Math.sign(t.length-e.length)}l();l();l();var mt;(function(t){t[t.OP_0=0]="OP_0",t[t.PUSHDATA1=76]="PUSHDATA1",t[t.PUSHDATA2=77]="PUSHDATA2",t[t.PUSHDATA4=78]="PUSHDATA4",t[t["1NEGATE"]=79]="1NEGATE",t[t.RESERVED=80]="RESERVED",t[t.OP_1=81]="OP_1",t[t.OP_2=82]="OP_2",t[t.OP_3=83]="OP_3",t[t.OP_4=84]="OP_4",t[t.OP_5=85]="OP_5",t[t.OP_6=86]="OP_6",t[t.OP_7=87]="OP_7",t[t.OP_8=88]="OP_8",t[t.OP_9=89]="OP_9",t[t.OP_10=90]="OP_10",t[t.OP_11=91]="OP_11",t[t.OP_12=92]="OP_12",t[t.OP_13=93]="OP_13",t[t.OP_14=94]="OP_14",t[t.OP_15=95]="OP_15",t[t.OP_16=96]="OP_16",t[t.NOP=97]="NOP",t[t.VER=98]="VER",t[t.IF=99]="IF",t[t.NOTIF=100]="NOTIF",t[t.VERIF=101]="VERIF",t[t.VERNOTIF=102]="VERNOTIF",t[t.ELSE=103]="ELSE",t[t.ENDIF=104]="ENDIF",t[t.VERIFY=105]="VERIFY",t[t.RETURN=106]="RETURN",t[t.TOALTSTACK=107]="TOALTSTACK",t[t.FROMALTSTACK=108]="FROMALTSTACK",t[t["2DROP"]=109]="2DROP",t[t["2DUP"]=110]="2DUP",t[t["3DUP"]=111]="3DUP",t[t["2OVER"]=112]="2OVER",t[t["2ROT"]=113]="2ROT",t[t["2SWAP"]=114]="2SWAP",t[t.IFDUP=115]="IFDUP",t[t.DEPTH=116]="DEPTH",t[t.DROP=117]="DROP",t[t.DUP=118]="DUP",t[t.NIP=119]="NIP",t[t.OVER=120]="OVER",t[t.PICK=121]="PICK",t[t.ROLL=122]="ROLL",t[t.ROT=123]="ROT",t[t.SWAP=124]="SWAP",t[t.TUCK=125]="TUCK",t[t.CAT=126]="CAT",t[t.SUBSTR=127]="SUBSTR",t[t.LEFT=128]="LEFT",t[t.RIGHT=129]="RIGHT",t[t.SIZE=130]="SIZE",t[t.INVERT=131]="INVERT",t[t.AND=132]="AND",t[t.OR=133]="OR",t[t.XOR=134]="XOR",t[t.EQUAL=135]="EQUAL",t[t.EQUALVERIFY=136]="EQUALVERIFY",t[t.RESERVED1=137]="RESERVED1",t[t.RESERVED2=138]="RESERVED2",t[t["1ADD"]=139]="1ADD",t[t["1SUB"]=140]="1SUB",t[t["2MUL"]=141]="2MUL",t[t["2DIV"]=142]="2DIV",t[t.NEGATE=143]="NEGATE",t[t.ABS=144]="ABS",t[t.NOT=145]="NOT",t[t["0NOTEQUAL"]=146]="0NOTEQUAL",t[t.ADD=147]="ADD",t[t.SUB=148]="SUB",t[t.MUL=149]="MUL",t[t.DIV=150]="DIV",t[t.MOD=151]="MOD",t[t.LSHIFT=152]="LSHIFT",t[t.RSHIFT=153]="RSHIFT",t[t.BOOLAND=154]="BOOLAND",t[t.BOOLOR=155]="BOOLOR",t[t.NUMEQUAL=156]="NUMEQUAL",t[t.NUMEQUALVERIFY=157]="NUMEQUALVERIFY",t[t.NUMNOTEQUAL=158]="NUMNOTEQUAL",t[t.LESSTHAN=159]="LESSTHAN",t[t.GREATERTHAN=160]="GREATERTHAN",t[t.LESSTHANOREQUAL=161]="LESSTHANOREQUAL",t[t.GREATERTHANOREQUAL=162]="GREATERTHANOREQUAL",t[t.MIN=163]="MIN",t[t.MAX=164]="MAX",t[t.WITHIN=165]="WITHIN",t[t.RIPEMD160=166]="RIPEMD160",t[t.SHA1=167]="SHA1",t[t.SHA256=168]="SHA256",t[t.HASH160=169]="HASH160",t[t.HASH256=170]="HASH256",t[t.CODESEPARATOR=171]="CODESEPARATOR",t[t.CHECKSIG=172]="CHECKSIG",t[t.CHECKSIGVERIFY=173]="CHECKSIGVERIFY",t[t.CHECKMULTISIG=174]="CHECKMULTISIG",t[t.CHECKMULTISIGVERIFY=175]="CHECKMULTISIGVERIFY",t[t.NOP1=176]="NOP1",t[t.CHECKLOCKTIMEVERIFY=177]="CHECKLOCKTIMEVERIFY",t[t.CHECKSEQUENCEVERIFY=178]="CHECKSEQUENCEVERIFY",t[t.NOP4=179]="NOP4",t[t.NOP5=180]="NOP5",t[t.NOP6=181]="NOP6",t[t.NOP7=182]="NOP7",t[t.NOP8=183]="NOP8",t[t.NOP9=184]="NOP9",t[t.NOP10=185]="NOP10",t[t.CHECKSIGADD=186]="CHECKSIGADD",t[t.INVALID=255]="INVALID"})(mt||(mt={}));function Xy(t=6,e=!1){return Wt({encodeStream:(r,n)=>{if(n===0n)return;let i=n<0,o=BigInt(n),s=[];for(let c=i?-o:o;c;c>>=8n)s.push(Number(c&0xffn));s[s.length-1]>=128?s.push(i?128:0):i&&(s[s.length-1]|=128),r.bytes(new Uint8Array(s))},decodeStream:r=>{let n=r.leftBytes;if(n>t)throw new Error(`ScriptNum: number (${n}) bigger than limit=${t}`);if(n===0)return 0n;if(e){let s=r.bytes(n,!0);if(!(s[s.length-1]&127)&&(n<=1||!(s[s.length-2]&128)))throw new Error("Non-minimally encoded ScriptNum")}let i=0,o=0n;for(let s=0;s<n;++s)i=r.byte(),o|=BigInt(i)<<8n*BigInt(s);return i>=128&&(o&=2n**BigInt(n*8)-1n>>1n,o=-o),o}})}function HE(t,e=4,r=!0){if(typeof t=="number")return t;if(Ce(t))try{let n=Xy(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Xe=Wt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(mt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(mt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(mt.OP_1-1+r);continue}}if(typeof r=="number"&&(r=Xy().encode(BigInt(r))),!Ce(r))throw new Error(`Wrong Script OP=${r} (${typeof r})`);let n=r.length;n<mt.PUSHDATA1?t.byte(n):n<=255?(t.byte(mt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(mt.PUSHDATA2),t.bytes(zy.encode(n))):(t.byte(mt.PUSHDATA4),t.bytes(_e.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(mt.OP_0<r&&r<=mt.PUSHDATA4){let n;if(r<mt.PUSHDATA1)n=r;else if(r===mt.PUSHDATA1)n=gn.decodeStream(t);else if(r===mt.PUSHDATA2)n=zy.decodeStream(t);else if(r===mt.PUSHDATA4)n=_e.decodeStream(t);else throw new Error("Should be not possible");e.push(t.bytes(n))}else if(r===0)e.push(0);else if(mt.OP_1<=r&&r<=mt.OP_16)e.push(r-(mt.OP_1-1));else{let n=mt[r];if(n===void 0)throw new Error(`Unknown opcode=${r.toString(16)}`);e.push(n)}}return e}}),$E={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},Wc=Wt({encodeStream:(t,e)=>{if(typeof e=="number"&&(e=BigInt(e)),0n<=e&&e<=252n)return t.byte(Number(e));for(let[r,n,i,o]of Object.values($E))if(!(i>e||e>o)){t.byte(r);for(let s=0;s<n;s++)t.byte(Number(e>>8n*BigInt(s)&0xffn));return}throw t.err(`VarInt too big: ${e}`)},decodeStream:t=>{let e=t.byte();if(e<=252)return BigInt(e);let[r,n,i]=$E[e],o=0n;for(let s=0;s<n;s++)o|=BigInt(t.byte())<<8n*BigInt(s);if(o<i)throw t.err(`Wrong CompactSize(${8*n})`);return o}}),Or=yn(Wc,Ii.numberBigint),fr=Fe(Wc),Gc=Gt(Or,fr),il=t=>Gt(Wc,t),VE=xt({txid:Fe(32,!0),index:_e,finalScriptSig:fr,sequence:_e}),Ri=xt({amount:Fc,script:fr}),C8=xt({version:bo,segwitFlag:OE(new Uint8Array([0,1])),inputs:il(VE),outputs:il(Ri),witnesses:DE("segwitFlag",Gt("inputs/length",Gc)),lockTime:_e});function L8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Ui=jt(C8,L8),Es=xt({version:bo,inputs:il(VE),outputs:il(Ri),lockTime:_e});var e0=jt(Fe(null),t=>xo(t,Et.ecdsa)),ol=jt(Fe(32),t=>xo(t,Et.schnorr)),qE=jt(Fe(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),sl=xt({fingerprint:BE,path:Gt(null,_e)}),WE=xt({hashes:Gt(Or,Fe(32)),der:sl}),P8=Fe(78),M8=xt({pubKey:ol,leafHash:Fe(32)}),K8=xt({version:gn,internalKey:Fe(32),merklePath:Gt(null,Fe(32))}),Oi=jt(K8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),$8=Gt(null,xt({depth:gn,version:gn,script:fr})),vt=Fe(null),FE=Fe(20),Nu=Fe(32),cl={unsignedTx:[0,!1,Es,[0],[0],!1],xpub:[1,P8,sl,[],[0,2],!1],txVersion:[2,!1,_e,[2],[2],!1],fallbackLocktime:[3,!1,_e,[],[2],!1],inputCount:[4,!1,Or,[2],[2],!1],outputCount:[5,!1,Or,[2],[2],!1],txModifiable:[6,!1,gn,[],[2],!1],version:[251,!1,_e,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},Cu={nonWitnessUtxo:[0,!1,Ui,[],[0,2],!1],witnessUtxo:[1,!1,Ri,[],[0,2],!1],partialSig:[2,e0,vt,[],[0,2],!1],sighashType:[3,!1,_e,[],[0,2],!1],redeemScript:[4,!1,vt,[],[0,2],!1],witnessScript:[5,!1,vt,[],[0,2],!1],bip32Derivation:[6,e0,sl,[],[0,2],!1],finalScriptSig:[7,!1,vt,[],[0,2],!1],finalScriptWitness:[8,!1,Gc,[],[0,2],!1],porCommitment:[9,!1,vt,[],[0,2],!1],ripemd160:[10,FE,vt,[],[0,2],!1],sha256:[11,Nu,vt,[],[0,2],!1],hash160:[12,FE,vt,[],[0,2],!1],hash256:[13,Nu,vt,[],[0,2],!1],txid:[14,!1,Nu,[2],[2],!0],index:[15,!1,_e,[2],[2],!0],sequence:[16,!1,_e,[],[2],!0],requiredTimeLocktime:[17,!1,_e,[],[2],!1],requiredHeightLocktime:[18,!1,_e,[],[2],!1],tapKeySig:[19,!1,qE,[],[0,2],!1],tapScriptSig:[20,M8,qE,[],[0,2],!1],tapLeafScript:[21,Oi,vt,[],[0,2],!1],tapBip32Derivation:[22,Nu,WE,[],[0,2],!1],tapInternalKey:[23,!1,ol,[],[0,2],!1],tapMerkleRoot:[24,!1,Nu,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},GE=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],zE=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Lu={redeemScript:[0,!1,vt,[],[0,2],!1],witnessScript:[1,!1,vt,[],[0,2],!1],bip32Derivation:[2,e0,sl,[],[0,2],!1],amount:[3,!1,IE,[2],[2],!0],script:[4,!1,vt,[2],[2],!0],tapInternalKey:[5,!1,ol,[],[0,2],!1],tapTree:[6,!1,$8,[],[0,2],!1],tapBip32Derivation:[7,ol,WE,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},YE=[],jE=Gt(jy,xt({key:RE(Or,xt({type:Or,key:Fe(null)})),value:Fe(Or)}));function t0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var lM=xt({type:Or,key:Fe(null)});function r0(t){let e={};for(let r in t){let[n,i,o]=t[r];e[n]=[r,i,o]}return Wt({encodeStream:(r,n)=>{let i=[];for(let o in t){let s=n[o];if(s===void 0)continue;let[c,a,u]=t[o];if(!a)i.push({key:{type:c,key:Ve},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>ku(f[0],h[0]));for(let[f,h]of d)i.push({key:{key:f,type:c},value:h})}}if(n.unknown){n.unknown.sort((o,s)=>ku(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}jE.encodeStream(r,i)},decodeStream:r=>{let n=jE.decodeStream(r),i={},o={};for(let s of n){let c="unknown",a=s.key.key,u=s.value;if(e[s.key.type]){let[d,f,h]=e[s.key.type];if(c=d,!f&&a.length)throw new Error(`PSBT: Non-empty key for ${c} (key=${Te.encode(a)} value=${Te.encode(u)}`);if(a=f?f.decode(a):void 0,u=h.decode(u),!f){if(i[c])throw new Error(`PSBT: Same keys: ${c} (key=${a} value=${u})`);i[c]=u,o[c]=!0;continue}}else a={type:s.key.type,key:s.key.key};if(o[c])throw new Error(`PSBT: Key type with empty key and no key=${c} val=${u}`);i[c]||(i[c]=[]),i[c].push([a,u])}return i}})}var al=jt(r0(Cu),t=>{if(t.finalScriptWitness&&!t.finalScriptWitness.length)throw new Error("validateInput: empty finalScriptWitness");if(t.partialSig&&!t.partialSig.length)throw new Error("Empty partialSig");if(t.partialSig)for(let[e]of t.partialSig)xo(e,Et.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)xo(e,Et.ecdsa);if(t.requiredTimeLocktime!==void 0&&t.requiredTimeLocktime<5e8)throw new Error(`validateInput: wrong timeLocktime=${t.requiredTimeLocktime}`);if(t.requiredHeightLocktime!==void 0&&(t.requiredHeightLocktime<=0||t.requiredHeightLocktime>=5e8))throw new Error(`validateInput: wrong heighLocktime=${t.requiredHeightLocktime}`);if(t.tapLeafScript)for(let[e,r]of t.tapLeafScript){if((e.version&254)!==r[r.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(r[r.length-1]&1)throw new Error("validateInput: tapLeafScript version has parity bit!")}return t}),ul=jt(r0(Lu),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)xo(e,Et.ecdsa);return t}),JE=jt(r0(cl),t=>{if((t.version||0)===0){if(!t.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");for(let r of t.unsignedTx.inputs)if(r.finalScriptSig&&r.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}return t}),H8=xt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),global:JE,inputs:Gt("global/unsignedTx/inputs/length",al),outputs:Gt(null,ul)}),V8=xt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),global:JE,inputs:Gt("global/inputCount",al),outputs:Gt("global/outputCount",ul)}),hM=xt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),items:Gt(null,yn(Gt(jy,NE([UE(Or),Fe(Wc)])),Ii.dict()))});function Qy(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=t0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=t0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function n0(t,e,r){let n={};for(let i in r){let o=i;if(o!=="unknown"){if(!e[o])continue;let{allowInc:s,silentIgnore:c}=t0(e[o]);if(!s.includes(t)){if(c)continue;throw new Error(`Failed to serialize in PSBTv${t}: ${o} but versions allows inclusion=${s}`)}}n[o]=r[o]}return n}function ZE(t){let e=t&&t.global&&t.global.version||0;Qy(e,cl,t.global);for(let s of t.inputs)Qy(e,Cu,s);for(let s of t.outputs)Qy(e,Lu,s);let r=e?t.global.inputCount:t.global.unsignedTx.inputs.length;if(t.inputs.length<r)throw new Error("Not enough inputs");let n=t.inputs.slice(r);if(n.length>1||n.length&&Object.keys(n[0]).length)throw new Error(`Unexpected inputs left in tx=${n}`);let i=e?t.global.outputCount:t.global.unsignedTx.outputs.length;if(t.outputs.length<i)throw new Error("Not outputs inputs");let o=t.outputs.slice(i);if(o.length>1||o.length&&Object.keys(o[0]).length)throw new Error(`Unexpected outputs left in tx=${o}`);return t}function dl(t,e,r,n,i){let o={...r,...e};for(let s in t){let c=s,[a,u,d]=t[c],f=n&&!n.includes(s);if(e[s]===void 0&&s in e){if(f)throw new Error(`Cannot remove signed field=${s}`);delete o[s]}else if(u){let h=r&&r[s]?r[s]:[],p=e[c];if(p){if(!Array.isArray(p))throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);p=p.map(E=>{if(E.length!==2)throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);return[typeof E[0]=="string"?u.decode(Te.decode(E[0])):E[0],typeof E[1]=="string"?d.decode(Te.decode(E[1])):E[1]]});let g={},y=(E,S,I)=>{if(g[E]===void 0){g[E]=[S,I];return}let A=Te.encode(d.encode(g[E][1])),O=Te.encode(d.encode(I));if(A!==O)throw new Error(`keyMap(${c}): same key=${E} oldVal=${A} newVal=${O}`)};for(let[E,S]of h){let I=Te.encode(u.encode(E));y(I,E,S)}for(let[E,S]of p){let I=Te.encode(u.encode(E));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${E}`);delete g[I]}else y(I,E,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(Te.decode(o[s]));else if(f&&s in e&&r&&r[s]!==void 0&&!st(d.encode(e[s]),d.encode(r[s])))throw new Error(`Cannot change signed field=${s}`)}for(let s in o)if(!t[s]){if(i&&s==="unknown")continue;delete o[s]}return o}var i0=jt(H8,ZE),o0=jt(V8,ZE);var F8={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])||Te.encode(t[1])!=="4e73"))return{type:"p2a",script:Xe.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,Te.decode("4e73")]}};function Eo(t,e){try{return xo(t,e),!0}catch{return!1}}var j8={encode(t){if(!(t.length!==2||!Ce(t[0])||!Eo(t[0],Et.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},W8={encode(t){if(!(t.length!==5||t[0]!=="DUP"||t[1]!=="HASH160"||!Ce(t[2]))&&!(t[3]!=="EQUALVERIFY"||t[4]!=="CHECKSIG"))return{type:"pkh",hash:t[2]}},decode:t=>t.type==="pkh"?["DUP","HASH160",t.hash,"EQUALVERIFY","CHECKSIG"]:void 0},G8={encode(t){if(!(t.length!==3||t[0]!=="HASH160"||!Ce(t[1])||t[2]!=="EQUAL"))return{type:"sh",hash:t[1]}},decode:t=>t.type==="sh"?["HASH160",t.hash,"EQUAL"]:void 0},z8={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===32)return{type:"wsh",hash:t[1]}},decode:t=>t.type==="wsh"?[0,t.hash]:void 0},Y8={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===20)return{type:"wpkh",hash:t[1]}},decode:t=>t.type==="wpkh"?[0,t.hash]:void 0},J8={encode(t){let e=t.length-1;if(t[e]!=="CHECKMULTISIG")return;let r=t[0],n=t[e-1];if(typeof r!="number"||typeof n!="number")return;let i=t.slice(1,-2);if(n===i.length){for(let o of i)if(!Ce(o))return;return{type:"ms",m:r,pubkeys:i}}},decode:t=>t.type==="ms"?[t.m,...t.pubkeys,t.pubkeys.length,"CHECKMULTISIG"]:void 0},Z8={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])))return{type:"tr",pubkey:t[1]}},decode:t=>t.type==="tr"?[1,t.pubkey]:void 0},X8={encode(t){let e=t.length-1;if(t[e]!=="CHECKSIG")return;let r=[];for(let n=0;n<e;n++){let i=t[n];if(n&1){if(i!=="CHECKSIGVERIFY"||n===e-1)return;continue}if(!Ce(i))return;r.push(i)}return{type:"tr_ns",pubkeys:r}},decode:t=>{if(t.type!=="tr_ns")return;let e=[];for(let r=0;r<t.pubkeys.length-1;r++)e.push(t.pubkeys[r],"CHECKSIGVERIFY");return e.push(t.pubkeys[t.pubkeys.length-1],"CHECKSIG"),e}},Q8={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=HE(t[e-1]);if(typeof n=="number"){for(let i=0;i<e-1;i++){let o=t[i];if(i&1){if(o!==(i===1?"CHECKSIG":"CHECKSIGADD"))throw new Error("OutScript.encode/tr_ms: wrong element");continue}if(!Ce(o))throw new Error("OutScript.encode/tr_ms: wrong key element");r.push(o)}return{type:"tr_ms",pubkeys:r,m:n}}},decode:t=>{if(t.type!=="tr_ms")return;let e=[t.pubkeys[0],"CHECKSIG"];for(let r=1;r<t.pubkeys.length;r++)e.push(t.pubkeys[r],"CHECKSIGADD");return e.push(t.m,"NUMEQUAL"),e}},eR={encode(t){return{type:"unknown",script:Xe.encode(t)}},decode:t=>t.type==="unknown"?Xe.decode(t.script):void 0},tR=[F8,j8,W8,G8,z8,Y8,J8,Z8,X8,Q8,eR],rR=yn(Xe,Ii.match(tR)),Qe=jt(rR,t=>{if(t.type==="pk"&&!Eo(t.pubkey,Et.ecdsa))throw new Error("OutScript/pk: wrong key");if((t.type==="pkh"||t.type==="sh"||t.type==="wpkh")&&(!Ce(t.hash)||t.hash.length!==20))throw new Error(`OutScript/${t.type}: wrong hash`);if(t.type==="wsh"&&(!Ce(t.hash)||t.hash.length!==32))throw new Error("OutScript/wsh: wrong hash");if(t.type==="tr"&&(!Ce(t.pubkey)||!Eo(t.pubkey,Et.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if((t.type==="ms"||t.type==="tr_ns"||t.type==="tr_ms")&&!Array.isArray(t.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if(t.type==="ms"){let e=t.pubkeys.length;for(let r of t.pubkeys)if(!Eo(r,Et.ecdsa))throw new Error("OutScript/multisig: wrong pubkey");if(t.m<=0||e>16||t.m>e)throw new Error("OutScript/multisig: invalid params")}if(t.type==="tr_ns"||t.type==="tr_ms"){for(let e of t.pubkeys)if(!Eo(e,Et.schnorr))throw new Error(`OutScript/${t.type}: wrong pubkey`)}if(t.type==="tr_ms"){let e=t.pubkeys.length;if(t.m<=0||e>999||t.m>e)throw new Error("OutScript/tr_ms: invalid params")}return t});function XE(t,e){if(!st(t.hash,ke(e)))throw new Error("checkScript: wsh wrong witnessScript hash");let r=Qe.decode(e);if(r.type==="tr"||r.type==="tr_ns"||r.type==="tr_ms")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2SH`);if(r.type==="wpkh"||r.type==="sh")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2WSH`)}function f0(t,e,r){if(t){let n=Qe.decode(t);if(n.type==="tr_ns"||n.type==="tr_ms"||n.type==="ms"||n.type=="pk")throw new Error(`checkScript: non-wrapped ${n.type}`);if(n.type==="sh"&&e){if(!st(n.hash,jc(e)))throw new Error("checkScript: sh wrong redeemScript hash");let i=Qe.decode(e);if(i.type==="tr"||i.type==="tr_ns"||i.type==="tr_ms")throw new Error(`checkScript: P2${i.type} cannot be wrapped in P2SH`);if(i.type==="sh")throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}n.type==="wsh"&&r&&XE(n,r)}if(e){let n=Qe.decode(e);n.type==="wsh"&&r&&XE(n,r)}}var Di=(t,e=zr)=>{if(!Eo(t,Et.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=jc(t);return{type:"pkh",script:Qe.encode({type:"pkh",hash:r}),address:Yr(e).encode({type:"pkh",hash:r}),hash:r}};var vs=(t,e=zr)=>{if(!Eo(t,Et.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=jc(t);return{type:"wpkh",script:Qe.encode({type:"wpkh",hash:r}),address:Yr(e).encode({type:"wpkh",hash:r}),hash:r}};function nR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=yn(Xe,Ii.match(n)).decode(t);if(c!==void 0){if(typeof c.type!="string"||!c.type.startsWith("tr_"))throw new Error(`P2TR: invalid custom type=${c.type}`);return}}if(r)return}if(!["tr_ns","tr_ms"].includes(i.type))throw new Error(`P2TR: invalid leaf script=${i.type}`);let o=i;if(!r&&o.pubkeys)for(let s of o.pubkeys){if(st(s,nl))throw new Error("Unspendable taproot key in leaf script");if(st(s,e))throw new Error("Using P2TR with leaf script with same key as internal key is not supported")}}function ev(t){let e=Array.from(t);for(;e.length>=2;){e.sort((s,c)=>(c.weight||1)-(s.weight||1));let n=e.pop(),i=e.pop(),o=(i?.weight||1)+(n?.weight||1);e.push({weight:o,childs:[i?.childs||i,n?.childs||n]})}let r=e[0];return r?.childs||r}function c0(t,e=[]){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return{...t,path:e};if(t.type!=="branch")throw new Error(`taprootAddPath: wrong type=${t}`);return{...t,path:e,left:c0(t.left,[t.right.hash,...e]),right:c0(t.right,[t.left.hash,...e])}}function a0(t){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return[t];if(t.type!=="branch")throw new Error(`taprootWalkTree: wrong type=${t}`);return[...a0(t.left),...a0(t.right)]}function u0(t,e,r=!1,n){if(!t)throw new Error("taprootHashTree: empty tree");if(Array.isArray(t)&&t.length===1&&(t=t[0]),!Array.isArray(t)){let{leafVersion:a,script:u}=t;if(t.tapLeafScript||t.tapMerkleRoot&&!st(t.tapMerkleRoot,Ve))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?Te.decode(u):u;if(!Ce(d))throw new Error(`checkScript: wrong script type=${d}`);return nR(d,e,r,n),{type:"leaf",version:a,script:d,hash:Pu(d,a)}}if(t.length!==2&&(t=ev(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=u0(t[0],e,r,n),o=u0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return ku(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Ou("TapBranch",s,c)}}var d0=192,Pu=(t,e=d0)=>Ou("TapLeaf",new Uint8Array([e]),fr.encode(t));function Ss(t,e,r=zr,n=!1,i){if(!t&&!e)throw new Error("p2tr: should have pubKey or scriptTree (or both)");let o=typeof t=="string"?Te.decode(t):t||nl;if(!Eo(o,Et.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=c0(u0(e,o,n,i)),c=s.hash,[a,u]=Du(o,c),d=a0(s).map(f=>({...f,controlBlock:Oi.encode({version:(f.version||d0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Qe.encode({type:"tr",pubkey:a}),address:Yr(r).encode({type:"tr",pubkey:a}),tweakedPubkey:a,tapInternalKey:o,leaves:d,tapLeafScript:d.map(f=>[Oi.decode(f.controlBlock),Fn(f.script,new Uint8Array([f.version||d0]))]),tapMerkleRoot:c}}else{let s=Du(o,Ve)[0];return{type:"tr",script:Qe.encode({type:"tr",pubkey:s}),address:Yr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var tv=bE(ke);function rv(t,e){if(e.length<2||e.length>40)throw new Error("Witness: invalid length");if(t>16)throw new Error("Witness: invalid version");if(t===0&&!(e.length===20||e.length===32))throw new Error("Witness: invalid length for version")}function s0(t,e,r=zr){rv(t,e);let n=t===0?zf:Hc;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function QE(t,e){return tv.encode(Fn(Uint8Array.from(e),t))}function Yr(t=zr){return{encode(e){let{type:r}=e;if(r==="wpkh")return s0(0,e.hash,t);if(r==="wsh")return s0(0,e.hash,t);if(r==="tr")return s0(1,e.pubkey,t);if(r==="pkh")return QE(e.hash,[t.pubKeyHash]);if(r==="sh")return QE(e.hash,[t.scriptHash]);throw new Error(`Unknown address type=${r}`)},decode(e){if(e.length<14||e.length>74)throw new Error("Invalid address length");if(t.bech32&&e.toLowerCase().startsWith(`${t.bech32}1`)){let n;try{if(n=zf.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=Hc.decode(e),n.words[0]===0)throw new Error(`bech32m: wrong version=${n.words[0]}`)}if(n.prefix!==t.bech32)throw new Error(`wrong bech32 prefix=${n.prefix}`);let[i,...o]=n.words,s=zf.fromWords(o);if(rv(i,s),i===0&&s.length===32)return{type:"wsh",hash:s};if(i===0&&s.length===20)return{type:"wpkh",hash:s};if(i===1&&s.length===32)return{type:"tr",pubkey:s};throw new Error("Unknown witness program")}let r=tv.decode(e);if(r.length!==21)throw new Error("Invalid base58 address");if(r[0]===t.pubKeyHash)return{type:"pkh",hash:r.slice(1)};if(r[0]===t.scriptHash)return{type:"sh",hash:r.slice(1)};throw new Error(`Invalid address prefix=${r[0]}`)}}}l();var fl=new Uint8Array(32),iR={amount:0xffffffffffffffffn,script:Ve},oR=t=>Math.ceil(t/4),sR=8,cR=2,As=0,y0=4294967295,aR=Ii.decimal(sR),Ku=(t,e)=>t===void 0?e:t;function hl(t){if(Array.isArray(t))return t.map(e=>hl(e));if(Ce(t))return Uint8Array.from(t);if(["number","bigint","boolean","string","undefined"].includes(typeof t))return t;if(t===null)return t;if(typeof t=="object")return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,hl(r)]));throw new Error(`cloneDeep: unknown type=${t} (${typeof t})`)}var je;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.ANYONECANPAY=128]="ANYONECANPAY"})(je||(je={}));var vo;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.DEFAULT_ANYONECANPAY=128]="DEFAULT_ANYONECANPAY",t[t.ALL_ANYONECANPAY=129]="ALL_ANYONECANPAY",t[t.NONE_ANYONECANPAY=130]="NONE_ANYONECANPAY",t[t.SINGLE_ANYONECANPAY=131]="SINGLE_ANYONECANPAY"})(vo||(vo={}));function uR(t,e,r,n=Ve){return st(r,e)&&(t=ME(t,n),e=rl(t)),{privKey:t,pubKey:e}}function Ts(t){if(t.script===void 0||t.amount===void 0)throw new Error("Transaction/output: script and amount required");return{script:t.script,amount:t.amount}}function Mu(t){if(t.txid===void 0||t.index===void 0)throw new Error("Transaction/input: txid and index required");return{txid:t.txid,index:t.index,sequence:Ku(t.sequence,y0),finalScriptSig:Ku(t.finalScriptSig,Ve)}}function l0(t){for(let e in t){let r=e;GE.includes(r)||delete t[r]}}var h0=xt({txid:Fe(32,!0),index:_e});function dR(t){if(typeof t!="number"||typeof vo[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function nv(t){let e=t&31;return{isAny:!!(t&je.ANYONECANPAY),isNone:e===je.NONE,isSingle:e===je.SINGLE}}function fR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:Ku(t.version,cR),lockTime:Ku(t.lockTime,0),PSBTVersion:Ku(t.PSBTVersion,0)};if(typeof e.allowUnknowInput<"u"&&(t.allowUnknownInputs=e.allowUnknowInput),typeof e.allowUnknowOutput<"u"&&(t.allowUnknownOutputs=e.allowUnknowOutput),typeof e.lockTime!="number")throw new Error("Transaction lock time should be number");if(_e.encode(e.lockTime),e.PSBTVersion!==0&&e.PSBTVersion!==2)throw new Error(`Unknown PSBT version ${e.PSBTVersion}`);for(let r of["allowUnknownVersion","allowUnknownOutputs","allowUnknownInputs","disableScriptCheck","bip174jsCompat","allowLegacyWitnessUtxo","lowR"]){let n=e[r];if(n!==void 0&&typeof n!="boolean")throw new Error(`Transation options wrong type: ${r}=${n} (${typeof n})`)}if(e.allowUnknownVersion?typeof e.version=="number":![-1,0,1,2,3].includes(e.version))throw new Error(`Unknown version: ${e.version}`);if(e.customScripts!==void 0){let r=e.customScripts;if(!Array.isArray(r))throw new Error(`wrong custom scripts type (expected array): customScripts=${r} (${typeof r})`);for(let n of r){if(typeof n.encode!="function"||typeof n.decode!="function")throw new Error(`wrong script=${n} (${typeof n})`);if(n.finalizeTaproot!==void 0&&typeof n.finalizeTaproot!="function")throw new Error(`wrong script=${n} (${typeof n})`)}}return Object.freeze(e)}function iv(t){if(t.nonWitnessUtxo&&t.index!==void 0){let e=t.nonWitnessUtxo.outputs.length-1;if(t.index>e)throw new Error(`validateInput: index(${t.index}) not in nonWitnessUtxo`);let r=t.nonWitnessUtxo.outputs[t.index];if(t.witnessUtxo&&(!st(t.witnessUtxo.script,r.script)||t.witnessUtxo.amount!==r.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo");if(t.txid){if(t.nonWitnessUtxo.outputs.length-1<t.index)throw new Error("nonWitnessUtxo: incorect output index");let i=_s.fromRaw(Ui.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=Te.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function ll(t){if(t.nonWitnessUtxo){if(t.index===void 0)throw new Error("Unknown input index");return t.nonWitnessUtxo.outputs[t.index]}else{if(t.witnessUtxo)return t.witnessUtxo;throw new Error("Cannot find previous output info")}}function ov(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=Te.decode(o)),Ce(o)&&(o=Ui.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=Te.decode(s)),s===void 0&&(s=e?.txid);let c={...e,...t,nonWitnessUtxo:o,txid:s};!("nonWitnessUtxo"in t)&&c.nonWitnessUtxo===void 0&&delete c.nonWitnessUtxo,c.sequence===void 0&&(c.sequence=y0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=dl(Cu,c,e,r,i),al.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&f0(a&&a.script,c.redeemScript,c.witnessScript),c}function p0(t,e=!1){let r="legacy",n=je.ALL,i=ll(t),o=Qe.decode(i.script),s=o.type,c=o,a=[o];if(o.type==="tr")return n=je.DEFAULT,{txType:"taproot",type:"tr",last:o,lastScript:i.script,defaultSighash:n,sighash:t.sighashType||n};{if((o.type==="wpkh"||o.type==="wsh")&&(r="segwit"),o.type==="sh"){if(!t.redeemScript)throw new Error("inputType: sh without redeemScript");let h=Qe.decode(t.redeemScript);(h.type==="wpkh"||h.type==="wsh")&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}if(c.type==="wsh"){if(!t.witnessScript)throw new Error("inputType: wsh without witnessScript");let h=Qe.decode(t.witnessScript);h.type==="wsh"&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}let u=a[a.length-1];if(u.type==="sh"||u.type==="wsh")throw new Error("inputType: sh/wsh cannot be terminal type");let d=Qe.encode(u),f={type:s,txType:r,last:u,lastScript:d,defaultSighash:n,sighash:t.sighashType||n};if(r==="legacy"&&!e&&!t.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");return f}}var _s=class t{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];let r=this.opts=fR(e);r.lockTime!==As&&(this.global.fallbackLocktime=r.lockTime),this.global.txVersion=r.version}static fromRaw(e,r={}){let n=Ui.decode(e),i=new t({...r,version:n.version,lockTime:n.lockTime});for(let o of n.outputs)i.addOutput(o);if(i.outputs=n.outputs,i.inputs=n.inputs,n.witnesses)for(let o=0;o<n.witnesses.length;o++)i.inputs[o].finalScriptWitness=n.witnesses[o];return i}static fromPSBT(e,r={}){let n;try{n=i0.decode(e)}catch(f){try{n=o0.decode(e)}catch{throw f}}let i=n.global.version||0;if(i!==0&&i!==2)throw new Error(`Wrong PSBT version=${i}`);let o=n.global.unsignedTx,s=i===0?o?.version:n.global.txVersion,c=i===0?o?.lockTime:n.global.fallbackLocktime,a=new t({...r,version:s,lockTime:c,PSBTVersion:i}),u=i===0?o?.inputs.length:n.global.inputCount;a.inputs=n.inputs.slice(0,u).map((f,h)=>iv({finalScriptSig:Ve,...n.global.unsignedTx?.inputs[h],...f}));let d=i===0?o?.outputs.length:n.global.outputCount;return a.outputs=n.outputs.slice(0,d).map((f,h)=>({...f,...n.global.unsignedTx?.outputs[h]})),a.global={...n.global,txVersion:s},c!==As&&(a.global.fallbackLocktime=c),a}toPSBT(e=this.opts.PSBTVersion){if(e!==0&&e!==2)throw new Error(`Wrong PSBT version=${e}`);let r=this.inputs.map(o=>iv(n0(e,Cu,o)));for(let o of r)o.partialSig&&!o.partialSig.length&&delete o.partialSig,o.finalScriptSig&&!o.finalScriptSig.length&&delete o.finalScriptSig,o.finalScriptWitness&&!o.finalScriptWitness.length&&delete o.finalScriptWitness;let n=this.outputs.map(o=>n0(e,Lu,o)),i={...this.global};return e===0?(i.unsignedTx=Es.decode(Es.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Mu).map(o=>({...o,finalScriptSig:Ve})),outputs:this.outputs.map(Ts)})),delete i.fallbackLocktime,delete i.txVersion):(i.version=e,i.txVersion=this.version,i.inputCount=this.inputs.length,i.outputCount=this.outputs.length,i.fallbackLocktime&&i.fallbackLocktime===As&&delete i.fallbackLocktime),this.opts.bip174jsCompat&&(r.length||r.push({}),n.length||n.push({})),(e===0?i0:o0).encode({global:i,inputs:r,outputs:n})}get lockTime(){let e=As,r=0,n=As,i=0;for(let o of this.inputs)o.requiredHeightLocktime&&(e=Math.max(e,o.requiredHeightLocktime),r++),o.requiredTimeLocktime&&(n=Math.max(n,o.requiredTimeLocktime),i++);return r&&r>=i?e:n!==As?n:this.global.fallbackLocktime||As}get version(){if(this.global.txVersion===void 0)throw new Error("No global.txVersion");return this.global.txVersion}inputStatus(e){this.checkInputIdx(e);let r=this.inputs[e];return r.finalScriptSig&&r.finalScriptSig.length||r.finalScriptWitness&&r.finalScriptWitness.length?"finalized":r.tapKeySig||r.tapScriptSig&&r.tapScriptSig.length||r.partialSig&&r.partialSig.length?"signed":"unsigned"}inputSighash(e){this.checkInputIdx(e);let r=this.inputs[e].sighashType,n=r===void 0?je.DEFAULT:r,i=n===je.DEFAULT?je.ALL:n&3;return{sigInputs:n&je.ANYONECANPAY,sigOutputs:i}}signStatus(){let e=!0,r=!0,n=[],i=[];for(let o=0;o<this.inputs.length;o++){if(this.inputStatus(o)==="unsigned")continue;let{sigInputs:c,sigOutputs:a}=this.inputSighash(o);if(c===je.ANYONECANPAY?n.push(o):e=!1,a===je.ALL)r=!1;else if(a===je.SINGLE)i.push(o);else if(a!==je.NONE)throw new Error(`Wrong signature hash output type: ${a}`)}return{addInput:e,addOutput:r,inputs:n,outputs:i}}get isFinal(){for(let e=0;e<this.inputs.length;e++)if(this.inputStatus(e)!=="finalized")return!1;return!0}get hasWitnesses(){let e=!1;for(let r of this.inputs)r.finalScriptWitness&&r.finalScriptWitness.length&&(e=!0);return e}get weight(){if(!this.isFinal)throw new Error("Transaction is not finalized");let e=32,r=this.outputs.map(Ts);e+=4*Or.encode(this.outputs.length).length;for(let n of r)e+=32+4*fr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Or.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*fr.encode(n.finalScriptSig||Ve).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Gc.encode(n.finalScriptWitness).length);return e}get vsize(){return oR(this.weight)}toBytes(e=!1,r=!1){return Ui.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Mu).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||Ve})),outputs:this.outputs.map(Ts),witnesses:this.inputs.map(n=>n.finalScriptWitness||[]),segwitFlag:r&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return Te.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Te.encode(Bi(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Te.encode(Bi(this.toBytes(!0)).reverse())}checkInputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.inputs.length)throw new Error(`Wrong input index=${e}`)}getInput(e){return this.checkInputIdx(e),hl(this.inputs[e])}get inputsLength(){return this.inputs.length}addInput(e,r=!1){if(!r&&!this.signStatus().addInput)throw new Error("Tx has signed inputs, cannot add new one");return this.inputs.push(ov(e,void 0,void 0,this.opts.disableScriptCheck)),this.inputs.length-1}updateInput(e,r,n=!1){this.checkInputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addInput||o.inputs.includes(e))&&(i=zE)}this.inputs[e]=ov(r,this.inputs[e],i,this.opts.disableScriptCheck,this.opts.allowUnknown)}checkOutputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.outputs.length)throw new Error(`Wrong output index=${e}`)}getOutput(e){return this.checkOutputIdx(e),hl(this.outputs[e])}getOutputAddress(e,r=zr){let n=this.getOutput(e);if(n.script)return Yr(r).encode(Qe.decode(n.script))}get outputsLength(){return this.outputs.length}normalizeOutput(e,r,n){let{amount:i,script:o}=e;if(i===void 0&&(i=r?.amount),typeof i!="bigint")throw new Error(`Wrong amount type, should be of type bigint in sats, but got ${i} of type ${typeof i}`);typeof o=="string"&&(o=Te.decode(o)),o===void 0&&(o=r?.script);let s={...r,...e,amount:i,script:o};if(s.amount===void 0&&delete s.amount,s=dl(Lu,s,r,n,this.opts.allowUnknown),ul.encode(s),s.script&&!this.opts.allowUnknownOutputs&&Qe.decode(s.script).type==="unknown")throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure");return this.opts.disableScriptCheck||f0(s.script,s.redeemScript,s.witnessScript),s}addOutput(e,r=!1){if(!r&&!this.signStatus().addOutput)throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(this.normalizeOutput(e)),this.outputs.length-1}updateOutput(e,r,n=!1){this.checkOutputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addOutput||o.outputs.includes(e))&&(i=YE)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=zr){return this.addOutput({script:Qe.encode(Yr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=ll(n);if(!i)throw new Error("Empty input amount");e+=i.amount}let r=this.outputs.map(Ts);for(let n of r)e-=n.amount;return e}preimageLegacy(e,r,n){let{isAny:i,isNone:o,isSingle:s}=nv(n);if(e<0||!Number.isSafeInteger(e))throw new Error(`Invalid input idx=${e}`);if(s&&e>=this.outputs.length||e>=this.inputs.length)return _E.encode(1n);r=Xe.encode(Xe.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(Mu).map((d,f)=>({...d,finalScriptSig:f===e?r:Ve}));i?c=[c[e]]:(o||s)&&(c=c.map((d,f)=>({...d,sequence:f===e?d.sequence:0})));let a=this.outputs.map(Ts);o?a=[]:s&&(a=a.slice(0,e).fill(iR).concat([a[e]]));let u=Ui.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Bi(u,bo.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=nv(n),a=fl,u=fl,d=fl,f=this.inputs.map(Mu),h=this.outputs.map(Ts);o||(a=Bi(...f.map(h0.encode))),!o&&!c&&!s&&(u=Bi(...f.map(g=>_e.encode(g.sequence)))),!c&&!s?d=Bi(...h.map(Ri.encode)):c&&e<h.length&&(d=Bi(Ri.encode(h[e])));let p=f[e];return Bi(bo.encode(this.version),a,u,Fe(32,!0).encode(p.txid),_e.encode(p.index),fr.encode(r),Fc.encode(i),_e.encode(p.sequence),d,_e.encode(this.lockTime),_e.encode(n))}preimageWitnessV1(e,r,n,i,o=-1,s,c=192,a){if(!Array.isArray(i)||this.inputs.length!==i.length)throw new Error(`Invalid amounts array=${i}`);if(!Array.isArray(r)||this.inputs.length!==r.length)throw new Error(`Invalid prevOutScript array=${r}`);let u=[gn.encode(0),gn.encode(n),bo.encode(this.version),_e.encode(this.lockTime)],d=n===je.DEFAULT?je.ALL:n&3,f=n&je.ANYONECANPAY,h=this.inputs.map(Mu),p=this.outputs.map(Ts);f!==je.ANYONECANPAY&&u.push(...[h.map(h0.encode),i.map(Fc.encode),r.map(fr.encode),h.map(y=>_e.encode(y.sequence))].map(y=>ke(Fn(...y)))),d===je.ALL&&u.push(ke(Fn(...p.map(Ri.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===je.ANYONECANPAY){let y=h[e];u.push(h0.encode(y),Fc.encode(i[e]),fr.encode(r[e]),_e.encode(y.sequence))}else u.push(_e.encode(e));return g&1&&u.push(ke(fr.encode(a||Ve))),d===je.SINGLE&&u.push(e<p.length?ke(Ri.encode(p[e])):fl),s&&u.push(Pu(s,c),gn.encode(0),bo.encode(o)),Ou("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=p0(o,this.opts.allowLegacyWitnessUtxo);if(!Ce(e)){if(!o.bip32Derivation||!o.bip32Derivation.length)throw new Error("bip32Derivation: empty");let d=o.bip32Derivation.filter(h=>h[1].fingerprint==e.fingerprint).map(([h,{path:p}])=>{let g=e;for(let y of p)g=g.deriveChild(y);if(!st(g.publicKey,h))throw new Error("bip32Derivation: wrong pubKey");if(!g.privateKey)throw new Error("bip32Derivation: no privateKey");return g});if(!d.length)throw new Error(`bip32Derivation: no items with fingerprint=${e.fingerprint}`);let f=!1;for(let h of d)this.signIdx(h.privateKey,r)&&(f=!0);return f}n?n.forEach(dR):n=[s.defaultSighash];let c=s.sighash;if(!n.includes(c))throw new Error(`Input with not allowed sigHash=${c}. Allowed: ${n.join(", ")}`);let{sigOutputs:a}=this.inputSighash(r);if(a===je.SINGLE&&r>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${r}`);let u=ll(o);if(s.txType==="taproot"){let d=this.inputs.map(ll),f=d.map(E=>E.script),h=d.map(E=>E.amount),p=!1,g=rl(e),y=o.tapMerkleRoot||Ve;if(o.tapInternalKey){let{pubKey:E,privKey:S}=uR(e,g,o.tapInternalKey,y),[I,A]=Du(o.tapInternalKey,y);if(st(I,E)){let O=this.preimageWitnessV1(r,f,c,h),T=Fn(Jy(O,S,i),c!==je.DEFAULT?new Uint8Array([c]):Ve);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[E,S]of o.tapLeafScript){let I=S.subarray(0,-1),A=Xe.decode(I),O=S[S.length-1],T=Pu(I,O);if(A.findIndex($=>Ce($)&&st($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,I,O),j=Fn(Jy(q,e,i),c!==je.DEFAULT?new Uint8Array([c]):Ve);this.updateInput(r,{tapScriptSig:[[{pubKey:g,leafHash:T},j]]},!0),p=!0}}if(!p)throw new Error("No taproot scripts signed");return!0}else{let d=Yy(e),f=!1,h=jc(d);for(let y of Xe.decode(s.lastScript))Ce(y)&&(st(y,d)||st(y,h))&&(f=!0);if(!f)throw new Error(`Input script doesn't have pubKey: ${s.lastScript}`);let p;if(s.txType==="legacy")p=this.preimageLegacy(r,s.lastScript,c);else if(s.txType==="segwit"){let y=s.lastScript;s.last.type==="wpkh"&&(y=Qe.encode({type:"pkh",hash:s.last.hash})),p=this.preimageWitnessV0(r,y,c,u.amount)}else throw new Error(`Transaction/sign: unknown tx type: ${s.txType}`);let g=LE(p,e,this.opts.lowR);this.updateInput(r,{partialSig:[[d,Fn(g,new Uint8Array([c]))]]},!0)}return!0}sign(e,r,n){let i=0;for(let o=0;o<this.inputs.length;o++)try{this.signIdx(e,o,r,n)&&i++}catch{}if(!i)throw new Error("No inputs signed");return i}finalizeIdx(e){if(this.checkInputIdx(e),this.fee<0n)throw new Error("Outputs spends more than inputs amount");let r=this.inputs[e],n=p0(r,this.opts.allowLegacyWitnessUtxo);if(n.txType==="taproot"){if(r.tapKeySig)r.finalScriptWitness=[r.tapKeySig];else if(r.tapLeafScript&&r.tapScriptSig){let a=r.tapLeafScript.sort((u,d)=>Oi.encode(u[0]).length-Oi.encode(d[0]).length);for(let[u,d]of a){let f=d.slice(0,-1),h=d[d.length-1],p=Qe.decode(f),g=Pu(f,h),y=r.tapScriptSig.filter(S=>st(S[0].leafHash,g)),E=[];if(p.type==="tr_ms"){let S=p.m,I=p.pubkeys,A=0;for(let O of I){let T=y.findIndex(M=>st(M[0].pubKey,O));if(A===S||T===-1){E.push(Ve);continue}E.push(y[T][1]),A++}if(A!==S)continue}else if(p.type==="tr_ns"){for(let S of p.pubkeys){let I=y.findIndex(A=>st(A[0].pubKey,S));I!==-1&&E.push(y[I][1])}if(E.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Xe.decode(f);if(E=y.map(([{pubKey:I},A])=>{let O=S.findIndex(T=>Ce(T)&&st(T,I));if(O===-1)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:A,pos:O}}).sort((I,A)=>I.pos-A.pos).map(I=>I.signature),!E.length)continue}else{let S=this.opts.customScripts;if(S)for(let I of S){if(!I.finalizeTaproot)continue;let A=Xe.decode(f),O=I.encode(A);if(O===void 0)continue;let T=I.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(Oi.encode(u)),r.finalScriptSig=Ve,l0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=E.reverse().concat([f,Oi.encode(u)]);break}if(!r.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}else throw new Error("finalize/taproot: unknown input");r.finalScriptSig=Ve,l0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=Ve,o=[];if(n.last.type==="ms"){let a=n.last.m,u=n.last.pubkeys,d=[];for(let f of u){let h=r.partialSig.find(p=>st(f,p[0]));h&&d.push(h[1])}if(d=d.slice(0,a),d.length!==a)throw new Error(`Multisig: wrong signatures count, m=${a} n=${u.length} signatures=${d.length}`);i=Xe.encode([0,...d])}else if(n.last.type==="pk")i=Xe.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Xe.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=Ve,o=[r.partialSig[0][1],r.partialSig[0][0]];else if(n.last.type==="unknown"&&!this.opts.allowUnknownInputs)throw new Error("Unknown inputs not allowed");let s,c;if(n.type.includes("wsh-")&&(i.length&&n.lastScript.length&&(o=Xe.decode(i).map(a=>{if(a===0)return Ve;if(Ce(a))return a;throw new Error(`Wrong witness op=${a}`)})),o=o.concat(n.lastScript)),n.txType==="segwit"&&(c=o),n.type.startsWith("sh-wsh-")?s=Xe.encode([Xe.encode([0,ke(n.lastScript)])]):n.type.startsWith("sh-")?s=Xe.encode([...Xe.decode(i),n.lastScript]):n.type.startsWith("wsh-")||n.txType!=="segwit"&&(s=i),!s&&!c)throw new Error("Unknown error finalizing input");s&&(r.finalScriptSig=s),c&&(r.finalScriptWitness=c),l0(r)}finalize(){for(let e=0;e<this.inputs.length;e++)this.finalizeIdx(e)}extract(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");if(this.fee<0n)throw new Error("Outputs spends more than inputs amount");return this.toBytes(!0,!0)}combine(e){for(let i of["PSBTVersion","version","lockTime"])if(this.opts[i]!==e.opts[i])throw new Error(`Transaction/combine: different ${i} this=${this.opts[i]} other=${e.opts[i]}`);for(let i of["inputs","outputs"])if(this[i].length!==e[i].length)throw new Error(`Transaction/combine: different ${i} length this=${this[i].length} other=${e[i].length}`);let r=this.global.unsignedTx?Es.encode(this.global.unsignedTx):Ve,n=e.global.unsignedTx?Es.encode(e.global.unsignedTx):Ve;if(!st(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=dl(cl,this.global,e.global,void 0,this.opts.allowUnknown);for(let i=0;i<this.inputs.length;i++)this.updateInput(i,e.inputs[i],!0);for(let i=0;i<this.outputs.length;i++)this.updateOutput(i,e.outputs[i],!0);return this}clone(){return t.fromPSBT(this.toPSBT(this.opts.PSBTVersion),this.opts)}};l();l();l();l();l();function sv(t,e){var r="",n=e&&e.include,i=e&&e.exclude;i&&typeof i=="string"&&(i=[i]),n&&n.sort();var o=new WeakMap,s=e&&e.allowCircular,c=e&&e.filterUndefined,a=e&&e.undefinedInArrayToNull;return u(t,""),r;function u(d,f){if(d===null||typeof d!="object"||d.toJSON!=null)r+=JSON.stringify(d);else if(Array.isArray(d)){var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="[";var p=!1;d.forEach(function(S,I){p&&(r+=","),p=!0,a&&S===void 0&&(S=null),u(S,f+"["+I+"]")}),r+="]"}else{var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="{";var g=!1,y=function(I){i&&i.includes(I)||(g&&(r+=","),g=!0,r+=JSON.stringify(I),r+=":",u(d[I],f+"."+I))};if(f===""&&n)n.forEach(function(I){d.hasOwnProperty(I)&&y(I)});else{var E=Object.keys(d);c&&(E=E.filter(function(I){return d[I]!==void 0})),E.sort(),E.forEach(function(I){y(I)})}r+="}"}}}function cv(t,e){return sv(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var g0;(function(t){t.INVALID_DID="INVALID_DID",t.METHOD_NOT_SUPPORTED="METHOD_NOT_SUPPORTED",t.INTERNAL_ERROR="INTERNAL_ERROR",t.INVALID_DID_DOCUMENT="INVALID_DID_DOCUMENT",t.INVALID_DID_UPDATE="INVALID_DID_UPDATE",t.INVALID_DID_DOCUMENT_LENGTH="INVALID_DID_DOCUMENT_LENGTH",t.INVALID_DID_URL="INVALID_DID_URL",t.INVALID_PREVIOUS_DID_PROOF="INVALID_PREVIOUS_DID_PROOF",t.INVALID_PUBLIC_KEY="INVALID_PUBLIC_KEY",t.INVALID_PUBLIC_KEY_MULTIBASE="INVALID_PUBLIC_KEY_MULTIBASE",t.INVALID_PUBLIC_KEY_LENGTH="INVALID_PUBLIC_KEY_LENGTH",t.INVALID_PUBLIC_KEY_TYPE="INVALID_PUBLIC_KEY_TYPE",t.INVALID_SIGNATURE="INVALID_SIGNATURE",t.NOT_FOUND="NOT_FOUND",t.REPRESENTATION_NOT_SUPPORTED="REPRESENTATION_NOT_SUPPORTED",t.UNSUPPORTED_PUBLIC_KEY_TYPE="UNSUPPORTED_PUBLIC_KEY_TYPE",t.PROOF_VERIFICATION_ERROR="PROOF_VERIFICATION_ERROR",t.PROOF_GENERATION_ERROR="PROOF_GENERATION_ERROR",t.PROOF_SERIALIZATION_ERROR="PROOF_SERIALIZATION_ERROR",t.PROOF_PARSING_ERROR="PROOF_PARSING_ERROR",t.VERIFICATION_METHOD_ERROR="VERIFICATION_METHOD_ERROR",t.LATE_PUBLISHING_ERROR="LATE_PUBLISHING_ERROR",t.INVALID_SIDECAR_DATA="INVALID_SIDECAR_DATA",t.MISSING_UPDATE_DATA="MISSING_UPDATE_DATA",t.INVALID_UPDATE="INVALID_UPDATE",t.INVALID_DOMAIN_ERROR="INVALID_DOMAIN_ERROR",t.MISSING_RESOLUTION_OPTIONS="MISSING_RESOLUTION_OPTIONS",t.INVALID_OPTIONS="INVALID_OPTIONS"})(g0||(g0={}));var{INVALID_DID:Pt,METHOD_NOT_SUPPORTED:pl,INTERNAL_ERROR:av,INVALID_DID_DOCUMENT:De,INVALID_DID_UPDATE:Ie,INVALID_DID_URL:rK,INVALID_PREVIOUS_DID_PROOF:nK,INVALID_PUBLIC_KEY:iK,INVALID_PUBLIC_KEY_MULTIBASE:oK,INVALID_PUBLIC_KEY_LENGTH:sK,INVALID_PUBLIC_KEY_TYPE:cK,INVALID_SIGNATURE:aK,PROOF_VERIFICATION_ERROR:ki,PROOF_GENERATION_ERROR:Ao,PROOF_SERIALIZATION_ERROR:uv,PROOF_PARSING_ERROR:uK,VERIFICATION_METHOD_ERROR:yl,LATE_PUBLISHING_ERROR:gl,INVALID_SIDECAR_DATA:dK,MISSING_UPDATE_DATA:fK,MISSING_RESOLUTION_OPTIONS:lK,INVALID_OPTIONS:dv}=g0,zt=class t extends Error{name="DidMethodError";type="DidMethodError";data;constructor(e,r={}){super(e),this.type=r.type??this.type,this.name=r.name??this.name,this.data=r.data,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,t)}},we=class extends zt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var wt=class extends zt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},St=class extends zt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},Le=class extends zt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var qe=class extends zt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},So=class extends zt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},mn=class extends zt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},wn=class extends zt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},jn=class extends zt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},Is=class extends zt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},bn=class extends zt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var zc=class extends zt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var lR=new Set(["jcs"]),hR=new Set(["hex","base58","base64urlnopad"]);function m0(t){let e=t.toLowerCase();if(!lR.has(e))throw new zc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function w0(t){let e=t.toLowerCase();if(!hR.has(e))throw new zc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function rr(t,e="jcs"){switch(m0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return cv(n)}default:throw new zc(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function To(t){return ke(t)}function Jr(t,e="base64urlnopad"){switch(w0(e)){case"hex":return Te.encode(t);case"base58":return Gf.encode(t);case"base64urlnopad":return $c.encode(t)}}function Bs(t,e="base64urlnopad"){switch(w0(e)){case"hex":return Te.decode(t);case"base58":return Gf.decode(t);case"base64urlnopad":return $c.decode(t)}}function Yc(t,e="jcs"){return To(rr(t,m0(e)))}function Wn(t,e){let r=m0(e?.algorithm??"jcs"),n=w0(e?.encoding??"base64urlnopad");return Jr(To(rr(t,r)),n)}l();l();var b0={};Sf(b0,{JsonPatchError:()=>ct,_areEquals:()=>Vu,applyOperation:()=>Rs,applyPatch:()=>Sl,applyReducer:()=>wR,deepClone:()=>gR,getValueByPointer:()=>El,validate:()=>lv,validator:()=>vl});l();l();var pR=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)i.hasOwnProperty(o)&&(n[o]=i[o])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),yR=Object.prototype.hasOwnProperty;function wl(t,e){return yR.call(t,e)}function bl(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var i in t)wl(t,i)&&n.push(i);return n}function Mt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function xl(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function Gn(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function $u(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function ml(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(ml(t[e]))return!0}else if(typeof t=="object"){for(var n=bl(t),i=n.length,o=0;o<i;o++)if(ml(t[n[o]]))return!0}}return!1}function fv(t,e){var r=[t];for(var n in e){var i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(n+": "+i)}return r.join(`
3
- `)}var Hu=function(t){pR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,fv(r,{name:n,index:i,operation:o,tree:s}))||this;return a.name=n,a.index=i,a.operation=o,a.tree=s,Object.setPrototypeOf(a,c.prototype),a.message=fv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var ct=Hu,gR=Mt,Jc={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=El(r,this.path);n&&(n=Mt(n));var i=Rs(r,{op:"remove",path:this.from}).removed;return Rs(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=El(r,this.from);return Rs(r,{op:"add",path:this.path,value:Mt(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Vu(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},mR={add:function(t,e,r){return xl(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Jc.move,copy:Jc.copy,test:Jc.test,_get:Jc._get};function El(t,e){if(e=="")return t;var r={op:"_get",path:e};return Rs(t,r),r.value}function Rs(t,e,r,n,i,o){if(r===void 0&&(r=!1),n===void 0&&(n=!0),i===void 0&&(i=!0),o===void 0&&(o=0),r&&(typeof r=="function"?r(e,0,t,e.path):vl(e,0)),e.path===""){var s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=El(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Vu(t,e.value),s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(r)throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{n||(t=Mt(t));var c=e.path||"",a=c.split("/"),u=t,d=1,f=a.length,h=void 0,p=void 0,g=void 0;for(typeof r=="function"?g=r:g=vl;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=$u(p)),i&&(p=="__proto__"||p=="prototype"&&d>0&&a[d-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&h===void 0&&(u[p]===void 0?h=a.slice(0,d).join("/"):d==f-1&&(h=e.path),h!==void 0&&g(e,0,t,h)),d++,Array.isArray(u)){if(p==="-")p=u.length;else{if(r&&!xl(p))throw new ct("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,t);xl(p)&&(p=~~p)}if(d>=f){if(r&&e.op==="add"&&p>u.length)throw new ct("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,t);var s=mR[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(d>=f){var s=Jc[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new ct("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function Sl(t,e,r,n,i){if(n===void 0&&(n=!0),i===void 0&&(i=!0),r&&!Array.isArray(e))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Mt(t));for(var o=new Array(e.length),s=0,c=e.length;s<c;s++)o[s]=Rs(t,e[s],r,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function wR(t,e,r){var n=Rs(t,e);if(n.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function vl(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ct("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Jc[t.op]){if(typeof t.path!="string")throw new ct("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ct('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ct("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&ml(t.value))throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var i=t.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new ct("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ct("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var s={op:"_get",path:t.from,value:void 0},c=lv([s],r);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new ct("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function lv(t,e,r){try{if(!Array.isArray(t))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Sl(Mt(e),Mt(t),r||!0);else{r=r||vl;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof ct)return i;throw i}}function Vu(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),i,o,s;if(r&&n){if(o=t.length,o!=e.length)return!1;for(i=o;i--!==0;)if(!Vu(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(o=c.length,o!==Object.keys(e).length)return!1;for(i=o;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=o;i--!==0;)if(s=c[i],!Vu(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var S0={};Sf(S0,{compare:()=>_R,generate:()=>x0,observe:()=>TR,unobserve:()=>AR});l();var E0=new WeakMap,bR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),xR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function ER(t){return E0.get(t)}function vR(t,e){return t.observers.get(e)}function SR(t,e){t.observers.delete(e.callback)}function AR(t,e){e.unobserve()}function TR(t,e){var r=[],n,i=ER(t);if(!i)i=new bR(t),E0.set(t,i);else{var o=vR(i,e);n=o&&o.observer}if(n)return n;if(n={},i.value=Mt(t),e){n.callback=e,n.next=null;var s=function(){x0(n)},c=function(){clearTimeout(n.next),n.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return n.patches=r,n.object=t,n.unobserve=function(){x0(n),clearTimeout(n.next),SR(i,n),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new xR(e,n)),n}function x0(t,e){e===void 0&&(e=!1);var r=E0.get(t.object);v0(r.value,t.object,t.patches,"",e),t.patches.length&&Sl(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function v0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=bl(e),s=bl(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(wl(e,d)&&!(e[d]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var h=e[d];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?v0(f,h,r,n+"/"+Gn(d),i):f!==h&&(c=!0,i&&r.push({op:"test",path:n+"/"+Gn(d),value:Mt(f)}),r.push({op:"replace",path:n+"/"+Gn(d),value:Mt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+Gn(d),value:Mt(f)}),r.push({op:"remove",path:n+"/"+Gn(d)}),a=!0):(i&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),c=!0)}if(!(!a&&o.length==s.length))for(var u=0;u<o.length;u++){var d=o[u];!wl(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+Gn(d),value:Mt(e[d])})}}}function _R(t,e,r){r===void 0&&(r=!1);var n=[];return v0(t,e,n,"",r),n}var hv=Object.assign({},b0,S0,{JsonPatchError:Hu,deepClone:Mt,escapePathComponent:Gn,unescapePathComponent:$u});var{applyPatch:IR,compare:BR,deepClone:RR}=hv,UR=new Set(["__proto__","constructor","prototype"]);function pv(t){return t.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")).find(e=>UR.has(e))}var Zc=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??RR,s=i?e:o(e),c=this.validateOperations(r);if(c)throw new we("Invalid JSON Patch operations","JSON_PATCH_APPLY_ERROR",{error:c});try{let a=IR(s,r,!1,i);if(a.newDocument===void 0)throw new we("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{result:a});return a.newDocument}catch(a){throw new we("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{error:a})}}static diff(e,r,n=""){let i=BR(e??{},r??{});if(!n)return i;let o=n.endsWith("/")?n.slice(0,-1):n;return i.map(s=>({...s,path:this.joinPointer(o,s.path)}))}static joinPointer(e,r){if(!e)return r;let n=e.startsWith("/")?e:`/${e}`;return`${this.escapeSegmentPath(n)}${r}`}static escapeSegmentPath(e){return e.split("/").map((r,n)=>n===0?r:r.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}static validateOperations(e){if(!Array.isArray(e))return new we("Operations must be an array","JSON_PATCH_VALIDATION_ERROR");for(let r of e){if(!r||typeof r!="object")return new we("Operation must be an object","JSON_PATCH_VALIDATION_ERROR");if(typeof r.op!="string")return new we("Operation.op must be a string","JSON_PATCH_VALIDATION_ERROR");if(typeof r.path!="string")return new we("Operation.path must be a string","JSON_PATCH_VALIDATION_ERROR");let n=pv(r.path);if(n)return new we(`Operation.path traverses prototype machinery: ${n}`,"JSON_PATCH_VALIDATION_ERROR");if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")return new we(`Operation.from must be a string for op=${r.op}`,"JSON_PATCH_VALIDATION_ERROR");if(typeof r.from=="string"){let i=pv(r.from);if(i)return new we(`Operation.from traverses prototype machinery: ${i}`,"JSON_PATCH_VALIDATION_ERROR")}}return null}};l();var _o;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(_o||(_o={}));var Al;(function(t){t.k="k",t.x="x"})(Al||(Al={}));var qu;(function(t){t[t.bitcoin=0]="bitcoin",t[t.signet=1]="signet",t[t.regtest=2]="regtest",t[t.testnet3=3]="testnet3",t[t.testnet4=4]="testnet4",t[t.mutinynet=5]="mutinynet"})(qu||(qu={}));l();var Io=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new we(`Invalid date: ${e}`,"INVALID_DATE");return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toUnixSeconds(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new we(`Invalid date: ${e}`,"INVALID_DATE");return Math.floor(e.getTime()/1e3)}static dateStringToTimestamp(e){let r=new Date(e);return Number.isNaN(r.getTime())?new Date(0):r}static blocktimeToTimestamp(e){return new Date(e*1e3)}static isValidXsdDateTime(e){if(!e)return!1;let r=/^-?(\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,n=e.match(r);if(!n)return!1;let[,i,o,s,c,a,u,,d]=n,f=parseInt(i,10),h=parseInt(o,10),p=parseInt(s,10),g=parseInt(c,10),y=parseInt(a,10),E=parseInt(u,10);if(f===0||h<1||h>12)return!1;let S=[31,28,31,30,31,30,31,31,30,31,30,31],I=f%4===0&&f%100!==0||f%400===0,A=h===2&&I?29:S[h-1];if(p<1||p>A)return!1;if(g===24){if(y!==0||E!==0)return!1}else if(g>23)return!1;if(y>59||E>59)return!1;if(d&&d!=="Z"){let O=d.match(/^[+-](\d{2}):(\d{2})$/);if(O){let T=parseInt(O[1],10),M=parseInt(O[2],10);if(T>14||T===14&&M!==0||M>59)return!1}}return!0}};l();function A0(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Us=class{static isObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}static isParsable(e){if(typeof e!="string")return!1;try{return JSON.parse(e),!0}catch{return!1}}static isUnprototyped(e){return e===null||typeof e!="object"?!1:Object.getPrototypeOf(e)===null}static normalize(e){return this.cloneInternal(e,{stripPrototypes:!0})}static copy(e){return{...e}}static clone(e){return typeof structuredClone=="function"?structuredClone(e):this.cloneInternal(e)}static cloneReplace(e,r,n){return this.cloneInternal(e,{transform:i=>typeof i=="string"?i.replace(r,n):i})}static deepEqual(e,r,n=new WeakMap,i=0){if(i>1024)throw new we("Maximum comparison depth exceeded","MAX_DEPTH_EXCEEDED");if(Object.is(e,r))return!0;if(typeof e!=typeof r||e===null||r===null||typeof e!="object")return!1;if(n.get(e)===r)return!0;if(n.set(e,r),ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){let c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(c.byteLength!==a.byteLength)return!1;for(let u=0;u<c.byteLength;u++)if(c[u]!==a[u])return!1;return!0}if(e instanceof Date&&r instanceof Date)return e.getTime()===r.getTime();if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(let c of e){let a=!1;for(let u of r)if(this.deepEqual(c,u,n,i+1)){a=!0;break}if(!a)return!1}return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(let[c,a]of e){let u=!1;if(r.has(c))u=this.deepEqual(a,r.get(c),n,i+1);else for(let[d,f]of r)if(this.deepEqual(c,d,n,i+1)&&this.deepEqual(a,f,n,i+1)){u=!0;break}if(!u)return!1}return!0}if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return!1;for(let c=0;c<e.length;c++)if(!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}let o=Object.keys(e),s=Object.keys(r);if(o.length!==s.length)return!1;for(let c of o)if(!Object.prototype.hasOwnProperty.call(r,c)||!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}static deleteKeys(e,r){let n=new Set(r.map(o=>typeof o=="number"?o.toString():o)),i=o=>{if(Array.isArray(o))return o.map(s=>i(s));if(o&&typeof o=="object"){let s={};for(let c of Object.keys(o))n.has(c)||A0(s,c,i(o[c]));return s}return o};return i(e)}static sanitize(e){let r=n=>{if(Array.isArray(n))return n.filter(i=>i!==void 0).map(i=>r(i));if(n&&typeof n=="object"){let i={};for(let[o,s]of Object.entries(n)){let c=r(s);c!==void 0&&A0(i,o,c)}return i}return n};return r(e)}static cloneInternal(e,r={},n=new WeakMap,i=0){if(i>1024)throw new we("Maximum clone depth exceeded","MAX_DEPTH_EXCEEDED");let o=r.transform?r.transform(e):e;if(o!==e||typeof e!="object"||e===null)return o;if(n.has(e))throw new we("Cannot clone circular structure","CIRCULAR_STRUCTURE");if(Array.isArray(e)){let c=[];n.set(e,c);for(let a of e)c.push(this.cloneInternal(a,r,n,i+1));return c}if(ArrayBuffer.isView(e)){if(e instanceof DataView)return new DataView(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(typeof e.slice=="function")return e.slice()}if(e instanceof Date)return new Date(e.getTime());let s=r.stripPrototypes?{}:Object.create(Object.getPrototypeOf(e));n.set(e,s);for(let c of Object.keys(e))A0(s,c,this.cloneInternal(e[c],r,n,i+1));return s}};l();var nr=class extends we{constructor(e,r="BeaconError",n){super(e,r,n)}},yv=class extends we{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},gv=class extends we{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},mv=class extends we{constructor(e,r="CASBeaconError",n){super(e,r,n)}},Fu=class extends we{constructor(e,r="SMTBeaconError",n){super(e,r,n)}};l();l();l();l();l();l();l();l();l();l();l();l();l();l();l();var $R={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Bo(t){switch(t){case"bitcoin":return zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return Zy;case"regtest":return $R;default:throw new Error(`Unknown network "${t}"`)}}l();var ju=class{satsPerVbyte;constructor(e=5){if(e<0||!Number.isFinite(e))throw new Error(`Invalid satsPerVbyte: ${e}`);this.satsPerVbyte=e}async estimateFee(e){if(e<0||!Number.isFinite(e))throw new Error(`Invalid vsize: ${e}`);return BigInt(Math.ceil(e*this.satsPerVbyte))}};l();var _0="0000000000000000000000000000000000000000000000000000000000000000",I0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var B0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(B0||(B0={}));var R0=new ju(5);var qR=160,FR=155,jR=240,WR={p2pkh:jR,p2wpkh:FR,p2tr:qR},bv={p2pkh:34,p2wpkh:31,p2tr:43},xv={p2pkh:546,p2wpkh:294,p2tr:330};function Ev(t,e){return WR[t]-bv[t]+bv[e]}function vv(t,e){let r=Yr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new nr(`Unsupported singleton beacon address type "${r.type}". Expected P2PKH, P2WPKH, or P2TR (taproot key-path).`,"UNSUPPORTED_BEACON_ADDRESS_TYPE",{address:t,kind:r.type})}function GR(t,e,r){return t==="p2pkh"?Di(e,r).address:t==="p2wpkh"?vs(e,r).address:Ss(e.slice(1,33),void 0,r).address}function Sv(t,e,r){if(!r||r===t)return t;try{Yr(e).decode(r)}catch{throw new nr(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function Av(t,e){try{return vv(t,e)}catch{return"p2tr"}}function Tv(t){return Xe.encode(["RETURN",t])}var U0=546;function zR(t){return t.status.confirmed===!0}function YR(t,e){if(t.status.block_height!==e.status.block_height)return t.status.block_height-e.status.block_height;let r=t.txid.localeCompare(e.txid);return r!==0?r:t.vout-e.vout}function JR(t,e){if(!t.length)throw new nr("No UTXOs found, please fund address!","UNFUNDED_BEACON_ADDRESS",{address:e});let r=t.filter(zR),n=r.filter(i=>i.value>U0);if(!n.length){let i=r.length===0?`all ${t.length} UTXO(s) are unconfirmed`:`all ${r.length} confirmed UTXO(s) are at or below the ${U0}-sat dust limit`;throw new nr(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:U0})}return[...n].sort(YR)[0]}async function _v(t,e){let r=await e.rest.address.getUtxos(t),n=JR(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:Tr(i)}}async function L$(t){let e=t.feeEstimator??R0,{utxo:r,prevTxBytes:n}=await _v(t.beaconAddress,t.bitcoin),i=Sv(t.beaconAddress,t.network,t.changeAddress),o=Qe.encode(Yr(t.network).decode(t.beaconAddress)),s=Av(i,t.network),c=await e.estimateFee(Ev("p2tr",s));if(BigInt(r.value)<=c)throw new nr(`UTXO value (${r.value}) insufficient to cover fee (${c}).`,"INSUFFICIENT_FUNDS",{address:t.beaconAddress,valueSats:r.value,feeSats:c});let a=new _s({allowUnknownOutputs:!0});a.addInput({txid:r.txid,index:r.vout,nonWitnessUtxo:n,witnessUtxo:{amount:BigInt(r.value),script:o},tapInternalKey:t.internalPubkey});let u=BigInt(r.value)-c;return u>=BigInt(xv[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:Tv(t.signalBytes),amount:0n}),{tx:a,prevOutScripts:[o],prevOutValues:[BigInt(r.value)],beaconAddress:t.beaconAddress,changeAddress:i,utxo:r,feeSats:c,scriptKind:"p2tr"}}async function ZR(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=vo.ALL,d=t.preimageLegacy(e,i,u),f=n.sign(d,"ecdsa"),h=dt(f,new Uint8Array([u]));return t.updateInput(e,{partialSig:[[s,h]]},!0),t.finalize(),t.hex}if(r==="p2wpkh"){let u=Qe.decode(i);if(u.type!=="wpkh")throw new nr(`Expected P2WPKH prev-output script, got "${u.type}".`,"PREVOUT_SCRIPT_MISMATCH",{kind:r,observedScriptType:u.type});let d=Qe.encode({type:"pkh",hash:u.hash}),f=vo.ALL,h=t.preimageWitnessV0(e,d,f,o),p=n.sign(h,"ecdsa"),g=dt(p,new Uint8Array([f]));return t.updateInput(e,{partialSig:[[s,g]]},!0),t.finalize(),t.hex}let c=t.preimageWitnessV1(e,[i],vo.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Ro=class{service;did;constructor(e,r){this.service=e,this.did=r}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??R0,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await _v(s,n),u=await this.buildSinglePartyTx({signalBytes:e,beaconAddress:s,utxo:c,prevTxBytes:a,signer:r,bitcoin:n,feeEstimator:o,changeAddress:i?.changeAddress}),d=await this.signSinglePartyTx(u,r);return this.broadcastRawTx(n,d)}async buildSinglePartyTx(e){let r=e.bitcoin.data,n=e.signer.publicKey,i=vv(e.beaconAddress,r),o=Sv(e.beaconAddress,r,e.changeAddress),s=GR(i,n,r);if(s!==e.beaconAddress)throw new nr(`Signer pubkey produces ${i.toUpperCase()} address "${s}", but beacon address is "${e.beaconAddress}".`,"SIGNER_KEY_MISMATCH",{kind:i,address:e.beaconAddress,derivedAddress:s});let c=Av(o,r),a=await e.feeEstimator.estimateFee(Ev(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new nr(`UTXO value (${e.utxo.value}) insufficient to cover fee (${a}).`,"INSUFFICIENT_FUNDS",{address:e.beaconAddress,valueSats:e.utxo.value,feeSats:a});let d=new _s({allowUnknownOutputs:!0}),f;if(i==="p2pkh")f=Di(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes});else if(i==="p2wpkh")f=vs(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f}});else{let p=n.slice(1,33);f=Ss(p,void 0,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f},tapInternalKey:p})}let h=u-a;return h>=BigInt(xv[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:Tv(e.signalBytes),amount:0n}),{tx:d,prevOutScripts:[f],prevOutValues:[u],beaconAddress:e.beaconAddress,changeAddress:o,utxo:e.utxo,feeSats:a,scriptKind:i}}async signSinglePartyTx(e,r){return ZR(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var Tl=class extends Ro{constructor(e,r){super({...e,type:"CASBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;for(let s of e){let c=s.signalBytes,a=r.casMap.get(c);if(!a){i.push({kind:"NeedCASAnnouncement",announcementHash:c,beaconServiceId:this.service.id});continue}let u=a[o];if(!u)continue;let d=Jr(Bs(u,"base64urlnopad"),"hex"),f=r.updateMap.get(d);if(!f){i.push({kind:"NeedSignedUpdate",updateHash:d,beaconServiceId:this.service.id});continue}n.push([f,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.did,s=Wn(e),c={[o]:s},a=To(rr(c));i?.casPublish&&await i.casPublish(c);let u=await this.buildSignAndBroadcast(a,r,n,i);return{signedUpdate:e,txid:u,announcement:c}}};l();l();var _l=class extends Ro{constructor(e,r){super({...e,type:"SingletonBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array;for(let o of e){let s=o.signalBytes,c=r.updateMap.get(s);if(!c){i.push({kind:"NeedSignedUpdate",updateHash:s,beaconServiceId:this.service.id});continue}n.push([c,o.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=To(rr(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var XR=new Uint8Array(32),O0=1n<<BigInt(256),Iv=(()=>{let t=new Array(257),e=O0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function Wu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function Se(t,e,r=""){let n=Wu(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function Il(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");zn(t.outputLen),zn(t.blockLen)}function Xc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Rv(t,e){Se(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Os(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Bl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function xn(t,e){return t<<32-e|t>>>e}var Uv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",QR=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ds(t){if(Se(t),Uv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=QR[t[r]];return e}var Ni={_0:48,_9:57,A:65,F:70,a:97,f:102};function Bv(t){if(t>=Ni._0&&t<=Ni._9)return t-Ni._0;if(t>=Ni.A&&t<=Ni.F)return t-(Ni.A-10);if(t>=Ni.a&&t<=Ni.f)return t-(Ni.a-10)}function ks(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Uv)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Bv(t.charCodeAt(o)),c=Bv(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function lr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Se(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}function Ov(t,e={}){let r=(i,o)=>t(o).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}function Ns(t=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(t))}var Dv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var k0=BigInt(0),D0=BigInt(1);function Gu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function kv(t){if(typeof t=="bigint"){if(!Rl(t))throw new Error("positive bigint expected, got "+t)}else zn(t);return t}function zu(t){let e=kv(t).toString(16);return e.length&1?"0"+e:e}function Nv(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?k0:BigInt("0x"+t)}function Uo(t){return Nv(Ds(t))}function N0(t){return Nv(Ds(e6(Se(t)).reverse()))}function Ul(t,e){zn(e),t=kv(t);let r=ks(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function C0(t,e){return Ul(t,e).reverse()}function Qc(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function e6(t){return Uint8Array.from(t)}function Cv(t){return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var Rl=t=>typeof t=="bigint"&&k0<=t;function t6(t,e,r){return Rl(t)&&Rl(e)&&Rl(r)&&e<=t&&t<r}function Lv(t,e,r,n){if(!t6(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function L0(t){let e;for(e=0;t>k0;t>>=D0,e+=1);return e}var Yu=t=>(D0<<BigInt(t))-D0;function Pv(t,e,r){if(zn(t,"hashLen"),zn(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=E=>new Uint8Array(E),i=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),c=1e3,a=n(t),u=n(t),d=0,f=()=>{a.fill(1),u.fill(0),d=0},h=(...E)=>r(u,lr(a,...E)),p=(E=i)=>{u=h(o,E),a=h(),E.length!==0&&(u=h(s,E),a=h())},g=()=>{if(d++>=c)throw new Error("drbg: tried max amount of iterations");let E=0,S=[];for(;E<e;){a=h();let I=a.slice();S.push(I),E+=a.length}return lr(...S)};return(E,S)=>{f(),p(E);let I;for(;!(I=S(g()));)p();return f(),I}}function Ju(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,c){let a=t[o];if(c&&a===void 0)return;let u=typeof a;if(u!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${u}`)}let i=(o,s)=>Object.entries(o).forEach(([c,a])=>n(c,a,s));i(e,!1),i(r,!0)}function P0(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}function M0(t){return t.length===32}function Ol(t){if(!M0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function ft(...t){return ke(dt(...t))}function Zu(t){Ol(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function K0(t){let e=new Uint8Array(32),r=t;for(let n=31;n>=0;n--)e[n]=Number(r&0xffn),r>>=8n;if(r!==0n)throw new RangeError("Value exceeds 256 bits");return e}function $0(t){Ol(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function H0(t,e){return!M0(t)||!M0(e)?!1:Qc(t,e)}function ea(t){return Ol(t),$c.encode(t)}function Yn(t){let e=$c.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var Mv;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(Mv||(Mv={}));l();l();var Oo=256;function ta(t,e){return Number(t>>BigInt(e)&1n)}var Kv=(()=>{let t=new Array(Oo+1),e=new Uint8Array(32);for(let r=0;r<=Oo;r++)e=ft(e,e),t[r]=e;return t})();function Dl(t,e){if(t.length===0)return Kv[e];if(e===0)return t[0].leaf;let r=Oo-e,n=[],i=[];for(let o of t)(ta(o.index,r)===0?n:i).push(o);return ft(Dl(n,e-1),Dl(i,e-1))}function $v(t){return Dl(t,Oo)}function Hv(t,e){let r=0n,n=[];for(let i=1;i<=Oo;i++){let o=Oo-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(ta(c.index,u)!==ta(e,u)){a=!1;break}a&&ta(c.index,o)!==ta(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(Dl(s,i-1))}return{collapsed:r,hashes:n}}function Vv(t,e,r,n,i){let o=n,s=0;for(let c=0;c<Oo;c++){let a=Oo-1-c,u;if((t>>BigInt(a)&1n)===1n)u=Kv[c];else{if(s>=e.length)return!1;u=e[s++]}o=ta(r,a)===1?ft(u,o):ft(o,u)}return s===e.length&&H0(o,i)}l();var r6=new TextEncoder;function kl(t){return Zu(ft(r6.encode(t)))}function qv(t,e){return ft(ft(t),ft(e))}function Fv(t){return ft(ft(t))}l();function jv(t,e,r){let n={id:ea(t),collapsed:ea(K0(e.collapsed)),hashes:e.hashes.map(i=>ea(i))};return r?.nonce&&(n.nonce=ea(r.nonce)),r?.updateId&&(n.updateId=ea(r.updateId)),n}function n6(t){let e={rootHash:Yn(t.id),collapsed:Zu(Yn(t.collapsed)),hashes:t.hashes.map(r=>Yn(r))};return t.nonce&&(e.nonce=Yn(t.nonce)),t.updateId&&(e.updateId=Yn(t.updateId)),e}function Wv(t,e,r){let{rootHash:n,collapsed:i,hashes:o}=n6(t);return Vv(i,o,e,r,n)}l();var Nl=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=kl(r.did);if(this.#e.has(n))throw new RangeError(`Duplicate DID index for: ${r.did}`);this.#e.set(n,r),this.#t.set(r.did,n)}this.#n=null,this.#r=null}finalize(){let e=[];for(let[r,n]of this.#e){let i=n.signedUpdate!==void 0?qv(n.nonce,n.signedUpdate):Fv(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=$v(e)}get rootHash(){if(this.#r===null)throw new Error("Tree not finalized: call finalize() first");return this.#r}proof(e){let r=this.#t.get(e);if(r===void 0)throw new RangeError(`DID not in tree: ${e}`);if(this.#n===null||this.#r===null)throw new Error("Tree not finalized: call finalize() first");let n=this.#e.get(r),i=Hv(this.#n,r),o=n.signedUpdate!==void 0?ft(n.signedUpdate):void 0;return jv(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var Cl=class extends Ro{constructor(e,r){super({...e,type:"SMTBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;for(let s of e){let c=r.smtMap.get(s.signalBytes);if(!c){i.push({kind:"NeedSMTProof",smtRootHash:s.signalBytes,beaconServiceId:this.service.id});continue}if(!c.nonce)throw new Fu("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=kl(o),u=Yn(c.nonce),d=c.updateId?ft(ft(u),Yn(c.updateId)):ft(ft(u));if(!Wv(c,a,d))throw new Fu("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=$0(Yn(c.updateId)),p=r.updateMap.get(h);if(!p){i.push({kind:"NeedSignedUpdate",updateHash:h,beaconServiceId:this.service.id});continue}n.push([p,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.did,s=new TextEncoder().encode(rr(e)),c=_r(32),a=new Nl;a.addEntries([{did:o,nonce:c,signedUpdate:s}]),a.finalize();let u=a.proof(o),d=await this.buildSignAndBroadcast(a.rootHash,r,n,i);return{signedUpdate:e,txid:d,proof:u}}};var ra=class{static establish(e,r){switch(e.type){case"SingletonBeacon":return new _l(e,r);case"CASBeacon":return new Tl(e,r);case"SMTBeacon":return new Cl(e,r);default:throw new we("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Li;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Li||(Li={}));l();var lt={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};l();var me=class t{constructor({method:e,id:r,path:n,query:i,fragment:o,params:s}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=i,this.fragment=o,this.params=s}static parse(e){if(!e)return null;let r=t.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:i,path:o,query:s,fragment:c}=r.groups,a={uri:`did:${n}:${i}`,method:n,id:i};if(o&&(a.path=o),s&&(a.query=s.slice(1)),c&&(a.fragment=c.slice(1)),s){let u={},d=s.slice(1).split("&");for(let f of d){let[h,p]=f.split("=");u[h]=p}a.params=u}return a}};me.METHOD_PATTERN="([a-z0-9]+)";me.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})";me.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${me.PCT_ENCODED_PATTERN})`;me.METHOD_ID_PATTERN=`((?:${me.ID_CHAR_PATTERN}*:)*(${me.ID_CHAR_PATTERN}+))`;me.PATH_PATTERN="(/[^#?]*)?";me.QUERY_PATTERN="([?][^#]*)?";me.FRAGMENT_PATTERN="(#.*)?";me.DID_URI_PATTERN=new RegExp(`^did:(?<method>${me.METHOD_PATTERN}):(?<id>${me.METHOD_ID_PATTERN})(?<path>${me.PATH_PATTERN})(?<query>${me.QUERY_PATTERN})(?<fragment>${me.FRAGMENT_PATTERN})$`);l();var re=class t extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,t)}},ie;(function(t){t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType"})(ie||(ie={}));l();l();l();l();l();var s6=Pn(zv(),1);l();l();l();l();var DH=new Uint8Array(0);function Yv(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function na(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function a6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,E=0,S=0,I=g.length;S!==I&&g[S]===0;)S++,y++;for(var A=(I-S)*d+1>>>0,O=new Uint8Array(A);S!==I;){for(var T=g[S],M=0,q=A-1;(T!==0||M<E)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");E=M,S++}for(var j=A-E;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var E=0,S=0;g[y]===a;)E++,y++;for(var I=(g.length-y)*u+1>>>0,A=new Uint8Array(I);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=I-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=I-S;q!==I&&A[q]===0;)q++;for(var j=new Uint8Array(E+(I-q)),$=E;q!==I;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var u6=a6,d6=u6,Jv=d6;var j0=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},W0=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),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 Zv(this,e)}},G0=class{decoders;constructor(e){this.decoders=e}or(e){return Zv(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 Zv(t,e){return new G0({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var z0=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new j0(e,r,n),this.decoder=new W0(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Xv({name:t,prefix:e,encode:r,decode:n}){return new z0(t,e,r,n)}function Y0({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=Jv(r,t);return Xv({prefix:e,name:t,encode:n,decode:o=>na(i(o))})}function f6(t,e,r,n){let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s}function l6(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s!==0&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o}function ir({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return Xv({prefix:e,name:t,encode(i){return l6(i,n,r)},decode(i){return f6(i,n,r,t)}})}var Xu=ir({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),HH=ir({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),VH=ir({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qH=ir({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),FH=ir({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),jH=ir({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),WH=ir({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),GH=ir({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),J0=ir({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var hr=Y0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ZH=Y0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var tV=ir({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rV=ir({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Jn=ir({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),nV=ir({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function Qv(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function e1(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function ia(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var Qu=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},t1=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(s){return new Promise(function(c,a){s=t[o](s),i(c,a,s.done,s.value)})}}function i(o,s,c,a){Promise.resolve(a).then(function(u){o({value:u,done:c})},s)}},Pl=new TextEncoder,Cs=new TextDecoder,ne=class t{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new t(e,"ArrayBuffer")}static asyncIterable(e){if(!e1(e))throw new TypeError("Input must be of type AsyncIterable.");return new t(e,"AsyncIterable")}static base32Z(e){return new t(e,"Base32Z")}static base58Btc(e){return new t(e,"Base58Btc")}static base64Url(e){return new t(e,"Base64Url")}static bufferSource(e){return new t(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new t(e,"Hex")}static multibase(e){return new t(e,"Multibase")}static object(e){return new t(e,"Object")}static string(e){return new t(e,"String")}static uint8Array(e){return new t(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return hr.baseDecode(this.data).buffer;case"Base64Url":return Jn.baseDecode(this.data).buffer;case"BufferSource":{if(ia(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Qv(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return J0.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return hr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return hr.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Jn.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Jn.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=Pl.encode(e);return Jn.baseEncode(r)}case"String":{let e=Pl.encode(this.data);return Jn.baseEncode(e)}case"Uint8Array":return Jn.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=t1(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let d=i;a.push(d)}}catch(d){r={error:d}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return new Blob(a)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=Jn.baseDecode(this.data),r=Cs.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Cs.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return Cs.decode(this.data);case"Base64Url":{let e=Jn.baseDecode(this.data);return Cs.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Cs.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=t1(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let u=i;typeof u=="string"?a+=u:a+=Cs.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return a+=Cs.decode(void 0,{stream:!1}),a}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return J0.baseDecode(this.data);case"Base58Btc":return hr.baseDecode(this.data);case"Base64Url":return Jn.baseDecode(this.data);case"BufferSource":{let e=ia(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return Pl.encode(e)}case"String":return Pl.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};l();var ed;(function(t){t.Debug="debug",t.Silent="silent"})(ed||(ed={}));var Z0=class{constructor(){this.logLevel=ed.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==ed.Silent&&console.info(e)}error(e){this.logLevel!==ed.Silent&&console.error(e)}},h6=new Z0;typeof window<"u"&&(window.web5logger=h6);l();l();l();l();var Pi={};Sf(Pi,{decode:()=>oa,encodeTo:()=>Ls,encodingLength:()=>Ps});l();l();var p6=i1,r1=128,y6=127,g6=~y6,m6=Math.pow(2,31);function i1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=m6;)e[r++]=t&255|r1,t/=128;for(;t&g6;)e[r++]=t&255|r1,t>>>=7;return e[r]=t|0,i1.bytes=r-n+1,e}var w6=X0,b6=128,n1=127;function X0(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw X0.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&n1)<<i:(s&n1)*Math.pow(2,i),i+=7}while(s>=b6);return X0.bytes=o-n,r}var x6=Math.pow(2,7),E6=Math.pow(2,14),v6=Math.pow(2,21),S6=Math.pow(2,28),A6=Math.pow(2,35),T6=Math.pow(2,42),_6=Math.pow(2,49),I6=Math.pow(2,56),B6=Math.pow(2,63),R6=function(t){return t<x6?1:t<E6?2:t<v6?3:t<S6?4:t<A6?5:t<T6?6:t<_6?7:t<I6?8:t<B6?9:10},U6={encode:p6,decode:w6,encodingLength:R6},O6=U6,td=O6;function oa(t,e=0){return[td.decode(t,e),td.decode.bytes]}function Ls(t,e,r=0){return td.encode(t,e,r),e}function Ps(t){return td.encodingLength(t)}function Q0(t,e){let r=e.byteLength,n=Ps(t),i=n+Ps(r),o=new Uint8Array(i+r);return Ls(t,o,0),Ls(r,o,n),o.set(e,i),new sa(t,r,e,o)}function o1(t){let e=na(t),[r,n]=oa(e),[i,o]=oa(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new sa(r,i,s,e)}function s1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Yv(t.bytes,r.bytes)}}var sa=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function c1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return k6(r,tg(t),e??hr.encoder);default:return N6(r,tg(t),e??Xu.encoder)}}var a1=new WeakMap;function tg(t){let e=a1.get(t);if(e==null){let r=new Map;return a1.set(t,r),r}return e}var rg=class t{code;version;multihash;bytes;"/";constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==rd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==C6)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Q0(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&s1(e.multihash,n.multihash)}toString(e){return c1(this,e)}toJSON(){return{"/":c1(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 r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new t(n,i,o,s??u1(n,i,o.bytes))}else if(r[L6]===!0){let{version:n,multihash:i,code:o}=r,s=o1(i);return t.create(n,o,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==rd)throw new Error(`Version 0 CID must use dag-pb (code: ${rd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=u1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,rd,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=na(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new sa(r.multihashCode,r.digestSize,o,i);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=oa(e.subarray(r));return r+=h,f},i=n(),o=rd;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,c=n(),a=n(),u=r+a,d=u-s;return{version:i,codec:o,multihashCode:c,digestSize:a,multihashSize:d,size:u}}static parse(e,r){let[n,i]=D6(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return tg(o).set(n,e),o}};function D6(t,e){switch(t[0]){case"Q":{let r=e??hr;return[hr.prefix,r.decode(`${hr.prefix}${t}`)]}case hr.prefix:{let r=e??hr;return[hr.prefix,r.decode(t)]}case Xu.prefix:{let r=e??Xu;return[Xu.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function k6(t,e,r){let{prefix:n}=r;if(n!==hr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return i}function N6(t,e,r){let{prefix:n}=r,i=e.get(n);if(i==null){let o=r.encode(t);return e.set(n,o),o}else return i}var rd=112,C6=18;function u1(t,e,r){let n=Ps(t),i=n+Ps(e),o=new Uint8Array(i+r.byteLength);return Ls(t,o,0),Ls(e,o,n),o.set(r,i),o}var L6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var Yt=class t{static addPrefix(e){var r;let{code:n,data:i,name:o}=e;if(!(o?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=t.codeToName.has(n)?n:t.nameToCode.get(o),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let s=Pi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Pi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Pi.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=t.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=t.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){t.codeToName.set(e.code,e.name),t.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,i]=Pi.decode(r),o=t.codeToName.get(n);if(o===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(i),name:o}}};Yt.codeToName=new Map;Yt.nameToCode=new Map;Yt.registerCodec({code:237,name:"ed25519-pub"});Yt.registerCodec({code:4864,name:"ed25519-priv"});Yt.registerCodec({code:236,name:"x25519-pub"});Yt.registerCodec({code:4866,name:"x25519-priv"});Yt.registerCodec({code:231,name:"secp256k1-pub"});Yt.registerCodec({code:4865,name:"secp256k1-priv"});l();function ng(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&ng(t[e])})}l();var qU=Pn(Yg(),1),Xs=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})};var fh=class{constructor(){this.store=new Map}clear(){return Xs(this,void 0,void 0,function*(){this.store.clear()})}close(){return Xs(this,void 0,void 0,function*(){})}delete(e){return Xs(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return Xs(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return Xs(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return Xs(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return Xs(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var sk=Pn(cw(),1);var ck=Pn(cw(),1);l();l();l();l();l();function ak(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function aw(t,...e){if(!ak(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function uw(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function gT(t,e){aw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Da=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Fh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),_n=(t,e)=>t<<32-e|t>>>e;var Rj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function uk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function dw(t){return typeof t=="string"&&(t=uk(t)),aw(t),t}var qh=class{clone(){return this._cloneInto()}},Uj={}.toString;function mT(t){let e=n=>t().update(dw(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function wT(t=32){if(Da&&typeof Da.getRandomValues=="function")return Da.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function dk(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var bT=(t,e,r)=>t&e^~t&r,xT=(t,e,r)=>t&e^t&r^e&r,jh=class extends qh{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Fh(this.buffer)}update(e){uw(this);let{view:r,buffer:n,blockLen:i}=this;e=dw(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Fh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){uw(this),gT(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;dk(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Fh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var fk=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Fo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jo=new Uint32Array(64),fw=class extends jh{constructor(){super(64,32,8,!1),this.A=Fo[0]|0,this.B=Fo[1]|0,this.C=Fo[2]|0,this.D=Fo[3]|0,this.E=Fo[4]|0,this.F=Fo[5]|0,this.G=Fo[6]|0,this.H=Fo[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)jo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=jo[f-15],p=jo[f-2],g=_n(h,7)^_n(h,18)^h>>>3,y=_n(p,17)^_n(p,19)^p>>>10;jo[f]=y+jo[f-7]+g+jo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=_n(c,6)^_n(c,11)^_n(c,25),p=d+h+bT(c,a,u)+fk[f]+jo[f]|0,y=(_n(n,2)^_n(n,13)^_n(n,22))+xT(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){jo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Wo=mT(()=>new fw);var lk=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},ka=class{static digest(e){return lk(this,arguments,void 0,function*({data:r}){return Wo(r)})}};l();var si=class{};var hk=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Wh=class extends si{digest(e){return hk(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield ka.digest({data:n})}})}};l();l();l();l();l();l();function ET(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function pk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function lw(t,...e){if(!pk(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function vT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ET(t.outputLen),ET(t.blockLen)}function Na(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ST(t,e){lw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Gh=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function AT(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var zh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),In=(t,e)=>t<<32-e|t>>>e,yk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!yk)throw new Error("Non little-endian hardware is not supported");function hw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Cd(t){if(typeof t=="string"&&(t=hw(t)),!AT(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function Yh(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!AT(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Ca=class{clone(){return this._cloneInto()}},tW={}.toString;function Jh(t){let e=n=>t().update(Cd(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ld(t=32){if(Gh&&typeof Gh.getRandomValues=="function")return Gh.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function gk(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var La=class extends Ca{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=zh(this.buffer)}update(e){Na(this);let{view:r,buffer:n,blockLen:i}=this;e=Cd(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=zh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Na(this),ST(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;gk(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=zh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var mk=(t,e,r)=>t&e^~t&r,wk=(t,e,r)=>t&e^t&r^e&r,bk=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Go=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zo=new Uint32Array(64),pw=class extends La{constructor(){super(64,32,8,!1),this.A=Go[0]|0,this.B=Go[1]|0,this.C=Go[2]|0,this.D=Go[3]|0,this.E=Go[4]|0,this.F=Go[5]|0,this.G=Go[6]|0,this.H=Go[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)zo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=zo[f-15],p=zo[f-2],g=In(h,7)^In(h,18)^h>>>3,y=In(p,17)^In(p,19)^p>>>10;zo[f]=y+zo[f-7]+g+zo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=In(c,6)^In(c,11)^In(c,25),p=d+h+mk(c,a,u)+bk[f]+zo[f]|0,y=(In(n,2)^In(n,13)^In(n,22))+wk(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){zo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Zh=Jh(()=>new pw);l();var Qh={};Sf(Qh,{bitGet:()=>_k,bitLen:()=>Tk,bitMask:()=>Pd,bitSet:()=>Ik,bytesToHex:()=>Ji,bytesToNumberBE:()=>Zi,bytesToNumberLE:()=>Rn,concatBytes:()=>Qi,createHmacDrbg:()=>mw,ensureBytes:()=>Ge,equalBytes:()=>Sk,hexToBytes:()=>dc,hexToNumber:()=>gw,isBytes:()=>Bn,numberToBytesBE:()=>yr,numberToBytesLE:()=>Xi,numberToHexUnpadded:()=>BT,numberToVarBytesBE:()=>vk,utf8ToBytes:()=>Ak,validateObject:()=>tn});l();var IT=BigInt(0),Xh=BigInt(1),xk=BigInt(2);function Bn(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Ek=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ji(t){if(!Bn(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=Ek[t[r]];return e}function BT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function gw(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Yi={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function TT(t){if(t>=Yi._0&&t<=Yi._9)return t-Yi._0;if(t>=Yi._A&&t<=Yi._F)return t-(Yi._A-10);if(t>=Yi._a&&t<=Yi._f)return t-(Yi._a-10)}function dc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=TT(t.charCodeAt(o)),c=TT(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function Zi(t){return gw(Ji(t))}function Rn(t){if(!Bn(t))throw new Error("Uint8Array expected");return gw(Ji(Uint8Array.from(t).reverse()))}function yr(t,e){return dc(t.toString(16).padStart(e*2,"0"))}function Xi(t,e){return yr(t,e).reverse()}function vk(t){return dc(BT(t))}function Ge(t,e,r){let n;if(typeof e=="string")try{n=dc(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(Bn(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function Qi(...t){let e=0;for(let i=0;i<t.length;i++){let o=t[i];if(!Bn(o))throw new Error("Uint8Array expected");e+=o.length}let r=new Uint8Array(e),n=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,n),n+=o.length}return r}function Sk(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function Ak(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Tk(t){let e;for(e=0;t>IT;t>>=Xh,e+=1);return e}function _k(t,e){return t>>BigInt(e)&Xh}var Ik=(t,e,r)=>t|(r?Xh:IT)<<BigInt(e),Pd=t=>(xk<<BigInt(t-1))-Xh,yw=t=>new Uint8Array(t),_T=t=>Uint8Array.from(t);function mw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=yw(t),i=yw(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=yw())=>{i=c(_T([0]),f),n=c(),f.length!==0&&(i=c(_T([1]),f),n=c())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){n=c();let p=n.slice();h.push(p),f+=n.length}return Qi(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var Bk={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Bn(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function tn(t,e,r={}){let n=(i,o,s)=>{let c=Bk[o];if(typeof c!="function")throw new Error(`Invalid validator "${o}", expected function`);let a=t[i];if(!(s&&a===void 0)&&!c(a,t))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${o}`)};for(let[i,o]of Object.entries(e))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return t}var _t=BigInt(0),et=BigInt(1),fc=BigInt(2),Rk=BigInt(3),ww=BigInt(4),RT=BigInt(5),UT=BigInt(8),Uk=BigInt(9),Ok=BigInt(16);function Be(t,e){let r=t%e;return r>=_t?r:e+r}function bw(t,e,r){if(r<=_t||e<_t)throw new Error("Expected power/modulo > 0");if(r===et)return _t;let n=et;for(;e>_t;)e&et&&(n=n*t%r),t=t*t%r,e>>=et;return n}function ze(t,e,r){let n=t;for(;e-- >_t;)n*=n,n%=r;return n}function ep(t,e){if(t===_t||e<=_t)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Be(t,e),n=e,i=_t,o=et,s=et,c=_t;for(;r!==_t;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==et)throw new Error("invert: does not exist");return Be(i,e)}function Dk(t){let e=(t-et)/fc,r,n,i;for(r=t-et,n=0;r%fc===_t;r/=fc,n++);for(i=fc;i<t&&bw(i,e,t)!==t-et;i++);if(n===1){let s=(t+et)/ww;return function(a,u){let d=a.pow(u,s);if(!a.eql(a.sqr(d),u))throw new Error("Cannot find square root");return d}}let o=(r+et)/fc;return function(c,a){if(c.pow(a,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let u=n,d=c.pow(c.mul(c.ONE,i),r),f=c.pow(a,o),h=c.pow(a,r);for(;!c.eql(h,c.ONE);){if(c.eql(h,c.ZERO))return c.ZERO;let p=1;for(let y=c.sqr(h);p<u&&!c.eql(y,c.ONE);p++)y=c.sqr(y);let g=c.pow(d,et<<BigInt(u-p-1));d=c.sqr(g),f=c.mul(f,g),h=c.mul(h,d),u=p}return f}}function kk(t){if(t%ww===Rk){let e=(t+et)/ww;return function(n,i){let o=n.pow(i,e);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(t%UT===RT){let e=(t-RT)/UT;return function(n,i){let o=n.mul(i,fc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,fc),s),u=n.mul(c,n.sub(a,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return t%Ok,Dk(t)}var OT=(t,e)=>(Be(t,e)&et)===et,Nk=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xw(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Nk.reduce((n,i)=>(n[i]="function",n),e);return tn(t,r)}function Ck(t,e,r){if(r<_t)throw new Error("Expected power > 0");if(r===_t)return t.ONE;if(r===et)return e;let n=t.ONE,i=e;for(;r>_t;)r&et&&(n=t.mul(n,i)),i=t.sqr(i),r>>=et;return n}function Lk(t,e){let r=new Array(e.length),n=e.reduce((o,s,c)=>t.is0(s)?o:(r[c]=o,t.mul(o,s)),t.ONE),i=t.inv(n);return e.reduceRight((o,s,c)=>t.is0(s)?o:(r[c]=t.mul(o,r[c]),t.mul(o,s)),i),r}function Ew(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Pa(t,e,r=!1,n={}){if(t<=_t)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=Ew(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=kk(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Pd(i),ZERO:_t,ONE:et,create:a=>Be(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return _t<=a&&a<t},is0:a=>a===_t,isOdd:a=>(a&et)===et,neg:a=>Be(-a,t),eql:(a,u)=>a===u,sqr:a=>Be(a*a,t),add:(a,u)=>Be(a+u,t),sub:(a,u)=>Be(a-u,t),mul:(a,u)=>Be(a*u,t),pow:(a,u)=>Ck(c,a,u),div:(a,u)=>Be(a*ep(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>ep(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>Lk(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?Xi(a,o):yr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?Rn(a):Zi(a)}});return Object.freeze(c)}function DT(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function kT(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function vw(t){let e=kT(t);return e+Math.ceil(e/2)}function NT(t,e,r=!1){let n=t.length,i=kT(e),o=vw(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?Zi(t):Rn(t),c=Be(s,e-et)+et;return r?Xi(c,i):yr(c,i)}l();l();var Mk=BigInt(0),Sw=BigInt(1);function tp(t,e){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(e/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=t.ZERO,c=i;for(;o>Mk;)o&Sw&&(s=s.add(c)),c=c.double(),o>>=Sw;return s},precomputeWindow(i,o){let{windows:s,windowSize:c}=n(o),a=[],u=i,d=u;for(let f=0;f<s;f++){d=u,a.push(d);for(let h=1;h<c;h++)d=d.add(u),a.push(d);u=d.double()}return a},wNAF(i,o,s){let{windows:c,windowSize:a}=n(i),u=t.ZERO,d=t.BASE,f=BigInt(2**i-1),h=2**i,p=BigInt(i);for(let g=0;g<c;g++){let y=g*a,E=Number(s&f);s>>=p,E>a&&(E-=h,s+=Sw);let S=y,I=y+Math.abs(E)-1,A=g%2!==0,O=E<0;E===0?d=d.add(r(A,o[S])):u=u.add(r(O,o[I]))}return{p:u,f:d}},wNAFCached(i,o,s,c){let a=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,a),a!==1&&o.set(i,c(u))),this.wNAF(a,u,s)}}}function Md(t){return xw(t.Fp),tn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ew(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Kk(t){let e=Md(t);tn(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:$k,hexToBytes:Hk}=Qh,lc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=lc;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:$k(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=lc,r=typeof t=="string"?Hk(t):t;if(!Bn(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:o}=lc._parseInt(r.subarray(2)),{d:s,l:c}=lc._parseInt(o);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),i=e(r(t.r)),o=n.length/2,s=i.length/2,c=r(o),a=r(s);return`30${r(s+o+4)}02${a}${i}02${c}${n}`}},eo=BigInt(0),rn=BigInt(1),vW=BigInt(2),CT=BigInt(3),SW=BigInt(4);function Vk(t){let e=Kk(t),{Fp:r}=e,n=e.toBytes||((g,y,E)=>{let S=y.toAffine();return Qi(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),i=e.fromBytes||(g=>{let y=g.subarray(1),E=r.fromBytes(y.subarray(0,r.BYTES)),S=r.fromBytes(y.subarray(r.BYTES,2*r.BYTES));return{x:E,y:S}});function o(g){let{a:y,b:E}=e,S=r.sqr(g),I=r.mul(S,g);return r.add(r.add(I,r.mul(g,y)),E)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function s(g){return typeof g=="bigint"&&eo<g&&g<e.n}function c(g){if(!s(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){let{allowedPrivateKeyLengths:y,nByteLength:E,wrapPrivateKey:S,n:I}=e;if(y&&typeof g!="bigint"){if(Bn(g)&&(g=Ji(g)),typeof g!="string"||!y.includes(g.length))throw new Error("Invalid key");g=g.padStart(E*2,"0")}let A;try{A=typeof g=="bigint"?g:Zi(Ge("private key",g,E))}catch{throw new Error(`private key must be ${E} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=Be(A,I)),c(A),A}let u=new Map;function d(g){if(!(g instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(y,E,S){if(this.px=y,this.py=E,this.pz=S,y==null||!r.isValid(y))throw new Error("x required");if(E==null||!r.isValid(E))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(y){let{x:E,y:S}=y||{};if(!y||!r.isValid(E)||!r.isValid(S))throw new Error("invalid affine point");if(y instanceof f)throw new Error("projective point not allowed");let I=A=>r.eql(A,r.ZERO);return I(E)&&I(S)?f.ZERO:new f(E,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let E=r.invertBatch(y.map(S=>S.pz));return y.map((S,I)=>S.toAffine(E[I])).map(f.fromAffine)}static fromHex(y){let E=f.fromAffine(i(Ge("pointHex",y)));return E.assertValidity(),E}static fromPrivateKey(y){return f.BASE.multiply(a(y))}_setWindowSize(y){this._WINDOW_SIZE=y,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:y,y:E}=this.toAffine();if(!r.isValid(y)||!r.isValid(E))throw new Error("bad point: x or y not FE");let S=r.sqr(E),I=o(y);if(!r.eql(S,I))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y}=this.toAffine();if(r.isOdd)return!r.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){d(y);let{px:E,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(E,T),r.mul(A,I)),q=r.eql(r.mul(S,T),r.mul(O,I));return M&&q}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:y,b:E}=e,S=r.mul(E,CT),{px:I,py:A,pz:O}=this,T=r.ZERO,M=r.ZERO,q=r.ZERO,j=r.mul(I,I),$=r.mul(A,A),X=r.mul(O,O),Q=r.mul(I,A);return Q=r.add(Q,Q),q=r.mul(I,O),q=r.add(q,q),T=r.mul(y,q),M=r.mul(S,X),M=r.add(T,M),T=r.sub($,M),M=r.add($,M),M=r.mul(T,M),T=r.mul(Q,T),q=r.mul(S,q),X=r.mul(y,X),Q=r.sub(j,X),Q=r.mul(y,Q),Q=r.add(Q,q),q=r.add(j,j),j=r.add(q,j),j=r.add(j,X),j=r.mul(j,Q),M=r.add(M,j),X=r.mul(A,O),X=r.add(X,X),j=r.mul(X,Q),T=r.sub(T,j),q=r.mul(X,$),q=r.add(q,q),q=r.add(q,q),new f(T,M,q)}add(y){d(y);let{px:E,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,X=r.mul(e.b,CT),Q=r.mul(E,A),G=r.mul(S,O),_=r.mul(I,T),D=r.add(E,S),x=r.add(A,O);D=r.mul(D,x),x=r.add(Q,G),D=r.sub(D,x),x=r.add(E,I);let U=r.add(A,T);return x=r.mul(x,U),U=r.add(Q,_),x=r.sub(x,U),U=r.add(S,I),M=r.add(O,T),U=r.mul(U,M),M=r.add(G,_),U=r.sub(U,M),j=r.mul($,x),M=r.mul(X,_),j=r.add(M,j),M=r.sub(G,j),j=r.add(G,j),q=r.mul(M,j),G=r.add(Q,Q),G=r.add(G,Q),_=r.mul($,_),x=r.mul(X,x),G=r.add(G,_),_=r.sub(Q,_),_=r.mul($,_),x=r.add(x,_),Q=r.mul(G,x),q=r.add(q,Q),Q=r.mul(U,x),M=r.mul(D,M),M=r.sub(M,Q),Q=r.mul(D,G),j=r.mul(U,j),j=r.add(j,Q),new f(M,q,j)}subtract(y){return this.add(y.negate())}is0(){return this.equals(f.ZERO)}wNAF(y){return p.wNAFCached(this,u,y,E=>{let S=r.invertBatch(E.map(I=>I.pz));return E.map((I,A)=>I.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let E=f.ZERO;if(y===eo)return E;if(c(y),y===rn)return this;let{endo:S}=e;if(!S)return p.unsafeLadder(this,y);let{k1neg:I,k1:A,k2neg:O,k2:T}=S.splitScalar(y),M=E,q=E,j=this;for(;A>eo||T>eo;)A&rn&&(M=M.add(j)),T&rn&&(q=q.add(j)),j=j.double(),A>>=rn,T>>=rn;return I&&(M=M.negate()),O&&(q=q.negate()),q=new f(r.mul(q.px,S.beta),q.py,q.pz),M.add(q)}multiply(y){c(y);let E=y,S,I,{endo:A}=e;if(A){let{k1neg:O,k1:T,k2neg:M,k2:q}=A.splitScalar(E),{p:j,f:$}=this.wNAF(T),{p:X,f:Q}=this.wNAF(q);j=p.constTimeNegate(O,j),X=p.constTimeNegate(M,X),X=new f(r.mul(X.px,A.beta),X.py,X.pz),S=j.add(X),I=$.add(Q)}else{let{p:O,f:T}=this.wNAF(E);S=O,I=T}return f.normalizeZ([S,I])[0]}multiplyAndAddUnsafe(y,E,S){let I=f.BASE,A=(T,M)=>M===eo||M===rn||!T.equals(I)?T.multiplyUnsafe(M):T.multiply(M),O=A(this,E).add(A(y,S));return O.is0()?void 0:O}toAffine(y){let{px:E,py:S,pz:I}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(I));let O=r.mul(E,y),T=r.mul(S,y),M=r.mul(I,y);if(A)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:O,y:T}}isTorsionFree(){let{h:y,isTorsionFree:E}=e;if(y===rn)return!0;if(E)return E(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:E}=e;return y===rn?this:E?E(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return Ji(this.toRawBytes(y))}}f.BASE=new f(e.Gx,e.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);let h=e.nBitLength,p=tp(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function qk(t){let e=Md(t);return tn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function LT(t){let e=qk(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(x){return eo<x&&x<r.ORDER}function c(x){return Be(x,n)}function a(x){return ep(x,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=Vk({...e,toBytes(x,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=Qi;return L?C(Uint8Array.from([U.hasEvenY()?2:3]),R):C(Uint8Array.from([4]),R,r.toBytes(N.y))},fromBytes(x){let U=x.length,L=x[0],N=x.subarray(1);if(U===i&&(L===2||L===3)){let R=Zi(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&rn)===rn;return(L&1)===1!==V&&(P=r.neg(P)),{x:R,y:P}}else if(U===o&&L===4){let R=r.fromBytes(N.subarray(0,r.BYTES)),C=r.fromBytes(N.subarray(r.BYTES,2*r.BYTES));return{x:R,y:C}}else throw new Error(`Point of length ${U} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=x=>Ji(yr(x,e.nByteLength));function g(x){let U=n>>rn;return x>U}function y(x){return g(x)?c(-x):x}let E=(x,U,L)=>Zi(x.slice(U,L));class S{constructor(U,L,N){this.r=U,this.s=L,this.recovery=N,this.assertValidity()}static fromCompact(U){let L=e.nByteLength;return U=Ge("compactSignature",U,L*2),new S(E(U,0,L),E(U,L,2*L))}static fromDER(U){let{r:L,s:N}=lc.toSig(Ge("DER",U));return new S(L,N)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(U){return new S(this.r,this.s,U)}recoverPublicKey(U){let{r:L,s:N,recovery:R}=this,C=q(Ge("msgHash",U));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let P=R===2||R===3?L+e.n:L;if(P>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let V=R&1?"03":"02",J=u.fromHex(V+p(P)),z=a(P),W=c(-C*z),Y=c(N*z),Z=u.BASE.multiplyAndAddUnsafe(J,W,Y);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return dc(this.toDERHex())}toDERHex(){return lc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return dc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let I={isValidPrivateKey(x){try{return d(x),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let x=vw(e.n);return NT(e.randomBytes(x),e.n)},precompute(x=8,U=u.BASE){return U._setWindowSize(x),U.multiply(BigInt(3)),U}};function A(x,U=!0){return u.fromPrivateKey(x).toRawBytes(U)}function O(x){let U=Bn(x),L=typeof x=="string",N=(U||L)&&x.length;return U?N===i||N===o:L?N===2*i||N===2*o:x instanceof u}function T(x,U,L=!0){if(O(x))throw new Error("first arg must be private key");if(!O(U))throw new Error("second arg must be public key");return u.fromHex(U).multiply(d(x)).toRawBytes(L)}let M=e.bits2int||function(x){let U=Zi(x),L=x.length*8-e.nBitLength;return L>0?U>>BigInt(L):U},q=e.bits2int_modN||function(x){return c(M(x))},j=Pd(e.nBitLength);function $(x){if(typeof x!="bigint")throw new Error("bigint expected");if(!(eo<=x&&x<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return yr(x,e.nByteLength)}function X(x,U,L=Q){if(["recovered","canonical"].some(ee=>ee in L))throw new Error("sign() legacy options not supported");let{hash:N,randomBytes:R}=e,{lowS:C,prehash:P,extraEntropy:V}=L;C==null&&(C=!0),x=Ge("msgHash",x),P&&(x=Ge("prehashed msgHash",N(x)));let J=q(x),z=d(U),W=[$(z),$(J)];if(V!=null){let ee=V===!0?R(r.BYTES):V;W.push(Ge("extraEntropy",ee))}let Y=Qi(...W),Z=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Ue=a(ce),Ke=u.BASE.multiply(ce).toAffine(),Je=c(Ke.x);if(Je===eo)return;let bt=c(Ue*c(Z+Je*z));if(bt===eo)return;let hi=(Ke.x===Je?0:2)|Number(Ke.y&rn),uo=bt;return C&&g(bt)&&(uo=y(bt),hi^=1),new S(Je,uo,hi)}return{seed:Y,k2sig:ue}}let Q={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function _(x,U,L=Q){let{seed:N,k2sig:R}=X(x,U,L),C=e;return mw(C.hash.outputLen,C.nByteLength,C.hmac)(N,R)}u.BASE._setWindowSize(8);function D(x,U,L,N=G){let R=x;if(U=Ge("msgHash",U),L=Ge("publicKey",L),"strict"in N)throw new Error("options.strict was renamed to lowS");let{lowS:C,prehash:P}=N,V,J;try{if(typeof R=="string"||Bn(R))try{V=S.fromDER(R)}catch(Ke){if(!(Ke instanceof lc.Err))throw Ke;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Ke,s:Je}=R;V=new S(Ke,Je)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Ke){if(Ke.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(C&&V.hasHighS())return!1;P&&(U=e.hash(U));let{r:z,s:W}=V,Y=q(U),Z=a(W),ue=c(Y*Z),ee=c(z*Z),ce=u.BASE.multiplyAndAddUnsafe(J,ue,ee)?.toAffine();return ce?c(ce.x)===z:!1}return{CURVE:e,getPublicKey:A,getSharedSecret:T,sign:_,verify:D,ProjectivePoint:u,Signature:S,utils:I}}l();l();var rp=class extends Ca{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,vT(e);let n=Cd(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(e){return Na(this),this.iHash.update(e),this}digestInto(e){Na(this),lw(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Aw=(t,e,r)=>new rp(t,e).update(r).digest();Aw.create=(t,e)=>new rp(t,e);function Fk(t){return{hash:t,hmac:(e,...r)=>Aw(t,e,Yh(...r)),randomBytes:Ld}}function np(t,e){let r=n=>LT({...t,...Fk(n)});return Object.freeze({...r(e),create:r})}var KT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),PT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),jk=BigInt(1),Tw=BigInt(2),MT=(t,e)=>(t+e/Tw)/e;function Wk(t){let e=KT,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=ze(d,r,e)*d%e,h=ze(f,r,e)*d%e,p=ze(h,Tw,e)*u%e,g=ze(p,i,e)*p%e,y=ze(g,o,e)*g%e,E=ze(y,c,e)*y%e,S=ze(E,a,e)*E%e,I=ze(S,c,e)*y%e,A=ze(I,r,e)*d%e,O=ze(A,s,e)*g%e,T=ze(O,n,e)*u%e,M=ze(T,Tw,e);if(!_w.eql(_w.sqr(M),t))throw new Error("Cannot find square root");return M}var _w=Pa(KT,void 0,void 0,{sqrt:Wk}),gr=np({a:BigInt(0),b:BigInt(7),Fp:_w,n:PT,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=PT,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-jk*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=MT(o*t,e),a=MT(-n*t,e),u=Be(t-c*r-a*i,e),d=Be(-c*n-a*o,e),f=u>s,h=d>s;if(f&&(u=e-u),h&&(d=e-d),u>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}}},Zh),MW=BigInt(0);var KW=gr.ProjectivePoint;l();l();function $T(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),o={};for(let s of i)o[s]=e(n[s]);return o}return n},r=e(t);return JSON.stringify(r)}var Gk=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Iw="urn:jwk:";function ge(t){return Gk(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);ng(n);let i=$T(n),o=ne.string(i).toUint8Array(),s=yield ka.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function ci(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function Ma(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function ai(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function Ka(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function HT(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}var $t=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},zk=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Dt=class t{static adjustSignatureToLowS(e){return $t(this,arguments,void 0,function*({signature:r}){let n=gr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return gr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return $t(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"secp256k1",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return $t(this,arguments,void 0,function*({derSignature:r}){return gr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return gr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=gr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return $t(this,arguments,void 0,function*({key:r}){var n;if(!(ci(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=zk(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return $t(this,arguments,void 0,function*({privateKey:r}){if(!ci(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return $t(this,arguments,void 0,function*({publicKey:r}){if(!(Ma(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return $t(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return gr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return $t(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Wo(r);return gr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return gr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{gr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return $t(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Wo(i);return gr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=gr.getPublicKey(r));let n=gr.ProjectivePoint.fromHex(r),i=yr(n.x,32),o=yr(n.y,32);return{x:i,y:o}})}};l();l();var VT=Pa(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Yk=VT.create(BigInt("-3")),Jk=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Zk=np({a:Yk,b:Jk,Fp:VT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Zh),Cr=Zk;var Ht=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Xk=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Vt=class t{static adjustSignatureToLowS(e){return Ht(this,arguments,void 0,function*({signature:r}){let n=Cr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ht(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ht(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"P-256",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return Ht(this,arguments,void 0,function*({derSignature:r}){return Cr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Cr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ht(this,void 0,void 0,function*(){let e=Cr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Ht(this,arguments,void 0,function*({key:r}){var n;if(!(ci(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,o=Xk(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Ht(this,arguments,void 0,function*({privateKey:r}){if(!ci(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ht(this,arguments,void 0,function*({publicKey:r}){if(!(Ma(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return Ht(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return Cr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return Ht(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Wo(r);return Cr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Ht(this,arguments,void 0,function*({privateKeyBytes:r}){return Cr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){try{Cr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ht(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Wo(i);return Cr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Ht(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Cr.getPublicKey(r));let n=Cr.ProjectivePoint.fromHex(r),i=yr(n.x,32),o=yr(n.y,32);return{x:i,y:o}})}};var Kd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},$d=class extends si{computePublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ci(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Dt.computePublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.computePublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Kd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"ES256K":case"secp256k1":{let n=yield Dt.generateKey();return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Vt.generateKey();return n.alg="ES256",n}}})}getPublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ci(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Dt.getPublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.getPublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Kd(this,arguments,void 0,function*({key:r,data:n}){if(!ci(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":return yield Dt.sign({key:r,data:n});case"P-256":return yield Vt.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Kd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ma(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(r.crv){case"secp256k1":return yield Dt.verify({key:r,signature:n,data:i});case"P-256":return yield Vt.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};l();l();l();l();l();var ip=BigInt(4294967295),Bw=BigInt(32);function qT(t,e=!1){return e?{h:Number(t&ip),l:Number(t>>Bw&ip)}:{h:Number(t>>Bw&ip)|0,l:Number(t&ip)|0}}function Qk(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:o,l:s}=qT(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var eN=(t,e)=>BigInt(t>>>0)<<Bw|BigInt(e>>>0),tN=(t,e,r)=>t>>>r,rN=(t,e,r)=>t<<32-r|e>>>r,nN=(t,e,r)=>t>>>r|e<<32-r,iN=(t,e,r)=>t<<32-r|e>>>r,oN=(t,e,r)=>t<<64-r|e>>>r-32,sN=(t,e,r)=>t>>>r-32|e<<64-r,cN=(t,e)=>e,aN=(t,e)=>t,uN=(t,e,r)=>t<<r|e>>>32-r,dN=(t,e,r)=>e<<r|t>>>32-r,fN=(t,e,r)=>e<<r-32|t>>>64-r,lN=(t,e,r)=>t<<r-32|e>>>64-r;function hN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var pN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),yN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,gN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),mN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,wN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),bN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var xN={fromBig:qT,split:Qk,toBig:eN,shrSH:tN,shrSL:rN,rotrSH:nN,rotrSL:iN,rotrBH:oN,rotrBL:sN,rotr32H:cN,rotr32L:aN,rotlSH:uN,rotlSL:dN,rotlBH:fN,rotlBL:lN,add:hN,add3L:pN,add3H:yN,add4L:gN,add4H:mN,add5H:bN,add5L:wN},le=xN;var[EN,vN]=le.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Yo=new Uint32Array(80),Jo=new Uint32Array(80),Rw=class extends La{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:c,Dl:a,Eh:u,El:d,Fh:f,Fl:h,Gh:p,Gl:g,Hh:y,Hl:E}=this;return[e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,E]}set(e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,E){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=c|0,this.Dl=a|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=y|0,this.Hl=E|0}process(e,r){for(let A=0;A<16;A++,r+=4)Yo[A]=e.getUint32(r),Jo[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=Yo[A-15]|0,T=Jo[A-15]|0,M=le.rotrSH(O,T,1)^le.rotrSH(O,T,8)^le.shrSH(O,T,7),q=le.rotrSL(O,T,1)^le.rotrSL(O,T,8)^le.shrSL(O,T,7),j=Yo[A-2]|0,$=Jo[A-2]|0,X=le.rotrSH(j,$,19)^le.rotrBH(j,$,61)^le.shrSH(j,$,6),Q=le.rotrSL(j,$,19)^le.rotrBL(j,$,61)^le.shrSL(j,$,6),G=le.add4L(q,Q,Jo[A-7],Jo[A-16]),_=le.add4H(G,M,X,Yo[A-7],Yo[A-16]);Yo[A]=_|0,Jo[A]=G|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:c,Cl:a,Dh:u,Dl:d,Eh:f,El:h,Fh:p,Fl:g,Gh:y,Gl:E,Hh:S,Hl:I}=this;for(let A=0;A<80;A++){let O=le.rotrSH(f,h,14)^le.rotrSH(f,h,18)^le.rotrBH(f,h,41),T=le.rotrSL(f,h,14)^le.rotrSL(f,h,18)^le.rotrBL(f,h,41),M=f&p^~f&y,q=h&g^~h&E,j=le.add5L(I,T,q,vN[A],Jo[A]),$=le.add5H(j,S,O,M,EN[A],Yo[A]),X=j|0,Q=le.rotrSH(n,i,28)^le.rotrBH(n,i,34)^le.rotrBH(n,i,39),G=le.rotrSL(n,i,28)^le.rotrBL(n,i,34)^le.rotrBL(n,i,39),_=n&o^n&c^o&c,D=i&s^i&a^s&a;S=y|0,I=E|0,y=p|0,E=g|0,p=f|0,g=h|0,{h:f,l:h}=le.add(u|0,d|0,$|0,X|0),u=c|0,d=a|0,c=o|0,a=s|0,o=n|0,s=i|0;let x=le.add3L(X,G,D);n=le.add3H(x,$,Q,_),i=x|0}({h:n,l:i}=le.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=le.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:c,l:a}=le.add(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:d}=le.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:h}=le.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:g}=le.add(this.Fh|0,this.Fl|0,p|0,g|0),{h:y,l:E}=le.add(this.Gh|0,this.Gl|0,y|0,E|0),{h:S,l:I}=le.add(this.Hh|0,this.Hl|0,S|0,I|0),this.set(n,i,o,s,c,a,u,d,f,h,p,g,y,E,S,I)}roundClean(){Yo.fill(0),Jo.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Uw=Jh(()=>new Rw);l();var Un=BigInt(0),Lr=BigInt(1),op=BigInt(2),SN=BigInt(8),AN={zip215:!0};function TN(t){let e=Md(t);return tn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function sp(t){let e=TN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=op<<BigInt(c*8)-Lr,d=r.create,f=e.uvRatio||((N,R)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(R))}}catch{return{isValid:!1,value:Un}}}),h=e.adjustScalarBytes||(N=>N),p=e.domain||((N,R,C)=>{if(R.length||C)throw new Error("Contexts/pre-hash are not supported");return N}),g=N=>typeof N=="bigint"&&Un<N,y=(N,R)=>g(N)&&g(R)&&N<R,E=N=>N===Un||y(N,u);function S(N,R){if(y(N,R))return N;throw new Error(`Expected valid scalar < ${R}, got ${typeof N} ${N}`)}function I(N){return N===Un?N:S(N,n)}let A=new Map;function O(N){if(!(N instanceof T))throw new Error("ExtendedPoint expected")}class T{constructor(R,C,P,V){if(this.ex=R,this.ey=C,this.ez=P,this.et=V,!E(R))throw new Error("x required");if(!E(C))throw new Error("y required");if(!E(P))throw new Error("z required");if(!E(V))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(R){if(R instanceof T)throw new Error("extended point not allowed");let{x:C,y:P}=R||{};if(!E(C)||!E(P))throw new Error("invalid affine point");return new T(C,P,Lr,d(C*P))}static normalizeZ(R){let C=r.invertBatch(R.map(P=>P.ez));return R.map((P,V)=>P.toAffine(C[V])).map(T.fromAffine)}_setWindowSize(R){this._WINDOW_SIZE=R,A.delete(this)}assertValidity(){let{a:R,d:C}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:P,ey:V,ez:J,et:z}=this,W=d(P*P),Y=d(V*V),Z=d(J*J),ue=d(Z*Z),ee=d(W*R),ce=d(Z*d(ee+Y)),Ue=d(ue+d(C*d(W*Y)));if(ce!==Ue)throw new Error("bad point: equation left != right (1)");let Ke=d(P*V),Je=d(J*z);if(Ke!==Je)throw new Error("bad point: equation left != right (2)")}equals(R){O(R);let{ex:C,ey:P,ez:V}=this,{ex:J,ey:z,ez:W}=R,Y=d(C*W),Z=d(J*V),ue=d(P*W),ee=d(z*V);return Y===Z&&ue===ee}is0(){return this.equals(T.ZERO)}negate(){return new T(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:R}=e,{ex:C,ey:P,ez:V}=this,J=d(C*C),z=d(P*P),W=d(op*d(V*V)),Y=d(R*J),Z=C+P,ue=d(d(Z*Z)-J-z),ee=Y+z,ce=ee-W,Ue=Y-z,Ke=d(ue*ce),Je=d(ee*Ue),bt=d(ue*Ue),hi=d(ce*ee);return new T(Ke,Je,hi,bt)}add(R){O(R);let{a:C,d:P}=e,{ex:V,ey:J,ez:z,et:W}=this,{ex:Y,ey:Z,ez:ue,et:ee}=R;if(C===BigInt(-1)){let uu=d((J-V)*(Z+Y)),yf=d((J+V)*(Z-Y)),du=d(yf-uu);if(du===Un)return this.double();let gf=d(z*op*ee),mf=d(W*op*ue),qr=mf+gf,lo=yf+uu,fu=mf-gf,wf=d(qr*du),us=d(lo*fu),bf=d(qr*fu),Zp=d(du*lo);return new T(wf,us,Zp,bf)}let ce=d(V*Y),Ue=d(J*Z),Ke=d(W*P*ee),Je=d(z*ue),bt=d((V+J)*(Y+Z)-ce-Ue),hi=Je-Ke,uo=Je+Ke,au=d(Ue-C*ce),pf=d(bt*hi),Jp=d(uo*au),fo=d(bt*au),Vr=d(hi*uo);return new T(pf,Jp,Vr,fo)}subtract(R){return this.add(R.negate())}wNAF(R){return j.wNAFCached(this,A,R,T.normalizeZ)}multiply(R){let{p:C,f:P}=this.wNAF(S(R,n));return T.normalizeZ([C,P])[0]}multiplyUnsafe(R){let C=I(R);return C===Un?q:this.equals(q)||C===Lr?this:this.equals(M)?this.wNAF(C).p:j.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return j.unsafeLadder(this,n).is0()}toAffine(R){let{ex:C,ey:P,ez:V}=this,J=this.is0();R==null&&(R=J?SN:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:Un,y:Lr};if(Y!==Lr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Lr?this:this.multiplyUnsafe(R)}static fromHex(R,C=!1){let{d:P,a:V}=e,J=r.BYTES;R=Ge("pointHex",R,J);let z=R.slice(),W=R[J-1];z[J-1]=W&-129;let Y=Rn(z);Y===Un||(C?S(Y,u):S(Y,r.ORDER));let Z=d(Y*Y),ue=d(Z-Lr),ee=d(P*Z-V),{isValid:ce,value:Ue}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Ke=(Ue&Lr)===Lr,Je=(W&128)!==0;if(!C&&Ue===Un&&Je)throw new Error("Point.fromHex: x=0 and x_0=1");return Je!==Ke&&(Ue=d(-Ue)),T.fromAffine({x:Ue,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=Xi(C,r.BYTES);return P[P.length-1]|=R&Lr?128:0,P}toHex(){return Ji(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Lr,d(e.Gx*e.Gy)),T.ZERO=new T(Un,Lr,Lr,Un);let{BASE:M,ZERO:q}=T,j=tp(T,c*8);function $(N){return Be(N,n)}function X(N){return $(Rn(N))}function Q(N){let R=c;N=Ge("private key",N,R);let C=Ge("hashed private key",o(N),2*R),P=h(C.slice(0,R)),V=C.slice(R,2*R),J=X(P),z=M.multiply(J),W=z.toRawBytes();return{head:P,prefix:V,scalar:J,point:z,pointBytes:W}}function G(N){return Q(N).pointBytes}function _(N=new Uint8Array,...R){let C=Qi(...R);return X(o(p(C,Ge("context",N),!!i)))}function D(N,R,C={}){N=Ge("message",N),i&&(N=i(N));let{prefix:P,scalar:V,pointBytes:J}=Q(R),z=_(C.context,P,N),W=M.multiply(z).toRawBytes(),Y=_(C.context,W,J,N),Z=$(z+Y*V);I(Z);let ue=Qi(W,Xi(Z,r.BYTES));return Ge("result",ue,c*2)}let x=AN;function U(N,R,C,P=x){let{context:V,zip215:J}=P,z=r.BYTES;N=Ge("signature",N,2*z),R=Ge("message",R),i&&(R=i(R));let W=Rn(N.slice(z,2*z)),Y,Z,ue;try{Y=T.fromHex(C,J),Z=T.fromHex(N.slice(0,z),J),ue=M.multiplyUnsafe(W)}catch{return!1}if(!J&&Y.isSmallOrder())return!1;let ee=_(V,Z.toRawBytes(),Y.toRawBytes(),R);return Z.add(Y.multiplyUnsafe(ee)).subtract(ue).clearCofactor().equals(T.ZERO)}return M._setWindowSize(8),{CURVE:e,getPublicKey:G,sign:D,verify:U,ExtendedPoint:T,utils:{getExtendedPublicKey:Q,randomPrivateKey:()=>s(r.BYTES),precompute(N=8,R=T.BASE){return R._setWindowSize(N),R.multiply(BigInt(3)),R}}}}l();var Hd=BigInt(0),Ow=BigInt(1);function _N(t){return tn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function FT(t){let e=_N(t),{P:r}=e,n=A=>Be(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>bw(A,r-BigInt(2),r));function u(A,O,T){let M=n(A*(O-T));return O=n(O-M),T=n(T+M),[O,T]}function d(A){if(typeof A=="bigint"&&Hd<=A&&A<r)return A;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let f=(e.a-BigInt(2))/BigInt(4);function h(A,O){let T=d(A),M=d(O),q=T,j=Ow,$=Hd,X=T,Q=Ow,G=Hd,_;for(let x=BigInt(i-1);x>=Hd;x--){let U=M>>x&Ow;G^=U,_=u(G,j,X),j=_[0],X=_[1],_=u(G,$,Q),$=_[0],Q=_[1],G=U;let L=j+$,N=n(L*L),R=j-$,C=n(R*R),P=N-C,V=X+Q,J=X-Q,z=n(J*L),W=n(V*R),Y=z+W,Z=z-W;X=n(Y*Y),Q=n(q*n(Z*Z)),j=n(N*C),$=n(P*(N+n(f*P)))}_=u(G,j,X),j=_[0],X=_[1],_=u(G,$,Q),$=_[0],Q=_[1];let D=a($);return n(j*D)}function p(A){return Xi(n(A),o)}function g(A){let O=Ge("u coordinate",A,o);return s===32&&(O[31]&=127),Rn(O)}function y(A){let O=Ge("scalar",A),T=O.length;if(T!==o&&T!==s)throw new Error(`Expected ${o} or ${s} bytes, got ${T}`);return Rn(c(O))}function E(A,O){let T=g(O),M=y(A),q=h(T,M);if(q===Hd)throw new Error("Invalid private or public key received");return p(q)}let S=p(e.Gu);function I(A){return E(A,S)}return{scalarMult:E,scalarMultBase:I,getSharedSecret:(A,O)=>E(A,O),getPublicKey:A=>I(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Vd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),jT=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),HG=BigInt(0),IN=BigInt(1),Dw=BigInt(2),BN=BigInt(5),WT=BigInt(10),RN=BigInt(20),UN=BigInt(40),GT=BigInt(80);function zT(t){let e=Vd,n=t*t%e*t%e,i=ze(n,Dw,e)*n%e,o=ze(i,IN,e)*t%e,s=ze(o,BN,e)*o%e,c=ze(s,WT,e)*s%e,a=ze(c,RN,e)*c%e,u=ze(a,UN,e)*a%e,d=ze(u,GT,e)*u%e,f=ze(d,GT,e)*u%e,h=ze(f,WT,e)*s%e;return{pow_p_5_8:ze(h,Dw,e)*t%e,b2:n}}function YT(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function ON(t,e){let r=Vd,n=Be(e*e*e,r),i=Be(n*n*e,r),o=zT(t*i).pow_p_5_8,s=Be(t*n*o,r),c=Be(e*s*s,r),a=s,u=Be(s*jT,r),d=c===t,f=c===Be(-t,r),h=c===Be(-t*jT,r);return d&&(s=a),(f||h)&&(s=u),OT(s,r)&&(s=Be(-s,r)),{isValid:d||f,value:s}}var nn=Pa(Vd,void 0,!0),qd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:nn,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Uw,randomBytes:Ld,adjustScalarBytes:YT,uvRatio:ON},Zo=sp(qd);function JT(t,e,r){if(e.length>255)throw new Error("Context is too big");return Yh(hw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var VG=sp({...qd,domain:JT}),qG=sp({...qd,domain:JT,prehash:Uw}),hc=FT({P:Vd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Vd,{pow_p_5_8:r,b2:n}=zT(t);return Be(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:YT,randomBytes:Ld});function ZT(t){let{y:e}=Zo.ExtendedPoint.fromHex(t),r=BigInt(1);return nn.toBytes(nn.create((r+e)*nn.inv(r-e)))}function XT(t){let e=qd.hash(t.subarray(0,32));return qd.adjustScalarBytes(e).subarray(0,32)}var DN=(nn.ORDER+BigInt(3))/BigInt(8),FG=nn.pow(Dw,DN),jG=nn.sqrt(nn.neg(nn.ONE)),WG=(nn.ORDER-BigInt(5))/BigInt(8),GG=BigInt(486662);var zG=DT(nn,nn.neg(BigInt(486664)));var YG=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),JG=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),ZG=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),XG=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var QG=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var on=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},kN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},It=class t{static bytesToPrivateKey(e){return on(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Zo.getPublicKey(r),i={crv:"Ed25519",d:ne.uint8Array(r).toBase64Url(),kty:"OKP",x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return on(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return on(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=Zo.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertPrivateKeyToX25519(e){return on(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=XT(n),o=hc.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:ne.uint8Array(i).toBase64Url(),x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static convertPublicKeyToX25519(e){return on(this,arguments,void 0,function*({publicKey:r}){let n=yield t.publicKeyToBytes({publicKey:r});if(!(yield t.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let o=ZT(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static generateKey(){return on(this,void 0,void 0,function*(){let e=Zo.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return on(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,o=kN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return on(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return on(this,arguments,void 0,function*({publicKey:r}){if(!Ka(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sign(e){return on(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return Zo.sign(n,i)})}static validatePublicKey(e){return on(this,arguments,void 0,function*({publicKeyBytes:r}){try{Zo.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return on(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return Zo.verify(n,i,o)})}};var Fd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},cp=class extends si{computePublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield It.computePublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Fd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield It.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield It.getPublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Fd(this,arguments,void 0,function*({key:r,data:n}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":return yield It.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Fd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ka(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(r.crv){case"Ed25519":return yield It.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};var to=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},kw={Ed25519:{implementation:cp,names:["Ed25519"]},secp256k1:{implementation:$d,names:["ES256K","secp256k1"]},secp256r1:{implementation:$d,names:["ES256","secp256r1"]},"SHA-256":{implementation:Wh,names:["SHA-256"]}},Qt=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new fh}digest(e){return to(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return to(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return to(this,arguments,void 0,function*({algorithm:r}){let i=yield this.getAlgorithm({algorithm:r}).generateKey({algorithm:r});if(i?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let o=`${Iw}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return to(this,arguments,void 0,function*({key:r}){let n=yield ge({jwk:r});return`${Iw}${n}`})}getPublicKey(e){return to(this,arguments,void 0,function*({keyUri:r}){let n=yield this.getPrivateKey({keyUri:r}),i=this.getAlgorithmName({key:n});return yield this.getAlgorithm({algorithm:i}).getPublicKey({key:n})})}importKey(e){return to(this,arguments,void 0,function*({key:r}){var n;if(!HT(r))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let i=structuredClone(r);(n=i.kid)!==null&&n!==void 0||(i.kid=yield ge({jwk:i}));let o=yield this.getKeyUri({key:i});return yield this._keyStore.set(o,i),o})}sign(e){return to(this,arguments,void 0,function*({keyUri:r,data:n}){let i=yield this.getPrivateKey({keyUri:r}),o=this.getAlgorithmName({key:i});return this.getAlgorithm({algorithm:o}).sign({data:n,key:i})})}verify(e){return to(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=this.getAlgorithmName({key:r});return this.getAlgorithm({algorithm:o}).verify({key:r,signature:n,data:i})})}getAlgorithm({algorithm:e}){var r;let n=(r=kw[e])===null||r===void 0?void 0:r.implementation;if(!n)throw new Error(`Algorithm not supported: ${e}`);return this._algorithmInstances.has(n)||this._algorithmInstances.set(n,new n),this._algorithmInstances.get(n)}getAlgorithmName({key:e}){let r=e.alg,n=e.crv;for(let i in kw){let o=kw[i];if(r&&o.names.includes(r))return i;if(n&&o.names.includes(n))return i}throw new Error(`Unable to determine algorithm based on provided input: alg=${r}, crv=${n}`)}getPrivateKey(e){return to(this,arguments,void 0,function*({keyUri:r}){let n=yield this._keyStore.get(r);if(!n)throw new Error(`Key not found: ${r}`);return n})}};l();var ap=class t{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return wT(e)}static randomUuid(){return Da.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let r=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let o=t.randomBytes(Math.ceil(e/2));n=new DataView(o.buffer).getUint16(0,!1)%i}while(n>r)}else{let i=Math.pow(10,10);do{let o=t.randomBytes(4);n=new DataView(o.buffer).getUint32(0,!1)%i}while(n>r)}return n.toString().padStart(e,"0")}};l();l();l();l();l();l();l();l();l();l();var Xo=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},NN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},$a=class t{static bytesToPrivateKey(e){return Xo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=hc.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return Xo(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return Xo(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=hc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static generateKey(){return Xo(this,void 0,void 0,function*(){let e=hc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Xo(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,o=NN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Xo(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Xo(this,arguments,void 0,function*({publicKey:r}){if(!Ka(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Xo(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return hc.getSharedSecret(i,o)})}};l();l();l();function Pr(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Lw({didDocument:t}){var e,r;if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let n=[];return n.push(...(r=(e=t.verificationMethod)===null||e===void 0?void 0:e.filter(Cw))!==null&&r!==void 0?r:[]),Object.keys(Li).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(Cw))!==null&&s!==void 0?s:[])}),n}function QT({didDocument:t}){let r=Lw({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function e_({didDocument:t,methodId:e}){let r=[];return Object.keys(Li).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=Pr(e);i.some(c=>{let a=Pr(c)===o,u=Cw(c)&&Pr(c.id)===o;return a||u})&&r.push(n)}}),r}function t_(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Cw(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function Pw({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Yt.addPrefix({code:e,data:t,name:r}),i=ne.uint8Array(n).toBase58Btc();return ne.base58Btc(i).toMultibase()}function Mw({multibaseKeyId:t}){try{let e=ne.multibase(t).toBase58Btc(),r=ne.base58Btc(e).toUint8Array(),{code:n,data:i,name:o}=Yt.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:o}}catch{throw new re(ie.InvalidDid,`Invalid multibase identifier: ${t}`)}}var jd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},mr=class t{constructor({uri:e,document:r,metadata:n,keyManager:i}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=i}export(){return jd(this,void 0,void 0,function*(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let r=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.exportKey({keyUri:i});r.push(Object.assign({},o))}e.privateKeys=r}return e})}getSigner(e){return jd(this,void 0,void 0,function*(){var r;let n=(r=this.document.verificationMethod)===null||r===void 0?void 0:r.find(a=>{var u,d;return Pr(a.id)===((u=Pr(e?.methodId))!==null&&u!==void 0?u:Pr((d=this.document.assertionMethod)===null||d===void 0?void 0:d[0]))});if(!(n&&n.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.getPublicKey({keyUri:i}),s=this.keyManager;return{algorithm:ap.getJoseSignatureAlgorithmFromPublicKey(o),keyId:n.id,sign(a){return jd(this,arguments,void 0,function*({data:u}){return yield s.sign({data:u,keyUri:i})})},verify(a){return jd(this,arguments,void 0,function*({data:u,signature:d}){return yield s.verify({data:u,key:o,signature:d})})}}})}static import(e){return jd(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){var i;let o=Lw({didDocument:r.document});if(o.length===0)throw new re(ie.InvalidDidDocument,"At least one verification method is required but 0 were given");for(let c of(i=r.privateKeys)!==null&&i!==void 0?i:[]){let a=yield n.getKeyUri({key:c});(yield n.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1))||(yield n.importKey({key:c}))}for(let c of o){if(!c.publicKeyJwk)throw new Error(`Verification method '${c.id}' does not contain a public key in JWK format`);let a=yield n.getKeyUri({key:c.publicKeyJwk});yield n.getPublicKey({keyUri:a})}return new t({uri:r.uri,document:r.document,metadata:r.metadata,keyManager:n})})}};l();l();l();l();l();var Kw="0123456789abcdef",n_=[],r_=[];for(let t=0;t<256;t++)n_[t]=Kw[t>>4&15]+Kw[t&15],t<16&&(t<10?r_[48+t]=t:r_[87+t]=t);var $w=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=n_[t[n++]];return r};var i_=(t,e=0)=>{let r=t.length||0;if(!e){let s=r;for(;s--;)e+=t[s].length}let n=new Uint8Array(e),i=e,o=r;for(;o--;)i-=t[o].length,n.set(t[o],i);return n};l();var o_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",LN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Wd=0;Wd<o_.length;Wd++)LN[o_.charCodeAt(Wd)]=Wd;var Wd;var PN=new TextDecoder,Hw=(t,e)=>e?new TextDecoder(e).decode(t):PN.decode(t),MN=new TextEncoder,sn=t=>MN.encode(t);var s_=typeof window<"u"?window:self,c_=s_.crypto||s_.msCrypto||{},QY=c_.subtle||c_.webkitSubtle;l();function Ha(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function up(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function Re(t,e,r){let n=[],i=null;return Re._encode(n,t),i=i_(n),Re.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Re.bytes=-1;Re._floatConversionDetected=!1;Re._encode=function(t,e){if(e!=null)switch(up(e)){case"object":Re.dict(t,e);break;case"map":Re.dictMap(t,e);break;case"array":Re.list(t,e);break;case"set":Re.listSet(t,e);break;case"string":Re.string(t,e);break;case"number":Re.number(t,e);break;case"boolean":Re.number(t,e);break;case"arraybufferview":Re.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Re.buffer(t,new Uint8Array(e));break}};var dp=new Uint8Array([101]),a_=new Uint8Array([100]),u_=new Uint8Array([108]);Re.buffer=function(t,e){t.push(sn(e.length+":"),e)};Re.string=function(t,e){t.push(sn(sn(e).byteLength+":"+e))};Re.number=function(t,e){if(Number.isInteger(e))return t.push(sn("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(sn("i"+o+"e")),o!==e&&!Re._floatConversionDetected&&(Re._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+o+'"'),console.trace())};Re.dict=function(t,e){t.push(a_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Re.string(t,n),Re._encode(t,e[n]));t.push(dp)};Re.dictMap=function(t,e){t.push(a_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Re._encode(t,n):Re.string(t,String(n)),Re._encode(t,e.get(n)));t.push(dp)};Re.list=function(t,e){let r=0,n=e.length;for(t.push(u_);r<n;r++)e[r]!=null&&Re._encode(t,e[r]);t.push(dp)};Re.listSet=function(t,e){t.push(u_);for(let r of e)r!=null&&Re._encode(t,r);t.push(dp)};var d_=Re;l();var KN=105,$N=58,HN=100,VN=108,Vw=101;function f_(t,e,r){let n=0,i=1;for(let o=e;o<r;o++){let s=t[o];if(s<58&&s>=48){n=n*10+(s-48);continue}if(!(o===e&&s===43)){if(o===e&&s===45){i=-1;continue}if(s===46)break;throw new Error("not a number: buffer["+o+"] = "+s)}}return n*i}function de(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),de.position=0,de.encoding=n||null,de.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):sn(t),de.bytes=de.data.length,de.next())}de.bytes=0;de.position=0;de.data=null;de.encoding=null;de.next=function(){switch(de.data[de.position]){case HN:return de.dictionary();case VN:return de.list();case KN:return de.integer();default:return de.buffer()}};de.find=function(t){let e=de.position,r=de.data.length,n=de.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};de.dictionary=function(){de.position++;let t={};for(;de.data[de.position]!==Vw;){let e=de.buffer(),r=Hw(e);r.includes("\uFFFD")&&(r=$w(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==Vw;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find(Vw),e=f_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find($N),e=f_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?Hw(de.data.slice(t,r)):de.data.slice(t,r)};var l_=de;l();function qN(t){let e=2;for(let r of t)e+=fp(r);return e}function FN(t){let e=2;for(let[r,n]of t){let i=sn(r).byteLength;e+=Ha(i)+1+i,e+=fp(n)}return e}function jN(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=sn(r[n]).byteLength;e+=Ha(i)+1+i,e+=fp(t[r[n]])}return e}function WN(t){let e=sn(t).byteLength;return Ha(e)+1+e}function GN(t){let e=t.byteLength-t.byteOffset;return Ha(e)+1+e}function fp(t){if(t==null)return 0;let r=up(t);switch(r){case"arraybufferview":return GN(t);case"string":return WN(t);case"array":case"set":return qN(t);case"number":return 1+Ha(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return jN(t);case"map":return FN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var qw=fp;var zN=qw,Fw={encode:d_,decode:l_,byteLength:qw,encodingLength:zN};l();l();var YN=/^(\d{1,3}\.){3,3}\d{1,3}$/;var JN=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var On={name:"v4",size:4,isFormat:t=>YN.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let o=0;o<n;){let s=t.charCodeAt(o++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},ro={name:"v6",size:16,isFormat:t=>t.length>0&&JN.test(t),encode(t,e,r){r=~~r;let n=r+16,i=-1,o=0,s=0,c=!0,a=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(c?i!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(i=r):(a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2),o=0,s=0),c=!0,a=!1):d===46?(r<n&&(e[r]=s),r++,s=0,o=0,c=!1,a=!0):(c=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,s=s*10+d),o=(o<<4)+d)}if(c===!1)a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2);else if(i===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(i!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=i+2;u--)e[u]=e[u-2];e[i]=0,e[i+1]=0,i=r}if(i!==r&&i!==-1)for(r>n-2&&(r=n-2);n>i;)e[--n]=r<n&&r>i?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function h_(t){if(On.isFormat(t))return On.size;if(ro.isFormat(t))return ro.size;throw Error(`Invalid ip address: ${t}`)}function p_(t){return h_(t)===On.size?1:2}function y_(t,e,r){r=~~r;let n=h_(t);return typeof e=="function"&&(e=e(r+n)),n===On.size?On.encode(t,e,r):ro.encode(t,e,r)}function g_(t,e,r){if(e=~~e,r=r||t.length-e,r===On.size)return On.decode(t,e,r);if(r===ro.size)return ro.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${On.size} for v4 or ${ro.size} for v6.`)}l();function Gd(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t}function Va(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}l();function m_(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t}l();function w_(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t}l();function jw(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function Ww(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}l();function b_(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`}function Gw(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}l();l();function zw(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let i=t.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let o=n+1;o===r||i>=56320||(t.charCodeAt(o)&64512)!==56320?e+=3:(n=o,e+=4)}}return e}function qa(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(zw(t)+r));let i=r;for(let o=0;o<n;o+=1){let s=t.charCodeAt(o);if(s<=127)e[i++]=s;else if(s<=2047)e[i++]=192|(s&1984)>>6,e[i++]=128|s&63;else if((s&63488)!==55296)e[i++]=224|(s&61440)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63;else{let c=o+1;if(c===n||s>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let a=t.charCodeAt(c);(a&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(o=c,s=65536|(s&1023)<<10|a&1023,e[i++]=240|(s&1835008)>>18,e[i++]=128|(s&258048)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63)}}}return qa.bytes=i-r,e}qa.bytes=0;function Fa(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let i=e;i<r;){let o=t[i++],s;if(o<=128)s=o;else if(o>191&&o<224)s=(o&31)<<6|t[i++]&63;else if(o>239&&o<365){s=((o&7)<<18|(t[i++]&63)<<12|(t[i++]&63)<<6|t[i++]&63)-65536;let c=55296|s>>10&1023;n+=String.fromCharCode(c),s=56320|s&1023}else s=(o&15)<<12|(t[i++]&63)<<6|t[i++]&63;n+=String.fromCharCode(s)}return Fa.bytes=r-e,n}Fa.bytes=0;var Qo=t=>t instanceof Uint8Array;function no(t){return typeof t=="string"?zw(t):t.byteLength}function lp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):qa(t)}function hp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return qa(e,t,r),qa.bytes}var zd={},x_=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),o=i.toUpperCase(),s=t<<4|n,c=`${e}${i}`;x_[s]=c,zd[c]=s,zd[`${r}${i}`]=s,zd[`${e}${o}`]=s,zd[`${r}${o}`]=s}}function E_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=x_[o]}return n}function Yw(t){return t.length>>>1}function v_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=zd[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var iC=Math.pow(2,24),oC=Math.pow(2,16),sC=Math.pow(2,8),ui=(t,e)=>t[e]*iC+t[e+1]*oC+t[e+2]*sC+t[e+3],he=(t,e)=>t[e]<<8|t[e+1],di=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),ae=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function wr(t,e,r,n,i){return r<0&&(n-=r,r=0),n<0&&(n=0),i<0?new Uint8Array(0):r>=e.length||n>=i?0:cC(t,e,r,n,i)}function cC(t,e,r,n,i){i-n>e.length-r&&(i=n+e.length-r);let o=i-n,s=t.length-n;return o>s&&(o=s),(n!==0||i<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,o)),e.set(t,r),o}var uC=0,S_=32768,Zw=32768,dC=~Zw,T_=32768,fC=~T_;function He({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var se=He({encode(t,e,r){e||(e=new Uint8Array(se.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=i.split(".");for(let s=0;s<o.length;s++){let c=hp(e,o[s],r+1);e[r]=c,r+=c+1}}return e[r++]=0,se.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,i=0,o=0,s=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=s?0:1,c===0)break;if(c&192)if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let a=he(t,e-1)-49152;if(a>=n)throw new Error("Cannot decode name (bad pointer)");e=a,n=a,o+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");r.push(Fa(t,e,e+c)),e+=c,o+=s?0:c}}return se.decode.bytes=o,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:no(t.replace(/^\.|\.$/gm,""))+2}}),Bt=He({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=hp(e,t,r+1);return e[r]=n,Bt.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=Fa(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return no(t)+1}}),ja=He({bytes:12,encode(t,e,r){e||(e=new Uint8Array(ja.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?S_:uC;return ae(e,t.id||0,r),ae(e,n|i,r+2),ae(e,t.questions.length,r+4),ae(e,t.answers.length,r+6),ae(e,t.authorities.length,r+8),ae(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=he(t,e+2);return{id:he(t,e),type:r&S_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:w_(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:m_(r&15),questions:new Array(he(t,e+4)),answers:new Array(he(t,e+6)),authorities:new Array(he(t,e+8)),additionals:new Array(he(t,e+10))}},encodingLength(){return 12}}),yp=He({encode(t,e,r){e||(e=new Uint8Array(yp.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),wr(t,e,r+2,0,n),yp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=t.slice(e+2,e+2+r);return yp.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),gp=He({encode(t,e,r){return e||(e=new Uint8Array(gp.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),gp.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=se.decode(t,e+2);return gp.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),mp=He({encode(t,e,r){e||(e=new Uint8Array(mp.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mname,e,r),r+=se.encode.bytes,se.encode(t.rname,e,r),r+=se.encode.bytes,di(e,t.serial||0,r),r+=4,di(e,t.refresh||0,r),r+=4,di(e,t.retry||0,r),r+=4,di(e,t.expire||0,r),r+=4,di(e,t.minimum||0,r),r+=4,ae(e,r-n-2,n),mp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=se.decode(t,e),e+=se.decode.bytes,n.rname=se.decode(t,e),e+=se.decode.bytes,n.serial=ui(t,e),e+=4,n.refresh=ui(t,e),e+=4,n.retry=ui(t,e),e+=4,n.expire=ui(t,e),e+=4,n.minimum=ui(t,e),e+=4,mp.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),wp=He({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=lp(t[i])),!Qo(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(wp.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,wr(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),wp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=[];for(;n>0;){let o=t[e++];if(--n,n<o)throw new Error("Buffer overflow");i.push(t.slice(e,e+o)),e+=o,n-=o}return wp.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=no(r)+1:e+=r.length+1}),e}}),bp=He({encode(t,e,r){e||(e=new Uint8Array(bp.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=lp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return wr(t,e,r,0,i),r+=i,ae(e,r-n-2,n),bp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,bp.decode.bytes=e-r,i},encodingLength(t){return t?(Qo(t)?t.length:no(t))+2:2}}),xp=He({encode(t,e,r){e||(e=new Uint8Array(xp.encodingLength(t))),r||(r=0);let n=r;return r+=2,Bt.encode(t.cpu,e,r),r+=Bt.encode.bytes,Bt.encode(t.os,e,r),r+=Bt.encode.bytes,ae(e,r-n-2,n),xp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Bt.decode(t,e),e+=Bt.decode.bytes,n.os=Bt.decode(t,e),e+=Bt.decode.bytes,xp.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),za=He({encode(t,e,r){return e||(e=new Uint8Array(za.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),za.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return za.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),Ep=He({encode(t,e,r){e||(e=new Uint8Array(Ep.encodingLength(t))),r||(r=0),ae(e,t.priority||0,r+2),ae(e,t.weight||0,r+4),ae(e,t.port||0,r+6),se.encode(t.target,e,r+8);let n=se.encode.bytes+6;return ae(e,n,r),Ep.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n={};return n.priority=he(t,e+2),n.weight=he(t,e+4),n.port=he(t,e+6),n.target=se.decode(t,e+8),Ep.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),es=He({encode(t,e,r){let n=es.encodingLength(t);return e||(e=new Uint8Array(es.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=es.ISSUER_CRITICAL),ae(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Bt.encode(t.tag,e,r),r+=Bt.encode.bytes,hp(e,t.value,r),r+=no(t.value),es.encode.bytes=n,e},decode(t,e){e||(e=0);let r=he(t,e);e+=2;let n=e,i={};return i.flags=t[e],e+=1,i.tag=Bt.decode(t,e),e+=Bt.decode.bytes,i.value=Fa(t,e,n+r),i.issuerCritical=!!(i.flags&es.ISSUER_CRITICAL),es.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});es.ISSUER_CRITICAL=128;var vp=He({encode(t,e,r){e||(e=new Uint8Array(vp.encodingLength(t))),r||(r=0);let n=r;return r+=2,ae(e,t.preference||0,r),r+=2,se.encode(t.exchange,e,r),r+=se.encode.bytes,ae(e,r-n-2,n),vp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=he(t,e),e+=2,n.exchange=se.decode(t,e),e+=se.decode.bytes,vp.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),__=He({encode(t,e,r){return e||(e=new Uint8Array(__.encodingLength(t))),r||(r=0),ae(e,4,r),r+=2,On.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,On.decode(t,e)},bytes:6}),Sp=He({encode(t,e,r){return e||(e=new Uint8Array(Sp.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,ro.encode(t,e,r),Sp.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=ro.decode(t,e);return Sp.decode.bytes=18,r},bytes:18}),A_=t=>new Uint8Array(t),io=He({encode(t,e,r){e||(e=new Uint8Array(io.encodingLength(t))),r||(r=0);let n=r,i=Gw(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,wr(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||p_(t.ip,A_),c=y_(t.ip,A_),a=Math.ceil(o/8);ae(e,a+4,r),r+=2,ae(e,s,r),r+=2,e[r++]=o,e[r++]=t.scopePrefixLength||0,wr(c,e,r,0,a),r+=a}break;case 11:t.timeout?(ae(e,2,r),r+=2,ae(e,t.timeout,r),r+=2):(ae(e,0,r),r+=2);break;case 12:{let o=t.length||0;ae(e,o,r),r+=2,e.fill(0,r,r+o),r+=o}break;case 14:{let o=t.tags.length*2;ae(e,o,r),r+=2;for(let s of t.tags)ae(e,s,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return io.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=he(t,e),r.type=b_(r.code),e+=2;let n=he(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=he(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);wr(t,i,0,e,e+n-4),r.ip=g_(i)}break;case 11:n>0&&(r.timeout=he(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(he(t,e)),e+=2}return io.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(Gw(t.code)){case 8:{let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),ts=He({encode(t,e,r){e||(e=new Uint8Array(ts.encodingLength(t))),r||(r=0);let n=r,i=Ga(t,io);return ae(e,i,r),r=ef(t,io,e,r+2),ts.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=he(t,e);e+=2;let o=0;for(;i>0;)n[o++]=io.decode(t,e),e+=io.decode.bytes,i-=io.decode.bytes;return ts.decode.bytes=e-r,n},encodingLength(t){return 2+Ga(t||[],io)}}),fi=He({encode(t,e,r){e||(e=new Uint8Array(fi.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!Qo(i))throw new Error("Key must be a Buffer");return r+=2,ae(e,t.flags,r),r+=2,e[r]=fi.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,wr(i,e,r,0,i.length),r+=i.length,fi.encode.bytes=r-n,ae(e,fi.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);if(e+=2,n.flags=he(t,e),e+=2,t[e]!==fi.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,fi.decode.bytes=e-r,n},encodingLength(t){return 6+no(t.key)}});fi.PROTOCOL_DNSSEC=3;fi.ZONE_KEY=128;fi.SECURE_ENTRYPOINT=32768;var Yd=He({encode(t,e,r){e||(e=new Uint8Array(Yd.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!Qo(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Va(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,di(e,t.originalTTL,r),r+=4,di(e,t.expiration,r),r+=4,di(e,t.inception,r),r+=4,ae(e,t.keyTag,r),r+=2,se.encode(t.signersName,e,r),r+=se.encode.bytes,wr(i,e,r,0,i.length),r+=i.length,Yd.encode.bytes=r-n,ae(e,Yd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.typeCovered=Gd(he(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=ui(t,e),e+=4,n.expiration=ui(t,e),e+=4,n.inception=ui(t,e),e+=4,n.keyTag=he(t,e),e+=2,n.signersName=se.decode(t,e),e+=se.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,Yd.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+no(t.signature)}}),Jd=He({encode(t,e,r){e||(e=new Uint8Array(Jd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mbox||".",e,r),r+=se.encode.bytes,se.encode(t.txt||".",e,r),r+=se.encode.bytes,Jd.encode.bytes=r-n,ae(e,Jd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=se.decode(t,e)||".",e+=se.decode.bytes,n.txt=se.decode(t,e)||".",e+=se.decode.bytes,Jd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Mr=He({encode(t,e,r){e||(e=new Uint8Array(Mr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Va(t[o]);i[s>>8]===void 0&&(i[s>>8]=[]),i[s>>8][s>>3&31]|=1<<7-(s&7)}for(let o=0;o<i.length;o++)if(i[o]!==void 0){let s=lp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,wr(s,e,r,0,s.length),r+=s.length}return Mr.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,i=[];for(;e-n<r;){let o=t[e];e+=1;let s=t[e];e+=1;for(let c=0;c<s;c++){let a=t[e+c];for(let u=0;u<8;u++)if(a&1<<7-u){let d=Gd(o<<8|c<<3|u);i.push(d)}}e+=s}return Mr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Va(t[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),Zd=He({encode(t,e,r){e||(e=new Uint8Array(Zd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,Zd.encode.bytes=r-n,ae(e,Zd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.nextDomain=se.decode(t,e),e+=se.decode.bytes,n.rrtypes=Mr.decode(t,e,i-(e-r)),e+=Mr.decode.bytes,Zd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Mr.encodingLength(t.rrtypes)}}),Xd=He({encode(t,e,r){e||(e=new Uint8Array(Xd.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!Qo(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!Qo(o))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,ae(e,t.iterations,r),r+=2,e[r]=i.length,r+=1,wr(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,wr(o,e,r,0,o.length),r+=o.length,Mr.encode(t.rrtypes,e,r),r+=Mr.encode.bytes,Xd.encode.bytes=r-n,ae(e,Xd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=he(t,e),e+=2;let o=t[e];e+=1,n.salt=t.slice(e,e+o),e+=o;let s=t[e];return e+=1,n.nextDomain=t.slice(e,e+s),e+=s,n.rrtypes=Mr.decode(t,e,i-(e-r)),e+=Mr.decode.bytes,Xd.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Mr.encodingLength(t.rrtypes)}}),Qd=He({encode(t,e,r){e||(e=new Uint8Array(Qd.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!Qo(i))throw new Error("Digest must be a Buffer");return r+=2,ae(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,wr(i,e,r,0,i.length),r+=i.length,Qd.encode.bytes=r-n,ae(e,Qd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.keyTag=he(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,Qd.decode.bytes=e-r,n},encodingLength(t){return 6+no(t.digest)}}),Wa=He({encode(t,e,r){e||(e=new Uint8Array(Wa.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=Yw(t.fingerprint),o=Xw(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return v_(e,t.fingerprint,r,r+=i),Wa.encode.bytes=r-n,ae(e,Wa.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let i=Xw(n.hash);return n.fingerprint=E_(t,e,e+i),e+=i,Wa.decode.bytes=e-r,n},encodingLength(t){return 4+Yw(t.fingerprint)}});function Xw(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Wa.getFingerprintLengthForHashType=Xw;function Jw(t){switch(t.toUpperCase()){case"A":return __;case"PTR":return za;case"CNAME":return za;case"DNAME":return za;case"TXT":return wp;case"NULL":return bp;case"AAAA":return Sp;case"SRV":return Ep;case"HINFO":return xp;case"CAA":return es;case"NS":return gp;case"SOA":return mp;case"MX":return vp;case"OPT":return ts;case"DNSKEY":return fi;case"RRSIG":return Yd;case"RP":return Jd;case"NSEC":return Zd;case"NSEC3":return Xd;case"SSHFP":return Wa;case"DS":return Qd}return yp}var cn=He({encode(t,e,r){e||(e=new Uint8Array(cn.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Va(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");ae(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,ae(e,t.flags||0,r+6),r+=8,ts.encode(t.options||[],e,r),r+=ts.encode.bytes}else{let i=Ww(t.class===void 0?"IN":t.class);t.flush&&(i|=Zw),ae(e,i,r+2),di(e,t.ttl||0,r+4),r+=8;let o=Jw(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return cn.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=se.decode(t,e),e+=se.decode.bytes,r.type=Gd(he(t,e)),r.type==="OPT")r.udpPayloadSize=he(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=he(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=ts.decode(t,e+8),e+=8+ts.decode.bytes;else{let i=he(t,e+2);r.ttl=ui(t,e+4),r.class=jw(i&dC),r.flush=!!(i&Zw);let o=Jw(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return cn.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return se.encodingLength(t.name)+8+Jw(t.type).encodingLength(e)}}),Ya=He({encode(t,e,r){e||(e=new Uint8Array(Ya.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Va(t.type),r),r+=2,ae(e,Ww(t.class===void 0?"IN":t.class),r),r+=2,Ya.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=se.decode(t,e),e+=se.decode.bytes,n.type=Gd(he(t,e)),e+=2,n.class=jw(he(t,e)),e+=2,!!(n.class&T_)&&(n.class&=fC),Ya.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var I_=1024;var qt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(lC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),ja.encode(t,e,r),r+=ja.encode.bytes,r=ef(t.questions,Ya,e,r),r=ef(t.answers,cn,e,r),r=ef(t.authorities,cn,e,r),r=ef(t.additionals,cn,e,r),qt.encode.bytes=r-i,n&&tf.bytes!==e.length?e.slice(0,tf.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=ja.decode(t,e);return e+=ja.decode.bytes,e=pp(n.questions,Ya,t,e),e=pp(n.answers,cn,t,e),e=pp(n.authorities,cn,t,e),e=pp(n.additionals,cn,t,e),qt.decode.bytes=e-r,n},encodingLength:function(t){return ja.encodingLength(t)+Ga(t.questions||[],Ya)+Ga(t.answers||[],cn)+Ga(t.authorities||[],cn)+Ga(t.additionals||[],cn)}};qt.encode.bytes=0;qt.decode.bytes=0;function Ap(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}var Tp={encode:function(t,e,r){return e=qt.encode(Ap(t,"query"),e,r),Tp.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Tp.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Ap(t,"query"))}};Tp.encode.bytes=0;Tp.decode.bytes=0;var _p={encode:function(t,e,r){return e=qt.encode(Ap(t,"response"),e,r),_p.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return _p.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Ap(t,"response"))}};_p.encode.bytes=0;_p.decode.bytes=0;var tf=qt.encode,Ip=qt.decode,lC=qt.encodingLength;function B_(t){let e=tf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),wr(e,r,2,0,e.length),B_.bytes=r.byteLength,r}B_.bytes=0;function R_(t){let e=he(t,0);if(t.byteLength<e+2)return null;let r=Ip(t.slice(2));return R_.bytes=Ip.bytes,r}R_.bytes=0;function Ga(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function ef(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}function pp(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}l();var U_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},an=class{static getSigningMethod(e){return U_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return U_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")})}};var Nt=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},O_=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},D_="https://diddht.tbddev.org",hC=0,rs=7200,Bp=";",sr=",",Qw;(function(t){t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution"})(Qw||(Qw={}));var cr;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(cr||(cr={}));var eb;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(eb||(eb={}));var N_={Ed25519:cr.Ed25519,ES256K:cr.secp256k1,ES256:cr.secp256r1,"P-256":cr.secp256r1,secp256k1:cr.secp256k1,secp256r1:cr.secp256r1,X25519:cr.X25519},k_={[cr.Ed25519]:"EdDSA",[cr.secp256k1]:"ES256K",[cr.secp256r1]:"ES256",[cr.X25519]:"ECDH-ES+A256KW"},rf=class t extends an{static create(){return Nt(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s,c,a,u,d,f,h,p;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in N_)))throw new Error("One or more verification method algorithms are not supported");let g=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(g&&g.length!==new Set(g).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let y=yield e.generateKey({algorithm:"Ed25519"}),E=yield e.getPublicKey({keyUri:y}),S=yield kt.identityKeyToIdentifier({identityKey:E}),I=Object.assign(Object.assign({id:S},r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs}),r.controllers&&{controller:r.controllers}),A=[...(s=r.verificationMethods)!==null&&s!==void 0?s:[]];A?.some(T=>{var M;return((M=T.id)===null||M===void 0?void 0:M.split("#").pop())==="0"})||A.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let T of A){let M=T.id&&T.id.split("#").pop()==="0"?y:yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M}),j=(a=(c=T.id)!==null&&c!==void 0?c:q.kid)!==null&&a!==void 0?a:yield ge({jwk:q});j=`${S}#${Pr(j)}`,(u=I.verificationMethod)!==null&&u!==void 0||(I.verificationMethod=[]),I.verificationMethod.push({id:j,type:"JsonWebKey",controller:(d=T.controller)!==null&&d!==void 0?d:S,publicKeyJwk:q});for(let $ of(f=T.purposes)!==null&&f!==void 0?f:[])I[$]||(I[$]=[]),I[$].push(j)}(h=r.services)===null||h===void 0||h.forEach(T=>{var M;(M=I.service)!==null&&M!==void 0||(I.service=[]),T.id=`${S}#${T.id.split("#").pop()}`,I.service.push(T)});let O=new mr({uri:S,document:I,metadata:Object.assign({published:!1},r.types&&{types:r.types}),keyManager:e});if(!((p=r.publish)!==null&&p!==void 0)||p){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static import(e){return Nt(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield mr.import({portableDid:r,keyManager:n});if(!(!((i=s.document.verificationMethod)===null||i===void 0)&&i.some(c=>{var a;return((a=c.id)===null||a===void 0?void 0:a.split("#").pop())==="0"})))throw new re(ie.InvalidDidDocument,"DID document must contain an Identity Key");return s})}static getSigningMethod(e){return Nt(this,arguments,void 0,function*({didDocument:r,methodId:n="#0"}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a,u;return Pr(c.id)===((a=Pr(n))!==null&&a!==void 0?a:Pr((u=r.assertionMethod)===null||u===void 0?void 0:u[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static publish(e){return Nt(this,arguments,void 0,function*({did:r,gatewayUri:n=D_}){return yield Rp.put({did:r,gatewayUri:n})})}static resolve(e){return Nt(this,arguments,void 0,function*(r,n={}){var i;let o=(i=n?.gatewayUri)!==null&&i!==void 0?i:D_;try{yield kt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Rp.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},lt),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},lt),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};rf.methodName="dht";var Rp=class t{static get(e){return Nt(this,arguments,void 0,function*({didUri:r,gatewayUri:n}){let i=kt.identifierToIdentityKeyBytes({didUri:r}),o=yield t.pkarrGet({gatewayUri:n,publicKeyBytes:i}),s=yield kt.parseBep44GetMessage({bep44Message:o}),c=yield t.fromDnsPacket({didUri:r,dnsPacket:s});return c.didDocumentMetadata.versionId=o.seq.toString(),c})}static put(e){return Nt(this,arguments,void 0,function*({did:r,gatewayUri:n}){let i=yield t.toDnsPacket({didDocument:r.document,didMetadata:r.metadata,authoritativeGatewayUris:[n]}),o=yield kt.createBep44PutMessage({dnsPacket:i,publicKeyBytes:kt.identifierToIdentityKeyBytes({didUri:r.uri}),signer:yield r.getSigner({methodId:"0"})}),s=yield t.pkarrPut({gatewayUri:n,bep44Message:o});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:s,versionId:o.seq.toString()}),didRegistrationMetadata:{}}})}static pkarrGet(e){return Nt(this,arguments,void 0,function*({gatewayUri:r,publicKeyBytes:n}){let i=ne.uint8Array(n).toBase32Z(),o=new URL(i,r).href,s;try{if(s=yield fetch(o,{method:"GET"}),!s.ok)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`)}catch(u){throw u instanceof re?u:new re(ie.InternalError,`Failed to fetch Pkarr record: ${u.message}`)}let c=yield s.arrayBuffer();if(!c)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`);if(c.byteLength<72)throw new re(ie.InvalidDidDocumentLength,`Pkarr response must be at least 72 bytes but got: ${c.byteLength}`);if(c.byteLength>1072)throw new re(ie.InvalidDidDocumentLength,`Pkarr response exceeds 1000 byte limit: ${c.byteLength}`);return{k:n,seq:Number(new DataView(c).getBigUint64(64)),sig:new Uint8Array(c,0,64),v:new Uint8Array(c,72)}})}static pkarrPut(e){return Nt(this,arguments,void 0,function*({gatewayUri:r,bep44Message:n}){let i=ne.uint8Array(n.k).toBase32Z(),o=new URL(i,r).href,s=new Uint8Array(n.v.length+72);s.set(n.sig,0),new DataView(s.buffer).setBigUint64(n.sig.length,BigInt(n.seq)),s.set(n.v,n.sig.length+8);let c;try{c=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s})}catch(a){throw new re(ie.InternalError,`Failed to put Pkarr record for identifier ${i}: ${a.message}`)}return c.ok})}static fromDnsPacket(e){return Nt(this,arguments,void 0,function*({didUri:r,dnsPacket:n}){var i,o,s;let c={id:r},a={published:!0},u=new Map;for(let d of(i=n?.answers)!==null&&i!==void 0?i:[]){if(d.type!=="TXT")continue;let f=d.name.split(".")[0].substring(1);switch(!0){case f.startsWith("aka"):{let h=kt.parseTxtDataToString(d.data);c.alsoKnownAs=h.split(sr);break}case f.startsWith("cnt"):{let h=kt.parseTxtDataToString(d.data);c.controller=h.includes(sr)?h.split(sr):h;break}case f.startsWith("k"):{let{id:h,t:p,k:g,c:y,a:E}=kt.parseTxtDataToObject(d.data),S=ne.base64Url(g).toUint8Array(),I=cr[Number(p)],A=yield kt.keyConverter(I).bytesToPublicKey({publicKeyBytes:S});A.alg=E||k_[Number(p)];let O=f==="k0"?"0":h!==void 0?h:yield ge({jwk:A});(o=c.verificationMethod)!==null&&o!==void 0||(c.verificationMethod=[]);let T=`${r}#${O}`;c.verificationMethod.push({id:T,type:"JsonWebKey",controller:y??r,publicKeyJwk:A}),u.set(f,T);break}case f.startsWith("s"):{let h=kt.parseTxtDataToObject(d.data),{id:p,t:g,se:y}=h,E=O_(h,["id","t","se"]),S=y.includes(sr)?y.split(sr):[y],I=Object.fromEntries(Object.entries(E).map(([A,O])=>[A,O.includes(sr)?O.split(sr):O]));(s=c.service)!==null&&s!==void 0||(c.service=[]),c.service.push(Object.assign(Object.assign({},I),{id:`${r}#${p}`,type:g,serviceEndpoint:S}));break}case f.startsWith("typ"):{let{id:h}=kt.parseTxtDataToObject(d.data);a.types=h.split(sr).map(p=>Number(p));break}case f.startsWith("did"):{let h=I=>I.split(sr).map(A=>u.get(A)).filter(A=>typeof A=="string"),{auth:p,asm:g,del:y,inv:E,agm:S}=kt.parseTxtDataToObject(d.data);p&&(c.authentication=h(p)),g&&(c.assertionMethod=h(g)),y&&(c.capabilityDelegation=h(y)),E&&(c.capabilityInvocation=h(E)),S&&(c.keyAgreement=h(S));break}}}return{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{}}})}static toDnsPacket(e){return Nt(this,arguments,void 0,function*({didDocument:r,didMetadata:n,authoritativeGatewayUris:i,previousDidProof:o}){var s,c,a,u,d;let f=[],h=[],p=new Map,g=[],y=[];if(o!==void 0){let{signature:I,previousDid:A}=o;yield kt.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:rs,data:`id=${A};s=${I}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:rs,data:r.alsoKnownAs.join(sr)}),r.controller){let I=Array.isArray(r.controller)?r.controller.join(sr):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:rs,data:I})}for(let[I,A]of(c=(s=r.verificationMethod)===null||s===void 0?void 0:s.entries())!==null&&c!==void 0?c:[]){let O=`k${I}`;y.push(O);let T=A.id.split("#").pop();p.set(T,O);let M=A.publicKeyJwk;if(!(M?.crv&&M.crv in N_))throw new re(ie.InvalidPublicKeyType,`Verification method '${A.id}' contains an unsupported key type: ${(a=M?.crv)!==null&&a!==void 0?a:"undefined"}`);let q=cr[M.crv],j=yield kt.keyConverter(M.crv).publicKeyToBytes({publicKey:M}),$=ne.uint8Array(j).toBase64Url(),X=[`t=${q}`,`k=${$}`];T!=="0"&&(yield ge({jwk:M}))!==T&&X.unshift(`id=${T}`),M.alg!==k_[q]&&X.push(`a=${M.alg}`),A.controller!==r.id&&X.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:rs,data:X.join(Bp)})}(u=r.service)===null||u===void 0||u.forEach((I,A)=>{let O=`s${A}`;g.push(O);let{id:T,type:M,serviceEndpoint:q}=I,j=O_(I,["id","type","serviceEndpoint"]);T=Pr(T),q=Array.isArray(q)?q.join(","):q;let X=Object.entries(Object.assign({id:T,t:M,se:q},j)).map(([G,_])=>`${G}=${_}`).join(Bp),Q=kt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:rs,data:Q})});let E=[`v=${hC}`];if(y.length&&E.push(`vm=${y.join(sr)}`),Object.keys(Li).forEach(I=>{var A;let O=(A=r[I])===null||A===void 0?void 0:A.map(T=>p.get(T.split("#").pop()));if(O){let T=eb[I];E.push(`${T}=${O.join(sr)}`)}}),g.length&&E.push(`svc=${g.join(sr)}`),!((d=n.types)===null||d===void 0)&&d.length){let A=n.types.map(O=>typeof O=="string"?Qw[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:rs,data:`id=${A.join(sr)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:rs,data:E.join(Bp)});for(let I of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:rs,data:I+"."});return{id:0,type:"response",flags:I_,answers:[...f,...h]}})}static getUniqueDidSuffix(e){return e.split(":")[2]}},kt=class t{static createBep44PutMessage(e){return Nt(this,arguments,void 0,function*({dnsPacket:r,publicKeyBytes:n,signer:i}){let o=Math.ceil(Date.now()/1e3),s=tf(r),c=Fw.encode({seq:o,v:s}).subarray(1,-1);if(c.length>1e3)throw new re(ie.InvalidDidDocumentLength,`DNS packet exceeds the 1000 byte maximum size: ${c.length} bytes`);let a=yield i.sign({data:c});return{k:n,seq:o,sig:a,v:s}})}static identifierToIdentityKey(e){return Nt(this,arguments,void 0,function*({didUri:r}){let n=t.identifierToIdentityKeyBytes({didUri:r});return yield It.bytesToPublicKey({publicKeyBytes:n})})}static identifierToIdentityKeyBytes({didUri:e}){let r=me.parse(e);if(!r)throw new re(ie.InvalidDid,`Invalid DID URI: ${e}`);if(r.method!==rf.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${r.method}`);let n;try{n=ne.base32Z(r.id).toUint8Array()}catch{throw new re(ie.InvalidPublicKey,"Failed to decode method-specific identifier")}if(n.length!==32)throw new re(ie.InvalidPublicKeyLength,`Invalid public key length: ${n.length}`);return n}static identityKeyToIdentifier(e){return Nt(this,arguments,void 0,function*({identityKey:r}){let n=yield It.publicKeyToBytes({publicKey:r}),i=ne.uint8Array(n).toBase32Z();return`did:${rf.methodName}:${i}`})}static keyConverter(e){let n={Ed25519:It,"P-256":{publicKeyToBytes:i=>Nt(this,[i],void 0,function*({publicKey:o}){let s=yield Vt.publicKeyToBytes({publicKey:o});return yield Vt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Vt.bytesToPublicKey,privateKeyToBytes:Vt.privateKeyToBytes,bytesToPrivateKey:Vt.bytesToPrivateKey},secp256k1:{publicKeyToBytes:i=>Nt(this,[i],void 0,function*({publicKey:o}){let s=yield Dt.publicKeyToBytes({publicKey:o});return yield Dt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Dt.bytesToPublicKey,privateKeyToBytes:Dt.privateKeyToBytes,bytesToPrivateKey:Dt.bytesToPrivateKey},X25519:$a}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static parseBep44GetMessage(e){return Nt(this,arguments,void 0,function*({bep44Message:r}){let n=yield It.bytesToPublicKey({publicKeyBytes:r.k}),i=Fw.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!(yield It.verify({key:n,signature:r.sig,data:i})))throw new re(ie.InvalidSignature,"Invalid signature for DHT BEP44 message");return Ip(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(Bp).reduce((r,n)=>{let[i,o]=n.split("=");return r[i]=o,r},{})}static parseTxtDataToString(e){if(typeof e=="string")return e;if(e instanceof Uint8Array)return ne.uint8Array(e).toString();if(Array.isArray(e))return e.map(r=>this.parseTxtDataToString(r)).join("");throw new re(ie.InternalError,"Pkarr returned DNS TXT record with invalid data type")}static validatePreviousDidProof(e){return Nt(this,arguments,void 0,function*({newDid:r,previousDidProof:n}){let i=yield t.identifierToIdentityKey({didUri:n.previousDid}),o=t.identifierToIdentityKeyBytes({didUri:r}),s=ne.base64Url(n.signature).toUint8Array();if(!(yield It.verify({key:i,data:o,signature:s})))throw new re(ie.InvalidPreviousDidProof,"The previous DID proof is invalid.")})}static chunkDataIfNeeded(e){if(e.length<=255)return e;let r=[];for(let n=0;n<e.length;n+=255)r.push(e.slice(n,n+255));return r}};l();l();l();l();l();var Ye={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"};l();var Me=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var QJ=new Uint8Array(0);var tb=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};l();var rb=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},nb=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),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 C_(this,e)}},ib=class{constructor(e){this.decoders=e}or(e){return C_(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},C_=(t,e)=>new ib({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),ob=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new rb(e,r,n),this.decoder=new nb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},pC=({name:t,prefix:e,encode:r,decode:n})=>new ob(t,e,r,n);var yC=(t,e,r,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s},gC=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o},nf=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>pC({prefix:e,name:t,encode(i){return gC(i,n,r)},decode(i){return yC(i,n,r,t)}});var dZ=nf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),fZ=nf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),of=nf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),lZ=nf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var br=class t{static encode(e){return of.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Me(Ye.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return of.baseDecode(e)}static decodeAsString(e,r){let n=t.decodeAsBytes(e,r);return t.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}};l();var W_=Pn(P_(),1);l();l();var sb;(function(t){t.Public="public",t.Private="private"})(sb||(sb={}));var Kr=sb;var Rt=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===Kr.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Me(Ye.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Me(Ye.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Me(Ye.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Me(Ye.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Me(Ye.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===Kr.Private&&(e.d===void 0||e.d.length!==43))throw new Me(Ye.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Me(Ye.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!br.isBase64UrlString(e))throw new Me(Ye.IdNotUsingBase64UrlCharacterSet,`Key ID '${e}' is not a Base64URL string.`)}static validatePublicKeyPurposes(e){if(e===void 0)return;let r=new Set;for(let n of e){if(r.has(n))throw new Me(Ye.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var sf=class{};sf.hashAlgorithmInMultihashCode=18;sf.maxCanonicalizedDeltaSizeInBytes=1e3;var ar=sf;l();var $_=Pn(K_(),1);var Dn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=$_.default(r);return br.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?t.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}};l();l();l();l();var mC=q_,H_=128,wC=127,bC=~wC,xC=Math.pow(2,31);function q_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=xC;)e[r++]=t&255|H_,t/=128;for(;t&bC;)e[r++]=t&255|H_,t>>>=7;return e[r]=t|0,q_.bytes=r-n+1,e}var EC=cb,vC=128,V_=127;function cb(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw cb.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&V_)<<i:(s&V_)*Math.pow(2,i),i+=7}while(s>=vC);return cb.bytes=o-n,r}var SC=Math.pow(2,7),AC=Math.pow(2,14),TC=Math.pow(2,21),_C=Math.pow(2,28),IC=Math.pow(2,35),BC=Math.pow(2,42),RC=Math.pow(2,49),UC=Math.pow(2,56),OC=Math.pow(2,63),DC=function(t){return t<SC?1:t<AC?2:t<TC?3:t<_C?4:t<IC?5:t<BC?6:t<RC?7:t<UC?8:t<OC?9:10},kC={encode:mC,decode:EC,encodingLength:DC},NC=kC,cf=NC;var ab=(t,e=0)=>[cf.decode(t,e),cf.decode.bytes],ub=(t,e,r=0)=>(cf.encode(t,e,r),e),db=t=>cf.encodingLength(t);var fb=(t,e)=>{let r=e.byteLength,n=db(t),i=n+db(r),o=new Uint8Array(i+r);return ub(t,o,0),ub(r,o,n),o.set(e,i),new Op(t,r,e,o)},F_=t=>{let e=tb(t),[r,n]=ab(e),[i,o]=ab(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Op(r,i,s,e)};var Op=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var hb=({name:t,code:e,encode:r})=>new lb(t,e,r),lb=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?fb(this.code,r):r.then(n=>fb(this.code,n))}else throw Error("Unknown type, must be binary type")}};var j_=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Dp=hb({name:"sha2-256",code:18,encode:j_("SHA-256")}),WZ=hb({name:"sha2-512",code:19,encode:j_("SHA-512")});var af=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Ct=class t{static hash(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Dp.digest(e)).bytes;break;default:throw new Me(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Dp.encode(e);break;default:throw new Me(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e),i=yield t.hashAsNonMultihashBytes(n,r);return yield t.hashThenEncode(i,r)})}static hashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return br.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=br.decodeAsBytes(e,r);try{n=F_(i)}catch{throw new Me(Ye.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=ar.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Me(Ye.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var pb;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(pb||(pb={}));var uf=pb;l();var yb;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(yb||(yb={}));var pc=yb;var kp=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},ns=class t{static createCreateRequest(e){return kp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;Rt.validateEs256kOperationKey(r,Kr.Public),Rt.validateEs256kOperationKey(n,Kr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=ar.hashAlgorithmInMultihashCode,c=[{action:pc.Replace,document:e.document}],a={updateCommitment:yield Ct.canonicalizeThenDoubleHashThenEncode(n,s),patches:c};t.validateDeltaSize(a);let d={deltaHash:yield Ct.canonicalizeThenHashThenEncode(a,s),recoveryCommitment:yield Ct.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:uf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return kp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,Kr.Public);let r=ar.hashAlgorithmInMultihashCode,n=yield Ct.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},o=yield e.signer.sign({alg:"ES256K"},i);return{type:uf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return kp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,Kr.Public),Rt.validateEs256kOperationKey(e.nextRecoveryPublicKey,Kr.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=ar.hashAlgorithmInMultihashCode,n=yield Ct.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:pc.Replace,document:e.document}],o=yield Ct.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:o},c=yield Ct.canonicalizeThenHashThenEncode(s,r),u={recoveryCommitment:yield Ct.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:c},d=yield e.signer.sign({alg:"ES256K"},u);return{type:uf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return kp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.updatePublicKey,Kr.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,Kr.Public),t.validateServices(e.servicesToAdd),t.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let g of e.idsOfServicesToRemove)Rt.validateId(g);if(e.idsOfPublicKeysToRemove!==void 0)for(let g of e.idsOfPublicKeysToRemove)Rt.validateId(g);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let g={action:pc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:pc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:pc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:pc.RemovePublicKeys,ids:s};r.push(g)}let c=ar.hashAlgorithmInMultihashCode,a=yield Ct.canonicalizeThenHashThenEncode(e.updatePublicKey,c),u=yield Ct.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,c),d={patches:r,updateCommitment:u},f=yield Ct.canonicalizeThenHashThenEncode(d,c),h={updateKey:e.updatePublicKey,deltaHash:f},p=yield e.signer.sign({alg:"ES256K"},h);return{type:uf.Update,didSuffix:e.didSuffix,revealValue:a,delta:d,signedData:p}})}static validateDidSuffix(e){Ct.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Me(Ye.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Rt.validateId(n.id),r.has(n.id))throw new Me(Ye.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),Rt.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(t.validateService(n),r.has(n.id))throw new Me(Ye.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){Rt.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new Me(Ye.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Me(Ye.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&W_.parse(e.serviceEndpoint).error!==void 0)throw new Me(Ye.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=Dn.canonicalizeAsBytes(e);if(r.length>ar.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${ar.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Me(Ye.DeltaExceedsMaximumSize,n)}}};var G_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Ja=class t{static createLongFormDid(e){return G_(this,void 0,void 0,function*(){let r=yield ns.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;ar.network===void 0||ar.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${ar.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=Dn.canonicalizeAsBytes(o),c=br.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return G_(this,void 0,void 0,function*(){let r=Dn.canonicalizeAsBytes(e),n=yield Ct.hash(r,ar.hashAlgorithmInMultihashCode);return br.encode(n)})}};l();l();var z_;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(z_||(z_={}));l();var Y_;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(Y_||(Y_={}));l();var is=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},li;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(li||(li={}));var PC={Ed25519:li.Ed25519,ES256K:li.secp256k1,ES256:li.secp256r1,"P-256":li.secp256r1,secp256k1:li.secp256k1,secp256r1:li.secp256r1},J_="https://ion.tbd.engineering",gb=class t extends an{static create(){return is(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in PC)))throw new Error("One or more verification method algorithms are not supported");let d=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(d&&d.length!==new Set(d).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let f={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},h=[];for(let T of(s=r.verificationMethods)!==null&&s!==void 0?s:[f]){let M=yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M});h.push({id:T.id,publicKeyJwk:q,purposes:(c=T.purposes)!==null&&c!==void 0?c:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let p=yield e.generateKey({algorithm:li.secp256k1}),g=yield e.getPublicKey({keyUri:p}),y=yield e.generateKey({algorithm:li.secp256k1}),E=yield e.getPublicKey({keyUri:y}),S=yield yc.computeLongFormDidUri({recoveryKey:g,updateKey:E,services:(a=r.services)!==null&&a!==void 0?a:[],verificationMethods:h}),{didDocument:I,didResolutionMetadata:A}=yield t.resolve(S,{gatewayUri:r.gatewayUri});if(I===null)throw new Error(`Unable to resolve DID during creation: ${A?.error}`);let O=new mr({uri:S,document:I,metadata:{published:!1,canonicalId:S.split(":",3).join(":"),recoveryKey:g,updateKey:E},keyManager:e});if(!((u=r.publish)!==null&&u!==void 0)||u){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static getSigningMethod(e){return is(this,arguments,void 0,function*({didDocument:r,methodId:n}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a;return c.id===(n??((a=r.assertionMethod)===null||a===void 0?void 0:a[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return is(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield mr.import({portableDid:r,keyManager:n})})}static publish(e){return is(this,arguments,void 0,function*({did:r,gatewayUri:n=J_}){var i,o,s;let c=(o=(i=r.document.verificationMethod)===null||i===void 0?void 0:i.map(d=>({id:d.id,publicKeyJwk:d.publicKeyJwk,purposes:e_({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield yc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield yc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=yc.appendPathToUrl({baseUrl:n,path:"/operations"}),f=yield fetch(d,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:f.ok}),didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:ie.InternalError,errorMessage:`Failed to publish DID document for: ${r.uri}`}}}})}static resolve(e){return is(this,arguments,void 0,function*(r,n={}){var i,o;let s=me.parse(r);if(!s)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:J_;try{let a=yc.appendPathToUrl({baseUrl:c,path:`/identifiers/${r}`}),u=yield fetch(a);if(!u.ok)throw new re(ie.NotFound,`Unable to find DID document for: ${r}`);let{didDocument:d,didDocumentMetadata:f}=yield u.json();return Object.assign(Object.assign(Object.assign({},lt),d&&{didDocument:d}),{didDocumentMetadata:Object.assign({published:(o=f?.method)===null||o===void 0?void 0:o.published},f)})}catch(a){if(!(a instanceof re))throw new Error(a);return Object.assign(Object.assign({},lt),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};gb.methodName="ion";var yc=class t{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static computeLongFormDidUri(e){return is(this,arguments,void 0,function*({recoveryKey:r,updateKey:n,services:i,verificationMethods:o}){let s=yield t.createIonDocument({services:i,verificationMethods:o}),c=t.normalizeJwk(r),a=t.normalizeJwk(n);return yield Ja.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return is(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield ns.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return is(this,arguments,void 0,function*({services:r,verificationMethods:n}){var i,o;let s=[];for(let u of n){let d=(o=(i=u.id)!==null&&i!==void 0?i:u.publicKeyJwk.kid)!==null&&o!==void 0?o:yield ge({jwk:u.publicKeyJwk});d=`${d.split("#").pop()}`;let f={id:d,publicKeyJwk:t.normalizeJwk(u.publicKeyJwk),purposes:u.purposes,type:"JsonWebKey2020"};s.push(f)}let c=r.map(u=>Object.assign(Object.assign({},u),{id:`${u.id.split("#").pop()}`}));return{publicKeys:s,services:c}})}static normalizeJwk(e){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}};l();var Np=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},mb=class t extends an{static create(){return Np(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=ne.object(u).toBase64Url(),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f)).didDocument;return new mr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return Np(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=(n=r.verificationMethod)!==null&&n!==void 0?n:[];if(!(o&&o.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o})}static import(e){return Np(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield mr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return Np(this,void 0,void 0,function*(){let n=me.parse(e),i;try{i=ne.base64Url(n.id).toObject()}catch{}if(!n||!i)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"methodNotSupported"}});let o={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},s=`${o.id}#0`;switch(o.verificationMethod=[{id:s,type:"JsonWebKey",controller:o.id,publicKeyJwk:i}],o.authentication=[s],o.assertionMethod=[s],o.capabilityInvocation=[s],o.capabilityDelegation=[s],o.keyAgreement=[s],i.use){case"sig":{delete o.keyAgreement;break}case"enc":{delete o.authentication,delete o.assertionMethod,delete o.capabilityInvocation,delete o.capabilityDelegation;break}}return Object.assign(Object.assign({},lt),{didDocument:o})})}};mb.methodName="jwk";l();var kn=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},oo;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(oo||(oo={}));var wb={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1",X25519KeyAgreementKey2020:"https://w3id.org/security/suites/x25519-2020/v1"},MC={Ed25519:oo.Ed25519,ES256K:oo.secp256k1,ES256:oo.secp256r1,"P-256":oo.secp256r1,secp256k1:oo.secp256k1,secp256r1:oo.secp256r1,X25519:oo.X25519},bb=class t extends an{static create(){return kn(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=yield xr.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new mr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return kn(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=r.assertionMethod||[],s=(n=r.verificationMethod)===null||n===void 0?void 0:n.find(c=>c.id===o);if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return kn(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield mr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return kn(this,void 0,void 0,function*(){try{let n=yield t.createDocument({didUri:e,options:r});return Object.assign(Object.assign({},lt),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},lt),{didResolutionMetadata:Object.assign({error:n.code},n.message&&{errorMessage:n.message})})}})}static createDocument(e){return kn(this,arguments,void 0,function*({didUri:r,options:n={}}){let{defaultContext:i="https://www.w3.org/ns/did/v1",enableEncryptionKeyDerivation:o=!1,enableExperimentalPublicKeyTypes:s=!1,publicKeyFormat:c="JsonWebKey2020"}=n,a={id:""},u=me.parse(r);if(!u)throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let d=u.id;if(u.method!==t.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${u.method}`);if(!t.validateIdentifier(u))throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let f=yield t.createSignatureMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:c}});if(a.id=u.uri,a.verificationMethod=[f],a.authentication=[f.id],a.assertionMethod=[f.id],a.capabilityInvocation=[f.id],a.capabilityDelegation=[f.id],o===!0){let g=c==="Ed25519VerificationKey2020"?"X25519KeyAgreementKey2020":"JsonWebKey2020",y=yield this.createEncryptionMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:g}});a.verificationMethod.push(y),a.keyAgreement=[y.id]}let h=[i];return QT({didDocument:a}).forEach(g=>{let y=wb[g];h.push(y)}),a["@context"]=h,a})}static createEncryptionMethod(e){return kn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u}=yield t.deriveEncryptionKey({multibaseValue:n}),d=a.byteLength,f=xr.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=Pw({keyBytes:a,multicodecCode:u});c.id=`${r}#${h}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in wb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","X25519KeyAgreementKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="X25519KeyAgreementKey2020"&&(c.publicKeyMultibase=h),s==="JsonWebKey2020"){let{crv:g}=yield xr.multicodecToJwk({code:u});c.publicKeyJwk=yield xr.keyConverter(g).bytesToPublicKey({publicKeyBytes:a})}return c})}static createSignatureMethod(e){return kn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u,multicodecName:d}=Mw({multibaseKeyId:n}),f=a.byteLength,h=xr.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(f!==h)throw new re(ie.InvalidPublicKeyLength,`Expected ${f} bytes. Actual: ${h}`);let p=!1;switch(d){case"secp256k1-pub":p=yield Dt.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":p=yield It.validatePublicKey({publicKeyBytes:a});break;case"x25519-pub":p=!0;break}if(!p)throw new re(ie.InvalidPublicKey,"Invalid public key detected.");c.id=`${r}#${n}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in wb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="Ed25519VerificationKey2020"&&(c.publicKeyMultibase=n),s==="JsonWebKey2020"){let{crv:y}=yield xr.multicodecToJwk({code:u});c.publicKeyJwk=yield xr.keyConverter(y).bytesToPublicKey({publicKeyBytes:a})}return c})}static deriveEncryptionKey(e){return kn(this,arguments,void 0,function*({multibaseValue:r}){let n={keyBytes:new Uint8Array,multicodecCode:0},{keyBytes:i,multicodecCode:o}=Mw({multibaseKeyId:r});if(o===237){let s=yield xr.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield It.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield xr.keyConverter("Ed25519").publicKeyToBytes({publicKey:c}),multicodecCode:236}}return n})}static validateIdentifier(e){let{method:r,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&r==="key"&&Number("1")>0&&ia(n)==="String"&&n.startsWith("z")}};bb.methodName="key";var xr=class t{static jwkToMulticodec(e){return kn(this,arguments,void 0,function*({jwk:r}){let n=[];r.crv&&(n.push(r.crv),r.d?n.push("private"):n.push("public"));let i=n.join(":"),o=t.JWK_TO_MULTICODEC[i];if(o===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${i}'`);return{code:Yt.getCodeFromName({name:o}),name:o}})}static keyCompressor(e){let n={"P-256":Vt.compressPublicKey,secp256k1:Dt.compressPublicKey}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static keyConverter(e){let n={Ed25519:It,"P-256":Vt,secp256k1:Dt,X25519:$a}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static multicodecToJwk(e){return kn(this,arguments,void 0,function*({code:r,name:n}){if(!(n?!r:r))throw new Error("Either 'name' or 'code' must be defined, but not both.");n=n===void 0?Yt.getNameFromCode({code:r}):n;let i=n,o=t.MULTICODEC_TO_JWK[i];if(o===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return Object.assign({},o)})}static publicKeyToMultibaseId(e){return kn(this,arguments,void 0,function*({publicKey:r}){var n;if(!(r?.crv&&r.crv in MC))throw new re(ie.InvalidPublicKeyType,`Public key contains an unsupported key type: ${(n=r?.crv)!==null&&n!==void 0?n:"undefined"}`);let i=yield t.keyConverter(r.crv).publicKeyToBytes({publicKey:r});/^(secp256k1|P-256|P-384|P-521)$/.test(r.crv)&&(i=yield t.keyCompressor(r.crv)({publicKeyBytes:i}));let{name:o}=yield t.jwkToMulticodec({jwk:r});return Pw({keyBytes:i,multicodecName:o})})}};xr.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv","X25519:public":"x25519-pub","X25519:private":"x25519-priv"};xr.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};xr.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""},"x25519-pub":{crv:"X25519",kty:"OKP",x:""},"x25519-priv":{crv:"X25519",kty:"OKP",x:"",d:""}};l();var KC=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},xb=class t extends an{static resolve(e,r){return KC(this,void 0,void 0,function*(){let n=me.parse(e);if(!n)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"methodNotSupported"}});let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let o=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let s=yield fetch(o);if(!s.ok)throw new Error("HTTP error status code returned");let c=yield s.json();return Object.assign(Object.assign({},lt),{didDocument:c})}catch{return Object.assign(Object.assign({},lt),{didResolutionMetadata:{error:"notFound"}})}})}};xb.methodName="web";l();var jC=Pn(X_(),1),WC=Pn(Yg(),1);l();l();var at=class t{static absoluteDidUrl(e,r){if(typeof e=="string"&&e.length!==0)return e.startsWith("#")?`${r}${e}`:e}static relationshipMethodId(e,r){let n=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.id:e;return t.absoluteDidUrl(n,r)}static isDidVerificationMethod(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"controller"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.controller!="string")}static isDidService(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"serviceEndpoint"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.serviceEndpoint!="string")}static getVerificationMethods(e){if(!e)throw new qe("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys(Li).forEach(n=>{r.push(...e[n]?.filter(t.isDidVerificationMethod)??[])}),r}static deriveRootCapability(e){return{"@context":"https://w3id.org/zcap/v1",id:`urn:zcap:root:${encodeURIComponent(e)}`,controller:e,invocationTarget:e}}static dereferenceZcapId(e){let r={},[n,i,o,s]=e.split(":")??[];if([n,i,o,s].length!==4)throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!n||n!=="urn")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!i||i!=="zcap")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!o||o!=="root")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let a=decodeURIComponent(s);return r.id=e,r.controller=a,r.invocationTarget=a,r}};l();l();l();l();l();l();l();function Q_(t,e,r){return t&e^~t&r}function eI(t,e,r){return t&e^t&r^e&r}var Lp=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Bl(this.buffer)}update(e){Xc(this),Se(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Bl(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xc(this),Rv(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Os(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let c=Bl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},so=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var GC=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]),os=new Uint32Array(64),Eb=class extends Lp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)os[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=os[f-15],p=os[f-2],g=xn(h,7)^xn(h,18)^h>>>3,y=xn(p,17)^xn(p,19)^p>>>10;os[f]=y+os[f-7]+g+os[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=xn(c,6)^xn(c,11)^xn(c,25),p=d+h+Q_(c,a,u)+GC[f]+os[f]|0,y=(xn(n,2)^xn(n,13)^xn(n,22))+eI(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Os(os)}destroy(){this.set(0,0,0,0,0,0,0,0),Os(this.buffer)}},vb=class extends Eb{A=so[0]|0;B=so[1]|0;C=so[2]|0;D=so[3]|0;E=so[4]|0;F=so[5]|0;G=so[6]|0;H=so[7]|0;constructor(){super(32)}};var Pp=Ov(()=>new vb,Dv(1));l();l();var ur=BigInt(0),er=BigInt(1),mc=BigInt(2),nI=BigInt(3),iI=BigInt(4),oI=BigInt(5),zC=BigInt(7),sI=BigInt(8),YC=BigInt(9),cI=BigInt(16);function Nn(t,e){let r=t%e;return r>=ur?r:e+r}function $r(t,e,r){let n=t;for(;e-- >ur;)n*=n,n%=r;return n}function tI(t,e){if(t===ur)throw new Error("invert: expected non-zero number");if(e<=ur)throw new Error("invert: expected positive modulus, got "+e);let r=Nn(t,e),n=e,i=ur,o=er,s=er,c=ur;for(;r!==ur;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==er)throw new Error("invert: does not exist");return Nn(i,e)}function Ab(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function aI(t,e){let r=(t.ORDER+er)/iI,n=t.pow(e,r);return Ab(t,n,e),n}function JC(t,e){let r=(t.ORDER-oI)/sI,n=t.mul(e,mc),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,mc),i),c=t.mul(o,t.sub(s,t.ONE));return Ab(t,c,e),c}function ZC(t){let e=eu(t),r=uI(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+zC)/cI;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),E=c.cmov(u,d,y);return Ab(c,E,a),E}}function uI(t){if(t<nI)throw new Error("sqrt is not defined for small field");let e=t-er,r=0;for(;e%mc===ur;)e/=mc,r++;let n=mc,i=eu(t);for(;rI(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return aI;let o=i.pow(n,e),s=(e+er)/mc;return function(a,u){if(a.is0(u))return u;if(rI(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let E=er<<BigInt(d-g-1),S=a.pow(f,E);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function XC(t){return t%iI===nI?aI:t%sI===oI?JC:t%cI===YC?ZC(t):uI(t)}var QC=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Tb(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=QC.reduce((n,i)=>(n[i]="function",n),e);return Ju(t,r),t}function eL(t,e,r){if(r<ur)throw new Error("invalid exponent, negatives unsupported");if(r===ur)return t.ONE;if(r===er)return e;let n=t.ONE,i=e;for(;r>ur;)r&er&&(n=t.mul(n,i)),i=t.sqr(i),r>>=er;return n}function Mp(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function rI(t,e){let r=(t.ORDER-er)/mc,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function tL(t,e){e!==void 0&&zn(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Sb=class{ORDER;BITS;BYTES;isLE;ZERO=ur;ONE=er;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=ur)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:i,nByteLength:o}=tL(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Nn(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ur<=e&&e<this.ORDER}is0(e){return e===ur}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&er)===er}neg(e){return Nn(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Nn(e*e,this.ORDER)}add(e,r){return Nn(e+r,this.ORDER)}sub(e,r){return Nn(e-r,this.ORDER)}mul(e,r){return Nn(e*r,this.ORDER)}pow(e,r){return eL(this,e,r)}div(e,r){return Nn(e*tI(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return tI(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=XC(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?C0(e,this.BYTES):Ul(e,this.BYTES)}fromBytes(e,r=!1){Se(e);let{_lengths:n,BYTES:i,isLE:o,ORDER:s,_mod:c}=this;if(n){if(!n.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(i);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=o?N0(e):Uo(e);if(c&&(a=Nn(a,s)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Mp(this,e)}cmov(e,r,n){return n?r:e}};function eu(t,e={}){return new Sb(t,e)}function dI(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function _b(t){let e=dI(t);return e+Math.ceil(e/2)}function Kp(t,e,r=!1){Se(t);let n=t.length,i=dI(e),o=_b(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?N0(t):Uo(t),c=Nn(s,e-er)+er;return r?C0(c,i):Ul(c,i)}var tu=BigInt(0),wc=BigInt(1);function df(t,e){let r=e.negate();return t?r:e}function Ub(t,e){let r=Mp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function pI(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ib(t,e){pI(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Yu(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function fI(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=wc);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}var Bb=new WeakMap,yI=new WeakMap;function Rb(t){return yI.get(t)||1}function lI(t){if(t!==tu)throw new Error("invalid wNAF")}var $p=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>tu;)r&wc&&(n=n.add(i)),i=i.double(),r>>=wc;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Ib(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=Ib(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=fI(n,c,s);n=a,d?o=o.add(df(h,r[p])):i=i.add(df(f,r[u]))}return lI(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Ib(e,this.bits);for(let s=0;s<o.windows&&n!==tu;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=fI(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return lI(n),i}getPrecomputes(e,r,n){let i=Bb.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Bb.set(r,i))),i}cached(e,r,n){let i=Rb(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Rb(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){pI(r,this.bits),yI.set(e,r),Bb.delete(e)}hasCache(e){return Rb(e)!==1}};function gI(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>tu||n>tu;)r&wc&&(o=o.add(i)),n&wc&&(s=s.add(i)),i=i.double(),r>>=wc,n>>=wc;return{p1:o,p2:s}}function hI(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Tb(e),e}else return eu(t,{isLE:r})}function mI(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>tu))throw new Error(`CURVE.${a} must be positive bigint`)}let i=hI(e.p,r.Fp,n),o=hI(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}function Hp(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var Vp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(Il(e),Se(r,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,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Os(i)}update(e){return Xc(this),this.iHash.update(e),this}digestInto(e){Xc(this),Se(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:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ob=(t,e,r)=>new Vp(t,e).update(r).digest();Ob.create=(t,e)=>new Vp(t,e);var wI=(t,e)=>(t+(t>=0?e:-e)/bI)/e;function rL(t,e,r){let[[n,i],[o,s]]=e,c=wI(s*t,r),a=wI(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<co,h=d<co;f&&(u=-u),h&&(d=-d);let p=Yu(Math.ceil(L0(r)/2))+ru;if(u<co||u>=p||d<co||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function kb(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Db(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Gu(r.lowS,"lowS"),Gu(r.prehash,"prehash"),r.format!==void 0&&kb(r.format),r}var Nb=class extends Error{constructor(e=""){super(e)}},ss={Err:Nb,_tlv:{encode:(t,e)=>{let{Err:r}=ss;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=zu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?zu(i.length/2|128):"";return zu(t)+o+i+e},decode(t,e){let{Err:r}=ss,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=ss;if(t<co)throw new e("integer: negative integers are not allowed");let r=zu(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=ss;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Uo(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=ss,i=Se(t,void 0,"signature"),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=ss,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},co=BigInt(0),ru=BigInt(1),bI=BigInt(2),qp=BigInt(3),nL=BigInt(4);function xI(t,e={}){let r=mI("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Ju(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=vI(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,_,D){let{x,y:U}=_.toAffine(),L=n.toBytes(x);if(Gu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return lr(EI(N),L)}else return lr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){Se(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,x=G.length,U=G[0],L=G.subarray(1);if(x===_&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(x===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!E(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${x}, expected compressed=${_} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let _=n.sqr(G),D=n.mul(_,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function E(G,_){let D=n.sqr(_),x=y(G);return n.eql(D,x)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,qp),nL),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,I)))throw new Error("bad curve params: a or b");function A(G,_,D=!1){if(!n.isValid(_)||D&&n.is0(_))throw new Error(`bad point coordinate ${G}`);return _}function O(G){if(!(G instanceof $))throw new Error("Weierstrass Point expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return rL(G,a.basises,i.ORDER)}let M=P0((G,_)=>{let{X:D,Y:x,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:x};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(x,_),C=n.mul(U,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=P0(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:_,y:D}=G.toAffine();if(!n.isValid(_)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(_,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,_,D,x,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=df(x,_),D=df(U,D),_.add(D)}class ${static BASE=new $(o.Gx,o.Gy,n.ONE);static ZERO=new $(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(_,D,x){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:x}=_||{};if(!_||!n.isValid(D)||!n.isValid(x))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(x)?$.ZERO:new $(D,x,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(Se(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ks(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(qp),this}assertValidity(){q(this)}hasEvenY(){let{y:_}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(_)}equals(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(x,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:_,b:D}=o,x=n.mul(D,qp),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(_,P),C=n.mul(x,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(x,P),z=n.mul(_,z),W=n.sub(V,z),W=n.mul(_,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,qp),W=n.mul(D,L),Y=n.mul(x,N),Z=n.mul(U,R),ue=n.add(D,x),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(x,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(_){return this.add(_.negate())}is0(){return this.equals($.ZERO)}multiply(_){let{endo:D}=e;if(!i.isValidNot0(_))throw new Error("invalid scalar: out of range");let x,U,L=N=>Q.cached(this,N,R=>Ub($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(_),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),x=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);x=N,U=R}return Ub($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===co||x.is0())return $.ZERO;if(_===ru)return x;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=gI($,x,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(x,_)}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===ru?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===ru?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Gu(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Ds(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=i.BITS,Q=new $p($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function EI(t){return Uint8Array.of(t?2:3)}function vI(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function iL(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ns,i=Object.assign(vI(t.Fp,r),{seed:_b(r.ORDER)});function o(p){try{let g=r.fromBytes(p);return r.isValidNot0(g)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:E}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==E?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Kp(Se(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(g)}function u(p){let{secretKey:g,publicKey:y,publicKeyUncompressed:E}=i;if(!Wu(p)||"_lengths"in r&&r._lengths||g===y)return;let S=Se(p,void 0,"key").length;return S===y||S===E}function d(p,g,y=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(g)===!1)throw new Error("second arg must be public key");let E=r.fromBytes(p);return t.fromBytes(g).multiply(E).toBytes(y)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c},h=Hp(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function SI(t,e,r={}){Il(e),Ju(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||Ns,i=r.hmac||((D,x)=>Ob(e,D,x)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=iL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*bI<o.ORDER;function E(D){let x=c>>ru;return D>x}function S(D,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return x}function I(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,x){kb(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return Se(D,L)}class O{r;s;recovery;constructor(x,U,L){if(this.r=S("r",x),this.s=S("s",U),L!=null){if(I(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(x,U=g.format){A(x,U);let L;if(U==="der"){let{r:P,s:V}=ss.toSig(Se(x));return new O(P,V)}U==="recovered"&&(L=x[0],U="compact",x=x.subarray(1));let N=p.signature/2,R=x.subarray(0,N),C=x.subarray(N,N*2);return new O(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(x,U){return this.fromBytes(ks(x),U)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new O(this.r,this.s,x)}recoverPublicKey(x){let{r:U,s:L}=this,N=this.assertRecovery(),R=N===2||N===3?U+c:U;if(!o.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let C=o.toBytes(R),P=t.fromBytes(lr(EI((N&1)===0),C)),V=s.inv(R),J=M(Se(x,void 0,"msgHash")),z=s.create(-J*V),W=s.create(L*V),Y=t.BASE.multiplyUnsafe(z).add(P.multiplyUnsafe(W));if(Y.is0())throw new Error("invalid recovery: point at infinify");return Y.assertValidity(),Y}hasHighS(){return E(this.s)}toBytes(x=g.format){if(kb(x),x==="der")return ks(ss.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return x==="recovered"?(I(),lr(Uint8Array.of(this.assertRecovery()),N,R)):lr(N,R)}toHex(x){return Ds(this.toBytes(x))}}let T=r.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let U=Uo(x),L=x.length*8-a;return L>0?U>>BigInt(L):U},M=r.bits2int_modN||function(x){return s.create(T(x))},q=Yu(a);function j(D){return Lv("num < 2^"+a,D,co,q),s.toBytes(D)}function $(D,x){return Se(D,void 0,"message"),x?Se(e(D),void 0,"prehashed message"):D}function X(D,x,U){let{lowS:L,prehash:N,extraEntropy:R}=Db(U,g);D=$(D,N);let C=M(D),P=s.fromBytes(x);if(!s.isValidNot0(P))throw new Error("invalid private key");let V=[j(P),j(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(Se(Y,void 0,"extraEntropy"))}let J=lr(...V),z=C;function W(Y){let Z=T(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===co)return;let Ue=s.create(ue*s.create(z+ce*P));if(Ue===co)return;let Ke=(ee.x===ce?0:2)|Number(ee.y&ru),Je=Ue;return L&&E(Ue)&&(Je=s.neg(Ue),Ke^=1),new O(ce,Je,y?void 0:Ke)}return{seed:J,k2sig:W}}function Q(D,x,U={}){let{seed:L,k2sig:N}=X(D,x,U);return Pv(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=Db(L,g);if(U=Se(U,void 0,"publicKey"),x=$(x,R),!Wu(D)){let P=D instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}A(D,C);try{let P=O.fromBytes(D,C),V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=M(x),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,x,U={}){let{prehash:L}=Db(U,g);return x=$(x,L),O.fromBytes(D,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:Q,verify:G,recoverPublicKey:_,Signature:O,hash:e})}var Wp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},oL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},sL=BigInt(0),Cb=BigInt(2);function cL(t){let e=Wp.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=$r(d,r,e)*d%e,h=$r(f,r,e)*d%e,p=$r(h,Cb,e)*u%e,g=$r(p,i,e)*p%e,y=$r(g,o,e)*g%e,E=$r(y,c,e)*y%e,S=$r(E,a,e)*E%e,I=$r(S,c,e)*y%e,A=$r(I,r,e)*d%e,O=$r(A,s,e)*g%e,T=$r(O,n,e)*u%e,M=$r(T,Cb,e);if(!Fp.eql(Fp.sqr(M),t))throw new Error("Cannot find square root");return M}var Fp=eu(Wp.p,{sqrt:cL}),bc=xI(Wp,{Fp,endo:oL}),un=SI(bc,Pp),AI={};function jp(t,...e){let r=AI[t];if(r===void 0){let n=Pp(Cv(t));r=lr(n,n),AI[t]=r}return Pp(lr(r,...e))}var Pb=t=>t.toBytes(!0).slice(1),Mb=t=>t%Cb===sL;function Lb(t){let{Fn:e,BASE:r}=bc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:Mb(i.y)?n:e.neg(n),bytes:Pb(i)}}function _I(t){let e=Fp;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Mb(i)||(i=e.neg(i));let o=bc.fromAffine({x:t,y:i});return o.assertValidity(),o}var ff=Uo;function II(...t){return bc.Fn.create(ff(jp("BIP0340/challenge",...t)))}function TI(t){return Lb(t).bytes}function aL(t,e,r=Ns(32)){let{Fn:n}=bc,i=Se(t,void 0,"message"),{bytes:o,scalar:s}=Lb(e),c=Se(r,32,"auxRand"),a=n.toBytes(s^ff(jp("BIP0340/aux",c))),u=jp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Lb(u),h=II(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!BI(p,i,o))throw new Error("sign: Invalid signature produced");return p}function BI(t,e,r){let{Fp:n,Fn:i,BASE:o}=bc,s=Se(t,64,"signature"),c=Se(e,void 0,"message"),a=Se(r,32,"publicKey");try{let u=_I(ff(a)),d=ff(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=ff(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=II(i.toBytes(d),Pb(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!Mb(y)||g!==d)}catch{return!1}}var Gp=(()=>{let r=(n=Ns(48))=>Kp(n,Wp.n);return{keygen:Hp(r,TI),getPublicKey:TI,sign:aL,verify:BI,Point:bc,utils:{randomSecretKey:r,taggedHash:jp,lift_x:_I,pointToBytes:Pb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function uL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function UI(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Kb(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function OI(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function $b(t){if(!Array.isArray(t))throw new Error("array expected")}function DI(t,e){if(!UI(!0,e))throw new Error(`${t}: array of strings expected`)}function dL(t,e){if(!UI(!1,e))throw new Error(`${t}: array of numbers expected`)}function fL(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function lL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;DI("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>($b(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>($b(i),i.map(o=>{Kb("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function hL(t=""){return Kb("join",t),{encode:e=>(DI("join.decode",e),e.join(t)),decode:e=>(Kb("join.decode",e),e.split(t))}}function RI(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if($b(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(OI(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}function pL(t){OI(t);let e=2**8;return{encode:r=>{if(!uL(r))throw new Error("radix.encode input should be Uint8Array");return RI(Array.from(r),e,t)},decode:r=>(dL("radix.decode",r),Uint8Array.from(RI(r,t,e)))}}var yL=t=>fL(pL(58),lL(t),hL("")),nu=yL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var kI=new Uint8Array([231,1]),pt=class t{#e;#t={prefix:kI,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Tr(e);if(!r||r.length!==33)throw new Is("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!un.utils.isValidPublicKey(r))throw new Is("Invalid argument: not a valid secp256k1 compressed point","CONSTRUCTOR_ERROR",{keyBytes:r});this.#e=new Uint8Array(r),this.#t.encoded=this.encode(),this.#t.key=[...this.#t.prefix,...this.compressed]}get compressed(){return new Uint8Array(this.#e)}get uncompressed(){return un.Point.fromBytes(this.compressed).toBytes(!1)}get xOnly(){return this.compressed.slice(1)}get parity(){let e=this.compressed[0];if(![2,3].includes(e))throw new Is("Invalid state: parity byte must be 2 or 3","PARITY_ERROR",{parity:e});return e}get isEven(){return this.parity===2}get x(){return this.compressed.slice(1,33)}get y(){return this.uncompressed.slice(33,65)}get multibase(){return{prefix:new Uint8Array(this.#t.prefix),key:[...this.#t.key],encoded:this.#t.encoded}}get hex(){return Lt(this.compressed)}get point(){return{x:this.x,y:this.y}}bip340(){return this.xOnly}decode(){return nu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(kI);return r.push(...e),"z"+nu.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return un.verify(e,r,this.compressed);if(n.scheme==="schnorr")return Gp.verify(e,r,this.x);throw new Is(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return Qc(this.compressed,e.compressed)}toJSON(){return{hex:this.hex,multibase:this.multibase,point:{x:Array.from(this.x),y:Array.from(this.y),parity:this.parity}}}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromJSON(e){return new t(Uint8Array.from([e.point.parity,...e.point.x]))}};l();var NI=new Uint8Array([129,38]),gL=Lt(ke(NI)),Hr=class t{#e;#t;#n;constructor(e){let r=e instanceof Uint8Array,n=typeof e=="bigint";if(!r&&!n)throw new jn("Invalid entropy: must be a valid byte array (32) or bigint","CONSTRUCTOR_ERROR");if(r&&e.length===32&&(this.#e=new Uint8Array(e),this.#t=t.toSecret(this.#e)),n&&e>=1n&&e<un.Point.Fn.ORDER&&(this.#e=t.toBytes(e),this.#t=e),!this.#e||this.#e.length!==32)throw new jn("Invalid bytes: must be a valid 32-byte secret key","CONSTRUCTOR_ERROR");if(!this.#t||this.#t<1n||this.#t>=un.Point.Fn.ORDER)throw new jn("Invalid seed: must be valid bigint","CONSTRUCTOR_ERROR");this.#n=this.encode()}destroy(){this.#e&&this.#e.fill(0),this.#t=void 0,this.#n=""}get bytes(){return new Uint8Array(this.#e)}get seed(){return BigInt(this.#t)}get hex(){return Lt(this.bytes)}get multibase(){return this.#n}encode(){let e=Array.from(this.bytes),r=Array.from(NI);return r.push(...e),"z"+nu.encode(Uint8Array.from(r))}equals(e){return Qc(this.bytes,e.bytes)}computePublicKey(){return new pt(un.getPublicKey(this.bytes))}toJSON(){return{type:"Secp256k1SecretKey"}}exportJSON(){return{bytes:Array.from(this.bytes),seed:this.seed.toString(),hex:this.hex}}toString(){return"[Secp256k1SecretKey]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[Secp256k1SecretKey]"}isValid(){return un.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return un.sign(e,this.bytes);if(r.scheme==="schnorr")return Gp.sign(e,this.bytes);throw new jn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=nu.decode(e.slice(1));if(r.length!==34)throw new jn("Invalid argument: must be 34 byte secretKeyMultibase","DECODE_MULTIBASE_ERROR");let n=r.slice(0,2);if(Lt(ke(n))!==gL)throw new jn(`Invalid prefix: malformed multibase prefix ${n}`,"DECODE_MULTIBASE_ERROR");return r}static fromJSON(e){return new t(new Uint8Array(e.bytes))}static toSecret(e){return e.reduce((r,n)=>r<<8n|BigInt(n),0n)}static toBytes(e){let r=Uint8Array.from({length:32},(n,i)=>Number(e>>BigInt(8*(31-i))&BigInt(255)));if(!un.utils.isValidSecretKey(r))throw new jn("Invalid secret key: secret out of valid range","SET_PRIVATE_KEY_ERROR");return new Uint8Array(r)}static fromBigInt(e){return new t(t.toBytes(e))}static random(){let e;do e=_r(32);while(!un.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var ao=class t{#e;#t;constructor(e={}){if(!e.publicKey&&!e.secretKey)throw new wn("Argument missing: must at least provide a publicKey","CONSTRUCTOR_ERROR");if(e.secretKey instanceof Uint8Array?this.#e=new Hr(e.secretKey):e.secretKey instanceof Hr&&(this.#e=e.secretKey),e.publicKey instanceof pt?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new pt(e.publicKey):this.#t=this.#e.computePublicKey(),this.#e&&e.publicKey){let r=this.#e.computePublicKey();if(!this.#t.equals(r))throw new wn("Public key does not match secret key","CONSTRUCTOR_ERROR")}}get secretKey(){if(!this.#e)throw new wn("Secret key not available","SECRET_KEY_ERROR");if(!this.#e.isValid())throw new wn("Secret key is not valid","SECRET_KEY_ERROR");return this.#e}set publicKey(e){if(this.#e){let r=this.#e.computePublicKey();if(!e.equals(r))throw new wn("Public key does not match secret key","PUBLIC_KEY_ERROR")}this.#t=e}get publicKey(){return this.#t}get hasSecretKey(){return!!this.#e}get raw(){return{public:this.publicKey.compressed,secret:this.#e?this.#e.bytes:void 0}}get hex(){return{public:this.publicKey.hex,secret:this.#e?this.#e.hex:void 0}}get multibase(){return{publicKeyMultibase:this.#t.multibase.encoded,secretKeyMultibase:this.#e?this.#e.multibase:""}}toJSON(){return{publicKey:this.publicKey.toJSON()}}exportJSON(){if(!this.#e)throw new wn("Cannot export: secret key required. Use publicKey.toJSON() for public-key-only pairs.","SERIALIZE_ERROR");return{secretKey:this.#e.exportJSON(),publicKey:this.publicKey.toJSON()}}[Symbol.for("nodejs.util.inspect.custom")](){return`[SchnorrKeyPair ${this.publicKey.hex}]`}static fromJSON(e){return new t({secretKey:Hr.fromJSON(e.secretKey),publicKey:pt.fromJSON(e.publicKey)})}static fromSecret(e){let r=typeof e=="string"?Tr(e):e;if(r.length!==32)throw new wn("Invalid arg: must be 32 byte secret key","FROM_SECRET_KEY_ERROR");let n=new Hr(r),i=n.computePublicKey();return new t({secretKey:n,publicKey:i})}static fromBigInt(e){let r=Hr.fromBigInt(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}static toHex(e){return Lt(e)}static equals(e,r){return e.publicKey.equals(r.publicKey)}static generate(){let e=Hr.random(),r=new Hr(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}};l();l();l();var Er=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in _o))throw new wt('Expected "idType" to be "KEY" or "EXTERNAL"',Pt,{idType:n});if(i!==1)throw new wt('Expected "version" to be 1',Pt,{version:i});if(typeof o!="string")throw new wt('Expected "network" to be a known network name',Pt,{network:o});let s=qu[o];if(s===void 0)throw new wt('Invalid "network" name',Pt,{network:o});if(n==="KEY")try{new pt(e)}catch{throw new wt('Expected "genesisBytes" to be a valid compressed secp256k1 public key',Pt,{genesisBytes:e})}else if(e.length!==32)throw new wt('Expected "genesisBytes" to be a 32-byte hash for EXTERNAL identifiers',Pt,{genesisBytes:e});let c=n==="KEY"?"k":"x",a=i-1<<4|s,u=new Uint8Array([a,...e]);return`did:btcr2:${Hc.encodeFromBytes(c,u)}`}static decode(e){let r=e.split(":");if(r.length!==3)throw new wt(`Invalid did: ${e}`,Pt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new wt(`Invalid did: ${e}`,Pt,{identifier:e});if(i!=="btcr2")throw new wt(`Invalid did method: ${i}`,pl,{identifier:e});if(!o)throw new wt(`Invalid method-specific id: ${e}`,Pt,{identifier:e});let{prefix:s,bytes:c}=Hc.decodeToBytes(o);if(!["x","k"].includes(s))throw new wt(`Invalid hrp: ${s}`,Pt,{identifier:e});if(!c||c.length<1)throw new wt(`Failed to decode id: ${o}`,Pt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new wt(`Invalid btcr2_version (expected 0): ${u}`,Pt,{identifier:e});let d=1,f=c[0]&15,h=qu[f],p;if(typeof h=="string")p=h;else if(f>=12&&f<=14)p=f-11;else throw new wt(`Invalid network: ${f}`,Pt,{identifier:e});let g=c.slice(1);if(a==="KEY")try{new pt(g)}catch{throw new wt(`Invalid genesisBytes: ${g}`,Pt,{identifier:e})}else if(g.length!==32)throw new wt(`Invalid genesisBytes: ${g}`,Pt,{identifier:e});return{idType:a,hrp:s,version:d,network:p,genesisBytes:g}}static generate(){let e=ao.generate(),r=this.encode(e.publicKey.compressed,{idType:"KEY",version:1,network:"regtest"});return{keyPair:e.exportJSON(),did:r}}static getPublicKey(e){let{idType:r,genesisBytes:n}=t.decode(e);if(r!=="KEY")throw new wt(`Cannot extract public key from EXTERNAL DID: ${e}. EXTERNAL DIDs encode a document hash, not a public key.`,Pt,{did:e,idType:r});return new pt(n)}static isValid(e){try{return this.decode(e),!0}catch{return!1}}};var dn=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new we("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!at.isDidService(e)||!["SingletonBeacon","CASBeacon","SMTBeacon"].includes(e.type)||[e.serviceEndpoint].flat().some(r=>typeof r=="string"&&!r.startsWith("bitcoin:")))}static getBeaconServices(e){return e.service.filter(this.isBeaconService)??[]}static createBeaconServices(e,r){try{return["p2pkh","p2wpkh","p2tr"].map(i=>this.createBeaconService(e,i,r))}catch(n){throw new nr("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=Er.decode(e),o=Bo(i.network),s=i.genesisBytes,c=`${e}#initial${r.toUpperCase()}`,u=`bitcoin:${r==="p2tr"?Ss(s.slice(1,33),void 0,o).address:r==="p2wpkh"?vs(s,o).address:Di(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new nr("Failed to create beacon service: "+i.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:n})}}static generateBeaconServices({id:e,publicKey:r,network:n,beaconType:i}){try{let o=Di(r,n).address,s=vs(r,n).address,c=Ss(r.slice(1,33),void 0,n).address;if(!o||!s||!c)throw new zt("Failed to generate bitcoin addresses");return[{id:`${e}#initialP2PKH`,type:i,serviceEndpoint:`bitcoin:${o}`},{id:`${e}#initialP2WPKH`,type:i,serviceEndpoint:`bitcoin:${s}`},{id:`${e}#initialP2TR`,type:i,serviceEndpoint:`bitcoin:${c}`}]}catch(o){throw new nr("Failed to create beacon services: "+o.message,"BEACON_SERVICE_ERROR",{id:e,publicKey:r,network:n,beaconType:i})}}static parseBeaconServiceEndpoint(e){return{...e,serviceEndpoint:e.serviceEndpoint.replace("bitcoin:","")}}static getBeaconServiceIds(e){return this.getBeaconServices(e).map(r=>r.id)}};var mL=/^6a20([0-9a-f]{64})$/i;function CI(t){if(!t)return null;let e=mL.exec(t.trim());return e?e[1].toLowerCase():null}var LI=class t{static async spendsFromAddress(e,r,n){for(let i of e.vin??[]){if(i.is_coinbase)continue;let o=i.prevout;if(!o&&i.txid&&(o=(await n.rest.transaction.get(i.txid))?.vout?.[i.vout]),o?.scriptpubkey_address===r)return!0}return!1}static async indexer(e,r){let n=new Map,i=await r.rest.block.count();for(let o of e){n.set(o,[]);let s=dn.parseBitcoinAddress(o.serviceEndpoint),c=await r.rest.address.getTxs(s);if(!(!c||!c.length))for(let a of c){let u=a.status;if(u.confirmed!==!0)continue;let d=a.vout.slice(-1)[0];if(!d)continue;let f=CI(d.scriptpubkey);if(!f||!await t.spendsFromAddress(a,s,r))continue;let h=i-u.block_height+1;n.get(o)?.push({tx:a,signalBytes:f,blockMetadata:{confirmations:h,height:u.block_height,time:u.block_time}})}}return n}static async fullnode(e,r){let n=new Map;for(let u of e)n.set(u,[]);let i=r.rpc;if(!i)throw new Le("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=new Map(e.map(u=>[dn.parseBitcoinAddress(u.serviceEndpoint),u])),c=0,a=await r.rpc.getBlock({height:c});for(console.info("Searching for beacon signals, please wait ...");a.height<=o;){for(let u of a.tx){if(u.txid===I0)continue;let d=u.vout.slice(-1)[0];if(!d)continue;let f=CI(d.scriptPubKey?.hex);if(!f)continue;let h=new Set;for(let p of u.vin){if(p.coinbase||p.txinwitness&&p.txinwitness.length===1&&p.txinwitness[0]===_0||!p.txid||p.vout===void 0)continue;let g=await i.getRawTransaction(p.txid,2);if(!g.vout[p.vout])continue;let y=g.vout[p.vout].scriptPubKey;if(!y.address)continue;let E=s.get(y.address);!E||h.has(E)||(h.add(E),console.info(`Tx ${u.txid} contains beacon address ${y.address}`),n.get(E)?.push({tx:u,signalBytes:f,blockMetadata:{height:a.height,time:a.time,confirmations:a.confirmations}}))}}if(c+=1,c>o){console.info(`Chain tip reached ${c}, breaking ...`);break}a=await i.getBlock({height:c})}return n}};l();l();l();l();l();l();l();var ere=new Uint8Array(0);function PI(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function wL(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,E=0,S=0,I=g.length;S!==I&&g[S]===0;)S++,y++;for(var A=(I-S)*d+1>>>0,O=new Uint8Array(A);S!==I;){for(var T=g[S],M=0,q=A-1;(T!==0||M<E)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");E=M,S++}for(var j=A-E;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var E=0,S=0;g[y]===a;)E++,y++;for(var I=(g.length-y)*u+1>>>0,A=new Uint8Array(I);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=I-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=I-S;q!==I&&A[q]===0;)q++;for(var j=new Uint8Array(E+(I-q)),$=E;q!==I;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var bL=wL,xL=bL,MI=xL;var Hb=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Vb=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return KI(this,e)}},qb=class{decoders;constructor(e){this.decoders=e}or(e){return KI(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 KI(t,e){return new qb({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Fb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Hb(e,r,n),this.decoder=new Vb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function EL({name:t,prefix:e,encode:r,decode:n}){return new Fb(t,e,r,n)}function jb({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=MI(r,t);return EL({prefix:e,name:t,encode:n,decode:o=>PI(i(o))})}var lf=jb({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dre=jb({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();function $I(t){return t===void 0?[]:Array.isArray(t)?t:[t]}var iu=class{cryptosuite;constructor(e){this.cryptosuite=e}addProof(e,r){let n=this.cryptosuite.createProof(e,r);if(!n.type||!n.verificationMethod||!n.proofPurpose)throw new mn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Ao,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new mn("Domain mismatch: proof.domain !== config.domain",Ao,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new mn("Challenge mismatch options and challenge passed",Ao,{config:r,proof:n});let i=e;return i.proof=n,i}verifyProof(e,r,n,i,o){let s=JSON.parse(e),c=s.proof;if(!c.type||!c.verificationMethod||!c.proofPurpose)throw new mn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",ki,s);if(r&&r!==c.proofPurpose)throw new mn("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",ki,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new mn("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){let u=$I(i),d=$I(c.domain);if(u.length!==d.length)throw new mn("Domain mismatch: expectedDomain length does not match proof.domain length",ki,{proof:c,expectedDomain:i});if(!u.every(f=>d.includes(f))||!d.every(f=>u.includes(f)))throw new mn("Domain mismatch: expectedDomain and proof.domain do not match",ki,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var ou=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new iu(this)}#e(){return{type:this.type,cryptosuite:this.cryptosuite,verificationMethod:this.multikey.fullId()}}createProof(e,r){r["@context"]=e["@context"]??r["@context"];let n=this.proofConfiguration(r),i=this.transformDocument(e,r),o=this.generateHash(n,i),s=this.proofSerialization(o,r),c=r;return c.proofValue=lf.encode(s),c.cryptosuite=this.cryptosuite,c.type=this.type,c}verifyProof(e){let{proof:r,...n}=e,{proofValue:i,...o}=r,s=this.transformDocument(n,o),c=this.proofConfiguration(o),a=this.generateHash(c,s),u=lf.decode(e.proof.proofValue),d=this.proofVerification(a,u,o);return{verified:d,verifiedDocument:d?e:void 0}}transformDocument(e,r){if(r.type!==this.type)throw new we("Type mismatch: config.type !== this.type",ki,{config:r,suite:this.#e()});if(r.cryptosuite!==this.cryptosuite)throw new we("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",ki,{config:r,suite:this.#e()});return rr(e)}generateHash(e,r){let n=ke(ws(e)),i=ke(ws(r)),o=dt(n,i);return ke(o)}proofConfiguration(e){if(e.type!==this.type)throw new So("Type mismatch: config.type !== this.type",Ao,{config:e,suite:this.#e()});if(e.cryptosuite!==this.cryptosuite)throw new So("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Ao,{config:e,suite:this.#e()});if(e.created&&!Io.isValidXsdDateTime(e.created))throw new So('Invalid config: "created" must be a valid XMLSchema DateTime string',Ao,e);return rr(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new So("Id mismatch: config.verificationMethod !== this.multikey.fullId()",uv,{config:r,suite:this.#e()});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new So("Id mismatch: config.verificationMethod !== this.multikey.fullId()",ki,{config:n,suite:this.#e()});return this.multikey.verify(r,e)}};l();l();l();var cs=class t{static type="Multikey";id;controller;#e;#t;constructor({id:e,controller:r,keyPair:n,externalSigner:i}){if(!n)throw new bn('Argument missing: "keyPair" required',"CONSTRUCTOR_ERROR");if(!n.publicKey)throw new bn('Argument missing: "keyPair" must contain a "publicKey"',"CONSTRUCTOR_ERROR");if(i){let o=i.publicKey,s=n.publicKey.compressed;if(o.length!==s.length||!o.every((c,a)=>c===s[a]))throw new bn("externalSigner.publicKey does not match keyPair.publicKey.compressed","CONSTRUCTOR_ERROR")}this.id=e,this.controller=r,this.#e=n,this.#t=i}get keyPair(){return this.#e}get publicKey(){return this.#e.publicKey}get secretKey(){try{return this.#e.secretKey}catch{throw new bn("Cannot get: no secretKey","PRIVATE_KEY_ERROR")}}toCryptosuite(){return new ou(this)}sign(e){if(this.#t)return this.#t.sign(e,"bip340");if(!this.signer)throw new bn("Cannot sign: no secretKey","SIGN_ERROR");return Rr.sign(e,this.secretKey.bytes,_r(32))}verify(e,r){return Rr.verify(e,r,this.publicKey.x)}fullId(){return this.id.startsWith("#")?`${this.controller}${this.id}`:this.id}toVerificationMethod(){return{id:this.id,type:t.type,controller:this.controller,publicKeyMultibase:this.publicKey.multibase.encoded}}get signer(){return!!this.#t||!!this.#e.secretKey}toJSON(){let e;try{e=this.signer}catch{e=!1}return{id:this.id,controller:this.controller,fullId:this.fullId(),signer:e,keyPair:this.keyPair.toJSON(),verificationMethod:this.toVerificationMethod()}}static create({id:e,controller:r,keyPair:n}){return new t({id:e,controller:r,keyPair:n})}static fromSecretKey(e,r,n){let i=new Hr(n),o=i.computePublicKey(),s=new ao({publicKey:o,secretKey:i});return new t({id:e,controller:r,keyPair:s})}static fromSigner(e,r,n){let i=new pt(n.publicKey),o=new ao({publicKey:i});return new t({id:e,controller:r,keyPair:o,externalSigner:n})}static fromPublicKey({id:e,controller:r,publicKeyBytes:n}){let i=new pt(n),o=new ao({publicKey:i});return new t({id:e,controller:r,keyPair:o})}static fromVerificationMethod({id:e,controller:r,publicKeyMultibase:n}){if(!n)throw new bn("Invalid publicKeyMultibase: cannot be undefined",yl,{publicKeyMultibase:n});let i=lf.decode(n);if(i.length!==35)throw new bn(`Invalid publicKeyMultibase length: ${i.length}`,yl,{publicKeyMultibase:n});if(i[0]!==231||i[1]!==1)throw new bn(`Invalid publicKeyMultibase prefix: expected secp256k1 multicodec [0xe7, 0x01], got [0x${i[0]?.toString(16)??"??"}, 0x${i[1]?.toString(16)??"??"}]`,yl,{publicKeyMultibase:n});let o=i.slice(2),s=new ao({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();l();l();var vL=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],su="Multikey",cu="zQ3s",fn="did:btcr2:_",Yre="",SL=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function AL(t){if(!at.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===su&&typeof r=="string"&&r.startsWith(cu)}var Wb=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==su)throw new qe(`Invalid verification method: type must be "${su}"`,De,{id:e,type:r});if(typeof i!="string"||!i.startsWith(cu))throw new qe(`Invalid verification method: publicKeyMultibase must start with "${cu}"`,De,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},ln=class t{id;"@context"=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"];verificationMethod;authentication;assertionMethod;capabilityInvocation;capabilityDelegation;service;deactivated;constructor(e){if(!e.id)throw new qe("DID Document must have an id",De,e);let r=e.id.includes("k1")?_o.KEY:_o.EXTERNAL,n=e.id===fn,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new qe(`Invalid id: ${i}`,De,e);if(!t.isValidVerificationMethods(o))throw new qe("Invalid verificationMethod: "+o,De,e);if(!t.isValidServices(s))throw new qe("Invalid service: "+s,De,e)}if(this.id=e.id,this.verificationMethod=e.verificationMethod||[],this.service=e.service||[],this["@context"]=e["@context"]||["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],r===_o.KEY){let c=`${this.id}#initialKey`;this.authentication=e.authentication||[c],this.assertionMethod=e.assertionMethod||[c],this.capabilityInvocation=e.capabilityInvocation||[c],this.capabilityDelegation=e.capabilityDelegation||[c]}else this.authentication=e.authentication,this.assertionMethod=e.assertionMethod,this.capabilityInvocation=e.capabilityInvocation,this.capabilityDelegation=e.capabilityDelegation;t.sanitize(this),n?this.validateGenesis():t.validate(this)}toJSON(){return{id:this.id,"@context":this["@context"],verificationMethod:this.verificationMethod,authentication:this.authentication,assertionMethod:this.assertionMethod,capabilityInvocation:this.capabilityInvocation,capabilityDelegation:this.capabilityDelegation,service:this.service,deactivated:this.deactivated}}static fromKeyIdentifier(e,r,n){e=e.includes("#")?e:`${e}#initialKey`;let i={id:e,verificationMethod:[new Wb({id:e,type:"Multikey",controller:e,publicKeyMultibase:r})],service:n};return new t(i)}static fromExternalIdentifier(e){return new t(e)}static sanitize(e){for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}static isValid(e){if(!this.isValidContext(e?.["@context"]))throw new qe('Invalid "@context"',De,e);if(!this.isValidId(e?.id))throw new qe('Invalid "id"',De,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new qe('Invalid "verificationMethod"',De,e);if(!this.isValidServices(e?.service))throw new qe('Invalid "service"',De,e);if(!this.isValidVerificationRelationships(e))throw new qe("Invalid verification relationships",De,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:vL.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return Er.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(AL)}static isValidServices(e){return Array.isArray(e)&&e.every(t_)}static isValidVerificationRelationships(e){let r=["authentication","assertionMethod","capabilityInvocation","capabilityDelegation"],n=Object.keys(e);return r.filter(o=>n.includes(o)).every(o=>{let s=e[o];return s&&Array.isArray(s)&&s.every(c=>typeof c=="string"||at.isDidVerificationMethod(c))})}static validate(e){return e.id===fn?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==fn)throw new qe("Invalid GenesisDocument ID",De,this);if(!this.verificationMethod.every(e=>e.id.includes(fn)&&e.controller===fn))throw new qe("Invalid GenesisDocument verificationMethod",De,this);if(!this.service.every(e=>e.id.includes(fn)))throw new qe("Invalid GenesisDocument service",De,this);if(!t.isValidVerificationRelationships(this))throw new qe("Invalid GenesisDocument assertionMethod",De,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new qe("Cannot convert a key identifier to an intermediate document",De,this);return new Gb(this)}},Gb=class t extends ln{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(fn,e),n=JSON.parse(r);return new ln(n)}static fromDidDocument(e){let r=Us.cloneReplace(e,SL,fn);return new t(r)}static create(e,r,n){return new t({id:fn,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new pt(e),i=fn,o=Di(n.compressed,Bo(r)).address,s=[{id:`${i}#service-0`,serviceEndpoint:`bitcoin:${o}`,type:"SingletonBeacon"}],c={authentication:[`${i}#key-0`],assertionMethod:[`${i}#key-0`],capabilityInvocation:[`${i}#key-0`],capabilityDelegation:[`${i}#key-0`]},a=[{id:`${i}#key-0`,type:"Multikey",controller:i,publicKeyMultibase:n.multibase.encoded}];return t.create(a,c,s)}static fromJSON(e){return new t(e)}static toGenesisBytes(e){return To(rr(e))}};var zp=class t{#e={phase:"Construct"};#t;#n;#r;#o;#i;constructor(e){this.#t=e.sourceDocument,this.#n=e.patches,this.#r=e.sourceVersionId,this.#o=e.verificationMethod,this.#i=e.beaconService}static construct(e,r,n){let i={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],patch:r,targetHash:"",targetVersionId:n+1,sourceHash:Wn(e)},o=Zc.apply(e,r);if(o.id!==e.id)throw new St(`Patches must not change the DID document id (source "${e.id}" to target "${o.id}").`,Ie,{sourceId:e.id,targetId:o.id});try{ln.isValid(o)}catch(s){throw new St("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),Ie,o)}return i.targetHash=Wn(o),i}static sign(e,r,n,i){if(!e.startsWith("did:btcr2:"))throw new St(`Expected a did:btcr2 identifier for the root capability; got "${e}".`,Ie,{did:e});let o=n.controller,s=n.id.indexOf("#");if(s<0)throw new St(`Verification method id must contain a fragment (e.g. "${n.id}#initialKey"); got "${n.id}".`,Ie,{verificationMethodId:n.id});let c=n.id.slice(s),a=cs.fromSigner(c,o,i),u=s===0?`${e}${c}`:n.id,d=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&d!==n.publicKeyMultibase)throw new St(`Signing key does not match verification method "${n.id}": the signer's public key differs from the method's published publicKeyMultibase.`,Ie,{verificationMethodId:n.id,expected:n.publicKeyMultibase,actual:d});let f={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],cryptosuite:"bip340-jcs-2025",type:"DataIntegrityProof",verificationMethod:u,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"};return a.toCryptosuite().toDataIntegrityProof().addProof(r,f)}static async announce(e,r,n,i,o,s){return ra.establish(e,r).broadcastSignal(n,i,o,s)}#s(){return t.construct(this.#t,this.#n,this.#r)}advance(){for(;;)switch(this.#e.phase){case"Construct":{let e=this.#s();this.#e={phase:"Sign",unsignedUpdate:e};continue}case"Sign":return{status:"action-required",needs:[{kind:"NeedSigningKey",verificationMethodId:this.#o.id,unsignedUpdate:this.#e.unsignedUpdate}]};case"Fund":return{status:"action-required",needs:[{kind:"NeedFunding",beaconAddress:this.#i.serviceEndpoint.replace("bitcoin:",""),beaconService:this.#i}]};case"Broadcast":return{status:"action-required",needs:[{kind:"NeedBroadcast",beaconService:this.#i,signedUpdate:this.#e.signedUpdate,did:this.#t.id}]};case"Complete":return{status:"complete",result:{signedUpdate:this.#e.signedUpdate}}}}provide(e,r){switch(e.kind){case"NeedSigningKey":{if(this.#e.phase!=="Sign")throw new St(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,Ie,{phase:this.#e.phase});if(!r)throw new St("NeedSigningKey requires a Signer.",Ie);let n=this.#e.unsignedUpdate,i=t.sign(this.#t.id,n,this.#o,r);this.#e={phase:"Fund",unsignedUpdate:n,signedUpdate:i};break}case"NeedFunding":{if(this.#e.phase!=="Fund")throw new St(`Cannot provide NeedFunding: updater phase is ${this.#e.phase}, expected Fund.`,Ie,{phase:this.#e.phase});if(r!==void 0){let n=r;if(typeof n.utxoCount!="number"||!Number.isFinite(n.utxoCount)||n.utxoCount<1)throw new St(`NeedFunding proof must have utxoCount >= 1; got ${String(n.utxoCount)}.`,Ie,{utxoCount:n.utxoCount})}this.#e={phase:"Broadcast",unsignedUpdate:this.#e.unsignedUpdate,signedUpdate:this.#e.signedUpdate};break}case"NeedBroadcast":{if(this.#e.phase!=="Broadcast")throw new St(`Cannot provide NeedBroadcast: updater phase is ${this.#e.phase}, expected Broadcast.`,Ie,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};var Yp=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new we("idType is required for creating a did:btcr2 identifier",De,r);return Er.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=Er.decode(e),i=as.sidecarData(r.sidecar),o=n.hrp===Al.k?as.deterministic(n):null;return new as(n,i,o,{versionId:r.versionId,versionTime:r.versionTime,genesisDocument:r.sidecar?.genesisDocument,maxDiscoveryRounds:r.maxDiscoveryRounds,minConf:r.minConf})}static update({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethodId:i,beaconId:o}){let s=at.relationshipMethodId(i,e.id);if(!(s!==void 0&&e.capabilityInvocation?.some(f=>at.relationshipMethodId(f,e.id)===s)))throw new St("Invalid verificationMethodId: not authorized for capabilityInvocation",De,e);let a=this.getSigningMethod(e,i);if(!a)throw new St("Invalid verificationMethod: not found in source document",De,{sourceDocument:e,verificationMethodId:i});if(a.type!==su)throw new St(`Invalid verificationMethod: verificationMethod.type must be "${su}"`,De,a);if(!a.publicKeyMultibase?.startsWith(cu))throw new St(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${cu}"`,De,a);let u=at.absoluteDidUrl(o,e.id),d=e.service.filter(f=>u!==void 0&&at.absoluteDidUrl(f.id,e.id)===u).filter(f=>!!f).shift();if(!d)throw new St("No beacon service found for provided beaconId",Ie,{sourceDocument:e,beaconId:o});return new zp({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:a,beaconService:d})}static getSigningMethod(e,r){r??="#initialKey";let n=me.parse(e.id);if(n&&n.method!==this.methodName)throw new we(`Method not supported: ${n.method}`,pl,{identifier:e.id});let i=at.absoluteDidUrl(r,e.id)??at.relationshipMethodId(e.assertionMethod?.[0],e.id),o=i===void 0?void 0:e.verificationMethod?.find(s=>at.absoluteDidUrl(s.id,e.id)===i);if(!(o&&o.publicKeyMultibase))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o}};var TL=6;function hf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function _L(t){return hf(t)&&Object.values(t).every(e=>typeof e=="string")}function IL(t){return hf(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&Number.isInteger(t.targetVersionId)&&t.targetVersionId>=2&&hf(t.proof):!1}function BL(t){return hf(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}function RL(t){if(t===void 0)return TL;if(typeof t=="number"&&Number.isInteger(t)&&t>=1)return t;let e=typeof t=="string"?JSON.stringify(t):String(t);throw new Le(`Invalid resolution option minConf: expected a positive integer (minimum 1), got ${e}.`,dv,{minConf:t})}var as=class t{#e;#t;#n;#r;#o;#i;#s=null;#f=new Map;#l=new Set;#d=new Set;#c=[];#a=null;#h=1;#g=[];#u;#p=0;#y;constructor(e,r,n,i){this.#e=e,this.#o=r,this.#i=n,this.#t=i?.versionId,this.#n=i?.versionTime;let o=i?.maxDiscoveryRounds;this.#u=typeof o=="number"&&o>0?o:1/0,this.#y=RL(i?.minConf),i?.genesisDocument&&(this.#s=i.genesisDocument),this.#r=n?"BeaconDiscovery":"GenesisDocument"}static deterministic(e){let r=e.genesisBytes,n=Er.encode(r,e),{multibase:i}=new pt(r),o=dn.generateBeaconServices({id:n,publicKey:r,network:Bo(e.network),beaconType:"SingletonBeacon"});return new ln({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=Yc(r);if(!vu(e.genesisBytes,n))throw new Le("Initial document mismatch: genesisBytes !== genesisDocumentHash",De,{genesisBytes:Jr(e.genesisBytes,"hex"),genesisDocumentHash:Jr(n,"hex")});let i=Er.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(fn,i));return new ln(o)}static sidecarData(e={}){let r=new Map;if(e.updates?.length)for(let o of e.updates)r.set(Wn(o,{encoding:"hex"}),o);let n=new Map;if(e.casUpdates?.length)for(let o of e.casUpdates)n.set(Wn(o,{encoding:"hex"}),o);let i=new Map;if(e.smtProofs?.length)for(let o of e.smtProofs)i.set(Jr(Bs(o.id,"base64urlnopad"),"hex"),o);return{updateMap:r,casMap:n,smtMap:i}}static updates(e,r,n,i,o={currentVersionId:1,updateHashHistory:[]}){let s=o.currentVersionId,c=o.updateHashHistory,a=r.sort(([d,f],[h,p])=>d.targetVersionId-h.targetVersionId||f.height-p.height),u={didDocument:e,metadata:{versionId:`${s}`,confirmations:0,updated:"",deactivated:e.deactivated||!1}};for(let[d,f]of a){let h=Yc(u.didDocument),p=Io.blocktimeToTimestamp(f.time);if(u.metadata.updated=Io.toISOStringNonFractional(p),u.metadata.confirmations=f.confirmations,d.targetVersionId<=s){this.confirmDuplicate(d,c);continue}if(n&&p>Io.dateStringToTimestamp(n))return u;if(d.targetVersionId===s+1){let y=Bs(d.sourceHash,"base64urlnopad");if(!vu(y,h))throw new Le("Hash mismatch: update.sourceHash !== currentDocumentHash",Ie,{sourceHash:d.sourceHash,currentDocumentHash:Jr(h,"hex")});u.didDocument=this.applyUpdate(u.didDocument,d);let E=Us.deleteKeys(d,["proof"]);c.push(Yc(E))}else throw new Le("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",gl,{targetVersionId:d.targetVersionId,currentVersionId:s+1});s++,u.metadata.versionId=`${s}`;let g=Number(i);if(!isNaN(g)&&g<=s)return u;if(u.didDocument.deactivated)return u.metadata.deactivated=u.didDocument.deactivated,u}return u}static confirmDuplicate(e,r){if(!Number.isInteger(e.targetVersionId)||e.targetVersionId<2)throw new Le("Invalid duplicate: targetVersionId must be an integer >= 2",Ie,{targetVersionId:e.targetVersionId});let{proof:n,...i}=e,o=Yc(i),s=r[e.targetVersionId-2];if(s===void 0)throw new Le("Invalid duplicate: no applied update in history for targetVersionId",gl,{targetVersionId:e.targetVersionId,historyLength:r.length});if(!vu(s,o))throw new Le("Invalid duplicate: unsigned update hash does not match historical hash",gl,{unsignedUpdateHash:Jr(o,"hex"),historicalHash:Jr(s,"hex")})}static applyUpdate(e,r){let n=r.proof?.capability;if(!n)throw new Le("No root capability found in update",Ie,r);let i=at.dereferenceZcapId(n),{invocationTarget:o,controller:s}=i;if(![o,s].every(A=>A===e.id))throw new Le("Invalid root capability",Ie,{rootCapability:i,currentDocument:e});let c=r.proof?.verificationMethod;if(!c)throw new Le("No verificationMethod found in update",Ie,r);let a=at.relationshipMethodId(c,e.id);if(!(a!==void 0&&e.capabilityInvocation?.some(A=>at.relationshipMethodId(A,e.id)===a)))throw new Le("Invalid update: verificationMethod is not authorized for capabilityInvocation",Ie,{verificationMethodId:c,capabilityInvocation:e.capabilityInvocation});let d=Yp.getSigningMethod(e,c),f=cs.fromVerificationMethod(d),h=new ou(f),p=rr(r),y=new iu(h).verifyProof(p,"capabilityInvocation");if(!y.verified)throw new Le("Invalid update: proof not verified",Ie,y);let E=Zc.apply(e,r.patch);ln.validate(E);let S=Yc(E),I=Bs(r.targetHash);if(!vu(I,S))throw new Le("Invalid update: update.targetHash !== currentDocumentHash",Ie,{updateTargetHash:I,currentDocumentHash:S});return E}resolve(){for(;;)switch(this.#r){case"GenesisDocument":{if(this.#s){this.#i=t.external(this.#e,this.#s),this.#s=null,this.#r="BeaconDiscovery";continue}return{status:"action-required",needs:[{kind:"NeedGenesisDocument",genesisHash:Jr(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=dn.getBeaconServices(this.#i).filter(n=>{let i=dn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=dn.parseBitcoinAddress(n.serviceEndpoint);this.#d.add(i)}return{status:"action-required",needs:[{kind:"NeedBeaconSignals",beaconServices:r}]}}this.#r="BeaconProcess";continue}case"BeaconProcess":{let e=[];for(let[r,n]of this.#f){if(this.#l.has(r.id)||!n.length)continue;let i=this.#m(n);if(!i.length)continue;let s=ra.establish(r,this.#i.id).processSignals(i,this.#o);s.needs.length>0?e.push(...s.needs):(this.#c.push(...s.updates),this.#l.add(r.id))}if(e.length>0)return{status:"action-required",needs:e};this.#r="ApplyUpdates";continue}case"ApplyUpdates":{if(this.#c.length>0&&(this.#a=t.updates(this.#i,this.#c,this.#n,this.#t,{currentVersionId:this.#h,updateHashHistory:this.#g}),this.#h=Number(this.#a.metadata.versionId),this.#i=this.#a.didDocument,this.#c=[],dn.getBeaconServices(this.#i).some(n=>{let i=dn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)}))){if(++this.#p>this.#u)throw new Le(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,av,{maxDiscoveryRounds:this.#u,discoveryRounds:this.#p});this.#r="BeaconDiscovery";continue}this.#r="Complete";continue}case"Complete":return{status:"resolved",result:this.#a??{didDocument:this.#i,metadata:{versionId:this.#t??"1",deactivated:this.#i.deactivated||!1}}}}}#m(e){let r=[];for(let n of e){let i=n.blockMetadata,o=i?.confirmations;if(!(!Number.isInteger(o)||o<this.#y)){if(!Number.isFinite(i?.height)||!Number.isFinite(i?.time))throw new Le(`Beacon signal ${n.signalBytes} has ${o} confirmations but no valid block height or block time.`,Ie,{signalBytes:n.signalBytes,confirmations:o,height:i?.height,time:i?.time});r.push(n)}}return r}provide(e,r){switch(e.kind){case"NeedGenesisDocument":{if(!hf(r))throw new Le("Provided data for NeedGenesisDocument must be a document object.",Ie,{kind:e.kind});this.#s=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new Le("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",Ie,{kind:e.kind});for(let[n,i]of r)this.#f.set(n,i);break}case"NeedCASAnnouncement":{if(!_L(r))throw new Le("Provided data for NeedCASAnnouncement is not a CAS announcement.",Ie,{kind:e.kind});let n=Wn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new Le(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,Ie,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!IL(r))throw new Le("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",Ie,{kind:e.kind});let n=Wn(r,{encoding:"hex"});if(n!==e.updateHash)throw new Le(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,Ie,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!BL(r))throw new Le("Provided data for NeedSMTProof is not an SMT proof.",Ie,{kind:e.kind});let n=Jr(Bs(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new Le(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,Ie,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function UL(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new qe("Cannot derive aggregation communication key: capabilityInvocation is absent",De,{id:t.id});let r=at.absoluteDidUrl(e,t.id),n=typeof e=="string"?r===void 0?void 0:t.verificationMethod?.find(i=>at.absoluteDidUrl(i.id,t.id)===r):e;if(!n)throw new qe(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,De,{id:t.id,invocation:e});return cs.fromVerificationMethod(n).publicKey}function Dne(t,e){try{let r=Er.decode(t);if(r.idType==="KEY")return new pt(r.genesisBytes);if(e?.genesisDocument){let n=as.external(r,e.genesisDocument);return UL(n)}}catch{}}l();l();l();var HI=class{document={};constructor(e){if(!e.id)throw new qe('Missing required "id" property',De,e);this.document.id=e.id,this.document.verificationMethod=e.verificationMethod??[],e["@context"]&&(this.document["@context"]=e["@context"])}withAuthentication(e){return e&&(this.document.authentication=e),this}withAssertionMethod(e){return e&&(this.document.assertionMethod=e),this}withCapabilityInvocation(e){return e&&(this.document.capabilityInvocation=e),this}withCapabilityDelegation(e){return e&&(this.document.capabilityDelegation=e),this}withService(e){return e&&(this.document.service=e),this}build(){let e=new ln(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};export{gv as AggregateBeaconError,at as Appendix,Yre as BECH32M_CHARS,vL as BTCR2_DID_DOCUMENT_CONTEXT,nr as BeaconError,ra as BeaconFactory,LI as BeaconSignalDiscovery,dn as BeaconUtils,Tl as CASBeacon,mv as CASBeaconError,bv as CHANGE_OUTPUT_VBYTES,R0 as DEFAULT_FEE_ESTIMATOR,TL as DEFAULT_MIN_CONF,SL as DID_REGEX,xv as DUST_LIMIT_SATS,Yp as DidBtcr2,ln as DidDocument,HI as DidDocumentBuilder,Wb as DidVerificationMethod,Gb as GenesisDocument,fn as ID_PLACEHOLDER_VALUE,Er as Identifier,cu as MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX,su as MULTIKEY_VERIFICATION_METHOD_TYPE,jR as P2PKH_BEACON_TX_VSIZE,qR as P2TR_BEACON_TX_VSIZE,FR as P2WPKH_BEACON_TX_VSIZE,as as Resolver,WR as SINGLETON_BEACON_TX_VSIZE,Cl as SMTBeacon,Fu as SMTBeaconError,U0 as SPENDABLE_DUST_LIMIT_SATS,Ro as SinglePartyBeacon,_l as SingletonBeacon,yv as SingletonBeaconError,ju as StaticFeeEstimator,zp as Updater,Ev as beaconTxVsize,L$ as buildAggregationBeaconTx,GR as deriveSingletonAddress,vv as detectSingletonScriptKind,CI as extractOpReturnSignalHash,UL as getAggregationCommunicationKey,AL as isMultikeyVerificationMethod,Tv as opReturnScript,Dne as resolveBtcr2SenderPk,Sv as resolveChangeAddress,JR as selectSpendableUtxo};
1
+ var cB=Object.create;var ry=Object.defineProperty;var aB=Object.getOwnPropertyDescriptor;var uB=Object.getOwnPropertyNames;var dB=Object.getPrototypeOf,fB=Object.prototype.hasOwnProperty;var lB=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Af=(t,e)=>{for(var r in e)ry(t,r,{get:e[r],enumerable:!0})},hB=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of uB(e))!fB.call(t,i)&&i!==r&&ry(t,i,{get:()=>e[i],enumerable:!(n=aB(e,i))||n.enumerable});return t};var Mn=(t,e,r)=>(r=t!=null?cB(dB(t)):{},hB(e||!t||!t.__esModule?ry(r,"default",{value:t,enumerable:!0}):r,t));var ox=oe(Tf=>{"use strict";l();Tf.byteLength=yB;Tf.toByteArray=mB;Tf.fromByteArray=xB;var Kn=[],Gr=[],pB=typeof Uint8Array<"u"?Uint8Array:Array,ny="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ys=0,nx=ny.length;ys<nx;++ys)Kn[ys]=ny[ys],Gr[ny.charCodeAt(ys)]=ys;var ys,nx;Gr[45]=62;Gr[95]=63;function ix(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function yB(t){var e=ix(t),r=e[0],n=e[1];return(r+n)*3/4-n}function gB(t,e,r){return(e+r)*3/4-r}function mB(t){var e,r=ix(t),n=r[0],i=r[1],o=new pB(gB(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Gr[t.charCodeAt(a)]<<18|Gr[t.charCodeAt(a+1)]<<12|Gr[t.charCodeAt(a+2)]<<6|Gr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Gr[t.charCodeAt(a)]<<2|Gr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Gr[t.charCodeAt(a)]<<10|Gr[t.charCodeAt(a+1)]<<4|Gr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function wB(t){return Kn[t>>18&63]+Kn[t>>12&63]+Kn[t>>6&63]+Kn[t&63]}function bB(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(wB(n));return i.join("")}function xB(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(bB(t,s,s+o>c?c:s+o));return n===1?(e=t[r-1],i.push(Kn[e>>2]+Kn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Kn[e>>10]+Kn[e>>4&63]+Kn[e<<2&63]+"=")),i.join("")}});var sx=oe(iy=>{l();iy.read=function(t,e,r,n,i){var o,s,c=i*8-n-1,a=(1<<c)-1,u=a>>1,d=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,o=p&(1<<-d)-1,p>>=-d,d+=c;d>0;o=o*256+t[e+f],f+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=n;d>0;s=s*256+t[e+f],f+=h,d-=8);if(o===0)o=1-u;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-u}return(p?-1:1)*s*Math.pow(2,o-n)};iy.write=function(t,e,r,n,i,o){var s,c,a,u=o*8-i-1,d=(1<<u)-1,f=d>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,g=n?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(c=isNaN(e)?1:0,s=d):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),s+f>=1?e+=h/a:e+=h*Math.pow(2,1-f),e*a>=2&&(s++,a/=2),s+f>=d?(c=0,s=d):s+f>=1?(c=(e*a-1)*Math.pow(2,i),s=s+f):(c=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=c&255,p+=g,c/=256,i-=8);for(s=s<<i|c,u+=i;u>0;t[r+p]=s&255,p+=g,s/=256,u-=8);t[r+p-g]|=y*128}});var Tr=oe(Oc=>{"use strict";l();var oy=ox(),Uc=sx(),cx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Oc.Buffer=F;Oc.SlowBuffer=_B;Oc.INSPECT_MAX_BYTES=50;var _f=2147483647;Oc.kMaxLength=_f;F.TYPED_ARRAY_SUPPORT=EB();!F.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function EB(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(F.prototype,"parent",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.buffer}});Object.defineProperty(F.prototype,"offset",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.byteOffset}});function wi(t){if(t>_f)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,F.prototype),e}function F(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return uy(t)}return dx(t,e,r)}F.poolSize=8192;function dx(t,e,r){if(typeof t=="string")return SB(t,e);if(ArrayBuffer.isView(t))return AB(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if($n(t,ArrayBuffer)||t&&$n(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&($n(t,SharedArrayBuffer)||t&&$n(t.buffer,SharedArrayBuffer)))return cy(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return F.from(n,e,r);var i=TB(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return F.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}F.from=function(t,e,r){return dx(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function fx(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function vB(t,e,r){return fx(t),t<=0?wi(t):e!==void 0?typeof r=="string"?wi(t).fill(e,r):wi(t).fill(e):wi(t)}F.alloc=function(t,e,r){return vB(t,e,r)};function uy(t){return fx(t),wi(t<0?0:dy(t)|0)}F.allocUnsafe=function(t){return uy(t)};F.allocUnsafeSlow=function(t){return uy(t)};function SB(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=lx(t,e)|0,n=wi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function sy(t){for(var e=t.length<0?0:dy(t.length)|0,r=wi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function AB(t){if($n(t,Uint8Array)){var e=new Uint8Array(t);return cy(e.buffer,e.byteOffset,e.byteLength)}return sy(t)}function cy(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');var n;return e===void 0&&r===void 0?n=new Uint8Array(t):r===void 0?n=new Uint8Array(t,e):n=new Uint8Array(t,e,r),Object.setPrototypeOf(n,F.prototype),n}function TB(t){if(F.isBuffer(t)){var e=dy(t.length)|0,r=wi(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||fy(t.length)?wi(0):sy(t);if(t.type==="Buffer"&&Array.isArray(t.data))return sy(t.data)}function dy(t){if(t>=_f)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+_f.toString(16)+" bytes");return t|0}function _B(t){return+t!=t&&(t=0),F.alloc(+t)}F.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==F.prototype};F.compare=function(e,r){if($n(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),$n(r,Uint8Array)&&(r=F.from(r,r.offset,r.byteLength)),!F.isBuffer(e)||!F.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,o=0,s=Math.min(n,i);o<s;++o)if(e[o]!==r[o]){n=e[o],i=r[o];break}return n<i?-1:i<n?1:0};F.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};F.concat=function(e,r){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return F.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=F.allocUnsafe(r),o=0;for(n=0;n<e.length;++n){var s=e[n];if($n(s,Uint8Array))o+s.length>i.length?F.from(s).copy(i,o):Uint8Array.prototype.set.call(i,s,o);else if(F.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function lx(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||$n(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return ay(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return wx(t).length;default:if(i)return n?-1:ay(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=lx;function IB(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return PB(this,e,r);case"utf8":case"utf-8":return px(this,e,r);case"ascii":return CB(this,e,r);case"latin1":case"binary":return LB(this,e,r);case"base64":return kB(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return MB(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function gs(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}F.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)gs(this,r,r+1);return this};F.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)gs(this,r,r+3),gs(this,r+1,r+2);return this};F.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)gs(this,r,r+7),gs(this,r+1,r+6),gs(this,r+2,r+5),gs(this,r+3,r+4);return this};F.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?px(this,0,e):IB.apply(this,arguments)};F.prototype.toLocaleString=F.prototype.toString;F.prototype.equals=function(e){if(!F.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:F.compare(this,e)===0};F.prototype.inspect=function(){var e="",r=Oc.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};cx&&(F.prototype[cx]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,o){if($n(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),!F.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),r<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&r>=n)return 0;if(i>=o)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,o>>>=0,this===e)return 0;for(var s=o-i,c=n-r,a=Math.min(s,c),u=this.slice(i,o),d=e.slice(r,n),f=0;f<a;++f)if(u[f]!==d[f]){s=u[f],c=d[f];break}return s<c?-1:c<s?1:0};function hx(t,e,r,n,i){if(t.length===0)return-1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,fy(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=F.from(e,n)),F.isBuffer(e))return e.length===0?-1:ax(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):ax(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function ax(t,e,r,n,i){var o=1,s=t.length,c=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;o=2,s/=2,c/=2,r/=2}function a(p,g){return o===1?p[g]:p.readUInt16BE(g*o)}var u;if(i){var d=-1;for(u=r;u<s;u++)if(a(t,u)===a(e,d===-1?0:u-d)){if(d===-1&&(d=u),u-d+1===c)return d*o}else d!==-1&&(u-=u-d),d=-1}else for(r+c>s&&(r=s-c),u=r;u>=0;u--){for(var f=!0,h=0;h<c;h++)if(a(t,u+h)!==a(e,h)){f=!1;break}if(f)return u}return-1}F.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};F.prototype.indexOf=function(e,r,n){return hx(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return hx(this,e,r,n,!1)};function BB(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=e.length;n>o/2&&(n=o/2);for(var s=0;s<n;++s){var c=parseInt(e.substr(s*2,2),16);if(fy(c))return s;t[r+s]=c}return s}function RB(t,e,r,n){return If(ay(e,t.length-r),t,r,n)}function UB(t,e,r,n){return If(HB(e),t,r,n)}function OB(t,e,r,n){return If(wx(e),t,r,n)}function DB(t,e,r,n){return If(VB(e,t.length-r),t,r,n)}F.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var o=this.length-r;if((n===void 0||n>o)&&(n=o),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return BB(this,e,r,n);case"utf8":case"utf-8":return RB(this,e,r,n);case"ascii":case"latin1":case"binary":return UB(this,e,r,n);case"base64":return OB(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return DB(this,e,r,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};F.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function kB(t,e,r){return e===0&&r===t.length?oy.fromByteArray(t):oy.fromByteArray(t.slice(e,r))}function px(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var o=t[i],s=null,c=o>239?4:o>223?3:o>191?2:1;if(i+c<=r){var a,u,d,f;switch(c){case 1:o<128&&(s=o);break;case 2:a=t[i+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(s=f));break;case 3:a=t[i+1],u=t[i+2],(a&192)===128&&(u&192)===128&&(f=(o&15)<<12|(a&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:a=t[i+1],u=t[i+2],d=t[i+3],(a&192)===128&&(u&192)===128&&(d&192)===128&&(f=(o&15)<<18|(a&63)<<12|(u&63)<<6|d&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,c=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),i+=c}return NB(n)}var ux=4096;function NB(t){var e=t.length;if(e<=ux)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=ux));return r}function CB(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function LB(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function PB(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",o=e;o<r;++o)i+=qB[t[o]];return i}function MB(t,e,r){for(var n=t.slice(e,r),i="",o=0;o<n.length-1;o+=2)i+=String.fromCharCode(n[o]+n[o+1]*256);return i}F.prototype.slice=function(e,r){var n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);var i=this.subarray(e,r);return Object.setPrototypeOf(i,F.prototype),i};function Ut(t,e,r){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}F.prototype.readUintLE=F.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return i};F.prototype.readUintBE=F.prototype.readUIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e+--r],o=1;r>0&&(o*=256);)i+=this[e+--r]*o;return i};F.prototype.readUint8=F.prototype.readUInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ut(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};F.prototype.readUint32BE=F.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};F.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*r)),i};F.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Ut(e,r,this.length);for(var i=r,o=1,s=this[e+--i];i>0&&(o*=256);)s+=this[e+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*r)),s};F.prototype.readInt8=function(e,r){return e=e>>>0,r||Ut(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};F.prototype.readInt16BE=function(e,r){e=e>>>0,r||Ut(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};F.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};F.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};F.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),Uc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),Uc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Uc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Uc.read(this,e,!1,52,8)};function fr(t,e,r,n,i,o){if(!F.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}F.prototype.writeUintLE=F.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;fr(this,e,r,n,o,0)}var s=1,c=0;for(this[r]=e&255;++c<n&&(s*=256);)this[r+c]=e/s&255;return r+n};F.prototype.writeUintBE=F.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;fr(this,e,r,n,o,0)}var s=n-1,c=1;for(this[r+s]=e&255;--s>=0&&(c*=256);)this[r+s]=e/c&255;return r+n};F.prototype.writeUint8=F.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,1,255,0),this[r]=e&255,r+1};F.prototype.writeUint16LE=F.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeUint16BE=F.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeUint32LE=F.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};F.prototype.writeUint32BE=F.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};F.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);fr(this,e,r,n,o-1,-o)}var s=0,c=1,a=0;for(this[r]=e&255;++s<n&&(c*=256);)e<0&&a===0&&this[r+s-1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);fr(this,e,r,n,o-1,-o)}var s=n-1,c=1,a=0;for(this[r+s]=e&255;--s>=0&&(c*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};F.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};F.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||fr(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function yx(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function gx(t,e,r,n,i){return e=+e,r=r>>>0,i||yx(t,e,r,4,34028234663852886e22,-34028234663852886e22),Uc.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return gx(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return gx(this,e,r,!1,n)};function mx(t,e,r,n,i){return e=+e,r=r>>>0,i||yx(t,e,r,8,17976931348623157e292,-17976931348623157e292),Uc.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return mx(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return mx(this,e,r,!1,n)};F.prototype.copy=function(e,r,n,i){if(!F.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r<i-n&&(i=e.length-r+n);var o=i-n;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),r),o};F.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!F.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(e.length===1){var o=e.charCodeAt(0);(i==="utf8"&&o<128||i==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var s;if(typeof e=="number")for(s=r;s<n;++s)this[s]=e;else{var c=F.isBuffer(e)?e:F.from(e,i),a=c.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-r;++s)this[s+r]=c[s%a]}return this};var KB=/[^+/0-9A-Za-z-_]/g;function $B(t){if(t=t.split("=")[0],t=t.trim().replace(KB,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function ay(t,e){e=e||1/0;for(var r,n=t.length,i=null,o=[],s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return o}function HB(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function VB(t,e){for(var r,n,i,o=[],s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}function wx(t){return oy.toByteArray($B(t))}function If(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function $n(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function fy(t){return t!==t}var qB=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var Ei=oe((GL,vx)=>{l();var dt=vx.exports={},Hn,Vn;function ly(){throw new Error("setTimeout has not been defined")}function hy(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Hn=setTimeout:Hn=ly}catch{Hn=ly}try{typeof clearTimeout=="function"?Vn=clearTimeout:Vn=hy}catch{Vn=hy}})();function bx(t){if(Hn===setTimeout)return setTimeout(t,0);if((Hn===ly||!Hn)&&setTimeout)return Hn=setTimeout,setTimeout(t,0);try{return Hn(t,0)}catch{try{return Hn.call(null,t,0)}catch{return Hn.call(this,t,0)}}}function FB(t){if(Vn===clearTimeout)return clearTimeout(t);if((Vn===hy||!Vn)&&clearTimeout)return Vn=clearTimeout,clearTimeout(t);try{return Vn(t)}catch{try{return Vn.call(null,t)}catch{return Vn.call(this,t)}}}var bi=[],Dc=!1,ms,Bf=-1;function jB(){!Dc||!ms||(Dc=!1,ms.length?bi=ms.concat(bi):Bf=-1,bi.length&&xx())}function xx(){if(!Dc){var t=bx(jB);Dc=!0;for(var e=bi.length;e;){for(ms=bi,bi=[];++Bf<e;)ms&&ms[Bf].run();Bf=-1,e=bi.length}ms=null,Dc=!1,FB(t)}}dt.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];bi.push(new Ex(t,e)),bi.length===1&&!Dc&&bx(xx)};function Ex(t,e){this.fun=t,this.array=e}Ex.prototype.run=function(){this.fun.apply(null,this.array)};dt.title="browser";dt.browser=!0;dt.env={};dt.argv=[];dt.version="";dt.versions={};function xi(){}dt.on=xi;dt.addListener=xi;dt.once=xi;dt.off=xi;dt.removeListener=xi;dt.removeAllListeners=xi;dt.emit=xi;dt.prependListener=xi;dt.prependOnceListener=xi;dt.listeners=function(t){return[]};dt.binding=function(t){throw new Error("process.binding is not supported")};dt.cwd=function(){return"/"};dt.chdir=function(t){throw new Error("process.chdir is not supported")};dt.umask=function(){return 0}});var b,w,YL,l=lB(()=>{b=Mn(Tr()),w=Mn(Ei()),YL=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object)});var zv=oe((RH,Gv)=>{l();var o6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Pl=()=>o6.now(),s6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),F0=t=>t===1/0||s6(t),j0=class t{constructor({max:e=1/0,ttl:r,updateAgeOnGet:n=!1,checkAgeOnGet:i=!1,noUpdateTTL:o=!1,dispose:s,noDisposeOnSet:c=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,r!==void 0&&!F0(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!F0(e))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=r,this.max=e,this.updateAgeOnGet=!!n,this.checkAgeOnGet=!!i,this.noUpdateTTL=!!o,this.noDisposeOnSet=!!c,s!==void 0){if(typeof s!="function")throw new TypeError("dispose must be function if set");this.dispose=s}this.timer=void 0,this.timerExpiration=void 0}setTimer(e,r){if(this.timerExpiration<e)return;this.timer&&clearTimeout(this.timer);let n=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let i in this.expirations){this.setTimer(i,i-Pl());break}},r);n.unref&&n.unref(),this.timerExpiration=e,this.timer=n}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return w.default.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let e=this.dispose!==t.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[r,n]of e)this.dispose(n,r,"delete")}setTTL(e,r=this.ttl){let n=this.expirationMap.get(e);if(n!==void 0){let i=this.expirations[n];!i||i.length<=1?delete this.expirations[n]:this.expirations[n]=i.filter(o=>o!==e)}if(r!==1/0){let i=Math.floor(Pl()+r);this.expirationMap.set(e,i),this.expirations[i]||(this.expirations[i]=[],this.setTimer(i,r)),this.expirations[i].push(e)}else this.expirationMap.set(e,1/0)}set(e,r,{ttl:n=this.ttl,noUpdateTTL:i=this.noUpdateTTL,noDisposeOnSet:o=this.noDisposeOnSet}={}){if(!F0(n))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(e)){i||this.setTTL(e,n);let s=this.data.get(e);s!==r&&(this.data.set(e,r),o||this.dispose(s,e,"set"))}else this.setTTL(e,n),this.data.set(e,r);for(;this.size>this.max;)this.purgeToCapacity();return this}has(e){return this.data.has(e)}getRemainingTTL(e){let r=this.expirationMap.get(e);return r===1/0?r:r!==void 0?Math.max(0,Math.ceil(r-Pl())):0}get(e,{updateAgeOnGet:r=this.updateAgeOnGet,ttl:n=this.ttl,checkAgeOnGet:i=this.checkAgeOnGet}={}){let o=this.data.get(e);if(i&&this.getRemainingTTL(e)===0){this.delete(e);return}return r&&this.setTTL(e,n),o}dispose(e,r){}delete(e){let r=this.expirationMap.get(e);if(r!==void 0){let n=this.data.get(e);this.data.delete(e),this.expirationMap.delete(e);let i=this.expirations[r];return i&&(i.length<=1?delete this.expirations[r]:this.expirations[r]=i.filter(o=>o!==e)),this.dispose(n,e,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let e in this.expirations){let r=this.expirations[e];if(this.size-r.length>=this.max){delete this.expirations[e];let n=[];for(let i of r)n.push([i,this.data.get(i)]),this.data.delete(i),this.expirationMap.delete(i);for(let[i,o]of n)this.dispose(o,i,"evict")}else{let n=this.size-this.max,i=[];for(let o of r.splice(0,n))i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"evict");return}}}get size(){return this.data.size}purgeStale(){let e=Math.ceil(Pl());for(let r in this.expirations){if(r==="Infinity"||r>e)return;let n=[...this.expirations[r]||[]],i=[];delete this.expirations[r];for(let o of n)i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let e in this.expirations)for(let r of this.expirations[e])yield[r,this.data.get(r)]}*keys(){for(let e in this.expirations)for(let r of this.expirations[e])yield r}*values(){for(let e in this.expirations)for(let r of this.expirations[e])yield this.data.get(r)}[Symbol.iterator](){return this.entries()}};Gv.exports=j0});var f1=oe(d1=>{"use strict";l();d1.supports=function(...e){let r=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}});var vn=oe((QV,l1)=>{"use strict";l();l1.exports=class extends Error{constructor(e,r){super(e||""),typeof r=="object"&&r!==null&&(r.code&&(this.code=String(r.code)),r.expected&&(this.expected=!0),r.transient&&(this.transient=!0),r.cause&&(this.cause=r.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var sg=oe((tq,h1)=>{"use strict";l();var og=null;h1.exports=function(){return og===null&&(og={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),og}});var ug=oe(p1=>{"use strict";l();var cg=vn(),K6=new Set(["buffer","view","utf8"]),ag=class{constructor(e){if(this.encode=e.encode||this.encode,this.decode=e.decode||this.decode,this.name=e.name||this.name,this.format=e.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!K6.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");e.createViewTranscoder&&(this.createViewTranscoder=e.createViewTranscoder),e.createBufferTranscoder&&(this.createBufferTranscoder=e.createBufferTranscoder),e.createUTF8Transcoder&&(this.createUTF8Transcoder=e.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new cg(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new cg(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new cg(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};p1.Encoding=ag});var hg=oe(Kl=>{"use strict";l();var{Buffer:fg}=Tr()||{},{Encoding:lg}=ug(),$6=sg(),nd=class extends lg{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new id({encode:this.encode,decode:e=>this.decode(fg.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},id=class extends lg{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new nd({encode:e=>{let r=this.encode(e);return fg.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},dg=class extends lg{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new nd({encode:e=>fg.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:r}=$6();return new id({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Kl.BufferFormat=nd;Kl.ViewFormat=id;Kl.UTF8Format=dg});var w1=oe(Hs=>{"use strict";l();var{Buffer:Jt}=Tr()||{Buffer:{isBuffer:()=>!1}},{textEncoder:g1,textDecoder:y1}=sg()(),{BufferFormat:od,ViewFormat:pg,UTF8Format:m1}=hg(),$l=t=>t;Hs.utf8=new m1({encode:function(t){return Jt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?y1.decode(t):String(t)},decode:$l,name:"utf8",createViewTranscoder(){return new pg({encode:function(t){return ArrayBuffer.isView(t)?t:g1.encode(t)},decode:function(t){return y1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new od({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Hs.json=new m1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Hs.buffer=new od({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:$l,name:"buffer",createViewTranscoder(){return new pg({encode:function(t){return ArrayBuffer.isView(t)?t:Jt.from(String(t),"utf8")},decode:function(t){return Jt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Hs.view=new pg({encode:function(t){return ArrayBuffer.isView(t)?t:g1.encode(t)},decode:$l,name:"view",createBufferTranscoder(){return new od({encode:function(t){return Jt.isBuffer(t)?t:ArrayBuffer.isView(t)?Jt.from(t.buffer,t.byteOffset,t.byteLength):Jt.from(String(t),"utf8")},decode:$l,name:`${this.name}+buffer`})}});Hs.hex=new od({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Hs.base64=new od({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var E1=oe(x1=>{"use strict";l();var b1=vn(),Vl=w1(),{Encoding:H6}=ug(),{BufferFormat:V6,ViewFormat:q6,UTF8Format:F6}=hg(),sd=Symbol("formats"),Hl=Symbol("encodings"),j6=new Set(["buffer","view","utf8"]),yg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>j6.has(r)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[Hl]=new Map,this[sd]=new Set(e);for(let r in Vl)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[Hl].values()))}encoding(e){let r=this[Hl].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=Y6[e],!r)throw new b1(`Encoding '${e}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof e!="object"||e===null)throw new TypeError("First argument 'encoding' must be a string or object");r=W6(e)}let{name:n,format:i}=r;if(!this[sd].has(i))if(this[sd].has("view"))r=r.createViewTranscoder();else if(this[sd].has("buffer"))r=r.createBufferTranscoder();else if(this[sd].has("utf8"))r=r.createUTF8Transcoder();else throw new b1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[Hl].set(o,r)}return r}};x1.Transcoder=yg;function W6(t){if(t instanceof H6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${J6++}`;switch(G6(t)){case"view":return new q6({...t,name:r});case"utf8":return new F6({...t,name:r});case"buffer":return new V6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function G6(t){return"format"in t&&t.format!==void 0?t.format:"buffer"in t&&typeof t.buffer=="boolean"?t.buffer?"buffer":"utf8":"code"in t&&Number.isInteger(t.code)?"view":"buffer"}var z6={binary:Vl.buffer,"utf-8":Vl.utf8},Y6={...Vl,...z6},J6=0});var da=oe((fq,gg)=>{"use strict";l();var ua=typeof Reflect=="object"?Reflect:null,v1=ua&&typeof ua.apply=="function"?ua.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},ql;ua&&typeof ua.ownKeys=="function"?ql=ua.ownKeys:Object.getOwnPropertySymbols?ql=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:ql=function(e){return Object.getOwnPropertyNames(e)};function Z6(t){console&&console.warn&&console.warn(t)}var A1=Number.isNaN||function(e){return e!==e};function Pe(){Pe.init.call(this)}gg.exports=Pe;gg.exports.once=tU;Pe.EventEmitter=Pe;Pe.prototype._events=void 0;Pe.prototype._eventsCount=0;Pe.prototype._maxListeners=void 0;var S1=10;function Fl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Pe,"defaultMaxListeners",{enumerable:!0,get:function(){return S1},set:function(t){if(typeof t!="number"||t<0||A1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");S1=t}});Pe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Pe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||A1(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function T1(t){return t._maxListeners===void 0?Pe.defaultMaxListeners:t._maxListeners}Pe.prototype.getMaxListeners=function(){return T1(this)};Pe.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(r.length>0&&(s=r[0]),s instanceof Error)throw s;var c=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw c.context=s,c}var a=o[e];if(a===void 0)return!1;if(typeof a=="function")v1(a,this,r);else for(var u=a.length,d=U1(a,u),n=0;n<u;++n)v1(d[n],this,r);return!0};function _1(t,e,r,n){var i,o,s;if(Fl(r),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),o=t._events),s=o[e]),s===void 0)s=o[e]=r,++t._eventsCount;else if(typeof s=="function"?s=o[e]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),i=T1(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=s.length,Z6(c)}return t}Pe.prototype.addListener=function(e,r){return _1(this,e,r,!1)};Pe.prototype.on=Pe.prototype.addListener;Pe.prototype.prependListener=function(e,r){return _1(this,e,r,!0)};function X6(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function I1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=X6.bind(n);return i.listener=r,n.wrapFn=i,i}Pe.prototype.once=function(e,r){return Fl(r),this.on(e,I1(this,e,r)),this};Pe.prototype.prependOnceListener=function(e,r){return Fl(r),this.prependListener(e,I1(this,e,r)),this};Pe.prototype.removeListener=function(e,r){var n,i,o,s,c;if(Fl(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===r||n[s].listener===r){c=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():Q6(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Pe.prototype.off=Pe.prototype.removeListener;Pe.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function B1(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?eU(i):U1(i,i.length)}Pe.prototype.listeners=function(e){return B1(this,e,!0)};Pe.prototype.rawListeners=function(e){return B1(this,e,!1)};Pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):R1.call(t,e)};Pe.prototype.listenerCount=R1;function R1(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Pe.prototype.eventNames=function(){return this._eventsCount>0?ql(this._events):[]};function U1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function Q6(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function eU(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function tU(t,e){return new Promise(function(r,n){function i(s){t.removeListener(e,o),n(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}O1(t,e,o,{once:!0}),e!=="error"&&rU(t,i,{once:!0})})}function rU(t,e,r){typeof t.on=="function"&&O1(t,"error",e,r)}function O1(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){n.once&&t.removeEventListener(e,i),r(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}});var k1=oe((hq,D1)=>{l();D1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var cd=oe(mg=>{"use strict";l();var N1=k1();mg.fromCallback=function(t,e){if(t===void 0){var r=new Promise(function(n,i){t=function(o,s){o?i(o):n(s)}});t[e!==void 0?e:"promise"]=r}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t};mg.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){N1(()=>e(null,r))}).catch(function(r){N1(()=>e(r))})}});var jl=oe(wg=>{"use strict";l();wg.getCallback=function(t,e){return typeof t=="function"?t:e};wg.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Ko=oe(Yl=>{"use strict";l();var{fromCallback:bg}=cd(),kr=vn(),{getOptions:xg,getCallback:C1}=jl(),Vs=Symbol("promise"),fa=Symbol("callback"),Xn=Symbol("working"),qs=Symbol("handleOne"),Ki=Symbol("handleMany"),Eg=Symbol("autoClose"),Po=Symbol("finishWork"),Qn=Symbol("returnMany"),No=Symbol("closing"),ad=Symbol("handleClose"),Wl=Symbol("closed"),ud=Symbol("closeCallbacks"),Lo=Symbol("keyEncoding"),Fs=Symbol("valueEncoding"),vg=Symbol("abortOnClose"),Gl=Symbol("legacy"),Sg=Symbol("keys"),Ag=Symbol("values"),Co=Symbol("limit"),Qr=Symbol("count"),zl=Object.freeze({}),nU=()=>{},L1=!1,dd=class{constructor(e,r,n){if(typeof e!="object"||e===null){let i=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof r!="object"||r===null)throw new TypeError("The second argument must be an options object");this[Wl]=!1,this[ud]=[],this[Xn]=!1,this[No]=!1,this[Eg]=!1,this[fa]=null,this[qs]=this[qs].bind(this),this[Ki]=this[Ki].bind(this),this[ad]=this[ad].bind(this),this[Lo]=r[Lo],this[Fs]=r[Fs],this[Gl]=n,this[Co]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[Qr]=0,this[vg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[Qr]}get limit(){return this[Co]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[Gl]?s===void 0&&c===void 0?n():n([s,c]):n(s)}});else if(typeof e!="function")throw new TypeError("Callback must be a function");return this[No]?this.nextTick(e,new kr("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(e,new kr("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[fa]=e,this[Qr]>=this[Co]?this.nextTick(this[qs],null):this._next(this[qs])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=C1(r,n),n=bg(n,Vs),r=xg(r,zl),Number.isInteger(e)?(this[No]?this.nextTick(n,new kr("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(n,new kr("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[Co]<1/0&&(e=Math.min(e,this[Co]-this[Qr])),this[Xn]=!0,this[fa]=n,e<=0?this.nextTick(this[Ki],null,[]):this._nextv(e,r,this[Ki])),n[Vs]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[Vs])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[Gl]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[Gl]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=C1(e,r),r=bg(r,Vs),e=xg(e,zl),this[No]?this.nextTick(r,new kr("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(r,new kr("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[fa]=r,this[Eg]=!0,this[Qr]>=this[Co]?this.nextTick(this[Ki],null,[]):this._all(e,this[Ki])),r[Vs]}_all(e,r){let n=this[Qr],i=[],o=()=>{let c=this[Co]<1/0?Math.min(1e3,this[Co]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,zl,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Po](){let e=this[fa];return this[vg]&&e===null?nU:(this[Xn]=!1,this[fa]=null,this[No]&&this._close(this[ad]),e)}[Qn](e,r,n){this[Eg]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=xg(r,zl),!this[No]){if(this[Xn])throw new kr("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[Lo]),i=n.format;r.keyEncoding!==i&&(r={...r,keyEncoding:i});let o=this.db.prefixKey(n.encode(e),i);this._seek(o,r)}}}_seek(e,r){throw new kr("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=bg(e,Vs),this[Wl]?this.nextTick(e):this[No]?this[ud].push(e):(this[No]=!0,this[ud].push(e),this[Xn]?this[vg]&&this[Po]()(new kr("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[ad])),e[Vs]}_close(e){this.nextTick(e)}[ad](){this[Wl]=!0,this.db.detachResource(this);let e=this[ud];this[ud]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[Wl]||await this.close()}}},la=class extends dd{constructor(e,r){super(e,r,!0),this[Sg]=r.keys!==!1,this[Ag]=r.values!==!1}[qs](e,r,n){let i=this[Po]();if(e)return i(e);try{r=this[Sg]&&r!==void 0?this[Lo].decode(r):void 0,n=this[Ag]&&n!==void 0?this[Fs].decode(n):void 0}catch(o){return i(new Mo("entry",o))}r===void 0&&n===void 0||this[Qr]++,i(null,r,n)}[Ki](e,r){let n=this[Po]();if(e)return this[Qn](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[Sg]&&o!==void 0?this[Lo].decode(o):void 0,i[1]=this[Ag]&&s!==void 0?this[Fs].decode(s):void 0}}catch(i){return this[Qn](n,new Mo("entries",i))}this[Qr]+=r.length,this[Qn](n,null,r)}end(e){return!L1&&typeof console<"u"&&(L1=!0,console.warn(new kr("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(e)}},Tg=class extends dd{constructor(e,r){super(e,r,!1)}[qs](e,r){let n=this[Po]();if(e)return n(e);try{r=r!==void 0?this[Lo].decode(r):void 0}catch(i){return n(new Mo("key",i))}r!==void 0&&this[Qr]++,n(null,r)}[Ki](e,r){let n=this[Po]();if(e)return this[Qn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Lo].decode(o):void 0}}catch(i){return this[Qn](n,new Mo("keys",i))}this[Qr]+=r.length,this[Qn](n,null,r)}},_g=class extends dd{constructor(e,r){super(e,r,!1)}[qs](e,r){let n=this[Po]();if(e)return n(e);try{r=r!==void 0?this[Fs].decode(r):void 0}catch(i){return n(new Mo("value",i))}r!==void 0&&this[Qr]++,n(null,r)}[Ki](e,r){let n=this[Po]();if(e)return this[Qn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Fs].decode(o):void 0}}catch(i){return this[Qn](n,new Mo("values",i))}this[Qr]+=r.length,this[Qn](n,null,r)}},Mo=class extends kr{constructor(e,r){super(`Iterator could not decode ${e}`,{code:"LEVEL_DECODE_ERROR",cause:r})}};for(let t of["_ended property","_nexting property","_end method"])Object.defineProperty(la.prototype,t.split(" ")[0],{get(){throw new kr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new kr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});la.keyEncoding=Lo;la.valueEncoding=Fs;Yl.AbstractIterator=la;Yl.AbstractKeyIterator=Tg;Yl.AbstractValueIterator=_g});var P1=oe(Ig=>{"use strict";l();var{AbstractKeyIterator:iU,AbstractValueIterator:oU}=Ko(),js=Symbol("iterator"),fd=Symbol("callback"),ha=Symbol("handleOne"),Ws=Symbol("handleMany"),ld=class extends iU{constructor(e,r){super(e,r),this[js]=e.iterator({...r,keys:!0,values:!1}),this[ha]=this[ha].bind(this),this[Ws]=this[Ws].bind(this)}},Jl=class extends oU{constructor(e,r){super(e,r),this[js]=e.iterator({...r,keys:!1,values:!0}),this[ha]=this[ha].bind(this),this[Ws]=this[Ws].bind(this)}};for(let t of[ld,Jl]){let e=t===ld,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[fd]=n,this[js].next(this[ha])},t.prototype[ha]=function(n,i,o){let s=this[fd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[fd]=o,this[js].nextv(n,i,this[Ws])},t.prototype._all=function(n,i){this[fd]=i,this[js].all(n,this[Ws])},t.prototype[Ws]=function(n,i){let o=this[fd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[js].seek(n,i)},t.prototype._close=function(n){this[js].close(n)}}Ig.DefaultKeyIterator=ld;Ig.DefaultValueIterator=Jl});var M1=oe(rh=>{"use strict";l();var{AbstractIterator:sU,AbstractKeyIterator:cU,AbstractValueIterator:aU}=Ko(),Bg=vn(),yr=Symbol("nut"),eh=Symbol("undefer"),th=Symbol("factory"),Zl=class extends sU{constructor(e,r){super(e,r),this[yr]=null,this[th]=()=>e.iterator(r),this.db.defer(()=>this[eh]())}},Xl=class extends cU{constructor(e,r){super(e,r),this[yr]=null,this[th]=()=>e.keys(r),this.db.defer(()=>this[eh]())}},Ql=class extends aU{constructor(e,r){super(e,r),this[yr]=null,this[th]=()=>e.values(r),this.db.defer(()=>this[eh]())}};for(let t of[Zl,Xl,Ql])t.prototype[eh]=function(){this.db.status==="open"&&(this[yr]=this[th]())},t.prototype._next=function(e){this[yr]!==null?this[yr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new Bg("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[yr]!==null?this[yr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new Bg("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[yr]!==null?this[yr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new Bg("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[yr]!==null?this[yr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[yr]!==null?this[yr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};rh.DeferredIterator=Zl;rh.DeferredKeyIterator=Xl;rh.DeferredValueIterator=Ql});var Ug=oe($1=>{"use strict";l();var{fromCallback:K1}=cd(),nh=vn(),{getCallback:uU,getOptions:dU}=jl(),ih=Symbol("promise"),en=Symbol("status"),pa=Symbol("operations"),hd=Symbol("finishClose"),ya=Symbol("closeCallbacks"),Rg=class{constructor(e){if(typeof e!="object"||e===null){let r=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${r}`)}this[pa]=[],this[ya]=[],this[en]="open",this[hd]=this[hd].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[pa].length}put(e,r,n){if(this[en]!=="open")throw new nh("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(e)||this.db._checkValue(r);if(i)throw i;let o=n&&n.sublevel!=null?n.sublevel:this.db,s=n,c=o.keyEncoding(n&&n.keyEncoding),a=o.valueEncoding(n&&n.valueEncoding),u=c.format;n={...n,keyEncoding:u,valueEncoding:a.format},o!==this.db&&(n.sublevel=null);let d=o.prefixKey(c.encode(e),u),f=a.encode(r);return this._put(d,f,n),this[pa].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[en]!=="open")throw new nh("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let n=this.db._checkKey(e);if(n)throw n;let i=r&&r.sublevel!=null?r.sublevel:this.db,o=r,s=i.keyEncoding(r&&r.keyEncoding),c=s.format;return r={...r,keyEncoding:c},i!==this.db&&(r.sublevel=null),this._del(i.prefixKey(s.encode(e),c),r),this[pa].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[en]!=="open")throw new nh("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[pa]=[],this}_clear(){}write(e,r){return r=uU(e,r),r=K1(r,ih),e=dU(e),this[en]!=="open"?this.nextTick(r,new nh("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[en]="writing",this._write(e,n=>{this[en]="closing",this[ya].push(()=>r(n)),n||this.db.emit("batch",this[pa]),this._close(this[hd])})),r[ih]}_write(e,r){}close(e){return e=K1(e,ih),this[en]==="closing"?this[ya].push(e):this[en]==="closed"?this.nextTick(e):(this[ya].push(e),this[en]!=="writing"&&(this[en]="closing",this._close(this[hd]))),e[ih]}_close(e){this.nextTick(e)}[hd](){this[en]="closed",this.db.detachResource(this);let e=this[ya];this[ya]=[];for(let r of e)r()}};$1.AbstractChainedBatch=Rg});var V1=oe(H1=>{"use strict";l();var{AbstractChainedBatch:fU}=Ug(),lU=vn(),ga=Symbol("encoded"),Og=class extends fU{constructor(e){super(e),this[ga]=[]}_put(e,r,n){this[ga].push({...n,type:"put",key:e,value:r})}_del(e,r){this[ga].push({...r,type:"del",key:e})}_clear(){this[ga]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[ga].length===0?this.nextTick(r):this.db._batch(this[ga],e,r):this.nextTick(r,new lU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};H1.DefaultChainedBatch=Og});var j1=oe((Rq,F1)=>{"use strict";l();var q1=vn(),hU=Object.prototype.hasOwnProperty,pU=new Set(["lt","lte","gt","gte"]);F1.exports=function(t,e){let r={};for(let n in t)if(hU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new q1(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new q1("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});pU.has(n)?r[n]=e.encode(t[n]):r[n]=t[n]}return r.reverse=!!r.reverse,r.limit=Number.isInteger(r.limit)&&r.limit>=0?r.limit:-1,r}});var Dg=oe((Oq,G1)=>{l();var W1;G1.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(W1||(W1=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var J1=oe((kq,Y1)=>{"use strict";l();var z1=Dg();Y1.exports=function(t,...e){e.length===0?z1(t):z1(()=>t(...e))}});var Z1=oe(oh=>{"use strict";l();var{AbstractIterator:yU,AbstractKeyIterator:gU,AbstractValueIterator:mU}=Ko(),ma=Symbol("unfix"),Sn=Symbol("iterator"),Gs=Symbol("handleOne"),$o=Symbol("handleMany"),$i=Symbol("callback"),pd=class extends yU{constructor(e,r,n,i){super(e,r),this[Sn]=n,this[ma]=i,this[Gs]=this[Gs].bind(this),this[$o]=this[$o].bind(this),this[$i]=null}[Gs](e,r,n){let i=this[$i];if(e)return i(e);r!==void 0&&(r=this[ma](r)),i(e,r,n)}[$o](e,r){let n=this[$i];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[ma](o))}n(e,r)}},yd=class extends gU{constructor(e,r,n,i){super(e,r),this[Sn]=n,this[ma]=i,this[Gs]=this[Gs].bind(this),this[$o]=this[$o].bind(this),this[$i]=null}[Gs](e,r){let n=this[$i];if(e)return n(e);r!==void 0&&(r=this[ma](r)),n(e,r)}[$o](e,r){let n=this[$i];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[ma](o))}n(e,r)}},gd=class extends mU{constructor(e,r,n){super(e,r),this[Sn]=n}};for(let t of[pd,yd])t.prototype._next=function(e){this[$i]=e,this[Sn].next(this[Gs])},t.prototype._nextv=function(e,r,n){this[$i]=n,this[Sn].nextv(e,r,this[$o])},t.prototype._all=function(e,r){this[$i]=r,this[Sn].all(e,this[$o])};for(let t of[gd])t.prototype._next=function(e){this[Sn].next(e)},t.prototype._nextv=function(e,r,n){this[Sn].nextv(e,r,n)},t.prototype._all=function(e,r){this[Sn].all(e,r)};for(let t of[pd,yd,gd])t.prototype._seek=function(e,r){this[Sn].seek(e,r)},t.prototype._close=function(e){this[Sn].close(e)};oh.AbstractSublevelIterator=pd;oh.AbstractSublevelKeyIterator=yd;oh.AbstractSublevelValueIterator=gd});var t2=oe((Pq,e2)=>{"use strict";l();var kg=vn(),{Buffer:Lg}=Tr()||{},{AbstractSublevelIterator:wU,AbstractSublevelKeyIterator:bU,AbstractSublevelValueIterator:xU}=Z1(),Hi=Symbol("prefix"),X1=Symbol("upperBound"),md=Symbol("prefixRange"),Nr=Symbol("parent"),Ng=Symbol("unfix"),Q1=new TextEncoder,EU={separator:"!"};e2.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new kg("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new kg("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?EU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=SU(i,s);let u=s.charCodeAt(0)+1,d=n[Nr]||n;if(!Q1.encode(i).every(p=>p>u&&p<127))throw new kg(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(vU(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[Nr]=d,this[Hi]=new sh(f),this[X1]=new sh(h),this[Ng]=new Pg,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[Hi].utf8+n;if(n.byteLength===0)return this[Hi][i];if(i==="view"){let o=this[Hi].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[Hi].buffer;return Lg.concat([o,n],o.byteLength+n.byteLength)}}[md](n,i){n.gte!==void 0?n.gte=this.prefixKey(n.gte,i):n.gt!==void 0?n.gt=this.prefixKey(n.gt,i):n.gte=this[Hi][i],n.lte!==void 0?n.lte=this.prefixKey(n.lte,i):n.lt!==void 0?n.lt=this.prefixKey(n.lt,i):n.lte=this[X1][i]}get prefix(){return this[Hi].utf8}get db(){return this[Nr]}_open(n,i){this[Nr].open({passive:!0},i)}_put(n,i,o,s){this[Nr].put(n,i,o,s)}_get(n,i,o){this[Nr].get(n,i,o)}_getMany(n,i,o){this[Nr].getMany(n,i,o)}_del(n,i,o){this[Nr].del(n,i,o)}_batch(n,i,o){this[Nr].batch(n,i,o)}_clear(n,i){this[md](n,n.keyEncoding),this[Nr].clear(n,i)}_iterator(n){this[md](n,n.keyEncoding);let i=this[Nr].iterator(n),o=this[Ng].get(this[Hi].utf8.length,n.keyEncoding);return new wU(this,n,i,o)}_keys(n){this[md](n,n.keyEncoding);let i=this[Nr].keys(n),o=this[Ng].get(this[Hi].utf8.length,n.keyEncoding);return new bU(this,n,i,o)}_values(n){this[md](n,n.keyEncoding);let i=this[Nr].values(n);return new xU(this,n,i)}}return{AbstractSublevel:e}};var vU=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:Cg(t,"utf8"),buffer:Cg(t,"buffer"),view:Cg(t,"view")}}},Cg=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},sh=class{constructor(e){this.utf8=e,this.view=Q1.encode(e),this.buffer=Lg?Lg.from(this.view.buffer,0,this.view.byteLength):{}}},Pg=class{constructor(){this.cache=new Map}get(e,r){let n=this.cache.get(r);return n===void 0&&(r==="view"?n=(function(i,o){return o.subarray(i)}).bind(null,e):n=(function(i,o){return o.slice(i)}).bind(null,e),this.cache.set(r,n)),n}},SU=function(t,e){let r=0,n=t.length;for(;r<n&&t[r]===e;)r++;for(;n>r&&t[n-1]===e;)n--;return t.slice(r,n)}});var Vg=oe(Hg=>{"use strict";l();var{supports:AU}=f1(),{Transcoder:TU}=E1(),{EventEmitter:_U}=da(),{fromCallback:Ho}=cd(),An=vn(),{AbstractIterator:zs}=Ko(),{DefaultKeyIterator:IU,DefaultValueIterator:BU}=P1(),{DeferredIterator:RU,DeferredKeyIterator:UU,DeferredValueIterator:OU}=M1(),{DefaultChainedBatch:r2}=V1(),{getCallback:Ys,getOptions:Vo}=jl(),ch=j1(),pe=Symbol("promise"),Vi=Symbol("landed"),Js=Symbol("resources"),Mg=Symbol("closeResources"),wd=Symbol("operations"),bd=Symbol("undefer"),ah=Symbol("deferOpen"),n2=Symbol("options"),be=Symbol("status"),Zs=Symbol("defaultOptions"),wa=Symbol("transcoder"),uh=Symbol("keyEncoding"),Kg=Symbol("valueEncoding"),DU=()=>{},xd=class extends _U{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=Vo(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[Js]=new Set,this[wd]=[],this[ah]=!0,this[n2]=s,this[be]="opening",this.supports=AU(e,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:e.snapshots!==!1,permanence:e.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:e.encodings||{},events:Object.assign({},e.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[wa]=new TU(kU(this)),this[uh]=this[wa].encoding(n||"utf8"),this[Kg]=this[wa].encoding(i||"utf8");for(let c of this[wa].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[Zs]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[uh].commonName,valueEncoding:this[Kg].commonName}),key:Object.freeze({keyEncoding:this[uh].commonName})},this.nextTick(()=>{this[ah]&&this.open({passive:!1},DU)})}get status(){return this[be]}keyEncoding(e){return this[wa].encoding(e??this[uh])}valueEncoding(e){return this[wa].encoding(e??this[Kg])}open(e,r){r=Ys(e,r),r=Ho(r,pe),e={...this[n2],...Vo(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[be]==="closing"||this[be]==="opening"?this.once(Vi,i?()=>n(i):n):this[be]!=="open"?r(new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[be]==="opening"?this.once(Vi,n):this.nextTick(n):this[be]==="closed"||this[ah]?(this[ah]=!1,this[be]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[be]="closed",this[Mg](()=>{this.emit(Vi),n(i)}),this[bd]();return}this[be]="open",this[bd](),this.emit(Vi),this[be]==="open"&&this.emit("open"),this[be]==="open"&&this.emit("ready"),n()})):this[be]==="open"?this.nextTick(n):this.once(Vi,()=>this.open(e,r)),r[pe]}_open(e,r){this.nextTick(r)}close(e){e=Ho(e,pe);let r=n=>{this[be]==="opening"||this[be]==="closing"?this.once(Vi,n?r(n):r):this[be]!=="closed"?e(new An("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[be]==="open"){this[be]="closing",this.emit("closing");let n=i=>{this[be]="open",this[bd](),this.emit(Vi),r(i)};this[Mg](()=>{this._close(i=>{if(i)return n(i);this[be]="closed",this[bd](),this.emit(Vi),this[be]==="closed"&&this.emit("closed"),r()})})}else this[be]==="closed"?this.nextTick(r):this.once(Vi,()=>this.close(e));return e[pe]}[Mg](e){if(this[Js].size===0)return this.nextTick(e);let r=this[Js].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[Js])o.close(i);n=!1,this[Js].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=Ys(r,n),n=Ho(n,pe),r=Vo(r,this[Zs].entry),this[be]==="opening")return this.defer(()=>this.get(e,r,n)),n[pe];if(ba(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=this.valueEncoding(r.valueEncoding),c=o.format,a=s.format;return(r.keyEncoding!==c||r.valueEncoding!==a)&&(r=Object.assign({},r,{keyEncoding:c,valueEncoding:a})),this._get(this.prefixKey(o.encode(e),c),r,(u,d)=>{if(u)return(u.code==="LEVEL_NOT_FOUND"||u.notFound||/NotFound/i.test(u))&&(u.code||(u.code="LEVEL_NOT_FOUND"),u.notFound||(u.notFound=!0),u.status||(u.status=404)),n(u);try{d=s.decode(d)}catch(f){return n(new An("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_get(e,r,n){this.nextTick(n,new Error("NotFound"))}getMany(e,r,n){if(n=Ys(r,n),n=Ho(n,pe),r=Vo(r,this[Zs].entry),this[be]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[pe];if(ba(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[pe];if(e.length===0)return this.nextTick(n,null,[]),n[pe];let i=this.keyEncoding(r.keyEncoding),o=this.valueEncoding(r.valueEncoding),s=i.format,c=o.format;(r.keyEncoding!==s||r.valueEncoding!==c)&&(r=Object.assign({},r,{keyEncoding:s,valueEncoding:c}));let a=new Array(e.length);for(let u=0;u<e.length;u++){let d=e[u],f=this._checkKey(d);if(f)return this.nextTick(n,f),n[pe];a[u]=this.prefixKey(i.encode(d),s)}return this._getMany(a,r,(u,d)=>{if(u)return n(u);try{for(let f=0;f<d.length;f++)d[f]!==void 0&&(d[f]=o.decode(d[f]))}catch(f){return n(new An(`Could not decode one or more of ${d.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_getMany(e,r,n){this.nextTick(n,null,new Array(e.length).fill(void 0))}put(e,r,n,i){if(i=Ys(n,i),i=Ho(i,pe),n=Vo(n,this[Zs].entry),this[be]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[pe];if(ba(this,i))return i[pe];let o=this._checkKey(e)||this._checkValue(r);if(o)return this.nextTick(i,o),i[pe];let s=this.keyEncoding(n.keyEncoding),c=this.valueEncoding(n.valueEncoding),a=s.format,u=c.format;(n.keyEncoding!==a||n.valueEncoding!==u)&&(n=Object.assign({},n,{keyEncoding:a,valueEncoding:u}));let d=this.prefixKey(s.encode(e),a),f=c.encode(r);return this._put(d,f,n,h=>{if(h)return i(h);this.emit("put",e,r),i()}),i[pe]}_put(e,r,n,i){this.nextTick(i)}del(e,r,n){if(n=Ys(r,n),n=Ho(n,pe),r=Vo(r,this[Zs].key),this[be]==="opening")return this.defer(()=>this.del(e,r,n)),n[pe];if(ba(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=o.format;return r.keyEncoding!==s&&(r=Object.assign({},r,{keyEncoding:s})),this._del(this.prefixKey(o.encode(e),s),r,c=>{if(c)return n(c);this.emit("del",e),n()}),n[pe]}_del(e,r,n){this.nextTick(n)}batch(e,r,n){if(!arguments.length){if(this[be]==="opening")return new r2(this);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=Ys(r,n),n=Ho(n,pe),r=Vo(r,this[Zs].empty),this[be]==="opening")return this.defer(()=>this.batch(e,r,n)),n[pe];if(ba(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[pe];if(e.length===0)return this.nextTick(n),n[pe];let i=new Array(e.length),{keyEncoding:o,valueEncoding:s,...c}=r;for(let a=0;a<e.length;a++){if(typeof e[a]!="object"||e[a]===null)return this.nextTick(n,new TypeError("A batch operation must be an object")),n[pe];let u=Object.assign({},e[a]);if(u.type!=="put"&&u.type!=="del")return this.nextTick(n,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),n[pe];let d=this._checkKey(u.key);if(d)return this.nextTick(n,d),n[pe];let f=u.sublevel!=null?u.sublevel:this,h=f.keyEncoding(u.keyEncoding||o),p=h.format;if(u.key=f.prefixKey(h.encode(u.key),p),u.keyEncoding=p,u.type==="put"){let g=this._checkValue(u.value);if(g)return this.nextTick(n,g),n[pe];let y=f.valueEncoding(u.valueEncoding||s);u.value=y.encode(u.value),u.valueEncoding=y.format}f!==this&&(u.sublevel=null),i[a]=u}return this._batch(i,c,a=>{if(a)return n(a);this.emit("batch",e),n()}),n[pe]}_batch(e,r,n){this.nextTick(n)}sublevel(e,r){return this._sublevel(e,$g.defaults(r))}_sublevel(e,r){return new $g(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=Ys(e,r),r=Ho(r,pe),e=Vo(e,this[Zs].empty),this[be]==="opening")return this.defer(()=>this.clear(e,r)),r[pe];if(ba(this,r))return r[pe];let n=e,i=this.keyEncoding(e.keyEncoding);return e=ch(e,i),e.keyEncoding=i.format,e.limit===0?this.nextTick(r):this._clear(e,o=>{if(o)return r(o);this.emit("clear",n),r()}),r[pe]}_clear(e,r){this.nextTick(r)}iterator(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=ch(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[zs.keyEncoding]=r,e[zs.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new RU(this,e);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new zs(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=ch(e,r),e[zs.keyEncoding]=r,e[zs.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new UU(this,e);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new IU(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=ch(e,r),e[zs.keyEncoding]=r,e[zs.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[be]==="opening")return new OU(this,e);if(this[be]!=="open")throw new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new BU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[wd].push(e)}[bd](){if(this[wd].length===0)return;let e=this[wd];this[wd]=[];for(let r of e)r()}attachResource(e){if(typeof e!="object"||e===null||typeof e.close!="function")throw new TypeError("The first argument must be a resource object");this[Js].add(e)}detachResource(e){this[Js].delete(e)}_chainedBatch(){return new r2(this)}_checkKey(e){if(e==null)return new An("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new An("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};xd.prototype.nextTick=J1();var{AbstractSublevel:$g}=t2()({AbstractLevel:xd});Hg.AbstractLevel=xd;Hg.AbstractSublevel=$g;var ba=function(t,e){return t[be]!=="open"?(t.nextTick(e,new An("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},kU=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var qg=oe(Xs=>{"use strict";l();Xs.AbstractLevel=Vg().AbstractLevel;Xs.AbstractSublevel=Vg().AbstractSublevel;Xs.AbstractIterator=Ko().AbstractIterator;Xs.AbstractKeyIterator=Ko().AbstractKeyIterator;Xs.AbstractValueIterator=Ko().AbstractValueIterator;Xs.AbstractChainedBatch=Ug().AbstractChainedBatch});var o2=oe((qq,i2)=>{l();i2.exports=CU;var NU=Dg();function CU(t,e,r){if(typeof e!="number")throw new Error("second argument must be a Number");let n,i,o,s,c,a=!0,u;Array.isArray(t)?(n=[],o=i=t.length):(s=Object.keys(t),n={},o=i=s.length);function d(h){function p(){r&&r(h,n),r=null}a?NU(p):p()}function f(h,p,g){if(n[h]=g,p&&(c=!0),--o===0||p)d(p);else if(!c&&u<i){let y;s?(y=s[u],u+=1,t[y](function(x,S){f(y,x,S)})):(y=u,u+=1,t[y](function(x,S){f(y,x,S)}))}}u=e,o?s?s.some(function(h,p){return t[h](function(g,y){f(h,g,y)}),p===e-1}):t.some(function(h,p){return h(function(g,y){f(p,g,y)}),p===e-1}):d(null),a=!1}});var Fg=oe((jq,s2)=>{"use strict";l();s2.exports=function(e){let r=e.gte!==void 0?e.gte:e.gt!==void 0?e.gt:void 0,n=e.lte!==void 0?e.lte:e.lt!==void 0?e.lt:void 0,i=e.gte===void 0,o=e.lte===void 0;return r!==void 0&&n!==void 0?IDBKeyRange.bound(r,n,i,o):r!==void 0?IDBKeyRange.lowerBound(r,i):n!==void 0?IDBKeyRange.upperBound(n,o):null}});var jg=oe((Gq,c2)=>{"use strict";l();var LU=new TextEncoder;c2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):LU.encode(t)}});var l2=oe(f2=>{"use strict";l();var{AbstractIterator:PU}=qg(),a2=Fg(),dh=jg(),ei=Symbol("cache"),qi=Symbol("finished"),Cr=Symbol("options"),Fi=Symbol("currentOptions"),Qs=Symbol("position"),Wg=Symbol("location"),xa=Symbol("first"),u2={},Gg=class extends PU{constructor(e,r,n){super(e,n),this[ei]=[],this[qi]=this.limit===0,this[Cr]=n,this[Fi]={...n},this[Qs]=void 0,this[Wg]=r,this[xa]=!0}_nextv(e,r,n){if(this[xa]=!1,this[qi])return this.nextTick(n,null,[]);if(this[ei].length>0)return e=Math.min(e,this[ei].length),this.nextTick(n,null,this[ei].splice(0,e));this[Qs]!==void 0&&(this[Cr].reverse?(this[Fi].lt=this[Qs],this[Fi].lte=void 0):(this[Fi].gt=this[Qs],this[Fi].gte=void 0));let i;try{i=a2(this[Fi])}catch{return this[qi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[Wg]],"readonly"),s=o.objectStore(this[Wg]),c=[];if(this[Cr].reverse){let a=!this[Cr].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[a](i,"prev").onsuccess=u=>{let d=u.target.result;if(d){let{key:f,value:h}=d;this[Qs]=f,c.push([this[Cr].keys&&f!==void 0?dh(f):void 0,this[Cr].values&&h!==void 0?dh(h):void 0]),c.length<e?d.continue():d2(o)}else this[qi]=!0}}else{let a,u,d=()=>{if(a===void 0||u===void 0)return;let f=Math.max(a.length,u.length);f===0||e===1/0?this[qi]=!0:this[Qs]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[Cr].keys&&p!==void 0?dh(p):void 0,this[Cr].values&&g!==void 0?dh(g):void 0]}d2(o)};this[Cr].keys||e<1/0?s.getAllKeys(i,e<1/0?e:void 0).onsuccess=f=>{a=f.target.result,d()}:(a=[],this.nextTick(d)),this[Cr].values?s.getAll(i,e<1/0?e:void 0).onsuccess=f=>{u=f.target.result,d()}:(u=[],this.nextTick(d))}o.onabort=()=>{n(o.error||new Error("aborted by user")),n=null},o.oncomplete=()=>{n(null,c),n=null}}_next(e){if(this[ei].length>0){let[r,n]=this[ei].shift();this.nextTick(e,null,r,n)}else if(this[qi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[xa]&&(this[xa]=!1,r=1),this._nextv(r,u2,(n,i)=>{if(n)return e(n);this[ei]=i,this._next(e)})}}_all(e,r){this[xa]=!1;let n=this[ei].splice(0,this[ei].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(r,null,n);this._nextv(i,u2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[xa]=!0,this[ei]=[],this[qi]=!1,this[Qs]=void 0,this[Fi]={...this[Cr]};let n;try{n=a2(this[Cr])}catch{this[qi]=!0;return}n!==null&&!n.includes(e)?this[qi]=!0:this[Cr].reverse?this[Fi].lte=e:this[Fi].gte=e}};f2.Iterator=Gg;function d2(t){typeof t.commit=="function"&&t.commit()}});var p2=oe((Zq,h2)=>{"use strict";l();h2.exports=function(e,r,n,i,o){if(i.limit===0)return e.nextTick(o);let s=e.db.transaction([r],"readwrite"),c=s.objectStore(r),a=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let u=c.openKeyCursor?"openKeyCursor":"openCursor",d=i.reverse?"prev":"next";c[u](n,d).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(i.limit<=0||++a<i.limit)&&h.continue()})}}});var x2=oe(b2=>{"use strict";l();var{AbstractLevel:MU}=qg(),y2=vn(),KU=o2(),{fromCallback:$U}=cd(),{Iterator:HU}=l2(),g2=jg(),VU=p2(),qU=Fg(),w2="level-js-",Ed=Symbol("idb"),zg=Symbol("namePrefix"),ji=Symbol("location"),Yg=Symbol("version"),ec=Symbol("store"),vd=Symbol("onComplete"),m2=Symbol("promise"),fh=class extends MU{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new y2("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=r||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof e!="string")throw new Error("constructor requires a location string argument");this[ji]=e,this[zg]=i??w2,this[Yg]=parseInt(o||1,10),this[Ed]=null}get location(){return this[ji]}get namePrefix(){return this[zg]}get version(){return this[Yg]}get db(){return this[Ed]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[zg]+this[ji],this[Yg]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[Ed]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[ji])||o.createObjectStore(this[ji])}}[ec](e){return this[Ed].transaction([this[ji]],e).objectStore(this[ji])}[vd](e,r){let n=e.transaction;n.onabort=function(){r(n.error||new Error("aborted by user"))},n.oncomplete=function(){r(null,e.result)}}_get(e,r,n){let i=this[ec]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[vd](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new y2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,g2(c))})}_getMany(e,r,n){let i=this[ec]("readonly"),o=e.map(s=>c=>{let a;try{a=i.get(s)}catch(u){return c(u)}a.onsuccess=()=>{let u=a.result;c(null,u===void 0?u:g2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});KU(o,16,n)}_del(e,r,n){let i=this[ec]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[vd](o,n)}_put(e,r,n,i){let o=this[ec]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[vd](s,i)}_iterator(e){return new HU(this,this[ji],e)}_batch(e,r,n){let i=this[ec]("readwrite"),o=i.transaction,s=0,c;o.onabort=function(){n(c||o.error||new Error("aborted by user"))},o.oncomplete=function(){n()};function a(){let u=e[s++],d=u.key,f;try{f=u.type==="del"?i.delete(d):i.put(u.value,d)}catch(h){c=h,o.abort();return}s<e.length?f.onsuccess=a:typeof o.commit=="function"&&o.commit()}a()}_clear(e,r){let n,i;try{n=qU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return VU(this,this[ji],n,e,r);try{let o=this[ec]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[vd](i,r)}_close(e){this[Ed].close(),this.nextTick(e)}};fh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=w2),r=$U(r,m2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[m2]};b2.BrowserLevel=fh});var Jg=oe(E2=>{l();E2.Level=x2().BrowserLevel});var nt=oe((aF,v2)=>{"use strict";l();v2.exports={ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var Ea=oe((dF,hh)=>{"use strict";l();var{AbortController:S2,AbortSignal:jU}=typeof self<"u"?self:typeof window<"u"?window:void 0;hh.exports=S2;hh.exports.AbortSignal=jU;hh.exports.default=S2});var Zt=oe((lF,Xg)=>{"use strict";l();var WU=Tr(),{kResistStopPropagation:GU,SymbolDispose:zU}=nt(),YU=globalThis.AbortSignal||Ea().AbortSignal,JU=globalThis.AbortController||Ea().AbortController,ZU=Object.getPrototypeOf(async function(){}).constructor,A2=globalThis.Blob||WU.Blob,XU=typeof A2<"u"?function(e){return e instanceof A2}:function(e){return!1},T2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},QU=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},Zg=class extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError(`Expected input to be an Array, got ${typeof e}`);let r="";for(let n=0;n<e.length;n++)r+=` ${e[n].stack}
2
+ `;super(r),this.name="AggregateError",this.errors=e}};Xg.exports={AggregateError:Zg,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...i)=>n?r(n):e(...i))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let i=e.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof ZU},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:XU,deprecate(t,e){return t},addAbortListener:da().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);T2(e,"signal"),QU(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[GU]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[zU](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:YU.any||function(e){if(e.length===1)return e[0];let r=new JU,n=()=>r.abort();return e.forEach(i=>{T2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};Xg.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var or=oe((pF,B2)=>{"use strict";l();var{format:eO,inspect:ph,AggregateError:tO}=Zt(),rO=globalThis.AggregateError||tO,nO=Symbol("kIsNodeError"),iO=["string","function","number","object","Function","Object","boolean","bigint","symbol"],oO=/^([A-Z][a-z0-9]*)+$/,sO="__node_internal_",yh={};function rc(t,e){if(!t)throw new yh.ERR_INTERNAL_ASSERTION(e)}function _2(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function cO(t,e,r){if(typeof e=="function")return rc(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return rc(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:eO(e,...r)}function Kt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(cO(t,e,o))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[nO]=!0,yh[t]=n}function I2(t){let e=sO+t.name;return Object.defineProperty(t,"name",{value:e}),t}function aO(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new rO([e,t],e.message);return r.code=e.code,r}return t||e}var Qg=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new yh.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Kt("ERR_ASSERTION","%s",Error);Kt("ERR_INVALID_ARG_TYPE",(t,e,r)=>{rc(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let i=[],o=[],s=[];for(let a of e)rc(typeof a=="string","All expected entries have to be of type string"),iO.includes(a)?i.push(a.toLowerCase()):oO.test(a)?o.push(a):(rc(a!=="object",'The value "object" should be written as "Object"'),s.push(a));if(o.length>0){let a=i.indexOf("object");a!==-1&&(i.splice(i,a,1),o.push("Object"))}if(i.length>0){switch(i.length){case 1:n+=`of type ${i[0]}`;break;case 2:n+=`one of type ${i[0]} or ${i[1]}`;break;default:{let a=i.pop();n+=`one of type ${i.join(", ")}, or ${a}`}}(o.length>0||s.length>0)&&(n+=" or ")}if(o.length>0){switch(o.length){case 1:n+=`an instance of ${o[0]}`;break;case 2:n+=`an instance of ${o[0]} or ${o[1]}`;break;default:{let a=o.pop();n+=`an instance of ${o.join(", ")}, or ${a}`}}s.length>0&&(n+=" or ")}switch(s.length){case 0:break;case 1:s[0].toLowerCase()!==s[0]&&(n+="an "),n+=`${s[0]}`;break;case 2:n+=`one of ${s[0]} or ${s[1]}`;break;default:{let a=s.pop();n+=`one of ${s.join(", ")}, or ${a}`}}if(r==null)n+=`. Received ${r}`;else if(typeof r=="function"&&r.name)n+=`. Received function ${r.name}`;else if(typeof r=="object"){var c;if((c=r.constructor)!==null&&c!==void 0&&c.name)n+=`. Received an instance of ${r.constructor.name}`;else{let a=ph(r,{depth:-1});n+=`. Received ${a}`}}else{let a=ph(r,{colors:!1});a.length>25&&(a=`${a.slice(0,25)}...`),n+=`. Received type ${typeof r} (${a})`}return n},TypeError);Kt("ERR_INVALID_ARG_VALUE",(t,e,r="is invalid")=>{let n=ph(e);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${t.includes(".")?"property":"argument"} '${t}' ${r}. Received ${n}`},TypeError);Kt("ERR_INVALID_RETURN_VALUE",(t,e,r)=>{var n;let i=r!=null&&(n=r.constructor)!==null&&n!==void 0&&n.name?`instance of ${r.constructor.name}`:`type ${typeof r}`;return`Expected ${t} to be returned from the "${e}" function but got ${i}.`},TypeError);Kt("ERR_MISSING_ARGS",(...t)=>{rc(t.length>0,"At least one arg needs to be specified");let e,r=t.length;switch(t=(Array.isArray(t)?t:[t]).map(n=>`"${n}"`).join(" or "),r){case 1:e+=`The ${t[0]} argument`;break;case 2:e+=`The ${t[0]} and ${t[1]} arguments`;break;default:{let n=t.pop();e+=`The ${t.join(", ")}, and ${n} arguments`}break}return`${e} must be specified`},TypeError);Kt("ERR_OUT_OF_RANGE",(t,e,r)=>{rc(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=_2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=_2(n)),n+="n"):n=ph(r),`The value of "${t}" is out of range. It must be ${e}. Received ${n}`},RangeError);Kt("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Kt("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Kt("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Kt("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Kt("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Kt("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Kt("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Kt("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Kt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Kt("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Kt("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);B2.exports={AbortError:Qg,aggregateTwoErrors:I2(aO),hideStackFrames:I2,codes:yh}});var Sa=oe((gF,M2)=>{"use strict";l();var{ArrayIsArray:tm,ArrayPrototypeIncludes:D2,ArrayPrototypeJoin:k2,ArrayPrototypeMap:uO,NumberIsInteger:rm,NumberIsNaN:dO,NumberMAX_SAFE_INTEGER:fO,NumberMIN_SAFE_INTEGER:lO,NumberParseInt:hO,ObjectPrototypeHasOwnProperty:pO,RegExpPrototypeExec:N2,String:yO,StringPrototypeToUpperCase:gO,StringPrototypeTrim:mO}=nt(),{hideStackFrames:tn,codes:{ERR_SOCKET_BAD_PORT:wO,ERR_INVALID_ARG_TYPE:Xt,ERR_INVALID_ARG_VALUE:va,ERR_OUT_OF_RANGE:nc,ERR_UNKNOWN_SIGNAL:R2}}=or(),{normalizeEncoding:bO}=Zt(),{isAsyncFunction:xO,isArrayBufferView:EO}=Zt().types,U2={};function vO(t){return t===(t|0)}function SO(t){return t===t>>>0}var AO=/^[0-7]+$/,TO="must be a 32-bit unsigned integer or an octal string";function _O(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(N2(AO,t)===null)throw new va(e,t,TO);t=hO(t,8)}return C2(t,e),t}var IO=tn((t,e,r=lO,n=fO)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!rm(t))throw new nc(e,"an integer",t);if(t<r||t>n)throw new nc(e,`>= ${r} && <= ${n}`,t)}),BO=tn((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!rm(t))throw new nc(e,"an integer",t);if(t<r||t>n)throw new nc(e,`>= ${r} && <= ${n}`,t)}),C2=tn((t,e,r=!1)=>{if(typeof t!="number")throw new Xt(e,"number",t);if(!rm(t))throw new nc(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new nc(e,`>= ${n} && <= ${i}`,t)});function nm(t,e){if(typeof t!="string")throw new Xt(e,"string",t)}function RO(t,e,r=void 0,n){if(typeof t!="number")throw new Xt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&dO(t))throw new nc(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var UO=tn((t,e,r)=>{if(!D2(r,t)){let i="must be one of: "+k2(uO(r,o=>typeof o=="string"?`'${o}'`:yO(o)),", ");throw new va(e,t,i)}});function L2(t,e){if(typeof t!="boolean")throw new Xt(e,"boolean",t)}function em(t,e,r){return t==null||!pO(t,e)?r:t[e]}var OO=tn((t,e,r=null)=>{let n=em(r,"allowArray",!1),i=em(r,"allowFunction",!1);if(!em(r,"nullable",!1)&&t===null||!n&&tm(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new Xt(e,"Object",t)}),DO=tn((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Xt(e,"a dictionary",t)}),gh=tn((t,e,r=0)=>{if(!tm(t))throw new Xt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new va(e,t,n)}});function kO(t,e){gh(t,e);for(let r=0;r<t.length;r++)nm(t[r],`${e}[${r}]`)}function NO(t,e){gh(t,e);for(let r=0;r<t.length;r++)L2(t[r],`${e}[${r}]`)}function CO(t,e){gh(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Xt(i,"AbortSignal",n);P2(n,i)}}function LO(t,e="signal"){if(nm(t,e),U2[t]===void 0)throw U2[gO(t)]!==void 0?new R2(t+" (signals must use all capital letters)"):new R2(t)}var PO=tn((t,e="buffer")=>{if(!EO(t))throw new Xt(e,["Buffer","TypedArray","DataView"],t)});function MO(t,e){let r=bO(e),n=t.length;if(r==="hex"&&n%2!==0)throw new va("encoding",e,`is invalid for data of length ${n}`)}function KO(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&mO(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new wO(e,t,r);return t|0}var P2=tn((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Xt(e,"AbortSignal",t)}),$O=tn((t,e)=>{if(typeof t!="function")throw new Xt(e,"Function",t)}),HO=tn((t,e)=>{if(typeof t!="function"||xO(t))throw new Xt(e,"Function",t)}),VO=tn((t,e)=>{if(t!==void 0)throw new Xt(e,"undefined",t)});function qO(t,e,r){if(!D2(r,t))throw new Xt(e,`('${k2(r,"|")}')`,t)}var FO=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function O2(t,e){if(typeof t>"u"||!N2(FO,t))throw new va(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function jO(t){if(typeof t=="string")return O2(t,"hints"),t;if(tm(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];O2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new va("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}M2.exports={isInt32:vO,isUint32:SO,parseFileMode:_O,validateArray:gh,validateStringArray:kO,validateBooleanArray:NO,validateAbortSignalArray:CO,validateBoolean:L2,validateBuffer:PO,validateDictionary:DO,validateEncoding:MO,validateFunction:$O,validateInt32:BO,validateInteger:IO,validateNumber:RO,validateObject:OO,validateOneOf:UO,validatePlainFunction:HO,validatePort:KO,validateSignalName:LO,validateString:nm,validateUint32:C2,validateUndefined:VO,validateUnion:qO,validateAbortSignal:P2,validateLinkHeaderValue:jO}});var ri=oe((wF,Q2)=>{"use strict";l();var{SymbolAsyncIterator:K2,SymbolIterator:$2,SymbolFor:ic}=nt(),H2=ic("nodejs.stream.destroyed"),V2=ic("nodejs.stream.errored"),im=ic("nodejs.stream.readable"),om=ic("nodejs.stream.writable"),q2=ic("nodejs.stream.disturbed"),WO=ic("nodejs.webstream.isClosedPromise"),GO=ic("nodejs.webstream.controllerErrorFunction");function mh(t,e=!1){var r;return!!(t&&typeof t.pipe=="function"&&typeof t.on=="function"&&(!e||typeof t.pause=="function"&&typeof t.resume=="function")&&(!t._writableState||((r=t._readableState)===null||r===void 0?void 0:r.readable)!==!1)&&(!t._writableState||t._readableState))}function wh(t){var e;return!!(t&&typeof t.write=="function"&&typeof t.on=="function"&&(!t._readableState||((e=t._writableState)===null||e===void 0?void 0:e.writable)!==!1))}function zO(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function ti(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function F2(t){return!!(t&&!ti(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function j2(t){return!!(t&&!ti(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function W2(t){return!!(t&&!ti(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function YO(t){return F2(t)||j2(t)||W2(t)}function JO(t,e){return t==null?!1:e===!0?typeof t[K2]=="function":e===!1?typeof t[$2]=="function":typeof t[K2]=="function"||typeof t[$2]=="function"}function bh(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[H2]||n!=null&&n.destroyed)}function G2(t){if(!wh(t))return null;if(t.writableEnded===!0)return!0;let e=t._writableState;return e!=null&&e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function ZO(t,e){if(!wh(t))return null;if(t.writableFinished===!0)return!0;let r=t._writableState;return r!=null&&r.errored?!1:typeof r?.finished!="boolean"?null:!!(r.finished||e===!1&&r.ended===!0&&r.length===0)}function XO(t){if(!mh(t))return null;if(t.readableEnded===!0)return!0;let e=t._readableState;return!e||e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function z2(t,e){if(!mh(t))return null;let r=t._readableState;return r!=null&&r.errored?!1:typeof r?.endEmitted!="boolean"?null:!!(r.endEmitted||e===!1&&r.ended===!0&&r.length===0)}function Y2(t){return t&&t[im]!=null?t[im]:typeof t?.readable!="boolean"?null:bh(t)?!1:mh(t)&&t.readable&&!z2(t)}function J2(t){return t&&t[om]!=null?t[om]:typeof t?.writable!="boolean"?null:bh(t)?!1:wh(t)&&t.writable&&!G2(t)}function QO(t,e){return ti(t)?bh(t)?!0:!(e?.readable!==!1&&Y2(t)||e?.writable!==!1&&J2(t)):null}function e5(t){var e,r;return ti(t)?t.writableErrored?t.writableErrored:(e=(r=t._writableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function t5(t){var e,r;return ti(t)?t.readableErrored?t.readableErrored:(e=(r=t._readableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function r5(t){if(!ti(t))return null;if(typeof t.closed=="boolean")return t.closed;let e=t._writableState,r=t._readableState;return typeof e?.closed=="boolean"||typeof r?.closed=="boolean"?e?.closed||r?.closed:typeof t._closed=="boolean"&&Z2(t)?t._closed:null}function Z2(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function X2(t){return typeof t._sent100=="boolean"&&Z2(t)}function n5(t){var e;return typeof t._consuming=="boolean"&&typeof t._dumped=="boolean"&&((e=t.req)===null||e===void 0?void 0:e.upgradeOrConnect)===void 0}function i5(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&X2(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function o5(t){var e;return!!(t&&((e=t[q2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function s5(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[V2])!==null&&s!==void 0?s:t.readableErrored)!==null&&o!==void 0?o:t.writableErrored)!==null&&i!==void 0?i:(c=t._readableState)===null||c===void 0?void 0:c.errorEmitted)!==null&&n!==void 0?n:(a=t._writableState)===null||a===void 0?void 0:a.errorEmitted)!==null&&r!==void 0?r:(u=t._readableState)===null||u===void 0?void 0:u.errored)!==null&&e!==void 0?e:!((d=t._writableState)===null||d===void 0)&&d.errored))}Q2.exports={isDestroyed:bh,kIsDestroyed:H2,isDisturbed:o5,kIsDisturbed:q2,isErrored:s5,kIsErrored:V2,isReadable:Y2,kIsReadable:im,kIsClosedPromise:WO,kControllerErrorFunction:GO,kIsWritable:om,isClosed:r5,isDuplexNodeStream:zO,isFinished:QO,isIterable:JO,isReadableNodeStream:mh,isReadableStream:F2,isReadableEnded:XO,isReadableFinished:z2,isReadableErrored:t5,isNodeStream:ti,isWebStream:YO,isWritable:J2,isWritableNodeStream:wh,isWritableStream:j2,isWritableEnded:G2,isWritableFinished:ZO,isWritableErrored:e5,isServerRequest:n5,isServerResponse:X2,willEmitClose:i5,isTransformStream:W2}});var Wi=oe((xF,dm)=>{l();var qo=Ei(),{AbortError:aS,codes:c5}=or(),{ERR_INVALID_ARG_TYPE:a5,ERR_STREAM_PREMATURE_CLOSE:eS}=c5,{kEmptyObject:cm,once:am}=Zt(),{validateAbortSignal:u5,validateFunction:d5,validateObject:f5,validateBoolean:l5}=Sa(),{Promise:h5,PromisePrototypeThen:p5,SymbolDispose:uS}=nt(),{isClosed:y5,isReadable:tS,isReadableNodeStream:sm,isReadableStream:g5,isReadableFinished:rS,isReadableErrored:nS,isWritable:iS,isWritableNodeStream:oS,isWritableStream:m5,isWritableFinished:sS,isWritableErrored:cS,isNodeStream:w5,willEmitClose:b5,kIsClosedPromise:x5}=ri(),Aa;function E5(t){return t.setHeader&&typeof t.abort=="function"}var um=()=>{};function dS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=cm):e==null?e=cm:f5(e,"options"),d5(r,"callback"),u5(e.signal,"options.signal"),r=am(r),g5(t)||m5(t))return v5(t,e,r);if(!w5(t))throw new a5("stream",["ReadableStream","WritableStream","Stream"],t);let o=(n=e.readable)!==null&&n!==void 0?n:sm(t),s=(i=e.writable)!==null&&i!==void 0?i:oS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=b5(t)&&sm(t)===o&&oS(t)===s,f=sS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=rS(t,!1),g=()=>{p=!0,t.destroyed&&(d=!1),!(d&&(!t.writable||s))&&(!s||f)&&r.call(t)},y=T=>{r.call(t,T)},x=y5(t),S=()=>{x=!0;let T=cS(t)||nS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&sm(t,!0)&&!rS(t,!1))return r.call(t,new eS);if(s&&!f&&!sS(t,!1))return r.call(t,new eS);r.call(t)},_=()=>{x=!0;let T=cS(t)||nS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};E5(t)?(t.on("complete",h),d||t.on("abort",S),t.req?A():t.on("request",A)):s&&!c&&(t.on("end",u),t.on("close",u)),!d&&typeof t.aborted=="boolean"&&t.on("aborted",S),t.on("end",g),t.on("finish",h),e.error!==!1&&t.on("error",y),t.on("close",S),x?qo.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||qo.nextTick(_):(!o&&(!d||tS(t))&&(f||iS(t)===!1)||!s&&(!d||iS(t))&&(p||tS(t)===!1)||a&&t.req&&t.aborted)&&qo.nextTick(_);let O=()=>{r=um,t.removeListener("aborted",S),t.removeListener("complete",h),t.removeListener("abort",S),t.removeListener("request",A),t.req&&t.req.removeListener("finish",h),t.removeListener("end",u),t.removeListener("close",u),t.removeListener("finish",h),t.removeListener("end",g),t.removeListener("error",y),t.removeListener("close",S)};if(e.signal&&!x){let T=()=>{let M=r;O(),M.call(t,new aS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)qo.nextTick(T);else{Aa=Aa||Zt().addAbortListener;let M=Aa(e.signal,T),q=r;r=am((...j)=>{M[uS](),q.apply(t,j)})}}return O}function v5(t,e,r){let n=!1,i=um;if(e.signal)if(i=()=>{n=!0,r.call(t,new aS(void 0,{cause:e.signal.reason}))},e.signal.aborted)qo.nextTick(i);else{Aa=Aa||Zt().addAbortListener;let s=Aa(e.signal,i),c=r;r=am((...a)=>{s[uS](),c.apply(t,a)})}let o=(...s)=>{n||qo.nextTick(()=>r.apply(t,s))};return p5(t[x5].promise,o,o),um}function S5(t,e){var r;let n=!1;return e===null&&(e=cm),(r=e)!==null&&r!==void 0&&r.cleanup&&(l5(e.cleanup,"cleanup"),n=e.cleanup),new h5((i,o)=>{let s=dS(t,e,c=>{n&&s(),c?o(c):i()})})}dm.exports=dS;dm.exports.finished=S5});var oc=oe((vF,wS)=>{"use strict";l();var ni=Ei(),{aggregateTwoErrors:A5,codes:{ERR_MULTIPLE_CALLBACK:T5},AbortError:_5}=or(),{Symbol:hS}=nt(),{kIsDestroyed:I5,isDestroyed:B5,isFinished:R5,isServerRequest:U5}=ri(),pS=hS("kDestroy"),fm=hS("kConstruct");function yS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function O5(t,e){let r=this._readableState,n=this._writableState,i=n||r;return n!=null&&n.destroyed||r!=null&&r.destroyed?(typeof e=="function"&&e(),this):(yS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?fS(this,t,e):this.once(pS,function(o){fS(this,A5(o,t),e)}),this)}function fS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;yS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ni.nextTick(D5,t,o):ni.nextTick(gS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function D5(t,e){lm(t,e),gS(t)}function gS(t){let e=t._readableState,r=t._writableState;r&&(r.closeEmitted=!0),e&&(e.closeEmitted=!0),(r!=null&&r.emitClose||e!=null&&e.emitClose)&&t.emit("close")}function lm(t,e){let r=t._readableState,n=t._writableState;n!=null&&n.errorEmitted||r!=null&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),t.emit("error",e))}function k5(){let t=this._readableState,e=this._writableState;t&&(t.constructed=!0,t.closed=!1,t.closeEmitted=!1,t.destroyed=!1,t.errored=null,t.errorEmitted=!1,t.reading=!1,t.ended=t.readable===!1,t.endEmitted=t.readable===!1),e&&(e.constructed=!0,e.destroyed=!1,e.closed=!1,e.closeEmitted=!1,e.errored=null,e.errorEmitted=!1,e.finalCalled=!1,e.prefinished=!1,e.ended=e.writable===!1,e.ending=e.writable===!1,e.finished=e.writable===!1)}function hm(t,e,r){let n=t._readableState,i=t._writableState;if(i!=null&&i.destroyed||n!=null&&n.destroyed)return this;n!=null&&n.autoDestroy||i!=null&&i.autoDestroy?t.destroy(e):e&&(e.stack,i&&!i.errored&&(i.errored=e),n&&!n.errored&&(n.errored=e),r?ni.nextTick(lm,t,e):lm(t,e))}function N5(t,e){if(typeof t._construct!="function")return;let r=t._readableState,n=t._writableState;r&&(r.constructed=!1),n&&(n.constructed=!1),t.once(fm,e),!(t.listenerCount(fm)>1)&&ni.nextTick(C5,t)}function C5(t){let e=!1;function r(n){if(e){hm(t,n??new T5);return}e=!0;let i=t._readableState,o=t._writableState,s=o||i;i&&(i.constructed=!0),o&&(o.constructed=!0),s.destroyed?t.emit(pS,n):n?hm(t,n,!0):ni.nextTick(L5,t)}try{t._construct(n=>{ni.nextTick(r,n)})}catch(n){ni.nextTick(r,n)}}function L5(t){t.emit(fm)}function lS(t){return t?.setHeader&&typeof t.abort=="function"}function mS(t){t.emit("close")}function P5(t,e){t.emit("error",e),ni.nextTick(mS,t)}function M5(t,e){!t||B5(t)||(!e&&!R5(t)&&(e=new _5),U5(t)?(t.socket=null,t.destroy(e)):lS(t)?t.abort():lS(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ni.nextTick(P5,t,e):ni.nextTick(mS,t),t.destroyed||(t[I5]=!0))}wS.exports={construct:N5,destroyer:M5,destroy:O5,undestroy:k5,errorOrDestroy:hm}});var vh=oe((AF,xS)=>{"use strict";l();var{ArrayIsArray:K5,ObjectSetPrototypeOf:bS}=nt(),{EventEmitter:xh}=da();function Eh(t){xh.call(this,t)}bS(Eh.prototype,xh.prototype);bS(Eh,xh);Eh.prototype.pipe=function(t,e){let r=this;function n(d){t.writable&&t.write(d)===!1&&r.pause&&r.pause()}r.on("data",n);function i(){r.readable&&r.resume&&r.resume()}t.on("drain",i),!t._isStdio&&(!e||e.end!==!1)&&(r.on("end",s),r.on("close",c));let o=!1;function s(){o||(o=!0,t.end())}function c(){o||(o=!0,typeof t.destroy=="function"&&t.destroy())}function a(d){u(),xh.listenerCount(this,"error")===0&&this.emit("error",d)}pm(r,"error",a),pm(t,"error",a);function u(){r.removeListener("data",n),t.removeListener("drain",i),r.removeListener("end",s),r.removeListener("close",c),r.removeListener("error",a),t.removeListener("error",a),r.removeListener("end",u),r.removeListener("close",u),t.removeListener("close",u)}return r.on("end",u),r.on("close",u),t.on("close",u),t.emit("pipe",r),t};function pm(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):K5(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}xS.exports={Stream:Eh,prependListener:pm}});var Sd=oe((_F,Sh)=>{"use strict";l();var{SymbolDispose:$5}=nt(),{AbortError:ES,codes:H5}=or(),{isNodeStream:vS,isWebStream:V5,kControllerErrorFunction:q5}=ri(),F5=Wi(),{ERR_INVALID_ARG_TYPE:SS}=H5,ym,j5=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new SS(e,"AbortSignal",t)};Sh.exports.addAbortSignal=function(e,r){if(j5(e,"signal"),!vS(r)&&!V5(r))throw new SS("stream",["ReadableStream","WritableStream","Stream"],r);return Sh.exports.addAbortSignalNoValidate(e,r)};Sh.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=vS(e)?()=>{e.destroy(new ES(void 0,{cause:t.reason}))}:()=>{e[q5](new ES(void 0,{cause:t.reason}))};if(t.aborted)r();else{ym=ym||Zt().addAbortListener;let n=ym(t,r);F5(e,n[$5])}return e}});var _S=oe((RF,TS)=>{"use strict";l();var{StringPrototypeSlice:AS,SymbolIterator:W5,TypedArrayPrototypeSet:Ah,Uint8Array:G5}=nt(),{Buffer:gm}=Tr(),{inspect:z5}=Zt();TS.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){let r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length}unshift(e){let r={data:e,next:this.head};this.length===0&&(this.tail=r),this.head=r,++this.length}shift(){if(this.length===0)return;let e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(this.length===0)return"";let r=this.head,n=""+r.data;for(;(r=r.next)!==null;)n+=e+r.data;return n}concat(e){if(this.length===0)return gm.alloc(0);let r=gm.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)Ah(r,n.data,i),i+=n.data.length,n=n.next;return r}consume(e,r){let n=this.head.data;if(e<n.length){let i=n.slice(0,e);return this.head.data=n.slice(e),i}return e===n.length?this.shift():r?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[W5](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let r="",n=this.head,i=0;do{let o=n.data;if(e>o.length)r+=o,e-=o.length;else{e===o.length?(r+=o,++i,n.next?this.head=n.next:this.head=this.tail=null):(r+=AS(o,0,e),this.head=n,n.data=AS(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=gm.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)Ah(r,s,n-e),e-=s.length;else{e===s.length?(Ah(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Ah(r,new G5(s.buffer,s.byteOffset,e),n-e),this.head=i,i.data=s.slice(e));break}++o}while((i=i.next)!==null);return this.length-=o,r}[Symbol.for("nodejs.util.inspect.custom")](e,r){return z5(this,{...r,depth:0,customInspect:!1})}}});var Ad=oe((OF,US)=>{"use strict";l();var{MathFloor:Y5,NumberIsInteger:J5}=nt(),{validateInteger:Z5}=Sa(),{ERR_INVALID_ARG_VALUE:X5}=or().codes,IS=16*1024,BS=16;function Q5(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function RS(t){return t?BS:IS}function e3(t,e){Z5(e,"value",0),t?BS=e:IS=e}function t3(t,e,r,n){let i=Q5(e,n,r);if(i!=null){if(!J5(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new X5(o,i)}return Y5(i)}return RS(t.objectMode)}US.exports={getHighWaterMark:t3,getDefaultHighWaterMark:RS,setDefaultHighWaterMark:e3}});var kS=oe((mm,DS)=>{l();var Th=Tr(),ii=Th.Buffer;function OS(t,e){for(var r in t)e[r]=t[r]}ii.from&&ii.alloc&&ii.allocUnsafe&&ii.allocUnsafeSlow?DS.exports=Th:(OS(Th,mm),mm.Buffer=sc);function sc(t,e,r){return ii(t,e,r)}sc.prototype=Object.create(ii.prototype);OS(ii,sc);sc.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ii(t,e,r)};sc.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=ii(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};sc.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ii(t)};sc.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Th.SlowBuffer(t)}});var LS=oe(CS=>{"use strict";l();var bm=kS().Buffer,NS=bm.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function r3(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function n3(t){var e=r3(t);if(typeof e!="string"&&(bm.isEncoding===NS||!NS(t)))throw new Error("Unknown encoding: "+t);return e||t}CS.StringDecoder=Td;function Td(t){this.encoding=n3(t);var e;switch(this.encoding){case"utf16le":this.text=u3,this.end=d3,e=4;break;case"utf8":this.fillLast=s3,e=4;break;case"base64":this.text=f3,this.end=l3,e=3;break;default:this.write=h3,this.end=p3;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=bm.allocUnsafe(e)}Td.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||""};Td.prototype.end=a3;Td.prototype.text=c3;Td.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};function wm(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function i3(t,e,r){var n=e.length-1;if(n<r)return 0;var i=wm(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=wm(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=wm(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function o3(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function s3(t){var e=this.lastTotal-this.lastNeed,r=o3(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function c3(t,e){var r=i3(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function a3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function u3(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function d3(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function f3(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function l3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function h3(t){return t.toString(this.encoding)}function p3(t){return t&&t.length?this.write(t):""}});var xm=oe((LF,$S)=>{"use strict";l();var PS=Ei(),{PromisePrototypeThen:y3,SymbolAsyncIterator:MS,SymbolIterator:KS}=nt(),{Buffer:g3}=Tr(),{ERR_INVALID_ARG_TYPE:m3,ERR_STREAM_NULL_VALUES:w3}=or().codes;function b3(t,e,r){let n;if(typeof e=="string"||e instanceof g3)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[MS])i=!0,n=e[MS]();else if(e&&e[KS])i=!1,n=e[KS]();else throw new m3("iterable",["Iterable"],e);let o=new t({objectMode:!0,highWaterMark:1,...r}),s=!1;o._read=function(){s||(s=!0,a())},o._destroy=function(u,d){y3(c(u),()=>PS.nextTick(d,u),f=>PS.nextTick(d,f||u))};async function c(u){let d=u!=null,f=typeof n.throw=="function";if(d&&f){let{value:h,done:p}=await n.throw(u);if(await h,p)return}if(typeof n.return=="function"){let{value:h}=await n.return();await h}}async function a(){for(;;){try{let{value:u,done:d}=i?await n.next():n.next();if(d)o.push(null);else{let f=u&&typeof u.then=="function"?await u:u;if(f===null)throw s=!1,new w3;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}$S.exports=b3});var Id=oe((MF,iA)=>{l();var Tn=Ei(),{ArrayPrototypeIndexOf:x3,NumberIsInteger:E3,NumberIsNaN:v3,NumberParseInt:S3,ObjectDefineProperties:Bm,ObjectKeys:A3,ObjectSetPrototypeOf:qS,Promise:FS,SafeSet:T3,SymbolAsyncDispose:_3,SymbolAsyncIterator:I3,Symbol:B3}=nt();iA.exports=ye;ye.ReadableState=Rh;var{EventEmitter:R3}=da(),{Stream:Fo,prependListener:U3}=vh(),{Buffer:Em}=Tr(),{addAbortSignal:O3}=Sd(),jS=Wi(),Ee=Zt().debuglog("stream",t=>{Ee=t}),D3=_S(),Ia=oc(),{getHighWaterMark:k3,getDefaultHighWaterMark:N3}=Ad(),{aggregateTwoErrors:HS,codes:{ERR_INVALID_ARG_TYPE:C3,ERR_METHOD_NOT_IMPLEMENTED:L3,ERR_OUT_OF_RANGE:P3,ERR_STREAM_PUSH_AFTER_EOF:M3,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:K3},AbortError:$3}=or(),{validateObject:H3}=Sa(),cc=B3("kPaused"),{StringDecoder:WS}=LS(),V3=xm();qS(ye.prototype,Fo.prototype);qS(ye,Fo);var vm=()=>{},{errorOrDestroy:Ta}=Ia,_a=1,q3=2,GS=4,_d=8,zS=16,_h=32,Ih=64,YS=128,F3=256,j3=512,W3=1024,_m=2048,Im=4096,G3=8192,z3=16384,Y3=32768,JS=65536,J3=1<<17,Z3=1<<18;function At(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Bm(Rh.prototype,{objectMode:At(_a),ended:At(q3),endEmitted:At(GS),reading:At(_d),constructed:At(zS),sync:At(_h),needReadable:At(Ih),emittedReadable:At(YS),readableListening:At(F3),resumeScheduled:At(j3),errorEmitted:At(W3),emitClose:At(_m),autoDestroy:At(Im),destroyed:At(G3),closed:At(z3),closeEmitted:At(Y3),multiAwaitDrain:At(JS),readingMore:At(J3),dataEmitted:At(Z3)});function Rh(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.state=_m|Im|zS|_h,t&&t.objectMode&&(this.state|=_a),r&&t&&t.readableObjectMode&&(this.state|=_a),this.highWaterMark=t?k3(this,t,"readableHighWaterMark",r):N3(!1),this.buffer=new D3,this.length=0,this.pipes=[],this.flowing=null,this[cc]=null,t&&t.emitClose===!1&&(this.state&=~_m),t&&t.autoDestroy===!1&&(this.state&=~Im),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new WS(t.encoding),this.encoding=t.encoding)}function ye(t){if(!(this instanceof ye))return new ye(t);let e=this instanceof oi();this._readableState=new Rh(t,this,e),t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&!e&&O3(t.signal,this)),Fo.call(this,t),Ia.construct(this,()=>{this._readableState.needReadable&&Bh(this,this._readableState)})}ye.prototype.destroy=Ia.destroy;ye.prototype._undestroy=Ia.undestroy;ye.prototype._destroy=function(t,e){e(t)};ye.prototype[R3.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[_3]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new $3,this.destroy(t)),new FS((e,r)=>jS(this,n=>n&&n!==t?r(n):e(null)))};ye.prototype.push=function(t,e){return ZS(this,t,e,!1)};ye.prototype.unshift=function(t,e){return ZS(this,t,e,!0)};function ZS(t,e,r,n){Ee("readableAddChunk",e);let i=t._readableState,o;if(i.state&_a||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=Em.from(e,r).toString(i.encoding):(e=Em.from(e,r),r=""))):e instanceof Em?r="":Fo._isUint8Array(e)?(e=Fo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new C3("chunk",["string","Buffer","Uint8Array"],e))),o)Ta(t,o);else if(e===null)i.state&=~_d,eD(t,i);else if(i.state&_a||e&&e.length>0)if(n)if(i.state&GS)Ta(t,new K3);else{if(i.destroyed||i.errored)return!1;Sm(t,i,e,!0)}else if(i.ended)Ta(t,new M3);else{if(i.destroyed||i.errored)return!1;i.state&=~_d,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?Sm(t,i,e,!1):Bh(t,i)):Sm(t,i,e,!1)}else n||(i.state&=~_d,Bh(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function Sm(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&JS?e.awaitDrainWriters.clear():e.awaitDrainWriters=null,e.dataEmitted=!0,t.emit("data",r)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.state&Ih&&Uh(t)),Bh(t,e)}ye.prototype.isPaused=function(){let t=this._readableState;return t[cc]===!0||t.flowing===!1};ye.prototype.setEncoding=function(t){let e=new WS(t);this._readableState.decoder=e,this._readableState.encoding=this._readableState.decoder.encoding;let r=this._readableState.buffer,n="";for(let i of r)n+=e.write(i);return r.clear(),n!==""&&r.push(n),this._readableState.length=n.length,this};var X3=1073741824;function Q3(t){if(t>X3)throw new P3("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function VS(t,e){return t<=0||e.length===0&&e.ended?0:e.state&_a?1:v3(t)?e.flowing&&e.length?e.buffer.first().length:e.length:t<=e.length?t:e.ended?e.length:0}ye.prototype.read=function(t){Ee("read",t),t===void 0?t=NaN:E3(t)||(t=S3(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=Q3(t)),t!==0&&(e.state&=~YS),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Ee("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Am(this):Uh(this),null;if(t=VS(t,e),t===0&&e.ended)return e.length===0&&Am(this),null;let n=(e.state&Ih)!==0;if(Ee("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,Ee("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,Ee("reading, ended or constructing",n);else if(n){Ee("do read"),e.state|=_d|_h,e.length===0&&(e.state|=Ih);try{this._read(e.highWaterMark)}catch(o){Ta(this,o)}e.state&=~_h,e.reading||(t=VS(r,e))}let i;return t>0?i=rA(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.multiAwaitDrain?e.awaitDrainWriters.clear():e.awaitDrainWriters=null),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Am(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function eD(t,e){if(Ee("onEofChunk"),!e.ended){if(e.decoder){let r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?Uh(t):(e.needReadable=!1,e.emittedReadable=!0,XS(t))}}function Uh(t){let e=t._readableState;Ee("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Ee("emitReadable",e.flowing),e.emittedReadable=!0,Tn.nextTick(XS,t))}function XS(t){let e=t._readableState;Ee("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&!e.errored&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,eA(t)}function Bh(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,Tn.nextTick(tD,t,e))}function tD(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(Ee("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}ye.prototype._read=function(t){throw new L3("_read()")};ye.prototype.pipe=function(t,e){let r=this,n=this._readableState;n.pipes.length===1&&(n.multiAwaitDrain||(n.multiAwaitDrain=!0,n.awaitDrainWriters=new T3(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),Ee("pipe count=%d opts=%j",n.pipes.length,e);let o=(!e||e.end!==!1)&&t!==Tn.stdout&&t!==Tn.stderr?c:x;n.endEmitted?Tn.nextTick(o):r.once("end",o),t.on("unpipe",s);function s(S,_){Ee("onunpipe"),S===r&&_&&_.hasUnpiped===!1&&(_.hasUnpiped=!0,d())}function c(){Ee("onend"),t.end()}let a,u=!1;function d(){Ee("cleanup"),t.removeListener("close",g),t.removeListener("finish",y),a&&t.removeListener("drain",a),t.removeListener("error",p),t.removeListener("unpipe",s),r.removeListener("end",c),r.removeListener("end",x),r.removeListener("data",h),u=!0,a&&n.awaitDrainWriters&&(!t._writableState||t._writableState.needDrain)&&a()}function f(){u||(n.pipes.length===1&&n.pipes[0]===t?(Ee("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(Ee("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=rD(r,t),t.on("drain",a))}r.on("data",h);function h(S){Ee("ondata");let _=t.write(S);Ee("dest.write",_),_===!1&&f()}function p(S){if(Ee("onerror",S),x(),t.removeListener("error",p),t.listenerCount("error")===0){let _=t._writableState||t._readableState;_&&!_.errorEmitted?Ta(t,S):t.emit("error",S)}}U3(t,"error",p);function g(){t.removeListener("finish",y),x()}t.once("close",g);function y(){Ee("onfinish"),t.removeListener("close",g),x()}t.once("finish",y);function x(){Ee("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(Ee("pipe resume"),r.resume()),t};function rD(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(Ee("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(Ee("pipeOnDrain",n.awaitDrainWriters.size),n.awaitDrainWriters.delete(e)),(!n.awaitDrainWriters||n.awaitDrainWriters.size===0)&&t.listenerCount("data")&&t.resume()}}ye.prototype.unpipe=function(t){let e=this._readableState,r={hasUnpiped:!1};if(e.pipes.length===0)return this;if(!t){let i=e.pipes;e.pipes=[],this.pause();for(let o=0;o<i.length;o++)i[o].emit("unpipe",this,{hasUnpiped:!1});return this}let n=x3(e.pipes,t);return n===-1?this:(e.pipes.splice(n,1),e.pipes.length===0&&this.pause(),t.emit("unpipe",this,r),this)};ye.prototype.on=function(t,e){let r=Fo.prototype.on.call(this,t,e),n=this._readableState;return t==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,Ee("on readable",n.length,n.reading),n.length?Uh(this):n.reading||Tn.nextTick(nD,this)),r};ye.prototype.addListener=ye.prototype.on;ye.prototype.removeListener=function(t,e){let r=Fo.prototype.removeListener.call(this,t,e);return t==="readable"&&Tn.nextTick(QS,this),r};ye.prototype.off=ye.prototype.removeListener;ye.prototype.removeAllListeners=function(t){let e=Fo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&Tn.nextTick(QS,this),e};function QS(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[cc]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function nD(t){Ee("readable nexttick read 0"),t.read(0)}ye.prototype.resume=function(){let t=this._readableState;return t.flowing||(Ee("resume"),t.flowing=!t.readableListening,iD(this,t)),t[cc]=!1,this};function iD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,Tn.nextTick(oD,t,e))}function oD(t,e){Ee("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),eA(t),e.flowing&&!e.reading&&t.read(0)}ye.prototype.pause=function(){return Ee("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Ee("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[cc]=!0,this};function eA(t){let e=t._readableState;for(Ee("flow",e.flowing);e.flowing&&t.read()!==null;);}ye.prototype.wrap=function(t){let e=!1;t.on("data",n=>{!this.push(n)&&t.pause&&(e=!0,t.pause())}),t.on("end",()=>{this.push(null)}),t.on("error",n=>{Ta(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=A3(t);for(let n=1;n<r.length;n++){let i=r[n];this[i]===void 0&&typeof t[i]=="function"&&(this[i]=t[i].bind(t))}return this};ye.prototype[I3]=function(){return tA(this)};ye.prototype.iterator=function(t){return t!==void 0&&H3(t,"options"),tA(this,t)};function tA(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=sD(t,e);return r.stream=t,r}async function*sD(t,e){let r=vm;function n(s){this===t?(r(),r=vm):r=s}t.on("readable",n);let i,o=jS(t,{writable:!1},s=>{i=s?HS(i,s):null,r(),r=vm});try{for(;;){let s=t.destroyed?null:t.read();if(s!==null)yield s;else{if(i)throw i;if(i===null)return;await new FS(n)}}}catch(s){throw i=HS(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Ia.destroyer(t,null):(t.off("readable",n),o())}}Bm(ye.prototype,{readable:{__proto__:null,get(){let t=this._readableState;return!!t&&t.readable!==!1&&!t.destroyed&&!t.errorEmitted&&!t.endEmitted},set(t){this._readableState&&(this._readableState.readable=!!t)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(t){this._readableState&&(this._readableState.destroyed=t)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});Bm(Rh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[cc]!==!1},set(t){this[cc]=!!t}}});ye._fromList=rA;function rA(t,e){if(e.length===0)return null;let r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Am(t){let e=t._readableState;Ee("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,Tn.nextTick(cD,e,t))}function cD(t,e){if(Ee("endReadableNT",t.endEmitted,t.length),!t.errored&&!t.closeEmitted&&!t.endEmitted&&t.length===0){if(t.endEmitted=!0,e.emit("end"),e.writable&&e.allowHalfOpen===!1)Tn.nextTick(aD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function aD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return V3(ye,t,e)};var Tm;function nA(){return Tm===void 0&&(Tm={}),Tm}ye.fromWeb=function(t,e){return nA().newStreamReadableFromReadableStream(t,e)};ye.toWeb=function(t,e){return nA().newReadableStreamFromStreamReadable(t,e)};ye.wrap=function(t,e){var r,n;return new ye({objectMode:(r=(n=t.readableObjectMode)!==null&&n!==void 0?n:t.objectMode)!==null&&r!==void 0?r:!0,...e,destroy(i,o){Ia.destroyer(t,i),o(i)}}).wrap(t)}});var Ch=oe(($F,gA)=>{l();var ac=Ei(),{ArrayPrototypeSlice:cA,Error:uD,FunctionPrototypeSymbolHasInstance:aA,ObjectDefineProperty:uA,ObjectDefineProperties:dD,ObjectSetPrototypeOf:dA,StringPrototypeToLowerCase:fD,Symbol:lD,SymbolHasInstance:hD}=nt();gA.exports=it;it.WritableState=Ud;var{EventEmitter:pD}=da(),Bd=vh().Stream,{Buffer:Oh}=Tr(),Nh=oc(),{addAbortSignal:yD}=Sd(),{getHighWaterMark:gD,getDefaultHighWaterMark:mD}=Ad(),{ERR_INVALID_ARG_TYPE:wD,ERR_METHOD_NOT_IMPLEMENTED:bD,ERR_MULTIPLE_CALLBACK:fA,ERR_STREAM_CANNOT_PIPE:xD,ERR_STREAM_DESTROYED:Rd,ERR_STREAM_ALREADY_FINISHED:ED,ERR_STREAM_NULL_VALUES:vD,ERR_STREAM_WRITE_AFTER_END:SD,ERR_UNKNOWN_ENCODING:lA}=or().codes,{errorOrDestroy:Ba}=Nh;dA(it.prototype,Bd.prototype);dA(it,Bd);function Om(){}var Ra=lD("kOnFinished");function Ud(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?gD(this,t,"writableHighWaterMark",r):mD(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let n=!!(t&&t.decodeStrings===!1);this.decodeStrings=!n,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=TD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,kh(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!t||t.emitClose!==!1,this.autoDestroy=!t||t.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[Ra]=[]}function kh(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Ud.prototype.getBuffer=function(){return cA(this.buffered,this.bufferedIndex)};uA(Ud.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function it(t){let e=this instanceof oi();if(!e&&!aA(it,this))return new it(t);this._writableState=new Ud(t,this,e),t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&yD(t.signal,this)),Bd.call(this,t),Nh.construct(this,()=>{let r=this._writableState;r.writing||km(this,r),Nm(this,r)})}uA(it,hD,{__proto__:null,value:function(t){return aA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Ud}});it.prototype.pipe=function(){Ba(this,new xD)};function hA(t,e,r,n){let i=t._writableState;if(typeof r=="function")n=r,r=i.defaultEncoding;else{if(!r)r=i.defaultEncoding;else if(r!=="buffer"&&!Oh.isEncoding(r))throw new lA(r);typeof n!="function"&&(n=Om)}if(e===null)throw new vD;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Oh.from(e,r),r="buffer");else if(e instanceof Oh)r="buffer";else if(Bd._isUint8Array(e))e=Bd._uint8ArrayToBuffer(e),r="buffer";else throw new wD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new SD:i.destroyed&&(o=new Rd("write")),o?(ac.nextTick(n,o),Ba(t,o,!0),o):(i.pendingcb++,AD(t,i,e,r,n))}it.prototype.write=function(t,e,r){return hA(this,t,e,r)===!0};it.prototype.cork=function(){this._writableState.corked++};it.prototype.uncork=function(){let t=this._writableState;t.corked&&(t.corked--,t.writing||km(this,t))};it.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=fD(e)),!Oh.isEncoding(e))throw new lA(e);return this._writableState.defaultEncoding=e,this};function AD(t,e,r,n,i){let o=e.objectMode?1:r.length;e.length+=o;let s=e.length<e.highWaterMark;return s||(e.needDrain=!0),e.writing||e.corked||e.errored||!e.constructed?(e.buffered.push({chunk:r,encoding:n,callback:i}),e.allBuffers&&n!=="buffer"&&(e.allBuffers=!1),e.allNoop&&i!==Om&&(e.allNoop=!1)):(e.writelen=o,e.writecb=i,e.writing=!0,e.sync=!0,t._write(r,n,e.onwrite),e.sync=!1),s&&!e.errored&&!e.destroyed}function oA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new Rd("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function sA(t,e,r,n){--e.pendingcb,n(r),Dm(e),Ba(t,r)}function TD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){Ba(t,new fA);return}r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,e?(e.stack,r.errored||(r.errored=e),t._readableState&&!t._readableState.errored&&(t._readableState.errored=e),n?ac.nextTick(sA,t,r,e,i):sA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&km(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},ac.nextTick(_D,r.afterWriteTickInfo)):pA(t,r,1,i))}function _D({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,pA(t,e,r,n)}function pA(t,e,r,n){for(!e.ending&&!t.destroyed&&e.length===0&&e.needDrain&&(e.needDrain=!1,t.emit("drain"));r-- >0;)e.pendingcb--,n();e.destroyed&&Dm(e),Nm(t,e)}function Dm(t){if(t.writing)return;for(let i=t.bufferedIndex;i<t.buffered.length;++i){var e;let{chunk:o,callback:s}=t.buffered[i],c=t.objectMode?1:o.length;t.length-=c,s((e=t.errored)!==null&&e!==void 0?e:new Rd("write"))}let r=t[Ra].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new Rd("end"))}kh(t)}function km(t,e){if(e.corked||e.bufferProcessing||e.destroyed||!e.constructed)return;let{buffered:r,bufferedIndex:n,objectMode:i}=e,o=r.length-n;if(!o)return;let s=n;if(e.bufferProcessing=!0,o>1&&t._writev){e.pendingcb-=o-1;let c=e.allNoop?Om:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:cA(r,s);a.allBuffers=e.allBuffers,oA(t,e,!0,e.length,a,"",c),kh(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;oA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?kh(e):s>256?(r.splice(0,s),e.bufferedIndex=0):e.bufferedIndex=s}e.bufferProcessing=!1}it.prototype._write=function(t,e,r){if(this._writev)this._writev([{chunk:t,encoding:e}],r);else throw new bD("_write()")};it.prototype._writev=null;it.prototype.end=function(t,e,r){let n=this._writableState;typeof t=="function"?(r=t,t=null,e=null):typeof e=="function"&&(r=e,e=null);let i;if(t!=null){let o=hA(this,t,e);o instanceof uD&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,Nm(this,n,!0),n.ended=!0):n.finished?i=new ED("end"):n.destroyed&&(i=new Rd("end"))),typeof r=="function"&&(i||n.finished?ac.nextTick(r,i):n[Ra].push(r)),this};function Dh(t){return t.ending&&!t.destroyed&&t.constructed&&t.length===0&&!t.errored&&t.buffered.length===0&&!t.finished&&!t.writing&&!t.errorEmitted&&!t.closeEmitted}function ID(t,e){let r=!1;function n(i){if(r){Ba(t,i??fA());return}if(r=!0,e.pendingcb--,i){let o=e[Ra].splice(0);for(let s=0;s<o.length;s++)o[s](i);Ba(t,i,e.sync)}else Dh(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,ac.nextTick(Um,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function BD(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,ID(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function Nm(t,e,r){Dh(e)&&(BD(t,e),e.pendingcb===0&&(r?(e.pendingcb++,ac.nextTick((n,i)=>{Dh(i)?Um(n,i):i.pendingcb--},t,e)):Dh(e)&&(e.pendingcb++,Um(t,e))))}function Um(t,e){e.pendingcb--,e.finished=!0;let r=e[Ra].splice(0);for(let n=0;n<r.length;n++)r[n]();if(t.emit("finish"),e.autoDestroy){let n=t._readableState;(!n||n.autoDestroy&&(n.endEmitted||n.readable===!1))&&t.destroy()}}dD(it.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(t){this._writableState&&(this._writableState.destroyed=t)}},writable:{__proto__:null,get(){let t=this._writableState;return!!t&&t.writable!==!1&&!t.destroyed&&!t.errored&&!t.ending&&!t.ended},set(t){this._writableState&&(this._writableState.writable=!!t)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let t=this._writableState;return t?!t.destroyed&&!t.ending&&t.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var RD=Nh.destroy;it.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[Ra].length)&&ac.nextTick(Dm,r),RD.call(this,t,e),this};it.prototype._undestroy=Nh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[pD.captureRejectionSymbol]=function(t){this.destroy(t)};var Rm;function yA(){return Rm===void 0&&(Rm={}),Rm}it.fromWeb=function(t,e){return yA().newStreamWritableFromWritableStream(t,e)};it.toWeb=function(t){return yA().newWritableStreamFromStreamWritable(t)}});var OA=oe((VF,UA)=>{l();var Cm=Ei(),UD=Tr(),{isReadable:OD,isWritable:DD,isIterable:mA,isNodeStream:kD,isReadableNodeStream:wA,isWritableNodeStream:bA,isDuplexNodeStream:ND,isReadableStream:xA,isWritableStream:EA}=ri(),vA=Wi(),{AbortError:BA,codes:{ERR_INVALID_ARG_TYPE:CD,ERR_INVALID_RETURN_VALUE:SA}}=or(),{destroyer:Oa}=oc(),LD=oi(),RA=Id(),PD=Ch(),{createDeferredPromise:AA}=Zt(),TA=xm(),_A=globalThis.Blob||UD.Blob,MD=typeof _A<"u"?function(e){return e instanceof _A}:function(e){return!1},KD=globalThis.AbortController||Ea().AbortController,{FunctionPrototypeCall:IA}=nt(),jo=class extends LD{constructor(e){super(e),e?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),e?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};UA.exports=function t(e,r){if(ND(e))return e;if(wA(e))return Ua({readable:e});if(bA(e))return Ua({writable:e});if(kD(e))return Ua({writable:!1,readable:!1});if(xA(e))return Ua({readable:RA.fromWeb(e)});if(EA(e))return Ua({writable:PD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=$D(e);if(mA(i))return TA(jo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=IA(a,i,f=>{if(f!=null)throw new SA("nully","body",f)},f=>{Oa(u,f)});return u=new jo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,Cm.nextTick(f,null)}catch(h){Cm.nextTick(f,h)}})},destroy:c})}throw new SA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(MD(e))return t(e.arrayBuffer());if(mA(e))return TA(jo,e,{objectMode:!0,writable:!1});if(xA(e?.readable)&&EA(e?.writable))return jo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?wA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?bA(e?.writable)?e?.writable:t(e.writable):void 0;return Ua({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return IA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{Oa(i,o)}),i=new jo({objectMode:!0,writable:!1,read(){}})}throw new CD(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function $D(t){let{promise:e,resolve:r}=AA(),n=new KD,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(Cm.nextTick(u),a)return;if(i.aborted)throw new BA(void 0,{cause:i.reason});({promise:e,resolve:r}=AA()),yield c}}(),{signal:i}),write(s,c,a){let u=r;r=null,u({chunk:s,done:!1,cb:a})},final(s){let c=r;r=null,c({done:!0,cb:s})},destroy(s,c){n.abort(),c(s)}}}function Ua(t){let e=t.readable&&typeof t.readable.read!="function"?RA.wrap(t.readable):t.readable,r=t.writable,n=!!OD(e),i=!!DD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new jo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(vA(r,f=>{i=!1,f&&Oa(e,f),d(f)}),u._write=function(f,h,p){r.write(f,h)?p():o=p},u._final=function(f){r.end(),s=f},r.on("drain",function(){if(o){let f=o;o=null,f()}}),r.on("finish",function(){if(s){let f=s;s=null,f()}})),n&&(vA(e,f=>{n=!1,f&&Oa(e,f),d(f)}),e.on("readable",function(){if(c){let f=c;c=null,f()}}),e.on("end",function(){u.push(null)}),u._read=function(){for(;;){let f=e.read();if(f===null){c=u._read;return}if(!u.push(f))return}}),u._destroy=function(f,h){!f&&a!==null&&(f=new BA),c=null,o=null,s=null,a===null?h(f):(a=h,Oa(r,f),Oa(e,f))},u}});var oi=oe((FF,NA)=>{"use strict";l();var{ObjectDefineProperties:HD,ObjectGetOwnPropertyDescriptor:Gi,ObjectKeys:VD,ObjectSetPrototypeOf:DA}=nt();NA.exports=_n;var Mm=Id(),rn=Ch();DA(_n.prototype,Mm.prototype);DA(_n,Mm);{let t=VD(rn.prototype);for(let e=0;e<t.length;e++){let r=t[e];_n.prototype[r]||(_n.prototype[r]=rn.prototype[r])}}function _n(t){if(!(this instanceof _n))return new _n(t);Mm.call(this,t),rn.call(this,t),t?(this.allowHalfOpen=t.allowHalfOpen!==!1,t.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),t.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}HD(_n.prototype,{writable:{__proto__:null,...Gi(rn.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Gi(rn.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Gi(rn.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Gi(rn.prototype,"writableBuffer")},writableLength:{__proto__:null,...Gi(rn.prototype,"writableLength")},writableFinished:{__proto__:null,...Gi(rn.prototype,"writableFinished")},writableCorked:{__proto__:null,...Gi(rn.prototype,"writableCorked")},writableEnded:{__proto__:null,...Gi(rn.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Gi(rn.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(t){this._readableState&&this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}});var Lm;function kA(){return Lm===void 0&&(Lm={}),Lm}_n.fromWeb=function(t,e){return kA().newStreamDuplexFromReadableWritablePair(t,e)};_n.toWeb=function(t){return kA().newReadableWritablePairFromDuplex(t)};var Pm;_n.from=function(t){return Pm||(Pm=OA()),Pm(t,"body")}});var Hm=oe((WF,LA)=>{"use strict";l();var{ObjectSetPrototypeOf:CA,Symbol:qD}=nt();LA.exports=zi;var{ERR_METHOD_NOT_IMPLEMENTED:FD}=or().codes,$m=oi(),{getHighWaterMark:jD}=Ad();CA(zi.prototype,$m.prototype);CA(zi,$m);var Od=qD("kCallback");function zi(t){if(!(this instanceof zi))return new zi(t);let e=t?jD(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),$m.call(this,t),this._readableState.sync=!1,this[Od]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",WD)}function Km(t){typeof this._flush=="function"&&!this.destroyed?this._flush((e,r)=>{if(e){t?t(e):this.destroy(e);return}r!=null&&this.push(r),this.push(null),t&&t()}):(this.push(null),t&&t())}function WD(){this._final!==Km&&Km.call(this)}zi.prototype._final=Km;zi.prototype._transform=function(t,e,r){throw new FD("_transform()")};zi.prototype._write=function(t,e,r){let n=this._readableState,i=this._writableState,o=n.length;this._transform(t,e,(s,c)=>{if(s){r(s);return}c!=null&&this.push(c),i.ended||o===n.length||n.length<n.highWaterMark?r():this[Od]=r})};zi.prototype._read=function(){if(this[Od]){let t=this[Od];this[Od]=null,t()}}});var qm=oe((zF,MA)=>{"use strict";l();var{ObjectSetPrototypeOf:PA}=nt();MA.exports=Da;var Vm=Hm();PA(Da.prototype,Vm.prototype);PA(Da,Vm);function Da(t){if(!(this instanceof Da))return new Da(t);Vm.call(this,t)}Da.prototype._transform=function(t,e,r){r(null,t)}});var Kh=oe((JF,qA)=>{l();var Dd=Ei(),{ArrayIsArray:GD,Promise:zD,SymbolAsyncIterator:YD,SymbolDispose:JD}=nt(),Mh=Wi(),{once:ZD}=Zt(),XD=oc(),KA=oi(),{aggregateTwoErrors:QD,codes:{ERR_INVALID_ARG_TYPE:Xm,ERR_INVALID_RETURN_VALUE:Fm,ERR_MISSING_ARGS:ek,ERR_STREAM_DESTROYED:tk,ERR_STREAM_PREMATURE_CLOSE:rk},AbortError:nk}=or(),{validateFunction:ik,validateAbortSignal:ok}=Sa(),{isIterable:uc,isReadable:jm,isReadableNodeStream:Ph,isNodeStream:$A,isTransformStream:ka,isWebStream:sk,isReadableStream:Wm,isReadableFinished:ck}=ri(),ak=globalThis.AbortController||Ea().AbortController,Gm,zm,Ym;function HA(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Mh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,XD.destroyer(t,o||new tk("pipe")))},cleanup:i}}function uk(t){return ik(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function Jm(t){if(uc(t))return t;if(Ph(t))return dk(t);throw new Xm("val",["Readable","Iterable","AsyncIterable"],t)}async function*dk(t){zm||(zm=Id()),yield*zm.prototype[YD].call(t)}async function Lh(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new zD((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Mh(e,{readable:!1},s);try{e.writableNeedDrain&&await c();for await(let u of t)e.write(u)||await c();n&&(e.end(),await c()),r()}catch(u){r(i!==u?QD(i,u):u)}finally{a(),e.off("drain",s)}}async function Zm(t,e,r,{end:n}){ka(e)&&(e=e.writable);let i=e.getWriter();try{for await(let o of t)await i.ready,i.write(o).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(o){try{await i.abort(o),r(o)}catch(s){r(s)}}}function fk(...t){return VA(t,ZD(uk(t)))}function VA(t,e,r){if(t.length===1&&GD(t[0])&&(t=t[0]),t.length<2)throw new ek("streams");let n=new ak,i=n.signal,o=r?.signal,s=[];ok(o,"options.signal");function c(){g(new nk)}Ym=Ym||Zt().addAbortListener;let a;o&&(a=Ym(o,c));let u,d,f=[],h=0;function p(A){g(A,--h===0)}function g(A,O){var T;if(A&&(!u||u.code==="ERR_STREAM_PREMATURE_CLOSE")&&(u=A),!(!u&&!O)){for(;f.length;)f.shift()(u);(T=a)===null||T===void 0||T[JD](),n.abort(),O&&(u||s.forEach(M=>M()),Dd.nextTick(e,u,d))}}let y;for(let A=0;A<t.length;A++){let O=t[A],T=A<t.length-1,M=A>0,q=T||r?.end!==!1,j=A===t.length-1;if($A(O)){let $=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(X)};var _=$;if(q){let{destroy:X,cleanup:Q}=HA(O,T,M);f.push(X),jm(O)&&j&&s.push(Q)}O.on("error",$),jm(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!uc(y))throw new Fm("Iterable, AsyncIterable or Stream","source",y)}else uc(O)||Ph(O)||ka(O)?y=O:y=KA.from(O);else if(typeof O=="function"){if(ka(y)){var x;y=Jm((x=y)===null||x===void 0?void 0:x.readable)}else y=Jm(y);if(y=O(y,{signal:i}),T){if(!uc(y,!0))throw new Fm("AsyncIterable",`transform[${A-1}]`,y)}else{var S;Gm||(Gm=qm());let $=new Gm({objectMode:!0}),X=(S=y)===null||S===void 0?void 0:S.then;if(typeof X=="function")h++,X.call(y,I=>{d=I,I!=null&&$.write(I),q&&$.end(),Dd.nextTick(p)},I=>{$.destroy(I),Dd.nextTick(p,I)});else if(uc(y,!0))h++,Lh(y,$,p,{end:q});else if(Wm(y)||ka(y)){let I=y.readable||y;h++,Lh(I,$,p,{end:q})}else throw new Fm("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=HA(y,!1,!0);f.push(Q),j&&s.push(G)}}else if($A(O)){if(Ph(y)){h+=2;let $=lk(y,O,p,{end:q});jm(O)&&j&&s.push($)}else if(ka(y)||Wm(y)){let $=y.readable||y;h++,Lh($,O,p,{end:q})}else if(uc(y))h++,Lh(y,O,p,{end:q});else throw new Xm("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(sk(O)){if(Ph(y))h++,Zm(Jm(y),O,p,{end:q});else if(Wm(y)||uc(y))h++,Zm(y,O,p,{end:q});else if(ka(y))h++,Zm(y.readable,O,p,{end:q});else throw new Xm("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=KA.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&Dd.nextTick(c),y}function lk(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new rk)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;ck(t)?Dd.nextTick(s):t.once("end",s)}else r();return Mh(t,{readable:!0,writable:!1},s=>{let c=t._readableState;s&&s.code==="ERR_STREAM_PREMATURE_CLOSE"&&c&&c.ended&&!c.errored&&!c.errorEmitted?t.once("end",r).once("error",r):r(s)}),Mh(e,{readable:!1,writable:!0},r)}qA.exports={pipelineImpl:VA,pipeline:fk}});var ew=oe((XF,YA)=>{"use strict";l();var{pipeline:hk}=Kh(),$h=oi(),{destroyer:pk}=oc(),{isNodeStream:Hh,isReadable:FA,isWritable:jA,isWebStream:Qm,isTransformStream:dc,isWritableStream:WA,isReadableStream:GA}=ri(),{AbortError:yk,codes:{ERR_INVALID_ARG_VALUE:zA,ERR_MISSING_ARGS:gk}}=or(),mk=Wi();YA.exports=function(...e){if(e.length===0)throw new gk("streams");if(e.length===1)return $h.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=$h.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=$h.from(e[p])}for(let p=0;p<e.length;++p)if(!(!Hh(e[p])&&!Qm(e[p]))){if(p<e.length-1&&!(FA(e[p])||GA(e[p])||dc(e[p])))throw new zA(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(jA(e[p])||WA(e[p])||dc(e[p])))throw new zA(`streams[${p}]`,r[p],"must be writable")}let n,i,o,s,c;function a(p){let g=s;s=null,g?g(p):p?c.destroy(p):!h&&!f&&c.destroy()}let u=e[0],d=hk(e,a),f=!!(jA(u)||WA(u)||dc(u)),h=!!(FA(d)||GA(d)||dc(d));if(c=new $h({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(Hh(u))c._write=function(g,y,x){u.write(g,y)?x():n=x},c._final=function(g){u.end(),i=g},u.on("drain",function(){if(n){let g=n;n=null,g()}});else if(Qm(u)){let y=(dc(u)?u.writable:u).getWriter();c._write=async function(x,S,_){try{await y.ready,y.write(x).catch(()=>{}),_()}catch(A){_(A)}},c._final=async function(x){try{await y.ready,y.close().catch(()=>{}),i=x}catch(S){x(S)}}}let p=dc(d)?d.readable:d;mk(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(Hh(d))d.on("readable",function(){if(o){let p=o;o=null,p()}}),d.on("end",function(){c.push(null)}),c._read=function(){for(;;){let p=d.read();if(p===null){o=c._read;return}if(!c.push(p))return}};else if(Qm(d)){let g=(dc(d)?d.readable:d).getReader();c._read=async function(){for(;;)try{let{value:y,done:x}=await g.read();if(!c.push(y))return;if(x){c.push(null);return}}catch{return}}}}return c._destroy=function(p,g){!p&&s!==null&&(p=new yk),o=null,n=null,i=null,s===null?g(p):(s=g,Hh(d)&&pk(d,p))},c}});var oT=oe((ej,nw)=>{"use strict";l();var wk=globalThis.AbortController||Ea().AbortController,{codes:{ERR_INVALID_ARG_VALUE:bk,ERR_INVALID_ARG_TYPE:kd,ERR_MISSING_ARGS:xk,ERR_OUT_OF_RANGE:Ek},AbortError:si}=or(),{validateAbortSignal:fc,validateInteger:JA,validateObject:lc}=Sa(),vk=nt().Symbol("kWeak"),Sk=nt().Symbol("kResistStopPropagation"),{finished:Ak}=Wi(),Tk=ew(),{addAbortSignalNoValidate:_k}=Sd(),{isWritable:Ik,isNodeStream:Bk}=ri(),{deprecate:Rk}=Zt(),{ArrayPrototypePush:Uk,Boolean:Ok,MathFloor:ZA,Number:Dk,NumberIsNaN:kk,Promise:XA,PromiseReject:QA,PromiseResolve:Nk,PromisePrototypeThen:eT,Symbol:rT}=nt(),Vh=rT("kEmpty"),tT=rT("kEof");function Ck(t,e){if(e!=null&&lc(e,"options"),e?.signal!=null&&fc(e.signal,"options.signal"),Bk(t)&&!Ik(t))throw new bk("stream",t,"must be writable");let r=Tk(this,t);return e!=null&&e.signal&&_k(e.signal,r),r}function qh(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);e!=null&&lc(e,"options"),e?.signal!=null&&fc(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=ZA(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=ZA(e.highWaterMark)),JA(r,"options.concurrency",1),JA(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Zt().AbortSignalAny([e?.signal].filter(Ok)),s=this,c=[],a={signal:o},u,d,f=!1,h=0;function p(){f=!0,g()}function g(){h-=1,y()}function y(){d&&!f&&h<r&&c.length<n&&(d(),d=null)}async function x(){try{for await(let S of s){if(f)return;if(o.aborted)throw new si;try{if(S=t(S,a),S===Vh)continue;S=Nk(S)}catch(_){S=QA(_)}h+=1,eT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new XA(_=>{d=_})}c.push(tT)}catch(S){let _=QA(S);eT(_,g,p),c.push(_)}finally{f=!0,u&&(u(),u=null)}}x();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===tT)return;if(o.aborted)throw new si;S!==Vh&&(yield S),c.shift(),y()}await new XA(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function Lk(t=void 0){return t!=null&&lc(t,"options"),t?.signal!=null&&fc(t.signal,"options.signal"),(async function*(){let r=0;for await(let i of this){var n;if(t!=null&&(n=t.signal)!==null&&n!==void 0&&n.aborted)throw new si({cause:t.signal.reason});yield[r++,i]}}).call(this)}async function nT(t,e=void 0){for await(let r of rw.call(this,t,e))return!0;return!1}async function Pk(t,e=void 0){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);return!await nT.call(this,async(...r)=>!await t(...r),e)}async function Mk(t,e){for await(let r of rw.call(this,t,e))return r}async function Kk(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),Vh}for await(let n of qh.call(this,r,e));}function rw(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:Vh}return qh.call(this,r,e)}var tw=class extends xk{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function $k(t,e,r){var n;if(typeof t!="function")throw new kd("reducer",["Function","AsyncFunction"],t);r!=null&&lc(r,"options"),r?.signal!=null&&fc(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let u=new si(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await Ak(this.destroy(u)),u}let o=new wk,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[vk]:this,[Sk]:!0};r.signal.addEventListener("abort",()=>o.abort(),u)}let c=!1;try{for await(let u of this){var a;if(c=!0,r!=null&&(a=r.signal)!==null&&a!==void 0&&a.aborted)throw new si;i?e=await t(e,u,{signal:s}):(e=u,i=!0)}if(!c&&!i)throw new tw}finally{o.abort()}return e}async function Hk(t){t!=null&&lc(t,"options"),t?.signal!=null&&fc(t.signal,"options.signal");let e=[];for await(let n of this){var r;if(t!=null&&(r=t.signal)!==null&&r!==void 0&&r.aborted)throw new si(void 0,{cause:t.signal.reason});Uk(e,n)}return e}function Vk(t,e){let r=qh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function iT(t){if(t=Dk(t),kk(t))return 0;if(t<0)throw new Ek("number",">= 0",t);return t}function qk(t,e=void 0){return e!=null&&lc(e,"options"),e?.signal!=null&&fc(e.signal,"options.signal"),t=iT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new si;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new si;t--<=0&&(yield o)}}).call(this)}function Fk(t,e=void 0){return e!=null&&lc(e,"options"),e?.signal!=null&&fc(e.signal,"options.signal"),t=iT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new si;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new si;if(t-- >0&&(yield o),t<=0)return}}).call(this)}nw.exports.streamReturningOperators={asIndexedPairs:Rk(Lk,"readable.asIndexedPairs will be removed in a future version."),drop:qk,filter:rw,flatMap:Vk,map:qh,take:Fk,compose:Ck};nw.exports.promiseReturningOperators={every:Pk,forEach:Kk,reduce:$k,toArray:Hk,some:nT,find:Mk}});var iw=oe((rj,sT)=>{"use strict";l();var{ArrayPrototypePop:jk,Promise:Wk}=nt(),{isIterable:Gk,isNodeStream:zk,isWebStream:Yk}=ri(),{pipelineImpl:Jk}=Kh(),{finished:Zk}=Wi();ow();function Xk(...t){return new Wk((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!zk(o)&&!Gk(o)&&!Yk(o)){let s=jk(t);n=s.signal,i=s.end}Jk(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}sT.exports={finished:Zk,pipeline:Xk}});var ow=oe((ij,yT)=>{l();var{Buffer:Qk}=Tr(),{ObjectDefineProperty:Yi,ObjectKeys:uT,ReflectApply:dT}=nt(),{promisify:{custom:fT}}=Zt(),{streamReturningOperators:cT,promiseReturningOperators:aT}=oT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:lT}}=or(),e4=ew(),{setDefaultHighWaterMark:t4,getDefaultHighWaterMark:r4}=Ad(),{pipeline:hT}=Kh(),{destroyer:n4}=oc(),pT=Wi(),sw=iw(),Nd=ri(),We=yT.exports=vh().Stream;We.isDestroyed=Nd.isDestroyed;We.isDisturbed=Nd.isDisturbed;We.isErrored=Nd.isErrored;We.isReadable=Nd.isReadable;We.isWritable=Nd.isWritable;We.Readable=Id();for(let t of uT(cT)){let r=function(...n){if(new.target)throw lT();return We.Readable.from(dT(e,this,n))};cw=r;let e=cT[t];Yi(r,"name",{__proto__:null,value:e.name}),Yi(r,"length",{__proto__:null,value:e.length}),Yi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var cw;for(let t of uT(aT)){let r=function(...i){if(new.target)throw lT();return dT(e,this,i)};cw=r;let e=aT[t];Yi(r,"name",{__proto__:null,value:e.name}),Yi(r,"length",{__proto__:null,value:e.length}),Yi(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var cw;We.Writable=Ch();We.Duplex=oi();We.Transform=Hm();We.PassThrough=qm();We.pipeline=hT;var{addAbortSignal:i4}=Sd();We.addAbortSignal=i4;We.finished=pT;We.destroy=n4;We.compose=e4;We.setDefaultHighWaterMark=t4;We.getDefaultHighWaterMark=r4;Yi(We,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return sw}});Yi(hT,fT,{__proto__:null,enumerable:!0,get(){return sw.pipeline}});Yi(pT,fT,{__proto__:null,enumerable:!0,get(){return sw.finished}});We.Stream=We;We._isUint8Array=function(e){return e instanceof Uint8Array};We._uint8ArrayToBuffer=function(e){return Qk.from(e.buffer,e.byteOffset,e.byteLength)}});var aw=oe((sj,yt)=>{"use strict";l();var Tt=ow(),o4=iw(),s4=Tt.Readable.destroy;yt.exports=Tt.Readable;yt.exports._uint8ArrayToBuffer=Tt._uint8ArrayToBuffer;yt.exports._isUint8Array=Tt._isUint8Array;yt.exports.isDisturbed=Tt.isDisturbed;yt.exports.isErrored=Tt.isErrored;yt.exports.isReadable=Tt.isReadable;yt.exports.Readable=Tt.Readable;yt.exports.Writable=Tt.Writable;yt.exports.Duplex=Tt.Duplex;yt.exports.Transform=Tt.Transform;yt.exports.PassThrough=Tt.PassThrough;yt.exports.addAbortSignal=Tt.addAbortSignal;yt.exports.finished=Tt.finished;yt.exports.destroy=Tt.destroy;yt.exports.destroy=s4;yt.exports.pipeline=Tt.pipeline;yt.exports.compose=Tt.compose;Object.defineProperty(Tt,"promises",{configurable:!0,enumerable:!0,get(){return o4}});yt.exports.Stream=Tt.Stream;yt.exports.default=yt.exports});var P_=oe((Op,L_)=>{l();(function(t,e){typeof Op=="object"&&typeof L_<"u"?e(Op):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Op,function(t){"use strict";function e(){for(var B=arguments.length,v=Array(B),k=0;k<B;k++)v[k]=arguments[k];if(v.length>1){v[0]=v[0].slice(0,-1);for(var K=v.length-1,H=1;H<K;++H)v[H]=v[H].slice(1,-1);return v[K]=v[K].slice(1),v.join("")}else return v[0]}function r(B){return"(?:"+B+")"}function n(B){return B===void 0?"undefined":B===null?"null":Object.prototype.toString.call(B).split(" ").pop().split("]").shift().toLowerCase()}function i(B){return B.toUpperCase()}function o(B){return B!=null?B instanceof Array?B:typeof B.length!="number"||B.split||B.setInterval||B.call?[B]:Array.prototype.slice.call(B):[]}function s(B,v){var k=B;if(v)for(var K in v)k[K]=v[K];return k}function c(B){var v="[A-Za-z]",k="[\\x0D]",K="[0-9]",H="[\\x22]",te=e(K,"[A-Fa-f]"),fe="[\\x0A]",Se="[\\x20]",Oe=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),gt="[\\:\\/\\?\\#\\[\\]\\@]",ve="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",tt=e(gt,ve),mt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Ze=B?"[\\uE000-\\uF8FF]":"[]",Te=e(v,K,"[\\-\\.\\_\\~]",mt),rt=r(v+e(v,K,"[\\+\\-\\.]")+"*"),Ne=r(r(Oe+"|"+e(Te,ve,"[\\:]"))+"*"),ls=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),Sr=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),jr=r(Sr+"\\."+Sr+"\\."+Sr+"\\."+Sr),$e=r(te+"{1,4}"),Ar=r(r($e+"\\:"+$e)+"|"+jr),Wr=r(r($e+"\\:")+"{6}"+Ar),Pn=r("\\:\\:"+r($e+"\\:")+"{5}"+Ar),hs=r(r($e)+"?\\:\\:"+r($e+"\\:")+"{4}"+Ar),yi=r(r(r($e+"\\:")+"{0,1}"+$e)+"?\\:\\:"+r($e+"\\:")+"{3}"+Ar),pu=r(r(r($e+"\\:")+"{0,2}"+$e)+"?\\:\\:"+r($e+"\\:")+"{2}"+Ar),Ef=r(r(r($e+"\\:")+"{0,3}"+$e)+"?\\:\\:"+$e+"\\:"+Ar),vf=r(r(r($e+"\\:")+"{0,4}"+$e)+"?\\:\\:"+Ar),Ac=r(r(r($e+"\\:")+"{0,5}"+$e)+"?\\:\\:"+$e),Tc=r(r(r($e+"\\:")+"{0,6}"+$e)+"?\\:\\:"),gi=r([Wr,Pn,hs,yi,pu,Ef,vf,Ac,Tc].join("|")),_c=r(r(Te+"|"+Oe)+"+"),ey=r(gi+"\\%25"+_c),ps=r(gi+r("\\%25|\\%(?!"+te+"{2})")+_c),eB=r("[vV]"+te+"+\\."+e(Te,ve,"[\\:]")+"+"),tB=r("\\["+r(ps+"|"+gi+"|"+eB)+"\\]"),Qb=r(r(Oe+"|"+e(Te,ve))+"*"),yu=r(tB+"|"+jr+"(?!"+Qb+")|"+Qb),gu=r(K+"*"),ex=r(r(Ne+"@")+"?"+yu+r("\\:"+gu)+"?"),mu=r(Oe+"|"+e(Te,ve,"[\\:\\@]")),rB=r(mu+"*"),tx=r(mu+"+"),nB=r(r(Oe+"|"+e(Te,ve,"[\\@]"))+"+"),mi=r(r("\\/"+rB)+"*"),Ic=r("\\/"+r(tx+mi)+"?"),ty=r(nB+mi),Sf=r(tx+mi),Bc="(?!"+mu+")",DL=r(mi+"|"+Ic+"|"+ty+"|"+Sf+"|"+Bc),Rc=r(r(mu+"|"+e("[\\/\\?]",Ze))+"*"),wu=r(r(mu+"|[\\/\\?]")+"*"),rx=r(r("\\/\\/"+ex+mi)+"|"+Ic+"|"+Sf+"|"+Bc),iB=r(rt+"\\:"+rx+r("\\?"+Rc)+"?"+r("\\#"+wu)+"?"),oB=r(r("\\/\\/"+ex+mi)+"|"+Ic+"|"+ty+"|"+Bc),sB=r(oB+r("\\?"+Rc)+"?"+r("\\#"+wu)+"?"),kL=r(iB+"|"+sB),NL=r(rt+"\\:"+rx+r("\\?"+Rc)+"?"),CL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+mi+"|"+Ic+"|"+Sf+"|"+Bc+")")+r("\\?("+Rc+")")+"?"+r("\\#("+wu+")")+"?$",LL="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+mi+"|"+Ic+"|"+ty+"|"+Bc+")")+r("\\?("+Rc+")")+"?"+r("\\#("+wu+")")+"?$",PL="^("+rt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?)")+"?("+mi+"|"+Ic+"|"+Sf+"|"+Bc+")")+r("\\?("+Rc+")")+"?$",ML="^"+r("\\#("+wu+")")+"?$",KL="^"+r("("+Ne+")@")+"?("+yu+")"+r("\\:("+gu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Te,ve),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Te,ve),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Te,ve),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Te,ve),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Te,ve,"[\\:\\@\\/\\?]",Ze),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Te,ve,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Te,ve),"g"),UNRESERVED:new RegExp(Te,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Te,tt),"g"),PCT_ENCODED:new RegExp(Oe,"g"),IPV4ADDRESS:new RegExp("^("+jr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+gi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+_c+")")+"?\\]?$")}}var a=c(!1),u=c(!0),d=function(){function B(v,k){var K=[],H=!0,te=!1,fe=void 0;try{for(var Se=v[Symbol.iterator](),Oe;!(H=(Oe=Se.next()).done)&&(K.push(Oe.value),!(k&&K.length===k));H=!0);}catch(gt){te=!0,fe=gt}finally{try{!H&&Se.return&&Se.return()}finally{if(te)throw fe}}return K}return function(v,k){if(Array.isArray(v))return v;if(Symbol.iterator in Object(v))return B(v,k);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=function(B){if(Array.isArray(B)){for(var v=0,k=Array(B.length);v<B.length;v++)k[v]=B[v];return k}else return Array.from(B)},h=2147483647,p=36,g=1,y=26,x=38,S=700,_=72,A=128,O="-",T=/^xn--/,M=/[^\0-\x7E]/,q=/[\x2E\u3002\uFF0E\uFF61]/g,j={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},$=p-g,X=Math.floor,Q=String.fromCharCode;function G(B){throw new RangeError(j[B])}function I(B,v){for(var k=[],K=B.length;K--;)k[K]=v(B[K]);return k}function D(B,v){var k=B.split("@"),K="";k.length>1&&(K=k[0]+"@",B=k[1]),B=B.replace(q,".");var H=B.split("."),te=I(H,v).join(".");return K+te}function E(B){for(var v=[],k=0,K=B.length;k<K;){var H=B.charCodeAt(k++);if(H>=55296&&H<=56319&&k<K){var te=B.charCodeAt(k++);(te&64512)==56320?v.push(((H&1023)<<10)+(te&1023)+65536):(v.push(H),k--)}else v.push(H)}return v}var U=function(v){return String.fromCodePoint.apply(String,f(v))},L=function(v){return v-48<10?v-22:v-65<26?v-65:v-97<26?v-97:p},N=function(v,k){return v+22+75*(v<26)-((k!=0)<<5)},R=function(v,k,K){var H=0;for(v=K?X(v/S):v>>1,v+=X(v/k);v>$*y>>1;H+=p)v=X(v/$);return X(H+($+1)*v/(v+x))},C=function(v){var k=[],K=v.length,H=0,te=A,fe=_,Se=v.lastIndexOf(O);Se<0&&(Se=0);for(var Oe=0;Oe<Se;++Oe)v.charCodeAt(Oe)>=128&&G("not-basic"),k.push(v.charCodeAt(Oe));for(var gt=Se>0?Se+1:0;gt<K;){for(var ve=H,tt=1,mt=p;;mt+=p){gt>=K&&G("invalid-input");var Ze=L(v.charCodeAt(gt++));(Ze>=p||Ze>X((h-H)/tt))&&G("overflow"),H+=Ze*tt;var Te=mt<=fe?g:mt>=fe+y?y:mt-fe;if(Ze<Te)break;var rt=p-Te;tt>X(h/rt)&&G("overflow"),tt*=rt}var Ne=k.length+1;fe=R(H-ve,Ne,ve==0),X(H/Ne)>h-te&&G("overflow"),te+=X(H/Ne),H%=Ne,k.splice(H++,0,te)}return String.fromCodePoint.apply(String,k)},P=function(v){var k=[];v=E(v);var K=v.length,H=A,te=0,fe=_,Se=!0,Oe=!1,gt=void 0;try{for(var ve=v[Symbol.iterator](),tt;!(Se=(tt=ve.next()).done);Se=!0){var mt=tt.value;mt<128&&k.push(Q(mt))}}catch(ps){Oe=!0,gt=ps}finally{try{!Se&&ve.return&&ve.return()}finally{if(Oe)throw gt}}var Ze=k.length,Te=Ze;for(Ze&&k.push(O);Te<K;){var rt=h,Ne=!0,ls=!1,Sr=void 0;try{for(var jr=v[Symbol.iterator](),$e;!(Ne=($e=jr.next()).done);Ne=!0){var Ar=$e.value;Ar>=H&&Ar<rt&&(rt=Ar)}}catch(ps){ls=!0,Sr=ps}finally{try{!Ne&&jr.return&&jr.return()}finally{if(ls)throw Sr}}var Wr=Te+1;rt-H>X((h-te)/Wr)&&G("overflow"),te+=(rt-H)*Wr,H=rt;var Pn=!0,hs=!1,yi=void 0;try{for(var pu=v[Symbol.iterator](),Ef;!(Pn=(Ef=pu.next()).done);Pn=!0){var vf=Ef.value;if(vf<H&&++te>h&&G("overflow"),vf==H){for(var Ac=te,Tc=p;;Tc+=p){var gi=Tc<=fe?g:Tc>=fe+y?y:Tc-fe;if(Ac<gi)break;var _c=Ac-gi,ey=p-gi;k.push(Q(N(gi+_c%ey,0))),Ac=X(_c/ey)}k.push(Q(N(Ac,0))),fe=R(te,Wr,Te==Ze),te=0,++Te}}}catch(ps){hs=!0,yi=ps}finally{try{!Pn&&pu.return&&pu.return()}finally{if(hs)throw yi}}++te,++H}return k.join("")},V=function(v){return D(v,function(k){return T.test(k)?C(k.slice(4).toLowerCase()):k})},J=function(v){return D(v,function(k){return M.test(k)?"xn--"+P(k):k})},z={version:"2.1.0",ucs2:{decode:E,encode:U},decode:C,encode:P,toASCII:J,toUnicode:V},W={};function Y(B){var v=B.charCodeAt(0),k=void 0;return v<16?k="%0"+v.toString(16).toUpperCase():v<128?k="%"+v.toString(16).toUpperCase():v<2048?k="%"+(v>>6|192).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase():k="%"+(v>>12|224).toString(16).toUpperCase()+"%"+(v>>6&63|128).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase(),k}function Z(B){for(var v="",k=0,K=B.length;k<K;){var H=parseInt(B.substr(k+1,2),16);if(H<128)v+=String.fromCharCode(H),k+=3;else if(H>=194&&H<224){if(K-k>=6){var te=parseInt(B.substr(k+4,2),16);v+=String.fromCharCode((H&31)<<6|te&63)}else v+=B.substr(k,6);k+=6}else if(H>=224){if(K-k>=9){var fe=parseInt(B.substr(k+4,2),16),Se=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(fe&63)<<6|Se&63)}else v+=B.substr(k,9);k+=9}else v+=B.substr(k,3),k+=3}return v}function ue(B,v){function k(K){var H=Z(K);return H.match(v.UNRESERVED)?H:K}return B.scheme&&(B.scheme=String(B.scheme).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_SCHEME,"")),B.userinfo!==void 0&&(B.userinfo=String(B.userinfo).replace(v.PCT_ENCODED,k).replace(v.NOT_USERINFO,Y).replace(v.PCT_ENCODED,i)),B.host!==void 0&&(B.host=String(B.host).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_HOST,Y).replace(v.PCT_ENCODED,i)),B.path!==void 0&&(B.path=String(B.path).replace(v.PCT_ENCODED,k).replace(B.scheme?v.NOT_PATH:v.NOT_PATH_NOSCHEME,Y).replace(v.PCT_ENCODED,i)),B.query!==void 0&&(B.query=String(B.query).replace(v.PCT_ENCODED,k).replace(v.NOT_QUERY,Y).replace(v.PCT_ENCODED,i)),B.fragment!==void 0&&(B.fragment=String(B.fragment).replace(v.PCT_ENCODED,k).replace(v.NOT_FRAGMENT,Y).replace(v.PCT_ENCODED,i)),B}function ee(B){return B.replace(/^0*(.*)/,"$1")||"0"}function ce(B,v){var k=B.match(v.IPV4ADDRESS)||[],K=d(k,2),H=K[1];return H?H.split(".").map(ee).join("."):B}function Ue(B,v){var k=B.match(v.IPV6ADDRESS)||[],K=d(k,3),H=K[1],te=K[2];if(H){for(var fe=H.toLowerCase().split("::").reverse(),Se=d(fe,2),Oe=Se[0],gt=Se[1],ve=gt?gt.split(":").map(ee):[],tt=Oe.split(":").map(ee),mt=v.IPV4ADDRESS.test(tt[tt.length-1]),Ze=mt?7:8,Te=tt.length-Ze,rt=Array(Ze),Ne=0;Ne<Ze;++Ne)rt[Ne]=ve[Ne]||tt[Te+Ne]||"";mt&&(rt[Ze-1]=ce(rt[Ze-1],v));var ls=rt.reduce(function(Wr,Pn,hs){if(!Pn||Pn==="0"){var yi=Wr[Wr.length-1];yi&&yi.index+yi.length===hs?yi.length++:Wr.push({index:hs,length:1})}return Wr},[]),Sr=ls.sort(function(Wr,Pn){return Pn.length-Wr.length})[0],jr=void 0;if(Sr&&Sr.length>1){var $e=rt.slice(0,Sr.index),Ar=rt.slice(Sr.index+Sr.length);jr=$e.join(":")+"::"+Ar.join(":")}else jr=rt.join(":");return te&&(jr+="%"+te),jr}else return B}var Ke=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".match(/(){0}/)[1]===void 0;function bt(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k={},K=v.iri!==!1?u:a;v.reference==="suffix"&&(B=(v.scheme?v.scheme+":":"")+"//"+B);var H=B.match(Ke);if(H){Je?(k.scheme=H[1],k.userinfo=H[3],k.host=H[4],k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=H[7],k.fragment=H[8],isNaN(k.port)&&(k.port=H[5])):(k.scheme=H[1]||void 0,k.userinfo=B.indexOf("@")!==-1?H[3]:void 0,k.host=B.indexOf("//")!==-1?H[4]:void 0,k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=B.indexOf("?")!==-1?H[7]:void 0,k.fragment=B.indexOf("#")!==-1?H[8]:void 0,isNaN(k.port)&&(k.port=B.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?H[4]:void 0)),k.host&&(k.host=Ue(ce(k.host,K),K)),k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&!k.path&&k.query===void 0?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",v.reference&&v.reference!=="suffix"&&v.reference!==k.reference&&(k.error=k.error||"URI is not a "+v.reference+" reference.");var te=W[(v.scheme||k.scheme||"").toLowerCase()];if(!v.unicodeSupport&&(!te||!te.unicodeSupport)){if(k.host&&(v.domainHost||te&&te.domainHost))try{k.host=z.toASCII(k.host.replace(K.PCT_ENCODED,Z).toLowerCase())}catch(fe){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+fe}ue(k,a)}else ue(k,K);te&&te.parse&&te.parse(k,v)}else k.error=k.error||"URI can not be parsed.";return k}function pi(B,v){var k=v.iri!==!1?u:a,K=[];return B.userinfo!==void 0&&(K.push(B.userinfo),K.push("@")),B.host!==void 0&&K.push(Ue(ce(String(B.host),k),k).replace(k.IPV6ADDRESS,function(H,te,fe){return"["+te+(fe?"%25"+fe:"")+"]"})),(typeof B.port=="number"||typeof B.port=="string")&&(K.push(":"),K.push(String(B.port))),K.length?K.join(""):void 0}var fo=/^\.\.?\//,du=/^\/\.(\/|$)/,yf=/^\/\.\.(\/|$)/,Zp=/^\/?(?:.|\n)*?(?=\/|$)/;function lo(B){for(var v=[];B.length;)if(B.match(fo))B=B.replace(fo,"");else if(B.match(du))B=B.replace(du,"/");else if(B.match(yf))B=B.replace(yf,"/"),v.pop();else if(B==="."||B==="..")B="";else{var k=B.match(Zp);if(k){var K=k[0];B=B.slice(K.length),v.push(K)}else throw new Error("Unexpected dot segment condition")}return v.join("")}function qr(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=v.iri?u:a,K=[],H=W[(v.scheme||B.scheme||"").toLowerCase()];if(H&&H.serialize&&H.serialize(B,v),B.host&&!k.IPV6ADDRESS.test(B.host)){if(v.domainHost||H&&H.domainHost)try{B.host=v.iri?z.toUnicode(B.host):z.toASCII(B.host.replace(k.PCT_ENCODED,Z).toLowerCase())}catch(Se){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Se}}ue(B,k),v.reference!=="suffix"&&B.scheme&&(K.push(B.scheme),K.push(":"));var te=pi(B,v);if(te!==void 0&&(v.reference!=="suffix"&&K.push("//"),K.push(te),B.path&&B.path.charAt(0)!=="/"&&K.push("/")),B.path!==void 0){var fe=B.path;!v.absolutePath&&(!H||!H.absolutePath)&&(fe=lo(fe)),te===void 0&&(fe=fe.replace(/^\/\//,"/%2F")),K.push(fe)}return B.query!==void 0&&(K.push("?"),K.push(B.query)),B.fragment!==void 0&&(K.push("#"),K.push(B.fragment)),K.join("")}function fu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=bt(qr(B,k),k),v=bt(qr(v,k),k)),k=k||{},!k.tolerant&&v.scheme?(H.scheme=v.scheme,H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=lo(v.path||""),H.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=lo(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=lo(v.path):((B.userinfo!==void 0||B.host!==void 0||B.port!==void 0)&&!B.path?H.path="/"+v.path:B.path?H.path=B.path.slice(0,B.path.lastIndexOf("/")+1)+v.path:H.path=v.path,H.path=lo(H.path)),H.query=v.query):(H.path=B.path,v.query!==void 0?H.query=v.query:H.query=B.query),H.userinfo=B.userinfo,H.host=B.host,H.port=B.port),H.scheme=B.scheme),H.fragment=v.fragment,H}function gf(B,v,k){var K=s({scheme:"null"},k);return qr(fu(bt(B,K),bt(v,K),K,!0),K)}function lu(B,v){return typeof B=="string"?B=qr(bt(B,v),v):n(B)==="object"&&(B=bt(qr(B,v),v)),B}function mf(B,v,k){return typeof B=="string"?B=qr(bt(B,k),k):n(B)==="object"&&(B=qr(B,k)),typeof v=="string"?v=qr(bt(v,k),k):n(v)==="object"&&(v=qr(v,k)),B===v}function wf(B,v){return B&&B.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function Fr(B,v){return B&&B.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,Z)}var ho={scheme:"http",domainHost:!0,parse:function(v,k){return v.host||(v.error=v.error||"HTTP URIs must have a host."),v},serialize:function(v,k){var K=String(v.scheme).toLowerCase()==="https";return(v.port===(K?443:80)||v.port==="")&&(v.port=void 0),v.path||(v.path="/"),v}},hu={scheme:"https",domainHost:ho.domainHost,parse:ho.parse,serialize:ho.serialize};function bf(B){return typeof B.secure=="boolean"?B.secure:String(B.scheme).toLowerCase()==="wss"}var fs={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=bf(K),K.resourceName=(K.path||"/")+(K.query?"?"+K.query:""),K.path=void 0,K.query=void 0,K},serialize:function(v,k){if((v.port===(bf(v)?443:80)||v.port==="")&&(v.port=void 0),typeof v.secure=="boolean"&&(v.scheme=v.secure?"wss":"ws",v.secure=void 0),v.resourceName){var K=v.resourceName.split("?"),H=d(K,2),te=H[0],fe=H[1];v.path=te&&te!=="/"?te:void 0,v.query=fe,v.resourceName=void 0}return v.fragment=void 0,v}},xf={scheme:"wss",domainHost:fs.domainHost,parse:fs.parse,serialize:fs.serialize},Xp={},qI=!0,zb="[A-Za-z0-9\\-\\.\\_\\~"+(qI?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Ln="[0-9A-Fa-f]",FI=r(r("%[EFef]"+Ln+"%"+Ln+Ln+"%"+Ln+Ln)+"|"+r("%[89A-Fa-f]"+Ln+"%"+Ln+Ln)+"|"+r("%"+Ln+Ln)),jI="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",WI="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",GI=e(WI,'[\\"\\\\]'),zI="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",YI=new RegExp(zb,"g"),Sc=new RegExp(FI,"g"),JI=new RegExp(e("[^]",jI,"[\\.]",'[\\"]',GI),"g"),Yb=new RegExp(e("[^]",zb,zI),"g"),ZI=Yb;function Qp(B){var v=Z(B);return v.match(YI)?v:B}var Jb={scheme:"mailto",parse:function(v,k){var K=v,H=K.to=K.path?K.path.split(","):[];if(K.path=void 0,K.query){for(var te=!1,fe={},Se=K.query.split("&"),Oe=0,gt=Se.length;Oe<gt;++Oe){var ve=Se[Oe].split("=");switch(ve[0]){case"to":for(var tt=ve[1].split(","),mt=0,Ze=tt.length;mt<Ze;++mt)H.push(tt[mt]);break;case"subject":K.subject=Fr(ve[1],k);break;case"body":K.body=Fr(ve[1],k);break;default:te=!0,fe[Fr(ve[0],k)]=Fr(ve[1],k);break}}te&&(K.headers=fe)}K.query=void 0;for(var Te=0,rt=H.length;Te<rt;++Te){var Ne=H[Te].split("@");if(Ne[0]=Fr(Ne[0]),k.unicodeSupport)Ne[1]=Fr(Ne[1],k).toLowerCase();else try{Ne[1]=z.toASCII(Fr(Ne[1],k).toLowerCase())}catch(ls){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ls}H[Te]=Ne.join("@")}return K},serialize:function(v,k){var K=v,H=o(v.to);if(H){for(var te=0,fe=H.length;te<fe;++te){var Se=String(H[te]),Oe=Se.lastIndexOf("@"),gt=Se.slice(0,Oe).replace(Sc,Qp).replace(Sc,i).replace(JI,Y),ve=Se.slice(Oe+1);try{ve=k.iri?z.toUnicode(ve):z.toASCII(Fr(ve,k).toLowerCase())}catch(Te){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Te}H[te]=gt+"@"+ve}K.path=H.join(",")}var tt=v.headers=v.headers||{};v.subject&&(tt.subject=v.subject),v.body&&(tt.body=v.body);var mt=[];for(var Ze in tt)tt[Ze]!==Xp[Ze]&&mt.push(Ze.replace(Sc,Qp).replace(Sc,i).replace(Yb,Y)+"="+tt[Ze].replace(Sc,Qp).replace(Sc,i).replace(ZI,Y));return mt.length&&(K.query=mt.join("&")),K}},XI=/^([^\:]+)\:(.*)/,Zb={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(XI),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),Se=K[2],Oe=te+":"+(k.nid||fe),gt=W[Oe];H.nid=fe,H.nss=Se,H.path=void 0,gt&&(H=gt.parse(H,k))}else H.error=H.error||"URN can not be parsed.";return H},serialize:function(v,k){var K=k.scheme||v.scheme||"urn",H=v.nid,te=K+":"+(k.nid||H),fe=W[te];fe&&(v=fe.serialize(v,k));var Se=v,Oe=v.nss;return Se.path=(H||k.nid)+":"+Oe,Se}},QI=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Xb={scheme:"urn:uuid",parse:function(v,k){var K=v;return K.uuid=K.nss,K.nss=void 0,!k.tolerant&&(!K.uuid||!K.uuid.match(QI))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[ho.scheme]=ho,W[hu.scheme]=hu,W[fs.scheme]=fs,W[xf.scheme]=xf,W[Jb.scheme]=Jb,W[Zb.scheme]=Zb,W[Xb.scheme]=Xb,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=bt,t.removeDotSegments=lo,t.serialize=qr,t.resolveComponents=fu,t.resolve=gf,t.normalize=lu,t.equal=mf,t.escapeComponent=wf,t.unescapeComponent=Fr,Object.defineProperty(t,"__esModule",{value:!0})})});var K_=oe((DZ,M_)=>{"use strict";l();M_.exports=function t(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?t(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,o,s)=>`${i}${s===0?"":","}${t(o===void 0||typeof o=="symbol"?null:o)}`,"")}]`:`{${Object.keys(e).sort().reduce((n,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return n;let o=n.length===0?"":",";return`${n}${o}${t(i)}:${t(e[i])}`},"")}}`}});var X_=oe((CQ,Z_)=>{l();var Qa=1e3,eu=Qa*60,tu=eu*60,bc=tu*24,HC=bc*7,VC=bc*365.25;Z_.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return qC(t);if(r==="number"&&isFinite(t))return e.long?jC(t):FC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function qC(t){if(t=String(t),!(t.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(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*VC;case"weeks":case"week":case"w":return r*HC;case"days":case"day":case"d":return r*bc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*tu;case"minutes":case"minute":case"mins":case"min":case"m":return r*eu;case"seconds":case"second":case"secs":case"sec":case"s":return r*Qa;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function FC(t){var e=Math.abs(t);return e>=bc?Math.round(t/bc)+"d":e>=tu?Math.round(t/tu)+"h":e>=eu?Math.round(t/eu)+"m":e>=Qa?Math.round(t/Qa)+"s":t+"ms"}function jC(t){var e=Math.abs(t);return e>=bc?Lp(t,e,bc,"day"):e>=tu?Lp(t,e,tu,"hour"):e>=eu?Lp(t,e,eu,"minute"):e>=Qa?Lp(t,e,Qa,"second"):t+" ms"}function Lp(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});l();l();l();l();var ws=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function bs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function pn(t,...e){if(!bs(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Rf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");bu(t.outputLen),bu(t.blockLen)}function Nc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ax(t,e){pn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function qn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Uf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function yn(t,e){return t<<32-e|t>>>e}function xu(t,e){return t<<e|t>>>32-e>>>0}var Tx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",WB=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Pt(t){if(pn(t),Tx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=WB[t[r]];return e}var vi={_0:48,_9:57,A:65,F:70,a:97,f:102};function Sx(t){if(t>=vi._0&&t<=vi._9)return t-vi._0;if(t>=vi.A&&t<=vi.F)return t-(vi.A-10);if(t>=vi.a&&t<=vi.f)return t-(vi.a-10)}function _r(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Tx)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Sx(t.charCodeAt(o)),c=Sx(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function xs(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Eu(t){return typeof t=="string"&&(t=xs(t)),pn(t),t}function ft(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];pn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var kc=class{};function Of(t){let e=n=>t().update(Eu(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ir(t=32){if(ws&&typeof ws.getRandomValues=="function")return ws.getRandomValues(new Uint8Array(t));if(ws&&typeof ws.randomBytes=="function")return Uint8Array.from(ws.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}l();l();l();l();l();function GB(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}function py(t,e,r){return t&e^~t&r}function yy(t,e,r){return t&e^t&r^e&r}var Cc=class extends kc{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Uf(this.buffer)}update(e){Nc(this),e=Eu(e),pn(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Uf(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Nc(this),Ax(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,qn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;GB(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Uf(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Si=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var zB=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]),po=new Uint32Array(64),gy=class extends Cc{constructor(e=32){super(64,e,8,!1),this.A=Si[0]|0,this.B=Si[1]|0,this.C=Si[2]|0,this.D=Si[3]|0,this.E=Si[4]|0,this.F=Si[5]|0,this.G=Si[6]|0,this.H=Si[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)po[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=po[f-15],p=po[f-2],g=yn(h,7)^yn(h,18)^h>>>3,y=yn(p,17)^yn(p,19)^p>>>10;po[f]=y+po[f-7]+g+po[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=yn(c,6)^yn(c,11)^yn(c,25),p=d+h+py(c,a,u)+zB[f]+po[f]|0,y=(yn(n,2)^yn(n,13)^yn(n,22))+yy(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){qn(po)}destroy(){this.set(0,0,0,0,0,0,0,0),qn(this.buffer)}};var ke=Of(()=>new gy);l();l();l();var Df=class extends kc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Rf(e);let n=Eu(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),qn(o)}update(e){return Nc(this),this.iHash.update(e),this}digestInto(e){Nc(this),pn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},my=(t,e,r)=>new Df(t,e).update(r).digest();my.create=(t,e)=>new Df(t,e);l();var xy=BigInt(0),by=BigInt(1);function vu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function yo(t,e,r=""){let n=bs(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function Su(t){let e=t.toString(16);return e.length&1?"0"+e:e}function _x(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?xy:BigInt("0x"+t)}function Ai(t){return _x(Pt(t))}function Ey(t){return pn(t),_x(Pt(Uint8Array.from(t).reverse()))}function Lc(t,e){return _r(t.toString(16).padStart(e*2,"0"))}function vy(t,e){return Lc(t,e).reverse()}function ot(t,e,r){let n;if(typeof e=="string")try{n=_r(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(bs(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function go(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var wy=t=>typeof t=="bigint"&&xy<=t;function Au(t,e,r){return wy(t)&&wy(e)&&wy(r)&&e<=t&&t<r}function Ix(t,e,r,n){if(!Au(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function kf(t){let e;for(e=0;t>xy;t>>=by,e+=1);return e}var mo=t=>(by<<BigInt(t))-by;function Bx(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p),o=n(t),s=n(t),c=0,a=()=>{o.fill(1),s.fill(0),c=0},u=(...p)=>r(s,o,...p),d=(p=n(0))=>{s=u(i(0),p),o=u(),p.length!==0&&(s=u(i(1),p),o=u())},f=()=>{if(c++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,g=[];for(;p<e;){o=u();let y=o.slice();g.push(y),p+=o.length}return ft(...g)};return(p,g)=>{a(),d(p);let y;for(;!(y=g(f()));)d();return a(),y}}function Tu(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,o,s){let c=t[i];if(s&&c===void 0)return;let a=typeof c;if(a!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${a}`)}Object.entries(e).forEach(([i,o])=>n(i,o,!1)),Object.entries(r).forEach(([i,o])=>n(i,o,!0))}function Sy(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}l();l();var tr=BigInt(0),Ft=BigInt(1),Es=BigInt(2),Ox=BigInt(3),Dx=BigInt(4),kx=BigInt(5),YB=BigInt(7),Nx=BigInt(8),JB=BigInt(9),Cx=BigInt(16);function Br(t,e){let r=t%e;return r>=tr?r:e+r}function Rr(t,e,r){let n=t;for(;e-- >tr;)n*=n,n%=r;return n}function Rx(t,e){if(t===tr)throw new Error("invert: expected non-zero number");if(e<=tr)throw new Error("invert: expected positive modulus, got "+e);let r=Br(t,e),n=e,i=tr,o=Ft,s=Ft,c=tr;for(;r!==tr;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==Ft)throw new Error("invert: does not exist");return Br(i,e)}function Ay(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Lx(t,e){let r=(t.ORDER+Ft)/Dx,n=t.pow(e,r);return Ay(t,n,e),n}function ZB(t,e){let r=(t.ORDER-kx)/Nx,n=t.mul(e,Es),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,Es),i),c=t.mul(o,t.sub(s,t.ONE));return Ay(t,c,e),c}function XB(t){let e=wo(t),r=Px(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+YB)/Cx;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),x=c.cmov(u,d,y);return Ay(c,x,a),x}}function Px(t){if(t<Ox)throw new Error("sqrt is not defined for small field");let e=t-Ft,r=0;for(;e%Es===tr;)e/=Es,r++;let n=Es,i=wo(t);for(;Ux(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Lx;let o=i.pow(n,e),s=(e+Ft)/Es;return function(a,u){if(a.is0(u))return u;if(Ux(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let x=Ft<<BigInt(d-g-1),S=a.pow(f,x);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function QB(t){return t%Dx===Ox?Lx:t%Nx===kx?ZB:t%Cx===JB?XB(t):Px(t)}var e8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ty(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=e8.reduce((n,i)=>(n[i]="function",n),e);return Tu(t,r),t}function t8(t,e,r){if(r<tr)throw new Error("invalid exponent, negatives unsupported");if(r===tr)return t.ONE;if(r===Ft)return e;let n=t.ONE,i=e;for(;r>tr;)r&Ft&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Ft;return n}function Nf(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function Ux(t,e){let r=(t.ORDER-Ft)/Es,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Cf(t,e){e!==void 0&&bu(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function wo(t,e,r=!1,n={}){if(t<=tr)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s=!1,c;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(i=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(s=h.modFromBytes),c=h.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(o=n.sqrt);let{nBitLength:a,nByteLength:u}=Cf(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:t,isLE:r,BITS:a,BYTES:u,MASK:mo(a),ZERO:tr,ONE:Ft,allowedLengths:c,create:h=>Br(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return tr<=h&&h<t},is0:h=>h===tr,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ft)===Ft,neg:h=>Br(-h,t),eql:(h,p)=>h===p,sqr:h=>Br(h*h,t),add:(h,p)=>Br(h+p,t),sub:(h,p)=>Br(h-p,t),mul:(h,p)=>Br(h*p,t),pow:(h,p)=>t8(f,h,p),div:(h,p)=>Br(h*Rx(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Rx(h,t),sqrt:o||(h=>(d||(d=QB(t)),d(f,h))),toBytes:h=>r?vy(h,u):Lc(h,u),fromBytes:(h,p=!0)=>{if(c){if(!c.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+h.length);let y=new Uint8Array(u);y.set(h,r?0:y.length-h.length),h=y}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let g=r?Ey(h):Ai(h);if(s&&(g=Br(g,t)),!p&&!f.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>Nf(f,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(f)}function Mx(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function _y(t){let e=Mx(t);return e+Math.ceil(e/2)}function Lf(t,e,r=!1){let n=t.length,i=Mx(e),o=_y(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?Ey(t):Ai(t),c=Br(s,e-Ft)+Ft;return r?vy(c,i):Lc(c,i)}var Pc=BigInt(0),vs=BigInt(1);function _u(t,e){let r=e.negate();return t?r:e}function Mf(t,e){let r=Nf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function Vx(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Iy(t,e){Vx(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=mo(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function Kx(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=vs);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}function r8(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function n8(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}var By=new WeakMap,qx=new WeakMap;function Ry(t){return qx.get(t)||1}function $x(t){if(t!==Pc)throw new Error("invalid wNAF")}var Pf=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>Pc;)r&vs&&(n=n.add(i)),i=i.double(),r>>=vs;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Iy(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=Iy(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=Kx(n,c,s);n=a,d?o=o.add(_u(h,r[p])):i=i.add(_u(f,r[u]))}return $x(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Iy(e,this.bits);for(let s=0;s<o.windows&&n!==Pc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=Kx(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return $x(n),i}getPrecomputes(e,r,n){let i=By.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),By.set(r,i))),i}cached(e,r,n){let i=Ry(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Ry(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){Vx(r,this.bits),qx.set(e,r),By.delete(e)}hasCache(e){return Ry(e)!==1}};function Fx(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>Pc||n>Pc;)r&vs&&(o=o.add(i)),n&vs&&(s=s.add(i)),i=i.double(),r>>=vs,n>>=vs;return{p1:o,p2:s}}function jx(t,e,r,n){r8(r,t),n8(n,e);let i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,c=kf(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=mo(a),d=new Array(Number(u)+1).fill(s),f=Math.floor((e.BITS-1)/a)*a,h=s;for(let p=f;p>=0;p-=a){d.fill(s);for(let y=0;y<o;y++){let x=n[y],S=Number(x>>BigInt(p)&u);d[S]=d[S].add(r[y])}let g=s;for(let y=d.length-1,x=s;y>0;y--)x=x.add(d[y]),g=g.add(x);if(h=h.add(g),p!==0)for(let y=0;y<a;y++)h=h.double()}return h}function Hx(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ty(e),e}else return wo(t,{isLE:r})}function Wx(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>Pc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=Hx(e.p,r.Fp,n),o=Hx(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var Gx=(t,e)=>(t+(t>=0?e:-e)/zx)/e;function i8(t,e,r){let[[n,i],[o,s]]=e,c=Gx(s*t,r),a=Gx(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<_i,h=d<_i;f&&(u=-u),h&&(d=-d);let p=mo(Math.ceil(kf(r)/2))+Mc;if(u<_i||u>=p||d<_i||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Oy(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Uy(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return vu(r.lowS,"lowS"),vu(r.prehash,"prehash"),r.format!==void 0&&Oy(r.format),r}var Dy=class extends Error{constructor(e=""){super(e)}},Ti={Err:Dy,_tlv:{encode:(t,e)=>{let{Err:r}=Ti;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=Su(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Su(i.length/2|128):"";return Su(t)+o+i+e},decode(t,e){let{Err:r}=Ti,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=Ti;if(t<_i)throw new e("integer: negative integers are not allowed");let r=Su(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ti;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ai(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ti,i=ot("signature",t),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Ti,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},_i=BigInt(0),Mc=BigInt(1),zx=BigInt(2),Kf=BigInt(3),o8=BigInt(4);function bo(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=ot("private key",e);try{n=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function s8(t,e={}){let r=Wx("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Tu(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Jx(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,I,D){let{x:E,y:U}=I.toAffine(),L=n.toBytes(E);if(vu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ft(Yx(N),L)}else return ft(Uint8Array.of(4),L,n.toBytes(U))}function h(G){yo(G,void 0,"Point");let{publicKey:I,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===I&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(E===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!x(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${E}, expected compressed=${I} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let I=n.sqr(G),D=n.mul(I,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function x(G,I){let D=n.sqr(I),E=y(G);return n.eql(D,E)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Kf),o8),_=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,_)))throw new Error("bad curve params: a or b");function A(G,I,D=!1){if(!n.isValid(I)||D&&n.is0(I))throw new Error(`bad point coordinate ${G}`);return I}function O(G){if(!(G instanceof $))throw new Error("ProjectivePoint expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return i8(G,a.basises,i.ORDER)}let M=Sy((G,I)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();I==null&&(I=L?n.ONE:n.inv(U));let N=n.mul(D,I),R=n.mul(E,I),C=n.mul(U,I);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=Sy(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:D}=G.toAffine();if(!n.isValid(I)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!x(I,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,I,D,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),I=_u(E,I),D=_u(U,D),I.add(D)}class ${constructor(I,D,E){this.X=A("x",I),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:D,y:E}=I||{};if(!I||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(I instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(I){let D=$.fromAffine(g(yo(I,void 0,"point")));return D.assertValidity(),D}static fromHex(I){return $.fromBytes(ot("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,D=!0){return Q.createCache(this,I),D||this.multiply(Kf),this}assertValidity(){q(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(E,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:D}=o,E=n.mul(D,Kf),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(I,P),C=n.mul(E,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(E,P),z=n.mul(I,z),W=n.sub(V,z),W=n.mul(I,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Kf),W=n.mul(D,L),Y=n.mul(E,N),Z=n.mul(U,R),ue=n.add(D,E),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(E,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(I){return this.add(I.negate())}is0(){return this.equals($.ZERO)}multiply(I){let{endo:D}=e;if(!i.isValidNot0(I))throw new Error("invalid scalar: out of range");let E,U,L=N=>Q.cached(this,N,R=>Mf($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(I),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(I);E=N,U=R}return Mf($,[E,U])[0]}multiplyUnsafe(I){let{endo:D}=e,E=this;if(!i.isValid(I))throw new Error("invalid scalar: out of range");if(I===_i||E.is0())return $.ZERO;if(I===Mc)return E;if(Q.hasCache(this))return this.multiply(I);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(I),{p1:C,p2:P}=Fx($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,I)}multiplyAndAddUnsafe(I,D,E){let U=this.multiplyUnsafe(D).add(I.multiplyUnsafe(E));return U.is0()?void 0:U}toAffine(I){return M(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return s===Mc?!0:I?I($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:I}=e;return s===Mc?this:I?I($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return vu(I,"isCompressed"),this.assertValidity(),p($,this,I)}toHex(I=!0){return Pt(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return Mf($,I)}static msm(I,D){return jx($,i,I,D)}static fromPrivateKey(I){return $.BASE.multiply(bo(i,I))}}$.BASE=new $(o.Gx,o.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;let X=i.BITS,Q=new Pf($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function Yx(t){return Uint8Array.of(t?2:3)}function Jx(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function c8(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ir,i=Object.assign(Jx(t.Fp,r),{seed:_y(r.ORDER)});function o(p){try{return!!bo(r,p)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:x}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==x?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Lf(yo(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(bo(r,p)).toBytes(g)}function u(p){let g=c(p);return{secretKey:g,publicKey:a(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:g,publicKey:y,publicKeyUncompressed:x}=i;if(r.allowedLengths||g===y)return;let S=ot("key",p).length;return S===y||S===x}function f(p,g,y=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");let x=bo(r,p);return t.fromHex(g).multiply(x).toBytes(y)}return Object.freeze({getPublicKey:a,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c,isValidPrivateKey:o,randomPrivateKey:c,normPrivateKeyToScalar:p=>bo(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function a8(t,e,r={}){Rf(e),Tu(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Ir,i=r.hmac||((D,...E)=>my(e,D,ft(...E))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=c8(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function x(D){let E=c>>Mc;return D>E}function S(D,E){if(!s.isValidNot0(E))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return E}function _(D,E){Oy(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return yo(D,L,`${E} signature`)}class A{constructor(E,U,L){this.r=S("r",E),this.s=S("s",U),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(E,U=y){_(E,U);let L;if(U==="der"){let{r:P,s:V}=Ti.toSig(yo(E));return new A(P,V)}U==="recovered"&&(L=E[0],U="compact",E=E.subarray(1));let N=s.BYTES,R=E.subarray(0,N),C=E.subarray(N,N*2);return new A(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(E,U){return this.fromBytes(_r(E),U)}addRecoveryBit(E){return new A(this.r,this.s,E)}recoverPublicKey(E){let U=o.ORDER,{r:L,s:N,recovery:R}=this;if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");if(c*zx<U&&R>1)throw new Error("recovery id is ambiguous for h>1 curve");let P=R===2||R===3?L+c:L;if(!o.isValid(P))throw new Error("recovery id 2 or 3 invalid");let V=o.toBytes(P),J=t.fromBytes(ft(Yx((R&1)===0),V)),z=s.inv(P),W=T(ot("msgHash",E)),Y=s.create(-W*z),Z=s.create(N*z),ue=t.BASE.multiplyUnsafe(Y).add(J.multiplyUnsafe(Z));if(ue.is0())throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return x(this.s)}toBytes(E=y){if(Oy(E),E==="der")return _r(Ti.hexFromSig(this));let U=s.toBytes(this.r),L=s.toBytes(this.s);if(E==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ft(Uint8Array.of(this.recovery),U,L)}return ft(U,L)}toHex(E){return Pt(this.toBytes(E))}assertValidity(){}static fromCompact(E){return A.fromBytes(ot("sig",E),"compact")}static fromDER(E){return A.fromBytes(ot("sig",E),"der")}normalizeS(){return this.hasHighS()?new A(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Pt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Pt(this.toBytes("compact"))}}let O=r.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let U=Ai(E),L=E.length*8-a;return L>0?U>>BigInt(L):U},T=r.bits2int_modN||function(E){return s.create(O(E))},M=mo(a);function q(D){return Ix("num < 2^"+a,D,_i,M),s.toBytes(D)}function j(D,E){return yo(D,void 0,"message"),E?yo(e(D),void 0,"prehashed message"):D}function $(D,E,U){if(["recovered","canonical"].some(Y=>Y in U))throw new Error("sign() legacy options not supported");let{lowS:L,prehash:N,extraEntropy:R}=Uy(U,g);D=j(D,N);let C=T(D),P=bo(s,E),V=[q(P),q(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ot("extraEntropy",Y))}let J=ft(...V),z=C;function W(Y){let Z=O(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===_i)return;let Ue=s.create(ue*s.create(z+ce*P));if(Ue===_i)return;let Ke=(ee.x===ce?0:2)|Number(ee.y&Mc),Je=Ue;return L&&x(Ue)&&(Je=s.neg(Ue),Ke^=1),new A(ce,Je,Ke)}return{seed:J,k2sig:W}}function X(D,E,U={}){D=ot("message",D);let{seed:L,k2sig:N}=$(D,E,U);return Bx(e.outputLen,s.BYTES,i)(L,N)}function Q(D){let E,U=typeof D=="string"||bs(D),L=!U&&D!==null&&typeof D=="object"&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!U&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(L)E=new A(D.r,D.s);else if(U){try{E=A.fromBytes(ot("sig",D),"der")}catch(N){if(!(N instanceof Ti.Err))throw N}if(!E)try{E=A.fromBytes(ot("sig",D),"compact")}catch{return!1}}return E||!1}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=Uy(L,g);if(U=ot("publicKey",U),E=j(ot("message",E),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(ot("sig",D),C);if(P===!1)return!1;try{let V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=T(E),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function I(D,E,U={}){let{prehash:L}=Uy(U,g);return E=j(E,L),A.fromBytes(D,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:X,verify:G,recoverPublicKey:I,Signature:A,hash:e})}function u8(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=wo(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),o={Fp:r,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:o}}function d8(t){let{CURVE:e,curveOpts:r}=u8(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function f8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Cf(r.Fn.ORDER,r.Fn.BITS))})}function Zx(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=d8(t),o=s8(e,r),s=a8(o,n,i);return f8(t,s)}function Xx(t,e){let r=n=>Zx({...t,hash:n});return{...r(e),create:r}}var Kc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},l8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},h8=BigInt(0),Qx=BigInt(1),ky=BigInt(2);function p8(t){let e=Kc.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=Rr(d,r,e)*d%e,h=Rr(f,r,e)*d%e,p=Rr(h,ky,e)*u%e,g=Rr(p,i,e)*p%e,y=Rr(g,o,e)*g%e,x=Rr(y,c,e)*y%e,S=Rr(x,a,e)*x%e,_=Rr(S,c,e)*y%e,A=Rr(_,r,e)*d%e,O=Rr(A,s,e)*g%e,T=Rr(O,n,e)*u%e,M=Rr(T,ky,e);if(!$f.eql($f.sqr(M),t))throw new Error("Cannot find square root");return M}var $f=wo(Kc.p,{sqrt:p8}),xo=Xx({...Kc,Fp:$f,lowS:!0,endo:l8},ke),eE={};function Hf(t,...e){let r=eE[t];if(r===void 0){let n=ke(xs(t));r=ft(n,n),eE[t]=r}return ke(ft(r,...e))}var Cy=t=>t.toBytes(!0).slice(1),$c=xo.Point,Ly=t=>t%ky===h8;function Ny(t){let{Fn:e,BASE:r}=$c,n=bo(e,t),i=r.multiply(n);return{scalar:Ly(i.y)?n:e.neg(n),bytes:Cy(i)}}function rE(t){let e=$f;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Ly(i)||(i=e.neg(i));let o=$c.fromAffine({x:t,y:i});return o.assertValidity(),o}var Iu=Ai;function nE(...t){return $c.Fn.create(Iu(Hf("BIP0340/challenge",...t)))}function tE(t){return Ny(t).bytes}function y8(t,e,r=Ir(32)){let{Fn:n}=$c,i=ot("message",t),{bytes:o,scalar:s}=Ny(e),c=ot("auxRand",r,32),a=n.toBytes(s^Iu(Hf("BIP0340/aux",c))),u=Hf("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Ny(u),h=nE(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!iE(p,i,o))throw new Error("sign: Invalid signature produced");return p}function iE(t,e,r){let{Fn:n,BASE:i}=$c,o=ot("signature",t,64),s=ot("message",e),c=ot("publicKey",r,32);try{let a=rE(Iu(c)),u=Iu(o.subarray(0,32));if(!Au(u,Qx,Kc.p))return!1;let d=Iu(o.subarray(32,64));if(!Au(d,Qx,Kc.n))return!1;let f=nE(n.toBytes(u),Cy(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!Ly(g)||p!==u)}catch{return!1}}var Ur=(()=>{let r=(i=Ir(48))=>Lf(i,Kc.n);xo.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:tE(o)}}return{keygen:n,getPublicKey:tE,sign:y8,verify:iE,Point:$c,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Hf,lift_x:rE,pointToBytes:Cy,numberToBytesBE:Lc,bytesToNumberBE:Ai,mod:Br},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var g8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),sE=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),m8=sE.map(t=>(9*t+5)%16),cE=(()=>{let r=[[sE],[m8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>g8[o]));return r})(),aE=cE[0],uE=cE[1],dE=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(t=>Uint8Array.from(t)),w8=aE.map((t,e)=>t.map(r=>dE[e][r])),b8=uE.map((t,e)=>t.map(r=>dE[e][r])),x8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),E8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function oE(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}var Vf=new Uint32Array(16),Py=class extends Cc{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:r,h2:n,h3:i,h4:o}=this;return[e,r,n,i,o]}set(e,r,n,i,o){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=o|0}process(e,r){for(let p=0;p<16;p++,r+=4)Vf[p]=e.getUint32(r,!0);let n=this.h0|0,i=n,o=this.h1|0,s=o,c=this.h2|0,a=c,u=this.h3|0,d=u,f=this.h4|0,h=f;for(let p=0;p<5;p++){let g=4-p,y=x8[p],x=E8[p],S=aE[p],_=uE[p],A=w8[p],O=b8[p];for(let T=0;T<16;T++){let M=xu(n+oE(p,o,c,u)+Vf[S[T]]+y,A[T])+f|0;n=f,f=u,u=xu(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=xu(i+oE(g,s,a,d)+Vf[_[T]]+x,O[T])+h|0;i=h,h=d,d=xu(a,10)|0,a=s,s=M}}this.set(this.h1+c+d|0,this.h2+u+h|0,this.h3+f+i|0,this.h4+n+s|0,this.h0+o+a|0)}roundClean(){qn(Vf)}destroy(){this.destroyed=!0,qn(this.buffer),this.set(0,0,0,0,0)}},fE=Of(()=>new Py);l();l();function Hc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function v8(t,...e){if(!Hc(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function gE(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function $y(t){if(typeof t!="function")throw new Error("function expected");return!0}function Vc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Ru(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Ff(t){if(!Array.isArray(t))throw new Error("array expected")}function mE(t,e){if(!gE(!0,e))throw new Error(`${t}: array of strings expected`)}function Hy(t,e){if(!gE(!1,e))throw new Error(`${t}: array of numbers expected`)}function Uu(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function Wf(t){let e=typeof t=="string"?t.split(""):t,r=e.length;mE("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Ff(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(Ff(i),i.map(o=>{Vc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function Gf(t=""){return Vc("join",t),{encode:e=>(mE("join.decode",e),e.join(t)),decode:e=>(Vc("join.decode",e),e.split(t))}}function S8(t){return $y(t),{encode:e=>e,decode:e=>t(e)}}function lE(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Ff(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Ru(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}var wE=(t,e)=>e===0?t:wE(e,t%e),jf=(t,e)=>t+(e-wE(t,e)),qf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function My(t,e,r,n){if(Ff(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(jf(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${jf(e,r)}`);let i=0,o=0,s=qf[e],c=qf[r]-1,a=[];for(let u of t){if(Ru(u),u>=s)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=r;o-=r)a.push((i>>o-r&c)>>>0);let d=qf[o];if(d===void 0)throw new Error("invalid carry");i&=d-1}if(i=i<<r-o&c,!n&&o>=e)throw new Error("Excess padding");if(!n&&i>0)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&a.push(i>>>0),a}function A8(t){Ru(t);let e=2**8;return{encode:r=>{if(!Hc(r))throw new Error("radix.encode input should be Uint8Array");return lE(Array.from(r),e,t)},decode:r=>(Hy("radix.decode",r),Uint8Array.from(lE(r,t,e)))}}function Vy(t,e=!1){if(Ru(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(jf(8,t)>32||jf(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Hc(r))throw new Error("radix2.encode input should be Uint8Array");return My(Array.from(r),8,t,!e)},decode:r=>(Hy("radix2.decode",r),Uint8Array.from(My(r,t,8,e)))}}function hE(t){return $y(t),function(...e){try{return t.apply(null,e)}catch{}}}function T8(t,e){return Ru(t),$y(e),{encode(r){if(!Hc(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!Hc(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=r.slice(-t),o=e(n).slice(0,t);for(let s=0;s<t;s++)if(o[s]!==i[s])throw new Error("Invalid checksum");return n}}}var qc=Uu(Vy(6),Wf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Gf("")),_8=t=>Uu(A8(58),Wf(t),Gf("")),zf=_8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var bE=t=>Uu(T8(4,e=>t(t(e))),zf);var Ky=Uu(Wf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Gf("")),pE=[996825010,642813549,513874426,1027748829,705979059];function Bu(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<pE.length;n++)(e>>n&1)===1&&(r^=pE[n]);return r}function yE(t,e,r=1){let n=t.length,i=1;for(let o=0;o<n;o++){let s=t.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);i=Bu(i)^s>>5}i=Bu(i);for(let o=0;o<n;o++)i=Bu(i)^t.charCodeAt(o)&31;for(let o of e)i=Bu(i)^o;for(let o=0;o<6;o++)i=Bu(i);return i^=r,Ky.encode(My([i%qf[30]],30,5,!1))}function xE(t){let e=t==="bech32"?1:734539939,r=Vy(5),n=r.decode,i=r.encode,o=hE(n);function s(f,h,p=90){Vc("bech32.encode prefix",f),Hc(h)&&(h=Array.from(h)),Hy("bech32.encode",h);let g=f.length;if(g===0)throw new TypeError(`Invalid prefix length ${g}`);let y=g+7+h.length;if(p!==!1&&y>p)throw new TypeError(`Length ${y} exceeds limit ${p}`);let x=f.toLowerCase(),S=yE(x,h,e);return`${x}1${Ky.encode(h)}${S}`}function c(f,h=90){Vc("bech32.decode input",f);let p=f.length;if(p<8||h!==!1&&p>h)throw new TypeError(`invalid string length: ${p} (${f}). Expected (8..${h})`);let g=f.toLowerCase();if(f!==g&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");let y=g.lastIndexOf("1");if(y===0||y===-1)throw new Error('Letter "1" must be present between prefix and data only');let x=g.slice(0,y),S=g.slice(y+1);if(S.length<6)throw new Error("Data must be at least 6 characters long");let _=Ky.decode(S).slice(0,-6),A=yE(x,_,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:x,words:_}}let a=hE(c);function u(f){let{prefix:h,words:p}=c(f,!1);return{prefix:h,words:p,bytes:n(p)}}function d(f,h){return s(f,i(h))}return{encode:s,decode:c,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:a,fromWords:n,fromWordsUnsafe:o,toWords:i}}var Yf=xE("bech32"),Ss=xE("bech32m"),EE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},I8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",B8={encode(t){return v8(t),t.toHex()},decode(t){return Vc("hex",t),Uint8Array.fromHex(t)}},xe=I8?B8:Uu(Vy(4),Wf("0123456789abcdef"),Gf(""),S8(t=>{if(typeof t!="string"||t.length%2!==0)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));var Ve=new Uint8Array,Wy=new Uint8Array([0]);function Fc(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function zr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function R8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!zr(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Gy=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function jc(t){return Object.prototype.toString.call(t)==="[object Object]"}function Fn(t){return Number.isSafeInteger(t)}var Jf={equalBytes:Fc,isBytes:zr,isCoder:Or,checkBounds:SE,concatBytes:R8,createView:Gy,isPlainObject:jc},vE=t=>{if(t!==null&&typeof t!="string"&&!Or(t)&&!zr(t)&&!Fn(t))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${t} (${typeof t})`);return{encodeStream(e,r){if(t===null)return;if(Or(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=Ii.resolve(e.stack,t)),typeof n=="bigint"&&(n=Number(n)),n===void 0||n!==r)throw e.err(`Wrong length: ${n} len=${t} exp=${r} (${typeof r})`)},decodeStream(e){let r;if(Or(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=Ii.resolve(e.stack,t)),typeof r=="bigint"&&(r=Number(r)),typeof r!="number")throw e.err(`Wrong length: ${r}`);return r}}},Ot={BITS:32,FULL_MASK:-1>>>0,len:t=>Math.ceil(t/32),create:t=>new Uint32Array(Ot.len(t)),clean:t=>t.fill(0),debug:t=>Array.from(t).map(e=>(e>>>0).toString(2).padStart(32,"0")),checkLen:(t,e)=>{if(Ot.len(e)!==t.length)throw new Error(`wrong length=${t.length}. Expected: ${Ot.len(e)}`)},chunkLen:(t,e,r)=>{if(e<0)throw new Error(`wrong pos=${e}`);if(e+r>t)throw new Error(`wrong range=${e}/${r} of ${t}`)},set:(t,e,r,n=!0)=>!n&&t[e]&r?!1:(t[e]|=r,!0),pos:(t,e)=>({chunk:Math.floor((t+e)/32),mask:1<<32-(t+e)%32-1}),indices:(t,e,r=!1)=>{Ot.checkLen(t,e);let{FULL_MASK:n,BITS:i}=Ot,o=i-e%i,s=o?n>>>o<<o:n,c=[];for(let a=0;a<t.length;a++){let u=t[a];if(r&&(u=~u),a===t.length-1&&(u&=s),u!==0)for(let d=0;d<i;d++){let f=1<<i-d-1;u&f&&c.push(a*i+d)}}return c},range:t=>{let e=[],r;for(let n of t)r===void 0||n!==r.pos+r.length?e.push(r={pos:n,length:1}):r.length+=1;return e},rangeDebug:(t,e,r=!1)=>`[${Ot.range(Ot.indices(t,e,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(t,e,r,n,i=!0)=>{Ot.chunkLen(e,r,n);let{FULL_MASK:o,BITS:s}=Ot,c=r%s?Math.floor(r/s):void 0,a=r+n,u=a%s?Math.floor(a/s):void 0;if(c!==void 0&&c===u)return Ot.set(t,c,o>>>s-n<<s-n-r,i);if(c!==void 0&&!Ot.set(t,c,o>>>r%s,i))return!1;let d=c!==void 0?c+1:r/s,f=u!==void 0?u:a/s;for(let h=d;h<f;h++)if(!Ot.set(t,h,o,i))return!1;return!(u!==void 0&&c!==u&&!Ot.set(t,u,o<<s-a%s,i))}},Ii={pushObj:(t,e,r)=>{let n={obj:e};t.push(n),r((i,o)=>{n.field=i,o(),n.field=void 0}),t.pop()},path:t=>{let e=[];for(let r of t)r.field!==void 0&&e.push(r.field);return e.join("/")},err:(t,e,r)=>{let n=new Error(`${t}(${Ii.path(e)}): ${typeof r=="string"?r:r.message}`);return r instanceof Error&&r.stack&&(n.stack=r.stack),n},resolve:(t,e)=>{let r=e.split("/"),n=t.map(s=>s.obj),i=0;for(;i<r.length&&r[i]==="..";i++)n.pop();let o=n.pop();for(;i<r.length;i++){if(!o||o[r[i]]===void 0)return;o=o[r[i]]}return o}},qy=class t{constructor(e,r={},n=[],i=void 0,o=0){this.pos=0,this.bitBuf=0,this.bitPos=0,this.data=e,this.opts=r,this.stack=n,this.parent=i,this.parentOffset=o,this.view=Gy(e)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=Ot.create(this.data.length),Ot.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(e,r){return this.parent?this.parent.markBytesBS(this.parentOffset+e,r):!r||!this.bs?!0:Ot.setRange(this.bs,this.data.length,e,r,!1)}markBytes(e){let r=this.pos;this.pos+=e;let n=this.markBytesBS(r,e);if(!this.opts.allowMultipleReads&&!n)throw this.err(`multiple read pos=${this.pos} len=${e}`);return n}pushObj(e,r){return Ii.pushObj(this.stack,e,r)}readView(e,r){if(!Number.isFinite(e))throw this.err(`readView: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readView: Unexpected end of buffer");let n=r(this.view,this.pos);return this.markBytes(e),n}absBytes(e){if(e>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(e)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${xe.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){let e=Ot.indices(this.bs,this.data.length,!0);if(e.length){let r=Ot.range(e).map(({pos:n,length:i})=>`(${n}/${i})[${xe.encode(this.data.subarray(n,n+i))}]`).join(", ");throw this.err(`unread byte ranges: ${r} (total=${this.data.length})`)}else return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${xe.encode(this.data.slice(this.pos))}`)}}err(e){return Ii.err("Reader",this.stack,e)}offsetReader(e){if(e>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new t(this.absBytes(e),this.opts,this.stack,this,e)}bytes(e,r=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(e))throw this.err(`readBytes: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let n=this.data.subarray(this.pos,this.pos+e);return r||this.markBytes(e),n}byte(e=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let r=this.data[this.pos];return e||this.markBytes(1),r}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}bits(e){if(e>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let r=0;for(;e;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);let n=Math.min(e,this.bitPos);this.bitPos-=n,r=r<<n|this.bitBuf>>this.bitPos&2**n-1,this.bitBuf&=2**this.bitPos-1,e-=n}return r>>>0}find(e,r=this.pos){if(!zr(e))throw this.err(`find: needle is not bytes! ${e}`);if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!e.length)throw this.err("find: needle is empty");for(let n=r;(n=this.data.indexOf(e[0],n))!==-1;n++){if(n===-1||this.data.length-n<e.length)return;if(Fc(e,this.data.subarray(n,n+e.length)))return n}}},Fy=class{constructor(e=[]){this.pos=0,this.buffers=[],this.ptrs=[],this.bitBuf=0,this.bitPos=0,this.viewBuf=new Uint8Array(8),this.finished=!1,this.stack=e,this.view=Gy(this.viewBuf)}pushObj(e,r){return Ii.pushObj(this.stack,e,r)}writeView(e,r){if(this.finished)throw this.err("buffer: finished");if(!Fn(e)||e>8)throw new Error(`wrong writeView length=${e}`);r(this.view),this.bytes(this.viewBuf.slice(0,e)),this.viewBuf.fill(0)}err(e){if(this.finished)throw this.err("buffer: finished");return Ii.err("Reader",this.stack,e)}bytes(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(e),this.pos+=e.length}byte(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([e])),this.pos++}finish(e=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");let r=this.buffers.concat(this.ptrs.map(o=>o.buffer)),n=r.map(o=>o.length).reduce((o,s)=>o+s,0),i=new Uint8Array(n);for(let o=0,s=0;o<r.length;o++){let c=r[o];i.set(c,s),s+=c.length}for(let o=this.pos,s=0;s<this.ptrs.length;s++){let c=this.ptrs[s];i.set(c.ptr.encode(o),c.pos),o+=c.buffer.length}if(e){this.buffers=[];for(let o of this.ptrs)o.buffer.fill(0);this.ptrs=[],this.finished=!0,this.bitBuf=0}return i}bits(e,r){if(r>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(e>=2**r)throw this.err(`writeBits: value (${e}) >= 2**bits (${r})`);for(;r;){let n=Math.min(r,8-this.bitPos);this.bitBuf=this.bitBuf<<n|e>>r-n,this.bitPos+=n,r-=n,e&=2**r-1,this.bitPos===8&&(this.bitPos=0,this.buffers.push(new Uint8Array([this.bitBuf])),this.pos++)}}},jy=t=>Uint8Array.from(t).reverse();function SE(t,e,r){if(r){let n=2n**(e-1n);if(t<-n||t>=n)throw new Error(`value out of signed bounds. Expected ${-n} <= ${t} < ${n}`)}else if(0n>t||t>=2n**e)throw new Error(`value out of unsigned bounds. Expected 0 <= ${t} < ${2n**e}`)}function AE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new Fy;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new qy(e,r),i=t.decodeStream(n);return n.finish(),i}}}function jt(t,e){if(!Or(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return AE({size:t.size,encodeStream:(r,n)=>{let i;try{i=e(n)}catch(o){throw r.err(o)}t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e(n)}catch(i){throw r.err(i)}}})}var Wt=t=>{let e=AE(t);return t.validate?jt(e,t.validate):e},Zf=t=>jc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Or(t){return jc(t)&&Zf(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||Fn(t.size))}function U8(){return{encode:t=>{if(!Array.isArray(t))throw new Error("array expected");let e={};for(let r of t){if(!Array.isArray(r)||r.length!==2)throw new Error("array of two elements expected");let n=r[0],i=r[1];if(e[n]!==void 0)throw new Error(`key(${n}) appears twice in struct`);e[n]=i}return e},decode:t=>{if(!jc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var O8={encode:t=>{if(typeof t!="bigint")throw new Error(`expected bigint, got ${typeof t}`);if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${t}`);return Number(t)},decode:t=>{if(!Fn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function D8(t){if(!jc(t))throw new Error("plain object expected");return{encode:e=>{if(!Fn(e)||!(e in t))throw new Error(`wrong value ${e}`);return t[e]},decode:e=>{if(typeof e!="string")throw new Error(`wrong value ${typeof e}`);return t[e]}}}function k8(t,e=!1){if(!Fn(t))throw new Error(`decimal/precision: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`decimal/round: expected boolean, got ${typeof e}`);let r=10n**BigInt(t);return{encode:n=>{if(typeof n!="bigint")throw new Error(`expected bigint, got ${typeof n}`);let i=(n<0n?-n:n).toString(10),o=i.length-t;o<0&&(i=i.padStart(i.length-o,"0"),o=0);let s=i.length-1;for(;s>=o&&i[s]==="0";s--);let c=i.slice(0,o),a=i.slice(o,s+1);return c||(c="0"),n<0n&&(c="-"+c),a?`${c}.${a}`:c},decode:n=>{if(typeof n!="string")throw new Error(`expected string, got ${typeof n}`);if(n==="-0")throw new Error("negative zero is not allowed");let i=!1;if(n.startsWith("-")&&(i=!0,n=n.slice(1)),!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))throw new Error(`wrong string value=${n}`);let o=n.indexOf(".");o=o===-1?n.length:o;let s=n.slice(0,o),c=n.slice(o+1).replace(/0+$/,""),a=BigInt(s)*r;if(!e&&c.length>t)throw new Error(`fractional part cannot be represented with this precision (num=${n}, prec=${t})`);let u=Math.min(c.length,t),d=BigInt(c.slice(0,u))*10n**BigInt(t-u),f=a+d;return i?-f:f}}}function N8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!Zf(e))throw new Error(`wrong base coder ${e}`);return{encode:e=>{for(let r of t){let n=r.encode(e);if(n!==void 0)return n}throw new Error(`match/encode: cannot find match in ${e}`)},decode:e=>{for(let r of t){let n=r.decode(e);if(n!==void 0)return n}throw new Error(`match/decode: cannot find match in ${e}`)}}}var TE=t=>{if(!Zf(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Bi={dict:U8,numberBigint:O8,tsEnum:D8,decimal:k8,match:N8,reverse:TE};var zy=(t,e=!1,r=!1,n=!0)=>{if(!Fn(t))throw new Error(`bigint/size: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`bigint/le: expected boolean, got ${typeof e}`);if(typeof r!="boolean")throw new Error(`bigint/signed: expected boolean, got ${typeof r}`);if(typeof n!="boolean")throw new Error(`bigint/sized: expected boolean, got ${typeof n}`);let i=BigInt(t),o=2n**(8n*i-1n);return Wt({size:n?t:void 0,encodeStream:(s,c)=>{r&&c<0&&(c=c|o);let a=[];for(let d=0;d<t;d++)a.push(Number(c&255n)),c>>=8n;let u=new Uint8Array(a).reverse();if(!n){let d=0;for(d=0;d<u.length&&u[d]===0;d++);u=u.subarray(d)}s.bytes(e?u.reverse():u)},decodeStream:s=>{let c=s.bytes(n?t:Math.min(t,s.leftBytes)),a=e?c:jy(c),u=0n;for(let d=0;d<a.length;d++)u|=BigInt(a[d])<<8n*BigInt(d);return r&&u&o&&(u=(u^o)-o),u},validate:s=>{if(typeof s!="bigint")throw new Error(`bigint: invalid value: ${s}`);return SE(s,8n*i,!!r),s}})};var _E=zy(32,!1);var Wc=zy(8,!0);var IE=zy(8,!0,!0);var C8=(t,e)=>Wt({size:t,encodeStream:(r,n)=>r.writeView(t,i=>e.write(i,n)),decodeStream:r=>r.readView(t,e.read),validate:r=>{if(typeof r!="number")throw new Error(`viewCoder: expected number, got ${typeof r}`);return e.validate&&e.validate(r),r}}),Ou=(t,e,r)=>{let n=t*8,i=2**(n-1),o=a=>{if(!Fn(a))throw new Error(`sintView: value is not safe integer: ${a}`);if(a<-i||a>=i)throw new Error(`sintView: value out of bounds. Expected ${-i} <= ${a} < ${i}`)},s=2**n,c=a=>{if(!Fn(a))throw new Error(`uintView: value is not safe integer: ${a}`);if(0>a||a>=s)throw new Error(`uintView: value out of bounds. Expected 0 <= ${a} < ${s}`)};return C8(t,{write:r.write,read:r.read,validate:e?o:c})},_e=Ou(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),BE=Ou(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),Eo=Ou(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var Yy=Ou(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var mn=Ou(1,!1,{read:(t,e)=>t.getUint8(e),write:(t,e)=>t.setUint8(0,e)});var Fe=(t,e=!1)=>{if(typeof e!="boolean")throw new Error(`bytes/le: expected boolean, got ${typeof e}`);let r=vE(t),n=zr(t);return Wt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?jy(o):o),n&&i.bytes(t)},decodeStream:i=>{let o;if(n){let s=i.find(t);if(!s)throw i.err("bytes: cannot find terminator");o=i.bytes(s-i.pos),i.bytes(t.length)}else o=i.bytes(t===null?i.leftBytes:r.decodeStream(i));return e?jy(o):o},validate:i=>{if(!zr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function RE(t,e){if(!Or(e))throw new Error(`prefix: invalid inner value ${e}`);return gn(Fe(t),TE(e))}var Xf=(t,e=!1)=>jt(gn(Fe(t,e),EE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var UE=(t,e={isLE:!1,with0x:!1})=>{let r=gn(Fe(t,e.isLE),xe),n=e.with0x;if(typeof n!="boolean")throw new Error(`hex/with0x: expected boolean, got ${typeof n}`);return n&&(r=gn(r,{encode:i=>`0x${i}`,decode:i=>{if(!i.startsWith("0x"))throw new Error("hex(with0x=true).encode input should start with 0x");return i.slice(2)}})),r};function gn(t,e){if(!Or(t))throw new Error(`apply: invalid inner value ${t}`);if(!Zf(e))throw new Error(`apply: invalid base value ${t}`);return Wt({size:t.size,encodeStream:(r,n)=>{let i;try{i=e.decode(n)}catch(o){throw r.err(""+o)}return t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e.encode(n)}catch(i){throw r.err(""+i)}}})}var OE=(t,e=!1)=>{if(!zr(t))throw new Error(`flag/flagValue: expected Uint8Array, got ${typeof t}`);if(typeof e!="boolean")throw new Error(`flag/xor: expected boolean, got ${typeof e}`);return Wt({size:t.length,encodeStream:(r,n)=>{!!n!==e&&r.bytes(t)},decodeStream:r=>{let n=r.leftBytes>=t.length;return n&&(n=Fc(r.bytes(t.length,!0),t),n&&r.bytes(t.length)),n!==e},validate:r=>{if(r!==void 0&&typeof r!="boolean")throw new Error(`flag: expected boolean value or undefined, got ${typeof r}`);return r}})};function DE(t,e,r){if(!Or(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Or(e))throw new Error(`flagged: wrong path=${t}`);return Wt({encodeStream:(n,i)=>{typeof t=="string"?Ii.resolve(n.stack,t)?e.encodeStream(n,i):r&&e.encodeStream(n,r):(t.encodeStream(n,!!i),i?e.encodeStream(n,i):r&&e.encodeStream(n,r))},decodeStream:n=>{let i=!1;if(typeof t=="string"?i=!!Ii.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function Qf(t,e,r=!0){if(!Or(t))throw new Error(`magic: invalid inner value ${t}`);if(typeof r!="boolean")throw new Error(`magic: expected boolean, got ${typeof r}`);return Wt({size:t.size,encodeStream:(n,i)=>t.encodeStream(n,e),decodeStream:n=>{let i=t.decodeStream(n);if(r&&typeof i!="object"&&i!==e||zr(e)&&!Fc(e,i))throw n.err(`magic: invalid value: ${i} !== ${e}`)},validate:n=>{if(n!==void 0)throw new Error(`magic: wrong value=${typeof n}`);return n}})}function kE(t){let e=0;for(let r of t){if(r.size===void 0)return;if(!Fn(r.size))throw new Error(`sizeof: wrong element size=${e}`);e+=r.size}return e}function xt(t){if(!jc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Or(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return Wt({size:kE(Object.values(t)),encodeStream:(e,r)=>{e.pushObj(r,n=>{for(let i in t)n(i,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r={};return e.pushObj(r,n=>{for(let i in t)n(i,()=>r[i]=t[i].decodeStream(e))}),r},validate:e=>{if(typeof e!="object"||e===null)throw new Error(`struct: invalid value ${e}`);return e}})}function NE(t){if(!Array.isArray(t))throw new Error(`Packed.Tuple: got ${typeof t} instead of array`);for(let e=0;e<t.length;e++)if(!Or(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return Wt({size:kE(t),encodeStream:(e,r)=>{if(!Array.isArray(r))throw e.err(`tuple: invalid value ${r}`);e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r=[];return e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>r.push(t[i].decodeStream(e)))}),r},validate:e=>{if(!Array.isArray(e))throw new Error(`tuple: invalid value ${e}`);if(e.length!==t.length)throw new Error(`tuple: wrong length=${e.length}, expected ${t.length}`);return e}})}function Gt(t,e){if(!Or(e))throw new Error(`array: invalid inner value ${e}`);let r=vE(typeof t=="string"?`../${t}`:t);return Wt({size:typeof t=="number"&&e.size?t*e.size:void 0,encodeStream:(n,i)=>{let o=n;o.pushObj(i,s=>{zr(t)||r.encodeStream(n,i.length);for(let c=0;c<i.length;c++)s(`${c}`,()=>{let a=i[c],u=n.pos;if(e.encodeStream(n,a),zr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(Fc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),zr(t)&&n.bytes(t)},decodeStream:n=>{let i=[];return n.pushObj(i,o=>{if(t===null)for(let s=0;!n.isEnd()&&(o(`${s}`,()=>i.push(e.decodeStream(n))),!(e.size&&n.leftBytes<e.size));s++);else if(zr(t))for(let s=0;;s++){if(Fc(n.bytes(t.length,!0),t)){n.bytes(t.length);break}o(`${s}`,()=>i.push(e.decodeStream(n)))}else{let s;o("arrayLen",()=>s=r.decodeStream(n));for(let c=0;c<s;c++)o(`${c}`,()=>i.push(e.decodeStream(n)))}}),i},validate:n=>{if(!Array.isArray(n))throw new Error(`array: invalid value ${n}`);return n}})}var rl=xo.ProjectivePoint,tl=xo.CURVE.n,Ce=Jf.isBytes,jn=Jf.concatBytes,st=Jf.equalBytes;var Gc=t=>fE(ke(t)),Ri=(...t)=>ke(ke(jn(...t))),oM=Ur.utils.randomPrivateKey,nl=Ur.getPublicKey,Jy=xo.getPublicKey,CE=t=>t.r<tl/2n;function LE(t,e,r=!1){let n=xo.sign(t,e);if(r&&!CE(n)){let i=new Uint8Array(32),o=0;for(;!CE(n);)if(i.set(_e.encode(o++)),n=xo.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var Zy=Ur.sign,Du=Ur.utils.taggedHash,Et;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(Et||(Et={}));function vo(t,e){let r=t.length;if(e===Et.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return rl.fromHex(t),t}else if(e===Et.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Ur.utils.lift_x(Ur.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function PE(t,e){let r=Ur.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=tl)throw new Error("tweak higher than curve order");return i}function ME(t,e=Uint8Array.of()){let r=Ur.utils,n=r.bytesToNumberBE(t),i=rl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,tl),s=r.pointToBytes(i),c=PE(s,e);return r.numberToBytesBE(r.mod(o+c,tl),32)}function ku(t,e){let r=Ur.utils,n=PE(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(rl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var il=ke(rl.BASE.toRawBytes(!1)),Yr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},Xy={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function Nu(t,e){if(!Ce(t)||!Ce(e))throw new Error(`cmp: wrong type a=${typeof t} b=${typeof e}`);let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!=e[n])return Math.sign(t[n]-e[n]);return Math.sign(t.length-e.length)}l();l();l();var wt;(function(t){t[t.OP_0=0]="OP_0",t[t.PUSHDATA1=76]="PUSHDATA1",t[t.PUSHDATA2=77]="PUSHDATA2",t[t.PUSHDATA4=78]="PUSHDATA4",t[t["1NEGATE"]=79]="1NEGATE",t[t.RESERVED=80]="RESERVED",t[t.OP_1=81]="OP_1",t[t.OP_2=82]="OP_2",t[t.OP_3=83]="OP_3",t[t.OP_4=84]="OP_4",t[t.OP_5=85]="OP_5",t[t.OP_6=86]="OP_6",t[t.OP_7=87]="OP_7",t[t.OP_8=88]="OP_8",t[t.OP_9=89]="OP_9",t[t.OP_10=90]="OP_10",t[t.OP_11=91]="OP_11",t[t.OP_12=92]="OP_12",t[t.OP_13=93]="OP_13",t[t.OP_14=94]="OP_14",t[t.OP_15=95]="OP_15",t[t.OP_16=96]="OP_16",t[t.NOP=97]="NOP",t[t.VER=98]="VER",t[t.IF=99]="IF",t[t.NOTIF=100]="NOTIF",t[t.VERIF=101]="VERIF",t[t.VERNOTIF=102]="VERNOTIF",t[t.ELSE=103]="ELSE",t[t.ENDIF=104]="ENDIF",t[t.VERIFY=105]="VERIFY",t[t.RETURN=106]="RETURN",t[t.TOALTSTACK=107]="TOALTSTACK",t[t.FROMALTSTACK=108]="FROMALTSTACK",t[t["2DROP"]=109]="2DROP",t[t["2DUP"]=110]="2DUP",t[t["3DUP"]=111]="3DUP",t[t["2OVER"]=112]="2OVER",t[t["2ROT"]=113]="2ROT",t[t["2SWAP"]=114]="2SWAP",t[t.IFDUP=115]="IFDUP",t[t.DEPTH=116]="DEPTH",t[t.DROP=117]="DROP",t[t.DUP=118]="DUP",t[t.NIP=119]="NIP",t[t.OVER=120]="OVER",t[t.PICK=121]="PICK",t[t.ROLL=122]="ROLL",t[t.ROT=123]="ROT",t[t.SWAP=124]="SWAP",t[t.TUCK=125]="TUCK",t[t.CAT=126]="CAT",t[t.SUBSTR=127]="SUBSTR",t[t.LEFT=128]="LEFT",t[t.RIGHT=129]="RIGHT",t[t.SIZE=130]="SIZE",t[t.INVERT=131]="INVERT",t[t.AND=132]="AND",t[t.OR=133]="OR",t[t.XOR=134]="XOR",t[t.EQUAL=135]="EQUAL",t[t.EQUALVERIFY=136]="EQUALVERIFY",t[t.RESERVED1=137]="RESERVED1",t[t.RESERVED2=138]="RESERVED2",t[t["1ADD"]=139]="1ADD",t[t["1SUB"]=140]="1SUB",t[t["2MUL"]=141]="2MUL",t[t["2DIV"]=142]="2DIV",t[t.NEGATE=143]="NEGATE",t[t.ABS=144]="ABS",t[t.NOT=145]="NOT",t[t["0NOTEQUAL"]=146]="0NOTEQUAL",t[t.ADD=147]="ADD",t[t.SUB=148]="SUB",t[t.MUL=149]="MUL",t[t.DIV=150]="DIV",t[t.MOD=151]="MOD",t[t.LSHIFT=152]="LSHIFT",t[t.RSHIFT=153]="RSHIFT",t[t.BOOLAND=154]="BOOLAND",t[t.BOOLOR=155]="BOOLOR",t[t.NUMEQUAL=156]="NUMEQUAL",t[t.NUMEQUALVERIFY=157]="NUMEQUALVERIFY",t[t.NUMNOTEQUAL=158]="NUMNOTEQUAL",t[t.LESSTHAN=159]="LESSTHAN",t[t.GREATERTHAN=160]="GREATERTHAN",t[t.LESSTHANOREQUAL=161]="LESSTHANOREQUAL",t[t.GREATERTHANOREQUAL=162]="GREATERTHANOREQUAL",t[t.MIN=163]="MIN",t[t.MAX=164]="MAX",t[t.WITHIN=165]="WITHIN",t[t.RIPEMD160=166]="RIPEMD160",t[t.SHA1=167]="SHA1",t[t.SHA256=168]="SHA256",t[t.HASH160=169]="HASH160",t[t.HASH256=170]="HASH256",t[t.CODESEPARATOR=171]="CODESEPARATOR",t[t.CHECKSIG=172]="CHECKSIG",t[t.CHECKSIGVERIFY=173]="CHECKSIGVERIFY",t[t.CHECKMULTISIG=174]="CHECKMULTISIG",t[t.CHECKMULTISIGVERIFY=175]="CHECKMULTISIGVERIFY",t[t.NOP1=176]="NOP1",t[t.CHECKLOCKTIMEVERIFY=177]="CHECKLOCKTIMEVERIFY",t[t.CHECKSEQUENCEVERIFY=178]="CHECKSEQUENCEVERIFY",t[t.NOP4=179]="NOP4",t[t.NOP5=180]="NOP5",t[t.NOP6=181]="NOP6",t[t.NOP7=182]="NOP7",t[t.NOP8=183]="NOP8",t[t.NOP9=184]="NOP9",t[t.NOP10=185]="NOP10",t[t.CHECKSIGADD=186]="CHECKSIGADD",t[t.INVALID=255]="INVALID"})(wt||(wt={}));function Qy(t=6,e=!1){return Wt({encodeStream:(r,n)=>{if(n===0n)return;let i=n<0,o=BigInt(n),s=[];for(let c=i?-o:o;c;c>>=8n)s.push(Number(c&0xffn));s[s.length-1]>=128?s.push(i?128:0):i&&(s[s.length-1]|=128),r.bytes(new Uint8Array(s))},decodeStream:r=>{let n=r.leftBytes;if(n>t)throw new Error(`ScriptNum: number (${n}) bigger than limit=${t}`);if(n===0)return 0n;if(e){let s=r.bytes(n,!0);if(!(s[s.length-1]&127)&&(n<=1||!(s[s.length-2]&128)))throw new Error("Non-minimally encoded ScriptNum")}let i=0,o=0n;for(let s=0;s<n;++s)i=r.byte(),o|=BigInt(i)<<8n*BigInt(s);return i>=128&&(o&=2n**BigInt(n*8)-1n>>1n,o=-o),o}})}function HE(t,e=4,r=!0){if(typeof t=="number")return t;if(Ce(t))try{let n=Qy(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Xe=Wt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(wt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(wt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(wt.OP_1-1+r);continue}}if(typeof r=="number"&&(r=Qy().encode(BigInt(r))),!Ce(r))throw new Error(`Wrong Script OP=${r} (${typeof r})`);let n=r.length;n<wt.PUSHDATA1?t.byte(n):n<=255?(t.byte(wt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(wt.PUSHDATA2),t.bytes(Yy.encode(n))):(t.byte(wt.PUSHDATA4),t.bytes(_e.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(wt.OP_0<r&&r<=wt.PUSHDATA4){let n;if(r<wt.PUSHDATA1)n=r;else if(r===wt.PUSHDATA1)n=mn.decodeStream(t);else if(r===wt.PUSHDATA2)n=Yy.decodeStream(t);else if(r===wt.PUSHDATA4)n=_e.decodeStream(t);else throw new Error("Should be not possible");e.push(t.bytes(n))}else if(r===0)e.push(0);else if(wt.OP_1<=r&&r<=wt.OP_16)e.push(r-(wt.OP_1-1));else{let n=wt[r];if(n===void 0)throw new Error(`Unknown opcode=${r.toString(16)}`);e.push(n)}}return e}}),$E={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},zc=Wt({encodeStream:(t,e)=>{if(typeof e=="number"&&(e=BigInt(e)),0n<=e&&e<=252n)return t.byte(Number(e));for(let[r,n,i,o]of Object.values($E))if(!(i>e||e>o)){t.byte(r);for(let s=0;s<n;s++)t.byte(Number(e>>8n*BigInt(s)&0xffn));return}throw t.err(`VarInt too big: ${e}`)},decodeStream:t=>{let e=t.byte();if(e<=252)return BigInt(e);let[r,n,i]=$E[e],o=0n;for(let s=0;s<n;s++)o|=BigInt(t.byte())<<8n*BigInt(s);if(o<i)throw t.err(`Wrong CompactSize(${8*n})`);return o}}),Dr=gn(zc,Bi.numberBigint),lr=Fe(zc),Yc=Gt(Dr,lr),ol=t=>Gt(zc,t),VE=xt({txid:Fe(32,!0),index:_e,finalScriptSig:lr,sequence:_e}),Ui=xt({amount:Wc,script:lr}),L8=xt({version:Eo,segwitFlag:OE(new Uint8Array([0,1])),inputs:ol(VE),outputs:ol(Ui),witnesses:DE("segwitFlag",Gt("inputs/length",Yc)),lockTime:_e});function P8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Oi=jt(L8,P8),As=xt({version:Eo,inputs:ol(VE),outputs:ol(Ui),lockTime:_e});var t0=jt(Fe(null),t=>vo(t,Et.ecdsa)),sl=jt(Fe(32),t=>vo(t,Et.schnorr)),qE=jt(Fe(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),cl=xt({fingerprint:BE,path:Gt(null,_e)}),WE=xt({hashes:Gt(Dr,Fe(32)),der:cl}),M8=Fe(78),K8=xt({pubKey:sl,leafHash:Fe(32)}),$8=xt({version:mn,internalKey:Fe(32),merklePath:Gt(null,Fe(32))}),Di=jt($8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),H8=Gt(null,xt({depth:mn,version:mn,script:lr})),vt=Fe(null),FE=Fe(20),Cu=Fe(32),al={unsignedTx:[0,!1,As,[0],[0],!1],xpub:[1,M8,cl,[],[0,2],!1],txVersion:[2,!1,_e,[2],[2],!1],fallbackLocktime:[3,!1,_e,[],[2],!1],inputCount:[4,!1,Dr,[2],[2],!1],outputCount:[5,!1,Dr,[2],[2],!1],txModifiable:[6,!1,mn,[],[2],!1],version:[251,!1,_e,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},Lu={nonWitnessUtxo:[0,!1,Oi,[],[0,2],!1],witnessUtxo:[1,!1,Ui,[],[0,2],!1],partialSig:[2,t0,vt,[],[0,2],!1],sighashType:[3,!1,_e,[],[0,2],!1],redeemScript:[4,!1,vt,[],[0,2],!1],witnessScript:[5,!1,vt,[],[0,2],!1],bip32Derivation:[6,t0,cl,[],[0,2],!1],finalScriptSig:[7,!1,vt,[],[0,2],!1],finalScriptWitness:[8,!1,Yc,[],[0,2],!1],porCommitment:[9,!1,vt,[],[0,2],!1],ripemd160:[10,FE,vt,[],[0,2],!1],sha256:[11,Cu,vt,[],[0,2],!1],hash160:[12,FE,vt,[],[0,2],!1],hash256:[13,Cu,vt,[],[0,2],!1],txid:[14,!1,Cu,[2],[2],!0],index:[15,!1,_e,[2],[2],!0],sequence:[16,!1,_e,[],[2],!0],requiredTimeLocktime:[17,!1,_e,[],[2],!1],requiredHeightLocktime:[18,!1,_e,[],[2],!1],tapKeySig:[19,!1,qE,[],[0,2],!1],tapScriptSig:[20,K8,qE,[],[0,2],!1],tapLeafScript:[21,Di,vt,[],[0,2],!1],tapBip32Derivation:[22,Cu,WE,[],[0,2],!1],tapInternalKey:[23,!1,sl,[],[0,2],!1],tapMerkleRoot:[24,!1,Cu,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},GE=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],zE=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Pu={redeemScript:[0,!1,vt,[],[0,2],!1],witnessScript:[1,!1,vt,[],[0,2],!1],bip32Derivation:[2,t0,cl,[],[0,2],!1],amount:[3,!1,IE,[2],[2],!0],script:[4,!1,vt,[2],[2],!0],tapInternalKey:[5,!1,sl,[],[0,2],!1],tapTree:[6,!1,H8,[],[0,2],!1],tapBip32Derivation:[7,sl,WE,[],[0,2],!1],proprietary:[252,vt,vt,[],[0,2],!1]},YE=[],jE=Gt(Wy,xt({key:RE(Dr,xt({type:Dr,key:Fe(null)})),value:Fe(Dr)}));function r0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var hM=xt({type:Dr,key:Fe(null)});function n0(t){let e={};for(let r in t){let[n,i,o]=t[r];e[n]=[r,i,o]}return Wt({encodeStream:(r,n)=>{let i=[];for(let o in t){let s=n[o];if(s===void 0)continue;let[c,a,u]=t[o];if(!a)i.push({key:{type:c,key:Ve},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>Nu(f[0],h[0]));for(let[f,h]of d)i.push({key:{key:f,type:c},value:h})}}if(n.unknown){n.unknown.sort((o,s)=>Nu(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}jE.encodeStream(r,i)},decodeStream:r=>{let n=jE.decodeStream(r),i={},o={};for(let s of n){let c="unknown",a=s.key.key,u=s.value;if(e[s.key.type]){let[d,f,h]=e[s.key.type];if(c=d,!f&&a.length)throw new Error(`PSBT: Non-empty key for ${c} (key=${xe.encode(a)} value=${xe.encode(u)}`);if(a=f?f.decode(a):void 0,u=h.decode(u),!f){if(i[c])throw new Error(`PSBT: Same keys: ${c} (key=${a} value=${u})`);i[c]=u,o[c]=!0;continue}}else a={type:s.key.type,key:s.key.key};if(o[c])throw new Error(`PSBT: Key type with empty key and no key=${c} val=${u}`);i[c]||(i[c]=[]),i[c].push([a,u])}return i}})}var ul=jt(n0(Lu),t=>{if(t.finalScriptWitness&&!t.finalScriptWitness.length)throw new Error("validateInput: empty finalScriptWitness");if(t.partialSig&&!t.partialSig.length)throw new Error("Empty partialSig");if(t.partialSig)for(let[e]of t.partialSig)vo(e,Et.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(e,Et.ecdsa);if(t.requiredTimeLocktime!==void 0&&t.requiredTimeLocktime<5e8)throw new Error(`validateInput: wrong timeLocktime=${t.requiredTimeLocktime}`);if(t.requiredHeightLocktime!==void 0&&(t.requiredHeightLocktime<=0||t.requiredHeightLocktime>=5e8))throw new Error(`validateInput: wrong heighLocktime=${t.requiredHeightLocktime}`);if(t.tapLeafScript)for(let[e,r]of t.tapLeafScript){if((e.version&254)!==r[r.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(r[r.length-1]&1)throw new Error("validateInput: tapLeafScript version has parity bit!")}return t}),dl=jt(n0(Pu),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)vo(e,Et.ecdsa);return t}),JE=jt(n0(al),t=>{if((t.version||0)===0){if(!t.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");for(let r of t.unsignedTx.inputs)if(r.finalScriptSig&&r.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}return t}),V8=xt({magic:Qf(Xf(new Uint8Array([255])),"psbt"),global:JE,inputs:Gt("global/unsignedTx/inputs/length",ul),outputs:Gt(null,dl)}),q8=xt({magic:Qf(Xf(new Uint8Array([255])),"psbt"),global:JE,inputs:Gt("global/inputCount",ul),outputs:Gt("global/outputCount",dl)}),pM=xt({magic:Qf(Xf(new Uint8Array([255])),"psbt"),items:Gt(null,gn(Gt(Wy,NE([UE(Dr),Fe(zc)])),Bi.dict()))});function e0(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=r0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=r0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function i0(t,e,r){let n={};for(let i in r){let o=i;if(o!=="unknown"){if(!e[o])continue;let{allowInc:s,silentIgnore:c}=r0(e[o]);if(!s.includes(t)){if(c)continue;throw new Error(`Failed to serialize in PSBTv${t}: ${o} but versions allows inclusion=${s}`)}}n[o]=r[o]}return n}function ZE(t){let e=t&&t.global&&t.global.version||0;e0(e,al,t.global);for(let s of t.inputs)e0(e,Lu,s);for(let s of t.outputs)e0(e,Pu,s);let r=e?t.global.inputCount:t.global.unsignedTx.inputs.length;if(t.inputs.length<r)throw new Error("Not enough inputs");let n=t.inputs.slice(r);if(n.length>1||n.length&&Object.keys(n[0]).length)throw new Error(`Unexpected inputs left in tx=${n}`);let i=e?t.global.outputCount:t.global.unsignedTx.outputs.length;if(t.outputs.length<i)throw new Error("Not outputs inputs");let o=t.outputs.slice(i);if(o.length>1||o.length&&Object.keys(o[0]).length)throw new Error(`Unexpected outputs left in tx=${o}`);return t}function fl(t,e,r,n,i){let o={...r,...e};for(let s in t){let c=s,[a,u,d]=t[c],f=n&&!n.includes(s);if(e[s]===void 0&&s in e){if(f)throw new Error(`Cannot remove signed field=${s}`);delete o[s]}else if(u){let h=r&&r[s]?r[s]:[],p=e[c];if(p){if(!Array.isArray(p))throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);p=p.map(x=>{if(x.length!==2)throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);return[typeof x[0]=="string"?u.decode(xe.decode(x[0])):x[0],typeof x[1]=="string"?d.decode(xe.decode(x[1])):x[1]]});let g={},y=(x,S,_)=>{if(g[x]===void 0){g[x]=[S,_];return}let A=xe.encode(d.encode(g[x][1])),O=xe.encode(d.encode(_));if(A!==O)throw new Error(`keyMap(${c}): same key=${x} oldVal=${A} newVal=${O}`)};for(let[x,S]of h){let _=xe.encode(u.encode(x));y(_,x,S)}for(let[x,S]of p){let _=xe.encode(u.encode(x));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${x}`);delete g[_]}else y(_,x,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(xe.decode(o[s]));else if(f&&s in e&&r&&r[s]!==void 0&&!st(d.encode(e[s]),d.encode(r[s])))throw new Error(`Cannot change signed field=${s}`)}for(let s in o)if(!t[s]){if(i&&s==="unknown")continue;delete o[s]}return o}var o0=jt(V8,ZE),s0=jt(q8,ZE);var j8={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])||xe.encode(t[1])!=="4e73"))return{type:"p2a",script:Xe.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,xe.decode("4e73")]}};function So(t,e){try{return vo(t,e),!0}catch{return!1}}var W8={encode(t){if(!(t.length!==2||!Ce(t[0])||!So(t[0],Et.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},G8={encode(t){if(!(t.length!==5||t[0]!=="DUP"||t[1]!=="HASH160"||!Ce(t[2]))&&!(t[3]!=="EQUALVERIFY"||t[4]!=="CHECKSIG"))return{type:"pkh",hash:t[2]}},decode:t=>t.type==="pkh"?["DUP","HASH160",t.hash,"EQUALVERIFY","CHECKSIG"]:void 0},z8={encode(t){if(!(t.length!==3||t[0]!=="HASH160"||!Ce(t[1])||t[2]!=="EQUAL"))return{type:"sh",hash:t[1]}},decode:t=>t.type==="sh"?["HASH160",t.hash,"EQUAL"]:void 0},Y8={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===32)return{type:"wsh",hash:t[1]}},decode:t=>t.type==="wsh"?[0,t.hash]:void 0},J8={encode(t){if(!(t.length!==2||t[0]!==0||!Ce(t[1]))&&t[1].length===20)return{type:"wpkh",hash:t[1]}},decode:t=>t.type==="wpkh"?[0,t.hash]:void 0},Z8={encode(t){let e=t.length-1;if(t[e]!=="CHECKMULTISIG")return;let r=t[0],n=t[e-1];if(typeof r!="number"||typeof n!="number")return;let i=t.slice(1,-2);if(n===i.length){for(let o of i)if(!Ce(o))return;return{type:"ms",m:r,pubkeys:i}}},decode:t=>t.type==="ms"?[t.m,...t.pubkeys,t.pubkeys.length,"CHECKMULTISIG"]:void 0},X8={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])))return{type:"tr",pubkey:t[1]}},decode:t=>t.type==="tr"?[1,t.pubkey]:void 0},Q8={encode(t){let e=t.length-1;if(t[e]!=="CHECKSIG")return;let r=[];for(let n=0;n<e;n++){let i=t[n];if(n&1){if(i!=="CHECKSIGVERIFY"||n===e-1)return;continue}if(!Ce(i))return;r.push(i)}return{type:"tr_ns",pubkeys:r}},decode:t=>{if(t.type!=="tr_ns")return;let e=[];for(let r=0;r<t.pubkeys.length-1;r++)e.push(t.pubkeys[r],"CHECKSIGVERIFY");return e.push(t.pubkeys[t.pubkeys.length-1],"CHECKSIG"),e}},eR={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=HE(t[e-1]);if(typeof n=="number"){for(let i=0;i<e-1;i++){let o=t[i];if(i&1){if(o!==(i===1?"CHECKSIG":"CHECKSIGADD"))throw new Error("OutScript.encode/tr_ms: wrong element");continue}if(!Ce(o))throw new Error("OutScript.encode/tr_ms: wrong key element");r.push(o)}return{type:"tr_ms",pubkeys:r,m:n}}},decode:t=>{if(t.type!=="tr_ms")return;let e=[t.pubkeys[0],"CHECKSIG"];for(let r=1;r<t.pubkeys.length;r++)e.push(t.pubkeys[r],"CHECKSIGADD");return e.push(t.m,"NUMEQUAL"),e}},tR={encode(t){return{type:"unknown",script:Xe.encode(t)}},decode:t=>t.type==="unknown"?Xe.decode(t.script):void 0},rR=[j8,W8,G8,z8,Y8,J8,Z8,X8,Q8,eR,tR],nR=gn(Xe,Bi.match(rR)),Qe=jt(nR,t=>{if(t.type==="pk"&&!So(t.pubkey,Et.ecdsa))throw new Error("OutScript/pk: wrong key");if((t.type==="pkh"||t.type==="sh"||t.type==="wpkh")&&(!Ce(t.hash)||t.hash.length!==20))throw new Error(`OutScript/${t.type}: wrong hash`);if(t.type==="wsh"&&(!Ce(t.hash)||t.hash.length!==32))throw new Error("OutScript/wsh: wrong hash");if(t.type==="tr"&&(!Ce(t.pubkey)||!So(t.pubkey,Et.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if((t.type==="ms"||t.type==="tr_ns"||t.type==="tr_ms")&&!Array.isArray(t.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if(t.type==="ms"){let e=t.pubkeys.length;for(let r of t.pubkeys)if(!So(r,Et.ecdsa))throw new Error("OutScript/multisig: wrong pubkey");if(t.m<=0||e>16||t.m>e)throw new Error("OutScript/multisig: invalid params")}if(t.type==="tr_ns"||t.type==="tr_ms"){for(let e of t.pubkeys)if(!So(e,Et.schnorr))throw new Error(`OutScript/${t.type}: wrong pubkey`)}if(t.type==="tr_ms"){let e=t.pubkeys.length;if(t.m<=0||e>999||t.m>e)throw new Error("OutScript/tr_ms: invalid params")}return t});function XE(t,e){if(!st(t.hash,ke(e)))throw new Error("checkScript: wsh wrong witnessScript hash");let r=Qe.decode(e);if(r.type==="tr"||r.type==="tr_ns"||r.type==="tr_ms")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2SH`);if(r.type==="wpkh"||r.type==="sh")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2WSH`)}function l0(t,e,r){if(t){let n=Qe.decode(t);if(n.type==="tr_ns"||n.type==="tr_ms"||n.type==="ms"||n.type=="pk")throw new Error(`checkScript: non-wrapped ${n.type}`);if(n.type==="sh"&&e){if(!st(n.hash,Gc(e)))throw new Error("checkScript: sh wrong redeemScript hash");let i=Qe.decode(e);if(i.type==="tr"||i.type==="tr_ns"||i.type==="tr_ms")throw new Error(`checkScript: P2${i.type} cannot be wrapped in P2SH`);if(i.type==="sh")throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}n.type==="wsh"&&r&&XE(n,r)}if(e){let n=Qe.decode(e);n.type==="wsh"&&r&&XE(n,r)}}var ki=(t,e=Yr)=>{if(!So(t,Et.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=Gc(t);return{type:"pkh",script:Qe.encode({type:"pkh",hash:r}),address:Jr(e).encode({type:"pkh",hash:r}),hash:r}};var Ts=(t,e=Yr)=>{if(!So(t,Et.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=Gc(t);return{type:"wpkh",script:Qe.encode({type:"wpkh",hash:r}),address:Jr(e).encode({type:"wpkh",hash:r}),hash:r}};function iR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=gn(Xe,Bi.match(n)).decode(t);if(c!==void 0){if(typeof c.type!="string"||!c.type.startsWith("tr_"))throw new Error(`P2TR: invalid custom type=${c.type}`);return}}if(r)return}if(!["tr_ns","tr_ms"].includes(i.type))throw new Error(`P2TR: invalid leaf script=${i.type}`);let o=i;if(!r&&o.pubkeys)for(let s of o.pubkeys){if(st(s,il))throw new Error("Unspendable taproot key in leaf script");if(st(s,e))throw new Error("Using P2TR with leaf script with same key as internal key is not supported")}}function ev(t){let e=Array.from(t);for(;e.length>=2;){e.sort((s,c)=>(c.weight||1)-(s.weight||1));let n=e.pop(),i=e.pop(),o=(i?.weight||1)+(n?.weight||1);e.push({weight:o,childs:[i?.childs||i,n?.childs||n]})}let r=e[0];return r?.childs||r}function a0(t,e=[]){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return{...t,path:e};if(t.type!=="branch")throw new Error(`taprootAddPath: wrong type=${t}`);return{...t,path:e,left:a0(t.left,[t.right.hash,...e]),right:a0(t.right,[t.left.hash,...e])}}function u0(t){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return[t];if(t.type!=="branch")throw new Error(`taprootWalkTree: wrong type=${t}`);return[...u0(t.left),...u0(t.right)]}function d0(t,e,r=!1,n){if(!t)throw new Error("taprootHashTree: empty tree");if(Array.isArray(t)&&t.length===1&&(t=t[0]),!Array.isArray(t)){let{leafVersion:a,script:u}=t;if(t.tapLeafScript||t.tapMerkleRoot&&!st(t.tapMerkleRoot,Ve))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?xe.decode(u):u;if(!Ce(d))throw new Error(`checkScript: wrong script type=${d}`);return iR(d,e,r,n),{type:"leaf",version:a,script:d,hash:Mu(d,a)}}if(t.length!==2&&(t=ev(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=d0(t[0],e,r,n),o=d0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return Nu(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Du("TapBranch",s,c)}}var f0=192,Mu=(t,e=f0)=>Du("TapLeaf",new Uint8Array([e]),lr.encode(t));function _s(t,e,r=Yr,n=!1,i){if(!t&&!e)throw new Error("p2tr: should have pubKey or scriptTree (or both)");let o=typeof t=="string"?xe.decode(t):t||il;if(!So(o,Et.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=a0(d0(e,o,n,i)),c=s.hash,[a,u]=ku(o,c),d=u0(s).map(f=>({...f,controlBlock:Di.encode({version:(f.version||f0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Qe.encode({type:"tr",pubkey:a}),address:Jr(r).encode({type:"tr",pubkey:a}),tweakedPubkey:a,tapInternalKey:o,leaves:d,tapLeafScript:d.map(f=>[Di.decode(f.controlBlock),jn(f.script,new Uint8Array([f.version||f0]))]),tapMerkleRoot:c}}else{let s=ku(o,Ve)[0];return{type:"tr",script:Qe.encode({type:"tr",pubkey:s}),address:Jr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var tv=bE(ke);function rv(t,e){if(e.length<2||e.length>40)throw new Error("Witness: invalid length");if(t>16)throw new Error("Witness: invalid version");if(t===0&&!(e.length===20||e.length===32))throw new Error("Witness: invalid length for version")}function c0(t,e,r=Yr){rv(t,e);let n=t===0?Yf:Ss;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function QE(t,e){return tv.encode(jn(Uint8Array.from(e),t))}function Jr(t=Yr){return{encode(e){let{type:r}=e;if(r==="wpkh")return c0(0,e.hash,t);if(r==="wsh")return c0(0,e.hash,t);if(r==="tr")return c0(1,e.pubkey,t);if(r==="pkh")return QE(e.hash,[t.pubKeyHash]);if(r==="sh")return QE(e.hash,[t.scriptHash]);throw new Error(`Unknown address type=${r}`)},decode(e){if(e.length<14||e.length>74)throw new Error("Invalid address length");if(t.bech32&&e.toLowerCase().startsWith(`${t.bech32}1`)){let n;try{if(n=Yf.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=Ss.decode(e),n.words[0]===0)throw new Error(`bech32m: wrong version=${n.words[0]}`)}if(n.prefix!==t.bech32)throw new Error(`wrong bech32 prefix=${n.prefix}`);let[i,...o]=n.words,s=Yf.fromWords(o);if(rv(i,s),i===0&&s.length===32)return{type:"wsh",hash:s};if(i===0&&s.length===20)return{type:"wpkh",hash:s};if(i===1&&s.length===32)return{type:"tr",pubkey:s};throw new Error("Unknown witness program")}let r=tv.decode(e);if(r.length!==21)throw new Error("Invalid base58 address");if(r[0]===t.pubKeyHash)return{type:"pkh",hash:r.slice(1)};if(r[0]===t.scriptHash)return{type:"sh",hash:r.slice(1)};throw new Error(`Invalid address prefix=${r[0]}`)}}}l();var ll=new Uint8Array(32),oR={amount:0xffffffffffffffffn,script:Ve},sR=t=>Math.ceil(t/4),cR=8,aR=2,Is=0,g0=4294967295,uR=Bi.decimal(cR),$u=(t,e)=>t===void 0?e:t;function pl(t){if(Array.isArray(t))return t.map(e=>pl(e));if(Ce(t))return Uint8Array.from(t);if(["number","bigint","boolean","string","undefined"].includes(typeof t))return t;if(t===null)return t;if(typeof t=="object")return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,pl(r)]));throw new Error(`cloneDeep: unknown type=${t} (${typeof t})`)}var je;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.ANYONECANPAY=128]="ANYONECANPAY"})(je||(je={}));var Ao;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.DEFAULT_ANYONECANPAY=128]="DEFAULT_ANYONECANPAY",t[t.ALL_ANYONECANPAY=129]="ALL_ANYONECANPAY",t[t.NONE_ANYONECANPAY=130]="NONE_ANYONECANPAY",t[t.SINGLE_ANYONECANPAY=131]="SINGLE_ANYONECANPAY"})(Ao||(Ao={}));function dR(t,e,r,n=Ve){return st(r,e)&&(t=ME(t,n),e=nl(t)),{privKey:t,pubKey:e}}function Bs(t){if(t.script===void 0||t.amount===void 0)throw new Error("Transaction/output: script and amount required");return{script:t.script,amount:t.amount}}function Ku(t){if(t.txid===void 0||t.index===void 0)throw new Error("Transaction/input: txid and index required");return{txid:t.txid,index:t.index,sequence:$u(t.sequence,g0),finalScriptSig:$u(t.finalScriptSig,Ve)}}function h0(t){for(let e in t){let r=e;GE.includes(r)||delete t[r]}}var p0=xt({txid:Fe(32,!0),index:_e});function fR(t){if(typeof t!="number"||typeof Ao[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function nv(t){let e=t&31;return{isAny:!!(t&je.ANYONECANPAY),isNone:e===je.NONE,isSingle:e===je.SINGLE}}function lR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:$u(t.version,aR),lockTime:$u(t.lockTime,0),PSBTVersion:$u(t.PSBTVersion,0)};if(typeof e.allowUnknowInput<"u"&&(t.allowUnknownInputs=e.allowUnknowInput),typeof e.allowUnknowOutput<"u"&&(t.allowUnknownOutputs=e.allowUnknowOutput),typeof e.lockTime!="number")throw new Error("Transaction lock time should be number");if(_e.encode(e.lockTime),e.PSBTVersion!==0&&e.PSBTVersion!==2)throw new Error(`Unknown PSBT version ${e.PSBTVersion}`);for(let r of["allowUnknownVersion","allowUnknownOutputs","allowUnknownInputs","disableScriptCheck","bip174jsCompat","allowLegacyWitnessUtxo","lowR"]){let n=e[r];if(n!==void 0&&typeof n!="boolean")throw new Error(`Transation options wrong type: ${r}=${n} (${typeof n})`)}if(e.allowUnknownVersion?typeof e.version=="number":![-1,0,1,2,3].includes(e.version))throw new Error(`Unknown version: ${e.version}`);if(e.customScripts!==void 0){let r=e.customScripts;if(!Array.isArray(r))throw new Error(`wrong custom scripts type (expected array): customScripts=${r} (${typeof r})`);for(let n of r){if(typeof n.encode!="function"||typeof n.decode!="function")throw new Error(`wrong script=${n} (${typeof n})`);if(n.finalizeTaproot!==void 0&&typeof n.finalizeTaproot!="function")throw new Error(`wrong script=${n} (${typeof n})`)}}return Object.freeze(e)}function iv(t){if(t.nonWitnessUtxo&&t.index!==void 0){let e=t.nonWitnessUtxo.outputs.length-1;if(t.index>e)throw new Error(`validateInput: index(${t.index}) not in nonWitnessUtxo`);let r=t.nonWitnessUtxo.outputs[t.index];if(t.witnessUtxo&&(!st(t.witnessUtxo.script,r.script)||t.witnessUtxo.amount!==r.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo");if(t.txid){if(t.nonWitnessUtxo.outputs.length-1<t.index)throw new Error("nonWitnessUtxo: incorect output index");let i=Rs.fromRaw(Oi.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=xe.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function hl(t){if(t.nonWitnessUtxo){if(t.index===void 0)throw new Error("Unknown input index");return t.nonWitnessUtxo.outputs[t.index]}else{if(t.witnessUtxo)return t.witnessUtxo;throw new Error("Cannot find previous output info")}}function ov(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=xe.decode(o)),Ce(o)&&(o=Oi.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=xe.decode(s)),s===void 0&&(s=e?.txid);let c={...e,...t,nonWitnessUtxo:o,txid:s};!("nonWitnessUtxo"in t)&&c.nonWitnessUtxo===void 0&&delete c.nonWitnessUtxo,c.sequence===void 0&&(c.sequence=g0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=fl(Lu,c,e,r,i),ul.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&l0(a&&a.script,c.redeemScript,c.witnessScript),c}function y0(t,e=!1){let r="legacy",n=je.ALL,i=hl(t),o=Qe.decode(i.script),s=o.type,c=o,a=[o];if(o.type==="tr")return n=je.DEFAULT,{txType:"taproot",type:"tr",last:o,lastScript:i.script,defaultSighash:n,sighash:t.sighashType||n};{if((o.type==="wpkh"||o.type==="wsh")&&(r="segwit"),o.type==="sh"){if(!t.redeemScript)throw new Error("inputType: sh without redeemScript");let h=Qe.decode(t.redeemScript);(h.type==="wpkh"||h.type==="wsh")&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}if(c.type==="wsh"){if(!t.witnessScript)throw new Error("inputType: wsh without witnessScript");let h=Qe.decode(t.witnessScript);h.type==="wsh"&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}let u=a[a.length-1];if(u.type==="sh"||u.type==="wsh")throw new Error("inputType: sh/wsh cannot be terminal type");let d=Qe.encode(u),f={type:s,txType:r,last:u,lastScript:d,defaultSighash:n,sighash:t.sighashType||n};if(r==="legacy"&&!e&&!t.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");return f}}var Rs=class t{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];let r=this.opts=lR(e);r.lockTime!==Is&&(this.global.fallbackLocktime=r.lockTime),this.global.txVersion=r.version}static fromRaw(e,r={}){let n=Oi.decode(e),i=new t({...r,version:n.version,lockTime:n.lockTime});for(let o of n.outputs)i.addOutput(o);if(i.outputs=n.outputs,i.inputs=n.inputs,n.witnesses)for(let o=0;o<n.witnesses.length;o++)i.inputs[o].finalScriptWitness=n.witnesses[o];return i}static fromPSBT(e,r={}){let n;try{n=o0.decode(e)}catch(f){try{n=s0.decode(e)}catch{throw f}}let i=n.global.version||0;if(i!==0&&i!==2)throw new Error(`Wrong PSBT version=${i}`);let o=n.global.unsignedTx,s=i===0?o?.version:n.global.txVersion,c=i===0?o?.lockTime:n.global.fallbackLocktime,a=new t({...r,version:s,lockTime:c,PSBTVersion:i}),u=i===0?o?.inputs.length:n.global.inputCount;a.inputs=n.inputs.slice(0,u).map((f,h)=>iv({finalScriptSig:Ve,...n.global.unsignedTx?.inputs[h],...f}));let d=i===0?o?.outputs.length:n.global.outputCount;return a.outputs=n.outputs.slice(0,d).map((f,h)=>({...f,...n.global.unsignedTx?.outputs[h]})),a.global={...n.global,txVersion:s},c!==Is&&(a.global.fallbackLocktime=c),a}toPSBT(e=this.opts.PSBTVersion){if(e!==0&&e!==2)throw new Error(`Wrong PSBT version=${e}`);let r=this.inputs.map(o=>iv(i0(e,Lu,o)));for(let o of r)o.partialSig&&!o.partialSig.length&&delete o.partialSig,o.finalScriptSig&&!o.finalScriptSig.length&&delete o.finalScriptSig,o.finalScriptWitness&&!o.finalScriptWitness.length&&delete o.finalScriptWitness;let n=this.outputs.map(o=>i0(e,Pu,o)),i={...this.global};return e===0?(i.unsignedTx=As.decode(As.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Ku).map(o=>({...o,finalScriptSig:Ve})),outputs:this.outputs.map(Bs)})),delete i.fallbackLocktime,delete i.txVersion):(i.version=e,i.txVersion=this.version,i.inputCount=this.inputs.length,i.outputCount=this.outputs.length,i.fallbackLocktime&&i.fallbackLocktime===Is&&delete i.fallbackLocktime),this.opts.bip174jsCompat&&(r.length||r.push({}),n.length||n.push({})),(e===0?o0:s0).encode({global:i,inputs:r,outputs:n})}get lockTime(){let e=Is,r=0,n=Is,i=0;for(let o of this.inputs)o.requiredHeightLocktime&&(e=Math.max(e,o.requiredHeightLocktime),r++),o.requiredTimeLocktime&&(n=Math.max(n,o.requiredTimeLocktime),i++);return r&&r>=i?e:n!==Is?n:this.global.fallbackLocktime||Is}get version(){if(this.global.txVersion===void 0)throw new Error("No global.txVersion");return this.global.txVersion}inputStatus(e){this.checkInputIdx(e);let r=this.inputs[e];return r.finalScriptSig&&r.finalScriptSig.length||r.finalScriptWitness&&r.finalScriptWitness.length?"finalized":r.tapKeySig||r.tapScriptSig&&r.tapScriptSig.length||r.partialSig&&r.partialSig.length?"signed":"unsigned"}inputSighash(e){this.checkInputIdx(e);let r=this.inputs[e].sighashType,n=r===void 0?je.DEFAULT:r,i=n===je.DEFAULT?je.ALL:n&3;return{sigInputs:n&je.ANYONECANPAY,sigOutputs:i}}signStatus(){let e=!0,r=!0,n=[],i=[];for(let o=0;o<this.inputs.length;o++){if(this.inputStatus(o)==="unsigned")continue;let{sigInputs:c,sigOutputs:a}=this.inputSighash(o);if(c===je.ANYONECANPAY?n.push(o):e=!1,a===je.ALL)r=!1;else if(a===je.SINGLE)i.push(o);else if(a!==je.NONE)throw new Error(`Wrong signature hash output type: ${a}`)}return{addInput:e,addOutput:r,inputs:n,outputs:i}}get isFinal(){for(let e=0;e<this.inputs.length;e++)if(this.inputStatus(e)!=="finalized")return!1;return!0}get hasWitnesses(){let e=!1;for(let r of this.inputs)r.finalScriptWitness&&r.finalScriptWitness.length&&(e=!0);return e}get weight(){if(!this.isFinal)throw new Error("Transaction is not finalized");let e=32,r=this.outputs.map(Bs);e+=4*Dr.encode(this.outputs.length).length;for(let n of r)e+=32+4*lr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Dr.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*lr.encode(n.finalScriptSig||Ve).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Yc.encode(n.finalScriptWitness).length);return e}get vsize(){return sR(this.weight)}toBytes(e=!1,r=!1){return Oi.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Ku).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||Ve})),outputs:this.outputs.map(Bs),witnesses:this.inputs.map(n=>n.finalScriptWitness||[]),segwitFlag:r&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return xe.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return xe.encode(Ri(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return xe.encode(Ri(this.toBytes(!0)).reverse())}checkInputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.inputs.length)throw new Error(`Wrong input index=${e}`)}getInput(e){return this.checkInputIdx(e),pl(this.inputs[e])}get inputsLength(){return this.inputs.length}addInput(e,r=!1){if(!r&&!this.signStatus().addInput)throw new Error("Tx has signed inputs, cannot add new one");return this.inputs.push(ov(e,void 0,void 0,this.opts.disableScriptCheck)),this.inputs.length-1}updateInput(e,r,n=!1){this.checkInputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addInput||o.inputs.includes(e))&&(i=zE)}this.inputs[e]=ov(r,this.inputs[e],i,this.opts.disableScriptCheck,this.opts.allowUnknown)}checkOutputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.outputs.length)throw new Error(`Wrong output index=${e}`)}getOutput(e){return this.checkOutputIdx(e),pl(this.outputs[e])}getOutputAddress(e,r=Yr){let n=this.getOutput(e);if(n.script)return Jr(r).encode(Qe.decode(n.script))}get outputsLength(){return this.outputs.length}normalizeOutput(e,r,n){let{amount:i,script:o}=e;if(i===void 0&&(i=r?.amount),typeof i!="bigint")throw new Error(`Wrong amount type, should be of type bigint in sats, but got ${i} of type ${typeof i}`);typeof o=="string"&&(o=xe.decode(o)),o===void 0&&(o=r?.script);let s={...r,...e,amount:i,script:o};if(s.amount===void 0&&delete s.amount,s=fl(Pu,s,r,n,this.opts.allowUnknown),dl.encode(s),s.script&&!this.opts.allowUnknownOutputs&&Qe.decode(s.script).type==="unknown")throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure");return this.opts.disableScriptCheck||l0(s.script,s.redeemScript,s.witnessScript),s}addOutput(e,r=!1){if(!r&&!this.signStatus().addOutput)throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(this.normalizeOutput(e)),this.outputs.length-1}updateOutput(e,r,n=!1){this.checkOutputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addOutput||o.outputs.includes(e))&&(i=YE)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=Yr){return this.addOutput({script:Qe.encode(Jr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=hl(n);if(!i)throw new Error("Empty input amount");e+=i.amount}let r=this.outputs.map(Bs);for(let n of r)e-=n.amount;return e}preimageLegacy(e,r,n){let{isAny:i,isNone:o,isSingle:s}=nv(n);if(e<0||!Number.isSafeInteger(e))throw new Error(`Invalid input idx=${e}`);if(s&&e>=this.outputs.length||e>=this.inputs.length)return _E.encode(1n);r=Xe.encode(Xe.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(Ku).map((d,f)=>({...d,finalScriptSig:f===e?r:Ve}));i?c=[c[e]]:(o||s)&&(c=c.map((d,f)=>({...d,sequence:f===e?d.sequence:0})));let a=this.outputs.map(Bs);o?a=[]:s&&(a=a.slice(0,e).fill(oR).concat([a[e]]));let u=Oi.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Ri(u,Eo.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=nv(n),a=ll,u=ll,d=ll,f=this.inputs.map(Ku),h=this.outputs.map(Bs);o||(a=Ri(...f.map(p0.encode))),!o&&!c&&!s&&(u=Ri(...f.map(g=>_e.encode(g.sequence)))),!c&&!s?d=Ri(...h.map(Ui.encode)):c&&e<h.length&&(d=Ri(Ui.encode(h[e])));let p=f[e];return Ri(Eo.encode(this.version),a,u,Fe(32,!0).encode(p.txid),_e.encode(p.index),lr.encode(r),Wc.encode(i),_e.encode(p.sequence),d,_e.encode(this.lockTime),_e.encode(n))}preimageWitnessV1(e,r,n,i,o=-1,s,c=192,a){if(!Array.isArray(i)||this.inputs.length!==i.length)throw new Error(`Invalid amounts array=${i}`);if(!Array.isArray(r)||this.inputs.length!==r.length)throw new Error(`Invalid prevOutScript array=${r}`);let u=[mn.encode(0),mn.encode(n),Eo.encode(this.version),_e.encode(this.lockTime)],d=n===je.DEFAULT?je.ALL:n&3,f=n&je.ANYONECANPAY,h=this.inputs.map(Ku),p=this.outputs.map(Bs);f!==je.ANYONECANPAY&&u.push(...[h.map(p0.encode),i.map(Wc.encode),r.map(lr.encode),h.map(y=>_e.encode(y.sequence))].map(y=>ke(jn(...y)))),d===je.ALL&&u.push(ke(jn(...p.map(Ui.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===je.ANYONECANPAY){let y=h[e];u.push(p0.encode(y),Wc.encode(i[e]),lr.encode(r[e]),_e.encode(y.sequence))}else u.push(_e.encode(e));return g&1&&u.push(ke(lr.encode(a||Ve))),d===je.SINGLE&&u.push(e<p.length?ke(Ui.encode(p[e])):ll),s&&u.push(Mu(s,c),mn.encode(0),Eo.encode(o)),Du("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=y0(o,this.opts.allowLegacyWitnessUtxo);if(!Ce(e)){if(!o.bip32Derivation||!o.bip32Derivation.length)throw new Error("bip32Derivation: empty");let d=o.bip32Derivation.filter(h=>h[1].fingerprint==e.fingerprint).map(([h,{path:p}])=>{let g=e;for(let y of p)g=g.deriveChild(y);if(!st(g.publicKey,h))throw new Error("bip32Derivation: wrong pubKey");if(!g.privateKey)throw new Error("bip32Derivation: no privateKey");return g});if(!d.length)throw new Error(`bip32Derivation: no items with fingerprint=${e.fingerprint}`);let f=!1;for(let h of d)this.signIdx(h.privateKey,r)&&(f=!0);return f}n?n.forEach(fR):n=[s.defaultSighash];let c=s.sighash;if(!n.includes(c))throw new Error(`Input with not allowed sigHash=${c}. Allowed: ${n.join(", ")}`);let{sigOutputs:a}=this.inputSighash(r);if(a===je.SINGLE&&r>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${r}`);let u=hl(o);if(s.txType==="taproot"){let d=this.inputs.map(hl),f=d.map(x=>x.script),h=d.map(x=>x.amount),p=!1,g=nl(e),y=o.tapMerkleRoot||Ve;if(o.tapInternalKey){let{pubKey:x,privKey:S}=dR(e,g,o.tapInternalKey,y),[_,A]=ku(o.tapInternalKey,y);if(st(_,x)){let O=this.preimageWitnessV1(r,f,c,h),T=jn(Zy(O,S,i),c!==je.DEFAULT?new Uint8Array([c]):Ve);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[x,S]of o.tapLeafScript){let _=S.subarray(0,-1),A=Xe.decode(_),O=S[S.length-1],T=Mu(_,O);if(A.findIndex($=>Ce($)&&st($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,_,O),j=jn(Zy(q,e,i),c!==je.DEFAULT?new Uint8Array([c]):Ve);this.updateInput(r,{tapScriptSig:[[{pubKey:g,leafHash:T},j]]},!0),p=!0}}if(!p)throw new Error("No taproot scripts signed");return!0}else{let d=Jy(e),f=!1,h=Gc(d);for(let y of Xe.decode(s.lastScript))Ce(y)&&(st(y,d)||st(y,h))&&(f=!0);if(!f)throw new Error(`Input script doesn't have pubKey: ${s.lastScript}`);let p;if(s.txType==="legacy")p=this.preimageLegacy(r,s.lastScript,c);else if(s.txType==="segwit"){let y=s.lastScript;s.last.type==="wpkh"&&(y=Qe.encode({type:"pkh",hash:s.last.hash})),p=this.preimageWitnessV0(r,y,c,u.amount)}else throw new Error(`Transaction/sign: unknown tx type: ${s.txType}`);let g=LE(p,e,this.opts.lowR);this.updateInput(r,{partialSig:[[d,jn(g,new Uint8Array([c]))]]},!0)}return!0}sign(e,r,n){let i=0;for(let o=0;o<this.inputs.length;o++)try{this.signIdx(e,o,r,n)&&i++}catch{}if(!i)throw new Error("No inputs signed");return i}finalizeIdx(e){if(this.checkInputIdx(e),this.fee<0n)throw new Error("Outputs spends more than inputs amount");let r=this.inputs[e],n=y0(r,this.opts.allowLegacyWitnessUtxo);if(n.txType==="taproot"){if(r.tapKeySig)r.finalScriptWitness=[r.tapKeySig];else if(r.tapLeafScript&&r.tapScriptSig){let a=r.tapLeafScript.sort((u,d)=>Di.encode(u[0]).length-Di.encode(d[0]).length);for(let[u,d]of a){let f=d.slice(0,-1),h=d[d.length-1],p=Qe.decode(f),g=Mu(f,h),y=r.tapScriptSig.filter(S=>st(S[0].leafHash,g)),x=[];if(p.type==="tr_ms"){let S=p.m,_=p.pubkeys,A=0;for(let O of _){let T=y.findIndex(M=>st(M[0].pubKey,O));if(A===S||T===-1){x.push(Ve);continue}x.push(y[T][1]),A++}if(A!==S)continue}else if(p.type==="tr_ns"){for(let S of p.pubkeys){let _=y.findIndex(A=>st(A[0].pubKey,S));_!==-1&&x.push(y[_][1])}if(x.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Xe.decode(f);if(x=y.map(([{pubKey:_},A])=>{let O=S.findIndex(T=>Ce(T)&&st(T,_));if(O===-1)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:A,pos:O}}).sort((_,A)=>_.pos-A.pos).map(_=>_.signature),!x.length)continue}else{let S=this.opts.customScripts;if(S)for(let _ of S){if(!_.finalizeTaproot)continue;let A=Xe.decode(f),O=_.encode(A);if(O===void 0)continue;let T=_.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(Di.encode(u)),r.finalScriptSig=Ve,h0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=x.reverse().concat([f,Di.encode(u)]);break}if(!r.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}else throw new Error("finalize/taproot: unknown input");r.finalScriptSig=Ve,h0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=Ve,o=[];if(n.last.type==="ms"){let a=n.last.m,u=n.last.pubkeys,d=[];for(let f of u){let h=r.partialSig.find(p=>st(f,p[0]));h&&d.push(h[1])}if(d=d.slice(0,a),d.length!==a)throw new Error(`Multisig: wrong signatures count, m=${a} n=${u.length} signatures=${d.length}`);i=Xe.encode([0,...d])}else if(n.last.type==="pk")i=Xe.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Xe.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=Ve,o=[r.partialSig[0][1],r.partialSig[0][0]];else if(n.last.type==="unknown"&&!this.opts.allowUnknownInputs)throw new Error("Unknown inputs not allowed");let s,c;if(n.type.includes("wsh-")&&(i.length&&n.lastScript.length&&(o=Xe.decode(i).map(a=>{if(a===0)return Ve;if(Ce(a))return a;throw new Error(`Wrong witness op=${a}`)})),o=o.concat(n.lastScript)),n.txType==="segwit"&&(c=o),n.type.startsWith("sh-wsh-")?s=Xe.encode([Xe.encode([0,ke(n.lastScript)])]):n.type.startsWith("sh-")?s=Xe.encode([...Xe.decode(i),n.lastScript]):n.type.startsWith("wsh-")||n.txType!=="segwit"&&(s=i),!s&&!c)throw new Error("Unknown error finalizing input");s&&(r.finalScriptSig=s),c&&(r.finalScriptWitness=c),h0(r)}finalize(){for(let e=0;e<this.inputs.length;e++)this.finalizeIdx(e)}extract(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");if(this.fee<0n)throw new Error("Outputs spends more than inputs amount");return this.toBytes(!0,!0)}combine(e){for(let i of["PSBTVersion","version","lockTime"])if(this.opts[i]!==e.opts[i])throw new Error(`Transaction/combine: different ${i} this=${this.opts[i]} other=${e.opts[i]}`);for(let i of["inputs","outputs"])if(this[i].length!==e[i].length)throw new Error(`Transaction/combine: different ${i} length this=${this[i].length} other=${e[i].length}`);let r=this.global.unsignedTx?As.encode(this.global.unsignedTx):Ve,n=e.global.unsignedTx?As.encode(e.global.unsignedTx):Ve;if(!st(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=fl(al,this.global,e.global,void 0,this.opts.allowUnknown);for(let i=0;i<this.inputs.length;i++)this.updateInput(i,e.inputs[i],!0);for(let i=0;i<this.outputs.length;i++)this.updateOutput(i,e.outputs[i],!0);return this}clone(){return t.fromPSBT(this.toPSBT(this.opts.PSBTVersion),this.opts)}};l();l();l();l();l();function sv(t,e){var r="",n=e&&e.include,i=e&&e.exclude;i&&typeof i=="string"&&(i=[i]),n&&n.sort();var o=new WeakMap,s=e&&e.allowCircular,c=e&&e.filterUndefined,a=e&&e.undefinedInArrayToNull;return u(t,""),r;function u(d,f){if(d===null||typeof d!="object"||d.toJSON!=null)r+=JSON.stringify(d);else if(Array.isArray(d)){var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="[";var p=!1;d.forEach(function(S,_){p&&(r+=","),p=!0,a&&S===void 0&&(S=null),u(S,f+"["+_+"]")}),r+="]"}else{var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="{";var g=!1,y=function(_){i&&i.includes(_)||(g&&(r+=","),g=!0,r+=JSON.stringify(_),r+=":",u(d[_],f+"."+_))};if(f===""&&n)n.forEach(function(_){d.hasOwnProperty(_)&&y(_)});else{var x=Object.keys(d);c&&(x=x.filter(function(_){return d[_]!==void 0})),x.sort(),x.forEach(function(_){y(_)})}r+="}"}}}function cv(t,e){return sv(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var m0;(function(t){t.INVALID_DID="INVALID_DID",t.METHOD_NOT_SUPPORTED="METHOD_NOT_SUPPORTED",t.INTERNAL_ERROR="INTERNAL_ERROR",t.INVALID_DID_DOCUMENT="INVALID_DID_DOCUMENT",t.INVALID_DID_UPDATE="INVALID_DID_UPDATE",t.INVALID_DID_DOCUMENT_LENGTH="INVALID_DID_DOCUMENT_LENGTH",t.INVALID_DID_URL="INVALID_DID_URL",t.INVALID_PREVIOUS_DID_PROOF="INVALID_PREVIOUS_DID_PROOF",t.INVALID_PUBLIC_KEY="INVALID_PUBLIC_KEY",t.INVALID_PUBLIC_KEY_MULTIBASE="INVALID_PUBLIC_KEY_MULTIBASE",t.INVALID_PUBLIC_KEY_LENGTH="INVALID_PUBLIC_KEY_LENGTH",t.INVALID_PUBLIC_KEY_TYPE="INVALID_PUBLIC_KEY_TYPE",t.INVALID_SIGNATURE="INVALID_SIGNATURE",t.NOT_FOUND="NOT_FOUND",t.REPRESENTATION_NOT_SUPPORTED="REPRESENTATION_NOT_SUPPORTED",t.UNSUPPORTED_PUBLIC_KEY_TYPE="UNSUPPORTED_PUBLIC_KEY_TYPE",t.PROOF_VERIFICATION_ERROR="PROOF_VERIFICATION_ERROR",t.PROOF_GENERATION_ERROR="PROOF_GENERATION_ERROR",t.PROOF_SERIALIZATION_ERROR="PROOF_SERIALIZATION_ERROR",t.PROOF_PARSING_ERROR="PROOF_PARSING_ERROR",t.VERIFICATION_METHOD_ERROR="VERIFICATION_METHOD_ERROR",t.LATE_PUBLISHING_ERROR="LATE_PUBLISHING_ERROR",t.INVALID_SIDECAR_DATA="INVALID_SIDECAR_DATA",t.MISSING_UPDATE_DATA="MISSING_UPDATE_DATA",t.INVALID_UPDATE="INVALID_UPDATE",t.INVALID_DOMAIN_ERROR="INVALID_DOMAIN_ERROR",t.MISSING_RESOLUTION_OPTIONS="MISSING_RESOLUTION_OPTIONS",t.INVALID_OPTIONS="INVALID_OPTIONS"})(m0||(m0={}));var{INVALID_DID:Dt,METHOD_NOT_SUPPORTED:yl,INTERNAL_ERROR:av,INVALID_DID_DOCUMENT:De,INVALID_DID_UPDATE:Ie,INVALID_DID_URL:nK,INVALID_PREVIOUS_DID_PROOF:iK,INVALID_PUBLIC_KEY:oK,INVALID_PUBLIC_KEY_MULTIBASE:sK,INVALID_PUBLIC_KEY_LENGTH:cK,INVALID_PUBLIC_KEY_TYPE:aK,INVALID_SIGNATURE:uK,PROOF_VERIFICATION_ERROR:Ni,PROOF_GENERATION_ERROR:_o,PROOF_SERIALIZATION_ERROR:uv,PROOF_PARSING_ERROR:dK,VERIFICATION_METHOD_ERROR:gl,LATE_PUBLISHING_ERROR:ml,INVALID_SIDECAR_DATA:fK,MISSING_UPDATE_DATA:lK,MISSING_RESOLUTION_OPTIONS:hK,INVALID_OPTIONS:dv}=m0,zt=class t extends Error{name="DidMethodError";type="DidMethodError";data;constructor(e,r={}){super(e),this.type=r.type??this.type,this.name=r.name??this.name,this.data=r.data,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,t)}},we=class extends zt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var lt=class extends zt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},St=class extends zt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},Le=class extends zt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var qe=class extends zt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},To=class extends zt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},wn=class extends zt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},bn=class extends zt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},Wn=class extends zt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},Us=class extends zt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},xn=class extends zt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var Jc=class extends zt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var hR=new Set(["jcs"]),pR=new Set(["hex","base58","base64urlnopad"]);function w0(t){let e=t.toLowerCase();if(!hR.has(e))throw new Jc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function b0(t){let e=t.toLowerCase();if(!pR.has(e))throw new Jc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function rr(t,e="jcs"){switch(w0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return cv(n)}default:throw new Jc(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function Io(t){return ke(t)}function Zr(t,e="base64urlnopad"){switch(b0(e)){case"hex":return xe.encode(t);case"base58":return zf.encode(t);case"base64urlnopad":return qc.encode(t)}}function Os(t,e="base64urlnopad"){switch(b0(e)){case"hex":return xe.decode(t);case"base58":return zf.decode(t);case"base64urlnopad":return qc.decode(t)}}function Bo(t,e="jcs"){return Io(rr(t,w0(e)))}function Gn(t,e){let r=w0(e?.algorithm??"jcs"),n=b0(e?.encoding??"base64urlnopad");return Zr(Io(rr(t,r)),n)}l();l();var x0={};Af(x0,{JsonPatchError:()=>ct,_areEquals:()=>qu,applyOperation:()=>Ds,applyPatch:()=>Al,applyReducer:()=>bR,deepClone:()=>mR,getValueByPointer:()=>vl,validate:()=>lv,validator:()=>Sl});l();l();var yR=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)i.hasOwnProperty(o)&&(n[o]=i[o])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),gR=Object.prototype.hasOwnProperty;function bl(t,e){return gR.call(t,e)}function xl(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var i in t)bl(t,i)&&n.push(i);return n}function Mt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function El(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function zn(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Hu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function wl(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(wl(t[e]))return!0}else if(typeof t=="object"){for(var n=xl(t),i=n.length,o=0;o<i;o++)if(wl(t[n[o]]))return!0}}return!1}function fv(t,e){var r=[t];for(var n in e){var i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(n+": "+i)}return r.join(`
3
+ `)}var Vu=function(t){yR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,fv(r,{name:n,index:i,operation:o,tree:s}))||this;return a.name=n,a.index=i,a.operation=o,a.tree=s,Object.setPrototypeOf(a,c.prototype),a.message=fv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var ct=Vu,mR=Mt,Zc={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=vl(r,this.path);n&&(n=Mt(n));var i=Ds(r,{op:"remove",path:this.from}).removed;return Ds(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=vl(r,this.from);return Ds(r,{op:"add",path:this.path,value:Mt(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:qu(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},wR={add:function(t,e,r){return El(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Zc.move,copy:Zc.copy,test:Zc.test,_get:Zc._get};function vl(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ds(t,r),r.value}function Ds(t,e,r,n,i,o){if(r===void 0&&(r=!1),n===void 0&&(n=!0),i===void 0&&(i=!0),o===void 0&&(o=0),r&&(typeof r=="function"?r(e,0,t,e.path):Sl(e,0)),e.path===""){var s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=vl(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=qu(t,e.value),s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(r)throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{n||(t=Mt(t));var c=e.path||"",a=c.split("/"),u=t,d=1,f=a.length,h=void 0,p=void 0,g=void 0;for(typeof r=="function"?g=r:g=Sl;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=Hu(p)),i&&(p=="__proto__"||p=="prototype"&&d>0&&a[d-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&h===void 0&&(u[p]===void 0?h=a.slice(0,d).join("/"):d==f-1&&(h=e.path),h!==void 0&&g(e,0,t,h)),d++,Array.isArray(u)){if(p==="-")p=u.length;else{if(r&&!El(p))throw new ct("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,t);El(p)&&(p=~~p)}if(d>=f){if(r&&e.op==="add"&&p>u.length)throw new ct("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,t);var s=wR[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(d>=f){var s=Zc[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new ct("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function Al(t,e,r,n,i){if(n===void 0&&(n=!0),i===void 0&&(i=!0),r&&!Array.isArray(e))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Mt(t));for(var o=new Array(e.length),s=0,c=e.length;s<c;s++)o[s]=Ds(t,e[s],r,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function bR(t,e,r){var n=Ds(t,e);if(n.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Sl(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ct("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Zc[t.op]){if(typeof t.path!="string")throw new ct("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ct('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ct("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&wl(t.value))throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var i=t.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new ct("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ct("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var s={op:"_get",path:t.from,value:void 0},c=lv([s],r);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new ct("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function lv(t,e,r){try{if(!Array.isArray(t))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Al(Mt(e),Mt(t),r||!0);else{r=r||Sl;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof ct)return i;throw i}}function qu(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),i,o,s;if(r&&n){if(o=t.length,o!=e.length)return!1;for(i=o;i--!==0;)if(!qu(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(o=c.length,o!==Object.keys(e).length)return!1;for(i=o;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=o;i--!==0;)if(s=c[i],!qu(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var A0={};Af(A0,{compare:()=>IR,generate:()=>E0,observe:()=>_R,unobserve:()=>TR});l();var v0=new WeakMap,xR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),ER=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function vR(t){return v0.get(t)}function SR(t,e){return t.observers.get(e)}function AR(t,e){t.observers.delete(e.callback)}function TR(t,e){e.unobserve()}function _R(t,e){var r=[],n,i=vR(t);if(!i)i=new xR(t),v0.set(t,i);else{var o=SR(i,e);n=o&&o.observer}if(n)return n;if(n={},i.value=Mt(t),e){n.callback=e,n.next=null;var s=function(){E0(n)},c=function(){clearTimeout(n.next),n.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return n.patches=r,n.object=t,n.unobserve=function(){E0(n),clearTimeout(n.next),AR(i,n),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new ER(e,n)),n}function E0(t,e){e===void 0&&(e=!1);var r=v0.get(t.object);S0(r.value,t.object,t.patches,"",e),t.patches.length&&Al(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function S0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=xl(e),s=xl(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(bl(e,d)&&!(e[d]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var h=e[d];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?S0(f,h,r,n+"/"+zn(d),i):f!==h&&(c=!0,i&&r.push({op:"test",path:n+"/"+zn(d),value:Mt(f)}),r.push({op:"replace",path:n+"/"+zn(d),value:Mt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+zn(d),value:Mt(f)}),r.push({op:"remove",path:n+"/"+zn(d)}),a=!0):(i&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),c=!0)}if(!(!a&&o.length==s.length))for(var u=0;u<o.length;u++){var d=o[u];!bl(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+zn(d),value:Mt(e[d])})}}}function IR(t,e,r){r===void 0&&(r=!1);var n=[];return S0(t,e,n,"",r),n}var hv=Object.assign({},x0,A0,{JsonPatchError:Vu,deepClone:Mt,escapePathComponent:zn,unescapePathComponent:Hu});var{applyPatch:BR,compare:RR,deepClone:UR}=hv,OR=new Set(["__proto__","constructor","prototype"]);function pv(t){return t.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")).find(e=>OR.has(e))}var Xc=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??UR,s=i?e:o(e),c=this.validateOperations(r);if(c)throw new we("Invalid JSON Patch operations","JSON_PATCH_APPLY_ERROR",{error:c});try{let a=BR(s,r,!1,i);if(a.newDocument===void 0)throw new we("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{result:a});return a.newDocument}catch(a){throw new we("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{error:a})}}static diff(e,r,n=""){let i=RR(e??{},r??{});if(!n)return i;let o=n.endsWith("/")?n.slice(0,-1):n;return i.map(s=>({...s,path:this.joinPointer(o,s.path)}))}static joinPointer(e,r){if(!e)return r;let n=e.startsWith("/")?e:`/${e}`;return`${this.escapeSegmentPath(n)}${r}`}static escapeSegmentPath(e){return e.split("/").map((r,n)=>n===0?r:r.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}static validateOperations(e){if(!Array.isArray(e))return new we("Operations must be an array","JSON_PATCH_VALIDATION_ERROR");for(let r of e){if(!r||typeof r!="object")return new we("Operation must be an object","JSON_PATCH_VALIDATION_ERROR");if(typeof r.op!="string")return new we("Operation.op must be a string","JSON_PATCH_VALIDATION_ERROR");if(typeof r.path!="string")return new we("Operation.path must be a string","JSON_PATCH_VALIDATION_ERROR");let n=pv(r.path);if(n)return new we(`Operation.path traverses prototype machinery: ${n}`,"JSON_PATCH_VALIDATION_ERROR");if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")return new we(`Operation.from must be a string for op=${r.op}`,"JSON_PATCH_VALIDATION_ERROR");if(typeof r.from=="string"){let i=pv(r.from);if(i)return new we(`Operation.from traverses prototype machinery: ${i}`,"JSON_PATCH_VALIDATION_ERROR")}}return null}};l();var Xr;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(Xr||(Xr={}));var Tl;(function(t){t.k="k",t.x="x"})(Tl||(Tl={}));var Qc;(function(t){t[t.bitcoin=0]="bitcoin",t[t.signet=1]="signet",t[t.regtest=2]="regtest",t[t.testnet3=3]="testnet3",t[t.testnet4=4]="testnet4",t[t.mutinynet=5]="mutinynet"})(Qc||(Qc={}));l();var Ro=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new we(`Invalid date: ${e}`,"INVALID_DATE");return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toUnixSeconds(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new we(`Invalid date: ${e}`,"INVALID_DATE");return Math.floor(e.getTime()/1e3)}static dateStringToTimestamp(e){let r=new Date(e);return Number.isNaN(r.getTime())?new Date(0):r}static blocktimeToTimestamp(e){return new Date(e*1e3)}static isValidXsdDateTime(e){if(!e)return!1;let r=/^-?(\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,n=e.match(r);if(!n)return!1;let[,i,o,s,c,a,u,,d]=n,f=parseInt(i,10),h=parseInt(o,10),p=parseInt(s,10),g=parseInt(c,10),y=parseInt(a,10),x=parseInt(u,10);if(f===0||h<1||h>12)return!1;let S=[31,28,31,30,31,30,31,31,30,31,30,31],_=f%4===0&&f%100!==0||f%400===0,A=h===2&&_?29:S[h-1];if(p<1||p>A)return!1;if(g===24){if(y!==0||x!==0)return!1}else if(g>23)return!1;if(y>59||x>59)return!1;if(d&&d!=="Z"){let O=d.match(/^[+-](\d{2}):(\d{2})$/);if(O){let T=parseInt(O[1],10),M=parseInt(O[2],10);if(T>14||T===14&&M!==0||M>59)return!1}}return!0}};l();function T0(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}var ks=class{static isObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}static isParsable(e){if(typeof e!="string")return!1;try{return JSON.parse(e),!0}catch{return!1}}static isUnprototyped(e){return e===null||typeof e!="object"?!1:Object.getPrototypeOf(e)===null}static normalize(e){return this.cloneInternal(e,{stripPrototypes:!0})}static copy(e){return{...e}}static clone(e){return typeof structuredClone=="function"?structuredClone(e):this.cloneInternal(e)}static cloneReplace(e,r,n){return this.cloneInternal(e,{transform:i=>typeof i=="string"?i.replace(r,n):i})}static deepEqual(e,r,n=new WeakMap,i=0){if(i>1024)throw new we("Maximum comparison depth exceeded","MAX_DEPTH_EXCEEDED");if(Object.is(e,r))return!0;if(typeof e!=typeof r||e===null||r===null||typeof e!="object")return!1;if(n.get(e)===r)return!0;if(n.set(e,r),ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){let c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(c.byteLength!==a.byteLength)return!1;for(let u=0;u<c.byteLength;u++)if(c[u]!==a[u])return!1;return!0}if(e instanceof Date&&r instanceof Date)return e.getTime()===r.getTime();if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(let c of e){let a=!1;for(let u of r)if(this.deepEqual(c,u,n,i+1)){a=!0;break}if(!a)return!1}return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(let[c,a]of e){let u=!1;if(r.has(c))u=this.deepEqual(a,r.get(c),n,i+1);else for(let[d,f]of r)if(this.deepEqual(c,d,n,i+1)&&this.deepEqual(a,f,n,i+1)){u=!0;break}if(!u)return!1}return!0}if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return!1;for(let c=0;c<e.length;c++)if(!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}let o=Object.keys(e),s=Object.keys(r);if(o.length!==s.length)return!1;for(let c of o)if(!Object.prototype.hasOwnProperty.call(r,c)||!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}static deleteKeys(e,r){let n=new Set(r.map(o=>typeof o=="number"?o.toString():o)),i=o=>{if(Array.isArray(o))return o.map(s=>i(s));if(o&&typeof o=="object"){let s={};for(let c of Object.keys(o))n.has(c)||T0(s,c,i(o[c]));return s}return o};return i(e)}static sanitize(e){let r=n=>{if(Array.isArray(n))return n.filter(i=>i!==void 0).map(i=>r(i));if(n&&typeof n=="object"){let i={};for(let[o,s]of Object.entries(n)){let c=r(s);c!==void 0&&T0(i,o,c)}return i}return n};return r(e)}static cloneInternal(e,r={},n=new WeakMap,i=0){if(i>1024)throw new we("Maximum clone depth exceeded","MAX_DEPTH_EXCEEDED");let o=r.transform?r.transform(e):e;if(o!==e||typeof e!="object"||e===null)return o;if(n.has(e))throw new we("Cannot clone circular structure","CIRCULAR_STRUCTURE");if(Array.isArray(e)){let c=[];n.set(e,c);for(let a of e)c.push(this.cloneInternal(a,r,n,i+1));return c}if(ArrayBuffer.isView(e)){if(e instanceof DataView)return new DataView(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(typeof e.slice=="function")return e.slice()}if(e instanceof Date)return new Date(e.getTime());let s=r.stripPrototypes?{}:Object.create(Object.getPrototypeOf(e));n.set(e,s);for(let c of Object.keys(e))T0(s,c,this.cloneInternal(e[c],r,n,i+1));return s}};l();var nr=class extends we{constructor(e,r="BeaconError",n){super(e,r,n)}},yv=class extends we{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},gv=class extends we{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},mv=class extends we{constructor(e,r="CASBeaconError",n){super(e,r,n)}},Fu=class extends we{constructor(e,r="SMTBeaconError",n){super(e,r,n)}};l();l();l();l();l();l();l();l();l();l();l();l();l();l();l();var HR={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Uo(t){switch(t){case"bitcoin":return Yr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return Xy;case"regtest":return HR;default:throw new Error(`Unknown network "${t}"`)}}l();var ju=class{satsPerVbyte;constructor(e=5){if(e<0||!Number.isFinite(e))throw new Error(`Invalid satsPerVbyte: ${e}`);this.satsPerVbyte=e}async estimateFee(e){if(e<0||!Number.isFinite(e))throw new Error(`Invalid vsize: ${e}`);return BigInt(Math.ceil(e*this.satsPerVbyte))}};l();var I0="0000000000000000000000000000000000000000000000000000000000000000",B0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var R0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(R0||(R0={}));var U0=new ju(5);var FR=160,jR=155,WR=240,GR={p2pkh:WR,p2wpkh:jR,p2tr:FR},bv={p2pkh:34,p2wpkh:31,p2tr:43},xv={p2pkh:546,p2wpkh:294,p2tr:330};function Ev(t,e){return GR[t]-bv[t]+bv[e]}function vv(t,e){let r=Jr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new nr(`Unsupported singleton beacon address type "${r.type}". Expected P2PKH, P2WPKH, or P2TR (taproot key-path).`,"UNSUPPORTED_BEACON_ADDRESS_TYPE",{address:t,kind:r.type})}function zR(t,e,r){return t==="p2pkh"?ki(e,r).address:t==="p2wpkh"?Ts(e,r).address:_s(e.slice(1,33),void 0,r).address}function Sv(t,e,r){if(!r||r===t)return t;try{Jr(e).decode(r)}catch{throw new nr(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function Av(t,e){try{return vv(t,e)}catch{return"p2tr"}}function Tv(t){return Xe.encode(["RETURN",t])}var O0=546;function YR(t){return t.status.confirmed===!0}function JR(t,e){if(t.status.block_height!==e.status.block_height)return t.status.block_height-e.status.block_height;let r=t.txid.localeCompare(e.txid);return r!==0?r:t.vout-e.vout}function ZR(t,e){if(!t.length)throw new nr("No UTXOs found, please fund address!","UNFUNDED_BEACON_ADDRESS",{address:e});let r=t.filter(YR),n=r.filter(i=>i.value>O0);if(!n.length){let i=r.length===0?`all ${t.length} UTXO(s) are unconfirmed`:`all ${r.length} confirmed UTXO(s) are at or below the ${O0}-sat dust limit`;throw new nr(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:O0})}return[...n].sort(JR)[0]}async function _v(t,e){let r=await e.rest.address.getUtxos(t),n=ZR(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:_r(i)}}async function P$(t){let e=t.feeEstimator??U0,{utxo:r,prevTxBytes:n}=await _v(t.beaconAddress,t.bitcoin),i=Sv(t.beaconAddress,t.network,t.changeAddress),o=Qe.encode(Jr(t.network).decode(t.beaconAddress)),s=Av(i,t.network),c=await e.estimateFee(Ev("p2tr",s));if(BigInt(r.value)<=c)throw new nr(`UTXO value (${r.value}) insufficient to cover fee (${c}).`,"INSUFFICIENT_FUNDS",{address:t.beaconAddress,valueSats:r.value,feeSats:c});let a=new Rs({allowUnknownOutputs:!0});a.addInput({txid:r.txid,index:r.vout,nonWitnessUtxo:n,witnessUtxo:{amount:BigInt(r.value),script:o},tapInternalKey:t.internalPubkey});let u=BigInt(r.value)-c;return u>=BigInt(xv[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:Tv(t.signalBytes),amount:0n}),{tx:a,prevOutScripts:[o],prevOutValues:[BigInt(r.value)],beaconAddress:t.beaconAddress,changeAddress:i,utxo:r,feeSats:c,scriptKind:"p2tr"}}async function XR(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=Ao.ALL,d=t.preimageLegacy(e,i,u),f=n.sign(d,"ecdsa"),h=ft(f,new Uint8Array([u]));return t.updateInput(e,{partialSig:[[s,h]]},!0),t.finalize(),t.hex}if(r==="p2wpkh"){let u=Qe.decode(i);if(u.type!=="wpkh")throw new nr(`Expected P2WPKH prev-output script, got "${u.type}".`,"PREVOUT_SCRIPT_MISMATCH",{kind:r,observedScriptType:u.type});let d=Qe.encode({type:"pkh",hash:u.hash}),f=Ao.ALL,h=t.preimageWitnessV0(e,d,f,o),p=n.sign(h,"ecdsa"),g=ft(p,new Uint8Array([f]));return t.updateInput(e,{partialSig:[[s,g]]},!0),t.finalize(),t.hex}let c=t.preimageWitnessV1(e,[i],Ao.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Oo=class{service;did;constructor(e,r){this.service=e,this.did=r}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??U0,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await _v(s,n),u=await this.buildSinglePartyTx({signalBytes:e,beaconAddress:s,utxo:c,prevTxBytes:a,signer:r,bitcoin:n,feeEstimator:o,changeAddress:i?.changeAddress}),d=await this.signSinglePartyTx(u,r);return this.broadcastRawTx(n,d)}async buildSinglePartyTx(e){let r=e.bitcoin.data,n=e.signer.publicKey,i=vv(e.beaconAddress,r),o=Sv(e.beaconAddress,r,e.changeAddress),s=zR(i,n,r);if(s!==e.beaconAddress)throw new nr(`Signer pubkey produces ${i.toUpperCase()} address "${s}", but beacon address is "${e.beaconAddress}".`,"SIGNER_KEY_MISMATCH",{kind:i,address:e.beaconAddress,derivedAddress:s});let c=Av(o,r),a=await e.feeEstimator.estimateFee(Ev(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new nr(`UTXO value (${e.utxo.value}) insufficient to cover fee (${a}).`,"INSUFFICIENT_FUNDS",{address:e.beaconAddress,valueSats:e.utxo.value,feeSats:a});let d=new Rs({allowUnknownOutputs:!0}),f;if(i==="p2pkh")f=ki(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes});else if(i==="p2wpkh")f=Ts(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f}});else{let p=n.slice(1,33);f=_s(p,void 0,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f},tapInternalKey:p})}let h=u-a;return h>=BigInt(xv[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:Tv(e.signalBytes),amount:0n}),{tx:d,prevOutScripts:[f],prevOutValues:[u],beaconAddress:e.beaconAddress,changeAddress:o,utxo:e.utxo,feeSats:a,scriptKind:i}}async signSinglePartyTx(e,r){return XR(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var _l=class extends Oo{constructor(e,r){super({...e,type:"CASBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;for(let s of e){let c=s.signalBytes,a=r.casMap.get(c);if(!a){i.push({kind:"NeedCASAnnouncement",announcementHash:c,beaconServiceId:this.service.id});continue}let u=a[o];if(!u)continue;let d=Zr(Os(u,"base64urlnopad"),"hex"),f=r.updateMap.get(d);if(!f){i.push({kind:"NeedSignedUpdate",updateHash:d,beaconServiceId:this.service.id});continue}n.push([f,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.did,s=Gn(e),c={[o]:s},a=Io(rr(c));i?.casPublish&&await i.casPublish(c);let u=await this.buildSignAndBroadcast(a,r,n,i);return{signedUpdate:e,txid:u,announcement:c}}};l();l();var Il=class extends Oo{constructor(e,r){super({...e,type:"SingletonBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array;for(let o of e){let s=o.signalBytes,c=r.updateMap.get(s);if(!c){i.push({kind:"NeedSignedUpdate",updateHash:s,beaconServiceId:this.service.id});continue}n.push([c,o.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=Io(rr(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var QR=new Uint8Array(32),D0=1n<<BigInt(256),Iv=(()=>{let t=new Array(257),e=D0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function Wu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function Ae(t,e,r=""){let n=Wu(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function Bl(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Yn(t.outputLen),Yn(t.blockLen)}function ea(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Rv(t,e){Ae(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Ns(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Rl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function En(t,e){return t<<32-e|t>>>e}var Uv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",e6=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Cs(t){if(Ae(t),Uv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=e6[t[r]];return e}var Ci={_0:48,_9:57,A:65,F:70,a:97,f:102};function Bv(t){if(t>=Ci._0&&t<=Ci._9)return t-Ci._0;if(t>=Ci.A&&t<=Ci.F)return t-(Ci.A-10);if(t>=Ci.a&&t<=Ci.f)return t-(Ci.a-10)}function Ls(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Uv)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Bv(t.charCodeAt(o)),c=Bv(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function hr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];Ae(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}function Ov(t,e={}){let r=(i,o)=>t(o).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}function Ps(t=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(t))}var Dv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var N0=BigInt(0),k0=BigInt(1);function Gu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function kv(t){if(typeof t=="bigint"){if(!Ul(t))throw new Error("positive bigint expected, got "+t)}else Yn(t);return t}function zu(t){let e=kv(t).toString(16);return e.length&1?"0"+e:e}function Nv(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?N0:BigInt("0x"+t)}function Do(t){return Nv(Cs(t))}function C0(t){return Nv(Cs(t6(Ae(t)).reverse()))}function Ol(t,e){Yn(e),t=kv(t);let r=Ls(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function L0(t,e){return Ol(t,e).reverse()}function ta(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function t6(t){return Uint8Array.from(t)}function Cv(t){return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var Ul=t=>typeof t=="bigint"&&N0<=t;function r6(t,e,r){return Ul(t)&&Ul(e)&&Ul(r)&&e<=t&&t<r}function Lv(t,e,r,n){if(!r6(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function P0(t){let e;for(e=0;t>N0;t>>=k0,e+=1);return e}var Yu=t=>(k0<<BigInt(t))-k0;function Pv(t,e,r){if(Yn(t,"hashLen"),Yn(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=x=>new Uint8Array(x),i=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),c=1e3,a=n(t),u=n(t),d=0,f=()=>{a.fill(1),u.fill(0),d=0},h=(...x)=>r(u,hr(a,...x)),p=(x=i)=>{u=h(o,x),a=h(),x.length!==0&&(u=h(s,x),a=h())},g=()=>{if(d++>=c)throw new Error("drbg: tried max amount of iterations");let x=0,S=[];for(;x<e;){a=h();let _=a.slice();S.push(_),x+=a.length}return hr(...S)};return(x,S)=>{f(),p(x);let _;for(;!(_=S(g()));)p();return f(),_}}function Ju(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,c){let a=t[o];if(c&&a===void 0)return;let u=typeof a;if(u!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${u}`)}let i=(o,s)=>Object.entries(o).forEach(([c,a])=>n(c,a,s));i(e,!1),i(r,!0)}function M0(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}function K0(t){return t.length===32}function Dl(t){if(!K0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function ht(...t){return ke(ft(...t))}function Zu(t){Dl(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function $0(t){let e=new Uint8Array(32),r=t;for(let n=31;n>=0;n--)e[n]=Number(r&0xffn),r>>=8n;if(r!==0n)throw new RangeError("Value exceeds 256 bits");return e}function H0(t){Dl(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function V0(t,e){return!K0(t)||!K0(e)?!1:ta(t,e)}function ra(t){return Dl(t),qc.encode(t)}function Jn(t){let e=qc.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var Mv;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(Mv||(Mv={}));l();l();var ko=256;function na(t,e){return Number(t>>BigInt(e)&1n)}var Kv=(()=>{let t=new Array(ko+1),e=new Uint8Array(32);for(let r=0;r<=ko;r++)e=ht(e,e),t[r]=e;return t})();function kl(t,e){if(t.length===0)return Kv[e];if(e===0)return t[0].leaf;let r=ko-e,n=[],i=[];for(let o of t)(na(o.index,r)===0?n:i).push(o);return ht(kl(n,e-1),kl(i,e-1))}function $v(t){return kl(t,ko)}function Hv(t,e){let r=0n,n=[];for(let i=1;i<=ko;i++){let o=ko-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(na(c.index,u)!==na(e,u)){a=!1;break}a&&na(c.index,o)!==na(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(kl(s,i-1))}return{collapsed:r,hashes:n}}function Vv(t,e,r,n,i){let o=n,s=0;for(let c=0;c<ko;c++){let a=ko-1-c,u;if((t>>BigInt(a)&1n)===1n)u=Kv[c];else{if(s>=e.length)return!1;u=e[s++]}o=na(r,a)===1?ht(u,o):ht(o,u)}return s===e.length&&V0(o,i)}l();var n6=new TextEncoder;function Nl(t){return Zu(ht(n6.encode(t)))}function qv(t,e){return ht(ht(t),ht(e))}function Fv(t){return ht(ht(t))}l();function jv(t,e,r){let n={id:ra(t),collapsed:ra($0(e.collapsed)),hashes:e.hashes.map(i=>ra(i))};return r?.nonce&&(n.nonce=ra(r.nonce)),r?.updateId&&(n.updateId=ra(r.updateId)),n}function i6(t){let e={rootHash:Jn(t.id),collapsed:Zu(Jn(t.collapsed)),hashes:t.hashes.map(r=>Jn(r))};return t.nonce&&(e.nonce=Jn(t.nonce)),t.updateId&&(e.updateId=Jn(t.updateId)),e}function Wv(t,e,r){let{rootHash:n,collapsed:i,hashes:o}=i6(t);return Vv(i,o,e,r,n)}l();var Cl=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=Nl(r.did);if(this.#e.has(n))throw new RangeError(`Duplicate DID index for: ${r.did}`);this.#e.set(n,r),this.#t.set(r.did,n)}this.#n=null,this.#r=null}finalize(){let e=[];for(let[r,n]of this.#e){let i=n.signedUpdate!==void 0?qv(n.nonce,n.signedUpdate):Fv(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=$v(e)}get rootHash(){if(this.#r===null)throw new Error("Tree not finalized: call finalize() first");return this.#r}proof(e){let r=this.#t.get(e);if(r===void 0)throw new RangeError(`DID not in tree: ${e}`);if(this.#n===null||this.#r===null)throw new Error("Tree not finalized: call finalize() first");let n=this.#e.get(r),i=Hv(this.#n,r),o=n.signedUpdate!==void 0?ht(n.signedUpdate):void 0;return jv(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var Ll=class extends Oo{constructor(e,r){super({...e,type:"SMTBeacon"},r)}processSignals(e,r){let n=new Array,i=new Array,o=this.did;for(let s of e){let c=r.smtMap.get(s.signalBytes);if(!c){i.push({kind:"NeedSMTProof",smtRootHash:s.signalBytes,beaconServiceId:this.service.id});continue}if(!c.nonce)throw new Fu("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=Nl(o),u=Jn(c.nonce),d=c.updateId?ht(ht(u),Jn(c.updateId)):ht(ht(u));if(!Wv(c,a,d))throw new Fu("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=H0(Jn(c.updateId)),p=r.updateMap.get(h);if(!p){i.push({kind:"NeedSignedUpdate",updateHash:h,beaconServiceId:this.service.id});continue}n.push([p,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.did,s=new TextEncoder().encode(rr(e)),c=Ir(32),a=new Cl;a.addEntries([{did:o,nonce:c,signedUpdate:s}]),a.finalize();let u=a.proof(o),d=await this.buildSignAndBroadcast(a.rootHash,r,n,i);return{signedUpdate:e,txid:d,proof:u}}};var ia=class{static establish(e,r){switch(e.type){case"SingletonBeacon":return new Il(e,r);case"CASBeacon":return new _l(e,r);case"SMTBeacon":return new Ll(e,r);default:throw new we("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Pi;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Pi||(Pi={}));l();var pt={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};l();var me=class t{constructor({method:e,id:r,path:n,query:i,fragment:o,params:s}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=i,this.fragment=o,this.params=s}static parse(e){if(!e)return null;let r=t.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:i,path:o,query:s,fragment:c}=r.groups,a={uri:`did:${n}:${i}`,method:n,id:i};if(o&&(a.path=o),s&&(a.query=s.slice(1)),c&&(a.fragment=c.slice(1)),s){let u={},d=s.slice(1).split("&");for(let f of d){let[h,p]=f.split("=");u[h]=p}a.params=u}return a}};me.METHOD_PATTERN="([a-z0-9]+)";me.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})";me.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${me.PCT_ENCODED_PATTERN})`;me.METHOD_ID_PATTERN=`((?:${me.ID_CHAR_PATTERN}*:)*(${me.ID_CHAR_PATTERN}+))`;me.PATH_PATTERN="(/[^#?]*)?";me.QUERY_PATTERN="([?][^#]*)?";me.FRAGMENT_PATTERN="(#.*)?";me.DID_URI_PATTERN=new RegExp(`^did:(?<method>${me.METHOD_PATTERN}):(?<id>${me.METHOD_ID_PATTERN})(?<path>${me.PATH_PATTERN})(?<query>${me.QUERY_PATTERN})(?<fragment>${me.FRAGMENT_PATTERN})$`);l();var re=class t extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,t)}},ie;(function(t){t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType"})(ie||(ie={}));l();l();l();l();l();var c6=Mn(zv(),1);l();l();l();l();var kH=new Uint8Array(0);function Yv(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function oa(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function u6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,x=0,S=0,_=g.length;S!==_&&g[S]===0;)S++,y++;for(var A=(_-S)*d+1>>>0,O=new Uint8Array(A);S!==_;){for(var T=g[S],M=0,q=A-1;(T!==0||M<x)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");x=M,S++}for(var j=A-x;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var x=0,S=0;g[y]===a;)x++,y++;for(var _=(g.length-y)*u+1>>>0,A=new Uint8Array(_);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=_-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=_-S;q!==_&&A[q]===0;)q++;for(var j=new Uint8Array(x+(_-q)),$=x;q!==_;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var d6=u6,f6=d6,Jv=f6;var W0=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},G0=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),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 Zv(this,e)}},z0=class{decoders;constructor(e){this.decoders=e}or(e){return Zv(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 Zv(t,e){return new z0({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Y0=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new W0(e,r,n),this.decoder=new G0(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Xv({name:t,prefix:e,encode:r,decode:n}){return new Y0(t,e,r,n)}function J0({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=Jv(r,t);return Xv({prefix:e,name:t,encode:n,decode:o=>oa(i(o))})}function l6(t,e,r,n){let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s}function h6(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s!==0&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o}function ir({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return Xv({prefix:e,name:t,encode(i){return h6(i,n,r)},decode(i){return l6(i,n,r,t)}})}var Xu=ir({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),VH=ir({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qH=ir({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),FH=ir({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jH=ir({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),WH=ir({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),GH=ir({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),zH=ir({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z0=ir({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var pr=J0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),XH=J0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var rV=ir({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nV=ir({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zn=ir({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iV=ir({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function Qv(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function e1(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function sa(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var Qu=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},t1=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(s){return new Promise(function(c,a){s=t[o](s),i(c,a,s.done,s.value)})}}function i(o,s,c,a){Promise.resolve(a).then(function(u){o({value:u,done:c})},s)}},Ml=new TextEncoder,Ms=new TextDecoder,ne=class t{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new t(e,"ArrayBuffer")}static asyncIterable(e){if(!e1(e))throw new TypeError("Input must be of type AsyncIterable.");return new t(e,"AsyncIterable")}static base32Z(e){return new t(e,"Base32Z")}static base58Btc(e){return new t(e,"Base58Btc")}static base64Url(e){return new t(e,"Base64Url")}static bufferSource(e){return new t(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new t(e,"Hex")}static multibase(e){return new t(e,"Multibase")}static object(e){return new t(e,"Object")}static string(e){return new t(e,"String")}static uint8Array(e){return new t(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return pr.baseDecode(this.data).buffer;case"Base64Url":return Zn.baseDecode(this.data).buffer;case"BufferSource":{if(sa(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Qv(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return Z0.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return pr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return pr.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Zn.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Zn.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=Ml.encode(e);return Zn.baseEncode(r)}case"String":{let e=Ml.encode(this.data);return Zn.baseEncode(e)}case"Uint8Array":return Zn.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=t1(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let d=i;a.push(d)}}catch(d){r={error:d}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return new Blob(a)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=Zn.baseDecode(this.data),r=Ms.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Ms.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return Ms.decode(this.data);case"Base64Url":{let e=Zn.baseDecode(this.data);return Ms.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Ms.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=t1(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let u=i;typeof u=="string"?a+=u:a+=Ms.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return a+=Ms.decode(void 0,{stream:!1}),a}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return Z0.baseDecode(this.data);case"Base58Btc":return pr.baseDecode(this.data);case"Base64Url":return Zn.baseDecode(this.data);case"BufferSource":{let e=sa(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return Ml.encode(e)}case"String":return Ml.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};l();var ed;(function(t){t.Debug="debug",t.Silent="silent"})(ed||(ed={}));var X0=class{constructor(){this.logLevel=ed.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==ed.Silent&&console.info(e)}error(e){this.logLevel!==ed.Silent&&console.error(e)}},p6=new X0;typeof window<"u"&&(window.web5logger=p6);l();l();l();l();var Mi={};Af(Mi,{decode:()=>ca,encodeTo:()=>Ks,encodingLength:()=>$s});l();l();var y6=i1,r1=128,g6=127,m6=~g6,w6=Math.pow(2,31);function i1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=w6;)e[r++]=t&255|r1,t/=128;for(;t&m6;)e[r++]=t&255|r1,t>>>=7;return e[r]=t|0,i1.bytes=r-n+1,e}var b6=Q0,x6=128,n1=127;function Q0(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw Q0.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&n1)<<i:(s&n1)*Math.pow(2,i),i+=7}while(s>=x6);return Q0.bytes=o-n,r}var E6=Math.pow(2,7),v6=Math.pow(2,14),S6=Math.pow(2,21),A6=Math.pow(2,28),T6=Math.pow(2,35),_6=Math.pow(2,42),I6=Math.pow(2,49),B6=Math.pow(2,56),R6=Math.pow(2,63),U6=function(t){return t<E6?1:t<v6?2:t<S6?3:t<A6?4:t<T6?5:t<_6?6:t<I6?7:t<B6?8:t<R6?9:10},O6={encode:y6,decode:b6,encodingLength:U6},D6=O6,td=D6;function ca(t,e=0){return[td.decode(t,e),td.decode.bytes]}function Ks(t,e,r=0){return td.encode(t,e,r),e}function $s(t){return td.encodingLength(t)}function eg(t,e){let r=e.byteLength,n=$s(t),i=n+$s(r),o=new Uint8Array(i+r);return Ks(t,o,0),Ks(r,o,n),o.set(e,i),new aa(t,r,e,o)}function o1(t){let e=oa(t),[r,n]=ca(e),[i,o]=ca(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new aa(r,i,s,e)}function s1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Yv(t.bytes,r.bytes)}}var aa=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function c1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return N6(r,rg(t),e??pr.encoder);default:return C6(r,rg(t),e??Xu.encoder)}}var a1=new WeakMap;function rg(t){let e=a1.get(t);if(e==null){let r=new Map;return a1.set(t,r),r}return e}var ng=class t{code;version;multihash;bytes;"/";constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==rd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==L6)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=eg(e,r);return t.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 t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&s1(e.multihash,n.multihash)}toString(e){return c1(this,e)}toJSON(){return{"/":c1(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 r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new t(n,i,o,s??u1(n,i,o.bytes))}else if(r[P6]===!0){let{version:n,multihash:i,code:o}=r,s=o1(i);return t.create(n,o,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==rd)throw new Error(`Version 0 CID must use dag-pb (code: ${rd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=u1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,rd,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=oa(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new aa(r.multihashCode,r.digestSize,o,i);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=ca(e.subarray(r));return r+=h,f},i=n(),o=rd;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,c=n(),a=n(),u=r+a,d=u-s;return{version:i,codec:o,multihashCode:c,digestSize:a,multihashSize:d,size:u}}static parse(e,r){let[n,i]=k6(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return rg(o).set(n,e),o}};function k6(t,e){switch(t[0]){case"Q":{let r=e??pr;return[pr.prefix,r.decode(`${pr.prefix}${t}`)]}case pr.prefix:{let r=e??pr;return[pr.prefix,r.decode(t)]}case Xu.prefix:{let r=e??Xu;return[Xu.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function N6(t,e,r){let{prefix:n}=r;if(n!==pr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return i}function C6(t,e,r){let{prefix:n}=r,i=e.get(n);if(i==null){let o=r.encode(t);return e.set(n,o),o}else return i}var rd=112,L6=18;function u1(t,e,r){let n=$s(t),i=n+$s(e),o=new Uint8Array(i+r.byteLength);return Ks(t,o,0),Ks(e,o,n),o.set(r,i),o}var P6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var Yt=class t{static addPrefix(e){var r;let{code:n,data:i,name:o}=e;if(!(o?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=t.codeToName.has(n)?n:t.nameToCode.get(o),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let s=Mi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Mi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Mi.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=t.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=t.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){t.codeToName.set(e.code,e.name),t.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,i]=Mi.decode(r),o=t.codeToName.get(n);if(o===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(i),name:o}}};Yt.codeToName=new Map;Yt.nameToCode=new Map;Yt.registerCodec({code:237,name:"ed25519-pub"});Yt.registerCodec({code:4864,name:"ed25519-priv"});Yt.registerCodec({code:236,name:"x25519-pub"});Yt.registerCodec({code:4866,name:"x25519-priv"});Yt.registerCodec({code:231,name:"secp256k1-pub"});Yt.registerCodec({code:4865,name:"secp256k1-priv"});l();function ig(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&ig(t[e])})}l();var FU=Mn(Jg(),1),tc=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})};var lh=class{constructor(){this.store=new Map}clear(){return tc(this,void 0,void 0,function*(){this.store.clear()})}close(){return tc(this,void 0,void 0,function*(){})}delete(e){return tc(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return tc(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return tc(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return tc(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return tc(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var c4=Mn(aw(),1);var a4=Mn(aw(),1);l();l();l();l();l();function u4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function uw(t,...e){if(!u4(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function dw(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function gT(t,e){uw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Na=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var jh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),In=(t,e)=>t<<32-e|t>>>e;var Uj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function d4(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function fw(t){return typeof t=="string"&&(t=d4(t)),uw(t),t}var Fh=class{clone(){return this._cloneInto()}},Oj={}.toString;function mT(t){let e=n=>t().update(fw(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function wT(t=32){if(Na&&typeof Na.getRandomValues=="function")return Na.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function f4(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var bT=(t,e,r)=>t&e^~t&r,xT=(t,e,r)=>t&e^t&r^e&r,Wh=class extends Fh{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=jh(this.buffer)}update(e){dw(this);let{view:r,buffer:n,blockLen:i}=this;e=fw(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=jh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dw(this),gT(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;f4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=jh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var l4=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Wo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Go=new Uint32Array(64),lw=class extends Wh{constructor(){super(64,32,8,!1),this.A=Wo[0]|0,this.B=Wo[1]|0,this.C=Wo[2]|0,this.D=Wo[3]|0,this.E=Wo[4]|0,this.F=Wo[5]|0,this.G=Wo[6]|0,this.H=Wo[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)Go[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Go[f-15],p=Go[f-2],g=In(h,7)^In(h,18)^h>>>3,y=In(p,17)^In(p,19)^p>>>10;Go[f]=y+Go[f-7]+g+Go[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=In(c,6)^In(c,11)^In(c,25),p=d+h+bT(c,a,u)+l4[f]+Go[f]|0,y=(In(n,2)^In(n,13)^In(n,22))+xT(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Go.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var zo=mT(()=>new lw);var h4=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Ca=class{static digest(e){return h4(this,arguments,void 0,function*({data:r}){return zo(r)})}};l();var ci=class{};var p4=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Gh=class extends ci{digest(e){return p4(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield Ca.digest({data:n})}})}};l();l();l();l();l();l();function ET(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function y4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function hw(t,...e){if(!y4(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function vT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ET(t.outputLen),ET(t.blockLen)}function La(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ST(t,e){hw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var zh=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function AT(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Yh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e,g4=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!g4)throw new Error("Non little-endian hardware is not supported");function pw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Cd(t){if(typeof t=="string"&&(t=pw(t)),!AT(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function Jh(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!AT(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Pa=class{clone(){return this._cloneInto()}},rW={}.toString;function Zh(t){let e=n=>t().update(Cd(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ld(t=32){if(zh&&typeof zh.getRandomValues=="function")return zh.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function m4(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var Ma=class extends Pa{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Yh(this.buffer)}update(e){La(this);let{view:r,buffer:n,blockLen:i}=this;e=Cd(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Yh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){La(this),ST(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;m4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Yh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var w4=(t,e,r)=>t&e^~t&r,b4=(t,e,r)=>t&e^t&r^e&r,x4=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Yo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Jo=new Uint32Array(64),yw=class extends Ma{constructor(){super(64,32,8,!1),this.A=Yo[0]|0,this.B=Yo[1]|0,this.C=Yo[2]|0,this.D=Yo[3]|0,this.E=Yo[4]|0,this.F=Yo[5]|0,this.G=Yo[6]|0,this.H=Yo[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)Jo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Jo[f-15],p=Jo[f-2],g=Bn(h,7)^Bn(h,18)^h>>>3,y=Bn(p,17)^Bn(p,19)^p>>>10;Jo[f]=y+Jo[f-7]+g+Jo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=Bn(c,6)^Bn(c,11)^Bn(c,25),p=d+h+w4(c,a,u)+x4[f]+Jo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+b4(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Jo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Xh=Zh(()=>new yw);l();var ep={};Af(ep,{bitGet:()=>I4,bitLen:()=>_4,bitMask:()=>Pd,bitSet:()=>B4,bytesToHex:()=>Zi,bytesToNumberBE:()=>Xi,bytesToNumberLE:()=>Un,concatBytes:()=>eo,createHmacDrbg:()=>ww,ensureBytes:()=>Ge,equalBytes:()=>A4,hexToBytes:()=>hc,hexToNumber:()=>mw,isBytes:()=>Rn,numberToBytesBE:()=>gr,numberToBytesLE:()=>Qi,numberToHexUnpadded:()=>BT,numberToVarBytesBE:()=>S4,utf8ToBytes:()=>T4,validateObject:()=>nn});l();var IT=BigInt(0),Qh=BigInt(1),E4=BigInt(2);function Rn(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var v4=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Zi(t){if(!Rn(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=v4[t[r]];return e}function BT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function mw(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Ji={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function TT(t){if(t>=Ji._0&&t<=Ji._9)return t-Ji._0;if(t>=Ji._A&&t<=Ji._F)return t-(Ji._A-10);if(t>=Ji._a&&t<=Ji._f)return t-(Ji._a-10)}function hc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=TT(t.charCodeAt(o)),c=TT(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function Xi(t){return mw(Zi(t))}function Un(t){if(!Rn(t))throw new Error("Uint8Array expected");return mw(Zi(Uint8Array.from(t).reverse()))}function gr(t,e){return hc(t.toString(16).padStart(e*2,"0"))}function Qi(t,e){return gr(t,e).reverse()}function S4(t){return hc(BT(t))}function Ge(t,e,r){let n;if(typeof e=="string")try{n=hc(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(Rn(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function eo(...t){let e=0;for(let i=0;i<t.length;i++){let o=t[i];if(!Rn(o))throw new Error("Uint8Array expected");e+=o.length}let r=new Uint8Array(e),n=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,n),n+=o.length}return r}function A4(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function T4(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function _4(t){let e;for(e=0;t>IT;t>>=Qh,e+=1);return e}function I4(t,e){return t>>BigInt(e)&Qh}var B4=(t,e,r)=>t|(r?Qh:IT)<<BigInt(e),Pd=t=>(E4<<BigInt(t-1))-Qh,gw=t=>new Uint8Array(t),_T=t=>Uint8Array.from(t);function ww(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=gw(t),i=gw(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=gw())=>{i=c(_T([0]),f),n=c(),f.length!==0&&(i=c(_T([1]),f),n=c())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){n=c();let p=n.slice();h.push(p),f+=n.length}return eo(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var R4={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Rn(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function nn(t,e,r={}){let n=(i,o,s)=>{let c=R4[o];if(typeof c!="function")throw new Error(`Invalid validator "${o}", expected function`);let a=t[i];if(!(s&&a===void 0)&&!c(a,t))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${o}`)};for(let[i,o]of Object.entries(e))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return t}var _t=BigInt(0),et=BigInt(1),pc=BigInt(2),U4=BigInt(3),bw=BigInt(4),RT=BigInt(5),UT=BigInt(8),O4=BigInt(9),D4=BigInt(16);function Be(t,e){let r=t%e;return r>=_t?r:e+r}function xw(t,e,r){if(r<=_t||e<_t)throw new Error("Expected power/modulo > 0");if(r===et)return _t;let n=et;for(;e>_t;)e&et&&(n=n*t%r),t=t*t%r,e>>=et;return n}function ze(t,e,r){let n=t;for(;e-- >_t;)n*=n,n%=r;return n}function tp(t,e){if(t===_t||e<=_t)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Be(t,e),n=e,i=_t,o=et,s=et,c=_t;for(;r!==_t;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==et)throw new Error("invert: does not exist");return Be(i,e)}function k4(t){let e=(t-et)/pc,r,n,i;for(r=t-et,n=0;r%pc===_t;r/=pc,n++);for(i=pc;i<t&&xw(i,e,t)!==t-et;i++);if(n===1){let s=(t+et)/bw;return function(a,u){let d=a.pow(u,s);if(!a.eql(a.sqr(d),u))throw new Error("Cannot find square root");return d}}let o=(r+et)/pc;return function(c,a){if(c.pow(a,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let u=n,d=c.pow(c.mul(c.ONE,i),r),f=c.pow(a,o),h=c.pow(a,r);for(;!c.eql(h,c.ONE);){if(c.eql(h,c.ZERO))return c.ZERO;let p=1;for(let y=c.sqr(h);p<u&&!c.eql(y,c.ONE);p++)y=c.sqr(y);let g=c.pow(d,et<<BigInt(u-p-1));d=c.sqr(g),f=c.mul(f,g),h=c.mul(h,d),u=p}return f}}function N4(t){if(t%bw===U4){let e=(t+et)/bw;return function(n,i){let o=n.pow(i,e);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(t%UT===RT){let e=(t-RT)/UT;return function(n,i){let o=n.mul(i,pc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,pc),s),u=n.mul(c,n.sub(a,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return t%D4,k4(t)}var OT=(t,e)=>(Be(t,e)&et)===et,C4=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ew(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=C4.reduce((n,i)=>(n[i]="function",n),e);return nn(t,r)}function L4(t,e,r){if(r<_t)throw new Error("Expected power > 0");if(r===_t)return t.ONE;if(r===et)return e;let n=t.ONE,i=e;for(;r>_t;)r&et&&(n=t.mul(n,i)),i=t.sqr(i),r>>=et;return n}function P4(t,e){let r=new Array(e.length),n=e.reduce((o,s,c)=>t.is0(s)?o:(r[c]=o,t.mul(o,s)),t.ONE),i=t.inv(n);return e.reduceRight((o,s,c)=>t.is0(s)?o:(r[c]=t.mul(o,r[c]),t.mul(o,s)),i),r}function vw(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Ka(t,e,r=!1,n={}){if(t<=_t)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=vw(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=N4(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Pd(i),ZERO:_t,ONE:et,create:a=>Be(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return _t<=a&&a<t},is0:a=>a===_t,isOdd:a=>(a&et)===et,neg:a=>Be(-a,t),eql:(a,u)=>a===u,sqr:a=>Be(a*a,t),add:(a,u)=>Be(a+u,t),sub:(a,u)=>Be(a-u,t),mul:(a,u)=>Be(a*u,t),pow:(a,u)=>L4(c,a,u),div:(a,u)=>Be(a*tp(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>tp(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>P4(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?Qi(a,o):gr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?Un(a):Xi(a)}});return Object.freeze(c)}function DT(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function kT(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Sw(t){let e=kT(t);return e+Math.ceil(e/2)}function NT(t,e,r=!1){let n=t.length,i=kT(e),o=Sw(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?Xi(t):Un(t),c=Be(s,e-et)+et;return r?Qi(c,i):gr(c,i)}l();l();var K4=BigInt(0),Aw=BigInt(1);function rp(t,e){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(e/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=t.ZERO,c=i;for(;o>K4;)o&Aw&&(s=s.add(c)),c=c.double(),o>>=Aw;return s},precomputeWindow(i,o){let{windows:s,windowSize:c}=n(o),a=[],u=i,d=u;for(let f=0;f<s;f++){d=u,a.push(d);for(let h=1;h<c;h++)d=d.add(u),a.push(d);u=d.double()}return a},wNAF(i,o,s){let{windows:c,windowSize:a}=n(i),u=t.ZERO,d=t.BASE,f=BigInt(2**i-1),h=2**i,p=BigInt(i);for(let g=0;g<c;g++){let y=g*a,x=Number(s&f);s>>=p,x>a&&(x-=h,s+=Aw);let S=y,_=y+Math.abs(x)-1,A=g%2!==0,O=x<0;x===0?d=d.add(r(A,o[S])):u=u.add(r(O,o[_]))}return{p:u,f:d}},wNAFCached(i,o,s,c){let a=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,a),a!==1&&o.set(i,c(u))),this.wNAF(a,u,s)}}}function Md(t){return Ew(t.Fp),nn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function $4(t){let e=Md(t);nn(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:H4,hexToBytes:V4}=ep,yc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=yc;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)throw new e("Invalid signature integer: wrong length");if(n[0]&128)throw new e("Invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:H4(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=yc,r=typeof t=="string"?V4(t):t;if(!Rn(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:o}=yc._parseInt(r.subarray(2)),{d:s,l:c}=yc._parseInt(o);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),i=e(r(t.r)),o=n.length/2,s=i.length/2,c=r(o),a=r(s);return`30${r(s+o+4)}02${a}${i}02${c}${n}`}},to=BigInt(0),on=BigInt(1),SW=BigInt(2),CT=BigInt(3),AW=BigInt(4);function q4(t){let e=$4(t),{Fp:r}=e,n=e.toBytes||((g,y,x)=>{let S=y.toAffine();return eo(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),i=e.fromBytes||(g=>{let y=g.subarray(1),x=r.fromBytes(y.subarray(0,r.BYTES)),S=r.fromBytes(y.subarray(r.BYTES,2*r.BYTES));return{x,y:S}});function o(g){let{a:y,b:x}=e,S=r.sqr(g),_=r.mul(S,g);return r.add(r.add(_,r.mul(g,y)),x)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function s(g){return typeof g=="bigint"&&to<g&&g<e.n}function c(g){if(!s(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){let{allowedPrivateKeyLengths:y,nByteLength:x,wrapPrivateKey:S,n:_}=e;if(y&&typeof g!="bigint"){if(Rn(g)&&(g=Zi(g)),typeof g!="string"||!y.includes(g.length))throw new Error("Invalid key");g=g.padStart(x*2,"0")}let A;try{A=typeof g=="bigint"?g:Xi(Ge("private key",g,x))}catch{throw new Error(`private key must be ${x} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=Be(A,_)),c(A),A}let u=new Map;function d(g){if(!(g instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(y,x,S){if(this.px=y,this.py=x,this.pz=S,y==null||!r.isValid(y))throw new Error("x required");if(x==null||!r.isValid(x))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(y){let{x,y:S}=y||{};if(!y||!r.isValid(x)||!r.isValid(S))throw new Error("invalid affine point");if(y instanceof f)throw new Error("projective point not allowed");let _=A=>r.eql(A,r.ZERO);return _(x)&&_(S)?f.ZERO:new f(x,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let x=r.invertBatch(y.map(S=>S.pz));return y.map((S,_)=>S.toAffine(x[_])).map(f.fromAffine)}static fromHex(y){let x=f.fromAffine(i(Ge("pointHex",y)));return x.assertValidity(),x}static fromPrivateKey(y){return f.BASE.multiply(a(y))}_setWindowSize(y){this._WINDOW_SIZE=y,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:y,y:x}=this.toAffine();if(!r.isValid(y)||!r.isValid(x))throw new Error("bad point: x or y not FE");let S=r.sqr(x),_=o(y);if(!r.eql(S,_))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y}=this.toAffine();if(r.isOdd)return!r.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){d(y);let{px:x,py:S,pz:_}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(x,T),r.mul(A,_)),q=r.eql(r.mul(S,T),r.mul(O,_));return M&&q}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:y,b:x}=e,S=r.mul(x,CT),{px:_,py:A,pz:O}=this,T=r.ZERO,M=r.ZERO,q=r.ZERO,j=r.mul(_,_),$=r.mul(A,A),X=r.mul(O,O),Q=r.mul(_,A);return Q=r.add(Q,Q),q=r.mul(_,O),q=r.add(q,q),T=r.mul(y,q),M=r.mul(S,X),M=r.add(T,M),T=r.sub($,M),M=r.add($,M),M=r.mul(T,M),T=r.mul(Q,T),q=r.mul(S,q),X=r.mul(y,X),Q=r.sub(j,X),Q=r.mul(y,Q),Q=r.add(Q,q),q=r.add(j,j),j=r.add(q,j),j=r.add(j,X),j=r.mul(j,Q),M=r.add(M,j),X=r.mul(A,O),X=r.add(X,X),j=r.mul(X,Q),T=r.sub(T,j),q=r.mul(X,$),q=r.add(q,q),q=r.add(q,q),new f(T,M,q)}add(y){d(y);let{px:x,py:S,pz:_}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,X=r.mul(e.b,CT),Q=r.mul(x,A),G=r.mul(S,O),I=r.mul(_,T),D=r.add(x,S),E=r.add(A,O);D=r.mul(D,E),E=r.add(Q,G),D=r.sub(D,E),E=r.add(x,_);let U=r.add(A,T);return E=r.mul(E,U),U=r.add(Q,I),E=r.sub(E,U),U=r.add(S,_),M=r.add(O,T),U=r.mul(U,M),M=r.add(G,I),U=r.sub(U,M),j=r.mul($,E),M=r.mul(X,I),j=r.add(M,j),M=r.sub(G,j),j=r.add(G,j),q=r.mul(M,j),G=r.add(Q,Q),G=r.add(G,Q),I=r.mul($,I),E=r.mul(X,E),G=r.add(G,I),I=r.sub(Q,I),I=r.mul($,I),E=r.add(E,I),Q=r.mul(G,E),q=r.add(q,Q),Q=r.mul(U,E),M=r.mul(D,M),M=r.sub(M,Q),Q=r.mul(D,G),j=r.mul(U,j),j=r.add(j,Q),new f(M,q,j)}subtract(y){return this.add(y.negate())}is0(){return this.equals(f.ZERO)}wNAF(y){return p.wNAFCached(this,u,y,x=>{let S=r.invertBatch(x.map(_=>_.pz));return x.map((_,A)=>_.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let x=f.ZERO;if(y===to)return x;if(c(y),y===on)return this;let{endo:S}=e;if(!S)return p.unsafeLadder(this,y);let{k1neg:_,k1:A,k2neg:O,k2:T}=S.splitScalar(y),M=x,q=x,j=this;for(;A>to||T>to;)A&on&&(M=M.add(j)),T&on&&(q=q.add(j)),j=j.double(),A>>=on,T>>=on;return _&&(M=M.negate()),O&&(q=q.negate()),q=new f(r.mul(q.px,S.beta),q.py,q.pz),M.add(q)}multiply(y){c(y);let x=y,S,_,{endo:A}=e;if(A){let{k1neg:O,k1:T,k2neg:M,k2:q}=A.splitScalar(x),{p:j,f:$}=this.wNAF(T),{p:X,f:Q}=this.wNAF(q);j=p.constTimeNegate(O,j),X=p.constTimeNegate(M,X),X=new f(r.mul(X.px,A.beta),X.py,X.pz),S=j.add(X),_=$.add(Q)}else{let{p:O,f:T}=this.wNAF(x);S=O,_=T}return f.normalizeZ([S,_])[0]}multiplyAndAddUnsafe(y,x,S){let _=f.BASE,A=(T,M)=>M===to||M===on||!T.equals(_)?T.multiplyUnsafe(M):T.multiply(M),O=A(this,x).add(A(y,S));return O.is0()?void 0:O}toAffine(y){let{px:x,py:S,pz:_}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(_));let O=r.mul(x,y),T=r.mul(S,y),M=r.mul(_,y);if(A)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:O,y:T}}isTorsionFree(){let{h:y,isTorsionFree:x}=e;if(y===on)return!0;if(x)return x(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:x}=e;return y===on?this:x?x(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return Zi(this.toRawBytes(y))}}f.BASE=new f(e.Gx,e.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);let h=e.nBitLength,p=rp(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function F4(t){let e=Md(t);return nn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function LT(t){let e=F4(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(E){return to<E&&E<r.ORDER}function c(E){return Be(E,n)}function a(E){return tp(E,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=q4({...e,toBytes(E,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=eo;return L?C(Uint8Array.from([U.hasEvenY()?2:3]),R):C(Uint8Array.from([4]),R,r.toBytes(N.y))},fromBytes(E){let U=E.length,L=E[0],N=E.subarray(1);if(U===i&&(L===2||L===3)){let R=Xi(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&on)===on;return(L&1)===1!==V&&(P=r.neg(P)),{x:R,y:P}}else if(U===o&&L===4){let R=r.fromBytes(N.subarray(0,r.BYTES)),C=r.fromBytes(N.subarray(r.BYTES,2*r.BYTES));return{x:R,y:C}}else throw new Error(`Point of length ${U} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=E=>Zi(gr(E,e.nByteLength));function g(E){let U=n>>on;return E>U}function y(E){return g(E)?c(-E):E}let x=(E,U,L)=>Xi(E.slice(U,L));class S{constructor(U,L,N){this.r=U,this.s=L,this.recovery=N,this.assertValidity()}static fromCompact(U){let L=e.nByteLength;return U=Ge("compactSignature",U,L*2),new S(x(U,0,L),x(U,L,2*L))}static fromDER(U){let{r:L,s:N}=yc.toSig(Ge("DER",U));return new S(L,N)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(U){return new S(this.r,this.s,U)}recoverPublicKey(U){let{r:L,s:N,recovery:R}=this,C=q(Ge("msgHash",U));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let P=R===2||R===3?L+e.n:L;if(P>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let V=R&1?"03":"02",J=u.fromHex(V+p(P)),z=a(P),W=c(-C*z),Y=c(N*z),Z=u.BASE.multiplyAndAddUnsafe(J,W,Y);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return hc(this.toDERHex())}toDERHex(){return yc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let _={isValidPrivateKey(E){try{return d(E),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let E=Sw(e.n);return NT(e.randomBytes(E),e.n)},precompute(E=8,U=u.BASE){return U._setWindowSize(E),U.multiply(BigInt(3)),U}};function A(E,U=!0){return u.fromPrivateKey(E).toRawBytes(U)}function O(E){let U=Rn(E),L=typeof E=="string",N=(U||L)&&E.length;return U?N===i||N===o:L?N===2*i||N===2*o:E instanceof u}function T(E,U,L=!0){if(O(E))throw new Error("first arg must be private key");if(!O(U))throw new Error("second arg must be public key");return u.fromHex(U).multiply(d(E)).toRawBytes(L)}let M=e.bits2int||function(E){let U=Xi(E),L=E.length*8-e.nBitLength;return L>0?U>>BigInt(L):U},q=e.bits2int_modN||function(E){return c(M(E))},j=Pd(e.nBitLength);function $(E){if(typeof E!="bigint")throw new Error("bigint expected");if(!(to<=E&&E<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return gr(E,e.nByteLength)}function X(E,U,L=Q){if(["recovered","canonical"].some(ee=>ee in L))throw new Error("sign() legacy options not supported");let{hash:N,randomBytes:R}=e,{lowS:C,prehash:P,extraEntropy:V}=L;C==null&&(C=!0),E=Ge("msgHash",E),P&&(E=Ge("prehashed msgHash",N(E)));let J=q(E),z=d(U),W=[$(z),$(J)];if(V!=null){let ee=V===!0?R(r.BYTES):V;W.push(Ge("extraEntropy",ee))}let Y=eo(...W),Z=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Ue=a(ce),Ke=u.BASE.multiply(ce).toAffine(),Je=c(Ke.x);if(Je===to)return;let bt=c(Ue*c(Z+Je*z));if(bt===to)return;let pi=(Ke.x===Je?0:2)|Number(Ke.y&on),fo=bt;return C&&g(bt)&&(fo=y(bt),pi^=1),new S(Je,fo,pi)}return{seed:Y,k2sig:ue}}let Q={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function I(E,U,L=Q){let{seed:N,k2sig:R}=X(E,U,L),C=e;return ww(C.hash.outputLen,C.nByteLength,C.hmac)(N,R)}u.BASE._setWindowSize(8);function D(E,U,L,N=G){let R=E;if(U=Ge("msgHash",U),L=Ge("publicKey",L),"strict"in N)throw new Error("options.strict was renamed to lowS");let{lowS:C,prehash:P}=N,V,J;try{if(typeof R=="string"||Rn(R))try{V=S.fromDER(R)}catch(Ke){if(!(Ke instanceof yc.Err))throw Ke;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Ke,s:Je}=R;V=new S(Ke,Je)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Ke){if(Ke.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(C&&V.hasHighS())return!1;P&&(U=e.hash(U));let{r:z,s:W}=V,Y=q(U),Z=a(W),ue=c(Y*Z),ee=c(z*Z),ce=u.BASE.multiplyAndAddUnsafe(J,ue,ee)?.toAffine();return ce?c(ce.x)===z:!1}return{CURVE:e,getPublicKey:A,getSharedSecret:T,sign:I,verify:D,ProjectivePoint:u,Signature:S,utils:_}}l();l();var np=class extends Pa{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,vT(e);let n=Cd(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),o.fill(0)}update(e){return La(this),this.iHash.update(e),this}digestInto(e){La(this),hw(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Tw=(t,e,r)=>new np(t,e).update(r).digest();Tw.create=(t,e)=>new np(t,e);function j4(t){return{hash:t,hmac:(e,...r)=>Tw(t,e,Jh(...r)),randomBytes:Ld}}function ip(t,e){let r=n=>LT({...t,...j4(n)});return Object.freeze({...r(e),create:r})}var KT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),PT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),W4=BigInt(1),_w=BigInt(2),MT=(t,e)=>(t+e/_w)/e;function G4(t){let e=KT,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=ze(d,r,e)*d%e,h=ze(f,r,e)*d%e,p=ze(h,_w,e)*u%e,g=ze(p,i,e)*p%e,y=ze(g,o,e)*g%e,x=ze(y,c,e)*y%e,S=ze(x,a,e)*x%e,_=ze(S,c,e)*y%e,A=ze(_,r,e)*d%e,O=ze(A,s,e)*g%e,T=ze(O,n,e)*u%e,M=ze(T,_w,e);if(!Iw.eql(Iw.sqr(M),t))throw new Error("Cannot find square root");return M}var Iw=Ka(KT,void 0,void 0,{sqrt:G4}),mr=ip({a:BigInt(0),b:BigInt(7),Fp:Iw,n:PT,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=PT,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-W4*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=MT(o*t,e),a=MT(-n*t,e),u=Be(t-c*r-a*i,e),d=Be(-c*n-a*o,e),f=u>s,h=d>s;if(f&&(u=e-u),h&&(d=e-d),u>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}}},Xh),KW=BigInt(0);var $W=mr.ProjectivePoint;l();l();function $T(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),o={};for(let s of i)o[s]=e(n[s]);return o}return n},r=e(t);return JSON.stringify(r)}var z4=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Bw="urn:jwk:";function ge(t){return z4(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);ig(n);let i=$T(n),o=ne.string(i).toUint8Array(),s=yield Ca.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function ai(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function $a(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function ui(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function Ha(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function HT(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}var $t=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Y4=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},kt=class t{static adjustSignatureToLowS(e){return $t(this,arguments,void 0,function*({signature:r}){let n=mr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return mr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return $t(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"secp256k1",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return $t(this,arguments,void 0,function*({derSignature:r}){return mr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return mr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=mr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return $t(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=Y4(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return $t(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return $t(this,arguments,void 0,function*({publicKey:r}){if(!($a(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return $t(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return mr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return $t(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=zo(r);return mr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return mr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{mr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return $t(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=zo(i);return mr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=mr.getPublicKey(r));let n=mr.ProjectivePoint.fromHex(r),i=gr(n.x,32),o=gr(n.y,32);return{x:i,y:o}})}};l();l();var VT=Ka(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),J4=VT.create(BigInt("-3")),Z4=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),X4=ip({a:J4,b:Z4,Fp:VT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Xh),Lr=X4;var Ht=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Q4=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Vt=class t{static adjustSignatureToLowS(e){return Ht(this,arguments,void 0,function*({signature:r}){let n=Lr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Ht(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Lr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Ht(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"P-256",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return Ht(this,arguments,void 0,function*({derSignature:r}){return Lr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Lr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ht(this,void 0,void 0,function*(){let e=Lr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Ht(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,o=Q4(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Ht(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Ht(this,arguments,void 0,function*({publicKey:r}){if(!($a(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return Ht(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return Lr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return Ht(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=zo(r);return Lr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Ht(this,arguments,void 0,function*({privateKeyBytes:r}){return Lr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){try{Lr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Ht(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=zo(i);return Lr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Ht(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Lr.getPublicKey(r));let n=Lr.ProjectivePoint.fromHex(r),i=gr(n.x,32),o=gr(n.y,32);return{x:i,y:o}})}};var Kd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},$d=class extends ci{computePublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield kt.computePublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.computePublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Kd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"ES256K":case"secp256k1":{let n=yield kt.generateKey();return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Vt.generateKey();return n.alg="ES256",n}}})}getPublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield kt.getPublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Vt.getPublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Kd(this,arguments,void 0,function*({key:r,data:n}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":return yield kt.sign({key:r,data:n});case"P-256":return yield Vt.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Kd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!$a(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(r.crv){case"secp256k1":return yield kt.verify({key:r,signature:n,data:i});case"P-256":return yield Vt.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};l();l();l();l();l();var op=BigInt(4294967295),Rw=BigInt(32);function qT(t,e=!1){return e?{h:Number(t&op),l:Number(t>>Rw&op)}:{h:Number(t>>Rw&op)|0,l:Number(t&op)|0}}function eN(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:o,l:s}=qT(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var tN=(t,e)=>BigInt(t>>>0)<<Rw|BigInt(e>>>0),rN=(t,e,r)=>t>>>r,nN=(t,e,r)=>t<<32-r|e>>>r,iN=(t,e,r)=>t>>>r|e<<32-r,oN=(t,e,r)=>t<<32-r|e>>>r,sN=(t,e,r)=>t<<64-r|e>>>r-32,cN=(t,e,r)=>t>>>r-32|e<<64-r,aN=(t,e)=>e,uN=(t,e)=>t,dN=(t,e,r)=>t<<r|e>>>32-r,fN=(t,e,r)=>e<<r|t>>>32-r,lN=(t,e,r)=>e<<r-32|t>>>64-r,hN=(t,e,r)=>t<<r-32|e>>>64-r;function pN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var yN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),gN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,mN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),wN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,bN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),xN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var EN={fromBig:qT,split:eN,toBig:tN,shrSH:rN,shrSL:nN,rotrSH:iN,rotrSL:oN,rotrBH:sN,rotrBL:cN,rotr32H:aN,rotr32L:uN,rotlSH:dN,rotlSL:fN,rotlBH:lN,rotlBL:hN,add:pN,add3L:yN,add3H:gN,add4L:mN,add4H:wN,add5H:xN,add5L:bN},le=EN;var[vN,SN]=le.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Zo=new Uint32Array(80),Xo=new Uint32Array(80),Uw=class extends Ma{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:c,Dl:a,Eh:u,El:d,Fh:f,Fl:h,Gh:p,Gl:g,Hh:y,Hl:x}=this;return[e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,x]}set(e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,x){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=c|0,this.Dl=a|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=y|0,this.Hl=x|0}process(e,r){for(let A=0;A<16;A++,r+=4)Zo[A]=e.getUint32(r),Xo[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=Zo[A-15]|0,T=Xo[A-15]|0,M=le.rotrSH(O,T,1)^le.rotrSH(O,T,8)^le.shrSH(O,T,7),q=le.rotrSL(O,T,1)^le.rotrSL(O,T,8)^le.shrSL(O,T,7),j=Zo[A-2]|0,$=Xo[A-2]|0,X=le.rotrSH(j,$,19)^le.rotrBH(j,$,61)^le.shrSH(j,$,6),Q=le.rotrSL(j,$,19)^le.rotrBL(j,$,61)^le.shrSL(j,$,6),G=le.add4L(q,Q,Xo[A-7],Xo[A-16]),I=le.add4H(G,M,X,Zo[A-7],Zo[A-16]);Zo[A]=I|0,Xo[A]=G|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:c,Cl:a,Dh:u,Dl:d,Eh:f,El:h,Fh:p,Fl:g,Gh:y,Gl:x,Hh:S,Hl:_}=this;for(let A=0;A<80;A++){let O=le.rotrSH(f,h,14)^le.rotrSH(f,h,18)^le.rotrBH(f,h,41),T=le.rotrSL(f,h,14)^le.rotrSL(f,h,18)^le.rotrBL(f,h,41),M=f&p^~f&y,q=h&g^~h&x,j=le.add5L(_,T,q,SN[A],Xo[A]),$=le.add5H(j,S,O,M,vN[A],Zo[A]),X=j|0,Q=le.rotrSH(n,i,28)^le.rotrBH(n,i,34)^le.rotrBH(n,i,39),G=le.rotrSL(n,i,28)^le.rotrBL(n,i,34)^le.rotrBL(n,i,39),I=n&o^n&c^o&c,D=i&s^i&a^s&a;S=y|0,_=x|0,y=p|0,x=g|0,p=f|0,g=h|0,{h:f,l:h}=le.add(u|0,d|0,$|0,X|0),u=c|0,d=a|0,c=o|0,a=s|0,o=n|0,s=i|0;let E=le.add3L(X,G,D);n=le.add3H(E,$,Q,I),i=E|0}({h:n,l:i}=le.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=le.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:c,l:a}=le.add(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:d}=le.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:h}=le.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:g}=le.add(this.Fh|0,this.Fl|0,p|0,g|0),{h:y,l:x}=le.add(this.Gh|0,this.Gl|0,y|0,x|0),{h:S,l:_}=le.add(this.Hh|0,this.Hl|0,S|0,_|0),this.set(n,i,o,s,c,a,u,d,f,h,p,g,y,x,S,_)}roundClean(){Zo.fill(0),Xo.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ow=Zh(()=>new Uw);l();var On=BigInt(0),Pr=BigInt(1),sp=BigInt(2),AN=BigInt(8),TN={zip215:!0};function _N(t){let e=Md(t);return nn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function cp(t){let e=_N(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=sp<<BigInt(c*8)-Pr,d=r.create,f=e.uvRatio||((N,R)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(R))}}catch{return{isValid:!1,value:On}}}),h=e.adjustScalarBytes||(N=>N),p=e.domain||((N,R,C)=>{if(R.length||C)throw new Error("Contexts/pre-hash are not supported");return N}),g=N=>typeof N=="bigint"&&On<N,y=(N,R)=>g(N)&&g(R)&&N<R,x=N=>N===On||y(N,u);function S(N,R){if(y(N,R))return N;throw new Error(`Expected valid scalar < ${R}, got ${typeof N} ${N}`)}function _(N){return N===On?N:S(N,n)}let A=new Map;function O(N){if(!(N instanceof T))throw new Error("ExtendedPoint expected")}class T{constructor(R,C,P,V){if(this.ex=R,this.ey=C,this.ez=P,this.et=V,!x(R))throw new Error("x required");if(!x(C))throw new Error("y required");if(!x(P))throw new Error("z required");if(!x(V))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(R){if(R instanceof T)throw new Error("extended point not allowed");let{x:C,y:P}=R||{};if(!x(C)||!x(P))throw new Error("invalid affine point");return new T(C,P,Pr,d(C*P))}static normalizeZ(R){let C=r.invertBatch(R.map(P=>P.ez));return R.map((P,V)=>P.toAffine(C[V])).map(T.fromAffine)}_setWindowSize(R){this._WINDOW_SIZE=R,A.delete(this)}assertValidity(){let{a:R,d:C}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:P,ey:V,ez:J,et:z}=this,W=d(P*P),Y=d(V*V),Z=d(J*J),ue=d(Z*Z),ee=d(W*R),ce=d(Z*d(ee+Y)),Ue=d(ue+d(C*d(W*Y)));if(ce!==Ue)throw new Error("bad point: equation left != right (1)");let Ke=d(P*V),Je=d(J*z);if(Ke!==Je)throw new Error("bad point: equation left != right (2)")}equals(R){O(R);let{ex:C,ey:P,ez:V}=this,{ex:J,ey:z,ez:W}=R,Y=d(C*W),Z=d(J*V),ue=d(P*W),ee=d(z*V);return Y===Z&&ue===ee}is0(){return this.equals(T.ZERO)}negate(){return new T(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:R}=e,{ex:C,ey:P,ez:V}=this,J=d(C*C),z=d(P*P),W=d(sp*d(V*V)),Y=d(R*J),Z=C+P,ue=d(d(Z*Z)-J-z),ee=Y+z,ce=ee-W,Ue=Y-z,Ke=d(ue*ce),Je=d(ee*Ue),bt=d(ue*Ue),pi=d(ce*ee);return new T(Ke,Je,pi,bt)}add(R){O(R);let{a:C,d:P}=e,{ex:V,ey:J,ez:z,et:W}=this,{ex:Y,ey:Z,ez:ue,et:ee}=R;if(C===BigInt(-1)){let fu=d((J-V)*(Z+Y)),gf=d((J+V)*(Z-Y)),lu=d(gf-fu);if(lu===On)return this.double();let mf=d(z*sp*ee),wf=d(W*sp*ue),Fr=wf+mf,ho=gf+fu,hu=wf-mf,bf=d(Fr*lu),fs=d(ho*hu),xf=d(Fr*hu),Xp=d(lu*ho);return new T(bf,fs,Xp,xf)}let ce=d(V*Y),Ue=d(J*Z),Ke=d(W*P*ee),Je=d(z*ue),bt=d((V+J)*(Y+Z)-ce-Ue),pi=Je-Ke,fo=Je+Ke,du=d(Ue-C*ce),yf=d(bt*pi),Zp=d(fo*du),lo=d(bt*du),qr=d(pi*fo);return new T(yf,Zp,qr,lo)}subtract(R){return this.add(R.negate())}wNAF(R){return j.wNAFCached(this,A,R,T.normalizeZ)}multiply(R){let{p:C,f:P}=this.wNAF(S(R,n));return T.normalizeZ([C,P])[0]}multiplyUnsafe(R){let C=_(R);return C===On?q:this.equals(q)||C===Pr?this:this.equals(M)?this.wNAF(C).p:j.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return j.unsafeLadder(this,n).is0()}toAffine(R){let{ex:C,ey:P,ez:V}=this,J=this.is0();R==null&&(R=J?AN:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:On,y:Pr};if(Y!==Pr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Pr?this:this.multiplyUnsafe(R)}static fromHex(R,C=!1){let{d:P,a:V}=e,J=r.BYTES;R=Ge("pointHex",R,J);let z=R.slice(),W=R[J-1];z[J-1]=W&-129;let Y=Un(z);Y===On||(C?S(Y,u):S(Y,r.ORDER));let Z=d(Y*Y),ue=d(Z-Pr),ee=d(P*Z-V),{isValid:ce,value:Ue}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Ke=(Ue&Pr)===Pr,Je=(W&128)!==0;if(!C&&Ue===On&&Je)throw new Error("Point.fromHex: x=0 and x_0=1");return Je!==Ke&&(Ue=d(-Ue)),T.fromAffine({x:Ue,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=Qi(C,r.BYTES);return P[P.length-1]|=R&Pr?128:0,P}toHex(){return Zi(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Pr,d(e.Gx*e.Gy)),T.ZERO=new T(On,Pr,Pr,On);let{BASE:M,ZERO:q}=T,j=rp(T,c*8);function $(N){return Be(N,n)}function X(N){return $(Un(N))}function Q(N){let R=c;N=Ge("private key",N,R);let C=Ge("hashed private key",o(N),2*R),P=h(C.slice(0,R)),V=C.slice(R,2*R),J=X(P),z=M.multiply(J),W=z.toRawBytes();return{head:P,prefix:V,scalar:J,point:z,pointBytes:W}}function G(N){return Q(N).pointBytes}function I(N=new Uint8Array,...R){let C=eo(...R);return X(o(p(C,Ge("context",N),!!i)))}function D(N,R,C={}){N=Ge("message",N),i&&(N=i(N));let{prefix:P,scalar:V,pointBytes:J}=Q(R),z=I(C.context,P,N),W=M.multiply(z).toRawBytes(),Y=I(C.context,W,J,N),Z=$(z+Y*V);_(Z);let ue=eo(W,Qi(Z,r.BYTES));return Ge("result",ue,c*2)}let E=TN;function U(N,R,C,P=E){let{context:V,zip215:J}=P,z=r.BYTES;N=Ge("signature",N,2*z),R=Ge("message",R),i&&(R=i(R));let W=Un(N.slice(z,2*z)),Y,Z,ue;try{Y=T.fromHex(C,J),Z=T.fromHex(N.slice(0,z),J),ue=M.multiplyUnsafe(W)}catch{return!1}if(!J&&Y.isSmallOrder())return!1;let ee=I(V,Z.toRawBytes(),Y.toRawBytes(),R);return Z.add(Y.multiplyUnsafe(ee)).subtract(ue).clearCofactor().equals(T.ZERO)}return M._setWindowSize(8),{CURVE:e,getPublicKey:G,sign:D,verify:U,ExtendedPoint:T,utils:{getExtendedPublicKey:Q,randomPrivateKey:()=>s(r.BYTES),precompute(N=8,R=T.BASE){return R._setWindowSize(N),R.multiply(BigInt(3)),R}}}}l();var Hd=BigInt(0),Dw=BigInt(1);function IN(t){return nn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function FT(t){let e=IN(t),{P:r}=e,n=A=>Be(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>xw(A,r-BigInt(2),r));function u(A,O,T){let M=n(A*(O-T));return O=n(O-M),T=n(T+M),[O,T]}function d(A){if(typeof A=="bigint"&&Hd<=A&&A<r)return A;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let f=(e.a-BigInt(2))/BigInt(4);function h(A,O){let T=d(A),M=d(O),q=T,j=Dw,$=Hd,X=T,Q=Dw,G=Hd,I;for(let E=BigInt(i-1);E>=Hd;E--){let U=M>>E&Dw;G^=U,I=u(G,j,X),j=I[0],X=I[1],I=u(G,$,Q),$=I[0],Q=I[1],G=U;let L=j+$,N=n(L*L),R=j-$,C=n(R*R),P=N-C,V=X+Q,J=X-Q,z=n(J*L),W=n(V*R),Y=z+W,Z=z-W;X=n(Y*Y),Q=n(q*n(Z*Z)),j=n(N*C),$=n(P*(N+n(f*P)))}I=u(G,j,X),j=I[0],X=I[1],I=u(G,$,Q),$=I[0],Q=I[1];let D=a($);return n(j*D)}function p(A){return Qi(n(A),o)}function g(A){let O=Ge("u coordinate",A,o);return s===32&&(O[31]&=127),Un(O)}function y(A){let O=Ge("scalar",A),T=O.length;if(T!==o&&T!==s)throw new Error(`Expected ${o} or ${s} bytes, got ${T}`);return Un(c(O))}function x(A,O){let T=g(O),M=y(A),q=h(T,M);if(q===Hd)throw new Error("Invalid private or public key received");return p(q)}let S=p(e.Gu);function _(A){return x(A,S)}return{scalarMult:x,scalarMultBase:_,getSharedSecret:(A,O)=>x(A,O),getPublicKey:A=>_(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Vd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),jT=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),VG=BigInt(0),BN=BigInt(1),kw=BigInt(2),RN=BigInt(5),WT=BigInt(10),UN=BigInt(20),ON=BigInt(40),GT=BigInt(80);function zT(t){let e=Vd,n=t*t%e*t%e,i=ze(n,kw,e)*n%e,o=ze(i,BN,e)*t%e,s=ze(o,RN,e)*o%e,c=ze(s,WT,e)*s%e,a=ze(c,UN,e)*c%e,u=ze(a,ON,e)*a%e,d=ze(u,GT,e)*u%e,f=ze(d,GT,e)*u%e,h=ze(f,WT,e)*s%e;return{pow_p_5_8:ze(h,kw,e)*t%e,b2:n}}function YT(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function DN(t,e){let r=Vd,n=Be(e*e*e,r),i=Be(n*n*e,r),o=zT(t*i).pow_p_5_8,s=Be(t*n*o,r),c=Be(e*s*s,r),a=s,u=Be(s*jT,r),d=c===t,f=c===Be(-t,r),h=c===Be(-t*jT,r);return d&&(s=a),(f||h)&&(s=u),OT(s,r)&&(s=Be(-s,r)),{isValid:d||f,value:s}}var sn=Ka(Vd,void 0,!0),qd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:sn,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ow,randomBytes:Ld,adjustScalarBytes:YT,uvRatio:DN},Qo=cp(qd);function JT(t,e,r){if(e.length>255)throw new Error("Context is too big");return Jh(pw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var qG=cp({...qd,domain:JT}),FG=cp({...qd,domain:JT,prehash:Ow}),gc=FT({P:Vd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Vd,{pow_p_5_8:r,b2:n}=zT(t);return Be(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:YT,randomBytes:Ld});function ZT(t){let{y:e}=Qo.ExtendedPoint.fromHex(t),r=BigInt(1);return sn.toBytes(sn.create((r+e)*sn.inv(r-e)))}function XT(t){let e=qd.hash(t.subarray(0,32));return qd.adjustScalarBytes(e).subarray(0,32)}var kN=(sn.ORDER+BigInt(3))/BigInt(8),jG=sn.pow(kw,kN),WG=sn.sqrt(sn.neg(sn.ONE)),GG=(sn.ORDER-BigInt(5))/BigInt(8),zG=BigInt(486662);var YG=DT(sn,sn.neg(BigInt(486664)));var JG=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),ZG=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),XG=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),QG=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var ez=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var cn=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},NN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},It=class t{static bytesToPrivateKey(e){return cn(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Qo.getPublicKey(r),i={crv:"Ed25519",d:ne.uint8Array(r).toBase64Url(),kty:"OKP",x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return cn(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return cn(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=Qo.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertPrivateKeyToX25519(e){return cn(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=XT(n),o=gc.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:ne.uint8Array(i).toBase64Url(),x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static convertPublicKeyToX25519(e){return cn(this,arguments,void 0,function*({publicKey:r}){let n=yield t.publicKeyToBytes({publicKey:r});if(!(yield t.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let o=ZT(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static generateKey(){return cn(this,void 0,void 0,function*(){let e=Qo.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return cn(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,o=NN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return cn(this,arguments,void 0,function*({privateKey:r}){if(!ui(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return cn(this,arguments,void 0,function*({publicKey:r}){if(!Ha(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sign(e){return cn(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return Qo.sign(n,i)})}static validatePublicKey(e){return cn(this,arguments,void 0,function*({publicKeyBytes:r}){try{Qo.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return cn(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return Qo.verify(n,i,o)})}};var Fd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},ap=class extends ci{computePublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield It.computePublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Fd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield It.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield It.getPublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Fd(this,arguments,void 0,function*({key:r,data:n}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":return yield It.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Fd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ha(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(r.crv){case"Ed25519":return yield It.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};var ro=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Nw={Ed25519:{implementation:ap,names:["Ed25519"]},secp256k1:{implementation:$d,names:["ES256K","secp256k1"]},secp256r1:{implementation:$d,names:["ES256","secp256r1"]},"SHA-256":{implementation:Gh,names:["SHA-256"]}},Qt=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new lh}digest(e){return ro(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return ro(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return ro(this,arguments,void 0,function*({algorithm:r}){let i=yield this.getAlgorithm({algorithm:r}).generateKey({algorithm:r});if(i?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let o=`${Bw}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return ro(this,arguments,void 0,function*({key:r}){let n=yield ge({jwk:r});return`${Bw}${n}`})}getPublicKey(e){return ro(this,arguments,void 0,function*({keyUri:r}){let n=yield this.getPrivateKey({keyUri:r}),i=this.getAlgorithmName({key:n});return yield this.getAlgorithm({algorithm:i}).getPublicKey({key:n})})}importKey(e){return ro(this,arguments,void 0,function*({key:r}){var n;if(!HT(r))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let i=structuredClone(r);(n=i.kid)!==null&&n!==void 0||(i.kid=yield ge({jwk:i}));let o=yield this.getKeyUri({key:i});return yield this._keyStore.set(o,i),o})}sign(e){return ro(this,arguments,void 0,function*({keyUri:r,data:n}){let i=yield this.getPrivateKey({keyUri:r}),o=this.getAlgorithmName({key:i});return this.getAlgorithm({algorithm:o}).sign({data:n,key:i})})}verify(e){return ro(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=this.getAlgorithmName({key:r});return this.getAlgorithm({algorithm:o}).verify({key:r,signature:n,data:i})})}getAlgorithm({algorithm:e}){var r;let n=(r=Nw[e])===null||r===void 0?void 0:r.implementation;if(!n)throw new Error(`Algorithm not supported: ${e}`);return this._algorithmInstances.has(n)||this._algorithmInstances.set(n,new n),this._algorithmInstances.get(n)}getAlgorithmName({key:e}){let r=e.alg,n=e.crv;for(let i in Nw){let o=Nw[i];if(r&&o.names.includes(r))return i;if(n&&o.names.includes(n))return i}throw new Error(`Unable to determine algorithm based on provided input: alg=${r}, crv=${n}`)}getPrivateKey(e){return ro(this,arguments,void 0,function*({keyUri:r}){let n=yield this._keyStore.get(r);if(!n)throw new Error(`Key not found: ${r}`);return n})}};l();var up=class t{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return wT(e)}static randomUuid(){return Na.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let r=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let o=t.randomBytes(Math.ceil(e/2));n=new DataView(o.buffer).getUint16(0,!1)%i}while(n>r)}else{let i=Math.pow(10,10);do{let o=t.randomBytes(4);n=new DataView(o.buffer).getUint32(0,!1)%i}while(n>r)}return n.toString().padStart(e,"0")}};l();l();l();l();l();l();l();l();l();l();var es=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},CN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Va=class t{static bytesToPrivateKey(e){return es(this,arguments,void 0,function*({privateKeyBytes:r}){let n=gc.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return es(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return es(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=gc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static generateKey(){return es(this,void 0,void 0,function*(){let e=gc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return es(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,o=CN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return es(this,arguments,void 0,function*({privateKey:r}){if(!ui(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return es(this,arguments,void 0,function*({publicKey:r}){if(!Ha(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return es(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return gc.getSharedSecret(i,o)})}};l();l();l();function Mr(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Pw({didDocument:t}){var e,r;if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let n=[];return n.push(...(r=(e=t.verificationMethod)===null||e===void 0?void 0:e.filter(Lw))!==null&&r!==void 0?r:[]),Object.keys(Pi).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(Lw))!==null&&s!==void 0?s:[])}),n}function QT({didDocument:t}){let r=Pw({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function e_({didDocument:t,methodId:e}){let r=[];return Object.keys(Pi).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=Mr(e);i.some(c=>{let a=Mr(c)===o,u=Lw(c)&&Mr(c.id)===o;return a||u})&&r.push(n)}}),r}function t_(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Lw(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function Mw({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Yt.addPrefix({code:e,data:t,name:r}),i=ne.uint8Array(n).toBase58Btc();return ne.base58Btc(i).toMultibase()}function Kw({multibaseKeyId:t}){try{let e=ne.multibase(t).toBase58Btc(),r=ne.base58Btc(e).toUint8Array(),{code:n,data:i,name:o}=Yt.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:o}}catch{throw new re(ie.InvalidDid,`Invalid multibase identifier: ${t}`)}}var jd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},wr=class t{constructor({uri:e,document:r,metadata:n,keyManager:i}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=i}export(){return jd(this,void 0,void 0,function*(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let r=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.exportKey({keyUri:i});r.push(Object.assign({},o))}e.privateKeys=r}return e})}getSigner(e){return jd(this,void 0,void 0,function*(){var r;let n=(r=this.document.verificationMethod)===null||r===void 0?void 0:r.find(a=>{var u,d;return Mr(a.id)===((u=Mr(e?.methodId))!==null&&u!==void 0?u:Mr((d=this.document.assertionMethod)===null||d===void 0?void 0:d[0]))});if(!(n&&n.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.getPublicKey({keyUri:i}),s=this.keyManager;return{algorithm:up.getJoseSignatureAlgorithmFromPublicKey(o),keyId:n.id,sign(a){return jd(this,arguments,void 0,function*({data:u}){return yield s.sign({data:u,keyUri:i})})},verify(a){return jd(this,arguments,void 0,function*({data:u,signature:d}){return yield s.verify({data:u,key:o,signature:d})})}}})}static import(e){return jd(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){var i;let o=Pw({didDocument:r.document});if(o.length===0)throw new re(ie.InvalidDidDocument,"At least one verification method is required but 0 were given");for(let c of(i=r.privateKeys)!==null&&i!==void 0?i:[]){let a=yield n.getKeyUri({key:c});(yield n.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1))||(yield n.importKey({key:c}))}for(let c of o){if(!c.publicKeyJwk)throw new Error(`Verification method '${c.id}' does not contain a public key in JWK format`);let a=yield n.getKeyUri({key:c.publicKeyJwk});yield n.getPublicKey({keyUri:a})}return new t({uri:r.uri,document:r.document,metadata:r.metadata,keyManager:n})})}};l();l();l();l();l();var $w="0123456789abcdef",n_=[],r_=[];for(let t=0;t<256;t++)n_[t]=$w[t>>4&15]+$w[t&15],t<16&&(t<10?r_[48+t]=t:r_[87+t]=t);var Hw=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=n_[t[n++]];return r};var i_=(t,e=0)=>{let r=t.length||0;if(!e){let s=r;for(;s--;)e+=t[s].length}let n=new Uint8Array(e),i=e,o=r;for(;o--;)i-=t[o].length,n.set(t[o],i);return n};l();var o_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",PN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Wd=0;Wd<o_.length;Wd++)PN[o_.charCodeAt(Wd)]=Wd;var Wd;var MN=new TextDecoder,Vw=(t,e)=>e?new TextDecoder(e).decode(t):MN.decode(t),KN=new TextEncoder,an=t=>KN.encode(t);var s_=typeof window<"u"?window:self,c_=s_.crypto||s_.msCrypto||{},eJ=c_.subtle||c_.webkitSubtle;l();function qa(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function dp(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function Re(t,e,r){let n=[],i=null;return Re._encode(n,t),i=i_(n),Re.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Re.bytes=-1;Re._floatConversionDetected=!1;Re._encode=function(t,e){if(e!=null)switch(dp(e)){case"object":Re.dict(t,e);break;case"map":Re.dictMap(t,e);break;case"array":Re.list(t,e);break;case"set":Re.listSet(t,e);break;case"string":Re.string(t,e);break;case"number":Re.number(t,e);break;case"boolean":Re.number(t,e);break;case"arraybufferview":Re.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Re.buffer(t,new Uint8Array(e));break}};var fp=new Uint8Array([101]),a_=new Uint8Array([100]),u_=new Uint8Array([108]);Re.buffer=function(t,e){t.push(an(e.length+":"),e)};Re.string=function(t,e){t.push(an(an(e).byteLength+":"+e))};Re.number=function(t,e){if(Number.isInteger(e))return t.push(an("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(an("i"+o+"e")),o!==e&&!Re._floatConversionDetected&&(Re._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+o+'"'),console.trace())};Re.dict=function(t,e){t.push(a_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Re.string(t,n),Re._encode(t,e[n]));t.push(fp)};Re.dictMap=function(t,e){t.push(a_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Re._encode(t,n):Re.string(t,String(n)),Re._encode(t,e.get(n)));t.push(fp)};Re.list=function(t,e){let r=0,n=e.length;for(t.push(u_);r<n;r++)e[r]!=null&&Re._encode(t,e[r]);t.push(fp)};Re.listSet=function(t,e){t.push(u_);for(let r of e)r!=null&&Re._encode(t,r);t.push(fp)};var d_=Re;l();var $N=105,HN=58,VN=100,qN=108,qw=101;function f_(t,e,r){let n=0,i=1;for(let o=e;o<r;o++){let s=t[o];if(s<58&&s>=48){n=n*10+(s-48);continue}if(!(o===e&&s===43)){if(o===e&&s===45){i=-1;continue}if(s===46)break;throw new Error("not a number: buffer["+o+"] = "+s)}}return n*i}function de(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),de.position=0,de.encoding=n||null,de.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):an(t),de.bytes=de.data.length,de.next())}de.bytes=0;de.position=0;de.data=null;de.encoding=null;de.next=function(){switch(de.data[de.position]){case VN:return de.dictionary();case qN:return de.list();case $N:return de.integer();default:return de.buffer()}};de.find=function(t){let e=de.position,r=de.data.length,n=de.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};de.dictionary=function(){de.position++;let t={};for(;de.data[de.position]!==qw;){let e=de.buffer(),r=Vw(e);r.includes("\uFFFD")&&(r=Hw(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==qw;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find(qw),e=f_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find(HN),e=f_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?Vw(de.data.slice(t,r)):de.data.slice(t,r)};var l_=de;l();function FN(t){let e=2;for(let r of t)e+=lp(r);return e}function jN(t){let e=2;for(let[r,n]of t){let i=an(r).byteLength;e+=qa(i)+1+i,e+=lp(n)}return e}function WN(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=an(r[n]).byteLength;e+=qa(i)+1+i,e+=lp(t[r[n]])}return e}function GN(t){let e=an(t).byteLength;return qa(e)+1+e}function zN(t){let e=t.byteLength-t.byteOffset;return qa(e)+1+e}function lp(t){if(t==null)return 0;let r=dp(t);switch(r){case"arraybufferview":return zN(t);case"string":return GN(t);case"array":case"set":return FN(t);case"number":return 1+qa(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return WN(t);case"map":return jN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var Fw=lp;var YN=Fw,jw={encode:d_,decode:l_,byteLength:Fw,encodingLength:YN};l();l();var JN=/^(\d{1,3}\.){3,3}\d{1,3}$/;var ZN=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var Dn={name:"v4",size:4,isFormat:t=>JN.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let o=0;o<n;){let s=t.charCodeAt(o++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},no={name:"v6",size:16,isFormat:t=>t.length>0&&ZN.test(t),encode(t,e,r){r=~~r;let n=r+16,i=-1,o=0,s=0,c=!0,a=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(c?i!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(i=r):(a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2),o=0,s=0),c=!0,a=!1):d===46?(r<n&&(e[r]=s),r++,s=0,o=0,c=!1,a=!0):(c=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,s=s*10+d),o=(o<<4)+d)}if(c===!1)a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2);else if(i===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(i!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=i+2;u--)e[u]=e[u-2];e[i]=0,e[i+1]=0,i=r}if(i!==r&&i!==-1)for(r>n-2&&(r=n-2);n>i;)e[--n]=r<n&&r>i?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function h_(t){if(Dn.isFormat(t))return Dn.size;if(no.isFormat(t))return no.size;throw Error(`Invalid ip address: ${t}`)}function p_(t){return h_(t)===Dn.size?1:2}function y_(t,e,r){r=~~r;let n=h_(t);return typeof e=="function"&&(e=e(r+n)),n===Dn.size?Dn.encode(t,e,r):no.encode(t,e,r)}function g_(t,e,r){if(e=~~e,r=r||t.length-e,r===Dn.size)return Dn.decode(t,e,r);if(r===no.size)return no.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${Dn.size} for v4 or ${no.size} for v6.`)}l();function Gd(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t}function Fa(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}l();function m_(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t}l();function w_(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t}l();function Ww(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function Gw(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}l();function b_(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`}function zw(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}l();l();function Yw(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let i=t.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let o=n+1;o===r||i>=56320||(t.charCodeAt(o)&64512)!==56320?e+=3:(n=o,e+=4)}}return e}function ja(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(Yw(t)+r));let i=r;for(let o=0;o<n;o+=1){let s=t.charCodeAt(o);if(s<=127)e[i++]=s;else if(s<=2047)e[i++]=192|(s&1984)>>6,e[i++]=128|s&63;else if((s&63488)!==55296)e[i++]=224|(s&61440)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63;else{let c=o+1;if(c===n||s>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let a=t.charCodeAt(c);(a&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(o=c,s=65536|(s&1023)<<10|a&1023,e[i++]=240|(s&1835008)>>18,e[i++]=128|(s&258048)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63)}}}return ja.bytes=i-r,e}ja.bytes=0;function Wa(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let i=e;i<r;){let o=t[i++],s;if(o<=128)s=o;else if(o>191&&o<224)s=(o&31)<<6|t[i++]&63;else if(o>239&&o<365){s=((o&7)<<18|(t[i++]&63)<<12|(t[i++]&63)<<6|t[i++]&63)-65536;let c=55296|s>>10&1023;n+=String.fromCharCode(c),s=56320|s&1023}else s=(o&15)<<12|(t[i++]&63)<<6|t[i++]&63;n+=String.fromCharCode(s)}return Wa.bytes=r-e,n}Wa.bytes=0;var ts=t=>t instanceof Uint8Array;function io(t){return typeof t=="string"?Yw(t):t.byteLength}function hp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):ja(t)}function pp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return ja(e,t,r),ja.bytes}var zd={},x_=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),o=i.toUpperCase(),s=t<<4|n,c=`${e}${i}`;x_[s]=c,zd[c]=s,zd[`${r}${i}`]=s,zd[`${e}${o}`]=s,zd[`${r}${o}`]=s}}function E_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=x_[o]}return n}function Jw(t){return t.length>>>1}function v_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=zd[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var oC=Math.pow(2,24),sC=Math.pow(2,16),cC=Math.pow(2,8),di=(t,e)=>t[e]*oC+t[e+1]*sC+t[e+2]*cC+t[e+3],he=(t,e)=>t[e]<<8|t[e+1],fi=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),ae=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function br(t,e,r,n,i){return r<0&&(n-=r,r=0),n<0&&(n=0),i<0?new Uint8Array(0):r>=e.length||n>=i?0:aC(t,e,r,n,i)}function aC(t,e,r,n,i){i-n>e.length-r&&(i=n+e.length-r);let o=i-n,s=t.length-n;return o>s&&(o=s),(n!==0||i<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,o)),e.set(t,r),o}var dC=0,S_=32768,Xw=32768,fC=~Xw,T_=32768,lC=~T_;function He({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var se=He({encode(t,e,r){e||(e=new Uint8Array(se.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=i.split(".");for(let s=0;s<o.length;s++){let c=pp(e,o[s],r+1);e[r]=c,r+=c+1}}return e[r++]=0,se.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,i=0,o=0,s=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=s?0:1,c===0)break;if(c&192)if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let a=he(t,e-1)-49152;if(a>=n)throw new Error("Cannot decode name (bad pointer)");e=a,n=a,o+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");r.push(Wa(t,e,e+c)),e+=c,o+=s?0:c}}return se.decode.bytes=o,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:io(t.replace(/^\.|\.$/gm,""))+2}}),Bt=He({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=pp(e,t,r+1);return e[r]=n,Bt.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=Wa(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return io(t)+1}}),Ga=He({bytes:12,encode(t,e,r){e||(e=new Uint8Array(Ga.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?S_:dC;return ae(e,t.id||0,r),ae(e,n|i,r+2),ae(e,t.questions.length,r+4),ae(e,t.answers.length,r+6),ae(e,t.authorities.length,r+8),ae(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=he(t,e+2);return{id:he(t,e),type:r&S_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:w_(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:m_(r&15),questions:new Array(he(t,e+4)),answers:new Array(he(t,e+6)),authorities:new Array(he(t,e+8)),additionals:new Array(he(t,e+10))}},encodingLength(){return 12}}),gp=He({encode(t,e,r){e||(e=new Uint8Array(gp.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),br(t,e,r+2,0,n),gp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=t.slice(e+2,e+2+r);return gp.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),mp=He({encode(t,e,r){return e||(e=new Uint8Array(mp.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),mp.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=se.decode(t,e+2);return mp.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),wp=He({encode(t,e,r){e||(e=new Uint8Array(wp.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mname,e,r),r+=se.encode.bytes,se.encode(t.rname,e,r),r+=se.encode.bytes,fi(e,t.serial||0,r),r+=4,fi(e,t.refresh||0,r),r+=4,fi(e,t.retry||0,r),r+=4,fi(e,t.expire||0,r),r+=4,fi(e,t.minimum||0,r),r+=4,ae(e,r-n-2,n),wp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=se.decode(t,e),e+=se.decode.bytes,n.rname=se.decode(t,e),e+=se.decode.bytes,n.serial=di(t,e),e+=4,n.refresh=di(t,e),e+=4,n.retry=di(t,e),e+=4,n.expire=di(t,e),e+=4,n.minimum=di(t,e),e+=4,wp.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),bp=He({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=hp(t[i])),!ts(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(bp.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,br(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),bp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=[];for(;n>0;){let o=t[e++];if(--n,n<o)throw new Error("Buffer overflow");i.push(t.slice(e,e+o)),e+=o,n-=o}return bp.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=io(r)+1:e+=r.length+1}),e}}),xp=He({encode(t,e,r){e||(e=new Uint8Array(xp.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=hp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return br(t,e,r,0,i),r+=i,ae(e,r-n-2,n),xp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,xp.decode.bytes=e-r,i},encodingLength(t){return t?(ts(t)?t.length:io(t))+2:2}}),Ep=He({encode(t,e,r){e||(e=new Uint8Array(Ep.encodingLength(t))),r||(r=0);let n=r;return r+=2,Bt.encode(t.cpu,e,r),r+=Bt.encode.bytes,Bt.encode(t.os,e,r),r+=Bt.encode.bytes,ae(e,r-n-2,n),Ep.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Bt.decode(t,e),e+=Bt.decode.bytes,n.os=Bt.decode(t,e),e+=Bt.decode.bytes,Ep.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),Ja=He({encode(t,e,r){return e||(e=new Uint8Array(Ja.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),Ja.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return Ja.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),vp=He({encode(t,e,r){e||(e=new Uint8Array(vp.encodingLength(t))),r||(r=0),ae(e,t.priority||0,r+2),ae(e,t.weight||0,r+4),ae(e,t.port||0,r+6),se.encode(t.target,e,r+8);let n=se.encode.bytes+6;return ae(e,n,r),vp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n={};return n.priority=he(t,e+2),n.weight=he(t,e+4),n.port=he(t,e+6),n.target=se.decode(t,e+8),vp.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),rs=He({encode(t,e,r){let n=rs.encodingLength(t);return e||(e=new Uint8Array(rs.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=rs.ISSUER_CRITICAL),ae(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Bt.encode(t.tag,e,r),r+=Bt.encode.bytes,pp(e,t.value,r),r+=io(t.value),rs.encode.bytes=n,e},decode(t,e){e||(e=0);let r=he(t,e);e+=2;let n=e,i={};return i.flags=t[e],e+=1,i.tag=Bt.decode(t,e),e+=Bt.decode.bytes,i.value=Wa(t,e,n+r),i.issuerCritical=!!(i.flags&rs.ISSUER_CRITICAL),rs.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});rs.ISSUER_CRITICAL=128;var Sp=He({encode(t,e,r){e||(e=new Uint8Array(Sp.encodingLength(t))),r||(r=0);let n=r;return r+=2,ae(e,t.preference||0,r),r+=2,se.encode(t.exchange,e,r),r+=se.encode.bytes,ae(e,r-n-2,n),Sp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=he(t,e),e+=2,n.exchange=se.decode(t,e),e+=se.decode.bytes,Sp.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),__=He({encode(t,e,r){return e||(e=new Uint8Array(__.encodingLength(t))),r||(r=0),ae(e,4,r),r+=2,Dn.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,Dn.decode(t,e)},bytes:6}),Ap=He({encode(t,e,r){return e||(e=new Uint8Array(Ap.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,no.encode(t,e,r),Ap.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=no.decode(t,e);return Ap.decode.bytes=18,r},bytes:18}),A_=t=>new Uint8Array(t),oo=He({encode(t,e,r){e||(e=new Uint8Array(oo.encodingLength(t))),r||(r=0);let n=r,i=zw(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,br(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||p_(t.ip,A_),c=y_(t.ip,A_),a=Math.ceil(o/8);ae(e,a+4,r),r+=2,ae(e,s,r),r+=2,e[r++]=o,e[r++]=t.scopePrefixLength||0,br(c,e,r,0,a),r+=a}break;case 11:t.timeout?(ae(e,2,r),r+=2,ae(e,t.timeout,r),r+=2):(ae(e,0,r),r+=2);break;case 12:{let o=t.length||0;ae(e,o,r),r+=2,e.fill(0,r,r+o),r+=o}break;case 14:{let o=t.tags.length*2;ae(e,o,r),r+=2;for(let s of t.tags)ae(e,s,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return oo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=he(t,e),r.type=b_(r.code),e+=2;let n=he(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=he(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);br(t,i,0,e,e+n-4),r.ip=g_(i)}break;case 11:n>0&&(r.timeout=he(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(he(t,e)),e+=2}return oo.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(zw(t.code)){case 8:{let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),ns=He({encode(t,e,r){e||(e=new Uint8Array(ns.encodingLength(t))),r||(r=0);let n=r,i=Ya(t,oo);return ae(e,i,r),r=ef(t,oo,e,r+2),ns.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=he(t,e);e+=2;let o=0;for(;i>0;)n[o++]=oo.decode(t,e),e+=oo.decode.bytes,i-=oo.decode.bytes;return ns.decode.bytes=e-r,n},encodingLength(t){return 2+Ya(t||[],oo)}}),li=He({encode(t,e,r){e||(e=new Uint8Array(li.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!ts(i))throw new Error("Key must be a Buffer");return r+=2,ae(e,t.flags,r),r+=2,e[r]=li.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,br(i,e,r,0,i.length),r+=i.length,li.encode.bytes=r-n,ae(e,li.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);if(e+=2,n.flags=he(t,e),e+=2,t[e]!==li.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,li.decode.bytes=e-r,n},encodingLength(t){return 6+io(t.key)}});li.PROTOCOL_DNSSEC=3;li.ZONE_KEY=128;li.SECURE_ENTRYPOINT=32768;var Yd=He({encode(t,e,r){e||(e=new Uint8Array(Yd.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!ts(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Fa(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,fi(e,t.originalTTL,r),r+=4,fi(e,t.expiration,r),r+=4,fi(e,t.inception,r),r+=4,ae(e,t.keyTag,r),r+=2,se.encode(t.signersName,e,r),r+=se.encode.bytes,br(i,e,r,0,i.length),r+=i.length,Yd.encode.bytes=r-n,ae(e,Yd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.typeCovered=Gd(he(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=di(t,e),e+=4,n.expiration=di(t,e),e+=4,n.inception=di(t,e),e+=4,n.keyTag=he(t,e),e+=2,n.signersName=se.decode(t,e),e+=se.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,Yd.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+io(t.signature)}}),Jd=He({encode(t,e,r){e||(e=new Uint8Array(Jd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mbox||".",e,r),r+=se.encode.bytes,se.encode(t.txt||".",e,r),r+=se.encode.bytes,Jd.encode.bytes=r-n,ae(e,Jd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=se.decode(t,e)||".",e+=se.decode.bytes,n.txt=se.decode(t,e)||".",e+=se.decode.bytes,Jd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Kr=He({encode(t,e,r){e||(e=new Uint8Array(Kr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Fa(t[o]);i[s>>8]===void 0&&(i[s>>8]=[]),i[s>>8][s>>3&31]|=1<<7-(s&7)}for(let o=0;o<i.length;o++)if(i[o]!==void 0){let s=hp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,br(s,e,r,0,s.length),r+=s.length}return Kr.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,i=[];for(;e-n<r;){let o=t[e];e+=1;let s=t[e];e+=1;for(let c=0;c<s;c++){let a=t[e+c];for(let u=0;u<8;u++)if(a&1<<7-u){let d=Gd(o<<8|c<<3|u);i.push(d)}}e+=s}return Kr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Fa(t[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),Zd=He({encode(t,e,r){e||(e=new Uint8Array(Zd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Kr.encode(t.rrtypes,e,r),r+=Kr.encode.bytes,Zd.encode.bytes=r-n,ae(e,Zd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.nextDomain=se.decode(t,e),e+=se.decode.bytes,n.rrtypes=Kr.decode(t,e,i-(e-r)),e+=Kr.decode.bytes,Zd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Kr.encodingLength(t.rrtypes)}}),Xd=He({encode(t,e,r){e||(e=new Uint8Array(Xd.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!ts(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!ts(o))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,ae(e,t.iterations,r),r+=2,e[r]=i.length,r+=1,br(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,br(o,e,r,0,o.length),r+=o.length,Kr.encode(t.rrtypes,e,r),r+=Kr.encode.bytes,Xd.encode.bytes=r-n,ae(e,Xd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=he(t,e),e+=2;let o=t[e];e+=1,n.salt=t.slice(e,e+o),e+=o;let s=t[e];return e+=1,n.nextDomain=t.slice(e,e+s),e+=s,n.rrtypes=Kr.decode(t,e,i-(e-r)),e+=Kr.decode.bytes,Xd.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Kr.encodingLength(t.rrtypes)}}),Qd=He({encode(t,e,r){e||(e=new Uint8Array(Qd.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!ts(i))throw new Error("Digest must be a Buffer");return r+=2,ae(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,br(i,e,r,0,i.length),r+=i.length,Qd.encode.bytes=r-n,ae(e,Qd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.keyTag=he(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,Qd.decode.bytes=e-r,n},encodingLength(t){return 6+io(t.digest)}}),za=He({encode(t,e,r){e||(e=new Uint8Array(za.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=Jw(t.fingerprint),o=Qw(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return v_(e,t.fingerprint,r,r+=i),za.encode.bytes=r-n,ae(e,za.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let i=Qw(n.hash);return n.fingerprint=E_(t,e,e+i),e+=i,za.decode.bytes=e-r,n},encodingLength(t){return 4+Jw(t.fingerprint)}});function Qw(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}za.getFingerprintLengthForHashType=Qw;function Zw(t){switch(t.toUpperCase()){case"A":return __;case"PTR":return Ja;case"CNAME":return Ja;case"DNAME":return Ja;case"TXT":return bp;case"NULL":return xp;case"AAAA":return Ap;case"SRV":return vp;case"HINFO":return Ep;case"CAA":return rs;case"NS":return mp;case"SOA":return wp;case"MX":return Sp;case"OPT":return ns;case"DNSKEY":return li;case"RRSIG":return Yd;case"RP":return Jd;case"NSEC":return Zd;case"NSEC3":return Xd;case"SSHFP":return za;case"DS":return Qd}return gp}var un=He({encode(t,e,r){e||(e=new Uint8Array(un.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Fa(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");ae(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,ae(e,t.flags||0,r+6),r+=8,ns.encode(t.options||[],e,r),r+=ns.encode.bytes}else{let i=Gw(t.class===void 0?"IN":t.class);t.flush&&(i|=Xw),ae(e,i,r+2),fi(e,t.ttl||0,r+4),r+=8;let o=Zw(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return un.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=se.decode(t,e),e+=se.decode.bytes,r.type=Gd(he(t,e)),r.type==="OPT")r.udpPayloadSize=he(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=he(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=ns.decode(t,e+8),e+=8+ns.decode.bytes;else{let i=he(t,e+2);r.ttl=di(t,e+4),r.class=Ww(i&fC),r.flush=!!(i&Xw);let o=Zw(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return un.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return se.encodingLength(t.name)+8+Zw(t.type).encodingLength(e)}}),Za=He({encode(t,e,r){e||(e=new Uint8Array(Za.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Fa(t.type),r),r+=2,ae(e,Gw(t.class===void 0?"IN":t.class),r),r+=2,Za.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=se.decode(t,e),e+=se.decode.bytes,n.type=Gd(he(t,e)),e+=2,n.class=Ww(he(t,e)),e+=2,!!(n.class&T_)&&(n.class&=lC),Za.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var I_=1024;var qt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(hC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Ga.encode(t,e,r),r+=Ga.encode.bytes,r=ef(t.questions,Za,e,r),r=ef(t.answers,un,e,r),r=ef(t.authorities,un,e,r),r=ef(t.additionals,un,e,r),qt.encode.bytes=r-i,n&&tf.bytes!==e.length?e.slice(0,tf.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=Ga.decode(t,e);return e+=Ga.decode.bytes,e=yp(n.questions,Za,t,e),e=yp(n.answers,un,t,e),e=yp(n.authorities,un,t,e),e=yp(n.additionals,un,t,e),qt.decode.bytes=e-r,n},encodingLength:function(t){return Ga.encodingLength(t)+Ya(t.questions||[],Za)+Ya(t.answers||[],un)+Ya(t.authorities||[],un)+Ya(t.additionals||[],un)}};qt.encode.bytes=0;qt.decode.bytes=0;function Tp(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}var _p={encode:function(t,e,r){return e=qt.encode(Tp(t,"query"),e,r),_p.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return _p.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Tp(t,"query"))}};_p.encode.bytes=0;_p.decode.bytes=0;var Ip={encode:function(t,e,r){return e=qt.encode(Tp(t,"response"),e,r),Ip.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Ip.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Tp(t,"response"))}};Ip.encode.bytes=0;Ip.decode.bytes=0;var tf=qt.encode,Bp=qt.decode,hC=qt.encodingLength;function B_(t){let e=tf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),br(e,r,2,0,e.length),B_.bytes=r.byteLength,r}B_.bytes=0;function R_(t){let e=he(t,0);if(t.byteLength<e+2)return null;let r=Bp(t.slice(2));return R_.bytes=Bp.bytes,r}R_.bytes=0;function Ya(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function ef(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}function yp(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}l();var U_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},dn=class{static getSigningMethod(e){return U_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return U_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")})}};var Ct=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},O_=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},D_="https://diddht.tbddev.org",pC=0,is=7200,Rp=";",sr=",",eb;(function(t){t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution"})(eb||(eb={}));var cr;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(cr||(cr={}));var tb;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(tb||(tb={}));var N_={Ed25519:cr.Ed25519,ES256K:cr.secp256k1,ES256:cr.secp256r1,"P-256":cr.secp256r1,secp256k1:cr.secp256k1,secp256r1:cr.secp256r1,X25519:cr.X25519},k_={[cr.Ed25519]:"EdDSA",[cr.secp256k1]:"ES256K",[cr.secp256r1]:"ES256",[cr.X25519]:"ECDH-ES+A256KW"},rf=class t extends dn{static create(){return Ct(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s,c,a,u,d,f,h,p;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in N_)))throw new Error("One or more verification method algorithms are not supported");let g=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(g&&g.length!==new Set(g).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let y=yield e.generateKey({algorithm:"Ed25519"}),x=yield e.getPublicKey({keyUri:y}),S=yield Nt.identityKeyToIdentifier({identityKey:x}),_=Object.assign(Object.assign({id:S},r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs}),r.controllers&&{controller:r.controllers}),A=[...(s=r.verificationMethods)!==null&&s!==void 0?s:[]];A?.some(T=>{var M;return((M=T.id)===null||M===void 0?void 0:M.split("#").pop())==="0"})||A.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let T of A){let M=T.id&&T.id.split("#").pop()==="0"?y:yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M}),j=(a=(c=T.id)!==null&&c!==void 0?c:q.kid)!==null&&a!==void 0?a:yield ge({jwk:q});j=`${S}#${Mr(j)}`,(u=_.verificationMethod)!==null&&u!==void 0||(_.verificationMethod=[]),_.verificationMethod.push({id:j,type:"JsonWebKey",controller:(d=T.controller)!==null&&d!==void 0?d:S,publicKeyJwk:q});for(let $ of(f=T.purposes)!==null&&f!==void 0?f:[])_[$]||(_[$]=[]),_[$].push(j)}(h=r.services)===null||h===void 0||h.forEach(T=>{var M;(M=_.service)!==null&&M!==void 0||(_.service=[]),T.id=`${S}#${T.id.split("#").pop()}`,_.service.push(T)});let O=new wr({uri:S,document:_,metadata:Object.assign({published:!1},r.types&&{types:r.types}),keyManager:e});if(!((p=r.publish)!==null&&p!==void 0)||p){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static import(e){return Ct(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield wr.import({portableDid:r,keyManager:n});if(!(!((i=s.document.verificationMethod)===null||i===void 0)&&i.some(c=>{var a;return((a=c.id)===null||a===void 0?void 0:a.split("#").pop())==="0"})))throw new re(ie.InvalidDidDocument,"DID document must contain an Identity Key");return s})}static getSigningMethod(e){return Ct(this,arguments,void 0,function*({didDocument:r,methodId:n="#0"}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a,u;return Mr(c.id)===((a=Mr(n))!==null&&a!==void 0?a:Mr((u=r.assertionMethod)===null||u===void 0?void 0:u[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static publish(e){return Ct(this,arguments,void 0,function*({did:r,gatewayUri:n=D_}){return yield Up.put({did:r,gatewayUri:n})})}static resolve(e){return Ct(this,arguments,void 0,function*(r,n={}){var i;let o=(i=n?.gatewayUri)!==null&&i!==void 0?i:D_;try{yield Nt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Up.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},pt),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},pt),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};rf.methodName="dht";var Up=class t{static get(e){return Ct(this,arguments,void 0,function*({didUri:r,gatewayUri:n}){let i=Nt.identifierToIdentityKeyBytes({didUri:r}),o=yield t.pkarrGet({gatewayUri:n,publicKeyBytes:i}),s=yield Nt.parseBep44GetMessage({bep44Message:o}),c=yield t.fromDnsPacket({didUri:r,dnsPacket:s});return c.didDocumentMetadata.versionId=o.seq.toString(),c})}static put(e){return Ct(this,arguments,void 0,function*({did:r,gatewayUri:n}){let i=yield t.toDnsPacket({didDocument:r.document,didMetadata:r.metadata,authoritativeGatewayUris:[n]}),o=yield Nt.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Nt.identifierToIdentityKeyBytes({didUri:r.uri}),signer:yield r.getSigner({methodId:"0"})}),s=yield t.pkarrPut({gatewayUri:n,bep44Message:o});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:s,versionId:o.seq.toString()}),didRegistrationMetadata:{}}})}static pkarrGet(e){return Ct(this,arguments,void 0,function*({gatewayUri:r,publicKeyBytes:n}){let i=ne.uint8Array(n).toBase32Z(),o=new URL(i,r).href,s;try{if(s=yield fetch(o,{method:"GET"}),!s.ok)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`)}catch(u){throw u instanceof re?u:new re(ie.InternalError,`Failed to fetch Pkarr record: ${u.message}`)}let c=yield s.arrayBuffer();if(!c)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`);if(c.byteLength<72)throw new re(ie.InvalidDidDocumentLength,`Pkarr response must be at least 72 bytes but got: ${c.byteLength}`);if(c.byteLength>1072)throw new re(ie.InvalidDidDocumentLength,`Pkarr response exceeds 1000 byte limit: ${c.byteLength}`);return{k:n,seq:Number(new DataView(c).getBigUint64(64)),sig:new Uint8Array(c,0,64),v:new Uint8Array(c,72)}})}static pkarrPut(e){return Ct(this,arguments,void 0,function*({gatewayUri:r,bep44Message:n}){let i=ne.uint8Array(n.k).toBase32Z(),o=new URL(i,r).href,s=new Uint8Array(n.v.length+72);s.set(n.sig,0),new DataView(s.buffer).setBigUint64(n.sig.length,BigInt(n.seq)),s.set(n.v,n.sig.length+8);let c;try{c=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s})}catch(a){throw new re(ie.InternalError,`Failed to put Pkarr record for identifier ${i}: ${a.message}`)}return c.ok})}static fromDnsPacket(e){return Ct(this,arguments,void 0,function*({didUri:r,dnsPacket:n}){var i,o,s;let c={id:r},a={published:!0},u=new Map;for(let d of(i=n?.answers)!==null&&i!==void 0?i:[]){if(d.type!=="TXT")continue;let f=d.name.split(".")[0].substring(1);switch(!0){case f.startsWith("aka"):{let h=Nt.parseTxtDataToString(d.data);c.alsoKnownAs=h.split(sr);break}case f.startsWith("cnt"):{let h=Nt.parseTxtDataToString(d.data);c.controller=h.includes(sr)?h.split(sr):h;break}case f.startsWith("k"):{let{id:h,t:p,k:g,c:y,a:x}=Nt.parseTxtDataToObject(d.data),S=ne.base64Url(g).toUint8Array(),_=cr[Number(p)],A=yield Nt.keyConverter(_).bytesToPublicKey({publicKeyBytes:S});A.alg=x||k_[Number(p)];let O=f==="k0"?"0":h!==void 0?h:yield ge({jwk:A});(o=c.verificationMethod)!==null&&o!==void 0||(c.verificationMethod=[]);let T=`${r}#${O}`;c.verificationMethod.push({id:T,type:"JsonWebKey",controller:y??r,publicKeyJwk:A}),u.set(f,T);break}case f.startsWith("s"):{let h=Nt.parseTxtDataToObject(d.data),{id:p,t:g,se:y}=h,x=O_(h,["id","t","se"]),S=y.includes(sr)?y.split(sr):[y],_=Object.fromEntries(Object.entries(x).map(([A,O])=>[A,O.includes(sr)?O.split(sr):O]));(s=c.service)!==null&&s!==void 0||(c.service=[]),c.service.push(Object.assign(Object.assign({},_),{id:`${r}#${p}`,type:g,serviceEndpoint:S}));break}case f.startsWith("typ"):{let{id:h}=Nt.parseTxtDataToObject(d.data);a.types=h.split(sr).map(p=>Number(p));break}case f.startsWith("did"):{let h=_=>_.split(sr).map(A=>u.get(A)).filter(A=>typeof A=="string"),{auth:p,asm:g,del:y,inv:x,agm:S}=Nt.parseTxtDataToObject(d.data);p&&(c.authentication=h(p)),g&&(c.assertionMethod=h(g)),y&&(c.capabilityDelegation=h(y)),x&&(c.capabilityInvocation=h(x)),S&&(c.keyAgreement=h(S));break}}}return{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{}}})}static toDnsPacket(e){return Ct(this,arguments,void 0,function*({didDocument:r,didMetadata:n,authoritativeGatewayUris:i,previousDidProof:o}){var s,c,a,u,d;let f=[],h=[],p=new Map,g=[],y=[];if(o!==void 0){let{signature:_,previousDid:A}=o;yield Nt.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:is,data:`id=${A};s=${_}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:is,data:r.alsoKnownAs.join(sr)}),r.controller){let _=Array.isArray(r.controller)?r.controller.join(sr):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:is,data:_})}for(let[_,A]of(c=(s=r.verificationMethod)===null||s===void 0?void 0:s.entries())!==null&&c!==void 0?c:[]){let O=`k${_}`;y.push(O);let T=A.id.split("#").pop();p.set(T,O);let M=A.publicKeyJwk;if(!(M?.crv&&M.crv in N_))throw new re(ie.InvalidPublicKeyType,`Verification method '${A.id}' contains an unsupported key type: ${(a=M?.crv)!==null&&a!==void 0?a:"undefined"}`);let q=cr[M.crv],j=yield Nt.keyConverter(M.crv).publicKeyToBytes({publicKey:M}),$=ne.uint8Array(j).toBase64Url(),X=[`t=${q}`,`k=${$}`];T!=="0"&&(yield ge({jwk:M}))!==T&&X.unshift(`id=${T}`),M.alg!==k_[q]&&X.push(`a=${M.alg}`),A.controller!==r.id&&X.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:is,data:X.join(Rp)})}(u=r.service)===null||u===void 0||u.forEach((_,A)=>{let O=`s${A}`;g.push(O);let{id:T,type:M,serviceEndpoint:q}=_,j=O_(_,["id","type","serviceEndpoint"]);T=Mr(T),q=Array.isArray(q)?q.join(","):q;let X=Object.entries(Object.assign({id:T,t:M,se:q},j)).map(([G,I])=>`${G}=${I}`).join(Rp),Q=Nt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:is,data:Q})});let x=[`v=${pC}`];if(y.length&&x.push(`vm=${y.join(sr)}`),Object.keys(Pi).forEach(_=>{var A;let O=(A=r[_])===null||A===void 0?void 0:A.map(T=>p.get(T.split("#").pop()));if(O){let T=tb[_];x.push(`${T}=${O.join(sr)}`)}}),g.length&&x.push(`svc=${g.join(sr)}`),!((d=n.types)===null||d===void 0)&&d.length){let A=n.types.map(O=>typeof O=="string"?eb[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:is,data:`id=${A.join(sr)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:is,data:x.join(Rp)});for(let _ of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:is,data:_+"."});return{id:0,type:"response",flags:I_,answers:[...f,...h]}})}static getUniqueDidSuffix(e){return e.split(":")[2]}},Nt=class t{static createBep44PutMessage(e){return Ct(this,arguments,void 0,function*({dnsPacket:r,publicKeyBytes:n,signer:i}){let o=Math.ceil(Date.now()/1e3),s=tf(r),c=jw.encode({seq:o,v:s}).subarray(1,-1);if(c.length>1e3)throw new re(ie.InvalidDidDocumentLength,`DNS packet exceeds the 1000 byte maximum size: ${c.length} bytes`);let a=yield i.sign({data:c});return{k:n,seq:o,sig:a,v:s}})}static identifierToIdentityKey(e){return Ct(this,arguments,void 0,function*({didUri:r}){let n=t.identifierToIdentityKeyBytes({didUri:r});return yield It.bytesToPublicKey({publicKeyBytes:n})})}static identifierToIdentityKeyBytes({didUri:e}){let r=me.parse(e);if(!r)throw new re(ie.InvalidDid,`Invalid DID URI: ${e}`);if(r.method!==rf.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${r.method}`);let n;try{n=ne.base32Z(r.id).toUint8Array()}catch{throw new re(ie.InvalidPublicKey,"Failed to decode method-specific identifier")}if(n.length!==32)throw new re(ie.InvalidPublicKeyLength,`Invalid public key length: ${n.length}`);return n}static identityKeyToIdentifier(e){return Ct(this,arguments,void 0,function*({identityKey:r}){let n=yield It.publicKeyToBytes({publicKey:r}),i=ne.uint8Array(n).toBase32Z();return`did:${rf.methodName}:${i}`})}static keyConverter(e){let n={Ed25519:It,"P-256":{publicKeyToBytes:i=>Ct(this,[i],void 0,function*({publicKey:o}){let s=yield Vt.publicKeyToBytes({publicKey:o});return yield Vt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Vt.bytesToPublicKey,privateKeyToBytes:Vt.privateKeyToBytes,bytesToPrivateKey:Vt.bytesToPrivateKey},secp256k1:{publicKeyToBytes:i=>Ct(this,[i],void 0,function*({publicKey:o}){let s=yield kt.publicKeyToBytes({publicKey:o});return yield kt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:kt.bytesToPublicKey,privateKeyToBytes:kt.privateKeyToBytes,bytesToPrivateKey:kt.bytesToPrivateKey},X25519:Va}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static parseBep44GetMessage(e){return Ct(this,arguments,void 0,function*({bep44Message:r}){let n=yield It.bytesToPublicKey({publicKeyBytes:r.k}),i=jw.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!(yield It.verify({key:n,signature:r.sig,data:i})))throw new re(ie.InvalidSignature,"Invalid signature for DHT BEP44 message");return Bp(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(Rp).reduce((r,n)=>{let[i,o]=n.split("=");return r[i]=o,r},{})}static parseTxtDataToString(e){if(typeof e=="string")return e;if(e instanceof Uint8Array)return ne.uint8Array(e).toString();if(Array.isArray(e))return e.map(r=>this.parseTxtDataToString(r)).join("");throw new re(ie.InternalError,"Pkarr returned DNS TXT record with invalid data type")}static validatePreviousDidProof(e){return Ct(this,arguments,void 0,function*({newDid:r,previousDidProof:n}){let i=yield t.identifierToIdentityKey({didUri:n.previousDid}),o=t.identifierToIdentityKeyBytes({didUri:r}),s=ne.base64Url(n.signature).toUint8Array();if(!(yield It.verify({key:i,data:o,signature:s})))throw new re(ie.InvalidPreviousDidProof,"The previous DID proof is invalid.")})}static chunkDataIfNeeded(e){if(e.length<=255)return e;let r=[];for(let n=0;n<e.length;n+=255)r.push(e.slice(n,n+255));return r}};l();l();l();l();l();var Ye={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"};l();var Me=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var eZ=new Uint8Array(0);var rb=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};l();var nb=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},ib=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),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 C_(this,e)}},ob=class{constructor(e){this.decoders=e}or(e){return C_(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},C_=(t,e)=>new ob({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),sb=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new nb(e,r,n),this.decoder=new ib(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},yC=({name:t,prefix:e,encode:r,decode:n})=>new sb(t,e,r,n);var gC=(t,e,r,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s},mC=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o},nf=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>yC({prefix:e,name:t,encode(i){return mC(i,n,r)},decode(i){return gC(i,n,r,t)}});var fZ=nf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lZ=nf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),of=nf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hZ=nf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var xr=class t{static encode(e){return of.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Me(Ye.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return of.baseDecode(e)}static decodeAsString(e,r){let n=t.decodeAsBytes(e,r);return t.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}};l();var W_=Mn(P_(),1);l();l();var cb;(function(t){t.Public="public",t.Private="private"})(cb||(cb={}));var $r=cb;var Rt=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===$r.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Me(Ye.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Me(Ye.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Me(Ye.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Me(Ye.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Me(Ye.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===$r.Private&&(e.d===void 0||e.d.length!==43))throw new Me(Ye.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Me(Ye.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!xr.isBase64UrlString(e))throw new Me(Ye.IdNotUsingBase64UrlCharacterSet,`Key ID '${e}' is not a Base64URL string.`)}static validatePublicKeyPurposes(e){if(e===void 0)return;let r=new Set;for(let n of e){if(r.has(n))throw new Me(Ye.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var sf=class{};sf.hashAlgorithmInMultihashCode=18;sf.maxCanonicalizedDeltaSizeInBytes=1e3;var ar=sf;l();var $_=Mn(K_(),1);var kn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=$_.default(r);return xr.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?t.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}};l();l();l();l();var wC=q_,H_=128,bC=127,xC=~bC,EC=Math.pow(2,31);function q_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=EC;)e[r++]=t&255|H_,t/=128;for(;t&xC;)e[r++]=t&255|H_,t>>>=7;return e[r]=t|0,q_.bytes=r-n+1,e}var vC=ab,SC=128,V_=127;function ab(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw ab.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&V_)<<i:(s&V_)*Math.pow(2,i),i+=7}while(s>=SC);return ab.bytes=o-n,r}var AC=Math.pow(2,7),TC=Math.pow(2,14),_C=Math.pow(2,21),IC=Math.pow(2,28),BC=Math.pow(2,35),RC=Math.pow(2,42),UC=Math.pow(2,49),OC=Math.pow(2,56),DC=Math.pow(2,63),kC=function(t){return t<AC?1:t<TC?2:t<_C?3:t<IC?4:t<BC?5:t<RC?6:t<UC?7:t<OC?8:t<DC?9:10},NC={encode:wC,decode:vC,encodingLength:kC},CC=NC,cf=CC;var ub=(t,e=0)=>[cf.decode(t,e),cf.decode.bytes],db=(t,e,r=0)=>(cf.encode(t,e,r),e),fb=t=>cf.encodingLength(t);var lb=(t,e)=>{let r=e.byteLength,n=fb(t),i=n+fb(r),o=new Uint8Array(i+r);return db(t,o,0),db(r,o,n),o.set(e,i),new Dp(t,r,e,o)},F_=t=>{let e=rb(t),[r,n]=ub(e),[i,o]=ub(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Dp(r,i,s,e)};var Dp=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var pb=({name:t,code:e,encode:r})=>new hb(t,e,r),hb=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?lb(this.code,r):r.then(n=>lb(this.code,n))}else throw Error("Unknown type, must be binary type")}};var j_=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),kp=pb({name:"sha2-256",code:18,encode:j_("SHA-256")}),GZ=pb({name:"sha2-512",code:19,encode:j_("SHA-512")});var af=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Lt=class t{static hash(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield kp.digest(e)).bytes;break;default:throw new Me(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield kp.encode(e);break;default:throw new Me(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=kn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=kn.canonicalizeAsBytes(e),i=yield t.hashAsNonMultihashBytes(n,r);return yield t.hashThenEncode(i,r)})}static hashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return xr.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=xr.decodeAsBytes(e,r);try{n=F_(i)}catch{throw new Me(Ye.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=ar.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Me(Ye.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var yb;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(yb||(yb={}));var uf=yb;l();var gb;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(gb||(gb={}));var mc=gb;var Np=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},os=class t{static createCreateRequest(e){return Np(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;Rt.validateEs256kOperationKey(r,$r.Public),Rt.validateEs256kOperationKey(n,$r.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=ar.hashAlgorithmInMultihashCode,c=[{action:mc.Replace,document:e.document}],a={updateCommitment:yield Lt.canonicalizeThenDoubleHashThenEncode(n,s),patches:c};t.validateDeltaSize(a);let d={deltaHash:yield Lt.canonicalizeThenHashThenEncode(a,s),recoveryCommitment:yield Lt.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:uf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Np(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,$r.Public);let r=ar.hashAlgorithmInMultihashCode,n=yield Lt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},o=yield e.signer.sign({alg:"ES256K"},i);return{type:uf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return Np(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,$r.Public),Rt.validateEs256kOperationKey(e.nextRecoveryPublicKey,$r.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,$r.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=ar.hashAlgorithmInMultihashCode,n=yield Lt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:mc.Replace,document:e.document}],o=yield Lt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:o},c=yield Lt.canonicalizeThenHashThenEncode(s,r),u={recoveryCommitment:yield Lt.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:c},d=yield e.signer.sign({alg:"ES256K"},u);return{type:uf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return Np(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.updatePublicKey,$r.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,$r.Public),t.validateServices(e.servicesToAdd),t.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let g of e.idsOfServicesToRemove)Rt.validateId(g);if(e.idsOfPublicKeysToRemove!==void 0)for(let g of e.idsOfPublicKeysToRemove)Rt.validateId(g);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let g={action:mc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:mc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:mc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:mc.RemovePublicKeys,ids:s};r.push(g)}let c=ar.hashAlgorithmInMultihashCode,a=yield Lt.canonicalizeThenHashThenEncode(e.updatePublicKey,c),u=yield Lt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,c),d={patches:r,updateCommitment:u},f=yield Lt.canonicalizeThenHashThenEncode(d,c),h={updateKey:e.updatePublicKey,deltaHash:f},p=yield e.signer.sign({alg:"ES256K"},h);return{type:uf.Update,didSuffix:e.didSuffix,revealValue:a,delta:d,signedData:p}})}static validateDidSuffix(e){Lt.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Me(Ye.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Rt.validateId(n.id),r.has(n.id))throw new Me(Ye.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),Rt.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(t.validateService(n),r.has(n.id))throw new Me(Ye.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){Rt.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new Me(Ye.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Me(Ye.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&W_.parse(e.serviceEndpoint).error!==void 0)throw new Me(Ye.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=kn.canonicalizeAsBytes(e);if(r.length>ar.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${ar.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Me(Ye.DeltaExceedsMaximumSize,n)}}};var G_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Xa=class t{static createLongFormDid(e){return G_(this,void 0,void 0,function*(){let r=yield os.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;ar.network===void 0||ar.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${ar.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=kn.canonicalizeAsBytes(o),c=xr.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return G_(this,void 0,void 0,function*(){let r=kn.canonicalizeAsBytes(e),n=yield Lt.hash(r,ar.hashAlgorithmInMultihashCode);return xr.encode(n)})}};l();l();var z_;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(z_||(z_={}));l();var Y_;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(Y_||(Y_={}));l();var ss=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},hi;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(hi||(hi={}));var MC={Ed25519:hi.Ed25519,ES256K:hi.secp256k1,ES256:hi.secp256r1,"P-256":hi.secp256r1,secp256k1:hi.secp256k1,secp256r1:hi.secp256r1},J_="https://ion.tbd.engineering",mb=class t extends dn{static create(){return ss(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in MC)))throw new Error("One or more verification method algorithms are not supported");let d=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(d&&d.length!==new Set(d).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let f={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},h=[];for(let T of(s=r.verificationMethods)!==null&&s!==void 0?s:[f]){let M=yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M});h.push({id:T.id,publicKeyJwk:q,purposes:(c=T.purposes)!==null&&c!==void 0?c:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let p=yield e.generateKey({algorithm:hi.secp256k1}),g=yield e.getPublicKey({keyUri:p}),y=yield e.generateKey({algorithm:hi.secp256k1}),x=yield e.getPublicKey({keyUri:y}),S=yield wc.computeLongFormDidUri({recoveryKey:g,updateKey:x,services:(a=r.services)!==null&&a!==void 0?a:[],verificationMethods:h}),{didDocument:_,didResolutionMetadata:A}=yield t.resolve(S,{gatewayUri:r.gatewayUri});if(_===null)throw new Error(`Unable to resolve DID during creation: ${A?.error}`);let O=new wr({uri:S,document:_,metadata:{published:!1,canonicalId:S.split(":",3).join(":"),recoveryKey:g,updateKey:x},keyManager:e});if(!((u=r.publish)!==null&&u!==void 0)||u){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static getSigningMethod(e){return ss(this,arguments,void 0,function*({didDocument:r,methodId:n}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a;return c.id===(n??((a=r.assertionMethod)===null||a===void 0?void 0:a[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return ss(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield wr.import({portableDid:r,keyManager:n})})}static publish(e){return ss(this,arguments,void 0,function*({did:r,gatewayUri:n=J_}){var i,o,s;let c=(o=(i=r.document.verificationMethod)===null||i===void 0?void 0:i.map(d=>({id:d.id,publicKeyJwk:d.publicKeyJwk,purposes:e_({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield wc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield wc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=wc.appendPathToUrl({baseUrl:n,path:"/operations"}),f=yield fetch(d,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:f.ok}),didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:ie.InternalError,errorMessage:`Failed to publish DID document for: ${r.uri}`}}}})}static resolve(e){return ss(this,arguments,void 0,function*(r,n={}){var i,o;let s=me.parse(r);if(!s)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:J_;try{let a=wc.appendPathToUrl({baseUrl:c,path:`/identifiers/${r}`}),u=yield fetch(a);if(!u.ok)throw new re(ie.NotFound,`Unable to find DID document for: ${r}`);let{didDocument:d,didDocumentMetadata:f}=yield u.json();return Object.assign(Object.assign(Object.assign({},pt),d&&{didDocument:d}),{didDocumentMetadata:Object.assign({published:(o=f?.method)===null||o===void 0?void 0:o.published},f)})}catch(a){if(!(a instanceof re))throw new Error(a);return Object.assign(Object.assign({},pt),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};mb.methodName="ion";var wc=class t{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static computeLongFormDidUri(e){return ss(this,arguments,void 0,function*({recoveryKey:r,updateKey:n,services:i,verificationMethods:o}){let s=yield t.createIonDocument({services:i,verificationMethods:o}),c=t.normalizeJwk(r),a=t.normalizeJwk(n);return yield Xa.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return ss(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield os.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return ss(this,arguments,void 0,function*({services:r,verificationMethods:n}){var i,o;let s=[];for(let u of n){let d=(o=(i=u.id)!==null&&i!==void 0?i:u.publicKeyJwk.kid)!==null&&o!==void 0?o:yield ge({jwk:u.publicKeyJwk});d=`${d.split("#").pop()}`;let f={id:d,publicKeyJwk:t.normalizeJwk(u.publicKeyJwk),purposes:u.purposes,type:"JsonWebKey2020"};s.push(f)}let c=r.map(u=>Object.assign(Object.assign({},u),{id:`${u.id.split("#").pop()}`}));return{publicKeys:s,services:c}})}static normalizeJwk(e){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}};l();var Cp=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},wb=class t extends dn{static create(){return Cp(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=ne.object(u).toBase64Url(),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f)).didDocument;return new wr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return Cp(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=(n=r.verificationMethod)!==null&&n!==void 0?n:[];if(!(o&&o.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o})}static import(e){return Cp(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield wr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return Cp(this,void 0,void 0,function*(){let n=me.parse(e),i;try{i=ne.base64Url(n.id).toObject()}catch{}if(!n||!i)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"methodNotSupported"}});let o={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},s=`${o.id}#0`;switch(o.verificationMethod=[{id:s,type:"JsonWebKey",controller:o.id,publicKeyJwk:i}],o.authentication=[s],o.assertionMethod=[s],o.capabilityInvocation=[s],o.capabilityDelegation=[s],o.keyAgreement=[s],i.use){case"sig":{delete o.keyAgreement;break}case"enc":{delete o.authentication,delete o.assertionMethod,delete o.capabilityInvocation,delete o.capabilityDelegation;break}}return Object.assign(Object.assign({},pt),{didDocument:o})})}};wb.methodName="jwk";l();var Nn=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},so;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(so||(so={}));var bb={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1",X25519KeyAgreementKey2020:"https://w3id.org/security/suites/x25519-2020/v1"},KC={Ed25519:so.Ed25519,ES256K:so.secp256k1,ES256:so.secp256r1,"P-256":so.secp256r1,secp256k1:so.secp256k1,secp256r1:so.secp256r1,X25519:so.X25519},xb=class t extends dn{static create(){return Nn(this,arguments,void 0,function*({keyManager:e=new Qt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=yield Er.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new wr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return Nn(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=r.assertionMethod||[],s=(n=r.verificationMethod)===null||n===void 0?void 0:n.find(c=>c.id===o);if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return Nn(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield wr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return Nn(this,void 0,void 0,function*(){try{let n=yield t.createDocument({didUri:e,options:r});return Object.assign(Object.assign({},pt),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},pt),{didResolutionMetadata:Object.assign({error:n.code},n.message&&{errorMessage:n.message})})}})}static createDocument(e){return Nn(this,arguments,void 0,function*({didUri:r,options:n={}}){let{defaultContext:i="https://www.w3.org/ns/did/v1",enableEncryptionKeyDerivation:o=!1,enableExperimentalPublicKeyTypes:s=!1,publicKeyFormat:c="JsonWebKey2020"}=n,a={id:""},u=me.parse(r);if(!u)throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let d=u.id;if(u.method!==t.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${u.method}`);if(!t.validateIdentifier(u))throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let f=yield t.createSignatureMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:c}});if(a.id=u.uri,a.verificationMethod=[f],a.authentication=[f.id],a.assertionMethod=[f.id],a.capabilityInvocation=[f.id],a.capabilityDelegation=[f.id],o===!0){let g=c==="Ed25519VerificationKey2020"?"X25519KeyAgreementKey2020":"JsonWebKey2020",y=yield this.createEncryptionMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:g}});a.verificationMethod.push(y),a.keyAgreement=[y.id]}let h=[i];return QT({didDocument:a}).forEach(g=>{let y=bb[g];h.push(y)}),a["@context"]=h,a})}static createEncryptionMethod(e){return Nn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u}=yield t.deriveEncryptionKey({multibaseValue:n}),d=a.byteLength,f=Er.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=Mw({keyBytes:a,multicodecCode:u});c.id=`${r}#${h}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in bb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","X25519KeyAgreementKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="X25519KeyAgreementKey2020"&&(c.publicKeyMultibase=h),s==="JsonWebKey2020"){let{crv:g}=yield Er.multicodecToJwk({code:u});c.publicKeyJwk=yield Er.keyConverter(g).bytesToPublicKey({publicKeyBytes:a})}return c})}static createSignatureMethod(e){return Nn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u,multicodecName:d}=Kw({multibaseKeyId:n}),f=a.byteLength,h=Er.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(f!==h)throw new re(ie.InvalidPublicKeyLength,`Expected ${f} bytes. Actual: ${h}`);let p=!1;switch(d){case"secp256k1-pub":p=yield kt.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":p=yield It.validatePublicKey({publicKeyBytes:a});break;case"x25519-pub":p=!0;break}if(!p)throw new re(ie.InvalidPublicKey,"Invalid public key detected.");c.id=`${r}#${n}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in bb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="Ed25519VerificationKey2020"&&(c.publicKeyMultibase=n),s==="JsonWebKey2020"){let{crv:y}=yield Er.multicodecToJwk({code:u});c.publicKeyJwk=yield Er.keyConverter(y).bytesToPublicKey({publicKeyBytes:a})}return c})}static deriveEncryptionKey(e){return Nn(this,arguments,void 0,function*({multibaseValue:r}){let n={keyBytes:new Uint8Array,multicodecCode:0},{keyBytes:i,multicodecCode:o}=Kw({multibaseKeyId:r});if(o===237){let s=yield Er.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield It.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield Er.keyConverter("Ed25519").publicKeyToBytes({publicKey:c}),multicodecCode:236}}return n})}static validateIdentifier(e){let{method:r,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&r==="key"&&Number("1")>0&&sa(n)==="String"&&n.startsWith("z")}};xb.methodName="key";var Er=class t{static jwkToMulticodec(e){return Nn(this,arguments,void 0,function*({jwk:r}){let n=[];r.crv&&(n.push(r.crv),r.d?n.push("private"):n.push("public"));let i=n.join(":"),o=t.JWK_TO_MULTICODEC[i];if(o===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${i}'`);return{code:Yt.getCodeFromName({name:o}),name:o}})}static keyCompressor(e){let n={"P-256":Vt.compressPublicKey,secp256k1:kt.compressPublicKey}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static keyConverter(e){let n={Ed25519:It,"P-256":Vt,secp256k1:kt,X25519:Va}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static multicodecToJwk(e){return Nn(this,arguments,void 0,function*({code:r,name:n}){if(!(n?!r:r))throw new Error("Either 'name' or 'code' must be defined, but not both.");n=n===void 0?Yt.getNameFromCode({code:r}):n;let i=n,o=t.MULTICODEC_TO_JWK[i];if(o===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return Object.assign({},o)})}static publicKeyToMultibaseId(e){return Nn(this,arguments,void 0,function*({publicKey:r}){var n;if(!(r?.crv&&r.crv in KC))throw new re(ie.InvalidPublicKeyType,`Public key contains an unsupported key type: ${(n=r?.crv)!==null&&n!==void 0?n:"undefined"}`);let i=yield t.keyConverter(r.crv).publicKeyToBytes({publicKey:r});/^(secp256k1|P-256|P-384|P-521)$/.test(r.crv)&&(i=yield t.keyCompressor(r.crv)({publicKeyBytes:i}));let{name:o}=yield t.jwkToMulticodec({jwk:r});return Mw({keyBytes:i,multicodecName:o})})}};Er.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv","X25519:public":"x25519-pub","X25519:private":"x25519-priv"};Er.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};Er.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""},"x25519-pub":{crv:"X25519",kty:"OKP",x:""},"x25519-priv":{crv:"X25519",kty:"OKP",x:"",d:""}};l();var $C=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Eb=class t extends dn{static resolve(e,r){return $C(this,void 0,void 0,function*(){let n=me.parse(e);if(!n)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"methodNotSupported"}});let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let o=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let s=yield fetch(o);if(!s.ok)throw new Error("HTTP error status code returned");let c=yield s.json();return Object.assign(Object.assign({},pt),{didDocument:c})}catch{return Object.assign(Object.assign({},pt),{didResolutionMetadata:{error:"notFound"}})}})}};Eb.methodName="web";l();var WC=Mn(X_(),1),GC=Mn(Jg(),1);l();l();var at=class t{static absoluteDidUrl(e,r){if(typeof e=="string"&&e.length!==0)return e.startsWith("#")?`${r}${e}`:e}static relationshipMethodId(e,r){let n=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.id:e;return t.absoluteDidUrl(n,r)}static isDidVerificationMethod(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"controller"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.controller!="string")}static isDidService(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"serviceEndpoint"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.serviceEndpoint!="string")}static getVerificationMethods(e){if(!e)throw new qe("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys(Pi).forEach(n=>{r.push(...e[n]?.filter(t.isDidVerificationMethod)??[])}),r}static deriveRootCapability(e){return{"@context":"https://w3id.org/zcap/v1",id:`urn:zcap:root:${encodeURIComponent(e)}`,controller:e,invocationTarget:e}}static dereferenceZcapId(e){let r={},[n,i,o,s]=e.split(":")??[];if([n,i,o,s].length!==4)throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!n||n!=="urn")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!i||i!=="zcap")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!o||o!=="root")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let a=decodeURIComponent(s);return r.id=e,r.controller=a,r.invocationTarget=a,r}};l();l();l();l();l();l();l();function Q_(t,e,r){return t&e^~t&r}function eI(t,e,r){return t&e^t&r^e&r}var Pp=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Rl(this.buffer)}update(e){ea(this),Ae(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Rl(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ea(this),Rv(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Ns(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let c=Rl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},co=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var zC=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]),cs=new Uint32Array(64),vb=class extends Pp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)cs[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=cs[f-15],p=cs[f-2],g=En(h,7)^En(h,18)^h>>>3,y=En(p,17)^En(p,19)^p>>>10;cs[f]=y+cs[f-7]+g+cs[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=En(c,6)^En(c,11)^En(c,25),p=d+h+Q_(c,a,u)+zC[f]+cs[f]|0,y=(En(n,2)^En(n,13)^En(n,22))+eI(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Ns(cs)}destroy(){this.set(0,0,0,0,0,0,0,0),Ns(this.buffer)}},Sb=class extends vb{A=co[0]|0;B=co[1]|0;C=co[2]|0;D=co[3]|0;E=co[4]|0;F=co[5]|0;G=co[6]|0;H=co[7]|0;constructor(){super(32)}};var Mp=Ov(()=>new Sb,Dv(1));l();l();var ur=BigInt(0),er=BigInt(1),xc=BigInt(2),nI=BigInt(3),iI=BigInt(4),oI=BigInt(5),YC=BigInt(7),sI=BigInt(8),JC=BigInt(9),cI=BigInt(16);function Cn(t,e){let r=t%e;return r>=ur?r:e+r}function Hr(t,e,r){let n=t;for(;e-- >ur;)n*=n,n%=r;return n}function tI(t,e){if(t===ur)throw new Error("invert: expected non-zero number");if(e<=ur)throw new Error("invert: expected positive modulus, got "+e);let r=Cn(t,e),n=e,i=ur,o=er,s=er,c=ur;for(;r!==ur;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==er)throw new Error("invert: does not exist");return Cn(i,e)}function Tb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function aI(t,e){let r=(t.ORDER+er)/iI,n=t.pow(e,r);return Tb(t,n,e),n}function ZC(t,e){let r=(t.ORDER-oI)/sI,n=t.mul(e,xc),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,xc),i),c=t.mul(o,t.sub(s,t.ONE));return Tb(t,c,e),c}function XC(t){let e=ru(t),r=uI(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+YC)/cI;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),x=c.cmov(u,d,y);return Tb(c,x,a),x}}function uI(t){if(t<nI)throw new Error("sqrt is not defined for small field");let e=t-er,r=0;for(;e%xc===ur;)e/=xc,r++;let n=xc,i=ru(t);for(;rI(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return aI;let o=i.pow(n,e),s=(e+er)/xc;return function(a,u){if(a.is0(u))return u;if(rI(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let x=er<<BigInt(d-g-1),S=a.pow(f,x);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function QC(t){return t%iI===nI?aI:t%sI===oI?ZC:t%cI===JC?XC(t):uI(t)}var eL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function _b(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=eL.reduce((n,i)=>(n[i]="function",n),e);return Ju(t,r),t}function tL(t,e,r){if(r<ur)throw new Error("invalid exponent, negatives unsupported");if(r===ur)return t.ONE;if(r===er)return e;let n=t.ONE,i=e;for(;r>ur;)r&er&&(n=t.mul(n,i)),i=t.sqr(i),r>>=er;return n}function Kp(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function rI(t,e){let r=(t.ORDER-er)/xc,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function rL(t,e){e!==void 0&&Yn(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Ab=class{ORDER;BITS;BYTES;isLE;ZERO=ur;ONE=er;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=ur)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:i,nByteLength:o}=rL(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Cn(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ur<=e&&e<this.ORDER}is0(e){return e===ur}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&er)===er}neg(e){return Cn(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Cn(e*e,this.ORDER)}add(e,r){return Cn(e+r,this.ORDER)}sub(e,r){return Cn(e-r,this.ORDER)}mul(e,r){return Cn(e*r,this.ORDER)}pow(e,r){return tL(this,e,r)}div(e,r){return Cn(e*tI(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return tI(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=QC(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?L0(e,this.BYTES):Ol(e,this.BYTES)}fromBytes(e,r=!1){Ae(e);let{_lengths:n,BYTES:i,isLE:o,ORDER:s,_mod:c}=this;if(n){if(!n.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(i);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=o?C0(e):Do(e);if(c&&(a=Cn(a,s)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Kp(this,e)}cmov(e,r,n){return n?r:e}};function ru(t,e={}){return new Ab(t,e)}function dI(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ib(t){let e=dI(t);return e+Math.ceil(e/2)}function $p(t,e,r=!1){Ae(t);let n=t.length,i=dI(e),o=Ib(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?C0(t):Do(t),c=Cn(s,e-er)+er;return r?L0(c,i):Ol(c,i)}var nu=BigInt(0),Ec=BigInt(1);function df(t,e){let r=e.negate();return t?r:e}function Ob(t,e){let r=Kp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function pI(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Bb(t,e){pI(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Yu(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function fI(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=Ec);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}var Rb=new WeakMap,yI=new WeakMap;function Ub(t){return yI.get(t)||1}function lI(t){if(t!==nu)throw new Error("invalid wNAF")}var Hp=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>nu;)r&Ec&&(n=n.add(i)),i=i.double(),r>>=Ec;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Bb(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=Bb(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=fI(n,c,s);n=a,d?o=o.add(df(h,r[p])):i=i.add(df(f,r[u]))}return lI(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Bb(e,this.bits);for(let s=0;s<o.windows&&n!==nu;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=fI(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return lI(n),i}getPrecomputes(e,r,n){let i=Rb.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Rb.set(r,i))),i}cached(e,r,n){let i=Ub(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Ub(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){pI(r,this.bits),yI.set(e,r),Rb.delete(e)}hasCache(e){return Ub(e)!==1}};function gI(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>nu||n>nu;)r&Ec&&(o=o.add(i)),n&Ec&&(s=s.add(i)),i=i.double(),r>>=Ec,n>>=Ec;return{p1:o,p2:s}}function hI(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return _b(e),e}else return ru(t,{isLE:r})}function mI(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>nu))throw new Error(`CURVE.${a} must be positive bigint`)}let i=hI(e.p,r.Fp,n),o=hI(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}function Vp(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var qp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(Bl(e),Ae(r,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,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ns(i)}update(e){return ea(this),this.iHash.update(e),this}digestInto(e){ea(this),Ae(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:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Db=(t,e,r)=>new qp(t,e).update(r).digest();Db.create=(t,e)=>new qp(t,e);var wI=(t,e)=>(t+(t>=0?e:-e)/bI)/e;function nL(t,e,r){let[[n,i],[o,s]]=e,c=wI(s*t,r),a=wI(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<ao,h=d<ao;f&&(u=-u),h&&(d=-d);let p=Yu(Math.ceil(P0(r)/2))+iu;if(u<ao||u>=p||d<ao||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Nb(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function kb(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Gu(r.lowS,"lowS"),Gu(r.prehash,"prehash"),r.format!==void 0&&Nb(r.format),r}var Cb=class extends Error{constructor(e=""){super(e)}},as={Err:Cb,_tlv:{encode:(t,e)=>{let{Err:r}=as;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=zu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?zu(i.length/2|128):"";return zu(t)+o+i+e},decode(t,e){let{Err:r}=as,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=as;if(t<ao)throw new e("integer: negative integers are not allowed");let r=zu(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=as;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Do(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=as,i=Ae(t,void 0,"signature"),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=as,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},ao=BigInt(0),iu=BigInt(1),bI=BigInt(2),Fp=BigInt(3),iL=BigInt(4);function xI(t,e={}){let r=mI("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Ju(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=vI(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,I,D){let{x:E,y:U}=I.toAffine(),L=n.toBytes(E);if(Gu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return hr(EI(N),L)}else return hr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){Ae(G,void 0,"Point");let{publicKey:I,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===I&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(E===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!x(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${E}, expected compressed=${I} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let I=n.sqr(G),D=n.mul(I,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function x(G,I){let D=n.sqr(I),E=y(G);return n.eql(D,E)}if(!x(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Fp),iL),_=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,_)))throw new Error("bad curve params: a or b");function A(G,I,D=!1){if(!n.isValid(I)||D&&n.is0(I))throw new Error(`bad point coordinate ${G}`);return I}function O(G){if(!(G instanceof $))throw new Error("Weierstrass Point expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return nL(G,a.basises,i.ORDER)}let M=M0((G,I)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();I==null&&(I=L?n.ONE:n.inv(U));let N=n.mul(D,I),R=n.mul(E,I),C=n.mul(U,I);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=M0(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:I,y:D}=G.toAffine();if(!n.isValid(I)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!x(I,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,I,D,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),I=df(E,I),D=df(U,D),I.add(D)}class ${static BASE=new $(o.Gx,o.Gy,n.ONE);static ZERO=new $(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(I,D,E){this.X=A("x",I),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(I){let{x:D,y:E}=I||{};if(!I||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(I instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(I){let D=$.fromAffine(g(Ae(I,void 0,"point")));return D.assertValidity(),D}static fromHex(I){return $.fromBytes(Ls(I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,D=!0){return Q.createCache(this,I),D||this.multiply(Fp),this}assertValidity(){q(this)}hasEvenY(){let{y:I}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(I)}equals(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(E,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:I,b:D}=o,E=n.mul(D,Fp),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(I,P),C=n.mul(E,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(E,P),z=n.mul(I,z),W=n.sub(V,z),W=n.mul(I,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(I){O(I);let{X:D,Y:E,Z:U}=this,{X:L,Y:N,Z:R}=I,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Fp),W=n.mul(D,L),Y=n.mul(E,N),Z=n.mul(U,R),ue=n.add(D,E),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(E,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(I){return this.add(I.negate())}is0(){return this.equals($.ZERO)}multiply(I){let{endo:D}=e;if(!i.isValidNot0(I))throw new Error("invalid scalar: out of range");let E,U,L=N=>Q.cached(this,N,R=>Ob($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(I),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(I);E=N,U=R}return Ob($,[E,U])[0]}multiplyUnsafe(I){let{endo:D}=e,E=this;if(!i.isValid(I))throw new Error("invalid scalar: out of range");if(I===ao||E.is0())return $.ZERO;if(I===iu)return E;if(Q.hasCache(this))return this.multiply(I);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(I),{p1:C,p2:P}=gI($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,I)}toAffine(I){return M(this,I)}isTorsionFree(){let{isTorsionFree:I}=e;return s===iu?!0:I?I($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:I}=e;return s===iu?this:I?I($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(I=!0){return Gu(I,"isCompressed"),this.assertValidity(),p($,this,I)}toHex(I=!0){return Cs(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=i.BITS,Q=new Hp($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function EI(t){return Uint8Array.of(t?2:3)}function vI(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function oL(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ps,i=Object.assign(vI(t.Fp,r),{seed:Ib(r.ORDER)});function o(p){try{let g=r.fromBytes(p);return r.isValidNot0(g)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:x}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==x?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return $p(Ae(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(g)}function u(p){let{secretKey:g,publicKey:y,publicKeyUncompressed:x}=i;if(!Wu(p)||"_lengths"in r&&r._lengths||g===y)return;let S=Ae(p,void 0,"key").length;return S===y||S===x}function d(p,g,y=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(g)===!1)throw new Error("second arg must be public key");let x=r.fromBytes(p);return t.fromBytes(g).multiply(x).toBytes(y)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c},h=Vp(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function SI(t,e,r={}){Bl(e),Ju(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||Ps,i=r.hmac||((D,E)=>Db(e,D,E)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=oL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*bI<o.ORDER;function x(D){let E=c>>iu;return D>E}function S(D,E){if(!s.isValidNot0(E))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return E}function _(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,E){Nb(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return Ae(D,L)}class O{r;s;recovery;constructor(E,U,L){if(this.r=S("r",E),this.s=S("s",U),L!=null){if(_(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(E,U=g.format){A(E,U);let L;if(U==="der"){let{r:P,s:V}=as.toSig(Ae(E));return new O(P,V)}U==="recovered"&&(L=E[0],U="compact",E=E.subarray(1));let N=p.signature/2,R=E.subarray(0,N),C=E.subarray(N,N*2);return new O(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(E,U){return this.fromBytes(Ls(E),U)}assertRecovery(){let{recovery:E}=this;if(E==null)throw new Error("invalid recovery id: must be present");return E}addRecoveryBit(E){return new O(this.r,this.s,E)}recoverPublicKey(E){let{r:U,s:L}=this,N=this.assertRecovery(),R=N===2||N===3?U+c:U;if(!o.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let C=o.toBytes(R),P=t.fromBytes(hr(EI((N&1)===0),C)),V=s.inv(R),J=M(Ae(E,void 0,"msgHash")),z=s.create(-J*V),W=s.create(L*V),Y=t.BASE.multiplyUnsafe(z).add(P.multiplyUnsafe(W));if(Y.is0())throw new Error("invalid recovery: point at infinify");return Y.assertValidity(),Y}hasHighS(){return x(this.s)}toBytes(E=g.format){if(Nb(E),E==="der")return Ls(as.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return E==="recovered"?(_(),hr(Uint8Array.of(this.assertRecovery()),N,R)):hr(N,R)}toHex(E){return Cs(this.toBytes(E))}}let T=r.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let U=Do(E),L=E.length*8-a;return L>0?U>>BigInt(L):U},M=r.bits2int_modN||function(E){return s.create(T(E))},q=Yu(a);function j(D){return Lv("num < 2^"+a,D,ao,q),s.toBytes(D)}function $(D,E){return Ae(D,void 0,"message"),E?Ae(e(D),void 0,"prehashed message"):D}function X(D,E,U){let{lowS:L,prehash:N,extraEntropy:R}=kb(U,g);D=$(D,N);let C=M(D),P=s.fromBytes(E);if(!s.isValidNot0(P))throw new Error("invalid private key");let V=[j(P),j(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(Ae(Y,void 0,"extraEntropy"))}let J=hr(...V),z=C;function W(Y){let Z=T(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===ao)return;let Ue=s.create(ue*s.create(z+ce*P));if(Ue===ao)return;let Ke=(ee.x===ce?0:2)|Number(ee.y&iu),Je=Ue;return L&&x(Ue)&&(Je=s.neg(Ue),Ke^=1),new O(ce,Je,y?void 0:Ke)}return{seed:J,k2sig:W}}function Q(D,E,U={}){let{seed:L,k2sig:N}=X(D,E,U);return Pv(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=kb(L,g);if(U=Ae(U,void 0,"publicKey"),E=$(E,R),!Wu(D)){let P=D instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}A(D,C);try{let P=O.fromBytes(D,C),V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=M(E),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function I(D,E,U={}){let{prehash:L}=kb(U,g);return E=$(E,L),O.fromBytes(D,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:Q,verify:G,recoverPublicKey:I,Signature:O,hash:e})}var Gp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},sL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},cL=BigInt(0),Lb=BigInt(2);function aL(t){let e=Gp.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=Hr(d,r,e)*d%e,h=Hr(f,r,e)*d%e,p=Hr(h,Lb,e)*u%e,g=Hr(p,i,e)*p%e,y=Hr(g,o,e)*g%e,x=Hr(y,c,e)*y%e,S=Hr(x,a,e)*x%e,_=Hr(S,c,e)*y%e,A=Hr(_,r,e)*d%e,O=Hr(A,s,e)*g%e,T=Hr(O,n,e)*u%e,M=Hr(T,Lb,e);if(!jp.eql(jp.sqr(M),t))throw new Error("Cannot find square root");return M}var jp=ru(Gp.p,{sqrt:aL}),vc=xI(Gp,{Fp:jp,endo:sL}),fn=SI(vc,Mp),AI={};function Wp(t,...e){let r=AI[t];if(r===void 0){let n=Mp(Cv(t));r=hr(n,n),AI[t]=r}return Mp(hr(r,...e))}var Mb=t=>t.toBytes(!0).slice(1),Kb=t=>t%Lb===cL;function Pb(t){let{Fn:e,BASE:r}=vc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:Kb(i.y)?n:e.neg(n),bytes:Mb(i)}}function _I(t){let e=jp;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Kb(i)||(i=e.neg(i));let o=vc.fromAffine({x:t,y:i});return o.assertValidity(),o}var ff=Do;function II(...t){return vc.Fn.create(ff(Wp("BIP0340/challenge",...t)))}function TI(t){return Pb(t).bytes}function uL(t,e,r=Ps(32)){let{Fn:n}=vc,i=Ae(t,void 0,"message"),{bytes:o,scalar:s}=Pb(e),c=Ae(r,32,"auxRand"),a=n.toBytes(s^ff(Wp("BIP0340/aux",c))),u=Wp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Pb(u),h=II(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!BI(p,i,o))throw new Error("sign: Invalid signature produced");return p}function BI(t,e,r){let{Fp:n,Fn:i,BASE:o}=vc,s=Ae(t,64,"signature"),c=Ae(e,void 0,"message"),a=Ae(r,32,"publicKey");try{let u=_I(ff(a)),d=ff(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=ff(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=II(i.toBytes(d),Mb(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!Kb(y)||g!==d)}catch{return!1}}var zp=(()=>{let r=(n=Ps(48))=>$p(n,Gp.n);return{keygen:Vp(r,TI),getPublicKey:TI,sign:uL,verify:BI,Point:vc,utils:{randomSecretKey:r,taggedHash:Wp,lift_x:_I,pointToBytes:Mb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function dL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function UI(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function $b(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function OI(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Hb(t){if(!Array.isArray(t))throw new Error("array expected")}function DI(t,e){if(!UI(!0,e))throw new Error(`${t}: array of strings expected`)}function fL(t,e){if(!UI(!1,e))throw new Error(`${t}: array of numbers expected`)}function lL(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function hL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;DI("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Hb(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(Hb(i),i.map(o=>{$b("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function pL(t=""){return $b("join",t),{encode:e=>(DI("join.decode",e),e.join(t)),decode:e=>($b("join.decode",e),e.split(t))}}function RI(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Hb(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(OI(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}function yL(t){OI(t);let e=2**8;return{encode:r=>{if(!dL(r))throw new Error("radix.encode input should be Uint8Array");return RI(Array.from(r),e,t)},decode:r=>(fL("radix.decode",r),Uint8Array.from(RI(r,t,e)))}}var gL=t=>lL(yL(58),hL(t),pL("")),ou=gL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var kI=new Uint8Array([231,1]),ut=class t{#e;#t={prefix:kI,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:_r(e);if(!r||r.length!==33)throw new Us("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!fn.utils.isValidPublicKey(r))throw new Us("Invalid argument: not a valid secp256k1 compressed point","CONSTRUCTOR_ERROR",{keyBytes:r});this.#e=new Uint8Array(r),this.#t.encoded=this.encode(),this.#t.key=[...this.#t.prefix,...this.compressed]}get compressed(){return new Uint8Array(this.#e)}get uncompressed(){return fn.Point.fromBytes(this.compressed).toBytes(!1)}get xOnly(){return this.compressed.slice(1)}get parity(){let e=this.compressed[0];if(![2,3].includes(e))throw new Us("Invalid state: parity byte must be 2 or 3","PARITY_ERROR",{parity:e});return e}get isEven(){return this.parity===2}get x(){return this.compressed.slice(1,33)}get y(){return this.uncompressed.slice(33,65)}get multibase(){return{prefix:new Uint8Array(this.#t.prefix),key:[...this.#t.key],encoded:this.#t.encoded}}get hex(){return Pt(this.compressed)}get point(){return{x:this.x,y:this.y}}bip340(){return this.xOnly}decode(){return ou.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(kI);return r.push(...e),"z"+ou.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return fn.verify(e,r,this.compressed);if(n.scheme==="schnorr")return zp.verify(e,r,this.x);throw new Us(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return ta(this.compressed,e.compressed)}toJSON(){return{hex:this.hex,multibase:this.multibase,point:{x:Array.from(this.x),y:Array.from(this.y),parity:this.parity}}}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromJSON(e){return new t(Uint8Array.from([e.point.parity,...e.point.x]))}};l();var NI=new Uint8Array([129,38]),mL=Pt(ke(NI)),Vr=class t{#e;#t;#n;constructor(e){let r=e instanceof Uint8Array,n=typeof e=="bigint";if(!r&&!n)throw new Wn("Invalid entropy: must be a valid byte array (32) or bigint","CONSTRUCTOR_ERROR");if(r&&e.length===32&&(this.#e=new Uint8Array(e),this.#t=t.toSecret(this.#e)),n&&e>=1n&&e<fn.Point.Fn.ORDER&&(this.#e=t.toBytes(e),this.#t=e),!this.#e||this.#e.length!==32)throw new Wn("Invalid bytes: must be a valid 32-byte secret key","CONSTRUCTOR_ERROR");if(!this.#t||this.#t<1n||this.#t>=fn.Point.Fn.ORDER)throw new Wn("Invalid seed: must be valid bigint","CONSTRUCTOR_ERROR");this.#n=this.encode()}destroy(){this.#e&&this.#e.fill(0),this.#t=void 0,this.#n=""}get bytes(){return new Uint8Array(this.#e)}get seed(){return BigInt(this.#t)}get hex(){return Pt(this.bytes)}get multibase(){return this.#n}encode(){let e=Array.from(this.bytes),r=Array.from(NI);return r.push(...e),"z"+ou.encode(Uint8Array.from(r))}equals(e){return ta(this.bytes,e.bytes)}computePublicKey(){return new ut(fn.getPublicKey(this.bytes))}toJSON(){return{type:"Secp256k1SecretKey"}}exportJSON(){return{bytes:Array.from(this.bytes),seed:this.seed.toString(),hex:this.hex}}toString(){return"[Secp256k1SecretKey]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[Secp256k1SecretKey]"}isValid(){return fn.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return fn.sign(e,this.bytes);if(r.scheme==="schnorr")return zp.sign(e,this.bytes);throw new Wn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=ou.decode(e.slice(1));if(r.length!==34)throw new Wn("Invalid argument: must be 34 byte secretKeyMultibase","DECODE_MULTIBASE_ERROR");let n=r.slice(0,2);if(Pt(ke(n))!==mL)throw new Wn(`Invalid prefix: malformed multibase prefix ${n}`,"DECODE_MULTIBASE_ERROR");return r}static fromJSON(e){return new t(new Uint8Array(e.bytes))}static toSecret(e){return e.reduce((r,n)=>r<<8n|BigInt(n),0n)}static toBytes(e){let r=Uint8Array.from({length:32},(n,i)=>Number(e>>BigInt(8*(31-i))&BigInt(255)));if(!fn.utils.isValidSecretKey(r))throw new Wn("Invalid secret key: secret out of valid range","SET_PRIVATE_KEY_ERROR");return new Uint8Array(r)}static fromBigInt(e){return new t(t.toBytes(e))}static random(){let e;do e=Ir(32);while(!fn.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var uo=class t{#e;#t;constructor(e={}){if(!e.publicKey&&!e.secretKey)throw new bn("Argument missing: must at least provide a publicKey","CONSTRUCTOR_ERROR");if(e.secretKey instanceof Uint8Array?this.#e=new Vr(e.secretKey):e.secretKey instanceof Vr&&(this.#e=e.secretKey),e.publicKey instanceof ut?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new ut(e.publicKey):this.#t=this.#e.computePublicKey(),this.#e&&e.publicKey){let r=this.#e.computePublicKey();if(!this.#t.equals(r))throw new bn("Public key does not match secret key","CONSTRUCTOR_ERROR")}}get secretKey(){if(!this.#e)throw new bn("Secret key not available","SECRET_KEY_ERROR");if(!this.#e.isValid())throw new bn("Secret key is not valid","SECRET_KEY_ERROR");return this.#e}set publicKey(e){if(this.#e){let r=this.#e.computePublicKey();if(!e.equals(r))throw new bn("Public key does not match secret key","PUBLIC_KEY_ERROR")}this.#t=e}get publicKey(){return this.#t}get hasSecretKey(){return!!this.#e}get raw(){return{public:this.publicKey.compressed,secret:this.#e?this.#e.bytes:void 0}}get hex(){return{public:this.publicKey.hex,secret:this.#e?this.#e.hex:void 0}}get multibase(){return{publicKeyMultibase:this.#t.multibase.encoded,secretKeyMultibase:this.#e?this.#e.multibase:""}}toJSON(){return{publicKey:this.publicKey.toJSON()}}exportJSON(){if(!this.#e)throw new bn("Cannot export: secret key required. Use publicKey.toJSON() for public-key-only pairs.","SERIALIZE_ERROR");return{secretKey:this.#e.exportJSON(),publicKey:this.publicKey.toJSON()}}[Symbol.for("nodejs.util.inspect.custom")](){return`[SchnorrKeyPair ${this.publicKey.hex}]`}static fromJSON(e){return new t({secretKey:Vr.fromJSON(e.secretKey),publicKey:ut.fromJSON(e.publicKey)})}static fromSecret(e){let r=typeof e=="string"?_r(e):e;if(r.length!==32)throw new bn("Invalid arg: must be 32 byte secret key","FROM_SECRET_KEY_ERROR");let n=new Vr(r),i=n.computePublicKey();return new t({secretKey:n,publicKey:i})}static fromBigInt(e){let r=Vr.fromBigInt(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}static toHex(e){return Pt(e)}static equals(e,r){return e.publicKey.equals(r.publicKey)}static generate(){let e=Vr.random(),r=new Vr(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}};l();l();l();l();var wL=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],su="Multikey",cu="zQ3s",dr="did:btcr2:_",qte="",bL=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function xL(t){if(!at.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===su&&typeof r=="string"&&r.startsWith(cu)}var Vb=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==su)throw new qe(`Invalid verification method: type must be "${su}"`,De,{id:e,type:r});if(typeof i!="string"||!i.startsWith(cu))throw new qe(`Invalid verification method: publicKeyMultibase must start with "${cu}"`,De,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},ln=class t{id;"@context"=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"];verificationMethod;authentication;assertionMethod;capabilityInvocation;capabilityDelegation;service;deactivated;constructor(e){if(!e.id)throw new qe("DID Document must have an id",De,e);let r=e.id.includes("k1")?Xr.KEY:Xr.EXTERNAL,n=e.id===dr,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new qe(`Invalid id: ${i}`,De,e);if(!t.isValidVerificationMethods(o))throw new qe("Invalid verificationMethod: "+o,De,e);if(!t.isValidServices(s))throw new qe("Invalid service: "+s,De,e)}if(this.id=e.id,this.verificationMethod=e.verificationMethod||[],this.service=e.service||[],this["@context"]=e["@context"]||["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],r===Xr.KEY){let c=`${this.id}#initialKey`;this.authentication=e.authentication||[c],this.assertionMethod=e.assertionMethod||[c],this.capabilityInvocation=e.capabilityInvocation||[c],this.capabilityDelegation=e.capabilityDelegation||[c]}else this.authentication=e.authentication,this.assertionMethod=e.assertionMethod,this.capabilityInvocation=e.capabilityInvocation,this.capabilityDelegation=e.capabilityDelegation;t.sanitize(this),n?this.validateGenesis():t.validate(this)}toJSON(){return{id:this.id,"@context":this["@context"],verificationMethod:this.verificationMethod,authentication:this.authentication,assertionMethod:this.assertionMethod,capabilityInvocation:this.capabilityInvocation,capabilityDelegation:this.capabilityDelegation,service:this.service,deactivated:this.deactivated}}static fromKeyIdentifier(e,r,n){e=e.includes("#")?e:`${e}#initialKey`;let i={id:e,verificationMethod:[new Vb({id:e,type:"Multikey",controller:e,publicKeyMultibase:r})],service:n};return new t(i)}static fromExternalIdentifier(e){return new t(e)}static sanitize(e){for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}static isValid(e){if(!this.isValidContext(e?.["@context"]))throw new qe('Invalid "@context"',De,e);if(!this.isValidId(e?.id))throw new qe('Invalid "id"',De,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new qe('Invalid "verificationMethod"',De,e);if(!this.isValidServices(e?.service))throw new qe('Invalid "service"',De,e);if(!this.isValidVerificationRelationships(e))throw new qe("Invalid verification relationships",De,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:wL.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return vr.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(xL)}static isValidServices(e){return Array.isArray(e)&&e.every(t_)}static isValidVerificationRelationships(e){let r=["authentication","assertionMethod","capabilityInvocation","capabilityDelegation"],n=Object.keys(e);return r.filter(o=>n.includes(o)).every(o=>{let s=e[o];return s&&Array.isArray(s)&&s.every(c=>typeof c=="string"||at.isDidVerificationMethod(c))})}static validate(e){return e.id===dr?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==dr)throw new qe("Invalid GenesisDocument ID",De,this);if(!this.verificationMethod.every(e=>e.id.includes(dr)&&e.controller===dr))throw new qe("Invalid GenesisDocument verificationMethod",De,this);if(!this.service.every(e=>e.id.includes(dr)))throw new qe("Invalid GenesisDocument service",De,this);if(!t.isValidVerificationRelationships(this))throw new qe("Invalid GenesisDocument assertionMethod",De,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new qe("Cannot convert a key identifier to an intermediate document",De,this);return new lf(this)}},lf=class t extends ln{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(dr,e),n=JSON.parse(r);return new ln(n)}static fromDidDocument(e){let r=ks.cloneReplace(e,bL,dr);return new t(r)}static create(e,r,n){return new t({id:dr,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ut(e),i=dr,o=ki(n.compressed,Uo(r)).address,s=[{id:`${i}#service-0`,serviceEndpoint:`bitcoin:${o}`,type:"SingletonBeacon"}],c={authentication:[`${i}#key-0`],assertionMethod:[`${i}#key-0`],capabilityInvocation:[`${i}#key-0`],capabilityDelegation:[`${i}#key-0`]},a=[{id:`${i}#key-0`,type:"Multikey",controller:i,publicKeyMultibase:n.multibase.encoded}];return t.create(a,c,s)}static fromJSON(e){return new t(e)}static toGenesisBytes(e){return Io(rr(e))}};var CI="did:btcr2:",vr=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in Xr))throw new lt('Expected "idType" to be "KEY" or "EXTERNAL"',Dt,{idType:n});if(i!==1)throw new lt('Expected "version" to be 1',Dt,{version:i});if(typeof o!="string")throw new lt('Expected "network" to be a known network name',Dt,{network:o});let s=Qc[o];if(s===void 0)throw new lt('Invalid "network" name',Dt,{network:o});if(n==="KEY")try{new ut(e)}catch{throw new lt('Expected "genesisBytes" to be a valid compressed secp256k1 public key',Dt,{genesisBytes:e})}else if(e.length!==32)throw new lt('Expected "genesisBytes" to be a 32-byte hash for EXTERNAL identifiers',Dt,{genesisBytes:e});let c=n==="KEY"?"k":"x",a=i-1<<4|s,u=new Uint8Array([a,...e]);return`${CI}${Ss.encodeFromBytes(c,u)}`}static decode(e){let r=e.split(":");if(r.length!==3)throw new lt(`Invalid did: ${e}`,Dt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new lt(`Invalid did: ${e}`,Dt,{identifier:e});if(i!=="btcr2")throw new lt(`Invalid did method: ${i}`,yl,{identifier:e});if(!o)throw new lt(`Invalid method-specific id: ${e}`,Dt,{identifier:e});if(o!==o.toLowerCase())throw new lt(`Invalid method-specific id (must be lowercase): ${e}`,Dt,{identifier:e});let{prefix:s,bytes:c}=Ss.decodeToBytes(o);if(!["x","k"].includes(s))throw new lt(`Invalid hrp: ${s}`,Dt,{identifier:e});if(!c||c.length<1)throw new lt(`Failed to decode id: ${o}`,Dt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new lt(`Invalid btcr2_version (expected 0): ${u}`,Dt,{identifier:e});let d=1,f=c[0]&15,h=Qc[f];if(typeof h!="string"){let g=f>=12?"custom network not supported":"reserved";throw new lt(`Invalid network (${g}): ${f}`,Dt,{identifier:e})}let p=c.slice(1);if(a==="KEY")try{new ut(p)}catch{throw new lt(`Invalid genesisBytes: ${p}`,Dt,{identifier:e})}else if(p.length!==32)throw new lt(`Invalid genesisBytes: ${p}`,Dt,{identifier:e});return{idType:a,hrp:s,version:d,network:h,genesisBytes:p}}static validate(e,r={}){let n=[],i=(x,S)=>{n.push(S===void 0?{name:x,ok:!0}:{name:x,ok:!0,detail:S})},o=(x,S,_={})=>(n.push({name:x,ok:!1,detail:S}),{did:e,valid:!1,..._,checks:n});if(typeof e!="string")return o("prefix","The identifier is not a string.");let s=e.split(":");if(s.length!==3||s[0]!=="did"||s[1]!=="btcr2")return o("prefix",`The identifier must be "${CI}" followed by the method-specific id.`);let c=s[2];if(c.length===0)return o("prefix","The method-specific id is empty.");if(i("prefix"),c!==c.toLowerCase())return o("lowercase","The method-specific id must be lowercase.");i("lowercase");let a,u;try{({prefix:a,bytes:u}=Ss.decodeToBytes(c))}catch(x){return o("bech32m",`Bech32m decoding failed: ${x instanceof Error?x.message:String(x)}`)}if(a!=="k"&&a!=="x")return o("bech32m",`The hrp must be "k" or "x", got "${a}".`);let d=a==="k"?Xr.KEY:Xr.EXTERNAL;if(u.length<1)return o("bech32m","The data bytes are empty.",{idType:d});i("bech32m",`hrp "${a}", ${u.length} data bytes`);let f=u[0]>>>4;if(f!==0)return o("version",`btcr2_version must be 0, got ${f}.`,{idType:d});i("version","btcr2_version 0 (version_number 1)");let h=u[0]&15,p=Qc[h];if(typeof p!="string"){let x=h>=12?`network_value ${h} is a custom network, not supported by this implementation.`:`network_value ${h} is reserved.`;return o("network",x,{idType:d})}i("network",`network_value ${h} (${p})`);let g=u.slice(1);if(d===Xr.KEY){try{new ut(g)}catch{return o("genesisBytes",`Expected a 33-byte SEC compressed secp256k1 public key, got ${g.length} bytes that are not a valid key.`,{idType:d,network:p})}i("genesisBytes","33-byte SEC compressed secp256k1 public key")}else{if(g.length!==32)return o("genesisBytes",`Expected a 32-byte SHA-256 hash, got ${g.length} bytes.`,{idType:d,network:p});i("genesisBytes","32-byte SHA-256 hash")}let y;try{y=t.encode(g,{idType:d,version:1,network:p})}catch(x){return o("roundTrip",`Re-encoding failed: ${x instanceof Error?x.message:String(x)}`,{idType:d,network:p})}if(y!==e)return o("roundTrip",`Re-encoding produced "${y}".`,{idType:d,network:p});if(i("roundTrip"),r.genesisBytes!==void 0){let x=r.genesisBytes;if(!(x instanceof Uint8Array))return o("genesisBytesMatch","The supplied genesis bytes are not a Uint8Array.",{idType:d,network:p});if(x.length!==g.length)return o("genesisBytesMatch",`Expected ${g.length} genesis bytes for a ${d} identifier, got ${x.length}.`,{idType:d,network:p});if(!go(x,g))return o("genesisBytesMatch",`The supplied genesis bytes ${xe.encode(x)} do not equal the genesis bytes of the identifier ${xe.encode(g)}.`,{idType:d,network:p});i("genesisBytesMatch","The supplied genesis bytes equal the genesis bytes of the identifier.")}if(r.genesisDocument!==void 0){let x=r.genesisDocument;if(d===Xr.KEY)return o("genesisDocument","A KEY identifier has no genesis document.",{idType:d,network:p});let S=x.id;if(S!==dr)return o("genesisDocument",`The genesis document id must be "${dr}", got ${JSON.stringify(S)}.`,{idType:d,network:p});try{lf.fromJSON(x)}catch(A){return o("genesisDocument",`Invalid genesis document: ${A instanceof Error?A.message:String(A)}`,{idType:d,network:p})}let _=Bo(x);if(!go(_,g))return o("genesisDocument",`The genesis document hash ${xe.encode(_)} does not equal the genesis bytes ${xe.encode(g)}.`,{idType:d,network:p});i("genesisDocument","The genesis document hashes to the genesis bytes.")}return{did:e,valid:!0,idType:d,network:p,checks:n}}static generate(){let e=uo.generate(),r=this.encode(e.publicKey.compressed,{idType:"KEY",version:1,network:"regtest"});return{keyPair:e.exportJSON(),did:r}}static getPublicKey(e){let{idType:r,genesisBytes:n}=t.decode(e);if(r!=="KEY")throw new lt(`Cannot extract public key from EXTERNAL DID: ${e}. EXTERNAL DIDs encode a document hash, not a public key.`,Dt,{did:e,idType:r});return new ut(n)}static isValid(e){try{return this.decode(e),!0}catch{return!1}}};var hn=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new we("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!at.isDidService(e)||!["SingletonBeacon","CASBeacon","SMTBeacon"].includes(e.type)||[e.serviceEndpoint].flat().some(r=>typeof r=="string"&&!r.startsWith("bitcoin:")))}static getBeaconServices(e){return e.service.filter(this.isBeaconService)??[]}static createBeaconServices(e,r){try{return["p2pkh","p2wpkh","p2tr"].map(i=>this.createBeaconService(e,i,r))}catch(n){throw new nr("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=vr.decode(e),o=Uo(i.network),s=i.genesisBytes,c=`${e}#initial${r.toUpperCase()}`,u=`bitcoin:${r==="p2tr"?_s(s.slice(1,33),void 0,o).address:r==="p2wpkh"?Ts(s,o).address:ki(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new nr("Failed to create beacon service: "+i.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:n})}}static generateBeaconServices({id:e,publicKey:r,network:n,beaconType:i}){try{let o=ki(r,n).address,s=Ts(r,n).address,c=_s(r.slice(1,33),void 0,n).address;if(!o||!s||!c)throw new zt("Failed to generate bitcoin addresses");return[{id:`${e}#initialP2PKH`,type:i,serviceEndpoint:`bitcoin:${o}`},{id:`${e}#initialP2WPKH`,type:i,serviceEndpoint:`bitcoin:${s}`},{id:`${e}#initialP2TR`,type:i,serviceEndpoint:`bitcoin:${c}`}]}catch(o){throw new nr("Failed to create beacon services: "+o.message,"BEACON_SERVICE_ERROR",{id:e,publicKey:r,network:n,beaconType:i})}}static parseBeaconServiceEndpoint(e){return{...e,serviceEndpoint:e.serviceEndpoint.replace("bitcoin:","")}}static getBeaconServiceIds(e){return this.getBeaconServices(e).map(r=>r.id)}};var EL=/^6a20([0-9a-f]{64})$/i;function LI(t){if(!t)return null;let e=EL.exec(t.trim());return e?e[1].toLowerCase():null}var PI=class t{static async spendsFromAddress(e,r,n){for(let i of e.vin??[]){if(i.is_coinbase)continue;let o=i.prevout;if(!o&&i.txid&&(o=(await n.rest.transaction.get(i.txid))?.vout?.[i.vout]),o?.scriptpubkey_address===r)return!0}return!1}static async indexer(e,r){let n=new Map,i=await r.rest.block.count();for(let o of e){n.set(o,[]);let s=hn.parseBitcoinAddress(o.serviceEndpoint),c=await r.rest.address.getTxs(s);if(!(!c||!c.length))for(let a of c){let u=a.status;if(u.confirmed!==!0)continue;let d=a.vout.slice(-1)[0];if(!d)continue;let f=LI(d.scriptpubkey);if(!f||!await t.spendsFromAddress(a,s,r))continue;let h=i-u.block_height+1;n.get(o)?.push({tx:a,signalBytes:f,blockMetadata:{confirmations:h,height:u.block_height,time:u.block_time}})}}return n}static async fullnode(e,r){let n=new Map;for(let u of e)n.set(u,[]);let i=r.rpc;if(!i)throw new Le("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=new Map(e.map(u=>[hn.parseBitcoinAddress(u.serviceEndpoint),u])),c=0,a=await r.rpc.getBlock({height:c});for(console.info("Searching for beacon signals, please wait ...");a.height<=o;){for(let u of a.tx){if(u.txid===B0)continue;let d=u.vout.slice(-1)[0];if(!d)continue;let f=LI(d.scriptPubKey?.hex);if(!f)continue;let h=new Set;for(let p of u.vin){if(p.coinbase||p.txinwitness&&p.txinwitness.length===1&&p.txinwitness[0]===I0||!p.txid||p.vout===void 0)continue;let g=await i.getRawTransaction(p.txid,2);if(!g.vout[p.vout])continue;let y=g.vout[p.vout].scriptPubKey;if(!y.address)continue;let x=s.get(y.address);!x||h.has(x)||(h.add(x),console.info(`Tx ${u.txid} contains beacon address ${y.address}`),n.get(x)?.push({tx:u,signalBytes:f,blockMetadata:{height:a.height,time:a.time,confirmations:a.confirmations}}))}}if(c+=1,c>o){console.info(`Chain tip reached ${c}, breaking ...`);break}a=await i.getBlock({height:c})}return n}};l();l();l();l();l();l();l();var hre=new Uint8Array(0);function MI(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function vL(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,x=0,S=0,_=g.length;S!==_&&g[S]===0;)S++,y++;for(var A=(_-S)*d+1>>>0,O=new Uint8Array(A);S!==_;){for(var T=g[S],M=0,q=A-1;(T!==0||M<x)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");x=M,S++}for(var j=A-x;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var x=0,S=0;g[y]===a;)x++,y++;for(var _=(g.length-y)*u+1>>>0,A=new Uint8Array(_);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=_-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=_-S;q!==_&&A[q]===0;)q++;for(var j=new Uint8Array(x+(_-q)),$=x;q!==_;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var SL=vL,AL=SL,KI=AL;var qb=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Fb=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return $I(this,e)}},jb=class{decoders;constructor(e){this.decoders=e}or(e){return $I(this,e)}decode(e){let r=e[0],n=this.decoders[r];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 $I(t,e){return new jb({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Wb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new qb(e,r,n),this.decoder=new Fb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function TL({name:t,prefix:e,encode:r,decode:n}){return new Wb(t,e,r,n)}function Gb({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=KI(r,t);return TL({prefix:e,name:t,encode:n,decode:o=>MI(i(o))})}var hf=Gb({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sre=Gb({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();function HI(t){return t===void 0?[]:Array.isArray(t)?t:[t]}var au=class{cryptosuite;constructor(e){this.cryptosuite=e}addProof(e,r){let n=this.cryptosuite.createProof(e,r);if(!n.type||!n.verificationMethod||!n.proofPurpose)throw new wn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",_o,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new wn("Domain mismatch: proof.domain !== config.domain",_o,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new wn("Challenge mismatch options and challenge passed",_o,{config:r,proof:n});let i=e;return i.proof=n,i}verifyProof(e,r,n,i,o){let s=JSON.parse(e),c=s.proof;if(!c.type||!c.verificationMethod||!c.proofPurpose)throw new wn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Ni,s);if(r&&r!==c.proofPurpose)throw new wn("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",Ni,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new wn("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){let u=HI(i),d=HI(c.domain);if(u.length!==d.length)throw new wn("Domain mismatch: expectedDomain length does not match proof.domain length",Ni,{proof:c,expectedDomain:i});if(!u.every(f=>d.includes(f))||!d.every(f=>u.includes(f)))throw new wn("Domain mismatch: expectedDomain and proof.domain do not match",Ni,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var uu=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new au(this)}#e(){return{type:this.type,cryptosuite:this.cryptosuite,verificationMethod:this.multikey.fullId()}}createProof(e,r){r["@context"]=e["@context"]??r["@context"];let n=this.proofConfiguration(r),i=this.transformDocument(e,r),o=this.generateHash(n,i),s=this.proofSerialization(o,r),c=r;return c.proofValue=hf.encode(s),c.cryptosuite=this.cryptosuite,c.type=this.type,c}verifyProof(e){let{proof:r,...n}=e,{proofValue:i,...o}=r,s=this.transformDocument(n,o),c=this.proofConfiguration(o),a=this.generateHash(c,s),u=hf.decode(e.proof.proofValue),d=this.proofVerification(a,u,o);return{verified:d,verifiedDocument:d?e:void 0}}transformDocument(e,r){if(r.type!==this.type)throw new we("Type mismatch: config.type !== this.type",Ni,{config:r,suite:this.#e()});if(r.cryptosuite!==this.cryptosuite)throw new we("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Ni,{config:r,suite:this.#e()});return rr(e)}generateHash(e,r){let n=ke(xs(e)),i=ke(xs(r)),o=ft(n,i);return ke(o)}proofConfiguration(e){if(e.type!==this.type)throw new To("Type mismatch: config.type !== this.type",_o,{config:e,suite:this.#e()});if(e.cryptosuite!==this.cryptosuite)throw new To("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",_o,{config:e,suite:this.#e()});if(e.created&&!Ro.isValidXsdDateTime(e.created))throw new To('Invalid config: "created" must be a valid XMLSchema DateTime string',_o,e);return rr(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new To("Id mismatch: config.verificationMethod !== this.multikey.fullId()",uv,{config:r,suite:this.#e()});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new To("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Ni,{config:n,suite:this.#e()});return this.multikey.verify(r,e)}};l();l();l();var us=class t{static type="Multikey";id;controller;#e;#t;constructor({id:e,controller:r,keyPair:n,externalSigner:i}){if(!n)throw new xn('Argument missing: "keyPair" required',"CONSTRUCTOR_ERROR");if(!n.publicKey)throw new xn('Argument missing: "keyPair" must contain a "publicKey"',"CONSTRUCTOR_ERROR");if(i){let o=i.publicKey,s=n.publicKey.compressed;if(o.length!==s.length||!o.every((c,a)=>c===s[a]))throw new xn("externalSigner.publicKey does not match keyPair.publicKey.compressed","CONSTRUCTOR_ERROR")}this.id=e,this.controller=r,this.#e=n,this.#t=i}get keyPair(){return this.#e}get publicKey(){return this.#e.publicKey}get secretKey(){try{return this.#e.secretKey}catch{throw new xn("Cannot get: no secretKey","PRIVATE_KEY_ERROR")}}toCryptosuite(){return new uu(this)}sign(e){if(this.#t)return this.#t.sign(e,"bip340");if(!this.signer)throw new xn("Cannot sign: no secretKey","SIGN_ERROR");return Ur.sign(e,this.secretKey.bytes,Ir(32))}verify(e,r){return Ur.verify(e,r,this.publicKey.x)}fullId(){return this.id.startsWith("#")?`${this.controller}${this.id}`:this.id}toVerificationMethod(){return{id:this.id,type:t.type,controller:this.controller,publicKeyMultibase:this.publicKey.multibase.encoded}}get signer(){return!!this.#t||!!this.#e.secretKey}toJSON(){let e;try{e=this.signer}catch{e=!1}return{id:this.id,controller:this.controller,fullId:this.fullId(),signer:e,keyPair:this.keyPair.toJSON(),verificationMethod:this.toVerificationMethod()}}static create({id:e,controller:r,keyPair:n}){return new t({id:e,controller:r,keyPair:n})}static fromSecretKey(e,r,n){let i=new Vr(n),o=i.computePublicKey(),s=new uo({publicKey:o,secretKey:i});return new t({id:e,controller:r,keyPair:s})}static fromSigner(e,r,n){let i=new ut(n.publicKey),o=new uo({publicKey:i});return new t({id:e,controller:r,keyPair:o,externalSigner:n})}static fromPublicKey({id:e,controller:r,publicKeyBytes:n}){let i=new ut(n),o=new uo({publicKey:i});return new t({id:e,controller:r,keyPair:o})}static fromVerificationMethod({id:e,controller:r,publicKeyMultibase:n}){if(!n)throw new xn("Invalid publicKeyMultibase: cannot be undefined",gl,{publicKeyMultibase:n});let i=hf.decode(n);if(i.length!==35)throw new xn(`Invalid publicKeyMultibase length: ${i.length}`,gl,{publicKeyMultibase:n});if(i[0]!==231||i[1]!==1)throw new xn(`Invalid publicKeyMultibase prefix: expected secp256k1 multicodec [0xe7, 0x01], got [0x${i[0]?.toString(16)??"??"}, 0x${i[1]?.toString(16)??"??"}]`,gl,{publicKeyMultibase:n});let o=i.slice(2),s=new uo({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();l();var Yp=class t{#e={phase:"Construct"};#t;#n;#r;#o;#i;constructor(e){this.#t=e.sourceDocument,this.#n=e.patches,this.#r=e.sourceVersionId,this.#o=e.verificationMethod,this.#i=e.beaconService}static construct(e,r,n){let i={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],patch:r,targetHash:"",targetVersionId:n+1,sourceHash:Gn(e)},o=Xc.apply(e,r);if(o.id!==e.id)throw new St(`Patches must not change the DID document id (source "${e.id}" to target "${o.id}").`,Ie,{sourceId:e.id,targetId:o.id});try{ln.isValid(o)}catch(s){throw new St("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),Ie,o)}return i.targetHash=Gn(o),i}static sign(e,r,n,i){if(!e.startsWith("did:btcr2:"))throw new St(`Expected a did:btcr2 identifier for the root capability; got "${e}".`,Ie,{did:e});let o=n.controller,s=n.id.indexOf("#");if(s<0)throw new St(`Verification method id must contain a fragment (e.g. "${n.id}#initialKey"); got "${n.id}".`,Ie,{verificationMethodId:n.id});let c=n.id.slice(s),a=us.fromSigner(c,o,i),u=s===0?`${e}${c}`:n.id,d=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&d!==n.publicKeyMultibase)throw new St(`Signing key does not match verification method "${n.id}": the signer's public key differs from the method's published publicKeyMultibase.`,Ie,{verificationMethodId:n.id,expected:n.publicKeyMultibase,actual:d});let f={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],cryptosuite:"bip340-jcs-2025",type:"DataIntegrityProof",verificationMethod:u,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"};return a.toCryptosuite().toDataIntegrityProof().addProof(r,f)}static async announce(e,r,n,i,o,s){return ia.establish(e,r).broadcastSignal(n,i,o,s)}#s(){return t.construct(this.#t,this.#n,this.#r)}advance(){for(;;)switch(this.#e.phase){case"Construct":{let e=this.#s();this.#e={phase:"Sign",unsignedUpdate:e};continue}case"Sign":return{status:"action-required",needs:[{kind:"NeedSigningKey",verificationMethodId:this.#o.id,unsignedUpdate:this.#e.unsignedUpdate}]};case"Fund":return{status:"action-required",needs:[{kind:"NeedFunding",beaconAddress:this.#i.serviceEndpoint.replace("bitcoin:",""),beaconService:this.#i}]};case"Broadcast":return{status:"action-required",needs:[{kind:"NeedBroadcast",beaconService:this.#i,signedUpdate:this.#e.signedUpdate,did:this.#t.id}]};case"Complete":return{status:"complete",result:{signedUpdate:this.#e.signedUpdate}}}}provide(e,r){switch(e.kind){case"NeedSigningKey":{if(this.#e.phase!=="Sign")throw new St(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,Ie,{phase:this.#e.phase});if(!r)throw new St("NeedSigningKey requires a Signer.",Ie);let n=this.#e.unsignedUpdate,i=t.sign(this.#t.id,n,this.#o,r);this.#e={phase:"Fund",unsignedUpdate:n,signedUpdate:i};break}case"NeedFunding":{if(this.#e.phase!=="Fund")throw new St(`Cannot provide NeedFunding: updater phase is ${this.#e.phase}, expected Fund.`,Ie,{phase:this.#e.phase});if(r!==void 0){let n=r;if(typeof n.utxoCount!="number"||!Number.isFinite(n.utxoCount)||n.utxoCount<1)throw new St(`NeedFunding proof must have utxoCount >= 1; got ${String(n.utxoCount)}.`,Ie,{utxoCount:n.utxoCount})}this.#e={phase:"Broadcast",unsignedUpdate:this.#e.unsignedUpdate,signedUpdate:this.#e.signedUpdate};break}case"NeedBroadcast":{if(this.#e.phase!=="Broadcast")throw new St(`Cannot provide NeedBroadcast: updater phase is ${this.#e.phase}, expected Broadcast.`,Ie,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};var Jp=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new we("idType is required for creating a did:btcr2 identifier",De,r);return vr.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=vr.decode(e),i=ds.sidecarData(r.sidecar),o=n.hrp===Tl.k?ds.deterministic(n):null;return new ds(n,i,o,{versionId:r.versionId,versionTime:r.versionTime,genesisDocument:r.sidecar?.genesisDocument,maxDiscoveryRounds:r.maxDiscoveryRounds,minConf:r.minConf})}static update({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethodId:i,beaconId:o}){let s=at.relationshipMethodId(i,e.id);if(!(s!==void 0&&e.capabilityInvocation?.some(f=>at.relationshipMethodId(f,e.id)===s)))throw new St("Invalid verificationMethodId: not authorized for capabilityInvocation",De,e);let a=this.getSigningMethod(e,i);if(!a)throw new St("Invalid verificationMethod: not found in source document",De,{sourceDocument:e,verificationMethodId:i});if(a.type!==su)throw new St(`Invalid verificationMethod: verificationMethod.type must be "${su}"`,De,a);if(!a.publicKeyMultibase?.startsWith(cu))throw new St(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${cu}"`,De,a);let u=at.absoluteDidUrl(o,e.id),d=e.service.filter(f=>u!==void 0&&at.absoluteDidUrl(f.id,e.id)===u).filter(f=>!!f).shift();if(!d)throw new St("No beacon service found for provided beaconId",Ie,{sourceDocument:e,beaconId:o});return new Yp({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:a,beaconService:d})}static getSigningMethod(e,r){r??="#initialKey";let n=me.parse(e.id);if(n&&n.method!==this.methodName)throw new we(`Method not supported: ${n.method}`,yl,{identifier:e.id});let i=at.absoluteDidUrl(r,e.id)??at.relationshipMethodId(e.assertionMethod?.[0],e.id),o=i===void 0?void 0:e.verificationMethod?.find(s=>at.absoluteDidUrl(s.id,e.id)===i);if(!(o&&o.publicKeyMultibase))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o}};var _L=6;function pf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function IL(t){return pf(t)&&Object.values(t).every(e=>typeof e=="string")}function BL(t){return pf(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&Number.isInteger(t.targetVersionId)&&t.targetVersionId>=2&&pf(t.proof):!1}function RL(t){return pf(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}function UL(t){if(t===void 0)return _L;if(typeof t=="number"&&Number.isInteger(t)&&t>=1)return t;let e=typeof t=="string"?JSON.stringify(t):String(t);throw new Le(`Invalid resolution option minConf: expected a positive integer (minimum 1), got ${e}.`,dv,{minConf:t})}var ds=class t{#e;#t;#n;#r;#o;#i;#s=null;#f=new Map;#l=new Set;#d=new Set;#c=[];#a=null;#h=1;#g=[];#u;#p=0;#y;constructor(e,r,n,i){this.#e=e,this.#o=r,this.#i=n,this.#t=i?.versionId,this.#n=i?.versionTime;let o=i?.maxDiscoveryRounds;this.#u=typeof o=="number"&&o>0?o:1/0,this.#y=UL(i?.minConf),i?.genesisDocument&&(this.#s=i.genesisDocument),this.#r=n?"BeaconDiscovery":"GenesisDocument"}static deterministic(e){let r=e.genesisBytes,n=vr.encode(r,e),{multibase:i}=new ut(r),o=hn.generateBeaconServices({id:n,publicKey:r,network:Uo(e.network),beaconType:"SingletonBeacon"});return new ln({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=Bo(r);if(!go(e.genesisBytes,n))throw new Le("Initial document mismatch: genesisBytes !== genesisDocumentHash",De,{genesisBytes:Zr(e.genesisBytes,"hex"),genesisDocumentHash:Zr(n,"hex")});let i=vr.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(dr,i));return new ln(o)}static sidecarData(e={}){let r=new Map;if(e.updates?.length)for(let o of e.updates)r.set(Gn(o,{encoding:"hex"}),o);let n=new Map;if(e.casUpdates?.length)for(let o of e.casUpdates)n.set(Gn(o,{encoding:"hex"}),o);let i=new Map;if(e.smtProofs?.length)for(let o of e.smtProofs)i.set(Zr(Os(o.id,"base64urlnopad"),"hex"),o);return{updateMap:r,casMap:n,smtMap:i}}static updates(e,r,n,i,o={currentVersionId:1,updateHashHistory:[]}){let s=o.currentVersionId,c=o.updateHashHistory,a=r.sort(([d,f],[h,p])=>d.targetVersionId-h.targetVersionId||f.height-p.height),u={didDocument:e,metadata:{versionId:`${s}`,confirmations:0,updated:"",deactivated:e.deactivated||!1}};for(let[d,f]of a){let h=Bo(u.didDocument),p=Ro.blocktimeToTimestamp(f.time);if(u.metadata.updated=Ro.toISOStringNonFractional(p),u.metadata.confirmations=f.confirmations,d.targetVersionId<=s){this.confirmDuplicate(d,c);continue}if(n&&p>Ro.dateStringToTimestamp(n))return u;if(d.targetVersionId===s+1){let y=Os(d.sourceHash,"base64urlnopad");if(!go(y,h))throw new Le("Hash mismatch: update.sourceHash !== currentDocumentHash",Ie,{sourceHash:d.sourceHash,currentDocumentHash:Zr(h,"hex")});u.didDocument=this.applyUpdate(u.didDocument,d);let x=ks.deleteKeys(d,["proof"]);c.push(Bo(x))}else throw new Le("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",ml,{targetVersionId:d.targetVersionId,currentVersionId:s+1});s++,u.metadata.versionId=`${s}`;let g=Number(i);if(!isNaN(g)&&g<=s)return u;if(u.didDocument.deactivated)return u.metadata.deactivated=u.didDocument.deactivated,u}return u}static confirmDuplicate(e,r){if(!Number.isInteger(e.targetVersionId)||e.targetVersionId<2)throw new Le("Invalid duplicate: targetVersionId must be an integer >= 2",Ie,{targetVersionId:e.targetVersionId});let{proof:n,...i}=e,o=Bo(i),s=r[e.targetVersionId-2];if(s===void 0)throw new Le("Invalid duplicate: no applied update in history for targetVersionId",ml,{targetVersionId:e.targetVersionId,historyLength:r.length});if(!go(s,o))throw new Le("Invalid duplicate: unsigned update hash does not match historical hash",ml,{unsignedUpdateHash:Zr(o,"hex"),historicalHash:Zr(s,"hex")})}static applyUpdate(e,r){let n=r.proof?.capability;if(!n)throw new Le("No root capability found in update",Ie,r);let i=at.dereferenceZcapId(n),{invocationTarget:o,controller:s}=i;if(![o,s].every(A=>A===e.id))throw new Le("Invalid root capability",Ie,{rootCapability:i,currentDocument:e});let c=r.proof?.verificationMethod;if(!c)throw new Le("No verificationMethod found in update",Ie,r);let a=at.relationshipMethodId(c,e.id);if(!(a!==void 0&&e.capabilityInvocation?.some(A=>at.relationshipMethodId(A,e.id)===a)))throw new Le("Invalid update: verificationMethod is not authorized for capabilityInvocation",Ie,{verificationMethodId:c,capabilityInvocation:e.capabilityInvocation});let d=Jp.getSigningMethod(e,c),f=us.fromVerificationMethod(d),h=new uu(f),p=rr(r),y=new au(h).verifyProof(p,"capabilityInvocation");if(!y.verified)throw new Le("Invalid update: proof not verified",Ie,y);let x=Xc.apply(e,r.patch);ln.validate(x);let S=Bo(x),_=Os(r.targetHash);if(!go(_,S))throw new Le("Invalid update: update.targetHash !== currentDocumentHash",Ie,{updateTargetHash:_,currentDocumentHash:S});return x}resolve(){for(;;)switch(this.#r){case"GenesisDocument":{if(this.#s){this.#i=t.external(this.#e,this.#s),this.#s=null,this.#r="BeaconDiscovery";continue}return{status:"action-required",needs:[{kind:"NeedGenesisDocument",genesisHash:Zr(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=hn.getBeaconServices(this.#i).filter(n=>{let i=hn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=hn.parseBitcoinAddress(n.serviceEndpoint);this.#d.add(i)}return{status:"action-required",needs:[{kind:"NeedBeaconSignals",beaconServices:r}]}}this.#r="BeaconProcess";continue}case"BeaconProcess":{let e=[];for(let[r,n]of this.#f){if(this.#l.has(r.id)||!n.length)continue;let i=this.#m(n);if(!i.length)continue;let s=ia.establish(r,this.#i.id).processSignals(i,this.#o);s.needs.length>0?e.push(...s.needs):(this.#c.push(...s.updates),this.#l.add(r.id))}if(e.length>0)return{status:"action-required",needs:e};this.#r="ApplyUpdates";continue}case"ApplyUpdates":{if(this.#c.length>0&&(this.#a=t.updates(this.#i,this.#c,this.#n,this.#t,{currentVersionId:this.#h,updateHashHistory:this.#g}),this.#h=Number(this.#a.metadata.versionId),this.#i=this.#a.didDocument,this.#c=[],hn.getBeaconServices(this.#i).some(n=>{let i=hn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)}))){if(++this.#p>this.#u)throw new Le(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,av,{maxDiscoveryRounds:this.#u,discoveryRounds:this.#p});this.#r="BeaconDiscovery";continue}this.#r="Complete";continue}case"Complete":return{status:"resolved",result:this.#a??{didDocument:this.#i,metadata:{versionId:this.#t??"1",deactivated:this.#i.deactivated||!1}}}}}#m(e){let r=[];for(let n of e){let i=n.blockMetadata,o=i?.confirmations;if(!(!Number.isInteger(o)||o<this.#y)){if(!Number.isFinite(i?.height)||!Number.isFinite(i?.time))throw new Le(`Beacon signal ${n.signalBytes} has ${o} confirmations but no valid block height or block time.`,Ie,{signalBytes:n.signalBytes,confirmations:o,height:i?.height,time:i?.time});r.push(n)}}return r}provide(e,r){switch(e.kind){case"NeedGenesisDocument":{if(!pf(r))throw new Le("Provided data for NeedGenesisDocument must be a document object.",Ie,{kind:e.kind});this.#s=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new Le("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",Ie,{kind:e.kind});for(let[n,i]of r)this.#f.set(n,i);break}case"NeedCASAnnouncement":{if(!IL(r))throw new Le("Provided data for NeedCASAnnouncement is not a CAS announcement.",Ie,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new Le(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,Ie,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!BL(r))throw new Le("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",Ie,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.updateHash)throw new Le(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,Ie,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!RL(r))throw new Le("Provided data for NeedSMTProof is not an SMT proof.",Ie,{kind:e.kind});let n=Zr(Os(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new Le(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,Ie,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function OL(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new qe("Cannot derive aggregation communication key: capabilityInvocation is absent",De,{id:t.id});let r=at.absoluteDidUrl(e,t.id),n=typeof e=="string"?r===void 0?void 0:t.verificationMethod?.find(i=>at.absoluteDidUrl(i.id,t.id)===r):e;if(!n)throw new qe(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,De,{id:t.id,invocation:e});return us.fromVerificationMethod(n).publicKey}function Cne(t,e){try{let r=vr.decode(t);if(r.idType==="KEY")return new ut(r.genesisBytes);if(e?.genesisDocument){let n=ds.external(r,e.genesisDocument);return OL(n)}}catch{}}l();l();l();var VI=class{document={};constructor(e){if(!e.id)throw new qe('Missing required "id" property',De,e);this.document.id=e.id,this.document.verificationMethod=e.verificationMethod??[],e["@context"]&&(this.document["@context"]=e["@context"])}withAuthentication(e){return e&&(this.document.authentication=e),this}withAssertionMethod(e){return e&&(this.document.assertionMethod=e),this}withCapabilityInvocation(e){return e&&(this.document.capabilityInvocation=e),this}withCapabilityDelegation(e){return e&&(this.document.capabilityDelegation=e),this}withService(e){return e&&(this.document.service=e),this}build(){let e=new ln(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};export{gv as AggregateBeaconError,at as Appendix,qte as BECH32M_CHARS,wL as BTCR2_DID_DOCUMENT_CONTEXT,nr as BeaconError,ia as BeaconFactory,PI as BeaconSignalDiscovery,hn as BeaconUtils,_l as CASBeacon,mv as CASBeaconError,bv as CHANGE_OUTPUT_VBYTES,U0 as DEFAULT_FEE_ESTIMATOR,_L as DEFAULT_MIN_CONF,bL as DID_REGEX,xv as DUST_LIMIT_SATS,Jp as DidBtcr2,ln as DidDocument,VI as DidDocumentBuilder,Vb as DidVerificationMethod,lf as GenesisDocument,dr as ID_PLACEHOLDER_VALUE,vr as Identifier,cu as MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX,su as MULTIKEY_VERIFICATION_METHOD_TYPE,WR as P2PKH_BEACON_TX_VSIZE,FR as P2TR_BEACON_TX_VSIZE,jR as P2WPKH_BEACON_TX_VSIZE,ds as Resolver,GR as SINGLETON_BEACON_TX_VSIZE,Ll as SMTBeacon,Fu as SMTBeaconError,O0 as SPENDABLE_DUST_LIMIT_SATS,Oo as SinglePartyBeacon,Il as SingletonBeacon,yv as SingletonBeaconError,ju as StaticFeeEstimator,Yp as Updater,Ev as beaconTxVsize,P$ as buildAggregationBeaconTx,zR as deriveSingletonAddress,vv as detectSingletonScriptKind,LI as extractOpReturnSignalHash,OL as getAggregationCommunicationKey,xL as isMultikeyVerificationMethod,Tv as opReturnScript,Cne as resolveBtcr2SenderPk,Sv as resolveChangeAddress,ZR as selectSpendableUtxo};
4
4
  /*! Bundled license information:
5
5
 
6
6
  ieee754/index.js: