@did-btcr2/method 0.65.1 → 0.66.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.js CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var BTCR2=(()=>{var _B=Object.create;var Df=Object.defineProperty;var IB=Object.getOwnPropertyDescriptor;var BB=Object.getOwnPropertyNames;var RB=Object.getPrototypeOf,UB=Object.prototype.hasOwnProperty;var OB=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Au=(t,e)=>{for(var r in e)Df(t,r,{get:e[r],enumerable:!0})},vx=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of BB(e))!UB.call(t,i)&&i!==r&&Df(t,i,{get:()=>e[i],enumerable:!(n=IB(e,i))||n.enumerable});return t};var Kn=(t,e,r)=>(r=t!=null?_B(RB(t)):{},vx(e||!t||!t.__esModule?Df(r,"default",{value:t,enumerable:!0}):r,t)),DB=t=>vx(Df({},"__esModule",{value:!0}),t);var Tx=oe(kf=>{"use strict";l();kf.byteLength=NB;kf.toByteArray=LB;kf.fromByteArray=KB;var $n=[],Jr=[],kB=typeof Uint8Array<"u"?Uint8Array:Array,dy="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(gs=0,Sx=dy.length;gs<Sx;++gs)$n[gs]=dy[gs],Jr[dy.charCodeAt(gs)]=gs;var gs,Sx;Jr[45]=62;Jr[95]=63;function Ax(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 NB(t){var e=Ax(t),r=e[0],n=e[1];return(r+n)*3/4-n}function CB(t,e,r){return(e+r)*3/4-r}function LB(t){var e,r=Ax(t),n=r[0],i=r[1],o=new kB(CB(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Jr[t.charCodeAt(a)]<<18|Jr[t.charCodeAt(a+1)]<<12|Jr[t.charCodeAt(a+2)]<<6|Jr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Jr[t.charCodeAt(a)]<<2|Jr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Jr[t.charCodeAt(a)]<<10|Jr[t.charCodeAt(a+1)]<<4|Jr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function PB(t){return $n[t>>18&63]+$n[t>>12&63]+$n[t>>6&63]+$n[t&63]}function MB(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(PB(n));return i.join("")}function KB(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(MB(t,s,s+o>c?c:s+o));return n===1?(e=t[r-1],i.push($n[e>>2]+$n[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push($n[e>>10]+$n[e>>4&63]+$n[e<<2&63]+"=")),i.join("")}});var _x=oe(fy=>{l();fy.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)};fy.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 Ir=oe(Cc=>{"use strict";l();var ly=Tx(),Nc=_x(),Ix=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Cc.Buffer=F;Cc.SlowBuffer=jB;Cc.INSPECT_MAX_BYTES=50;var Nf=2147483647;Cc.kMaxLength=Nf;F.TYPED_ARRAY_SUPPORT=$B();!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 $B(){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 bi(t){if(t>Nf)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 gy(t)}return Ux(t,e,r)}F.poolSize=8192;function Ux(t,e,r){if(typeof t=="string")return VB(t,e);if(ArrayBuffer.isView(t))return qB(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(Hn(t,ArrayBuffer)||t&&Hn(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Hn(t,SharedArrayBuffer)||t&&Hn(t.buffer,SharedArrayBuffer)))return py(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=FB(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 Ux(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function Ox(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 HB(t,e,r){return Ox(t),t<=0?bi(t):e!==void 0?typeof r=="string"?bi(t).fill(e,r):bi(t).fill(e):bi(t)}F.alloc=function(t,e,r){return HB(t,e,r)};function gy(t){return Ox(t),bi(t<0?0:my(t)|0)}F.allocUnsafe=function(t){return gy(t)};F.allocUnsafeSlow=function(t){return gy(t)};function VB(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=Dx(t,e)|0,n=bi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function hy(t){for(var e=t.length<0?0:my(t.length)|0,r=bi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function qB(t){if(Hn(t,Uint8Array)){var e=new Uint8Array(t);return py(e.buffer,e.byteOffset,e.byteLength)}return hy(t)}function py(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 FB(t){if(F.isBuffer(t)){var e=my(t.length)|0,r=bi(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||wy(t.length)?bi(0):hy(t);if(t.type==="Buffer"&&Array.isArray(t.data))return hy(t.data)}function my(t){if(t>=Nf)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Nf.toString(16)+" bytes");return t|0}function jB(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(Hn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),Hn(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(Hn(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 Dx(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Hn(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 yy(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Mx(t).length;default:if(i)return n?-1:yy(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=Dx;function WB(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 r8(this,e,r);case"utf8":case"utf-8":return Nx(this,e,r);case"ascii":return e8(this,e,r);case"latin1":case"binary":return t8(this,e,r);case"base64":return ZB(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return n8(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function ms(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)ms(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)ms(this,r,r+3),ms(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)ms(this,r,r+7),ms(this,r+1,r+6),ms(this,r+2,r+5),ms(this,r+3,r+4);return this};F.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?Nx(this,0,e):WB.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=Cc.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};Ix&&(F.prototype[Ix]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,o){if(Hn(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 kx(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,wy(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:Bx(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):Bx(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Bx(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 kx(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return kx(this,e,r,n,!1)};function GB(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(wy(c))return s;t[r+s]=c}return s}function zB(t,e,r,n){return Cf(yy(e,t.length-r),t,r,n)}function YB(t,e,r,n){return Cf(s8(e),t,r,n)}function JB(t,e,r,n){return Cf(Mx(e),t,r,n)}function XB(t,e,r,n){return Cf(c8(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 GB(this,e,r,n);case"utf8":case"utf-8":return zB(this,e,r,n);case"ascii":case"latin1":case"binary":return YB(this,e,r,n);case"base64":return JB(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return XB(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 ZB(t,e,r){return e===0&&r===t.length?ly.fromByteArray(t):ly.fromByteArray(t.slice(e,r))}function Nx(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 QB(n)}var Rx=4096;function QB(t){var e=t.length;if(e<=Rx)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Rx));return r}function e8(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 t8(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 r8(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+=a8[t[o]];return i}function n8(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 Ot(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||Ot(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||Ot(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||Ot(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Ot(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Ot(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Ot(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||Ot(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||Ot(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||Ot(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||Ot(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Ot(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||Ot(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||Ot(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||Ot(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||Ot(e,4,this.length),Nc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ot(e,4,this.length),Nc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ot(e,8,this.length),Nc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ot(e,8,this.length),Nc.read(this,e,!1,52,8)};function hr(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;hr(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;hr(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||hr(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||hr(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||hr(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||hr(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||hr(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);hr(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);hr(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||hr(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||hr(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||hr(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||hr(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||hr(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 Cx(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 Lx(t,e,r,n,i){return e=+e,r=r>>>0,i||Cx(t,e,r,4,34028234663852886e22,-34028234663852886e22),Nc.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return Lx(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return Lx(this,e,r,!1,n)};function Px(t,e,r,n,i){return e=+e,r=r>>>0,i||Cx(t,e,r,8,17976931348623157e292,-17976931348623157e292),Nc.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return Px(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return Px(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 i8=/[^+/0-9A-Za-z-_]/g;function o8(t){if(t=t.split("=")[0],t=t.trim().replace(i8,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function yy(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 s8(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function c8(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 Mx(t){return ly.toByteArray(o8(t))}function Cf(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 Hn(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function wy(t){return t!==t}var a8=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 vi=oe((lP,Vx)=>{l();var lt=Vx.exports={},Vn,qn;function by(){throw new Error("setTimeout has not been defined")}function xy(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Vn=setTimeout:Vn=by}catch{Vn=by}try{typeof clearTimeout=="function"?qn=clearTimeout:qn=xy}catch{qn=xy}})();function Kx(t){if(Vn===setTimeout)return setTimeout(t,0);if((Vn===by||!Vn)&&setTimeout)return Vn=setTimeout,setTimeout(t,0);try{return Vn(t,0)}catch{try{return Vn.call(null,t,0)}catch{return Vn.call(this,t,0)}}}function u8(t){if(qn===clearTimeout)return clearTimeout(t);if((qn===xy||!qn)&&clearTimeout)return qn=clearTimeout,clearTimeout(t);try{return qn(t)}catch{try{return qn.call(null,t)}catch{return qn.call(this,t)}}}var xi=[],Lc=!1,ws,Lf=-1;function d8(){!Lc||!ws||(Lc=!1,ws.length?xi=ws.concat(xi):Lf=-1,xi.length&&$x())}function $x(){if(!Lc){var t=Kx(d8);Lc=!0;for(var e=xi.length;e;){for(ws=xi,xi=[];++Lf<e;)ws&&ws[Lf].run();Lf=-1,e=xi.length}ws=null,Lc=!1,u8(t)}}lt.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];xi.push(new Hx(t,e)),xi.length===1&&!Lc&&Kx($x)};function Hx(t,e){this.fun=t,this.array=e}Hx.prototype.run=function(){this.fun.apply(null,this.array)};lt.title="browser";lt.browser=!0;lt.env={};lt.argv=[];lt.version="";lt.versions={};function Ei(){}lt.on=Ei;lt.addListener=Ei;lt.once=Ei;lt.off=Ei;lt.removeListener=Ei;lt.removeAllListeners=Ei;lt.emit=Ei;lt.prependListener=Ei;lt.prependOnceListener=Ei;lt.listeners=function(t){return[]};lt.binding=function(t){throw new Error("process.binding is not supported")};lt.cwd=function(){return"/"};lt.chdir=function(t){throw new Error("process.chdir is not supported")};lt.umask=function(){return 0}});var b,w,pP,l=OB(()=>{b=Kn(Ir()),w=Kn(vi()),pP=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 f1=oe((zH,d1)=>{l();var E6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,jl=()=>E6.now(),v6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),ig=t=>t===1/0||v6(t),og=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&&!ig(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!ig(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-jl());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(jl()+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(!ig(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-jl())):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(jl());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()}};d1.exports=og});var B1=oe(I1=>{"use strict";l();I1.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 Sn=oe((wq,R1)=>{"use strict";l();R1.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 xg=oe((xq,U1)=>{"use strict";l();var bg=null;U1.exports=function(){return bg===null&&(bg={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),bg}});var Sg=oe(O1=>{"use strict";l();var Eg=Sn(),tU=new Set(["buffer","view","utf8"]),vg=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"||!tU.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 Eg(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new Eg(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new Eg(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};O1.Encoding=vg});var Ig=oe(Gl=>{"use strict";l();var{Buffer:Tg}=Ir()||{},{Encoding:_g}=Sg(),rU=xg(),fd=class extends _g{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new ld({encode:this.encode,decode:e=>this.decode(Tg.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},ld=class extends _g{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new fd({encode:e=>{let r=this.encode(e);return Tg.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},Ag=class extends _g{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new fd({encode:e=>Tg.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:r}=rU();return new ld({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Gl.BufferFormat=fd;Gl.ViewFormat=ld;Gl.UTF8Format=Ag});var C1=oe(Vs=>{"use strict";l();var{Buffer:Zt}=Ir()||{Buffer:{isBuffer:()=>!1}},{textEncoder:k1,textDecoder:D1}=xg()(),{BufferFormat:hd,ViewFormat:Bg,UTF8Format:N1}=Ig(),zl=t=>t;Vs.utf8=new N1({encode:function(t){return Zt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?D1.decode(t):String(t)},decode:zl,name:"utf8",createViewTranscoder(){return new Bg({encode:function(t){return ArrayBuffer.isView(t)?t:k1.encode(t)},decode:function(t){return D1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new hd({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Vs.json=new N1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Vs.buffer=new hd({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:zl,name:"buffer",createViewTranscoder(){return new Bg({encode:function(t){return ArrayBuffer.isView(t)?t:Zt.from(String(t),"utf8")},decode:function(t){return Zt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Vs.view=new Bg({encode:function(t){return ArrayBuffer.isView(t)?t:k1.encode(t)},decode:zl,name:"view",createBufferTranscoder(){return new hd({encode:function(t){return Zt.isBuffer(t)?t:ArrayBuffer.isView(t)?Zt.from(t.buffer,t.byteOffset,t.byteLength):Zt.from(String(t),"utf8")},decode:zl,name:`${this.name}+buffer`})}});Vs.hex=new hd({encode:function(t){return Zt.isBuffer(t)?t:Zt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Vs.base64=new hd({encode:function(t){return Zt.isBuffer(t)?t:Zt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var M1=oe(P1=>{"use strict";l();var L1=Sn(),Jl=C1(),{Encoding:nU}=Sg(),{BufferFormat:iU,ViewFormat:oU,UTF8Format:sU}=Ig(),pd=Symbol("formats"),Yl=Symbol("encodings"),cU=new Set(["buffer","view","utf8"]),Rg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>cU.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[Yl]=new Map,this[pd]=new Set(e);for(let r in Jl)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[Yl].values()))}encoding(e){let r=this[Yl].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=fU[e],!r)throw new L1(`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=aU(e)}let{name:n,format:i}=r;if(!this[pd].has(i))if(this[pd].has("view"))r=r.createViewTranscoder();else if(this[pd].has("buffer"))r=r.createBufferTranscoder();else if(this[pd].has("utf8"))r=r.createUTF8Transcoder();else throw new L1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[Yl].set(o,r)}return r}};P1.Transcoder=Rg;function aU(t){if(t instanceof nU)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${lU++}`;switch(uU(t)){case"view":return new oU({...t,name:r});case"utf8":return new sU({...t,name:r});case"buffer":return new iU({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function uU(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 dU={binary:Jl.buffer,"utf-8":Jl.utf8},fU={...Jl,...dU},lU=0});var ga=oe((Uq,Ug)=>{"use strict";l();var ya=typeof Reflect=="object"?Reflect:null,K1=ya&&typeof ya.apply=="function"?ya.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Xl;ya&&typeof ya.ownKeys=="function"?Xl=ya.ownKeys:Object.getOwnPropertySymbols?Xl=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Xl=function(e){return Object.getOwnPropertyNames(e)};function hU(t){console&&console.warn&&console.warn(t)}var H1=Number.isNaN||function(e){return e!==e};function Le(){Le.init.call(this)}Ug.exports=Le;Ug.exports.once=mU;Le.EventEmitter=Le;Le.prototype._events=void 0;Le.prototype._eventsCount=0;Le.prototype._maxListeners=void 0;var $1=10;function Zl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Le,"defaultMaxListeners",{enumerable:!0,get:function(){return $1},set:function(t){if(typeof t!="number"||t<0||H1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");$1=t}});Le.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};Le.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||H1(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 V1(t){return t._maxListeners===void 0?Le.defaultMaxListeners:t._maxListeners}Le.prototype.getMaxListeners=function(){return V1(this)};Le.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")K1(a,this,r);else for(var u=a.length,d=G1(a,u),n=0;n<u;++n)K1(d[n],this,r);return!0};function q1(t,e,r,n){var i,o,s;if(Zl(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=V1(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,hU(c)}return t}Le.prototype.addListener=function(e,r){return q1(this,e,r,!1)};Le.prototype.on=Le.prototype.addListener;Le.prototype.prependListener=function(e,r){return q1(this,e,r,!0)};function pU(){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 F1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=pU.bind(n);return i.listener=r,n.wrapFn=i,i}Le.prototype.once=function(e,r){return Zl(r),this.on(e,F1(this,e,r)),this};Le.prototype.prependOnceListener=function(e,r){return Zl(r),this.prependListener(e,F1(this,e,r)),this};Le.prototype.removeListener=function(e,r){var n,i,o,s,c;if(Zl(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():yU(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Le.prototype.off=Le.prototype.removeListener;Le.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 j1(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?gU(i):G1(i,i.length)}Le.prototype.listeners=function(e){return j1(this,e,!0)};Le.prototype.rawListeners=function(e){return j1(this,e,!1)};Le.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):W1.call(t,e)};Le.prototype.listenerCount=W1;function W1(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}Le.prototype.eventNames=function(){return this._eventsCount>0?Xl(this._events):[]};function G1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function yU(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function gU(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function mU(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))}z1(t,e,o,{once:!0}),e!=="error"&&wU(t,i,{once:!0})})}function wU(t,e,r){typeof t.on=="function"&&z1(t,"error",e,r)}function z1(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 J1=oe((Dq,Y1)=>{l();Y1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var yd=oe(Og=>{"use strict";l();var X1=J1();Og.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};Og.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){X1(()=>e(null,r))}).catch(function(r){X1(()=>e(r))})}});var Ql=oe(Dg=>{"use strict";l();Dg.getCallback=function(t,e){return typeof t=="function"?t:e};Dg.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Vo=oe(nh=>{"use strict";l();var{fromCallback:kg}=yd(),Cr=Sn(),{getOptions:Ng,getCallback:Z1}=Ql(),qs=Symbol("promise"),ma=Symbol("callback"),Qn=Symbol("working"),Fs=Symbol("handleOne"),Vi=Symbol("handleMany"),Cg=Symbol("autoClose"),$o=Symbol("finishWork"),ei=Symbol("returnMany"),Po=Symbol("closing"),gd=Symbol("handleClose"),eh=Symbol("closed"),md=Symbol("closeCallbacks"),Ko=Symbol("keyEncoding"),js=Symbol("valueEncoding"),Lg=Symbol("abortOnClose"),th=Symbol("legacy"),Pg=Symbol("keys"),Mg=Symbol("values"),Mo=Symbol("limit"),rn=Symbol("count"),rh=Object.freeze({}),bU=()=>{},Q1=!1,wd=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[eh]=!1,this[md]=[],this[Qn]=!1,this[Po]=!1,this[Cg]=!1,this[ma]=null,this[Fs]=this[Fs].bind(this),this[Vi]=this[Vi].bind(this),this[gd]=this[gd].bind(this),this[Ko]=r[Ko],this[js]=r[js],this[th]=n,this[Mo]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[rn]=0,this[Lg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[rn]}get limit(){return this[Mo]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[th]?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[Po]?this.nextTick(e,new Cr("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Qn]?this.nextTick(e,new Cr("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Qn]=!0,this[ma]=e,this[rn]>=this[Mo]?this.nextTick(this[Fs],null):this._next(this[Fs])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=Z1(r,n),n=kg(n,qs),r=Ng(r,rh),Number.isInteger(e)?(this[Po]?this.nextTick(n,new Cr("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Qn]?this.nextTick(n,new Cr("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[Mo]<1/0&&(e=Math.min(e,this[Mo]-this[rn])),this[Qn]=!0,this[ma]=n,e<=0?this.nextTick(this[Vi],null,[]):this._nextv(e,r,this[Vi])),n[qs]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[qs])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[th]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[th]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=Z1(e,r),r=kg(r,qs),e=Ng(e,rh),this[Po]?this.nextTick(r,new Cr("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Qn]?this.nextTick(r,new Cr("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Qn]=!0,this[ma]=r,this[Cg]=!0,this[rn]>=this[Mo]?this.nextTick(this[Vi],null,[]):this._all(e,this[Vi])),r[qs]}_all(e,r){let n=this[rn],i=[],o=()=>{let c=this[Mo]<1/0?Math.min(1e3,this[Mo]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,rh,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[$o](){let e=this[ma];return this[Lg]&&e===null?bU:(this[Qn]=!1,this[ma]=null,this[Po]&&this._close(this[gd]),e)}[ei](e,r,n){this[Cg]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=Ng(r,rh),!this[Po]){if(this[Qn])throw new Cr("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[Ko]),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 Cr("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=kg(e,qs),this[eh]?this.nextTick(e):this[Po]?this[md].push(e):(this[Po]=!0,this[md].push(e),this[Qn]?this[Lg]&&this[$o]()(new Cr("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[gd])),e[qs]}_close(e){this.nextTick(e)}[gd](){this[eh]=!0,this.db.detachResource(this);let e=this[md];this[md]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[eh]||await this.close()}}},wa=class extends wd{constructor(e,r){super(e,r,!0),this[Pg]=r.keys!==!1,this[Mg]=r.values!==!1}[Fs](e,r,n){let i=this[$o]();if(e)return i(e);try{r=this[Pg]&&r!==void 0?this[Ko].decode(r):void 0,n=this[Mg]&&n!==void 0?this[js].decode(n):void 0}catch(o){return i(new Ho("entry",o))}r===void 0&&n===void 0||this[rn]++,i(null,r,n)}[Vi](e,r){let n=this[$o]();if(e)return this[ei](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[Pg]&&o!==void 0?this[Ko].decode(o):void 0,i[1]=this[Mg]&&s!==void 0?this[js].decode(s):void 0}}catch(i){return this[ei](n,new Ho("entries",i))}this[rn]+=r.length,this[ei](n,null,r)}end(e){return!Q1&&typeof console<"u"&&(Q1=!0,console.warn(new Cr("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)}},Kg=class extends wd{constructor(e,r){super(e,r,!1)}[Fs](e,r){let n=this[$o]();if(e)return n(e);try{r=r!==void 0?this[Ko].decode(r):void 0}catch(i){return n(new Ho("key",i))}r!==void 0&&this[rn]++,n(null,r)}[Vi](e,r){let n=this[$o]();if(e)return this[ei](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Ko].decode(o):void 0}}catch(i){return this[ei](n,new Ho("keys",i))}this[rn]+=r.length,this[ei](n,null,r)}},$g=class extends wd{constructor(e,r){super(e,r,!1)}[Fs](e,r){let n=this[$o]();if(e)return n(e);try{r=r!==void 0?this[js].decode(r):void 0}catch(i){return n(new Ho("value",i))}r!==void 0&&this[rn]++,n(null,r)}[Vi](e,r){let n=this[$o]();if(e)return this[ei](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[js].decode(o):void 0}}catch(i){return this[ei](n,new Ho("values",i))}this[rn]+=r.length,this[ei](n,null,r)}},Ho=class extends Cr{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(wa.prototype,t.split(" ")[0],{get(){throw new Cr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new Cr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});wa.keyEncoding=Ko;wa.valueEncoding=js;nh.AbstractIterator=wa;nh.AbstractKeyIterator=Kg;nh.AbstractValueIterator=$g});var e2=oe(Hg=>{"use strict";l();var{AbstractKeyIterator:xU,AbstractValueIterator:EU}=Vo(),Ws=Symbol("iterator"),bd=Symbol("callback"),ba=Symbol("handleOne"),Gs=Symbol("handleMany"),xd=class extends xU{constructor(e,r){super(e,r),this[Ws]=e.iterator({...r,keys:!0,values:!1}),this[ba]=this[ba].bind(this),this[Gs]=this[Gs].bind(this)}},ih=class extends EU{constructor(e,r){super(e,r),this[Ws]=e.iterator({...r,keys:!1,values:!0}),this[ba]=this[ba].bind(this),this[Gs]=this[Gs].bind(this)}};for(let t of[xd,ih]){let e=t===xd,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[bd]=n,this[Ws].next(this[ba])},t.prototype[ba]=function(n,i,o){let s=this[bd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[bd]=o,this[Ws].nextv(n,i,this[Gs])},t.prototype._all=function(n,i){this[bd]=i,this[Ws].all(n,this[Gs])},t.prototype[Gs]=function(n,i){let o=this[bd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[Ws].seek(n,i)},t.prototype._close=function(n){this[Ws].close(n)}}Hg.DefaultKeyIterator=xd;Hg.DefaultValueIterator=ih});var t2=oe(dh=>{"use strict";l();var{AbstractIterator:vU,AbstractKeyIterator:SU,AbstractValueIterator:AU}=Vo(),Vg=Sn(),mr=Symbol("nut"),ah=Symbol("undefer"),uh=Symbol("factory"),oh=class extends vU{constructor(e,r){super(e,r),this[mr]=null,this[uh]=()=>e.iterator(r),this.db.defer(()=>this[ah]())}},sh=class extends SU{constructor(e,r){super(e,r),this[mr]=null,this[uh]=()=>e.keys(r),this.db.defer(()=>this[ah]())}},ch=class extends AU{constructor(e,r){super(e,r),this[mr]=null,this[uh]=()=>e.values(r),this.db.defer(()=>this[ah]())}};for(let t of[oh,sh,ch])t.prototype[ah]=function(){this.db.status==="open"&&(this[mr]=this[uh]())},t.prototype._next=function(e){this[mr]!==null?this[mr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new Vg("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[mr]!==null?this[mr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new Vg("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[mr]!==null?this[mr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new Vg("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[mr]!==null?this[mr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[mr]!==null?this[mr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};dh.DeferredIterator=oh;dh.DeferredKeyIterator=sh;dh.DeferredValueIterator=ch});var Fg=oe(n2=>{"use strict";l();var{fromCallback:r2}=yd(),fh=Sn(),{getCallback:TU,getOptions:_U}=Ql(),lh=Symbol("promise"),nn=Symbol("status"),xa=Symbol("operations"),Ed=Symbol("finishClose"),Ea=Symbol("closeCallbacks"),qg=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[xa]=[],this[Ea]=[],this[nn]="open",this[Ed]=this[Ed].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[xa].length}put(e,r,n){if(this[nn]!=="open")throw new fh("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[xa].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[nn]!=="open")throw new fh("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[xa].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[nn]!=="open")throw new fh("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[xa]=[],this}_clear(){}write(e,r){return r=TU(e,r),r=r2(r,lh),e=_U(e),this[nn]!=="open"?this.nextTick(r,new fh("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[nn]="writing",this._write(e,n=>{this[nn]="closing",this[Ea].push(()=>r(n)),n||this.db.emit("batch",this[xa]),this._close(this[Ed])})),r[lh]}_write(e,r){}close(e){return e=r2(e,lh),this[nn]==="closing"?this[Ea].push(e):this[nn]==="closed"?this.nextTick(e):(this[Ea].push(e),this[nn]!=="writing"&&(this[nn]="closing",this._close(this[Ed]))),e[lh]}_close(e){this.nextTick(e)}[Ed](){this[nn]="closed",this.db.detachResource(this);let e=this[Ea];this[Ea]=[];for(let r of e)r()}};n2.AbstractChainedBatch=qg});var o2=oe(i2=>{"use strict";l();var{AbstractChainedBatch:IU}=Fg(),BU=Sn(),va=Symbol("encoded"),jg=class extends IU{constructor(e){super(e),this[va]=[]}_put(e,r,n){this[va].push({...n,type:"put",key:e,value:r})}_del(e,r){this[va].push({...r,type:"del",key:e})}_clear(){this[va]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[va].length===0?this.nextTick(r):this.db._batch(this[va],e,r):this.nextTick(r,new BU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};i2.DefaultChainedBatch=jg});var a2=oe((zq,c2)=>{"use strict";l();var s2=Sn(),RU=Object.prototype.hasOwnProperty,UU=new Set(["lt","lte","gt","gte"]);c2.exports=function(t,e){let r={};for(let n in t)if(RU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new s2(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new s2("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});UU.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 Wg=oe((Jq,d2)=>{l();var u2;d2.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(u2||(u2=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var h2=oe((Zq,l2)=>{"use strict";l();var f2=Wg();l2.exports=function(t,...e){e.length===0?f2(t):f2(()=>t(...e))}});var p2=oe(hh=>{"use strict";l();var{AbstractIterator:OU,AbstractKeyIterator:DU,AbstractValueIterator:kU}=Vo(),Sa=Symbol("unfix"),An=Symbol("iterator"),zs=Symbol("handleOne"),qo=Symbol("handleMany"),qi=Symbol("callback"),vd=class extends OU{constructor(e,r,n,i){super(e,r),this[An]=n,this[Sa]=i,this[zs]=this[zs].bind(this),this[qo]=this[qo].bind(this),this[qi]=null}[zs](e,r,n){let i=this[qi];if(e)return i(e);r!==void 0&&(r=this[Sa](r)),i(e,r,n)}[qo](e,r){let n=this[qi];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[Sa](o))}n(e,r)}},Sd=class extends DU{constructor(e,r,n,i){super(e,r),this[An]=n,this[Sa]=i,this[zs]=this[zs].bind(this),this[qo]=this[qo].bind(this),this[qi]=null}[zs](e,r){let n=this[qi];if(e)return n(e);r!==void 0&&(r=this[Sa](r)),n(e,r)}[qo](e,r){let n=this[qi];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[Sa](o))}n(e,r)}},Ad=class extends kU{constructor(e,r,n){super(e,r),this[An]=n}};for(let t of[vd,Sd])t.prototype._next=function(e){this[qi]=e,this[An].next(this[zs])},t.prototype._nextv=function(e,r,n){this[qi]=n,this[An].nextv(e,r,this[qo])},t.prototype._all=function(e,r){this[qi]=r,this[An].all(e,this[qo])};for(let t of[Ad])t.prototype._next=function(e){this[An].next(e)},t.prototype._nextv=function(e,r,n){this[An].nextv(e,r,n)},t.prototype._all=function(e,r){this[An].all(e,r)};for(let t of[vd,Sd,Ad])t.prototype._seek=function(e,r){this[An].seek(e,r)},t.prototype._close=function(e){this[An].close(e)};hh.AbstractSublevelIterator=vd;hh.AbstractSublevelKeyIterator=Sd;hh.AbstractSublevelValueIterator=Ad});var w2=oe((rF,m2)=>{"use strict";l();var Gg=Sn(),{Buffer:Jg}=Ir()||{},{AbstractSublevelIterator:NU,AbstractSublevelKeyIterator:CU,AbstractSublevelValueIterator:LU}=p2(),Fi=Symbol("prefix"),y2=Symbol("upperBound"),Td=Symbol("prefixRange"),Lr=Symbol("parent"),zg=Symbol("unfix"),g2=new TextEncoder,PU={separator:"!"};m2.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new Gg("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new Gg("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?PU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=KU(i,s);let u=s.charCodeAt(0)+1,d=n[Lr]||n;if(!g2.encode(i).every(p=>p>u&&p<127))throw new Gg(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(MU(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[Lr]=d,this[Fi]=new ph(f),this[y2]=new ph(h),this[zg]=new Xg,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[Fi].utf8+n;if(n.byteLength===0)return this[Fi][i];if(i==="view"){let o=this[Fi].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[Fi].buffer;return Jg.concat([o,n],o.byteLength+n.byteLength)}}[Td](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[Fi][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[y2][i]}get prefix(){return this[Fi].utf8}get db(){return this[Lr]}_open(n,i){this[Lr].open({passive:!0},i)}_put(n,i,o,s){this[Lr].put(n,i,o,s)}_get(n,i,o){this[Lr].get(n,i,o)}_getMany(n,i,o){this[Lr].getMany(n,i,o)}_del(n,i,o){this[Lr].del(n,i,o)}_batch(n,i,o){this[Lr].batch(n,i,o)}_clear(n,i){this[Td](n,n.keyEncoding),this[Lr].clear(n,i)}_iterator(n){this[Td](n,n.keyEncoding);let i=this[Lr].iterator(n),o=this[zg].get(this[Fi].utf8.length,n.keyEncoding);return new NU(this,n,i,o)}_keys(n){this[Td](n,n.keyEncoding);let i=this[Lr].keys(n),o=this[zg].get(this[Fi].utf8.length,n.keyEncoding);return new CU(this,n,i,o)}_values(n){this[Td](n,n.keyEncoding);let i=this[Lr].values(n);return new LU(this,n,i)}}return{AbstractSublevel:e}};var MU=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:Yg(t,"utf8"),buffer:Yg(t,"buffer"),view:Yg(t,"view")}}},Yg=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},ph=class{constructor(e){this.utf8=e,this.view=g2.encode(e),this.buffer=Jg?Jg.from(this.view.buffer,0,this.view.byteLength):{}}},Xg=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}},KU=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 rm=oe(tm=>{"use strict";l();var{supports:$U}=B1(),{Transcoder:HU}=M1(),{EventEmitter:VU}=ga(),{fromCallback:Fo}=yd(),Tn=Sn(),{AbstractIterator:Ys}=Vo(),{DefaultKeyIterator:qU,DefaultValueIterator:FU}=e2(),{DeferredIterator:jU,DeferredKeyIterator:WU,DeferredValueIterator:GU}=t2(),{DefaultChainedBatch:b2}=o2(),{getCallback:Js,getOptions:jo}=Ql(),yh=a2(),ge=Symbol("promise"),ji=Symbol("landed"),Xs=Symbol("resources"),Zg=Symbol("closeResources"),_d=Symbol("operations"),Id=Symbol("undefer"),gh=Symbol("deferOpen"),x2=Symbol("options"),Ee=Symbol("status"),Zs=Symbol("defaultOptions"),Aa=Symbol("transcoder"),mh=Symbol("keyEncoding"),Qg=Symbol("valueEncoding"),zU=()=>{},Bd=class extends VU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=jo(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[Xs]=new Set,this[_d]=[],this[gh]=!0,this[x2]=s,this[Ee]="opening",this.supports=$U(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[Aa]=new HU(YU(this)),this[mh]=this[Aa].encoding(n||"utf8"),this[Qg]=this[Aa].encoding(i||"utf8");for(let c of this[Aa].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[Zs]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[mh].commonName,valueEncoding:this[Qg].commonName}),key:Object.freeze({keyEncoding:this[mh].commonName})},this.nextTick(()=>{this[gh]&&this.open({passive:!1},zU)})}get status(){return this[Ee]}keyEncoding(e){return this[Aa].encoding(e??this[mh])}valueEncoding(e){return this[Aa].encoding(e??this[Qg])}open(e,r){r=Js(e,r),r=Fo(r,ge),e={...this[x2],...jo(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[Ee]==="closing"||this[Ee]==="opening"?this.once(ji,i?()=>n(i):n):this[Ee]!=="open"?r(new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[Ee]==="opening"?this.once(ji,n):this.nextTick(n):this[Ee]==="closed"||this[gh]?(this[gh]=!1,this[Ee]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[Ee]="closed",this[Zg](()=>{this.emit(ji),n(i)}),this[Id]();return}this[Ee]="open",this[Id](),this.emit(ji),this[Ee]==="open"&&this.emit("open"),this[Ee]==="open"&&this.emit("ready"),n()})):this[Ee]==="open"?this.nextTick(n):this.once(ji,()=>this.open(e,r)),r[ge]}_open(e,r){this.nextTick(r)}close(e){e=Fo(e,ge);let r=n=>{this[Ee]==="opening"||this[Ee]==="closing"?this.once(ji,n?r(n):r):this[Ee]!=="closed"?e(new Tn("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[Ee]==="open"){this[Ee]="closing",this.emit("closing");let n=i=>{this[Ee]="open",this[Id](),this.emit(ji),r(i)};this[Zg](()=>{this._close(i=>{if(i)return n(i);this[Ee]="closed",this[Id](),this.emit(ji),this[Ee]==="closed"&&this.emit("closed"),r()})})}else this[Ee]==="closed"?this.nextTick(r):this.once(ji,()=>this.close(e));return e[ge]}[Zg](e){if(this[Xs].size===0)return this.nextTick(e);let r=this[Xs].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[Xs])o.close(i);n=!1,this[Xs].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=Js(r,n),n=Fo(n,ge),r=jo(r,this[Zs].entry),this[Ee]==="opening")return this.defer(()=>this.get(e,r,n)),n[ge];if(Ta(this,n))return n[ge];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[ge];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 Tn("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[ge]}_get(e,r,n){this.nextTick(n,new Error("NotFound"))}getMany(e,r,n){if(n=Js(r,n),n=Fo(n,ge),r=jo(r,this[Zs].entry),this[Ee]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[ge];if(Ta(this,n))return n[ge];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[ge];if(e.length===0)return this.nextTick(n,null,[]),n[ge];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[ge];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 Tn(`Could not decode one or more of ${d.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[ge]}_getMany(e,r,n){this.nextTick(n,null,new Array(e.length).fill(void 0))}put(e,r,n,i){if(i=Js(n,i),i=Fo(i,ge),n=jo(n,this[Zs].entry),this[Ee]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[ge];if(Ta(this,i))return i[ge];let o=this._checkKey(e)||this._checkValue(r);if(o)return this.nextTick(i,o),i[ge];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[ge]}_put(e,r,n,i){this.nextTick(i)}del(e,r,n){if(n=Js(r,n),n=Fo(n,ge),r=jo(r,this[Zs].key),this[Ee]==="opening")return this.defer(()=>this.del(e,r,n)),n[ge];if(Ta(this,n))return n[ge];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[ge];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[ge]}_del(e,r,n){this.nextTick(n)}batch(e,r,n){if(!arguments.length){if(this[Ee]==="opening")return new b2(this);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=Js(r,n),n=Fo(n,ge),r=jo(r,this[Zs].empty),this[Ee]==="opening")return this.defer(()=>this.batch(e,r,n)),n[ge];if(Ta(this,n))return n[ge];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[ge];if(e.length===0)return this.nextTick(n),n[ge];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[ge];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[ge];let d=this._checkKey(u.key);if(d)return this.nextTick(n,d),n[ge];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[ge];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[ge]}_batch(e,r,n){this.nextTick(n)}sublevel(e,r){return this._sublevel(e,em.defaults(r))}_sublevel(e,r){return new em(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=Js(e,r),r=Fo(r,ge),e=jo(e,this[Zs].empty),this[Ee]==="opening")return this.defer(()=>this.clear(e,r)),r[ge];if(Ta(this,r))return r[ge];let n=e,i=this.keyEncoding(e.keyEncoding);return e=yh(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[ge]}_clear(e,r){this.nextTick(r)}iterator(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=yh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[Ys.keyEncoding]=r,e[Ys.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[Ee]==="opening")return new jU(this,e);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new Ys(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=yh(e,r),e[Ys.keyEncoding]=r,e[Ys.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[Ee]==="opening")return new WU(this,e);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new qU(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=yh(e,r),e[Ys.keyEncoding]=r,e[Ys.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[Ee]==="opening")return new GU(this,e);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new FU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[_d].push(e)}[Id](){if(this[_d].length===0)return;let e=this[_d];this[_d]=[];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[Xs].add(e)}detachResource(e){this[Xs].delete(e)}_chainedBatch(){return new b2(this)}_checkKey(e){if(e==null)return new Tn("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new Tn("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};Bd.prototype.nextTick=h2();var{AbstractSublevel:em}=w2()({AbstractLevel:Bd});tm.AbstractLevel=Bd;tm.AbstractSublevel=em;var Ta=function(t,e){return t[Ee]!=="open"?(t.nextTick(e,new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},YU=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var nm=oe(Qs=>{"use strict";l();Qs.AbstractLevel=rm().AbstractLevel;Qs.AbstractSublevel=rm().AbstractSublevel;Qs.AbstractIterator=Vo().AbstractIterator;Qs.AbstractKeyIterator=Vo().AbstractKeyIterator;Qs.AbstractValueIterator=Vo().AbstractValueIterator;Qs.AbstractChainedBatch=Fg().AbstractChainedBatch});var v2=oe((aF,E2)=>{l();E2.exports=XU;var JU=Wg();function XU(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?JU(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 im=oe((dF,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 om=oe((lF,A2)=>{"use strict";l();var ZU=new TextEncoder;A2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):ZU.encode(t)}});var R2=oe(B2=>{"use strict";l();var{AbstractIterator:QU}=nm(),T2=im(),wh=om(),ti=Symbol("cache"),Wi=Symbol("finished"),Pr=Symbol("options"),Gi=Symbol("currentOptions"),ec=Symbol("position"),sm=Symbol("location"),_a=Symbol("first"),_2={},cm=class extends QU{constructor(e,r,n){super(e,n),this[ti]=[],this[Wi]=this.limit===0,this[Pr]=n,this[Gi]={...n},this[ec]=void 0,this[sm]=r,this[_a]=!0}_nextv(e,r,n){if(this[_a]=!1,this[Wi])return this.nextTick(n,null,[]);if(this[ti].length>0)return e=Math.min(e,this[ti].length),this.nextTick(n,null,this[ti].splice(0,e));this[ec]!==void 0&&(this[Pr].reverse?(this[Gi].lt=this[ec],this[Gi].lte=void 0):(this[Gi].gt=this[ec],this[Gi].gte=void 0));let i;try{i=T2(this[Gi])}catch{return this[Wi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[sm]],"readonly"),s=o.objectStore(this[sm]),c=[];if(this[Pr].reverse){let a=!this[Pr].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[ec]=f,c.push([this[Pr].keys&&f!==void 0?wh(f):void 0,this[Pr].values&&h!==void 0?wh(h):void 0]),c.length<e?d.continue():I2(o)}else this[Wi]=!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[Wi]=!0:this[ec]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[Pr].keys&&p!==void 0?wh(p):void 0,this[Pr].values&&g!==void 0?wh(g):void 0]}I2(o)};this[Pr].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[Pr].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[ti].length>0){let[r,n]=this[ti].shift();this.nextTick(e,null,r,n)}else if(this[Wi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[_a]&&(this[_a]=!1,r=1),this._nextv(r,_2,(n,i)=>{if(n)return e(n);this[ti]=i,this._next(e)})}}_all(e,r){this[_a]=!1;let n=this[ti].splice(0,this[ti].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(r,null,n);this._nextv(i,_2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[_a]=!0,this[ti]=[],this[Wi]=!1,this[ec]=void 0,this[Gi]={...this[Pr]};let n;try{n=T2(this[Pr])}catch{this[Wi]=!0;return}n!==null&&!n.includes(e)?this[Wi]=!0:this[Pr].reverse?this[Gi].lte=e:this[Gi].gte=e}};B2.Iterator=cm;function I2(t){typeof t.commit=="function"&&t.commit()}});var O2=oe((gF,U2)=>{"use strict";l();U2.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 P2=oe(L2=>{"use strict";l();var{AbstractLevel:eO}=nm(),D2=Sn(),tO=v2(),{fromCallback:rO}=yd(),{Iterator:nO}=R2(),k2=om(),iO=O2(),oO=im(),C2="level-js-",Rd=Symbol("idb"),am=Symbol("namePrefix"),zi=Symbol("location"),um=Symbol("version"),tc=Symbol("store"),Ud=Symbol("onComplete"),N2=Symbol("promise"),bh=class extends eO{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new D2("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[zi]=e,this[am]=i??C2,this[um]=parseInt(o||1,10),this[Rd]=null}get location(){return this[zi]}get namePrefix(){return this[am]}get version(){return this[um]}get db(){return this[Rd]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[am]+this[zi],this[um]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[Rd]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[zi])||o.createObjectStore(this[zi])}}[tc](e){return this[Rd].transaction([this[zi]],e).objectStore(this[zi])}[Ud](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[tc]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[Ud](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new D2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,k2(c))})}_getMany(e,r,n){let i=this[tc]("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:k2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});tO(o,16,n)}_del(e,r,n){let i=this[tc]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[Ud](o,n)}_put(e,r,n,i){let o=this[tc]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[Ud](s,i)}_iterator(e){return new nO(this,this[zi],e)}_batch(e,r,n){let i=this[tc]("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=oO(e)}catch{return this.nextTick(r)}if(e.limit>=0)return iO(this,this[zi],n,e,r);try{let o=this[tc]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[Ud](i,r)}_close(e){this[Rd].close(),this.nextTick(e)}};bh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=C2),r=rO(r,N2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[N2]};L2.BrowserLevel=bh});var dm=oe(M2=>{l();M2.Level=P2().BrowserLevel});var ot=oe((IF,K2)=>{"use strict";l();K2.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 Ia=oe((RF,Eh)=>{"use strict";l();var{AbortController:$2,AbortSignal:cO}=typeof self<"u"?self:typeof window<"u"?window:void 0;Eh.exports=$2;Eh.exports.AbortSignal=cO;Eh.exports.default=$2});var Qt=oe((OF,lm)=>{"use strict";l();var aO=Ir(),{kResistStopPropagation:uO,SymbolDispose:dO}=ot(),fO=globalThis.AbortSignal||Ia().AbortSignal,lO=globalThis.AbortController||Ia().AbortController,hO=Object.getPrototypeOf(async function(){}).constructor,H2=globalThis.Blob||aO.Blob,pO=typeof H2<"u"?function(e){return e instanceof H2}:function(e){return!1},V2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},yO=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},fm=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}};lm.exports={AggregateError:fm,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 hO},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:pO,deprecate(t,e){return t},addAbortListener:ga().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);V2(e,"signal"),yO(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[uO]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[dO](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:fO.any||function(e){if(e.length===1)return e[0];let r=new lO,n=()=>r.abort();return e.forEach(i=>{V2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};lm.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var cr=oe((kF,j2)=>{"use strict";l();var{format:gO,inspect:vh,AggregateError:mO}=Qt(),wO=globalThis.AggregateError||mO,bO=Symbol("kIsNodeError"),xO=["string","function","number","object","Function","Object","boolean","bigint","symbol"],EO=/^([A-Z][a-z0-9]*)+$/,vO="__node_internal_",Sh={};function nc(t,e){if(!t)throw new Sh.ERR_INTERNAL_ASSERTION(e)}function q2(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 nc(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 nc(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:gO(e,...r)}function Ht(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[bO]=!0,Sh[t]=n}function F2(t){let e=vO+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 wO([e,t],e.message);return r.code=e.code,r}return t||e}var hm=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new Sh.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Ht("ERR_ASSERTION","%s",Error);Ht("ERR_INVALID_ARG_TYPE",(t,e,r)=>{nc(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)nc(typeof a=="string","All expected entries have to be of type string"),xO.includes(a)?i.push(a.toLowerCase()):EO.test(a)?o.push(a):(nc(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=vh(r,{depth:-1});n+=`. Received ${a}`}}else{let a=vh(r,{colors:!1});a.length>25&&(a=`${a.slice(0,25)}...`),n+=`. Received type ${typeof r} (${a})`}return n},TypeError);Ht("ERR_INVALID_ARG_VALUE",(t,e,r="is invalid")=>{let n=vh(e);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${t.includes(".")?"property":"argument"} '${t}' ${r}. Received ${n}`},TypeError);Ht("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);Ht("ERR_MISSING_ARGS",(...t)=>{nc(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);Ht("ERR_OUT_OF_RANGE",(t,e,r)=>{nc(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=q2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=q2(n)),n+="n"):n=vh(r),`The value of "${t}" is out of range. It must be ${e}. Received ${n}`},RangeError);Ht("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Ht("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Ht("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Ht("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Ht("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Ht("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Ht("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Ht("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Ht("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Ht("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Ht("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);j2.exports={AbortError:hm,aggregateTwoErrors:F2(AO),hideStackFrames:F2,codes:Sh}});var Ra=oe((CF,tS)=>{"use strict";l();var{ArrayIsArray:ym,ArrayPrototypeIncludes:Y2,ArrayPrototypeJoin:J2,ArrayPrototypeMap:TO,NumberIsInteger:gm,NumberIsNaN:_O,NumberMAX_SAFE_INTEGER:IO,NumberMIN_SAFE_INTEGER:BO,NumberParseInt:RO,ObjectPrototypeHasOwnProperty:UO,RegExpPrototypeExec:X2,String:OO,StringPrototypeToUpperCase:DO,StringPrototypeTrim:kO}=ot(),{hideStackFrames:on,codes:{ERR_SOCKET_BAD_PORT:NO,ERR_INVALID_ARG_TYPE:er,ERR_INVALID_ARG_VALUE:Ba,ERR_OUT_OF_RANGE:ic,ERR_UNKNOWN_SIGNAL:W2}}=cr(),{normalizeEncoding:CO}=Qt(),{isAsyncFunction:LO,isArrayBufferView:PO}=Qt().types,G2={};function MO(t){return t===(t|0)}function KO(t){return t===t>>>0}var $O=/^[0-7]+$/,HO="must be a 32-bit unsigned integer or an octal string";function VO(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(X2($O,t)===null)throw new Ba(e,t,HO);t=RO(t,8)}return Z2(t,e),t}var qO=on((t,e,r=BO,n=IO)=>{if(typeof t!="number")throw new er(e,"number",t);if(!gm(t))throw new ic(e,"an integer",t);if(t<r||t>n)throw new ic(e,`>= ${r} && <= ${n}`,t)}),FO=on((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new er(e,"number",t);if(!gm(t))throw new ic(e,"an integer",t);if(t<r||t>n)throw new ic(e,`>= ${r} && <= ${n}`,t)}),Z2=on((t,e,r=!1)=>{if(typeof t!="number")throw new er(e,"number",t);if(!gm(t))throw new ic(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new ic(e,`>= ${n} && <= ${i}`,t)});function mm(t,e){if(typeof t!="string")throw new er(e,"string",t)}function jO(t,e,r=void 0,n){if(typeof t!="number")throw new er(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&_O(t))throw new ic(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var WO=on((t,e,r)=>{if(!Y2(r,t)){let i="must be one of: "+J2(TO(r,o=>typeof o=="string"?`'${o}'`:OO(o)),", ");throw new Ba(e,t,i)}});function Q2(t,e){if(typeof t!="boolean")throw new er(e,"boolean",t)}function pm(t,e,r){return t==null||!UO(t,e)?r:t[e]}var GO=on((t,e,r=null)=>{let n=pm(r,"allowArray",!1),i=pm(r,"allowFunction",!1);if(!pm(r,"nullable",!1)&&t===null||!n&&ym(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new er(e,"Object",t)}),zO=on((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new er(e,"a dictionary",t)}),Ah=on((t,e,r=0)=>{if(!ym(t))throw new er(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new Ba(e,t,n)}});function YO(t,e){Ah(t,e);for(let r=0;r<t.length;r++)mm(t[r],`${e}[${r}]`)}function JO(t,e){Ah(t,e);for(let r=0;r<t.length;r++)Q2(t[r],`${e}[${r}]`)}function XO(t,e){Ah(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new er(i,"AbortSignal",n);eS(n,i)}}function ZO(t,e="signal"){if(mm(t,e),G2[t]===void 0)throw G2[DO(t)]!==void 0?new W2(t+" (signals must use all capital letters)"):new W2(t)}var QO=on((t,e="buffer")=>{if(!PO(t))throw new er(e,["Buffer","TypedArray","DataView"],t)});function e5(t,e){let r=CO(e),n=t.length;if(r==="hex"&&n%2!==0)throw new Ba("encoding",e,`is invalid for data of length ${n}`)}function t5(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&kO(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new NO(e,t,r);return t|0}var eS=on((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new er(e,"AbortSignal",t)}),r5=on((t,e)=>{if(typeof t!="function")throw new er(e,"Function",t)}),n5=on((t,e)=>{if(typeof t!="function"||LO(t))throw new er(e,"Function",t)}),i5=on((t,e)=>{if(t!==void 0)throw new er(e,"undefined",t)});function o5(t,e,r){if(!Y2(r,t))throw new er(e,`('${J2(r,"|")}')`,t)}var s5=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function z2(t,e){if(typeof t>"u"||!X2(s5,t))throw new Ba(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function c5(t){if(typeof t=="string")return z2(t,"hints"),t;if(ym(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];z2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new Ba("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}tS.exports={isInt32:MO,isUint32:KO,parseFileMode:VO,validateArray:Ah,validateStringArray:YO,validateBooleanArray:JO,validateAbortSignalArray:XO,validateBoolean:Q2,validateBuffer:QO,validateDictionary:zO,validateEncoding:e5,validateFunction:r5,validateInt32:FO,validateInteger:qO,validateNumber:jO,validateObject:GO,validateOneOf:WO,validatePlainFunction:n5,validatePort:t5,validateSignalName:ZO,validateString:mm,validateUint32:Z2,validateUndefined:i5,validateUnion:o5,validateAbortSignal:eS,validateLinkHeaderValue:c5}});var ni=oe((PF,gS)=>{"use strict";l();var{SymbolAsyncIterator:rS,SymbolIterator:nS,SymbolFor:oc}=ot(),iS=oc("nodejs.stream.destroyed"),oS=oc("nodejs.stream.errored"),wm=oc("nodejs.stream.readable"),bm=oc("nodejs.stream.writable"),sS=oc("nodejs.stream.disturbed"),a5=oc("nodejs.webstream.isClosedPromise"),u5=oc("nodejs.webstream.controllerErrorFunction");function Th(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 _h(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 d5(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function ri(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function cS(t){return!!(t&&!ri(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function aS(t){return!!(t&&!ri(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function uS(t){return!!(t&&!ri(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function f5(t){return cS(t)||aS(t)||uS(t)}function l5(t,e){return t==null?!1:e===!0?typeof t[rS]=="function":e===!1?typeof t[nS]=="function":typeof t[rS]=="function"||typeof t[nS]=="function"}function Ih(t){if(!ri(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[iS]||n!=null&&n.destroyed)}function dS(t){if(!_h(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 h5(t,e){if(!_h(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 p5(t){if(!Th(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 fS(t,e){if(!Th(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 lS(t){return t&&t[wm]!=null?t[wm]:typeof t?.readable!="boolean"?null:Ih(t)?!1:Th(t)&&t.readable&&!fS(t)}function hS(t){return t&&t[bm]!=null?t[bm]:typeof t?.writable!="boolean"?null:Ih(t)?!1:_h(t)&&t.writable&&!dS(t)}function y5(t,e){return ri(t)?Ih(t)?!0:!(e?.readable!==!1&&lS(t)||e?.writable!==!1&&hS(t)):null}function g5(t){var e,r;return ri(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 m5(t){var e,r;return ri(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 w5(t){if(!ri(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"&&pS(t)?t._closed:null}function pS(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function yS(t){return typeof t._sent100=="boolean"&&pS(t)}function b5(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 x5(t){if(!ri(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&yS(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function E5(t){var e;return!!(t&&((e=t[sS])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function v5(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[oS])!==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))}gS.exports={isDestroyed:Ih,kIsDestroyed:iS,isDisturbed:E5,kIsDisturbed:sS,isErrored:v5,kIsErrored:oS,isReadable:lS,kIsReadable:wm,kIsClosedPromise:a5,kControllerErrorFunction:u5,kIsWritable:bm,isClosed:w5,isDuplexNodeStream:d5,isFinished:y5,isIterable:l5,isReadableNodeStream:Th,isReadableStream:cS,isReadableEnded:p5,isReadableFinished:fS,isReadableErrored:m5,isNodeStream:ri,isWebStream:f5,isWritable:hS,isWritableNodeStream:_h,isWritableStream:aS,isWritableEnded:dS,isWritableFinished:h5,isWritableErrored:g5,isServerRequest:b5,isServerResponse:yS,willEmitClose:x5,isTransformStream:uS}});var Yi=oe((KF,Am)=>{l();var Wo=vi(),{AbortError:TS,codes:S5}=cr(),{ERR_INVALID_ARG_TYPE:A5,ERR_STREAM_PREMATURE_CLOSE:mS}=S5,{kEmptyObject:Em,once:vm}=Qt(),{validateAbortSignal:T5,validateFunction:_5,validateObject:I5,validateBoolean:B5}=Ra(),{Promise:R5,PromisePrototypeThen:U5,SymbolDispose:_S}=ot(),{isClosed:O5,isReadable:wS,isReadableNodeStream:xm,isReadableStream:D5,isReadableFinished:bS,isReadableErrored:xS,isWritable:ES,isWritableNodeStream:vS,isWritableStream:k5,isWritableFinished:SS,isWritableErrored:AS,isNodeStream:N5,willEmitClose:C5,kIsClosedPromise:L5}=ni(),Ua;function P5(t){return t.setHeader&&typeof t.abort=="function"}var Sm=()=>{};function IS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=Em):e==null?e=Em:I5(e,"options"),_5(r,"callback"),T5(e.signal,"options.signal"),r=vm(r),D5(t)||k5(t))return M5(t,e,r);if(!N5(t))throw new A5("stream",["ReadableStream","WritableStream","Stream"],t);let o=(n=e.readable)!==null&&n!==void 0?n:xm(t),s=(i=e.writable)!==null&&i!==void 0?i:vS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=C5(t)&&xm(t)===o&&vS(t)===s,f=SS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=bS(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=O5(t),S=()=>{x=!0;let T=AS(t)||xS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&xm(t,!0)&&!bS(t,!1))return r.call(t,new mS);if(s&&!f&&!SS(t,!1))return r.call(t,new mS);r.call(t)},I=()=>{x=!0;let T=AS(t)||xS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};P5(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?Wo.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||Wo.nextTick(I):(!o&&(!d||wS(t))&&(f||ES(t)===!1)||!s&&(!d||ES(t))&&(p||wS(t)===!1)||a&&t.req&&t.aborted)&&Wo.nextTick(I);let O=()=>{r=Sm,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 TS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)Wo.nextTick(T);else{Ua=Ua||Qt().addAbortListener;let M=Ua(e.signal,T),q=r;r=vm((...j)=>{M[_S](),q.apply(t,j)})}}return O}function M5(t,e,r){let n=!1,i=Sm;if(e.signal)if(i=()=>{n=!0,r.call(t,new TS(void 0,{cause:e.signal.reason}))},e.signal.aborted)Wo.nextTick(i);else{Ua=Ua||Qt().addAbortListener;let s=Ua(e.signal,i),c=r;r=vm((...a)=>{s[_S](),c.apply(t,a)})}let o=(...s)=>{n||Wo.nextTick(()=>r.apply(t,s))};return U5(t[L5].promise,o,o),Sm}function K5(t,e){var r;let n=!1;return e===null&&(e=Em),(r=e)!==null&&r!==void 0&&r.cleanup&&(B5(e.cleanup,"cleanup"),n=e.cleanup),new R5((i,o)=>{let s=IS(t,e,c=>{n&&s(),c?o(c):i()})})}Am.exports=IS;Am.exports.finished=K5});var sc=oe((HF,CS)=>{"use strict";l();var ii=vi(),{aggregateTwoErrors:$5,codes:{ERR_MULTIPLE_CALLBACK:H5},AbortError:V5}=cr(),{Symbol:US}=ot(),{kIsDestroyed:q5,isDestroyed:F5,isFinished:j5,isServerRequest:W5}=ni(),OS=US("kDestroy"),Tm=US("kConstruct");function DS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function G5(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):(DS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?BS(this,t,e):this.once(OS,function(o){BS(this,$5(o,t),e)}),this)}function BS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;DS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ii.nextTick(z5,t,o):ii.nextTick(kS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function z5(t,e){_m(t,e),kS(t)}function kS(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 _m(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 Y5(){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 Im(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?ii.nextTick(_m,t,e):_m(t,e))}function J5(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(Tm,e),!(t.listenerCount(Tm)>1)&&ii.nextTick(X5,t)}function X5(t){let e=!1;function r(n){if(e){Im(t,n??new H5);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(OS,n):n?Im(t,n,!0):ii.nextTick(Z5,t)}try{t._construct(n=>{ii.nextTick(r,n)})}catch(n){ii.nextTick(r,n)}}function Z5(t){t.emit(Tm)}function RS(t){return t?.setHeader&&typeof t.abort=="function"}function NS(t){t.emit("close")}function Q5(t,e){t.emit("error",e),ii.nextTick(NS,t)}function e3(t,e){!t||F5(t)||(!e&&!j5(t)&&(e=new V5),W5(t)?(t.socket=null,t.destroy(e)):RS(t)?t.abort():RS(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ii.nextTick(Q5,t,e):ii.nextTick(NS,t),t.destroyed||(t[q5]=!0))}CS.exports={construct:J5,destroyer:e3,destroy:G5,undestroy:Y5,errorOrDestroy:Im}});var Uh=oe((qF,PS)=>{"use strict";l();var{ArrayIsArray:t3,ObjectSetPrototypeOf:LS}=ot(),{EventEmitter:Bh}=ga();function Rh(t){Bh.call(this,t)}LS(Rh.prototype,Bh.prototype);LS(Rh,Bh);Rh.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)}Bm(r,"error",a),Bm(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 Bm(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):t3(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}PS.exports={Stream:Rh,prependListener:Bm}});var Od=oe((jF,Oh)=>{"use strict";l();var{SymbolDispose:r3}=ot(),{AbortError:MS,codes:n3}=cr(),{isNodeStream:KS,isWebStream:i3,kControllerErrorFunction:o3}=ni(),s3=Yi(),{ERR_INVALID_ARG_TYPE:$S}=n3,Rm,c3=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new $S(e,"AbortSignal",t)};Oh.exports.addAbortSignal=function(e,r){if(c3(e,"signal"),!KS(r)&&!i3(r))throw new $S("stream",["ReadableStream","WritableStream","Stream"],r);return Oh.exports.addAbortSignalNoValidate(e,r)};Oh.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=KS(e)?()=>{e.destroy(new MS(void 0,{cause:t.reason}))}:()=>{e[o3](new MS(void 0,{cause:t.reason}))};if(t.aborted)r();else{Rm=Rm||Qt().addAbortListener;let n=Rm(t,r);s3(e,n[r3])}return e}});var qS=oe((zF,VS)=>{"use strict";l();var{StringPrototypeSlice:HS,SymbolIterator:a3,TypedArrayPrototypeSet:Dh,Uint8Array:u3}=ot(),{Buffer:Um}=Ir(),{inspect:d3}=Qt();VS.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 Um.alloc(0);let r=Um.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)Dh(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}*[a3](){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+=HS(o,0,e),this.head=n,n.data=HS(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=Um.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)Dh(r,s,n-e),e-=s.length;else{e===s.length?(Dh(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Dh(r,new u3(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 d3(this,{...r,depth:0,customInspect:!1})}}});var Dd=oe((JF,GS)=>{"use strict";l();var{MathFloor:f3,NumberIsInteger:l3}=ot(),{validateInteger:h3}=Ra(),{ERR_INVALID_ARG_VALUE:p3}=cr().codes,FS=16*1024,jS=16;function y3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function WS(t){return t?jS:FS}function g3(t,e){h3(e,"value",0),t?jS=e:FS=e}function m3(t,e,r,n){let i=y3(e,n,r);if(i!=null){if(!l3(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new p3(o,i)}return f3(i)}return WS(t.objectMode)}GS.exports={getHighWaterMark:m3,getDefaultHighWaterMark:WS,setDefaultHighWaterMark:g3}});var JS=oe((Om,YS)=>{l();var kh=Ir(),oi=kh.Buffer;function zS(t,e){for(var r in t)e[r]=t[r]}oi.from&&oi.alloc&&oi.allocUnsafe&&oi.allocUnsafeSlow?YS.exports=kh:(zS(kh,Om),Om.Buffer=cc);function cc(t,e,r){return oi(t,e,r)}cc.prototype=Object.create(oi.prototype);zS(oi,cc);cc.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return oi(t,e,r)};cc.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=oi(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};cc.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return oi(t)};cc.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return kh.SlowBuffer(t)}});var QS=oe(ZS=>{"use strict";l();var km=JS().Buffer,XS=km.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 w3(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 b3(t){var e=w3(t);if(typeof e!="string"&&(km.isEncoding===XS||!XS(t)))throw new Error("Unknown encoding: "+t);return e||t}ZS.StringDecoder=kd;function kd(t){this.encoding=b3(t);var e;switch(this.encoding){case"utf16le":this.text=T3,this.end=_3,e=4;break;case"utf8":this.fillLast=v3,e=4;break;case"base64":this.text=I3,this.end=B3,e=3;break;default:this.write=R3,this.end=U3;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=km.allocUnsafe(e)}kd.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||""};kd.prototype.end=A3;kd.prototype.text=S3;kd.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 Dm(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function x3(t,e,r){var n=e.length-1;if(n<r)return 0;var i=Dm(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=Dm(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=Dm(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function E3(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 v3(t){var e=this.lastTotal-this.lastNeed,r=E3(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=x3(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 T3(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 _3(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 I3(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 B3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function R3(t){return t.toString(this.encoding)}function U3(t){return t&&t.length?this.write(t):""}});var Nm=oe((tj,nA)=>{"use strict";l();var eA=vi(),{PromisePrototypeThen:O3,SymbolAsyncIterator:tA,SymbolIterator:rA}=ot(),{Buffer:D3}=Ir(),{ERR_INVALID_ARG_TYPE:k3,ERR_STREAM_NULL_VALUES:N3}=cr().codes;function C3(t,e,r){let n;if(typeof e=="string"||e instanceof D3)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[tA])i=!0,n=e[tA]();else if(e&&e[rA])i=!1,n=e[rA]();else throw new k3("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){O3(c(u),()=>eA.nextTick(d,u),f=>eA.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 N3;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}nA.exports=C3});var Cd=oe((nj,EA)=>{l();var _n=vi(),{ArrayPrototypeIndexOf:L3,NumberIsInteger:P3,NumberIsNaN:M3,NumberParseInt:K3,ObjectDefineProperties:Vm,ObjectKeys:$3,ObjectSetPrototypeOf:sA,Promise:cA,SafeSet:H3,SymbolAsyncDispose:V3,SymbolAsyncIterator:q3,Symbol:F3}=ot();EA.exports=me;me.ReadableState=Ph;var{EventEmitter:j3}=ga(),{Stream:Go,prependListener:W3}=Uh(),{Buffer:Cm}=Ir(),{addAbortSignal:G3}=Od(),aA=Yi(),Se=Qt().debuglog("stream",t=>{Se=t}),z3=qS(),ka=sc(),{getHighWaterMark:Y3,getDefaultHighWaterMark:J3}=Dd(),{aggregateTwoErrors:iA,codes:{ERR_INVALID_ARG_TYPE:X3,ERR_METHOD_NOT_IMPLEMENTED:Z3,ERR_OUT_OF_RANGE:Q3,ERR_STREAM_PUSH_AFTER_EOF:eD,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:tD},AbortError:rD}=cr(),{validateObject:nD}=Ra(),ac=F3("kPaused"),{StringDecoder:uA}=QS(),iD=Nm();sA(me.prototype,Go.prototype);sA(me,Go);var Lm=()=>{},{errorOrDestroy:Oa}=ka,Da=1,oD=2,dA=4,Nd=8,fA=16,Nh=32,Ch=64,lA=128,sD=256,cD=512,aD=1024,$m=2048,Hm=4096,uD=8192,dD=16384,fD=32768,hA=65536,lD=1<<17,hD=1<<18;function Tt(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Vm(Ph.prototype,{objectMode:Tt(Da),ended:Tt(oD),endEmitted:Tt(dA),reading:Tt(Nd),constructed:Tt(fA),sync:Tt(Nh),needReadable:Tt(Ch),emittedReadable:Tt(lA),readableListening:Tt(sD),resumeScheduled:Tt(cD),errorEmitted:Tt(aD),emitClose:Tt($m),autoDestroy:Tt(Hm),destroyed:Tt(uD),closed:Tt(dD),closeEmitted:Tt(fD),multiAwaitDrain:Tt(hA),readingMore:Tt(lD),dataEmitted:Tt(hD)});function Ph(t,e,r){typeof r!="boolean"&&(r=e instanceof si()),this.state=$m|Hm|fA|Nh,t&&t.objectMode&&(this.state|=Da),r&&t&&t.readableObjectMode&&(this.state|=Da),this.highWaterMark=t?Y3(this,t,"readableHighWaterMark",r):J3(!1),this.buffer=new z3,this.length=0,this.pipes=[],this.flowing=null,this[ac]=null,t&&t.emitClose===!1&&(this.state&=~$m),t&&t.autoDestroy===!1&&(this.state&=~Hm),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new uA(t.encoding),this.encoding=t.encoding)}function me(t){if(!(this instanceof me))return new me(t);let e=this instanceof si();this._readableState=new Ph(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&&G3(t.signal,this)),Go.call(this,t),ka.construct(this,()=>{this._readableState.needReadable&&Lh(this,this._readableState)})}me.prototype.destroy=ka.destroy;me.prototype._undestroy=ka.undestroy;me.prototype._destroy=function(t,e){e(t)};me.prototype[j3.captureRejectionSymbol]=function(t){this.destroy(t)};me.prototype[V3]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new rD,this.destroy(t)),new cA((e,r)=>aA(this,n=>n&&n!==t?r(n):e(null)))};me.prototype.push=function(t,e){return pA(this,t,e,!1)};me.prototype.unshift=function(t,e){return pA(this,t,e,!0)};function pA(t,e,r,n){Se("readableAddChunk",e);let i=t._readableState,o;if(i.state&Da||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=Cm.from(e,r).toString(i.encoding):(e=Cm.from(e,r),r=""))):e instanceof Cm?r="":Go._isUint8Array(e)?(e=Go._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new X3("chunk",["string","Buffer","Uint8Array"],e))),o)Oa(t,o);else if(e===null)i.state&=~Nd,gD(t,i);else if(i.state&Da||e&&e.length>0)if(n)if(i.state&dA)Oa(t,new tD);else{if(i.destroyed||i.errored)return!1;Pm(t,i,e,!0)}else if(i.ended)Oa(t,new eD);else{if(i.destroyed||i.errored)return!1;i.state&=~Nd,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?Pm(t,i,e,!1):Lh(t,i)):Pm(t,i,e,!1)}else n||(i.state&=~Nd,Lh(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function Pm(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&hA?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&Ch&&Mh(t)),Lh(t,e)}me.prototype.isPaused=function(){let t=this._readableState;return t[ac]===!0||t.flowing===!1};me.prototype.setEncoding=function(t){let e=new uA(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 pD=1073741824;function yD(t){if(t>pD)throw new Q3("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function oA(t,e){return t<=0||e.length===0&&e.ended?0:e.state&Da?1:M3(t)?e.flowing&&e.length?e.buffer.first().length:e.length:t<=e.length?t:e.ended?e.length:0}me.prototype.read=function(t){Se("read",t),t===void 0?t=NaN:P3(t)||(t=K3(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=yD(t)),t!==0&&(e.state&=~lA),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Se("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Mm(this):Mh(this),null;if(t=oA(t,e),t===0&&e.ended)return e.length===0&&Mm(this),null;let n=(e.state&Ch)!==0;if(Se("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,Se("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,Se("reading, ended or constructing",n);else if(n){Se("do read"),e.state|=Nd|Nh,e.length===0&&(e.state|=Ch);try{this._read(e.highWaterMark)}catch(o){Oa(this,o)}e.state&=~Nh,e.reading||(t=oA(r,e))}let i;return t>0?i=bA(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&&Mm(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function gD(t,e){if(Se("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?Mh(t):(e.needReadable=!1,e.emittedReadable=!0,yA(t))}}function Mh(t){let e=t._readableState;Se("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Se("emitReadable",e.flowing),e.emittedReadable=!0,_n.nextTick(yA,t))}function yA(t){let e=t._readableState;Se("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,mA(t)}function Lh(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,_n.nextTick(mD,t,e))}function mD(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(Se("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}me.prototype._read=function(t){throw new Z3("_read()")};me.prototype.pipe=function(t,e){let r=this,n=this._readableState;n.pipes.length===1&&(n.multiAwaitDrain||(n.multiAwaitDrain=!0,n.awaitDrainWriters=new H3(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),Se("pipe count=%d opts=%j",n.pipes.length,e);let o=(!e||e.end!==!1)&&t!==_n.stdout&&t!==_n.stderr?c:x;n.endEmitted?_n.nextTick(o):r.once("end",o),t.on("unpipe",s);function s(S,I){Se("onunpipe"),S===r&&I&&I.hasUnpiped===!1&&(I.hasUnpiped=!0,d())}function c(){Se("onend"),t.end()}let a,u=!1;function d(){Se("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?(Se("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(Se("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=wD(r,t),t.on("drain",a))}r.on("data",h);function h(S){Se("ondata");let I=t.write(S);Se("dest.write",I),I===!1&&f()}function p(S){if(Se("onerror",S),x(),t.removeListener("error",p),t.listenerCount("error")===0){let I=t._writableState||t._readableState;I&&!I.errorEmitted?Oa(t,S):t.emit("error",S)}}W3(t,"error",p);function g(){t.removeListener("finish",y),x()}t.once("close",g);function y(){Se("onfinish"),t.removeListener("close",g),x()}t.once("finish",y);function x(){Se("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(Se("pipe resume"),r.resume()),t};function wD(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(Se("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(Se("pipeOnDrain",n.awaitDrainWriters.size),n.awaitDrainWriters.delete(e)),(!n.awaitDrainWriters||n.awaitDrainWriters.size===0)&&t.listenerCount("data")&&t.resume()}}me.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=L3(e.pipes,t);return n===-1?this:(e.pipes.splice(n,1),e.pipes.length===0&&this.pause(),t.emit("unpipe",this,r),this)};me.prototype.on=function(t,e){let r=Go.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,Se("on readable",n.length,n.reading),n.length?Mh(this):n.reading||_n.nextTick(bD,this)),r};me.prototype.addListener=me.prototype.on;me.prototype.removeListener=function(t,e){let r=Go.prototype.removeListener.call(this,t,e);return t==="readable"&&_n.nextTick(gA,this),r};me.prototype.off=me.prototype.removeListener;me.prototype.removeAllListeners=function(t){let e=Go.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&_n.nextTick(gA,this),e};function gA(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[ac]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function bD(t){Se("readable nexttick read 0"),t.read(0)}me.prototype.resume=function(){let t=this._readableState;return t.flowing||(Se("resume"),t.flowing=!t.readableListening,xD(this,t)),t[ac]=!1,this};function xD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,_n.nextTick(ED,t,e))}function ED(t,e){Se("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),mA(t),e.flowing&&!e.reading&&t.read(0)}me.prototype.pause=function(){return Se("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Se("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[ac]=!0,this};function mA(t){let e=t._readableState;for(Se("flow",e.flowing);e.flowing&&t.read()!==null;);}me.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=>{Oa(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=$3(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};me.prototype[q3]=function(){return wA(this)};me.prototype.iterator=function(t){return t!==void 0&&nD(t,"options"),wA(this,t)};function wA(t,e){typeof t.read!="function"&&(t=me.wrap(t,{objectMode:!0}));let r=vD(t,e);return r.stream=t,r}async function*vD(t,e){let r=Lm;function n(s){this===t?(r(),r=Lm):r=s}t.on("readable",n);let i,o=aA(t,{writable:!1},s=>{i=s?iA(i,s):null,r(),r=Lm});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 cA(n)}}}catch(s){throw i=iA(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?ka.destroyer(t,null):(t.off("readable",n),o())}}Vm(me.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}}});Vm(Ph.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[ac]!==!1},set(t){this[ac]=!!t}}});me._fromList=bA;function bA(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 Mm(t){let e=t._readableState;Se("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,_n.nextTick(SD,e,t))}function SD(t,e){if(Se("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)_n.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()}me.from=function(t,e){return iD(me,t,e)};var Km;function xA(){return Km===void 0&&(Km={}),Km}me.fromWeb=function(t,e){return xA().newStreamReadableFromReadableStream(t,e)};me.toWeb=function(t,e){return xA().newReadableStreamFromStreamReadable(t,e)};me.wrap=function(t,e){var r,n;return new me({objectMode:(r=(n=t.readableObjectMode)!==null&&n!==void 0?n:t.objectMode)!==null&&r!==void 0?r:!0,...e,destroy(i,o){ka.destroyer(t,i),o(i)}}).wrap(t)}});var qh=oe((oj,kA)=>{l();var uc=vi(),{ArrayPrototypeSlice:AA,Error:TD,FunctionPrototypeSymbolHasInstance:TA,ObjectDefineProperty:_A,ObjectDefineProperties:_D,ObjectSetPrototypeOf:IA,StringPrototypeToLowerCase:ID,Symbol:BD,SymbolHasInstance:RD}=ot();kA.exports=st;st.WritableState=Md;var{EventEmitter:UD}=ga(),Ld=Uh().Stream,{Buffer:Kh}=Ir(),Vh=sc(),{addAbortSignal:OD}=Od(),{getHighWaterMark:DD,getDefaultHighWaterMark:kD}=Dd(),{ERR_INVALID_ARG_TYPE:ND,ERR_METHOD_NOT_IMPLEMENTED:CD,ERR_MULTIPLE_CALLBACK:BA,ERR_STREAM_CANNOT_PIPE:LD,ERR_STREAM_DESTROYED:Pd,ERR_STREAM_ALREADY_FINISHED:PD,ERR_STREAM_NULL_VALUES:MD,ERR_STREAM_WRITE_AFTER_END:KD,ERR_UNKNOWN_ENCODING:RA}=cr().codes,{errorOrDestroy:Na}=Vh;IA(st.prototype,Ld.prototype);IA(st,Ld);function jm(){}var Ca=BD("kOnFinished");function Md(t,e,r){typeof r!="boolean"&&(r=e instanceof si()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?DD(this,t,"writableHighWaterMark",r):kD(!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=HD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,Hh(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[Ca]=[]}function Hh(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Md.prototype.getBuffer=function(){return AA(this.buffered,this.bufferedIndex)};_A(Md.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function st(t){let e=this instanceof si();if(!e&&!TA(st,this))return new st(t);this._writableState=new Md(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&&OD(t.signal,this)),Ld.call(this,t),Vh.construct(this,()=>{let r=this._writableState;r.writing||Gm(this,r),zm(this,r)})}_A(st,RD,{__proto__:null,value:function(t){return TA(this,t)?!0:this!==st?!1:t&&t._writableState instanceof Md}});st.prototype.pipe=function(){Na(this,new LD)};function UA(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"&&!Kh.isEncoding(r))throw new RA(r);typeof n!="function"&&(n=jm)}if(e===null)throw new MD;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Kh.from(e,r),r="buffer");else if(e instanceof Kh)r="buffer";else if(Ld._isUint8Array(e))e=Ld._uint8ArrayToBuffer(e),r="buffer";else throw new ND("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new KD:i.destroyed&&(o=new Pd("write")),o?(uc.nextTick(n,o),Na(t,o,!0),o):(i.pendingcb++,$D(t,i,e,r,n))}st.prototype.write=function(t,e,r){return UA(this,t,e,r)===!0};st.prototype.cork=function(){this._writableState.corked++};st.prototype.uncork=function(){let t=this._writableState;t.corked&&(t.corked--,t.writing||Gm(this,t))};st.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=ID(e)),!Kh.isEncoding(e))throw new RA(e);return this._writableState.defaultEncoding=e,this};function $D(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!==jm&&(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 vA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new Pd("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),Wm(e),Na(t,r)}function HD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){Na(t,new BA);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?uc.nextTick(SA,t,r,e,i):SA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&Gm(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},uc.nextTick(VD,r.afterWriteTickInfo)):OA(t,r,1,i))}function VD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,OA(t,e,r,n)}function OA(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&&Wm(e),zm(t,e)}function Wm(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 Pd("write"))}let r=t[Ca].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new Pd("end"))}Hh(t)}function Gm(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?jm:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:AA(r,s);a.allBuffers=e.allBuffers,vA(t,e,!0,e.length,a,"",c),Hh(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;vA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?Hh(e):s>256?(r.splice(0,s),e.bufferedIndex=0):e.bufferedIndex=s}e.bufferProcessing=!1}st.prototype._write=function(t,e,r){if(this._writev)this._writev([{chunk:t,encoding:e}],r);else throw new CD("_write()")};st.prototype._writev=null;st.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=UA(this,t,e);o instanceof TD&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,zm(this,n,!0),n.ended=!0):n.finished?i=new PD("end"):n.destroyed&&(i=new Pd("end"))),typeof r=="function"&&(i||n.finished?uc.nextTick(r,i):n[Ca].push(r)),this};function $h(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 qD(t,e){let r=!1;function n(i){if(r){Na(t,i??BA());return}if(r=!0,e.pendingcb--,i){let o=e[Ca].splice(0);for(let s=0;s<o.length;s++)o[s](i);Na(t,i,e.sync)}else $h(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,uc.nextTick(Fm,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function FD(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,qD(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function zm(t,e,r){$h(e)&&(FD(t,e),e.pendingcb===0&&(r?(e.pendingcb++,uc.nextTick((n,i)=>{$h(i)?Fm(n,i):i.pendingcb--},t,e)):$h(e)&&(e.pendingcb++,Fm(t,e))))}function Fm(t,e){e.pendingcb--,e.finished=!0;let r=e[Ca].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()}}_D(st.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 jD=Vh.destroy;st.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[Ca].length)&&uc.nextTick(Wm,r),jD.call(this,t,e),this};st.prototype._undestroy=Vh.undestroy;st.prototype._destroy=function(t,e){e(t)};st.prototype[UD.captureRejectionSymbol]=function(t){this.destroy(t)};var qm;function DA(){return qm===void 0&&(qm={}),qm}st.fromWeb=function(t,e){return DA().newStreamWritableFromWritableStream(t,e)};st.toWeb=function(t){return DA().newWritableStreamFromStreamWritable(t)}});var zA=oe((cj,GA)=>{l();var Ym=vi(),WD=Ir(),{isReadable:GD,isWritable:zD,isIterable:NA,isNodeStream:YD,isReadableNodeStream:CA,isWritableNodeStream:LA,isDuplexNodeStream:JD,isReadableStream:PA,isWritableStream:MA}=ni(),KA=Yi(),{AbortError:jA,codes:{ERR_INVALID_ARG_TYPE:XD,ERR_INVALID_RETURN_VALUE:$A}}=cr(),{destroyer:Pa}=sc(),ZD=si(),WA=Cd(),QD=qh(),{createDeferredPromise:HA}=Qt(),VA=Nm(),qA=globalThis.Blob||WD.Blob,ek=typeof qA<"u"?function(e){return e instanceof qA}:function(e){return!1},tk=globalThis.AbortController||Ia().AbortController,{FunctionPrototypeCall:FA}=ot(),zo=class extends ZD{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)}};GA.exports=function t(e,r){if(JD(e))return e;if(CA(e))return La({readable:e});if(LA(e))return La({writable:e});if(YD(e))return La({writable:!1,readable:!1});if(PA(e))return La({readable:WA.fromWeb(e)});if(MA(e))return La({writable:QD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=rk(e);if(NA(i))return VA(zo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=FA(a,i,f=>{if(f!=null)throw new $A("nully","body",f)},f=>{Pa(u,f)});return u=new zo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,Ym.nextTick(f,null)}catch(h){Ym.nextTick(f,h)}})},destroy:c})}throw new $A("Iterable, AsyncIterable or AsyncFunction",r,i)}if(ek(e))return t(e.arrayBuffer());if(NA(e))return VA(zo,e,{objectMode:!0,writable:!1});if(PA(e?.readable)&&MA(e?.writable))return zo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?CA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?LA(e?.writable)?e?.writable:t(e.writable):void 0;return La({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return FA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{Pa(i,o)}),i=new zo({objectMode:!0,writable:!1,read(){}})}throw new XD(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function rk(t){let{promise:e,resolve:r}=HA(),n=new tk,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(Ym.nextTick(u),a)return;if(i.aborted)throw new jA(void 0,{cause:i.reason});({promise:e,resolve:r}=HA()),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 La(t){let e=t.readable&&typeof t.readable.read!="function"?WA.wrap(t.readable):t.readable,r=t.writable,n=!!GD(e),i=!!zD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new zo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(KA(r,f=>{i=!1,f&&Pa(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&&(KA(e,f=>{n=!1,f&&Pa(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 jA),c=null,o=null,s=null,a===null?h(f):(a=h,Pa(r,f),Pa(e,f))},u}});var si=oe((uj,XA)=>{"use strict";l();var{ObjectDefineProperties:nk,ObjectGetOwnPropertyDescriptor:Ji,ObjectKeys:ik,ObjectSetPrototypeOf:YA}=ot();XA.exports=In;var Zm=Cd(),sn=qh();YA(In.prototype,Zm.prototype);YA(In,Zm);{let t=ik(sn.prototype);for(let e=0;e<t.length;e++){let r=t[e];In.prototype[r]||(In.prototype[r]=sn.prototype[r])}}function In(t){if(!(this instanceof In))return new In(t);Zm.call(this,t),sn.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}nk(In.prototype,{writable:{__proto__:null,...Ji(sn.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Ji(sn.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Ji(sn.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Ji(sn.prototype,"writableBuffer")},writableLength:{__proto__:null,...Ji(sn.prototype,"writableLength")},writableFinished:{__proto__:null,...Ji(sn.prototype,"writableFinished")},writableCorked:{__proto__:null,...Ji(sn.prototype,"writableCorked")},writableEnded:{__proto__:null,...Ji(sn.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Ji(sn.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 Jm;function JA(){return Jm===void 0&&(Jm={}),Jm}In.fromWeb=function(t,e){return JA().newStreamDuplexFromReadableWritablePair(t,e)};In.toWeb=function(t){return JA().newReadableWritablePairFromDuplex(t)};var Xm;In.from=function(t){return Xm||(Xm=zA()),Xm(t,"body")}});var tw=oe((fj,QA)=>{"use strict";l();var{ObjectSetPrototypeOf:ZA,Symbol:ok}=ot();QA.exports=Xi;var{ERR_METHOD_NOT_IMPLEMENTED:sk}=cr().codes,ew=si(),{getHighWaterMark:ck}=Dd();ZA(Xi.prototype,ew.prototype);ZA(Xi,ew);var Kd=ok("kCallback");function Xi(t){if(!(this instanceof Xi))return new Xi(t);let e=t?ck(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),ew.call(this,t),this._readableState.sync=!1,this[Kd]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",ak)}function Qm(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 ak(){this._final!==Qm&&Qm.call(this)}Xi.prototype._final=Qm;Xi.prototype._transform=function(t,e,r){throw new sk("_transform()")};Xi.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[Kd]=r})};Xi.prototype._read=function(){if(this[Kd]){let t=this[Kd];this[Kd]=null,t()}}});var nw=oe((hj,tT)=>{"use strict";l();var{ObjectSetPrototypeOf:eT}=ot();tT.exports=Ma;var rw=tw();eT(Ma.prototype,rw.prototype);eT(Ma,rw);function Ma(t){if(!(this instanceof Ma))return new Ma(t);rw.call(this,t)}Ma.prototype._transform=function(t,e,r){r(null,t)}});var Gh=oe((yj,sT)=>{l();var $d=vi(),{ArrayIsArray:uk,Promise:dk,SymbolAsyncIterator:fk,SymbolDispose:lk}=ot(),Wh=Yi(),{once:hk}=Qt(),pk=sc(),rT=si(),{aggregateTwoErrors:yk,codes:{ERR_INVALID_ARG_TYPE:lw,ERR_INVALID_RETURN_VALUE:iw,ERR_MISSING_ARGS:gk,ERR_STREAM_DESTROYED:mk,ERR_STREAM_PREMATURE_CLOSE:wk},AbortError:bk}=cr(),{validateFunction:xk,validateAbortSignal:Ek}=Ra(),{isIterable:dc,isReadable:ow,isReadableNodeStream:jh,isNodeStream:nT,isTransformStream:Ka,isWebStream:vk,isReadableStream:sw,isReadableFinished:Sk}=ni(),Ak=globalThis.AbortController||Ia().AbortController,cw,aw,uw;function iT(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Wh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,pk.destroyer(t,o||new mk("pipe")))},cleanup:i}}function Tk(t){return xk(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function dw(t){if(dc(t))return t;if(jh(t))return _k(t);throw new lw("val",["Readable","Iterable","AsyncIterable"],t)}async function*_k(t){aw||(aw=Cd()),yield*aw.prototype[fk].call(t)}async function Fh(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new dk((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Wh(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?yk(i,u):u)}finally{a(),e.off("drain",s)}}async function fw(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 Ik(...t){return oT(t,hk(Tk(t)))}function oT(t,e,r){if(t.length===1&&uk(t[0])&&(t=t[0]),t.length<2)throw new gk("streams");let n=new Ak,i=n.signal,o=r?.signal,s=[];Ek(o,"options.signal");function c(){g(new bk)}uw=uw||Qt().addAbortListener;let a;o&&(a=uw(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[lk](),n.abort(),O&&(u||s.forEach(M=>M()),$d.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(nT(O)){let $=function(Z){Z&&Z.name!=="AbortError"&&Z.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(Z)};var I=$;if(q){let{destroy:Z,cleanup:Q}=iT(O,T,M);f.push(Z),ow(O)&&j&&s.push(Q)}O.on("error",$),ow(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!dc(y))throw new iw("Iterable, AsyncIterable or Stream","source",y)}else dc(O)||jh(O)||Ka(O)?y=O:y=rT.from(O);else if(typeof O=="function"){if(Ka(y)){var x;y=dw((x=y)===null||x===void 0?void 0:x.readable)}else y=dw(y);if(y=O(y,{signal:i}),T){if(!dc(y,!0))throw new iw("AsyncIterable",`transform[${A-1}]`,y)}else{var S;cw||(cw=nw());let $=new cw({objectMode:!0}),Z=(S=y)===null||S===void 0?void 0:S.then;if(typeof Z=="function")h++,Z.call(y,_=>{d=_,_!=null&&$.write(_),q&&$.end(),$d.nextTick(p)},_=>{$.destroy(_),$d.nextTick(p,_)});else if(dc(y,!0))h++,Fh(y,$,p,{end:q});else if(sw(y)||Ka(y)){let _=y.readable||y;h++,Fh(_,$,p,{end:q})}else throw new iw("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=iT(y,!1,!0);f.push(Q),j&&s.push(G)}}else if(nT(O)){if(jh(y)){h+=2;let $=Bk(y,O,p,{end:q});ow(O)&&j&&s.push($)}else if(Ka(y)||sw(y)){let $=y.readable||y;h++,Fh($,O,p,{end:q})}else if(dc(y))h++,Fh(y,O,p,{end:q});else throw new lw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(vk(O)){if(jh(y))h++,fw(dw(y),O,p,{end:q});else if(sw(y)||dc(y))h++,fw(y,O,p,{end:q});else if(Ka(y))h++,fw(y.readable,O,p,{end:q});else throw new lw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=rT.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&$d.nextTick(c),y}function Bk(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new wk)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;Sk(t)?$d.nextTick(s):t.once("end",s)}else r();return Wh(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)}),Wh(e,{readable:!1,writable:!0},r)}sT.exports={pipelineImpl:oT,pipeline:Ik}});var pw=oe((mj,lT)=>{"use strict";l();var{pipeline:Rk}=Gh(),zh=si(),{destroyer:Uk}=sc(),{isNodeStream:Yh,isReadable:cT,isWritable:aT,isWebStream:hw,isTransformStream:fc,isWritableStream:uT,isReadableStream:dT}=ni(),{AbortError:Ok,codes:{ERR_INVALID_ARG_VALUE:fT,ERR_MISSING_ARGS:Dk}}=cr(),kk=Yi();lT.exports=function(...e){if(e.length===0)throw new Dk("streams");if(e.length===1)return zh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=zh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=zh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!Yh(e[p])&&!hw(e[p]))){if(p<e.length-1&&!(cT(e[p])||dT(e[p])||fc(e[p])))throw new fT(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(aT(e[p])||uT(e[p])||fc(e[p])))throw new fT(`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=Rk(e,a),f=!!(aT(u)||uT(u)||fc(u)),h=!!(cT(d)||dT(d)||fc(d));if(c=new zh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(Yh(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(hw(u)){let y=(fc(u)?u.writable:u).getWriter();c._write=async function(x,S,I){try{await y.ready,y.write(x).catch(()=>{}),I()}catch(A){I(A)}},c._final=async function(x){try{await y.ready,y.close().catch(()=>{}),i=x}catch(S){x(S)}}}let p=fc(d)?d.readable:d;kk(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(Yh(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(hw(d)){let g=(fc(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 Ok),o=null,n=null,i=null,s===null?g(p):(s=g,Yh(d)&&Uk(d,p))},c}});var vT=oe((bj,mw)=>{"use strict";l();var Nk=globalThis.AbortController||Ia().AbortController,{codes:{ERR_INVALID_ARG_VALUE:Ck,ERR_INVALID_ARG_TYPE:Hd,ERR_MISSING_ARGS:Lk,ERR_OUT_OF_RANGE:Pk},AbortError:ci}=cr(),{validateAbortSignal:lc,validateInteger:hT,validateObject:hc}=Ra(),Mk=ot().Symbol("kWeak"),Kk=ot().Symbol("kResistStopPropagation"),{finished:$k}=Yi(),Hk=pw(),{addAbortSignalNoValidate:Vk}=Od(),{isWritable:qk,isNodeStream:Fk}=ni(),{deprecate:jk}=Qt(),{ArrayPrototypePush:Wk,Boolean:Gk,MathFloor:pT,Number:zk,NumberIsNaN:Yk,Promise:yT,PromiseReject:gT,PromiseResolve:Jk,PromisePrototypeThen:mT,Symbol:bT}=ot(),Jh=bT("kEmpty"),wT=bT("kEof");function Xk(t,e){if(e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal"),Fk(t)&&!qk(t))throw new Ck("stream",t,"must be writable");let r=Hk(this,t);return e!=null&&e.signal&&Vk(e.signal,r),r}function Xh(t,e){if(typeof t!="function")throw new Hd("fn",["Function","AsyncFunction"],t);e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=pT(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=pT(e.highWaterMark)),hT(r,"options.concurrency",1),hT(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Qt().AbortSignalAny([e?.signal].filter(Gk)),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 ci;try{if(S=t(S,a),S===Jh)continue;S=Jk(S)}catch(I){S=gT(I)}h+=1,mT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new yT(I=>{d=I})}c.push(wT)}catch(S){let I=gT(S);mT(I,g,p),c.push(I)}finally{f=!0,u&&(u(),u=null)}}x();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===wT)return;if(o.aborted)throw new ci;S!==Jh&&(yield S),c.shift(),y()}await new yT(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function Zk(t=void 0){return t!=null&&hc(t,"options"),t?.signal!=null&&lc(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 ci({cause:t.signal.reason});yield[r++,i]}}).call(this)}async function xT(t,e=void 0){for await(let r of gw.call(this,t,e))return!0;return!1}async function Qk(t,e=void 0){if(typeof t!="function")throw new Hd("fn",["Function","AsyncFunction"],t);return!await xT.call(this,async(...r)=>!await t(...r),e)}async function e4(t,e){for await(let r of gw.call(this,t,e))return r}async function t4(t,e){if(typeof t!="function")throw new Hd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),Jh}for await(let n of Xh.call(this,r,e));}function gw(t,e){if(typeof t!="function")throw new Hd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:Jh}return Xh.call(this,r,e)}var yw=class extends Lk{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function r4(t,e,r){var n;if(typeof t!="function")throw new Hd("reducer",["Function","AsyncFunction"],t);r!=null&&hc(r,"options"),r?.signal!=null&&lc(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let u=new ci(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await $k(this.destroy(u)),u}let o=new Nk,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[Mk]:this,[Kk]:!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 ci;i?e=await t(e,u,{signal:s}):(e=u,i=!0)}if(!c&&!i)throw new yw}finally{o.abort()}return e}async function n4(t){t!=null&&hc(t,"options"),t?.signal!=null&&lc(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 ci(void 0,{cause:t.signal.reason});Wk(e,n)}return e}function i4(t,e){let r=Xh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function ET(t){if(t=zk(t),Yk(t))return 0;if(t<0)throw new Pk("number",">= 0",t);return t}function o4(t,e=void 0){return e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal"),t=ET(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new ci;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new ci;t--<=0&&(yield o)}}).call(this)}function s4(t,e=void 0){return e!=null&&hc(e,"options"),e?.signal!=null&&lc(e.signal,"options.signal"),t=ET(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new ci;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new ci;if(t-- >0&&(yield o),t<=0)return}}).call(this)}mw.exports.streamReturningOperators={asIndexedPairs:jk(Zk,"readable.asIndexedPairs will be removed in a future version."),drop:o4,filter:gw,flatMap:i4,map:Xh,take:s4,compose:Xk};mw.exports.promiseReturningOperators={every:Qk,forEach:t4,reduce:r4,toArray:n4,some:xT,find:e4}});var ww=oe((Ej,ST)=>{"use strict";l();var{ArrayPrototypePop:c4,Promise:a4}=ot(),{isIterable:u4,isNodeStream:d4,isWebStream:f4}=ni(),{pipelineImpl:l4}=Gh(),{finished:h4}=Yi();bw();function p4(...t){return new a4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!d4(o)&&!u4(o)&&!f4(o)){let s=c4(t);n=s.signal,i=s.end}l4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}ST.exports={finished:h4,pipeline:p4}});var bw=oe((Sj,DT)=>{l();var{Buffer:y4}=Ir(),{ObjectDefineProperty:Zi,ObjectKeys:_T,ReflectApply:IT}=ot(),{promisify:{custom:BT}}=Qt(),{streamReturningOperators:AT,promiseReturningOperators:TT}=vT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:RT}}=cr(),g4=pw(),{setDefaultHighWaterMark:m4,getDefaultHighWaterMark:w4}=Dd(),{pipeline:UT}=Gh(),{destroyer:b4}=sc(),OT=Yi(),xw=ww(),Vd=ni(),We=DT.exports=Uh().Stream;We.isDestroyed=Vd.isDestroyed;We.isDisturbed=Vd.isDisturbed;We.isErrored=Vd.isErrored;We.isReadable=Vd.isReadable;We.isWritable=Vd.isWritable;We.Readable=Cd();for(let t of _T(AT)){let r=function(...n){if(new.target)throw RT();return We.Readable.from(IT(e,this,n))};Ew=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 Ew;for(let t of _T(TT)){let r=function(...i){if(new.target)throw RT();return IT(e,this,i)};Ew=r;let e=TT[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 Ew;We.Writable=qh();We.Duplex=si();We.Transform=tw();We.PassThrough=nw();We.pipeline=UT;var{addAbortSignal:x4}=Od();We.addAbortSignal=x4;We.finished=OT;We.destroy=b4;We.compose=g4;We.setDefaultHighWaterMark=m4;We.getDefaultHighWaterMark=w4;Zi(We,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return xw}});Zi(UT,BT,{__proto__:null,enumerable:!0,get(){return xw.pipeline}});Zi(OT,BT,{__proto__:null,enumerable:!0,get(){return xw.finished}});We.Stream=We;We._isUint8Array=function(e){return e instanceof Uint8Array};We._uint8ArrayToBuffer=function(e){return y4.from(e.buffer,e.byteOffset,e.byteLength)}});var vw=oe((Tj,mt)=>{"use strict";l();var _t=bw(),E4=ww(),v4=_t.Readable.destroy;mt.exports=_t.Readable;mt.exports._uint8ArrayToBuffer=_t._uint8ArrayToBuffer;mt.exports._isUint8Array=_t._isUint8Array;mt.exports.isDisturbed=_t.isDisturbed;mt.exports.isErrored=_t.isErrored;mt.exports.isReadable=_t.isReadable;mt.exports.Readable=_t.Readable;mt.exports.Writable=_t.Writable;mt.exports.Duplex=_t.Duplex;mt.exports.Transform=_t.Transform;mt.exports.PassThrough=_t.PassThrough;mt.exports.addAbortSignal=_t.addAbortSignal;mt.exports.finished=_t.finished;mt.exports.destroy=_t.destroy;mt.exports.destroy=v4;mt.exports.pipeline=_t.pipeline;mt.exports.compose=_t.compose;Object.defineProperty(_t,"promises",{configurable:!0,enumerable:!0,get(){return E4}});mt.exports.Stream=_t.Stream;mt.exports.default=mt.exports});var eI=oe((Kp,Q_)=>{l();(function(t,e){typeof Kp=="object"&&typeof Q_<"u"?e(Kp):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Kp,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]"),he="[\\x0A]",Te="[\\x20]",De=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),wt="[\\:\\/\\?\\#\\[\\]\\@]",Ae="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",rt=e(wt,Ae),bt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Xe=B?"[\\uE000-\\uF8FF]":"[]",Ie=e(v,K,"[\\-\\.\\_\\~]",bt),nt=r(v+e(v,K,"[\\+\\-\\.]")+"*"),Ne=r(r(De+"|"+e(Ie,Ae,"[\\:]"))+"*"),hs=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),Tr=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),zr=r(Tr+"\\."+Tr+"\\."+Tr+"\\."+Tr),Ke=r(te+"{1,4}"),_r=r(r(Ke+"\\:"+Ke)+"|"+zr),Yr=r(r(Ke+"\\:")+"{6}"+_r),Mn=r("\\:\\:"+r(Ke+"\\:")+"{5}"+_r),ps=r(r(Ke)+"?\\:\\:"+r(Ke+"\\:")+"{4}"+_r),gi=r(r(r(Ke+"\\:")+"{0,1}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{3}"+_r),bu=r(r(r(Ke+"\\:")+"{0,2}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{2}"+_r),Rf=r(r(r(Ke+"\\:")+"{0,3}"+Ke)+"?\\:\\:"+Ke+"\\:"+_r),Uf=r(r(r(Ke+"\\:")+"{0,4}"+Ke)+"?\\:\\:"+_r),Bc=r(r(r(Ke+"\\:")+"{0,5}"+Ke)+"?\\:\\:"+Ke),Rc=r(r(r(Ke+"\\:")+"{0,6}"+Ke)+"?\\:\\:"),mi=r([Yr,Mn,ps,gi,bu,Rf,Uf,Bc,Rc].join("|")),Uc=r(r(Ie+"|"+De)+"+"),ay=r(mi+"\\%25"+Uc),ys=r(mi+r("\\%25|\\%(?!"+te+"{2})")+Uc),bB=r("[vV]"+te+"+\\."+e(Ie,Ae,"[\\:]")+"+"),xB=r("\\["+r(ys+"|"+mi+"|"+bB)+"\\]"),wx=r(r(De+"|"+e(Ie,Ae))+"*"),xu=r(xB+"|"+zr+"(?!"+wx+")|"+wx),Eu=r(K+"*"),bx=r(r(Ne+"@")+"?"+xu+r("\\:"+Eu)+"?"),vu=r(De+"|"+e(Ie,Ae,"[\\:\\@]")),EB=r(vu+"*"),xx=r(vu+"+"),vB=r(r(De+"|"+e(Ie,Ae,"[\\@]"))+"+"),wi=r(r("\\/"+EB)+"*"),Oc=r("\\/"+r(xx+wi)+"?"),uy=r(vB+wi),Of=r(xx+wi),Dc="(?!"+vu+")",XL=r(wi+"|"+Oc+"|"+uy+"|"+Of+"|"+Dc),kc=r(r(vu+"|"+e("[\\/\\?]",Xe))+"*"),Su=r(r(vu+"|[\\/\\?]")+"*"),Ex=r(r("\\/\\/"+bx+wi)+"|"+Oc+"|"+Of+"|"+Dc),SB=r(nt+"\\:"+Ex+r("\\?"+kc)+"?"+r("\\#"+Su)+"?"),AB=r(r("\\/\\/"+bx+wi)+"|"+Oc+"|"+uy+"|"+Dc),TB=r(AB+r("\\?"+kc)+"?"+r("\\#"+Su)+"?"),ZL=r(SB+"|"+TB),QL=r(nt+"\\:"+Ex+r("\\?"+kc)+"?"),eP="^("+nt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+xu+")"+r("\\:("+Eu+")")+"?)")+"?("+wi+"|"+Oc+"|"+Of+"|"+Dc+")")+r("\\?("+kc+")")+"?"+r("\\#("+Su+")")+"?$",tP="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+xu+")"+r("\\:("+Eu+")")+"?)")+"?("+wi+"|"+Oc+"|"+uy+"|"+Dc+")")+r("\\?("+kc+")")+"?"+r("\\#("+Su+")")+"?$",rP="^("+nt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+xu+")"+r("\\:("+Eu+")")+"?)")+"?("+wi+"|"+Oc+"|"+Of+"|"+Dc+")")+r("\\?("+kc+")")+"?$",nP="^"+r("\\#("+Su+")")+"?$",iP="^"+r("("+Ne+")@")+"?("+xu+")"+r("\\:("+Eu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Ie,Ae),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Ie,Ae),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Ie,Ae),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Ie,Ae),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Ie,Ae,"[\\:\\@\\/\\?]",Xe),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Ie,Ae,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Ie,Ae),"g"),UNRESERVED:new RegExp(Ie,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Ie,rt),"g"),PCT_ENCODED:new RegExp(De,"g"),IPV4ADDRESS:new RegExp("^("+zr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+mi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+Uc+")")+"?\\]?$")}}var a=c(!1),u=c(!0),d=function(){function B(v,k){var K=[],H=!0,te=!1,he=void 0;try{for(var Te=v[Symbol.iterator](),De;!(H=(De=Te.next()).done)&&(K.push(De.value),!(k&&K.length===k));H=!0);}catch(wt){te=!0,he=wt}finally{try{!H&&Te.return&&Te.return()}finally{if(te)throw he}}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,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,Z=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 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?Z(v/S):v>>1,v+=Z(v/k);v>$*y>>1;H+=p)v=Z(v/$);return Z(H+($+1)*v/(v+x))},C=function(v){var k=[],K=v.length,H=0,te=A,he=I,Te=v.lastIndexOf(O);Te<0&&(Te=0);for(var De=0;De<Te;++De)v.charCodeAt(De)>=128&&G("not-basic"),k.push(v.charCodeAt(De));for(var wt=Te>0?Te+1:0;wt<K;){for(var Ae=H,rt=1,bt=p;;bt+=p){wt>=K&&G("invalid-input");var Xe=L(v.charCodeAt(wt++));(Xe>=p||Xe>Z((h-H)/rt))&&G("overflow"),H+=Xe*rt;var Ie=bt<=he?g:bt>=he+y?y:bt-he;if(Xe<Ie)break;var nt=p-Ie;rt>Z(h/nt)&&G("overflow"),rt*=nt}var Ne=k.length+1;he=R(H-Ae,Ne,Ae==0),Z(H/Ne)>h-te&&G("overflow"),te+=Z(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,he=I,Te=!0,De=!1,wt=void 0;try{for(var Ae=v[Symbol.iterator](),rt;!(Te=(rt=Ae.next()).done);Te=!0){var bt=rt.value;bt<128&&k.push(Q(bt))}}catch(ys){De=!0,wt=ys}finally{try{!Te&&Ae.return&&Ae.return()}finally{if(De)throw wt}}var Xe=k.length,Ie=Xe;for(Xe&&k.push(O);Ie<K;){var nt=h,Ne=!0,hs=!1,Tr=void 0;try{for(var zr=v[Symbol.iterator](),Ke;!(Ne=(Ke=zr.next()).done);Ne=!0){var _r=Ke.value;_r>=H&&_r<nt&&(nt=_r)}}catch(ys){hs=!0,Tr=ys}finally{try{!Ne&&zr.return&&zr.return()}finally{if(hs)throw Tr}}var Yr=Ie+1;nt-H>Z((h-te)/Yr)&&G("overflow"),te+=(nt-H)*Yr,H=nt;var Mn=!0,ps=!1,gi=void 0;try{for(var bu=v[Symbol.iterator](),Rf;!(Mn=(Rf=bu.next()).done);Mn=!0){var Uf=Rf.value;if(Uf<H&&++te>h&&G("overflow"),Uf==H){for(var Bc=te,Rc=p;;Rc+=p){var mi=Rc<=he?g:Rc>=he+y?y:Rc-he;if(Bc<mi)break;var Uc=Bc-mi,ay=p-mi;k.push(Q(N(mi+Uc%ay,0))),Bc=Z(Uc/ay)}k.push(Q(N(Bc,0))),he=R(te,Yr,Ie==Xe),te=0,++Ie}}}catch(ys){ps=!0,gi=ys}finally{try{!Mn&&bu.return&&bu.return()}finally{if(ps)throw gi}}++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 X(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 he=parseInt(B.substr(k+4,2),16),Te=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(he&63)<<6|Te&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=X(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 Oe(B,v){var k=B.match(v.IPV6ADDRESS)||[],K=d(k,3),H=K[1],te=K[2];if(H){for(var he=H.toLowerCase().split("::").reverse(),Te=d(he,2),De=Te[0],wt=Te[1],Ae=wt?wt.split(":").map(ee):[],rt=De.split(":").map(ee),bt=v.IPV4ADDRESS.test(rt[rt.length-1]),Xe=bt?7:8,Ie=rt.length-Xe,nt=Array(Xe),Ne=0;Ne<Xe;++Ne)nt[Ne]=Ae[Ne]||rt[Ie+Ne]||"";bt&&(nt[Xe-1]=ce(nt[Xe-1],v));var hs=nt.reduce(function(Yr,Mn,ps){if(!Mn||Mn==="0"){var gi=Yr[Yr.length-1];gi&&gi.index+gi.length===ps?gi.length++:Yr.push({index:ps,length:1})}return Yr},[]),Tr=hs.sort(function(Yr,Mn){return Mn.length-Yr.length})[0],zr=void 0;if(Tr&&Tr.length>1){var Ke=nt.slice(0,Tr.index),_r=nt.slice(Tr.index+Tr.length);zr=Ke.join(":")+"::"+_r.join(":")}else zr=nt.join(":");return te&&(zr+="%"+te),zr}else return B}var Me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".match(/(){0}/)[1]===void 0;function Et(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(Me);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=Oe(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,X).toLowerCase())}catch(he){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+he}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 yi(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(Oe(ce(String(B.host),k),k).replace(k.IPV6ADDRESS,function(H,te,he){return"["+te+(he?"%25"+he:"")+"]"})),(typeof B.port=="number"||typeof B.port=="string")&&(K.push(":"),K.push(String(B.port))),K.length?K.join(""):void 0}var go=/^\.\.?\//,yu=/^\/\.(\/|$)/,Sf=/^\/\.\.(\/|$)/,oy=/^\/?(?:.|\n)*?(?=\/|$)/;function mo(B){for(var v=[];B.length;)if(B.match(go))B=B.replace(go,"");else if(B.match(yu))B=B.replace(yu,"/");else if(B.match(Sf))B=B.replace(Sf,"/"),v.pop();else if(B==="."||B==="..")B="";else{var k=B.match(oy);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 Wr(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,X).toLowerCase())}catch(Te){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Te}}ue(B,k),v.reference!=="suffix"&&B.scheme&&(K.push(B.scheme),K.push(":"));var te=yi(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 he=B.path;!v.absolutePath&&(!H||!H.absolutePath)&&(he=mo(he)),te===void 0&&(he=he.replace(/^\/\//,"/%2F")),K.push(he)}return B.query!==void 0&&(K.push("?"),K.push(B.query)),B.fragment!==void 0&&(K.push("#"),K.push(B.fragment)),K.join("")}function gu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=Et(Wr(B,k),k),v=Et(Wr(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=mo(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=mo(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=mo(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=mo(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 Af(B,v,k){var K=s({scheme:"null"},k);return Wr(gu(Et(B,K),Et(v,K),K,!0),K)}function mu(B,v){return typeof B=="string"?B=Wr(Et(B,v),v):n(B)==="object"&&(B=Et(Wr(B,v),v)),B}function Tf(B,v,k){return typeof B=="string"?B=Wr(Et(B,k),k):n(B)==="object"&&(B=Wr(B,k)),typeof v=="string"?v=Wr(Et(v,k),k):n(v)==="object"&&(v=Wr(v,k)),B===v}function _f(B,v){return B&&B.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function Gr(B,v){return B&&B.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,X)}var wo={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}},wu={scheme:"https",domainHost:wo.domainHost,parse:wo.parse,serialize:wo.serialize};function If(B){return typeof B.secure=="boolean"?B.secure:String(B.scheme).toLowerCase()==="wss"}var ls={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=If(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===(If(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],he=H[1];v.path=te&&te!=="/"?te:void 0,v.query=he,v.resourceName=void 0}return v.fragment=void 0,v}},Bf={scheme:"wss",domainHost:ls.domainHost,parse:ls.parse,serialize:ls.serialize},sy={},aB=!0,hx="[A-Za-z0-9\\-\\.\\_\\~"+(aB?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Pn="[0-9A-Fa-f]",uB=r(r("%[EFef]"+Pn+"%"+Pn+Pn+"%"+Pn+Pn)+"|"+r("%[89A-Fa-f]"+Pn+"%"+Pn+Pn)+"|"+r("%"+Pn+Pn)),dB="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",fB="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",lB=e(fB,'[\\"\\\\]'),hB="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",pB=new RegExp(hx,"g"),Ic=new RegExp(uB,"g"),yB=new RegExp(e("[^]",dB,"[\\.]",'[\\"]',lB),"g"),px=new RegExp(e("[^]",hx,hB),"g"),gB=px;function cy(B){var v=X(B);return v.match(pB)?v:B}var yx={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,he={},Te=K.query.split("&"),De=0,wt=Te.length;De<wt;++De){var Ae=Te[De].split("=");switch(Ae[0]){case"to":for(var rt=Ae[1].split(","),bt=0,Xe=rt.length;bt<Xe;++bt)H.push(rt[bt]);break;case"subject":K.subject=Gr(Ae[1],k);break;case"body":K.body=Gr(Ae[1],k);break;default:te=!0,he[Gr(Ae[0],k)]=Gr(Ae[1],k);break}}te&&(K.headers=he)}K.query=void 0;for(var Ie=0,nt=H.length;Ie<nt;++Ie){var Ne=H[Ie].split("@");if(Ne[0]=Gr(Ne[0]),k.unicodeSupport)Ne[1]=Gr(Ne[1],k).toLowerCase();else try{Ne[1]=z.toASCII(Gr(Ne[1],k).toLowerCase())}catch(hs){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+hs}H[Ie]=Ne.join("@")}return K},serialize:function(v,k){var K=v,H=o(v.to);if(H){for(var te=0,he=H.length;te<he;++te){var Te=String(H[te]),De=Te.lastIndexOf("@"),wt=Te.slice(0,De).replace(Ic,cy).replace(Ic,i).replace(yB,Y),Ae=Te.slice(De+1);try{Ae=k.iri?z.toUnicode(Ae):z.toASCII(Gr(Ae,k).toLowerCase())}catch(Ie){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Ie}H[te]=wt+"@"+Ae}K.path=H.join(",")}var rt=v.headers=v.headers||{};v.subject&&(rt.subject=v.subject),v.body&&(rt.body=v.body);var bt=[];for(var Xe in rt)rt[Xe]!==sy[Xe]&&bt.push(Xe.replace(Ic,cy).replace(Ic,i).replace(px,Y)+"="+rt[Xe].replace(Ic,cy).replace(Ic,i).replace(gB,Y));return bt.length&&(K.query=bt.join("&")),K}},mB=/^([^\:]+)\:(.*)/,gx={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(mB),H=v;if(K){var te=k.scheme||H.scheme||"urn",he=K[1].toLowerCase(),Te=K[2],De=te+":"+(k.nid||he),wt=W[De];H.nid=he,H.nss=Te,H.path=void 0,wt&&(H=wt.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),he=W[te];he&&(v=he.serialize(v,k));var Te=v,De=v.nss;return Te.path=(H||k.nid)+":"+De,Te}},wB=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,mx={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(wB))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[wo.scheme]=wo,W[wu.scheme]=wu,W[ls.scheme]=ls,W[Bf.scheme]=Bf,W[yx.scheme]=yx,W[gx.scheme]=gx,W[mx.scheme]=mx,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=X,t.parse=Et,t.removeDotSegments=mo,t.serialize=Wr,t.resolveComponents=gu,t.resolve=Af,t.normalize=mu,t.equal=Tf,t.escapeComponent=_f,t.unescapeComponent=Gr,Object.defineProperty(t,"__esModule",{value:!0})})});var rI=oe((XX,tI)=>{"use strict";l();tI.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 yI=oe((eee,pI)=>{l();var ou=1e3,su=ou*60,cu=su*60,xc=cu*24,nL=xc*7,iL=xc*365.25;pI.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return oL(t);if(r==="number"&&isFinite(t))return e.long?cL(t):sL(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function oL(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*iL;case"weeks":case"week":case"w":return r*nL;case"days":case"day":case"d":return r*xc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*cu;case"minutes":case"minute":case"mins":case"min":case"m":return r*su;case"seconds":case"second":case"secs":case"sec":case"s":return r*ou;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function sL(t){var e=Math.abs(t);return e>=xc?Math.round(t/xc)+"d":e>=cu?Math.round(t/cu)+"h":e>=su?Math.round(t/su)+"m":e>=ou?Math.round(t/ou)+"s":t+"ms"}function cL(t){var e=Math.abs(t);return e>=xc?Fp(t,e,xc,"day"):e>=cu?Fp(t,e,cu,"hour"):e>=su?Fp(t,e,su,"minute"):e>=ou?Fp(t,e,ou,"second"):t+" ms"}function Fp(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var JL={};Au(JL,{AggregateBeaconError:()=>N0,Appendix:()=>tt,BECH32M_CHARS:()=>NL,BTCR2_DID_DOCUMENT_CONTEXT:()=>ZI,BTCR2_UPDATE_CONTEXT:()=>_c,BeaconError:()=>Jt,BeaconFactory:()=>Ms,BeaconSignalDiscovery:()=>nx,BeaconUtils:()=>ir,CASBeacon:()=>Xu,CASBeaconError:()=>C0,CHANGE_OUTPUT_VBYTES:()=>$0,DEACTIVATION_PATCH:()=>ix,DEFAULT_FEE_ESTIMATOR:()=>Cl,DEFAULT_MIN_CONF:()=>sB,DID_REGEX:()=>QI,DUST_LIMIT_SATS:()=>H0,DidBtcr2:()=>lx,DidDocument:()=>jr,DidDocumentBuilder:()=>fx,DidVerificationMethod:()=>ny,GenesisDocument:()=>lu,ID_PLACEHOLDER_VALUE:()=>nr,Identifier:()=>lr,MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX:()=>Tc,MULTIKEY_VERIFICATION_METHOD_TYPE:()=>Ac,P2PKH_BEACON_TX_VSIZE:()=>Mv,P2TR_BEACON_TX_VSIZE:()=>Lv,P2WPKH_BEACON_TX_VSIZE:()=>Pv,Resolver:()=>yo,SINGLETON_BEACON_TX_VSIZE:()=>Kv,SMTBeacon:()=>od,SMTBeaconError:()=>oa,SPENDABLE_DUST_LIMIT_SATS:()=>Ll,SinglePartyBeacon:()=>Pi,SingletonBeacon:()=>Zu,SingletonBeaconError:()=>k0,StaticFeeEstimator:()=>sa,Updater:()=>vf,beaconTxVsize:()=>V0,buildAggregationBeaconTx:()=>h6,deriveSingletonAddress:()=>$v,detectSingletonScriptKind:()=>q0,extractOpReturnSignalHash:()=>rx,getAggregationCommunicationKey:()=>cB,isBtcr2UpdateContext:()=>iy,isMultikeyVerificationMethod:()=>eB,opReturnScript:()=>j0,resolveBtcr2SenderPk:()=>YL,resolveChangeAddress:()=>F0,selectSpendableUtxo:()=>Vv});l();l();l();l();var bs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function xs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Tu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function yn(t,...e){if(!xs(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 Pf(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Tu(t.outputLen),Tu(t.blockLen)}function Mc(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 Fx(t,e){yn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Fn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Mf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function gn(t,e){return t<<32-e|t>>>e}function _u(t,e){return t<<e|t>>>32-e>>>0}var jx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",f8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mt(t){if(yn(t),jx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=f8[t[r]];return e}var Si={_0:48,_9:57,A:65,F:70,a:97,f:102};function qx(t){if(t>=Si._0&&t<=Si._9)return t-Si._0;if(t>=Si.A&&t<=Si.F)return t-(Si.A-10);if(t>=Si.a&&t<=Si.f)return t-(Si.a-10)}function Br(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(jx)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=qx(t.charCodeAt(o)),c=qx(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 Es(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Iu(t){return typeof t=="string"&&(t=Es(t)),yn(t),t}function ht(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];yn(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 Pc=class{};function Kf(t){let e=n=>t().update(Iu(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Rr(t=32){if(bs&&typeof bs.getRandomValues=="function")return bs.getRandomValues(new Uint8Array(t));if(bs&&typeof bs.randomBytes=="function")return Uint8Array.from(bs.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}l();l();l();l();l();function l8(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 Ey(t,e,r){return t&e^~t&r}function vy(t,e,r){return t&e^t&r^e&r}var Kc=class extends Pc{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=Mf(this.buffer)}update(e){Mc(this),e=Iu(e),yn(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=Mf(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){Mc(this),Fx(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Fn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;l8(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Mf(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()}},Ai=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var h8=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]),bo=new Uint32Array(64),Sy=class extends Kc{constructor(e=32){super(64,e,8,!1),this.A=Ai[0]|0,this.B=Ai[1]|0,this.C=Ai[2]|0,this.D=Ai[3]|0,this.E=Ai[4]|0,this.F=Ai[5]|0,this.G=Ai[6]|0,this.H=Ai[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)bo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=bo[f-15],p=bo[f-2],g=gn(h,7)^gn(h,18)^h>>>3,y=gn(p,17)^gn(p,19)^p>>>10;bo[f]=y+bo[f-7]+g+bo[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=gn(c,6)^gn(c,11)^gn(c,25),p=d+h+Ey(c,a,u)+h8[f]+bo[f]|0,y=(gn(n,2)^gn(n,13)^gn(n,22))+vy(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(){Fn(bo)}destroy(){this.set(0,0,0,0,0,0,0,0),Fn(this.buffer)}};var ke=Kf(()=>new Sy);l();l();l();var $f=class extends Pc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Pf(e);let n=Iu(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),Fn(o)}update(e){return Mc(this),this.iHash.update(e),this}digestInto(e){Mc(this),yn(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()}},Ay=(t,e,r)=>new $f(t,e).update(r).digest();Ay.create=(t,e)=>new $f(t,e);l();var Iy=BigInt(0),_y=BigInt(1);function Bu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function xo(t,e,r=""){let n=xs(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 Ru(t){let e=t.toString(16);return e.length&1?"0"+e:e}function Wx(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Iy:BigInt("0x"+t)}function Ti(t){return Wx(Mt(t))}function By(t){return yn(t),Wx(Mt(Uint8Array.from(t).reverse()))}function $c(t,e){return Br(t.toString(16).padStart(e*2,"0"))}function Ry(t,e){return $c(t,e).reverse()}function ct(t,e,r){let n;if(typeof e=="string")try{n=Br(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(xs(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 Eo(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 Ty=t=>typeof t=="bigint"&&Iy<=t;function Uu(t,e,r){return Ty(t)&&Ty(e)&&Ty(r)&&e<=t&&t<r}function Gx(t,e,r,n){if(!Uu(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Hf(t){let e;for(e=0;t>Iy;t>>=_y,e+=1);return e}var vo=t=>(_y<<BigInt(t))-_y;function zx(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 ht(...g)};return(p,g)=>{a(),d(p);let y;for(;!(y=g(f()));)d();return a(),y}}function Ou(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 Uy(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 or=BigInt(0),Wt=BigInt(1),vs=BigInt(2),Xx=BigInt(3),Zx=BigInt(4),Qx=BigInt(5),p8=BigInt(7),eE=BigInt(8),y8=BigInt(9),tE=BigInt(16);function Ur(t,e){let r=t%e;return r>=or?r:e+r}function Or(t,e,r){let n=t;for(;e-- >or;)n*=n,n%=r;return n}function Yx(t,e){if(t===or)throw new Error("invert: expected non-zero number");if(e<=or)throw new Error("invert: expected positive modulus, got "+e);let r=Ur(t,e),n=e,i=or,o=Wt,s=Wt,c=or;for(;r!==or;){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!==Wt)throw new Error("invert: does not exist");return Ur(i,e)}function Oy(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function rE(t,e){let r=(t.ORDER+Wt)/Zx,n=t.pow(e,r);return Oy(t,n,e),n}function g8(t,e){let r=(t.ORDER-Qx)/eE,n=t.mul(e,vs),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,vs),i),c=t.mul(o,t.sub(s,t.ONE));return Oy(t,c,e),c}function m8(t){let e=So(t),r=nE(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+p8)/tE;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 Oy(c,x,a),x}}function nE(t){if(t<Xx)throw new Error("sqrt is not defined for small field");let e=t-Wt,r=0;for(;e%vs===or;)e/=vs,r++;let n=vs,i=So(t);for(;Jx(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return rE;let o=i.pow(n,e),s=(e+Wt)/vs;return function(a,u){if(a.is0(u))return u;if(Jx(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=Wt<<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 w8(t){return t%Zx===Xx?rE:t%eE===Qx?g8:t%tE===y8?m8(t):nE(t)}var b8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Dy(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=b8.reduce((n,i)=>(n[i]="function",n),e);return Ou(t,r),t}function x8(t,e,r){if(r<or)throw new Error("invalid exponent, negatives unsupported");if(r===or)return t.ONE;if(r===Wt)return e;let n=t.ONE,i=e;for(;r>or;)r&Wt&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Wt;return n}function Vf(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 Jx(t,e){let r=(t.ORDER-Wt)/vs,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 qf(t,e){e!==void 0&&Tu(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function So(t,e,r=!1,n={}){if(t<=or)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}=qf(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:vo(a),ZERO:or,ONE:Wt,allowedLengths:c,create:h=>Ur(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return or<=h&&h<t},is0:h=>h===or,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Wt)===Wt,neg:h=>Ur(-h,t),eql:(h,p)=>h===p,sqr:h=>Ur(h*h,t),add:(h,p)=>Ur(h+p,t),sub:(h,p)=>Ur(h-p,t),mul:(h,p)=>Ur(h*p,t),pow:(h,p)=>x8(f,h,p),div:(h,p)=>Ur(h*Yx(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Yx(h,t),sqrt:o||(h=>(d||(d=w8(t)),d(f,h))),toBytes:h=>r?Ry(h,u):$c(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?By(h):Ti(h);if(s&&(g=Ur(g,t)),!p&&!f.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>Vf(f,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(f)}function iE(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 ky(t){let e=iE(t);return e+Math.ceil(e/2)}function Ff(t,e,r=!1){let n=t.length,i=iE(e),o=ky(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?By(t):Ti(t),c=Ur(s,e-Wt)+Wt;return r?Ry(c,i):$c(c,i)}var Hc=BigInt(0),Ss=BigInt(1);function Du(t,e){let r=e.negate();return t?r:e}function Wf(t,e){let r=Vf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function aE(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ny(t,e){aE(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=vo(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function oE(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+=Ss);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 E8(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 v8(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 Cy=new WeakMap,uE=new WeakMap;function Ly(t){return uE.get(t)||1}function sE(t){if(t!==Hc)throw new Error("invalid wNAF")}var jf=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>Hc;)r&Ss&&(n=n.add(i)),i=i.double(),r>>=Ss;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Ny(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=Ny(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=oE(n,c,s);n=a,d?o=o.add(Du(h,r[p])):i=i.add(Du(f,r[u]))}return sE(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Ny(e,this.bits);for(let s=0;s<o.windows&&n!==Hc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=oE(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return sE(n),i}getPrecomputes(e,r,n){let i=Cy.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Cy.set(r,i))),i}cached(e,r,n){let i=Ly(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Ly(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){aE(r,this.bits),uE.set(e,r),Cy.delete(e)}hasCache(e){return Ly(e)!==1}};function dE(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>Hc||n>Hc;)r&Ss&&(o=o.add(i)),n&Ss&&(s=s.add(i)),i=i.double(),r>>=Ss,n>>=Ss;return{p1:o,p2:s}}function fE(t,e,r,n){E8(r,t),v8(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=Hf(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=vo(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 cE(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Dy(e),e}else return So(t,{isLE:r})}function lE(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>Hc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=cE(e.p,r.Fp,n),o=cE(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 hE=(t,e)=>(t+(t>=0?e:-e)/pE)/e;function S8(t,e,r){let[[n,i],[o,s]]=e,c=hE(s*t,r),a=hE(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<Ii,h=d<Ii;f&&(u=-u),h&&(d=-d);let p=vo(Math.ceil(Hf(r)/2))+Vc;if(u<Ii||u>=p||d<Ii||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function My(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Py(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Bu(r.lowS,"lowS"),Bu(r.prehash,"prehash"),r.format!==void 0&&My(r.format),r}var Ky=class extends Error{constructor(e=""){super(e)}},_i={Err:Ky,_tlv:{encode:(t,e)=>{let{Err:r}=_i;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=Ru(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Ru(i.length/2|128):"";return Ru(t)+o+i+e},decode(t,e){let{Err:r}=_i,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}=_i;if(t<Ii)throw new e("integer: negative integers are not allowed");let r=Ru(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}=_i;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 Ti(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=_i,i=ct("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}=_i,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},Ii=BigInt(0),Vc=BigInt(1),pE=BigInt(2),Gf=BigInt(3),A8=BigInt(4);function Ao(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=ct("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 T8(t,e={}){let r=lE("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Ou(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=gE(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:E,y:U}=_.toAffine(),L=n.toBytes(E);if(Bu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ht(yE(N),L)}else return ht(Uint8Array.of(4),L,n.toBytes(U))}function h(G){xo(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===_&&(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=${_} 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 x(G,_){let D=n.sqr(_),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,Gf),A8),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 S8(G,a.basises,i.ORDER)}let M=Uy((G,_)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(E,_),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=Uy(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(!x(_,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,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=Du(E,_),D=Du(U,D),_.add(D)}class ${constructor(_,D,E){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:E}=_||{};if(!_||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(xo(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ct("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Gf),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:E,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(E,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,E=n.mul(D,Gf),{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(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(_,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:E,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,Gf),W=n.mul(D,L),Y=n.mul(E,N),X=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,X),ee=n.sub(ee,ce),ce=n.add(E,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,X),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,X),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),X=n.mul(J,X),ee=n.mul(z,ee),Y=n.add(Y,X),X=n.sub(W,X),X=n.mul(J,X),ee=n.add(ee,X),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 E,U,L=N=>Q.cached(this,N,R=>Wf($,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),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);E=N,U=R}return Wf($,[E,U])[0]}multiplyUnsafe(_){let{endo:D}=e,E=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===Ii||E.is0())return $.ZERO;if(_===Vc)return E;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=dE($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,_)}multiplyAndAddUnsafe(_,D,E){let U=this.multiplyUnsafe(D).add(_.multiplyUnsafe(E));return U.is0()?void 0:U}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===Vc?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===Vc?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Bu(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Mt(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 Wf($,_)}static msm(_,D){return fE($,i,_,D)}static fromPrivateKey(_){return $.BASE.multiply(Ao(i,_))}}$.BASE=new $(o.Gx,o.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;let Z=i.BITS,Q=new jf($,e.endo?Math.ceil(Z/2):Z);return $.BASE.precompute(8),$}function yE(t){return Uint8Array.of(t?2:3)}function gE(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function _8(t,e={}){let{Fn:r}=t,n=e.randomBytes||Rr,i=Object.assign(gE(t.Fp,r),{seed:ky(r.ORDER)});function o(p){try{return!!Ao(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 Ff(xo(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(Ao(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=ct("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=Ao(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=>Ao(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function I8(t,e,r={}){Pf(e),Ou(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Rr,i=r.hmac||((D,...E)=>Ay(e,D,ht(...E))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=_8(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>>Vc;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 I(D,E){My(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return xo(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){I(E,U);let L;if(U==="der"){let{r:P,s:V}=_i.toSig(xo(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(Br(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*pE<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(ht(yE((R&1)===0),V)),z=s.inv(P),W=T(ct("msgHash",E)),Y=s.create(-W*z),X=s.create(N*z),ue=t.BASE.multiplyUnsafe(Y).add(J.multiplyUnsafe(X));if(ue.is0())throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return x(this.s)}toBytes(E=y){if(My(E),E==="der")return Br(_i.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 ht(Uint8Array.of(this.recovery),U,L)}return ht(U,L)}toHex(E){return Mt(this.toBytes(E))}assertValidity(){}static fromCompact(E){return A.fromBytes(ct("sig",E),"compact")}static fromDER(E){return A.fromBytes(ct("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 Mt(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Mt(this.toBytes("compact"))}}let O=r.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let U=Ti(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=vo(a);function q(D){return Gx("num < 2^"+a,D,Ii,M),s.toBytes(D)}function j(D,E){return xo(D,void 0,"message"),E?xo(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}=Py(U,g);D=j(D,N);let C=T(D),P=Ao(s,E),V=[q(P),q(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ct("extraEntropy",Y))}let J=ht(...V),z=C;function W(Y){let X=O(Y);if(!s.isValidNot0(X))return;let ue=s.inv(X),ee=t.BASE.multiply(X).toAffine(),ce=s.create(ee.x);if(ce===Ii)return;let Oe=s.create(ue*s.create(z+ce*P));if(Oe===Ii)return;let Me=(ee.x===ce?0:2)|Number(ee.y&Vc),Je=Oe;return L&&x(Oe)&&(Je=s.neg(Oe),Me^=1),new A(ce,Je,Me)}return{seed:J,k2sig:W}}function Z(D,E,U={}){D=ct("message",D);let{seed:L,k2sig:N}=$(D,E,U);return zx(e.outputLen,s.BYTES,i)(L,N)}function Q(D){let E,U=typeof D=="string"||xs(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(ct("sig",D),"der")}catch(N){if(!(N instanceof _i.Err))throw N}if(!E)try{E=A.fromBytes(ct("sig",D),"compact")}catch{return!1}}return E||!1}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=Py(L,g);if(U=ct("publicKey",U),E=j(ct("message",E),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(ct("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),X=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(X).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,E,U={}){let{prehash:L}=Py(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:Z,verify:G,recoverPublicKey:_,Signature:A,hash:e})}function B8(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=So(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 R8(t){let{CURVE:e,curveOpts:r}=B8(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 U8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,qf(r.Fn.ORDER,r.Fn.BITS))})}function mE(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=R8(t),o=T8(e,r),s=I8(o,n,i);return U8(t,s)}function wE(t,e){let r=n=>mE({...t,hash:n});return{...r(e),create:r}}var qc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},O8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},D8=BigInt(0),bE=BigInt(1),$y=BigInt(2);function k8(t){let e=qc.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=Or(d,r,e)*d%e,h=Or(f,r,e)*d%e,p=Or(h,$y,e)*u%e,g=Or(p,i,e)*p%e,y=Or(g,o,e)*g%e,x=Or(y,c,e)*y%e,S=Or(x,a,e)*x%e,I=Or(S,c,e)*y%e,A=Or(I,r,e)*d%e,O=Or(A,s,e)*g%e,T=Or(O,n,e)*u%e,M=Or(T,$y,e);if(!zf.eql(zf.sqr(M),t))throw new Error("Cannot find square root");return M}var zf=So(qc.p,{sqrt:k8}),To=wE({...qc,Fp:zf,lowS:!0,endo:O8},ke),xE={};function Yf(t,...e){let r=xE[t];if(r===void 0){let n=ke(Es(t));r=ht(n,n),xE[t]=r}return ke(ht(r,...e))}var Vy=t=>t.toBytes(!0).slice(1),Fc=To.Point,qy=t=>t%$y===D8;function Hy(t){let{Fn:e,BASE:r}=Fc,n=Ao(e,t),i=r.multiply(n);return{scalar:qy(i.y)?n:e.neg(n),bytes:Vy(i)}}function vE(t){let e=zf;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);qy(i)||(i=e.neg(i));let o=Fc.fromAffine({x:t,y:i});return o.assertValidity(),o}var ku=Ti;function SE(...t){return Fc.Fn.create(ku(Yf("BIP0340/challenge",...t)))}function EE(t){return Hy(t).bytes}function N8(t,e,r=Rr(32)){let{Fn:n}=Fc,i=ct("message",t),{bytes:o,scalar:s}=Hy(e),c=ct("auxRand",r,32),a=n.toBytes(s^ku(Yf("BIP0340/aux",c))),u=Yf("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Hy(u),h=SE(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!AE(p,i,o))throw new Error("sign: Invalid signature produced");return p}function AE(t,e,r){let{Fn:n,BASE:i}=Fc,o=ct("signature",t,64),s=ct("message",e),c=ct("publicKey",r,32);try{let a=vE(ku(c)),u=ku(o.subarray(0,32));if(!Uu(u,bE,qc.p))return!1;let d=ku(o.subarray(32,64));if(!Uu(d,bE,qc.n))return!1;let f=SE(n.toBytes(u),Vy(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!qy(g)||p!==u)}catch{return!1}}var Dr=(()=>{let r=(i=Rr(48))=>Ff(i,qc.n);To.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:EE(o)}}return{keygen:n,getPublicKey:EE,sign:N8,verify:AE,Point:Fc,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Yf,lift_x:vE,pointToBytes:Vy,numberToBytesBE:$c,bytesToNumberBE:Ti,mod:Ur},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var C8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),_E=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),L8=_E.map(t=>(9*t+5)%16),IE=(()=>{let r=[[_E],[L8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>C8[o]));return r})(),BE=IE[0],RE=IE[1],UE=[[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)),P8=BE.map((t,e)=>t.map(r=>UE[e][r])),M8=RE.map((t,e)=>t.map(r=>UE[e][r])),K8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),$8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function TE(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 Jf=new Uint32Array(16),Fy=class extends Kc{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)Jf[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=K8[p],x=$8[p],S=BE[p],I=RE[p],A=P8[p],O=M8[p];for(let T=0;T<16;T++){let M=_u(n+TE(p,o,c,u)+Jf[S[T]]+y,A[T])+f|0;n=f,f=u,u=_u(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=_u(i+TE(g,s,a,d)+Jf[I[T]]+x,O[T])+h|0;i=h,h=d,d=_u(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(){Fn(Jf)}destroy(){this.destroyed=!0,Fn(this.buffer),this.set(0,0,0,0,0)}},OE=Kf(()=>new Fy);l();l();function jc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function H8(t,...e){if(!jc(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 LE(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 Gy(t){if(typeof t!="function")throw new Error("function expected");return!0}function Wc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Cu(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Zf(t){if(!Array.isArray(t))throw new Error("array expected")}function PE(t,e){if(!LE(!0,e))throw new Error(`${t}: array of strings expected`)}function zy(t,e){if(!LE(!1,e))throw new Error(`${t}: array of numbers expected`)}function Lu(...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 el(t){let e=typeof t=="string"?t.split(""):t,r=e.length;PE("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Zf(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=>(Zf(i),i.map(o=>{Wc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function tl(t=""){return Wc("join",t),{encode:e=>(PE("join.decode",e),e.join(t)),decode:e=>(Wc("join.decode",e),e.split(t))}}function V8(t){return Gy(t),{encode:e=>e,decode:e=>t(e)}}function DE(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(Zf(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Cu(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 ME=(t,e)=>e===0?t:ME(e,t%e),Qf=(t,e)=>t+(e-ME(t,e)),Xf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function jy(t,e,r,n){if(Zf(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(Qf(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Qf(e,r)}`);let i=0,o=0,s=Xf[e],c=Xf[r]-1,a=[];for(let u of t){if(Cu(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=Xf[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 q8(t){Cu(t);let e=2**8;return{encode:r=>{if(!jc(r))throw new Error("radix.encode input should be Uint8Array");return DE(Array.from(r),e,t)},decode:r=>(zy("radix.decode",r),Uint8Array.from(DE(r,t,e)))}}function Yy(t,e=!1){if(Cu(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Qf(8,t)>32||Qf(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!jc(r))throw new Error("radix2.encode input should be Uint8Array");return jy(Array.from(r),8,t,!e)},decode:r=>(zy("radix2.decode",r),Uint8Array.from(jy(r,t,8,e)))}}function kE(t){return Gy(t),function(...e){try{return t.apply(null,e)}catch{}}}function F8(t,e){return Cu(t),Gy(e),{encode(r){if(!jc(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(!jc(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 Gc=Lu(Yy(6),el("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),tl("")),j8=t=>Lu(q8(58),el(t),tl("")),rl=j8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var KE=t=>Lu(F8(4,e=>t(t(e))),rl);var Wy=Lu(el("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),tl("")),NE=[996825010,642813549,513874426,1027748829,705979059];function Nu(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<NE.length;n++)(e>>n&1)===1&&(r^=NE[n]);return r}function CE(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=Nu(i)^s>>5}i=Nu(i);for(let o=0;o<n;o++)i=Nu(i)^t.charCodeAt(o)&31;for(let o of e)i=Nu(i)^o;for(let o=0;o<6;o++)i=Nu(i);return i^=r,Wy.encode(jy([i%Xf[30]],30,5,!1))}function $E(t){let e=t==="bech32"?1:734539939,r=Yy(5),n=r.decode,i=r.encode,o=kE(n);function s(f,h,p=90){Wc("bech32.encode prefix",f),jc(h)&&(h=Array.from(h)),zy("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=CE(x,h,e);return`${x}1${Wy.encode(h)}${S}`}function c(f,h=90){Wc("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 I=Wy.decode(S).slice(0,-6),A=CE(x,I,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:x,words:I}}let a=kE(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 nl=$E("bech32"),As=$E("bech32m"),HE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},W8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",G8={encode(t){return H8(t),t.toHex()},decode(t){return Wc("hex",t),Uint8Array.fromHex(t)}},ve=W8?G8:Lu(Yy(4),el("0123456789abcdef"),tl(""),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 He=new Uint8Array,Qy=new Uint8Array([0]);function zc(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 Xr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function z8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!Xr(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 e0=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Yc(t){return Object.prototype.toString.call(t)==="[object Object]"}function jn(t){return Number.isSafeInteger(t)}var il={equalBytes:zc,isBytes:Xr,isCoder:kr,checkBounds:qE,concatBytes:z8,createView:e0,isPlainObject:Yc},VE=t=>{if(t!==null&&typeof t!="string"&&!kr(t)&&!Xr(t)&&!jn(t))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${t} (${typeof t})`);return{encodeStream(e,r){if(t===null)return;if(kr(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=Bi.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(kr(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=Bi.resolve(e.stack,t)),typeof r=="bigint"&&(r=Number(r)),typeof r!="number")throw e.err(`Wrong length: ${r}`);return r}}},Dt={BITS:32,FULL_MASK:-1>>>0,len:t=>Math.ceil(t/32),create:t=>new Uint32Array(Dt.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(Dt.len(e)!==t.length)throw new Error(`wrong length=${t.length}. Expected: ${Dt.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)=>{Dt.checkLen(t,e);let{FULL_MASK:n,BITS:i}=Dt,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)=>`[${Dt.range(Dt.indices(t,e,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(t,e,r,n,i=!0)=>{Dt.chunkLen(e,r,n);let{FULL_MASK:o,BITS:s}=Dt,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 Dt.set(t,c,o>>>s-n<<s-n-r,i);if(c!==void 0&&!Dt.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(!Dt.set(t,h,o,i))return!1;return!(u!==void 0&&c!==u&&!Dt.set(t,u,o<<s-a%s,i))}},Bi={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}(${Bi.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}},Jy=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=e0(e)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=Dt.create(this.data.length),Dt.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:Dt.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 Bi.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: ${ve.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){let e=Dt.indices(this.bs,this.data.length,!0);if(e.length){let r=Dt.range(e).map(({pos:n,length:i})=>`(${n}/${i})[${ve.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: ${ve.encode(this.data.slice(this.pos))}`)}}err(e){return Bi.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(!Xr(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(zc(e,this.data.subarray(n,n+e.length)))return n}}},Xy=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=e0(this.viewBuf)}pushObj(e,r){return Bi.pushObj(this.stack,e,r)}writeView(e,r){if(this.finished)throw this.err("buffer: finished");if(!jn(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 Bi.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++)}}},Zy=t=>Uint8Array.from(t).reverse();function qE(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 FE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new Xy;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new Jy(e,r),i=t.decodeStream(n);return n.finish(),i}}}function Gt(t,e){if(!kr(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return FE({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 zt=t=>{let e=FE(t);return t.validate?Gt(e,t.validate):e},ol=t=>Yc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function kr(t){return Yc(t)&&ol(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||jn(t.size))}function Y8(){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(!Yc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var J8={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(!jn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function X8(t){if(!Yc(t))throw new Error("plain object expected");return{encode:e=>{if(!jn(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 Z8(t,e=!1){if(!jn(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 Q8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!ol(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 jE=t=>{if(!ol(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Ri={dict:Y8,numberBigint:J8,tsEnum:X8,decimal:Z8,match:Q8,reverse:jE};var t0=(t,e=!1,r=!1,n=!0)=>{if(!jn(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 zt({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:Zy(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 qE(s,8n*i,!!r),s}})};var WE=t0(32,!1);var Jc=t0(8,!0);var GE=t0(8,!0,!0);var eR=(t,e)=>zt({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}}),Pu=(t,e,r)=>{let n=t*8,i=2**(n-1),o=a=>{if(!jn(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(!jn(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 eR(t,{write:r.write,read:r.read,validate:e?o:c})},Be=Pu(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),zE=Pu(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),_o=Pu(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var r0=Pu(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var wn=Pu(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=Xr(t);return zt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?Zy(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?Zy(o):o},validate:i=>{if(!Xr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function YE(t,e){if(!kr(e))throw new Error(`prefix: invalid inner value ${e}`);return mn(Fe(t),jE(e))}var sl=(t,e=!1)=>Gt(mn(Fe(t,e),HE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var JE=(t,e={isLE:!1,with0x:!1})=>{let r=mn(Fe(t,e.isLE),ve),n=e.with0x;if(typeof n!="boolean")throw new Error(`hex/with0x: expected boolean, got ${typeof n}`);return n&&(r=mn(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 mn(t,e){if(!kr(t))throw new Error(`apply: invalid inner value ${t}`);if(!ol(e))throw new Error(`apply: invalid base value ${t}`);return zt({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 XE=(t,e=!1)=>{if(!Xr(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 zt({size:t.length,encodeStream:(r,n)=>{!!n!==e&&r.bytes(t)},decodeStream:r=>{let n=r.leftBytes>=t.length;return n&&(n=zc(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 ZE(t,e,r){if(!kr(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!kr(e))throw new Error(`flagged: wrong path=${t}`);return zt({encodeStream:(n,i)=>{typeof t=="string"?Bi.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=!!Bi.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function cl(t,e,r=!0){if(!kr(t))throw new Error(`magic: invalid inner value ${t}`);if(typeof r!="boolean")throw new Error(`magic: expected boolean, got ${typeof r}`);return zt({size:t.size,encodeStream:(n,i)=>t.encodeStream(n,e),decodeStream:n=>{let i=t.decodeStream(n);if(r&&typeof i!="object"&&i!==e||Xr(e)&&!zc(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 QE(t){let e=0;for(let r of t){if(r.size===void 0)return;if(!jn(r.size))throw new Error(`sizeof: wrong element size=${e}`);e+=r.size}return e}function vt(t){if(!Yc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!kr(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return zt({size:QE(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 ev(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(!kr(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return zt({size:QE(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 Yt(t,e){if(!kr(e))throw new Error(`array: invalid inner value ${e}`);let r=VE(typeof t=="string"?`../${t}`:t);return zt({size:typeof t=="number"&&e.size?t*e.size:void 0,encodeStream:(n,i)=>{let o=n;o.pushObj(i,s=>{Xr(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),Xr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(zc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),Xr(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(Xr(t))for(let s=0;;s++){if(zc(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 dl=To.ProjectivePoint,ul=To.CURVE.n,Ce=il.isBytes,Wn=il.concatBytes,at=il.equalBytes;var Xc=t=>OE(ke(t)),Ui=(...t)=>ke(ke(Wn(...t))),AM=Dr.utils.randomPrivateKey,fl=Dr.getPublicKey,n0=To.getPublicKey,tv=t=>t.r<ul/2n;function rv(t,e,r=!1){let n=To.sign(t,e);if(r&&!tv(n)){let i=new Uint8Array(32),o=0;for(;!tv(n);)if(i.set(Be.encode(o++)),n=To.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var i0=Dr.sign,Mu=Dr.utils.taggedHash,St;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(St||(St={}));function Io(t,e){let r=t.length;if(e===St.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return dl.fromHex(t),t}else if(e===St.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Dr.utils.lift_x(Dr.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function nv(t,e){let r=Dr.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=ul)throw new Error("tweak higher than curve order");return i}function iv(t,e=Uint8Array.of()){let r=Dr.utils,n=r.bytesToNumberBE(t),i=dl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,ul),s=r.pointToBytes(i),c=nv(s,e);return r.numberToBytesBE(r.mod(o+c,ul),32)}function Ku(t,e){let r=Dr.utils,n=nv(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(dl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var ll=ke(dl.BASE.toRawBytes(!1)),Zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},o0={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function $u(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 xt;(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"})(xt||(xt={}));function s0(t=6,e=!1){return zt({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 cv(t,e=4,r=!0){if(typeof t=="number")return t;if(Ce(t))try{let n=s0(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Ze=zt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(xt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(xt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(xt.OP_1-1+r);continue}}if(typeof r=="number"&&(r=s0().encode(BigInt(r))),!Ce(r))throw new Error(`Wrong Script OP=${r} (${typeof r})`);let n=r.length;n<xt.PUSHDATA1?t.byte(n):n<=255?(t.byte(xt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(xt.PUSHDATA2),t.bytes(r0.encode(n))):(t.byte(xt.PUSHDATA4),t.bytes(Be.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(xt.OP_0<r&&r<=xt.PUSHDATA4){let n;if(r<xt.PUSHDATA1)n=r;else if(r===xt.PUSHDATA1)n=wn.decodeStream(t);else if(r===xt.PUSHDATA2)n=r0.decodeStream(t);else if(r===xt.PUSHDATA4)n=Be.decodeStream(t);else throw new Error("Should be not possible");e.push(t.bytes(n))}else if(r===0)e.push(0);else if(xt.OP_1<=r&&r<=xt.OP_16)e.push(r-(xt.OP_1-1));else{let n=xt[r];if(n===void 0)throw new Error(`Unknown opcode=${r.toString(16)}`);e.push(n)}}return e}}),sv={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},Zc=zt({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(sv))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]=sv[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}}),Nr=mn(Zc,Ri.numberBigint),pr=Fe(Zc),Qc=Yt(Nr,pr),hl=t=>Yt(Zc,t),av=vt({txid:Fe(32,!0),index:Be,finalScriptSig:pr,sequence:Be}),Oi=vt({amount:Jc,script:pr}),tR=vt({version:_o,segwitFlag:XE(new Uint8Array([0,1])),inputs:hl(av),outputs:hl(Oi),witnesses:ZE("segwitFlag",Yt("inputs/length",Qc)),lockTime:Be});function rR(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Di=Gt(tR,rR),Ts=vt({version:_o,inputs:hl(av),outputs:hl(Oi),lockTime:Be});var a0=Gt(Fe(null),t=>Io(t,St.ecdsa)),pl=Gt(Fe(32),t=>Io(t,St.schnorr)),uv=Gt(Fe(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),yl=vt({fingerprint:zE,path:Yt(null,Be)}),lv=vt({hashes:Yt(Nr,Fe(32)),der:yl}),nR=Fe(78),iR=vt({pubKey:pl,leafHash:Fe(32)}),oR=vt({version:wn,internalKey:Fe(32),merklePath:Yt(null,Fe(32))}),ki=Gt(oR,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),sR=Yt(null,vt({depth:wn,version:wn,script:pr})),At=Fe(null),dv=Fe(20),Hu=Fe(32),gl={unsignedTx:[0,!1,Ts,[0],[0],!1],xpub:[1,nR,yl,[],[0,2],!1],txVersion:[2,!1,Be,[2],[2],!1],fallbackLocktime:[3,!1,Be,[],[2],!1],inputCount:[4,!1,Nr,[2],[2],!1],outputCount:[5,!1,Nr,[2],[2],!1],txModifiable:[6,!1,wn,[],[2],!1],version:[251,!1,Be,[],[0,2],!1],proprietary:[252,At,At,[],[0,2],!1]},Vu={nonWitnessUtxo:[0,!1,Di,[],[0,2],!1],witnessUtxo:[1,!1,Oi,[],[0,2],!1],partialSig:[2,a0,At,[],[0,2],!1],sighashType:[3,!1,Be,[],[0,2],!1],redeemScript:[4,!1,At,[],[0,2],!1],witnessScript:[5,!1,At,[],[0,2],!1],bip32Derivation:[6,a0,yl,[],[0,2],!1],finalScriptSig:[7,!1,At,[],[0,2],!1],finalScriptWitness:[8,!1,Qc,[],[0,2],!1],porCommitment:[9,!1,At,[],[0,2],!1],ripemd160:[10,dv,At,[],[0,2],!1],sha256:[11,Hu,At,[],[0,2],!1],hash160:[12,dv,At,[],[0,2],!1],hash256:[13,Hu,At,[],[0,2],!1],txid:[14,!1,Hu,[2],[2],!0],index:[15,!1,Be,[2],[2],!0],sequence:[16,!1,Be,[],[2],!0],requiredTimeLocktime:[17,!1,Be,[],[2],!1],requiredHeightLocktime:[18,!1,Be,[],[2],!1],tapKeySig:[19,!1,uv,[],[0,2],!1],tapScriptSig:[20,iR,uv,[],[0,2],!1],tapLeafScript:[21,ki,At,[],[0,2],!1],tapBip32Derivation:[22,Hu,lv,[],[0,2],!1],tapInternalKey:[23,!1,pl,[],[0,2],!1],tapMerkleRoot:[24,!1,Hu,[],[0,2],!1],proprietary:[252,At,At,[],[0,2],!1]},hv=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],pv=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],qu={redeemScript:[0,!1,At,[],[0,2],!1],witnessScript:[1,!1,At,[],[0,2],!1],bip32Derivation:[2,a0,yl,[],[0,2],!1],amount:[3,!1,GE,[2],[2],!0],script:[4,!1,At,[2],[2],!0],tapInternalKey:[5,!1,pl,[],[0,2],!1],tapTree:[6,!1,sR,[],[0,2],!1],tapBip32Derivation:[7,pl,lv,[],[0,2],!1],proprietary:[252,At,At,[],[0,2],!1]},yv=[],fv=Yt(Qy,vt({key:YE(Nr,vt({type:Nr,key:Fe(null)})),value:Fe(Nr)}));function u0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var DM=vt({type:Nr,key:Fe(null)});function d0(t){let e={};for(let r in t){let[n,i,o]=t[r];e[n]=[r,i,o]}return zt({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:He},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>$u(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)=>$u(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}fv.encodeStream(r,i)},decodeStream:r=>{let n=fv.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=${ve.encode(a)} value=${ve.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 ml=Gt(d0(Vu),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)Io(e,St.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)Io(e,St.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}),wl=Gt(d0(qu),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)Io(e,St.ecdsa);return t}),gv=Gt(d0(gl),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}),cR=vt({magic:cl(sl(new Uint8Array([255])),"psbt"),global:gv,inputs:Yt("global/unsignedTx/inputs/length",ml),outputs:Yt(null,wl)}),aR=vt({magic:cl(sl(new Uint8Array([255])),"psbt"),global:gv,inputs:Yt("global/inputCount",ml),outputs:Yt("global/outputCount",wl)}),kM=vt({magic:cl(sl(new Uint8Array([255])),"psbt"),items:Yt(null,mn(Yt(Qy,ev([JE(Nr),Fe(Zc)])),Ri.dict()))});function c0(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=u0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=u0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function f0(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}=u0(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 mv(t){let e=t&&t.global&&t.global.version||0;c0(e,gl,t.global);for(let s of t.inputs)c0(e,Vu,s);for(let s of t.outputs)c0(e,qu,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 bl(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(ve.decode(x[0])):x[0],typeof x[1]=="string"?d.decode(ve.decode(x[1])):x[1]]});let g={},y=(x,S,I)=>{if(g[x]===void 0){g[x]=[S,I];return}let A=ve.encode(d.encode(g[x][1])),O=ve.encode(d.encode(I));if(A!==O)throw new Error(`keyMap(${c}): same key=${x} oldVal=${A} newVal=${O}`)};for(let[x,S]of h){let I=ve.encode(u.encode(x));y(I,x,S)}for(let[x,S]of p){let I=ve.encode(u.encode(x));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${x}`);delete g[I]}else y(I,x,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(ve.decode(o[s]));else if(f&&s in e&&r&&r[s]!==void 0&&!at(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 l0=Gt(cR,mv),h0=Gt(aR,mv);var dR={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])||ve.encode(t[1])!=="4e73"))return{type:"p2a",script:Ze.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,ve.decode("4e73")]}};function Bo(t,e){try{return Io(t,e),!0}catch{return!1}}var fR={encode(t){if(!(t.length!==2||!Ce(t[0])||!Bo(t[0],St.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},lR={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},hR={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},pR={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},yR={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},gR={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},mR={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},wR={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}},bR={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=cv(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}},xR={encode(t){return{type:"unknown",script:Ze.encode(t)}},decode:t=>t.type==="unknown"?Ze.decode(t.script):void 0},ER=[dR,fR,lR,hR,pR,yR,gR,mR,wR,bR,xR],vR=mn(Ze,Ri.match(ER)),Qe=Gt(vR,t=>{if(t.type==="pk"&&!Bo(t.pubkey,St.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)||!Bo(t.pubkey,St.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(!Bo(r,St.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(!Bo(e,St.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 wv(t,e){if(!at(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 b0(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(!at(n.hash,Xc(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&&wv(n,r)}if(e){let n=Qe.decode(e);n.type==="wsh"&&r&&wv(n,r)}}var Ni=(t,e=Zr)=>{if(!Bo(t,St.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=Xc(t);return{type:"pkh",script:Qe.encode({type:"pkh",hash:r}),address:Qr(e).encode({type:"pkh",hash:r}),hash:r}};var _s=(t,e=Zr)=>{if(!Bo(t,St.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=Xc(t);return{type:"wpkh",script:Qe.encode({type:"wpkh",hash:r}),address:Qr(e).encode({type:"wpkh",hash:r}),hash:r}};function SR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=mn(Ze,Ri.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(at(s,ll))throw new Error("Unspendable taproot key in leaf script");if(at(s,e))throw new Error("Using P2TR with leaf script with same key as internal key is not supported")}}function xv(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 y0(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:y0(t.left,[t.right.hash,...e]),right:y0(t.right,[t.left.hash,...e])}}function g0(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[...g0(t.left),...g0(t.right)]}function m0(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&&!at(t.tapMerkleRoot,He))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?ve.decode(u):u;if(!Ce(d))throw new Error(`checkScript: wrong script type=${d}`);return SR(d,e,r,n),{type:"leaf",version:a,script:d,hash:Fu(d,a)}}if(t.length!==2&&(t=xv(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=m0(t[0],e,r,n),o=m0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return $u(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Mu("TapBranch",s,c)}}var w0=192,Fu=(t,e=w0)=>Mu("TapLeaf",new Uint8Array([e]),pr.encode(t));function Is(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"?ve.decode(t):t||ll;if(!Bo(o,St.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=y0(m0(e,o,n,i)),c=s.hash,[a,u]=Ku(o,c),d=g0(s).map(f=>({...f,controlBlock:ki.encode({version:(f.version||w0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Qe.encode({type:"tr",pubkey:a}),address:Qr(r).encode({type:"tr",pubkey:a}),tweakedPubkey:a,tapInternalKey:o,leaves:d,tapLeafScript:d.map(f=>[ki.decode(f.controlBlock),Wn(f.script,new Uint8Array([f.version||w0]))]),tapMerkleRoot:c}}else{let s=Ku(o,He)[0];return{type:"tr",script:Qe.encode({type:"tr",pubkey:s}),address:Qr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var Ev=KE(ke);function vv(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 p0(t,e,r=Zr){vv(t,e);let n=t===0?nl:As;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function bv(t,e){return Ev.encode(Wn(Uint8Array.from(e),t))}function Qr(t=Zr){return{encode(e){let{type:r}=e;if(r==="wpkh")return p0(0,e.hash,t);if(r==="wsh")return p0(0,e.hash,t);if(r==="tr")return p0(1,e.pubkey,t);if(r==="pkh")return bv(e.hash,[t.pubKeyHash]);if(r==="sh")return bv(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=nl.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=As.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=nl.fromWords(o);if(vv(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=Ev.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 xl=new Uint8Array(32),AR={amount:0xffffffffffffffffn,script:He},TR=t=>Math.ceil(t/4),_R=8,IR=2,Bs=0,S0=4294967295,BR=Ri.decimal(_R),Wu=(t,e)=>t===void 0?e:t;function vl(t){if(Array.isArray(t))return t.map(e=>vl(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,vl(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 Ro;(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"})(Ro||(Ro={}));function RR(t,e,r,n=He){return at(r,e)&&(t=iv(t,n),e=fl(t)),{privKey:t,pubKey:e}}function Rs(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 ju(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:Wu(t.sequence,S0),finalScriptSig:Wu(t.finalScriptSig,He)}}function x0(t){for(let e in t){let r=e;hv.includes(r)||delete t[r]}}var E0=vt({txid:Fe(32,!0),index:Be});function UR(t){if(typeof t!="number"||typeof Ro[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function Sv(t){let e=t&31;return{isAny:!!(t&je.ANYONECANPAY),isNone:e===je.NONE,isSingle:e===je.SINGLE}}function OR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:Wu(t.version,IR),lockTime:Wu(t.lockTime,0),PSBTVersion:Wu(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(Be.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 Av(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&&(!at(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=Us.fromRaw(Di.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=ve.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function El(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 Tv(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=ve.decode(o)),Ce(o)&&(o=Di.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=ve.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=S0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=bl(Vu,c,e,r,i),ml.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&b0(a&&a.script,c.redeemScript,c.witnessScript),c}function v0(t,e=!1){let r="legacy",n=je.ALL,i=El(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 Us=class t{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];let r=this.opts=OR(e);r.lockTime!==Bs&&(this.global.fallbackLocktime=r.lockTime),this.global.txVersion=r.version}static fromRaw(e,r={}){let n=Di.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=l0.decode(e)}catch(f){try{n=h0.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)=>Av({finalScriptSig:He,...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!==Bs&&(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=>Av(f0(e,Vu,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=>f0(e,qu,o)),i={...this.global};return e===0?(i.unsignedTx=Ts.decode(Ts.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(ju).map(o=>({...o,finalScriptSig:He})),outputs:this.outputs.map(Rs)})),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===Bs&&delete i.fallbackLocktime),this.opts.bip174jsCompat&&(r.length||r.push({}),n.length||n.push({})),(e===0?l0:h0).encode({global:i,inputs:r,outputs:n})}get lockTime(){let e=Bs,r=0,n=Bs,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!==Bs?n:this.global.fallbackLocktime||Bs}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(Rs);e+=4*Nr.encode(this.outputs.length).length;for(let n of r)e+=32+4*pr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Nr.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*pr.encode(n.finalScriptSig||He).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Qc.encode(n.finalScriptWitness).length);return e}get vsize(){return TR(this.weight)}toBytes(e=!1,r=!1){return Di.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(ju).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||He})),outputs:this.outputs.map(Rs),witnesses:this.inputs.map(n=>n.finalScriptWitness||[]),segwitFlag:r&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return ve.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return ve.encode(Ui(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return ve.encode(Ui(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),vl(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(Tv(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=pv)}this.inputs[e]=Tv(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),vl(this.outputs[e])}getOutputAddress(e,r=Zr){let n=this.getOutput(e);if(n.script)return Qr(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=ve.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=bl(qu,s,r,n,this.opts.allowUnknown),wl.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||b0(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=yv)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=Zr){return this.addOutput({script:Qe.encode(Qr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=El(n);if(!i)throw new Error("Empty input amount");e+=i.amount}let r=this.outputs.map(Rs);for(let n of r)e-=n.amount;return e}preimageLegacy(e,r,n){let{isAny:i,isNone:o,isSingle:s}=Sv(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 WE.encode(1n);r=Ze.encode(Ze.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(ju).map((d,f)=>({...d,finalScriptSig:f===e?r:He}));i?c=[c[e]]:(o||s)&&(c=c.map((d,f)=>({...d,sequence:f===e?d.sequence:0})));let a=this.outputs.map(Rs);o?a=[]:s&&(a=a.slice(0,e).fill(AR).concat([a[e]]));let u=Di.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Ui(u,_o.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=Sv(n),a=xl,u=xl,d=xl,f=this.inputs.map(ju),h=this.outputs.map(Rs);o||(a=Ui(...f.map(E0.encode))),!o&&!c&&!s&&(u=Ui(...f.map(g=>Be.encode(g.sequence)))),!c&&!s?d=Ui(...h.map(Oi.encode)):c&&e<h.length&&(d=Ui(Oi.encode(h[e])));let p=f[e];return Ui(_o.encode(this.version),a,u,Fe(32,!0).encode(p.txid),Be.encode(p.index),pr.encode(r),Jc.encode(i),Be.encode(p.sequence),d,Be.encode(this.lockTime),Be.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=[wn.encode(0),wn.encode(n),_o.encode(this.version),Be.encode(this.lockTime)],d=n===je.DEFAULT?je.ALL:n&3,f=n&je.ANYONECANPAY,h=this.inputs.map(ju),p=this.outputs.map(Rs);f!==je.ANYONECANPAY&&u.push(...[h.map(E0.encode),i.map(Jc.encode),r.map(pr.encode),h.map(y=>Be.encode(y.sequence))].map(y=>ke(Wn(...y)))),d===je.ALL&&u.push(ke(Wn(...p.map(Oi.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===je.ANYONECANPAY){let y=h[e];u.push(E0.encode(y),Jc.encode(i[e]),pr.encode(r[e]),Be.encode(y.sequence))}else u.push(Be.encode(e));return g&1&&u.push(ke(pr.encode(a||He))),d===je.SINGLE&&u.push(e<p.length?ke(Oi.encode(p[e])):xl),s&&u.push(Fu(s,c),wn.encode(0),_o.encode(o)),Mu("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=v0(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(!at(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(UR):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=El(o);if(s.txType==="taproot"){let d=this.inputs.map(El),f=d.map(x=>x.script),h=d.map(x=>x.amount),p=!1,g=fl(e),y=o.tapMerkleRoot||He;if(o.tapInternalKey){let{pubKey:x,privKey:S}=RR(e,g,o.tapInternalKey,y),[I,A]=Ku(o.tapInternalKey,y);if(at(I,x)){let O=this.preimageWitnessV1(r,f,c,h),T=Wn(i0(O,S,i),c!==je.DEFAULT?new Uint8Array([c]):He);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[x,S]of o.tapLeafScript){let I=S.subarray(0,-1),A=Ze.decode(I),O=S[S.length-1],T=Fu(I,O);if(A.findIndex($=>Ce($)&&at($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,I,O),j=Wn(i0(q,e,i),c!==je.DEFAULT?new Uint8Array([c]):He);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=n0(e),f=!1,h=Xc(d);for(let y of Ze.decode(s.lastScript))Ce(y)&&(at(y,d)||at(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=rv(p,e,this.opts.lowR);this.updateInput(r,{partialSig:[[d,Wn(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=v0(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)=>ki.encode(u[0]).length-ki.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=Fu(f,h),y=r.tapScriptSig.filter(S=>at(S[0].leafHash,g)),x=[];if(p.type==="tr_ms"){let S=p.m,I=p.pubkeys,A=0;for(let O of I){let T=y.findIndex(M=>at(M[0].pubKey,O));if(A===S||T===-1){x.push(He);continue}x.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=>at(A[0].pubKey,S));I!==-1&&x.push(y[I][1])}if(x.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Ze.decode(f);if(x=y.map(([{pubKey:I},A])=>{let O=S.findIndex(T=>Ce(T)&&at(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),!x.length)continue}else{let S=this.opts.customScripts;if(S)for(let I of S){if(!I.finalizeTaproot)continue;let A=Ze.decode(f),O=I.encode(A);if(O===void 0)continue;let T=I.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(ki.encode(u)),r.finalScriptSig=He,x0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=x.reverse().concat([f,ki.encode(u)]);break}if(!r.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}else throw new Error("finalize/taproot: unknown input");r.finalScriptSig=He,x0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=He,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=>at(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=Ze.encode([0,...d])}else if(n.last.type==="pk")i=Ze.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Ze.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=He,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=Ze.decode(i).map(a=>{if(a===0)return He;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=Ze.encode([Ze.encode([0,ke(n.lastScript)])]):n.type.startsWith("sh-")?s=Ze.encode([...Ze.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),x0(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?Ts.encode(this.global.unsignedTx):He,n=e.global.unsignedTx?Ts.encode(e.global.unsignedTx):He;if(!at(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=bl(gl,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 _v(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 x=Object.keys(d);c&&(x=x.filter(function(I){return d[I]!==void 0})),x.sort(),x.forEach(function(I){y(I)})}r+="}"}}}function Iv(t,e){return _v(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var A0;(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"})(A0||(A0={}));var{INVALID_DID:pt,METHOD_NOT_SUPPORTED:Sl,INTERNAL_ERROR:Al,INVALID_DID_DOCUMENT:qe,INVALID_DID_UPDATE:fe,INVALID_DID_URL:vK,INVALID_PREVIOUS_DID_PROOF:SK,INVALID_PUBLIC_KEY:AK,INVALID_PUBLIC_KEY_MULTIBASE:TK,INVALID_PUBLIC_KEY_LENGTH:_K,INVALID_PUBLIC_KEY_TYPE:IK,INVALID_SIGNATURE:BK,NOT_FOUND:Bv,PROOF_VERIFICATION_ERROR:Ci,PROOF_GENERATION_ERROR:Oo,PROOF_SERIALIZATION_ERROR:Rv,PROOF_PARSING_ERROR:RK,VERIFICATION_METHOD_ERROR:Tl,LATE_PUBLISHING_ERROR:_l,INVALID_SIDECAR_DATA:UK,MISSING_UPDATE_DATA:OK,MISSING_RESOLUTION_OPTIONS:DK,INVALID_OPTIONS:Gu}=A0,kt=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)}},be=class extends kt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var ut=class extends kt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},it=class extends kt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},le=class extends kt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var Ve=class extends kt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},Uo=class extends kt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},bn=class extends kt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},xn=class extends kt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},Gn=class extends kt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},Os=class extends kt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},En=class extends kt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var ea=class extends kt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var DR=new Set(["jcs"]),kR=new Set(["hex","base58","base64urlnopad"]);function T0(t){let e=t.toLowerCase();if(!DR.has(e))throw new ea(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function _0(t){let e=t.toLowerCase();if(!kR.has(e))throw new ea(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function Kt(t,e="jcs"){switch(T0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return Iv(n)}default:throw new ea(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function Do(t){return ke(t)}function en(t,e="base64urlnopad"){switch(_0(e)){case"hex":return ve.encode(t);case"base58":return rl.encode(t);case"base64urlnopad":return Gc.encode(t)}}function ta(t,e="base64urlnopad"){switch(_0(e)){case"hex":return ve.decode(t);case"base58":return rl.decode(t);case"base64urlnopad":return Gc.decode(t)}}function ko(t,e="jcs"){return Do(Kt(t,T0(e)))}function zn(t,e){let r=T0(e?.algorithm??"jcs"),n=_0(e?.encoding??"base64urlnopad");return en(Do(Kt(t,r)),n)}l();l();var I0={};Au(I0,{JsonPatchError:()=>dt,_areEquals:()=>Ju,applyOperation:()=>Ds,applyPatch:()=>kl,applyReducer:()=>MR,deepClone:()=>LR,getValueByPointer:()=>Ol,validate:()=>Ov,validator:()=>Dl});l();l();var NR=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)}}(),CR=Object.prototype.hasOwnProperty;function Bl(t,e){return CR.call(t,e)}function Rl(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 $t(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Ul(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 Yn(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function zu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Il(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Il(t[e]))return!0}else if(typeof t=="object"){for(var n=Rl(t),i=n.length,o=0;o<i;o++)if(Il(t[n[o]]))return!0}}return!1}function Uv(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 Yu=function(t){NR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,Uv(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=Uv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var dt=Yu,LR=$t,ra={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=Ol(r,this.path);n&&(n=$t(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=Ol(r,this.from);return Ds(r,{op:"add",path:this.path,value:$t(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Ju(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},PR={add:function(t,e,r){return Ul(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:ra.move,copy:ra.copy,test:ra.test,_get:ra._get};function Ol(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):Dl(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=Ol(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Ju(t,e.value),s.test===!1)throw new dt("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 dt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{n||(t=$t(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=Dl;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=zu(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&&!Ul(p))throw new dt("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);Ul(p)&&(p=~~p)}if(d>=f){if(r&&e.op==="add"&&p>u.length)throw new dt("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=PR[e.op].call(e,u,p,t);if(s.test===!1)throw new dt("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(d>=f){var s=ra[e.op].call(e,u,p,t);if(s.test===!1)throw new dt("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new dt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function kl(t,e,r,n,i){if(n===void 0&&(n=!0),i===void 0&&(i=!0),r&&!Array.isArray(e))throw new dt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=$t(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 MR(t,e,r){var n=Ds(t,e);if(n.test===!1)throw new dt("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Dl(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new dt("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(ra[t.op]){if(typeof t.path!="string")throw new dt("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new dt('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 dt("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 dt("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")&&Il(t.value))throw new dt("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 dt("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 dt("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=Ov([s],r);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new dt("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new dt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Ov(t,e,r){try{if(!Array.isArray(t))throw new dt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)kl($t(e),$t(t),r||!0);else{r=r||Dl;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof dt)return i;throw i}}function Ju(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(!Ju(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],!Ju(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var O0={};Au(O0,{compare:()=>WR,generate:()=>B0,observe:()=>jR,unobserve:()=>FR});l();var R0=new WeakMap,KR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),$R=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function HR(t){return R0.get(t)}function VR(t,e){return t.observers.get(e)}function qR(t,e){t.observers.delete(e.callback)}function FR(t,e){e.unobserve()}function jR(t,e){var r=[],n,i=HR(t);if(!i)i=new KR(t),R0.set(t,i);else{var o=VR(i,e);n=o&&o.observer}if(n)return n;if(n={},i.value=$t(t),e){n.callback=e,n.next=null;var s=function(){B0(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(){B0(n),clearTimeout(n.next),qR(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 $R(e,n)),n}function B0(t,e){e===void 0&&(e=!1);var r=R0.get(t.object);U0(r.value,t.object,t.patches,"",e),t.patches.length&&kl(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function U0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Rl(e),s=Rl(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)?U0(f,h,r,n+"/"+Yn(d),i):f!==h&&(c=!0,i&&r.push({op:"test",path:n+"/"+Yn(d),value:$t(f)}),r.push({op:"replace",path:n+"/"+Yn(d),value:$t(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+Yn(d),value:$t(f)}),r.push({op:"remove",path:n+"/"+Yn(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+"/"+Yn(d),value:$t(e[d])})}}}function WR(t,e,r){r===void 0&&(r=!1);var n=[];return U0(t,e,n,"",r),n}var Dv=Object.assign({},I0,O0,{JsonPatchError:Yu,deepClone:$t,escapePathComponent:Yn,unescapePathComponent:zu});var{applyPatch:GR,compare:zR,deepClone:YR}=Dv,JR=new Set(["__proto__","constructor","prototype"]);function kv(t){return t.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")).find(e=>JR.has(e))}var XR=new Set(["add","remove","replace","move","copy","test"]),ZR=new Set(["add","replace","test"]);function QR(t){if(!(t instanceof Error))return"";let{index:e,operation:r}=t;return`${typeof e=="number"&&r&&typeof r=="object"?` at operation ${e} (${String(r.op)} ${String(r.path)})`:""}: ${t.message}`}var na=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.strict??!1,s=n.clone??YR,c=i?e:s(e),a=this.validateOperations(r,o);if(a)throw new be(`Invalid JSON Patch operations: ${a.message}`,"JSON_PATCH_APPLY_ERROR",{error:a});let u;try{u=GR(c,r,o,i)}catch(d){throw new be(`JSON Patch application failed${QR(d)}`,"JSON_PATCH_APPLY_ERROR",{error:d})}if(u.newDocument===void 0)throw new be("JSON Patch application failed: no document","JSON_PATCH_APPLY_ERROR",{result:u});return u.newDocument}static diff(e,r,n=""){let i=zR(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,r=!1){if(!Array.isArray(e))return new be("Operations must be an array","JSON_PATCH_VALIDATION_ERROR");for(let n of e){if(!n||typeof n!="object")return new be("Operation must be an object","JSON_PATCH_VALIDATION_ERROR");if(typeof n.op!="string")return new be("Operation.op must be a string","JSON_PATCH_VALIDATION_ERROR");if(typeof n.path!="string")return new be("Operation.path must be a string","JSON_PATCH_VALIDATION_ERROR");if(r&&!XR.has(n.op))return new be(`Operation.op is not an RFC 6902 operation: ${n.op}`,"JSON_PATCH_VALIDATION_ERROR");if(r&&ZR.has(n.op)&&n.value===void 0)return new be(`Operation.value is required for op=${n.op}`,"JSON_PATCH_VALIDATION_ERROR");let i=kv(n.path);if(i)return new be(`Operation.path traverses prototype machinery: ${i}`,"JSON_PATCH_VALIDATION_ERROR");if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")return new be(`Operation.from must be a string for op=${n.op}`,"JSON_PATCH_VALIDATION_ERROR");if(typeof n.from=="string"){let o=kv(n.from);if(o)return new be(`Operation.from traverses prototype machinery: ${o}`,"JSON_PATCH_VALIDATION_ERROR")}}return null}};l();var tn;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(tn||(tn={}));var Nl;(function(t){t.k="k",t.x="x"})(Nl||(Nl={}));var ia;(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"})(ia||(ia={}));l();var Li=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new be(`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 be(`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],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||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 D0(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 be("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)||D0(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&&D0(i,o,c)}return i}return n};return r(e)}static cloneInternal(e,r={},n=new WeakMap,i=0){if(i>1024)throw new be("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 be("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))D0(s,c,this.cloneInternal(e[c],r,n,i+1));return s}};l();var Jt=class extends be{constructor(e,r="BeaconError",n){super(e,r,n)}},k0=class extends be{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},N0=class extends be{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},C0=class extends be{constructor(e,r="CASBeaconError",n){super(e,r,n)}},oa=class extends be{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 a6={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function No(t){switch(t){case"bitcoin":return Zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return o0;case"regtest":return a6;default:throw new Error(`Unknown network "${t}"`)}}l();var sa=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 P0="0000000000000000000000000000000000000000000000000000000000000000",M0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var K0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(K0||(K0={}));var Cl=new sa(5);var Lv=160,Pv=155,Mv=240,Kv={p2pkh:Mv,p2wpkh:Pv,p2tr:Lv},$0={p2pkh:34,p2wpkh:31,p2tr:43},H0={p2pkh:546,p2wpkh:294,p2tr:330};function V0(t,e){return Kv[t]-$0[t]+$0[e]}function q0(t,e){let r=Qr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new Jt(`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 $v(t,e,r){return t==="p2pkh"?Ni(e,r).address:t==="p2wpkh"?_s(e,r).address:Is(e.slice(1,33),void 0,r).address}function F0(t,e,r){if(!r||r===t)return t;try{Qr(e).decode(r)}catch{throw new Jt(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function Hv(t,e){try{return q0(t,e)}catch{return"p2tr"}}function j0(t){return Ze.encode(["RETURN",t])}var Ll=546;function f6(t){return t.status.confirmed===!0}function l6(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 Vv(t,e){if(!t.length)throw new Jt("No UTXOs found, please fund address!","UNFUNDED_BEACON_ADDRESS",{address:e});let r=t.filter(f6),n=r.filter(i=>i.value>Ll);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 ${Ll}-sat dust limit`;throw new Jt(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:Ll})}return[...n].sort(l6)[0]}async function qv(t,e){let r=await e.rest.address.getUtxos(t),n=Vv(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:Br(i)}}async function h6(t){let e=t.feeEstimator??Cl,{utxo:r,prevTxBytes:n}=await qv(t.beaconAddress,t.bitcoin),i=F0(t.beaconAddress,t.network,t.changeAddress),o=Qe.encode(Qr(t.network).decode(t.beaconAddress)),s=Hv(i,t.network),c=await e.estimateFee(V0("p2tr",s));if(BigInt(r.value)<=c)throw new Jt(`UTXO value (${r.value}) insufficient to cover fee (${c}).`,"INSUFFICIENT_FUNDS",{address:t.beaconAddress,valueSats:r.value,feeSats:c});let a=new Us({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(H0[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:j0(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 p6(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=Ro.ALL,d=t.preimageLegacy(e,i,u),f=n.sign(d,"ecdsa"),h=ht(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 Jt(`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=Ro.ALL,h=t.preimageWitnessV0(e,d,f,o),p=n.sign(h,"ecdsa"),g=ht(p,new Uint8Array([f]));return t.updateInput(e,{partialSig:[[s,g]]},!0),t.finalize(),t.hex}let c=t.preimageWitnessV1(e,[i],Ro.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Pi=class{service;did;constructor(e,r){this.service=e,this.did=r}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??Cl,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await qv(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=q0(e.beaconAddress,r),o=F0(e.beaconAddress,r,e.changeAddress),s=$v(i,n,r);if(s!==e.beaconAddress)throw new Jt(`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=Hv(o,r),a=await e.feeEstimator.estimateFee(V0(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new Jt(`UTXO value (${e.utxo.value}) insufficient to cover fee (${a}).`,"INSUFFICIENT_FUNDS",{address:e.beaconAddress,valueSats:e.utxo.value,feeSats:a});let d=new Us({allowUnknownOutputs:!0}),f;if(i==="p2pkh")f=Ni(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes});else if(i==="p2wpkh")f=_s(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=Is(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(H0[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:j0(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 p6(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var Xu=class extends Pi{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=en(ta(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=zn(e),c={[o]:s},a=Do(Kt(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 Zu=class extends Pi{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=Do(Kt(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var y6=new Uint8Array(32),W0=1n<<BigInt(256),Fv=(()=>{let t=new Array(257),e=W0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function Qu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Jn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function _e(t,e,r=""){let n=Qu(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 Pl(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Jn(t.outputLen),Jn(t.blockLen)}function ca(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 Wv(t,e){_e(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 Ml(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function vn(t,e){return t<<32-e|t>>>e}var Gv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",g6=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Cs(t){if(_e(t),Gv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=g6[t[r]];return e}var Mi={_0:48,_9:57,A:65,F:70,a:97,f:102};function jv(t){if(t>=Mi._0&&t<=Mi._9)return t-Mi._0;if(t>=Mi.A&&t<=Mi.F)return t-(Mi.A-10);if(t>=Mi.a&&t<=Mi.f)return t-(Mi.a-10)}function Ls(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Gv)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=jv(t.charCodeAt(o)),c=jv(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 yr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];_e(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 zv(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 Yv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var z0=BigInt(0),G0=BigInt(1);function ed(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Jv(t){if(typeof t=="bigint"){if(!Kl(t))throw new Error("positive bigint expected, got "+t)}else Jn(t);return t}function td(t){let e=Jv(t).toString(16);return e.length&1?"0"+e:e}function Xv(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?z0:BigInt("0x"+t)}function Co(t){return Xv(Cs(t))}function Y0(t){return Xv(Cs(m6(_e(t)).reverse()))}function $l(t,e){Jn(e),t=Jv(t);let r=Ls(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function J0(t,e){return $l(t,e).reverse()}function aa(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 m6(t){return Uint8Array.from(t)}function Zv(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 Kl=t=>typeof t=="bigint"&&z0<=t;function w6(t,e,r){return Kl(t)&&Kl(e)&&Kl(r)&&e<=t&&t<r}function Qv(t,e,r,n){if(!w6(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function X0(t){let e;for(e=0;t>z0;t>>=G0,e+=1);return e}var rd=t=>(G0<<BigInt(t))-G0;function e1(t,e,r){if(Jn(t,"hashLen"),Jn(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,yr(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 I=a.slice();S.push(I),x+=a.length}return yr(...S)};return(x,S)=>{f(),p(x);let I;for(;!(I=S(g()));)p();return f(),I}}function nd(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 Z0(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 Q0(t){return t.length===32}function Hl(t){if(!Q0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function yt(...t){return ke(ht(...t))}function id(t){Hl(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function eg(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 tg(t){Hl(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function rg(t,e){return!Q0(t)||!Q0(e)?!1:aa(t,e)}function ua(t){return Hl(t),Gc.encode(t)}function Xn(t){let e=Gc.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var t1;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(t1||(t1={}));l();l();var Lo=256;function da(t,e){return Number(t>>BigInt(e)&1n)}var r1=(()=>{let t=new Array(Lo+1),e=new Uint8Array(32);for(let r=0;r<=Lo;r++)e=yt(e,e),t[r]=e;return t})();function Vl(t,e){if(t.length===0)return r1[e];if(e===0)return t[0].leaf;let r=Lo-e,n=[],i=[];for(let o of t)(da(o.index,r)===0?n:i).push(o);return yt(Vl(n,e-1),Vl(i,e-1))}function n1(t){return Vl(t,Lo)}function i1(t,e){let r=0n,n=[];for(let i=1;i<=Lo;i++){let o=Lo-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(da(c.index,u)!==da(e,u)){a=!1;break}a&&da(c.index,o)!==da(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(Vl(s,i-1))}return{collapsed:r,hashes:n}}function o1(t,e,r,n,i){let o=n,s=0;for(let c=0;c<Lo;c++){let a=Lo-1-c,u;if((t>>BigInt(a)&1n)===1n)u=r1[c];else{if(s>=e.length)return!1;u=e[s++]}o=da(r,a)===1?yt(u,o):yt(o,u)}return s===e.length&&rg(o,i)}l();var b6=new TextEncoder;function ql(t){return id(yt(b6.encode(t)))}function s1(t,e){return yt(yt(t),yt(e))}function c1(t){return yt(yt(t))}l();function a1(t,e,r){let n={id:ua(t),collapsed:ua(eg(e.collapsed)),hashes:e.hashes.map(i=>ua(i))};return r?.nonce&&(n.nonce=ua(r.nonce)),r?.updateId&&(n.updateId=ua(r.updateId)),n}function x6(t){let e={rootHash:Xn(t.id),collapsed:id(Xn(t.collapsed)),hashes:t.hashes.map(r=>Xn(r))};return t.nonce&&(e.nonce=Xn(t.nonce)),t.updateId&&(e.updateId=Xn(t.updateId)),e}function u1(t,e,r){let{rootHash:n,collapsed:i,hashes:o}=x6(t);return o1(i,o,e,r,n)}l();var Fl=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=ql(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?s1(n.nonce,n.signedUpdate):c1(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=n1(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=i1(this.#n,r),o=n.signedUpdate!==void 0?yt(n.signedUpdate):void 0;return a1(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var od=class extends Pi{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 oa("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=ql(o),u=Xn(c.nonce),d=c.updateId?yt(yt(u),Xn(c.updateId)):yt(yt(u));if(!u1(c,a,d))throw new oa("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=tg(Xn(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(Kt(e)),c=Rr(32),a=new Fl;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 Ms=class{static establish(e,r){switch(e.type){case"SingletonBeacon":return new Zu(e,r);case"CASBeacon":return new Xu(e,r);case"SMTBeacon":return new od(e,r);default:throw new be("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var $i;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})($i||($i={}));l();var gt={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};l();var xe=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}};xe.METHOD_PATTERN="([a-z0-9]+)";xe.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})";xe.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${xe.PCT_ENCODED_PATTERN})`;xe.METHOD_ID_PATTERN=`((?:${xe.ID_CHAR_PATTERN}*:)*(${xe.ID_CHAR_PATTERN}+))`;xe.PATH_PATTERN="(/[^#?]*)?";xe.QUERY_PATTERN="([?][^#]*)?";xe.FRAGMENT_PATTERN="(#.*)?";xe.DID_URI_PATTERN=new RegExp(`^did:(?<method>${xe.METHOD_PATTERN}):(?<id>${xe.METHOD_ID_PATTERN})(?<path>${xe.PATH_PATTERN})(?<query>${xe.QUERY_PATTERN})(?<fragment>${xe.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=Kn(f1(),1);l();l();l();l();var ZH=new Uint8Array(0);function l1(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 fa(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 T6(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,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<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 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(x+(I-q)),$=x;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 _6=T6,I6=_6,h1=I6;var sg=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")}},cg=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 p1(this,e)}},ag=class{decoders;constructor(e){this.decoders=e}or(e){return p1(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 p1(t,e){return new ag({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var ug=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 sg(e,r,n),this.decoder=new cg(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function y1({name:t,prefix:e,encode:r,decode:n}){return new ug(t,e,r,n)}function dg({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=h1(r,t);return y1({prefix:e,name:t,encode:n,decode:o=>fa(i(o))})}function B6(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 R6(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 sr({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return y1({prefix:e,name:t,encode(i){return R6(i,n,r)},decode(i){return B6(i,n,r,t)}})}var sd=sr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),cV=sr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),aV=sr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),uV=sr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),dV=sr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),fV=sr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),lV=sr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),hV=sr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),fg=sr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var gr=dg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),mV=dg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var EV=sr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),vV=sr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zn=sr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),SV=sr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function g1(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function m1(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function la(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var cd=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())})},w1=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)}},Wl=new TextEncoder,Ks=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(!m1(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 gr.baseDecode(this.data).buffer;case"Base64Url":return Zn.baseDecode(this.data).buffer;case"BufferSource":{if(la(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return g1(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 cd(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 fg.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 gr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return gr.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=Wl.encode(e);return Zn.baseEncode(r)}case"String":{let e=Wl.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 cd(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=w1(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=Ks.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Ks.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return cd(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 Ks.decode(this.data);case"Base64Url":{let e=Zn.baseDecode(this.data);return Ks.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Ks.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return cd(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=w1(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+=Ks.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+=Ks.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 fg.baseDecode(this.data);case"Base58Btc":return gr.baseDecode(this.data);case"Base64Url":return Zn.baseDecode(this.data);case"BufferSource":{let e=la(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 Wl.encode(e)}case"String":return Wl.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return cd(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 ad;(function(t){t.Debug="debug",t.Silent="silent"})(ad||(ad={}));var lg=class{constructor(){this.logLevel=ad.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==ad.Silent&&console.info(e)}error(e){this.logLevel!==ad.Silent&&console.error(e)}},U6=new lg;typeof window<"u"&&(window.web5logger=U6);l();l();l();l();var Hi={};Au(Hi,{decode:()=>ha,encodeTo:()=>$s,encodingLength:()=>Hs});l();l();var O6=E1,b1=128,D6=127,k6=~D6,N6=Math.pow(2,31);function E1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=N6;)e[r++]=t&255|b1,t/=128;for(;t&k6;)e[r++]=t&255|b1,t>>>=7;return e[r]=t|0,E1.bytes=r-n+1,e}var C6=hg,L6=128,x1=127;function hg(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw hg.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&x1)<<i:(s&x1)*Math.pow(2,i),i+=7}while(s>=L6);return hg.bytes=o-n,r}var P6=Math.pow(2,7),M6=Math.pow(2,14),K6=Math.pow(2,21),$6=Math.pow(2,28),H6=Math.pow(2,35),V6=Math.pow(2,42),q6=Math.pow(2,49),F6=Math.pow(2,56),j6=Math.pow(2,63),W6=function(t){return t<P6?1:t<M6?2:t<K6?3:t<$6?4:t<H6?5:t<V6?6:t<q6?7:t<F6?8:t<j6?9:10},G6={encode:O6,decode:C6,encodingLength:W6},z6=G6,ud=z6;function ha(t,e=0){return[ud.decode(t,e),ud.decode.bytes]}function $s(t,e,r=0){return ud.encode(t,e,r),e}function Hs(t){return ud.encodingLength(t)}function pg(t,e){let r=e.byteLength,n=Hs(t),i=n+Hs(r),o=new Uint8Array(i+r);return $s(t,o,0),$s(r,o,n),o.set(e,i),new pa(t,r,e,o)}function v1(t){let e=fa(t),[r,n]=ha(e),[i,o]=ha(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new pa(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&&l1(t.bytes,r.bytes)}}var pa=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function A1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return J6(r,gg(t),e??gr.encoder);default:return X6(r,gg(t),e??sd.encoder)}}var T1=new WeakMap;function gg(t){let e=T1.get(t);if(e==null){let r=new Map;return T1.set(t,r),r}return e}var mg=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!==dd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==Z6)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=pg(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 A1(this,e)}toJSON(){return{"/":A1(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??_1(n,i,o.bytes))}else if(r[Q6]===!0){let{version:n,multihash:i,code:o}=r,s=v1(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!==dd)throw new Error(`Version 0 CID must use dag-pb (code: ${dd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=_1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,dd,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=fa(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 pa(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]=ha(e.subarray(r));return r+=h,f},i=n(),o=dd;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]=Y6(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 gg(o).set(n,e),o}};function Y6(t,e){switch(t[0]){case"Q":{let r=e??gr;return[gr.prefix,r.decode(`${gr.prefix}${t}`)]}case gr.prefix:{let r=e??gr;return[gr.prefix,r.decode(t)]}case sd.prefix:{let r=e??sd;return[sd.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 J6(t,e,r){let{prefix:n}=r;if(n!==gr.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 X6(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 dd=112,Z6=18;function _1(t,e,r){let n=Hs(t),i=n+Hs(e),o=new Uint8Array(i+r.byteLength);return $s(t,o,0),$s(e,o,n),o.set(r,i),o}var Q6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var Xt=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=Hi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Hi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Hi.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]=Hi.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}}};Xt.codeToName=new Map;Xt.nameToCode=new Map;Xt.registerCodec({code:237,name:"ed25519-pub"});Xt.registerCodec({code:4864,name:"ed25519-priv"});Xt.registerCodec({code:236,name:"x25519-pub"});Xt.registerCodec({code:4866,name:"x25519-priv"});Xt.registerCodec({code:231,name:"secp256k1-pub"});Xt.registerCodec({code:4865,name:"secp256k1-priv"});l();function wg(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&wg(t[e])})}l();var sO=Kn(dm(),1),rc=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 xh=class{constructor(){this.store=new Map}clear(){return rc(this,void 0,void 0,function*(){this.store.clear()})}close(){return rc(this,void 0,void 0,function*(){})}delete(e){return rc(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return rc(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return rc(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return rc(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return rc(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var S4=Kn(vw(),1);var A4=Kn(vw(),1);l();l();l();l();l();function T4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Sw(t,...e){if(!T4(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 Aw(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 kT(t,e){Sw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var $a=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var Qh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e;var Yj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function _4(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Tw(t){return typeof t=="string"&&(t=_4(t)),Sw(t),t}var Zh=class{clone(){return this._cloneInto()}},Jj={}.toString;function NT(t){let e=n=>t().update(Tw(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function CT(t=32){if($a&&typeof $a.getRandomValues=="function")return $a.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function I4(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 LT=(t,e,r)=>t&e^~t&r,PT=(t,e,r)=>t&e^t&r^e&r,ep=class extends Zh{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=Qh(this.buffer)}update(e){Aw(this);let{view:r,buffer:n,blockLen:i}=this;e=Tw(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=Qh(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){Aw(this),kT(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;I4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Qh(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 B4=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),_w=class extends ep{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+LT(c,a,u)+B4[f]+Jo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+PT(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 Xo=NT(()=>new _w);var R4=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())})},Ha=class{static digest(e){return R4(this,arguments,void 0,function*({data:r}){return Xo(r)})}};l();var ai=class{};var U4=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())})},tp=class extends ai{digest(e){return U4(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield Ha.digest({data:n})}})}};l();l();l();l();l();l();function MT(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function O4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Iw(t,...e){if(!O4(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 KT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");MT(t.outputLen),MT(t.blockLen)}function Va(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 $T(t,e){Iw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var rp=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function HT(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var np=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Rn=(t,e)=>t<<32-e|t>>>e,D4=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!D4)throw new Error("Non little-endian hardware is not supported");function Bw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function qd(t){if(typeof t=="string"&&(t=Bw(t)),!HT(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function ip(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!HT(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 qa=class{clone(){return this._cloneInto()}},EW={}.toString;function op(t){let e=n=>t().update(qd(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Fd(t=32){if(rp&&typeof rp.getRandomValues=="function")return rp.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function k4(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 Fa=class extends qa{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=np(this.buffer)}update(e){Va(this);let{view:r,buffer:n,blockLen:i}=this;e=qd(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=np(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){Va(this),$T(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;k4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=np(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 N4=(t,e,r)=>t&e^~t&r,C4=(t,e,r)=>t&e^t&r^e&r,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]),Zo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Qo=new Uint32Array(64),Rw=class extends Fa{constructor(){super(64,32,8,!1),this.A=Zo[0]|0,this.B=Zo[1]|0,this.C=Zo[2]|0,this.D=Zo[3]|0,this.E=Zo[4]|0,this.F=Zo[5]|0,this.G=Zo[6]|0,this.H=Zo[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)Qo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Qo[f-15],p=Qo[f-2],g=Rn(h,7)^Rn(h,18)^h>>>3,y=Rn(p,17)^Rn(p,19)^p>>>10;Qo[f]=y+Qo[f-7]+g+Qo[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=Rn(c,6)^Rn(c,11)^Rn(c,25),p=d+h+N4(c,a,u)+L4[f]+Qo[f]|0,y=(Rn(n,2)^Rn(n,13)^Rn(n,22))+C4(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(){Qo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var sp=op(()=>new Rw);l();var ap={};Au(ap,{bitGet:()=>q4,bitLen:()=>V4,bitMask:()=>jd,bitSet:()=>F4,bytesToHex:()=>eo,bytesToNumberBE:()=>to,bytesToNumberLE:()=>On,concatBytes:()=>no,createHmacDrbg:()=>Dw,ensureBytes:()=>Ge,equalBytes:()=>$4,hexToBytes:()=>pc,hexToNumber:()=>Ow,isBytes:()=>Un,numberToBytesBE:()=>wr,numberToBytesLE:()=>ro,numberToHexUnpadded:()=>jT,numberToVarBytesBE:()=>K4,utf8ToBytes:()=>H4,validateObject:()=>cn});l();var FT=BigInt(0),cp=BigInt(1),P4=BigInt(2);function Un(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var M4=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function eo(t){if(!Un(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=M4[t[r]];return e}function jT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Ow(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Qi={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function VT(t){if(t>=Qi._0&&t<=Qi._9)return t-Qi._0;if(t>=Qi._A&&t<=Qi._F)return t-(Qi._A-10);if(t>=Qi._a&&t<=Qi._f)return t-(Qi._a-10)}function pc(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=VT(t.charCodeAt(o)),c=VT(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 to(t){return Ow(eo(t))}function On(t){if(!Un(t))throw new Error("Uint8Array expected");return Ow(eo(Uint8Array.from(t).reverse()))}function wr(t,e){return pc(t.toString(16).padStart(e*2,"0"))}function ro(t,e){return wr(t,e).reverse()}function K4(t){return pc(jT(t))}function Ge(t,e,r){let n;if(typeof e=="string")try{n=pc(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(Un(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 no(...t){let e=0;for(let i=0;i<t.length;i++){let o=t[i];if(!Un(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 $4(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 H4(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function V4(t){let e;for(e=0;t>FT;t>>=cp,e+=1);return e}function q4(t,e){return t>>BigInt(e)&cp}var F4=(t,e,r)=>t|(r?cp:FT)<<BigInt(e),jd=t=>(P4<<BigInt(t-1))-cp,Uw=t=>new Uint8Array(t),qT=t=>Uint8Array.from(t);function Dw(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=Uw(t),i=Uw(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=Uw())=>{i=c(qT([0]),f),n=c(),f.length!==0&&(i=c(qT([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 no(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var j4={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"||Un(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 cn(t,e,r={}){let n=(i,o,s)=>{let c=j4[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 It=BigInt(0),et=BigInt(1),yc=BigInt(2),W4=BigInt(3),kw=BigInt(4),WT=BigInt(5),GT=BigInt(8),G4=BigInt(9),z4=BigInt(16);function Re(t,e){let r=t%e;return r>=It?r:e+r}function Nw(t,e,r){if(r<=It||e<It)throw new Error("Expected power/modulo > 0");if(r===et)return It;let n=et;for(;e>It;)e&et&&(n=n*t%r),t=t*t%r,e>>=et;return n}function ze(t,e,r){let n=t;for(;e-- >It;)n*=n,n%=r;return n}function up(t,e){if(t===It||e<=It)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Re(t,e),n=e,i=It,o=et,s=et,c=It;for(;r!==It;){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 Re(i,e)}function Y4(t){let e=(t-et)/yc,r,n,i;for(r=t-et,n=0;r%yc===It;r/=yc,n++);for(i=yc;i<t&&Nw(i,e,t)!==t-et;i++);if(n===1){let s=(t+et)/kw;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)/yc;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 J4(t){if(t%kw===W4){let e=(t+et)/kw;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%GT===WT){let e=(t-WT)/GT;return function(n,i){let o=n.mul(i,yc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,yc),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%z4,Y4(t)}var zT=(t,e)=>(Re(t,e)&et)===et,X4=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Cw(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=X4.reduce((n,i)=>(n[i]="function",n),e);return cn(t,r)}function Z4(t,e,r){if(r<It)throw new Error("Expected power > 0");if(r===It)return t.ONE;if(r===et)return e;let n=t.ONE,i=e;for(;r>It;)r&et&&(n=t.mul(n,i)),i=t.sqr(i),r>>=et;return n}function Q4(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 Lw(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function ja(t,e,r=!1,n={}){if(t<=It)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=Lw(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=J4(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:jd(i),ZERO:It,ONE:et,create:a=>Re(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return It<=a&&a<t},is0:a=>a===It,isOdd:a=>(a&et)===et,neg:a=>Re(-a,t),eql:(a,u)=>a===u,sqr:a=>Re(a*a,t),add:(a,u)=>Re(a+u,t),sub:(a,u)=>Re(a-u,t),mul:(a,u)=>Re(a*u,t),pow:(a,u)=>Z4(c,a,u),div:(a,u)=>Re(a*up(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>up(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>Q4(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?ro(a,o):wr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?On(a):to(a)}});return Object.freeze(c)}function YT(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 JT(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 Pw(t){let e=JT(t);return e+Math.ceil(e/2)}function XT(t,e,r=!1){let n=t.length,i=JT(e),o=Pw(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?to(t):On(t),c=Re(s,e-et)+et;return r?ro(c,i):wr(c,i)}l();l();var tN=BigInt(0),Mw=BigInt(1);function dp(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>tN;)o&Mw&&(s=s.add(c)),c=c.double(),o>>=Mw;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+=Mw);let S=y,I=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[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 Wd(t){return Cw(t.Fp),cn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Lw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function rN(t){let e=Wd(t);cn(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:nN,hexToBytes:iN}=ap,gc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=gc;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:nN(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=gc,r=typeof t=="string"?iN(t):t;if(!Un(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}=gc._parseInt(r.subarray(2)),{d:s,l:c}=gc._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}`}},io=BigInt(0),an=BigInt(1),VW=BigInt(2),ZT=BigInt(3),qW=BigInt(4);function oN(t){let e=rN(t),{Fp:r}=e,n=e.toBytes||((g,y,x)=>{let S=y.toAffine();return no(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),I=r.mul(S,g);return r.add(r.add(I,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"&&io<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:I}=e;if(y&&typeof g!="bigint"){if(Un(g)&&(g=eo(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:to(Ge("private key",g,x))}catch{throw new Error(`private key must be ${x} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=Re(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,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 I=A=>r.eql(A,r.ZERO);return I(x)&&I(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,I)=>S.toAffine(x[I])).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),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:x,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(x,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:x}=e,S=r.mul(x,ZT),{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),Z=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,Z),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),Z=r.mul(y,Z),Q=r.sub(j,Z),Q=r.mul(y,Q),Q=r.add(Q,q),q=r.add(j,j),j=r.add(q,j),j=r.add(j,Z),j=r.mul(j,Q),M=r.add(M,j),Z=r.mul(A,O),Z=r.add(Z,Z),j=r.mul(Z,Q),T=r.sub(T,j),q=r.mul(Z,$),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:I}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,Z=r.mul(e.b,ZT),Q=r.mul(x,A),G=r.mul(S,O),_=r.mul(I,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,I);let U=r.add(A,T);return E=r.mul(E,U),U=r.add(Q,_),E=r.sub(E,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($,E),M=r.mul(Z,_),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($,_),E=r.mul(Z,E),G=r.add(G,_),_=r.sub(Q,_),_=r.mul($,_),E=r.add(E,_),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(I=>I.pz));return x.map((I,A)=>I.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let x=f.ZERO;if(y===io)return x;if(c(y),y===an)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=x,q=x,j=this;for(;A>io||T>io;)A&an&&(M=M.add(j)),T&an&&(q=q.add(j)),j=j.double(),A>>=an,T>>=an;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 x=y,S,I,{endo:A}=e;if(A){let{k1neg:O,k1:T,k2neg:M,k2:q}=A.splitScalar(x),{p:j,f:$}=this.wNAF(T),{p:Z,f:Q}=this.wNAF(q);j=p.constTimeNegate(O,j),Z=p.constTimeNegate(M,Z),Z=new f(r.mul(Z.px,A.beta),Z.py,Z.pz),S=j.add(Z),I=$.add(Q)}else{let{p:O,f:T}=this.wNAF(x);S=O,I=T}return f.normalizeZ([S,I])[0]}multiplyAndAddUnsafe(y,x,S){let I=f.BASE,A=(T,M)=>M===io||M===an||!T.equals(I)?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:I}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(I));let O=r.mul(x,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:x}=e;if(y===an)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===an?this:x?x(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return eo(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=dp(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function sN(t){let e=Wd(t);return cn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function QT(t){let e=sN(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(E){return io<E&&E<r.ORDER}function c(E){return Re(E,n)}function a(E){return up(E,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=oN({...e,toBytes(E,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=no;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=to(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&an)===an;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=>eo(wr(E,e.nByteLength));function g(E){let U=n>>an;return E>U}function y(E){return g(E)?c(-E):E}let x=(E,U,L)=>to(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}=gc.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),X=u.BASE.multiplyAndAddUnsafe(J,W,Y);if(!X)throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return pc(this.toDERHex())}toDERHex(){return gc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return pc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let I={isValidPrivateKey(E){try{return d(E),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let E=Pw(e.n);return XT(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=Un(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=to(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=jd(e.nBitLength);function $(E){if(typeof E!="bigint")throw new Error("bigint expected");if(!(io<=E&&E<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return wr(E,e.nByteLength)}function Z(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=no(...W),X=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Oe=a(ce),Me=u.BASE.multiply(ce).toAffine(),Je=c(Me.x);if(Je===io)return;let Et=c(Oe*c(X+Je*z));if(Et===io)return;let yi=(Me.x===Je?0:2)|Number(Me.y&an),go=Et;return C&&g(Et)&&(go=y(Et),yi^=1),new S(Je,go,yi)}return{seed:Y,k2sig:ue}}let Q={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function _(E,U,L=Q){let{seed:N,k2sig:R}=Z(E,U,L),C=e;return Dw(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"||Un(R))try{V=S.fromDER(R)}catch(Me){if(!(Me instanceof gc.Err))throw Me;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Me,s:Je}=R;V=new S(Me,Je)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Me){if(Me.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),X=a(W),ue=c(Y*X),ee=c(z*X),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 fp=class extends qa{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,KT(e);let n=qd(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 Va(this),this.iHash.update(e),this}digestInto(e){Va(this),Iw(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()}},Kw=(t,e,r)=>new fp(t,e).update(r).digest();Kw.create=(t,e)=>new fp(t,e);function cN(t){return{hash:t,hmac:(e,...r)=>Kw(t,e,ip(...r)),randomBytes:Fd}}function lp(t,e){let r=n=>QT({...t,...cN(n)});return Object.freeze({...r(e),create:r})}var r_=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),e_=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),aN=BigInt(1),$w=BigInt(2),t_=(t,e)=>(t+e/$w)/e;function uN(t){let e=r_,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,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,$w,e);if(!Hw.eql(Hw.sqr(M),t))throw new Error("Cannot find square root");return M}var Hw=ja(r_,void 0,void 0,{sqrt:uN}),br=lp({a:BigInt(0),b:BigInt(7),Fp:Hw,n:e_,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=e_,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-aN*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=t_(o*t,e),a=t_(-n*t,e),u=Re(t-c*r-a*i,e),d=Re(-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}}}},sp),iG=BigInt(0);var oG=br.ProjectivePoint;l();l();function n_(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 dN=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())})},Vw="urn:jwk:";function we(t){return dN(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}`);wg(n);let i=n_(n),o=ne.string(i).toUint8Array(),s=yield Ha.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function ui(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 Wa(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 di(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 Ga(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 i_(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 Vt=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())})},fN=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},Nt=class t{static adjustSignatureToLowS(e){return Vt(this,arguments,void 0,function*({signature:r}){let n=br.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Vt(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 we({jwk:i}),i})}static bytesToPublicKey(e){return Vt(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 we({jwk:i}),i})}static compressPublicKey(e){return Vt(this,arguments,void 0,function*({publicKeyBytes:r}){return br.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Vt(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 we({jwk:o}),o})}static convertDerToCompactSignature(e){return Vt(this,arguments,void 0,function*({derSignature:r}){return br.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Vt(this,arguments,void 0,function*({publicKeyBytes:r}){return br.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Vt(this,void 0,void 0,function*(){let e=br.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return Vt(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=fN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return Vt(this,arguments,void 0,function*({privateKey:r}){if(!ui(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 Vt(this,arguments,void 0,function*({publicKey:r}){if(!(Wa(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 Vt(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 br.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return Vt(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Xo(r);return br.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Vt(this,arguments,void 0,function*({privateKeyBytes:r}){return br.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Vt(this,arguments,void 0,function*({publicKeyBytes:r}){try{br.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Vt(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Xo(i);return br.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Vt(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=br.getPublicKey(r));let n=br.ProjectivePoint.fromHex(r),i=wr(n.x,32),o=wr(n.y,32);return{x:i,y:o}})}};l();l();var o_=ja(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),lN=o_.create(BigInt("-3")),hN=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),pN=lp({a:lN,b:hN,Fp:o_,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},sp),Mr=pN;var qt=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())})},yN=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},Ft=class t{static adjustSignatureToLowS(e){return qt(this,arguments,void 0,function*({signature:r}){let n=Mr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return qt(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 we({jwk:i}),i})}static bytesToPublicKey(e){return qt(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 we({jwk:i}),i})}static compressPublicKey(e){return qt(this,arguments,void 0,function*({publicKeyBytes:r}){return Mr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return qt(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 we({jwk:o}),o})}static convertDerToCompactSignature(e){return qt(this,arguments,void 0,function*({derSignature:r}){return Mr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return qt(this,arguments,void 0,function*({publicKeyBytes:r}){return Mr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return qt(this,void 0,void 0,function*(){let e=Mr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return qt(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,o=yN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return qt(this,arguments,void 0,function*({privateKey:r}){if(!ui(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 qt(this,arguments,void 0,function*({publicKey:r}){if(!(Wa(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 qt(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 Mr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return qt(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Xo(r);return Mr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return qt(this,arguments,void 0,function*({privateKeyBytes:r}){return Mr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return qt(this,arguments,void 0,function*({publicKeyBytes:r}){try{Mr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return qt(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Xo(i);return Mr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return qt(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Mr.getPublicKey(r));let n=Mr.ProjectivePoint.fromHex(r),i=wr(n.x,32),o=wr(n.y,32);return{x:i,y:o}})}};var Gd=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())})},zd=class extends ai{computePublicKey(e){return Gd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Nt.computePublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Ft.computePublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Gd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"ES256K":case"secp256k1":{let n=yield Nt.generateKey();return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Ft.generateKey();return n.alg="ES256",n}}})}getPublicKey(e){return Gd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Nt.getPublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Ft.getPublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Gd(this,arguments,void 0,function*({key:r,data:n}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":return yield Nt.sign({key:r,data:n});case"P-256":return yield Ft.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Gd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Wa(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(r.crv){case"secp256k1":return yield Nt.verify({key:r,signature:n,data:i});case"P-256":return yield Ft.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};l();l();l();l();l();var hp=BigInt(4294967295),qw=BigInt(32);function s_(t,e=!1){return e?{h:Number(t&hp),l:Number(t>>qw&hp)}:{h:Number(t>>qw&hp)|0,l:Number(t&hp)|0}}function gN(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}=s_(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var mN=(t,e)=>BigInt(t>>>0)<<qw|BigInt(e>>>0),wN=(t,e,r)=>t>>>r,bN=(t,e,r)=>t<<32-r|e>>>r,xN=(t,e,r)=>t>>>r|e<<32-r,EN=(t,e,r)=>t<<32-r|e>>>r,vN=(t,e,r)=>t<<64-r|e>>>r-32,SN=(t,e,r)=>t>>>r-32|e<<64-r,AN=(t,e)=>e,TN=(t,e)=>t,_N=(t,e,r)=>t<<r|e>>>32-r,IN=(t,e,r)=>e<<r|t>>>32-r,BN=(t,e,r)=>e<<r-32|t>>>64-r,RN=(t,e,r)=>t<<r-32|e>>>64-r;function UN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var ON=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),DN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,kN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),NN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,CN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),LN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var PN={fromBig:s_,split:gN,toBig:mN,shrSH:wN,shrSL:bN,rotrSH:xN,rotrSL:EN,rotrBH:vN,rotrBL:SN,rotr32H:AN,rotr32L:TN,rotlSH:_N,rotlSL:IN,rotlBH:BN,rotlBL:RN,add:UN,add3L:ON,add3H:DN,add4L:kN,add4H:NN,add5H:LN,add5L:CN},pe=PN;var[MN,KN]=pe.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))),es=new Uint32Array(80),ts=new Uint32Array(80),Fw=class extends Fa{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)es[A]=e.getUint32(r),ts[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=es[A-15]|0,T=ts[A-15]|0,M=pe.rotrSH(O,T,1)^pe.rotrSH(O,T,8)^pe.shrSH(O,T,7),q=pe.rotrSL(O,T,1)^pe.rotrSL(O,T,8)^pe.shrSL(O,T,7),j=es[A-2]|0,$=ts[A-2]|0,Z=pe.rotrSH(j,$,19)^pe.rotrBH(j,$,61)^pe.shrSH(j,$,6),Q=pe.rotrSL(j,$,19)^pe.rotrBL(j,$,61)^pe.shrSL(j,$,6),G=pe.add4L(q,Q,ts[A-7],ts[A-16]),_=pe.add4H(G,M,Z,es[A-7],es[A-16]);es[A]=_|0,ts[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:I}=this;for(let A=0;A<80;A++){let O=pe.rotrSH(f,h,14)^pe.rotrSH(f,h,18)^pe.rotrBH(f,h,41),T=pe.rotrSL(f,h,14)^pe.rotrSL(f,h,18)^pe.rotrBL(f,h,41),M=f&p^~f&y,q=h&g^~h&x,j=pe.add5L(I,T,q,KN[A],ts[A]),$=pe.add5H(j,S,O,M,MN[A],es[A]),Z=j|0,Q=pe.rotrSH(n,i,28)^pe.rotrBH(n,i,34)^pe.rotrBH(n,i,39),G=pe.rotrSL(n,i,28)^pe.rotrBL(n,i,34)^pe.rotrBL(n,i,39),_=n&o^n&c^o&c,D=i&s^i&a^s&a;S=y|0,I=x|0,y=p|0,x=g|0,p=f|0,g=h|0,{h:f,l:h}=pe.add(u|0,d|0,$|0,Z|0),u=c|0,d=a|0,c=o|0,a=s|0,o=n|0,s=i|0;let E=pe.add3L(Z,G,D);n=pe.add3H(E,$,Q,_),i=E|0}({h:n,l:i}=pe.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=pe.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:c,l:a}=pe.add(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:d}=pe.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:h}=pe.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:g}=pe.add(this.Fh|0,this.Fl|0,p|0,g|0),{h:y,l:x}=pe.add(this.Gh|0,this.Gl|0,y|0,x|0),{h:S,l:I}=pe.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,x,S,I)}roundClean(){es.fill(0),ts.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 jw=op(()=>new Fw);l();var Dn=BigInt(0),Kr=BigInt(1),pp=BigInt(2),$N=BigInt(8),HN={zip215:!0};function VN(t){let e=Wd(t);return cn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function yp(t){let e=VN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=pp<<BigInt(c*8)-Kr,d=r.create,f=e.uvRatio||((N,R)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(R))}}catch{return{isValid:!1,value:Dn}}}),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"&&Dn<N,y=(N,R)=>g(N)&&g(R)&&N<R,x=N=>N===Dn||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===Dn?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,Kr,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),X=d(J*J),ue=d(X*X),ee=d(W*R),ce=d(X*d(ee+Y)),Oe=d(ue+d(C*d(W*Y)));if(ce!==Oe)throw new Error("bad point: equation left != right (1)");let Me=d(P*V),Je=d(J*z);if(Me!==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),X=d(J*V),ue=d(P*W),ee=d(z*V);return Y===X&&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(pp*d(V*V)),Y=d(R*J),X=C+P,ue=d(d(X*X)-J-z),ee=Y+z,ce=ee-W,Oe=Y-z,Me=d(ue*ce),Je=d(ee*Oe),Et=d(ue*Oe),yi=d(ce*ee);return new T(Me,Je,yi,Et)}add(R){O(R);let{a:C,d:P}=e,{ex:V,ey:J,ez:z,et:W}=this,{ex:Y,ey:X,ez:ue,et:ee}=R;if(C===BigInt(-1)){let gu=d((J-V)*(X+Y)),Af=d((J+V)*(X-Y)),mu=d(Af-gu);if(mu===Dn)return this.double();let Tf=d(z*pp*ee),_f=d(W*pp*ue),Gr=_f+Tf,wo=Af+gu,wu=_f-Tf,If=d(Gr*mu),ls=d(wo*wu),Bf=d(Gr*wu),sy=d(mu*wo);return new T(If,ls,sy,Bf)}let ce=d(V*Y),Oe=d(J*X),Me=d(W*P*ee),Je=d(z*ue),Et=d((V+J)*(Y+X)-ce-Oe),yi=Je-Me,go=Je+Me,yu=d(Oe-C*ce),Sf=d(Et*yi),oy=d(go*yu),mo=d(Et*yu),Wr=d(yi*go);return new T(Sf,oy,Wr,mo)}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===Dn?q:this.equals(q)||C===Kr?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?$N:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:Dn,y:Kr};if(Y!==Kr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Kr?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=On(z);Y===Dn||(C?S(Y,u):S(Y,r.ORDER));let X=d(Y*Y),ue=d(X-Kr),ee=d(P*X-V),{isValid:ce,value:Oe}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Me=(Oe&Kr)===Kr,Je=(W&128)!==0;if(!C&&Oe===Dn&&Je)throw new Error("Point.fromHex: x=0 and x_0=1");return Je!==Me&&(Oe=d(-Oe)),T.fromAffine({x:Oe,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=ro(C,r.BYTES);return P[P.length-1]|=R&Kr?128:0,P}toHex(){return eo(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Kr,d(e.Gx*e.Gy)),T.ZERO=new T(Dn,Kr,Kr,Dn);let{BASE:M,ZERO:q}=T,j=dp(T,c*8);function $(N){return Re(N,n)}function Z(N){return $(On(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=Z(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=no(...R);return Z(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),X=$(z+Y*V);I(X);let ue=no(W,ro(X,r.BYTES));return Ge("result",ue,c*2)}let E=HN;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=On(N.slice(z,2*z)),Y,X,ue;try{Y=T.fromHex(C,J),X=T.fromHex(N.slice(0,z),J),ue=M.multiplyUnsafe(W)}catch{return!1}if(!J&&Y.isSmallOrder())return!1;let ee=_(V,X.toRawBytes(),Y.toRawBytes(),R);return X.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 Yd=BigInt(0),Ww=BigInt(1);function qN(t){return cn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function c_(t){let e=qN(t),{P:r}=e,n=A=>Re(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>Nw(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"&&Yd<=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=Ww,$=Yd,Z=T,Q=Ww,G=Yd,_;for(let E=BigInt(i-1);E>=Yd;E--){let U=M>>E&Ww;G^=U,_=u(G,j,Z),j=_[0],Z=_[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=Z+Q,J=Z-Q,z=n(J*L),W=n(V*R),Y=z+W,X=z-W;Z=n(Y*Y),Q=n(q*n(X*X)),j=n(N*C),$=n(P*(N+n(f*P)))}_=u(G,j,Z),j=_[0],Z=_[1],_=u(G,$,Q),$=_[0],Q=_[1];let D=a($);return n(j*D)}function p(A){return ro(n(A),o)}function g(A){let O=Ge("u coordinate",A,o);return s===32&&(O[31]&=127),On(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 On(c(O))}function x(A,O){let T=g(O),M=y(A),q=h(T,M);if(q===Yd)throw new Error("Invalid private or public key received");return p(q)}let S=p(e.Gu);function I(A){return x(A,S)}return{scalarMult:x,scalarMultBase:I,getSharedSecret:(A,O)=>x(A,O),getPublicKey:A=>I(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Jd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),a_=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),cz=BigInt(0),FN=BigInt(1),Gw=BigInt(2),jN=BigInt(5),u_=BigInt(10),WN=BigInt(20),GN=BigInt(40),d_=BigInt(80);function f_(t){let e=Jd,n=t*t%e*t%e,i=ze(n,Gw,e)*n%e,o=ze(i,FN,e)*t%e,s=ze(o,jN,e)*o%e,c=ze(s,u_,e)*s%e,a=ze(c,WN,e)*c%e,u=ze(a,GN,e)*a%e,d=ze(u,d_,e)*u%e,f=ze(d,d_,e)*u%e,h=ze(f,u_,e)*s%e;return{pow_p_5_8:ze(h,Gw,e)*t%e,b2:n}}function l_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function zN(t,e){let r=Jd,n=Re(e*e*e,r),i=Re(n*n*e,r),o=f_(t*i).pow_p_5_8,s=Re(t*n*o,r),c=Re(e*s*s,r),a=s,u=Re(s*a_,r),d=c===t,f=c===Re(-t,r),h=c===Re(-t*a_,r);return d&&(s=a),(f||h)&&(s=u),zT(s,r)&&(s=Re(-s,r)),{isValid:d||f,value:s}}var un=ja(Jd,void 0,!0),Xd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:un,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:jw,randomBytes:Fd,adjustScalarBytes:l_,uvRatio:zN},rs=yp(Xd);function h_(t,e,r){if(e.length>255)throw new Error("Context is too big");return ip(Bw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var az=yp({...Xd,domain:h_}),uz=yp({...Xd,domain:h_,prehash:jw}),mc=c_({P:Jd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Jd,{pow_p_5_8:r,b2:n}=f_(t);return Re(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:l_,randomBytes:Fd});function p_(t){let{y:e}=rs.ExtendedPoint.fromHex(t),r=BigInt(1);return un.toBytes(un.create((r+e)*un.inv(r-e)))}function y_(t){let e=Xd.hash(t.subarray(0,32));return Xd.adjustScalarBytes(e).subarray(0,32)}var YN=(un.ORDER+BigInt(3))/BigInt(8),dz=un.pow(Gw,YN),fz=un.sqrt(un.neg(un.ONE)),lz=(un.ORDER-BigInt(5))/BigInt(8),hz=BigInt(486662);var pz=YT(un,un.neg(BigInt(486664)));var yz=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),gz=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),mz=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),wz=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var bz=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var dn=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())})},JN=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},Bt=class t{static bytesToPrivateKey(e){return dn(this,arguments,void 0,function*({privateKeyBytes:r}){let n=rs.getPublicKey(r),i={crv:"Ed25519",d:ne.uint8Array(r).toBase64Url(),kty:"OKP",x:ne.uint8Array(n).toBase64Url()};return i.kid=yield we({jwk:i}),i})}static bytesToPublicKey(e){return dn(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield we({jwk:n}),n})}static computePublicKey(e){return dn(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=rs.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield we({jwk:o}),o})}static convertPrivateKeyToX25519(e){return dn(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=y_(n),o=mc.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:ne.uint8Array(i).toBase64Url(),x:ne.uint8Array(o).toBase64Url()};return s.kid=yield we({jwk:s}),s})}static convertPublicKeyToX25519(e){return dn(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=p_(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield we({jwk:s}),s})}static generateKey(){return dn(this,void 0,void 0,function*(){let e=rs.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return dn(this,arguments,void 0,function*({key:r}){var n;if(!(di(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,o=JN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return dn(this,arguments,void 0,function*({privateKey:r}){if(!di(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 dn(this,arguments,void 0,function*({publicKey:r}){if(!Ga(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 dn(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return rs.sign(n,i)})}static validatePublicKey(e){return dn(this,arguments,void 0,function*({publicKeyBytes:r}){try{rs.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return dn(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return rs.verify(n,i,o)})}};var Zd=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())})},gp=class extends ai{computePublicKey(e){return Zd(this,arguments,void 0,function*({key:r}){if(!di(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield Bt.computePublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Zd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield Bt.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return Zd(this,arguments,void 0,function*({key:r}){if(!di(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield Bt.getPublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Zd(this,arguments,void 0,function*({key:r,data:n}){if(!di(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":return yield Bt.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Zd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ga(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(r.crv){case"Ed25519":return yield Bt.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};var oo=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())})},zw={Ed25519:{implementation:gp,names:["Ed25519"]},secp256k1:{implementation:zd,names:["ES256K","secp256k1"]},secp256r1:{implementation:zd,names:["ES256","secp256r1"]},"SHA-256":{implementation:tp,names:["SHA-256"]}},tr=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new xh}digest(e){return oo(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return oo(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return oo(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=`${Vw}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return oo(this,arguments,void 0,function*({key:r}){let n=yield we({jwk:r});return`${Vw}${n}`})}getPublicKey(e){return oo(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 oo(this,arguments,void 0,function*({key:r}){var n;if(!i_(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 we({jwk:i}));let o=yield this.getKeyUri({key:i});return yield this._keyStore.set(o,i),o})}sign(e){return oo(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 oo(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=zw[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 zw){let o=zw[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 oo(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 mp=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 CT(e)}static randomUuid(){return $a.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 ns=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())})},XN=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},za=class t{static bytesToPrivateKey(e){return ns(this,arguments,void 0,function*({privateKeyBytes:r}){let n=mc.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n).toBase64Url()};return i.kid=yield we({jwk:i}),i})}static bytesToPublicKey(e){return ns(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield we({jwk:n}),n})}static computePublicKey(e){return ns(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=mc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield we({jwk:o}),o})}static generateKey(){return ns(this,void 0,void 0,function*(){let e=mc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return ns(this,arguments,void 0,function*({key:r}){var n;if(!(di(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,o=XN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return ns(this,arguments,void 0,function*({privateKey:r}){if(!di(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 ns(this,arguments,void 0,function*({publicKey:r}){if(!Ga(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 ns(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 mc.getSharedSecret(i,o)})}};l();l();l();function $r(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Xw({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(Jw))!==null&&r!==void 0?r:[]),Object.keys($i).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(Jw))!==null&&s!==void 0?s:[])}),n}function g_({didDocument:t}){let r=Xw({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function m_({didDocument:t,methodId:e}){let r=[];return Object.keys($i).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=$r(e);i.some(c=>{let a=$r(c)===o,u=Jw(c)&&$r(c.id)===o;return a||u})&&r.push(n)}}),r}function w_(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Jw(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 Zw({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=Xt.addPrefix({code:e,data:t,name:r}),i=ne.uint8Array(n).toBase58Btc();return ne.base58Btc(i).toMultibase()}function Qw({multibaseKeyId:t}){try{let e=ne.multibase(t).toBase58Btc(),r=ne.base58Btc(e).toUint8Array(),{code:n,data:i,name:o}=Xt.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:o}}catch{throw new re(ie.InvalidDid,`Invalid multibase identifier: ${t}`)}}var Qd=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())})},xr=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 Qd(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 Qd(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 $r(a.id)===((u=$r(e?.methodId))!==null&&u!==void 0?u:$r((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:mp.getJoseSignatureAlgorithmFromPublicKey(o),keyId:n.id,sign(a){return Qd(this,arguments,void 0,function*({data:u}){return yield s.sign({data:u,keyUri:i})})},verify(a){return Qd(this,arguments,void 0,function*({data:u,signature:d}){return yield s.verify({data:u,key:o,signature:d})})}}})}static import(e){return Qd(this,arguments,void 0,function*({portableDid:r,keyManager:n=new tr}){var i;let o=Xw({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 eb="0123456789abcdef",x_=[],b_=[];for(let t=0;t<256;t++)x_[t]=eb[t>>4&15]+eb[t&15],t<16&&(t<10?b_[48+t]=t:b_[87+t]=t);var tb=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=x_[t[n++]];return r};var E_=(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 v_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",QN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(ef=0;ef<v_.length;ef++)QN[v_.charCodeAt(ef)]=ef;var ef;var eC=new TextDecoder,rb=(t,e)=>e?new TextDecoder(e).decode(t):eC.decode(t),tC=new TextEncoder,fn=t=>tC.encode(t);var S_=typeof window<"u"?window:self,A_=S_.crypto||S_.msCrypto||{},bJ=A_.subtle||A_.webkitSubtle;l();function Ya(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function wp(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 Ue(t,e,r){let n=[],i=null;return Ue._encode(n,t),i=E_(n),Ue.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Ue.bytes=-1;Ue._floatConversionDetected=!1;Ue._encode=function(t,e){if(e!=null)switch(wp(e)){case"object":Ue.dict(t,e);break;case"map":Ue.dictMap(t,e);break;case"array":Ue.list(t,e);break;case"set":Ue.listSet(t,e);break;case"string":Ue.string(t,e);break;case"number":Ue.number(t,e);break;case"boolean":Ue.number(t,e);break;case"arraybufferview":Ue.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Ue.buffer(t,new Uint8Array(e));break}};var bp=new Uint8Array([101]),T_=new Uint8Array([100]),__=new Uint8Array([108]);Ue.buffer=function(t,e){t.push(fn(e.length+":"),e)};Ue.string=function(t,e){t.push(fn(fn(e).byteLength+":"+e))};Ue.number=function(t,e){if(Number.isInteger(e))return t.push(fn("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(fn("i"+o+"e")),o!==e&&!Ue._floatConversionDetected&&(Ue._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())};Ue.dict=function(t,e){t.push(T_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Ue.string(t,n),Ue._encode(t,e[n]));t.push(bp)};Ue.dictMap=function(t,e){t.push(T_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Ue._encode(t,n):Ue.string(t,String(n)),Ue._encode(t,e.get(n)));t.push(bp)};Ue.list=function(t,e){let r=0,n=e.length;for(t.push(__);r<n;r++)e[r]!=null&&Ue._encode(t,e[r]);t.push(bp)};Ue.listSet=function(t,e){t.push(__);for(let r of e)r!=null&&Ue._encode(t,r);t.push(bp)};var I_=Ue;l();var rC=105,nC=58,iC=100,oC=108,nb=101;function B_(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)):fn(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 iC:return de.dictionary();case oC:return de.list();case rC: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]!==nb;){let e=de.buffer(),r=rb(e);r.includes("\uFFFD")&&(r=tb(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==nb;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find(nb),e=B_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find(nC),e=B_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?rb(de.data.slice(t,r)):de.data.slice(t,r)};var R_=de;l();function sC(t){let e=2;for(let r of t)e+=xp(r);return e}function cC(t){let e=2;for(let[r,n]of t){let i=fn(r).byteLength;e+=Ya(i)+1+i,e+=xp(n)}return e}function aC(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=fn(r[n]).byteLength;e+=Ya(i)+1+i,e+=xp(t[r[n]])}return e}function uC(t){let e=fn(t).byteLength;return Ya(e)+1+e}function dC(t){let e=t.byteLength-t.byteOffset;return Ya(e)+1+e}function xp(t){if(t==null)return 0;let r=wp(t);switch(r){case"arraybufferview":return dC(t);case"string":return uC(t);case"array":case"set":return sC(t);case"number":return 1+Ya(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return aC(t);case"map":return cC(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var ib=xp;var fC=ib,ob={encode:I_,decode:R_,byteLength:ib,encodingLength:fC};l();l();var lC=/^(\d{1,3}\.){3,3}\d{1,3}$/;var hC=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var kn={name:"v4",size:4,isFormat:t=>lC.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]}`}},so={name:"v6",size:16,isFormat:t=>t.length>0&&hC.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 U_(t){if(kn.isFormat(t))return kn.size;if(so.isFormat(t))return so.size;throw Error(`Invalid ip address: ${t}`)}function O_(t){return U_(t)===kn.size?1:2}function D_(t,e,r){r=~~r;let n=U_(t);return typeof e=="function"&&(e=e(r+n)),n===kn.size?kn.encode(t,e,r):so.encode(t,e,r)}function k_(t,e,r){if(e=~~e,r=r||t.length-e,r===kn.size)return kn.decode(t,e,r);if(r===so.size)return so.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${kn.size} for v4 or ${so.size} for v6.`)}l();function tf(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 Ja(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 N_(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 C_(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 sb(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 cb(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 L_(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 ab(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 ub(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 Xa(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(ub(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 Xa.bytes=i-r,e}Xa.bytes=0;function Za(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 Za.bytes=r-e,n}Za.bytes=0;var is=t=>t instanceof Uint8Array;function co(t){return typeof t=="string"?ub(t):t.byteLength}function Ep(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Xa(t)}function vp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Xa(e,t,r),Xa.bytes}var rf={},P_=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}`;P_[s]=c,rf[c]=s,rf[`${r}${i}`]=s,rf[`${e}${o}`]=s,rf[`${r}${o}`]=s}}function M_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=P_[o]}return n}function db(t){return t.length>>>1}function K_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=rf[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var EC=Math.pow(2,24),vC=Math.pow(2,16),SC=Math.pow(2,8),fi=(t,e)=>t[e]*EC+t[e+1]*vC+t[e+2]*SC+t[e+3],ye=(t,e)=>t[e]<<8|t[e+1],li=(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 Er(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 _C=0,$_=32768,lb=32768,IC=~lb,V_=32768,BC=~V_;function $e({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=$e({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=vp(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=ye(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(Za(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:co(t.replace(/^\.|\.$/gm,""))+2}}),Rt=$e({encode(t,e,r){e||(e=new Uint8Array(Rt.encodingLength(t))),r||(r=0);let n=vp(e,t,r+1);return e[r]=n,Rt.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=Za(t,e+1,e+1+r);return Rt.decode.bytes=r+1,n},encodingLength(t){return co(t)+1}}),Qa=$e({bytes:12,encode(t,e,r){e||(e=new Uint8Array(Qa.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?$_:_C;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=ye(t,e+2);return{id:ye(t,e),type:r&$_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:C_(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:N_(r&15),questions:new Array(ye(t,e+4)),answers:new Array(ye(t,e+6)),authorities:new Array(ye(t,e+8)),additionals:new Array(ye(t,e+10))}},encodingLength(){return 12}}),Ap=$e({encode(t,e,r){e||(e=new Uint8Array(Ap.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),Er(t,e,r+2,0,n),Ap.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=ye(t,e),n=t.slice(e+2,e+2+r);return Ap.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),Tp=$e({encode(t,e,r){return e||(e=new Uint8Array(Tp.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),Tp.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=ye(t,e),n=se.decode(t,e+2);return Tp.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),_p=$e({encode(t,e,r){e||(e=new Uint8Array(_p.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,li(e,t.serial||0,r),r+=4,li(e,t.refresh||0,r),r+=4,li(e,t.retry||0,r),r+=4,li(e,t.expire||0,r),r+=4,li(e,t.minimum||0,r),r+=4,ae(e,r-n-2,n),_p.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=fi(t,e),e+=4,n.refresh=fi(t,e),e+=4,n.retry=fi(t,e),e+=4,n.expire=fi(t,e),e+=4,n.minimum=fi(t,e),e+=4,_p.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),Ip=$e({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=Ep(t[i])),!is(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(Ip.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,Er(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),Ip.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=ye(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 Ip.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=co(r)+1:e+=r.length+1}),e}}),Bp=$e({encode(t,e,r){e||(e=new Uint8Array(Bp.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=Ep(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return Er(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=ye(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,Bp.decode.bytes=e-r,i},encodingLength(t){return t?(is(t)?t.length:co(t))+2:2}}),Rp=$e({encode(t,e,r){e||(e=new Uint8Array(Rp.encodingLength(t))),r||(r=0);let n=r;return r+=2,Rt.encode(t.cpu,e,r),r+=Rt.encode.bytes,Rt.encode(t.os,e,r),r+=Rt.encode.bytes,ae(e,r-n-2,n),Rp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Rt.decode(t,e),e+=Rt.decode.bytes,n.os=Rt.decode(t,e),e+=Rt.decode.bytes,Rp.decode.bytes=e-r,n},encodingLength(t){return Rt.encodingLength(t.cpu)+Rt.encodingLength(t.os)+2}}),ru=$e({encode(t,e,r){return e||(e=new Uint8Array(ru.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),ru.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return ru.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),Up=$e({encode(t,e,r){e||(e=new Uint8Array(Up.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),Up.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=ye(t,e),n={};return n.priority=ye(t,e+2),n.weight=ye(t,e+4),n.port=ye(t,e+6),n.target=se.decode(t,e+8),Up.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),os=$e({encode(t,e,r){let n=os.encodingLength(t);return e||(e=new Uint8Array(os.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=os.ISSUER_CRITICAL),ae(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Rt.encode(t.tag,e,r),r+=Rt.encode.bytes,vp(e,t.value,r),r+=co(t.value),os.encode.bytes=n,e},decode(t,e){e||(e=0);let r=ye(t,e);e+=2;let n=e,i={};return i.flags=t[e],e+=1,i.tag=Rt.decode(t,e),e+=Rt.decode.bytes,i.value=Za(t,e,n+r),i.issuerCritical=!!(i.flags&os.ISSUER_CRITICAL),os.decode.bytes=r+2,i},encodingLength(t){return Rt.encodingLength(t.tag)+Rt.encodingLength(t.value)+2}});os.ISSUER_CRITICAL=128;var Op=$e({encode(t,e,r){e||(e=new Uint8Array(Op.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),Op.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=ye(t,e),e+=2,n.exchange=se.decode(t,e),e+=se.decode.bytes,Op.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),q_=$e({encode(t,e,r){return e||(e=new Uint8Array(q_.encodingLength(t))),r||(r=0),ae(e,4,r),r+=2,kn.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,kn.decode(t,e)},bytes:6}),Dp=$e({encode(t,e,r){return e||(e=new Uint8Array(Dp.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,so.encode(t,e,r),Dp.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=so.decode(t,e);return Dp.decode.bytes=18,r},bytes:18}),H_=t=>new Uint8Array(t),ao=$e({encode(t,e,r){e||(e=new Uint8Array(ao.encodingLength(t))),r||(r=0);let n=r,i=ab(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,Er(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||O_(t.ip,H_),c=D_(t.ip,H_),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,Er(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 ao.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=ye(t,e),r.type=L_(r.code),e+=2;let n=ye(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=ye(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);Er(t,i,0,e,e+n-4),r.ip=k_(i)}break;case 11:n>0&&(r.timeout=ye(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(ye(t,e)),e+=2}return ao.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(ab(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}`)}}),ss=$e({encode(t,e,r){e||(e=new Uint8Array(ss.encodingLength(t))),r||(r=0);let n=r,i=tu(t,ao);return ae(e,i,r),r=uf(t,ao,e,r+2),ss.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=ye(t,e);e+=2;let o=0;for(;i>0;)n[o++]=ao.decode(t,e),e+=ao.decode.bytes,i-=ao.decode.bytes;return ss.decode.bytes=e-r,n},encodingLength(t){return 2+tu(t||[],ao)}}),hi=$e({encode(t,e,r){e||(e=new Uint8Array(hi.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!is(i))throw new Error("Key must be a Buffer");return r+=2,ae(e,t.flags,r),r+=2,e[r]=hi.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,Er(i,e,r,0,i.length),r+=i.length,hi.encode.bytes=r-n,ae(e,hi.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);if(e+=2,n.flags=ye(t,e),e+=2,t[e]!==hi.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,hi.decode.bytes=e-r,n},encodingLength(t){return 6+co(t.key)}});hi.PROTOCOL_DNSSEC=3;hi.ZONE_KEY=128;hi.SECURE_ENTRYPOINT=32768;var nf=$e({encode(t,e,r){e||(e=new Uint8Array(nf.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!is(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Ja(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,li(e,t.originalTTL,r),r+=4,li(e,t.expiration,r),r+=4,li(e,t.inception,r),r+=4,ae(e,t.keyTag,r),r+=2,se.encode(t.signersName,e,r),r+=se.encode.bytes,Er(i,e,r,0,i.length),r+=i.length,nf.encode.bytes=r-n,ae(e,nf.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);return e+=2,n.typeCovered=tf(ye(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=fi(t,e),e+=4,n.expiration=fi(t,e),e+=4,n.inception=fi(t,e),e+=4,n.keyTag=ye(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,nf.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+co(t.signature)}}),of=$e({encode(t,e,r){e||(e=new Uint8Array(of.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,of.encode.bytes=r-n,ae(e,of.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,of.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Hr=$e({encode(t,e,r){e||(e=new Uint8Array(Hr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Ja(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=Ep(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,Er(s,e,r,0,s.length),r+=s.length}return Hr.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=tf(o<<8|c<<3|u);i.push(d)}}e+=s}return Hr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Ja(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}}),sf=$e({encode(t,e,r){e||(e=new Uint8Array(sf.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Hr.encode(t.rrtypes,e,r),r+=Hr.encode.bytes,sf.encode.bytes=r-n,ae(e,sf.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);return e+=2,n.nextDomain=se.decode(t,e),e+=se.decode.bytes,n.rrtypes=Hr.decode(t,e,i-(e-r)),e+=Hr.decode.bytes,sf.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Hr.encodingLength(t.rrtypes)}}),cf=$e({encode(t,e,r){e||(e=new Uint8Array(cf.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!is(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!is(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,Er(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,Er(o,e,r,0,o.length),r+=o.length,Hr.encode(t.rrtypes,e,r),r+=Hr.encode.bytes,cf.encode.bytes=r-n,ae(e,cf.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=ye(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=Hr.decode(t,e,i-(e-r)),e+=Hr.decode.bytes,cf.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Hr.encodingLength(t.rrtypes)}}),af=$e({encode(t,e,r){e||(e=new Uint8Array(af.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!is(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,Er(i,e,r,0,i.length),r+=i.length,af.encode.bytes=r-n,ae(e,af.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);return e+=2,n.keyTag=ye(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,af.decode.bytes=e-r,n},encodingLength(t){return 6+co(t.digest)}}),eu=$e({encode(t,e,r){e||(e=new Uint8Array(eu.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=db(t.fingerprint),o=hb(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return K_(e,t.fingerprint,r,r+=i),eu.encode.bytes=r-n,ae(e,eu.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=hb(n.hash);return n.fingerprint=M_(t,e,e+i),e+=i,eu.decode.bytes=e-r,n},encodingLength(t){return 4+db(t.fingerprint)}});function hb(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}eu.getFingerprintLengthForHashType=hb;function fb(t){switch(t.toUpperCase()){case"A":return q_;case"PTR":return ru;case"CNAME":return ru;case"DNAME":return ru;case"TXT":return Ip;case"NULL":return Bp;case"AAAA":return Dp;case"SRV":return Up;case"HINFO":return Rp;case"CAA":return os;case"NS":return Tp;case"SOA":return _p;case"MX":return Op;case"OPT":return ss;case"DNSKEY":return hi;case"RRSIG":return nf;case"RP":return of;case"NSEC":return sf;case"NSEC3":return cf;case"SSHFP":return eu;case"DS":return af}return Ap}var ln=$e({encode(t,e,r){e||(e=new Uint8Array(ln.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Ja(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,ss.encode(t.options||[],e,r),r+=ss.encode.bytes}else{let i=cb(t.class===void 0?"IN":t.class);t.flush&&(i|=lb),ae(e,i,r+2),li(e,t.ttl||0,r+4),r+=8;let o=fb(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return ln.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=tf(ye(t,e)),r.type==="OPT")r.udpPayloadSize=ye(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=ye(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=ss.decode(t,e+8),e+=8+ss.decode.bytes;else{let i=ye(t,e+2);r.ttl=fi(t,e+4),r.class=sb(i&IC),r.flush=!!(i&lb);let o=fb(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return ln.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+fb(t.type).encodingLength(e)}}),nu=$e({encode(t,e,r){e||(e=new Uint8Array(nu.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Ja(t.type),r),r+=2,ae(e,cb(t.class===void 0?"IN":t.class),r),r+=2,nu.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=tf(ye(t,e)),e+=2,n.class=sb(ye(t,e)),e+=2,!!(n.class&V_)&&(n.class&=BC),nu.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var F_=1024;var jt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(RC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),Qa.encode(t,e,r),r+=Qa.encode.bytes,r=uf(t.questions,nu,e,r),r=uf(t.answers,ln,e,r),r=uf(t.authorities,ln,e,r),r=uf(t.additionals,ln,e,r),jt.encode.bytes=r-i,n&&df.bytes!==e.length?e.slice(0,df.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=Qa.decode(t,e);return e+=Qa.decode.bytes,e=Sp(n.questions,nu,t,e),e=Sp(n.answers,ln,t,e),e=Sp(n.authorities,ln,t,e),e=Sp(n.additionals,ln,t,e),jt.decode.bytes=e-r,n},encodingLength:function(t){return Qa.encodingLength(t)+tu(t.questions||[],nu)+tu(t.answers||[],ln)+tu(t.authorities||[],ln)+tu(t.additionals||[],ln)}};jt.encode.bytes=0;jt.decode.bytes=0;function kp(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 Np={encode:function(t,e,r){return e=jt.encode(kp(t,"query"),e,r),Np.encode.bytes=jt.encode.bytes,e},decode:function(t,e){let r=jt.decode(t,e);return Np.decode.bytes=jt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return jt.encodingLength(kp(t,"query"))}};Np.encode.bytes=0;Np.decode.bytes=0;var Cp={encode:function(t,e,r){return e=jt.encode(kp(t,"response"),e,r),Cp.encode.bytes=jt.encode.bytes,e},decode:function(t,e){let r=jt.decode(t,e);return Cp.decode.bytes=jt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return jt.encodingLength(kp(t,"response"))}};Cp.encode.bytes=0;Cp.decode.bytes=0;var df=jt.encode,Lp=jt.decode,RC=jt.encodingLength;function j_(t){let e=df(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),Er(e,r,2,0,e.length),j_.bytes=r.byteLength,r}j_.bytes=0;function W_(t){let e=ye(t,0);if(t.byteLength<e+2)return null;let r=Lp(t.slice(2));return W_.bytes=Lp.bytes,r}W_.bytes=0;function tu(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function uf(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 Sp(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 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())})},hn=class{static getSigningMethod(e){return G_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return G_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")})}};var Lt=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())})},z_=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},Y_="https://diddht.tbddev.org",UC=0,cs=7200,Pp=";",ar=",",pb;(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"})(pb||(pb={}));var ur;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(ur||(ur={}));var yb;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(yb||(yb={}));var X_={Ed25519:ur.Ed25519,ES256K:ur.secp256k1,ES256:ur.secp256r1,"P-256":ur.secp256r1,secp256k1:ur.secp256k1,secp256r1:ur.secp256r1,X25519:ur.X25519},J_={[ur.Ed25519]:"EdDSA",[ur.secp256k1]:"ES256K",[ur.secp256r1]:"ES256",[ur.X25519]:"ECDH-ES+A256KW"},ff=class t extends hn{static create(){return Lt(this,arguments,void 0,function*({keyManager:e=new tr,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 X_)))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 Ct.identityKeyToIdentifier({identityKey:x}),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 we({jwk:q});j=`${S}#${$r(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 xr({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 Lt(this,arguments,void 0,function*({portableDid:r,keyManager:n=new tr}){var i;let o=xe.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield xr.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 Lt(this,arguments,void 0,function*({didDocument:r,methodId:n="#0"}){var i;let o=xe.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 $r(c.id)===((a=$r(n))!==null&&a!==void 0?a:$r((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 Lt(this,arguments,void 0,function*({did:r,gatewayUri:n=Y_}){return yield Mp.put({did:r,gatewayUri:n})})}static resolve(e){return Lt(this,arguments,void 0,function*(r,n={}){var i;let o=(i=n?.gatewayUri)!==null&&i!==void 0?i:Y_;try{yield Ct.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Mp.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},gt),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},gt),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};ff.methodName="dht";var Mp=class t{static get(e){return Lt(this,arguments,void 0,function*({didUri:r,gatewayUri:n}){let i=Ct.identifierToIdentityKeyBytes({didUri:r}),o=yield t.pkarrGet({gatewayUri:n,publicKeyBytes:i}),s=yield Ct.parseBep44GetMessage({bep44Message:o}),c=yield t.fromDnsPacket({didUri:r,dnsPacket:s});return c.didDocumentMetadata.versionId=o.seq.toString(),c})}static put(e){return Lt(this,arguments,void 0,function*({did:r,gatewayUri:n}){let i=yield t.toDnsPacket({didDocument:r.document,didMetadata:r.metadata,authoritativeGatewayUris:[n]}),o=yield Ct.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Ct.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 Lt(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 Lt(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 Lt(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=Ct.parseTxtDataToString(d.data);c.alsoKnownAs=h.split(ar);break}case f.startsWith("cnt"):{let h=Ct.parseTxtDataToString(d.data);c.controller=h.includes(ar)?h.split(ar):h;break}case f.startsWith("k"):{let{id:h,t:p,k:g,c:y,a:x}=Ct.parseTxtDataToObject(d.data),S=ne.base64Url(g).toUint8Array(),I=ur[Number(p)],A=yield Ct.keyConverter(I).bytesToPublicKey({publicKeyBytes:S});A.alg=x||J_[Number(p)];let O=f==="k0"?"0":h!==void 0?h:yield we({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=Ct.parseTxtDataToObject(d.data),{id:p,t:g,se:y}=h,x=z_(h,["id","t","se"]),S=y.includes(ar)?y.split(ar):[y],I=Object.fromEntries(Object.entries(x).map(([A,O])=>[A,O.includes(ar)?O.split(ar):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}=Ct.parseTxtDataToObject(d.data);a.types=h.split(ar).map(p=>Number(p));break}case f.startsWith("did"):{let h=I=>I.split(ar).map(A=>u.get(A)).filter(A=>typeof A=="string"),{auth:p,asm:g,del:y,inv:x,agm:S}=Ct.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 Lt(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 Ct.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:cs,data:`id=${A};s=${I}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:cs,data:r.alsoKnownAs.join(ar)}),r.controller){let I=Array.isArray(r.controller)?r.controller.join(ar):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:cs,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 X_))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=ur[M.crv],j=yield Ct.keyConverter(M.crv).publicKeyToBytes({publicKey:M}),$=ne.uint8Array(j).toBase64Url(),Z=[`t=${q}`,`k=${$}`];T!=="0"&&(yield we({jwk:M}))!==T&&Z.unshift(`id=${T}`),M.alg!==J_[q]&&Z.push(`a=${M.alg}`),A.controller!==r.id&&Z.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:cs,data:Z.join(Pp)})}(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=z_(I,["id","type","serviceEndpoint"]);T=$r(T),q=Array.isArray(q)?q.join(","):q;let Z=Object.entries(Object.assign({id:T,t:M,se:q},j)).map(([G,_])=>`${G}=${_}`).join(Pp),Q=Ct.chunkDataIfNeeded(Z);f.push({type:"TXT",name:`_${O}._did.`,ttl:cs,data:Q})});let x=[`v=${UC}`];if(y.length&&x.push(`vm=${y.join(ar)}`),Object.keys($i).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=yb[I];x.push(`${T}=${O.join(ar)}`)}}),g.length&&x.push(`svc=${g.join(ar)}`),!((d=n.types)===null||d===void 0)&&d.length){let A=n.types.map(O=>typeof O=="string"?pb[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:cs,data:`id=${A.join(ar)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:cs,data:x.join(Pp)});for(let I of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:cs,data:I+"."});return{id:0,type:"response",flags:F_,answers:[...f,...h]}})}static getUniqueDidSuffix(e){return e.split(":")[2]}},Ct=class t{static createBep44PutMessage(e){return Lt(this,arguments,void 0,function*({dnsPacket:r,publicKeyBytes:n,signer:i}){let o=Math.ceil(Date.now()/1e3),s=df(r),c=ob.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 Lt(this,arguments,void 0,function*({didUri:r}){let n=t.identifierToIdentityKeyBytes({didUri:r});return yield Bt.bytesToPublicKey({publicKeyBytes:n})})}static identifierToIdentityKeyBytes({didUri:e}){let r=xe.parse(e);if(!r)throw new re(ie.InvalidDid,`Invalid DID URI: ${e}`);if(r.method!==ff.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 Lt(this,arguments,void 0,function*({identityKey:r}){let n=yield Bt.publicKeyToBytes({publicKey:r}),i=ne.uint8Array(n).toBase32Z();return`did:${ff.methodName}:${i}`})}static keyConverter(e){let n={Ed25519:Bt,"P-256":{publicKeyToBytes:i=>Lt(this,[i],void 0,function*({publicKey:o}){let s=yield Ft.publicKeyToBytes({publicKey:o});return yield Ft.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Ft.bytesToPublicKey,privateKeyToBytes:Ft.privateKeyToBytes,bytesToPrivateKey:Ft.bytesToPrivateKey},secp256k1:{publicKeyToBytes:i=>Lt(this,[i],void 0,function*({publicKey:o}){let s=yield Nt.publicKeyToBytes({publicKey:o});return yield Nt.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Nt.bytesToPublicKey,privateKeyToBytes:Nt.privateKeyToBytes,bytesToPrivateKey:Nt.bytesToPrivateKey},X25519:za}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static parseBep44GetMessage(e){return Lt(this,arguments,void 0,function*({bep44Message:r}){let n=yield Bt.bytesToPublicKey({publicKeyBytes:r.k}),i=ob.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!(yield Bt.verify({key:n,signature:r.sig,data:i})))throw new re(ie.InvalidSignature,"Invalid signature for DHT BEP44 message");return Lp(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(Pp).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 Lt(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 Bt.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 Pe=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var bX=new Uint8Array(0);var gb=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 mb=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")}},wb=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 Z_(this,e)}},bb=class{constructor(e){this.decoders=e}or(e){return Z_(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`)}},Z_=(t,e)=>new bb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),xb=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new mb(e,r,n),this.decoder=new wb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},OC=({name:t,prefix:e,encode:r,decode:n})=>new xb(t,e,r,n);var DC=(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},kC=(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},lf=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>OC({prefix:e,name:t,encode(i){return kC(i,n,r)},decode(i){return DC(i,n,r,t)}});var UX=lf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),OX=lf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),hf=lf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),DX=lf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vr=class t{static encode(e){return hf.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Pe(Ye.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return hf.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 uI=Kn(eI(),1);l();l();var Eb;(function(t){t.Public="public",t.Private="private"})(Eb||(Eb={}));var Vr=Eb;var Ut=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===Vr.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Pe(Ye.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Pe(Ye.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Pe(Ye.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===Vr.Private&&(e.d===void 0||e.d.length!==43))throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Pe(Ye.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!vr.isBase64UrlString(e))throw new Pe(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 Pe(Ye.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var pf=class{};pf.hashAlgorithmInMultihashCode=18;pf.maxCanonicalizedDeltaSizeInBytes=1e3;var dr=pf;l();var nI=Kn(rI(),1);var Nn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=nI.default(r);return vr.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 NC=sI,iI=128,CC=127,LC=~CC,PC=Math.pow(2,31);function sI(t,e,r){e=e||[],r=r||0;for(var n=r;t>=PC;)e[r++]=t&255|iI,t/=128;for(;t&LC;)e[r++]=t&255|iI,t>>>=7;return e[r]=t|0,sI.bytes=r-n+1,e}var MC=vb,KC=128,oI=127;function vb(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw vb.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&oI)<<i:(s&oI)*Math.pow(2,i),i+=7}while(s>=KC);return vb.bytes=o-n,r}var $C=Math.pow(2,7),HC=Math.pow(2,14),VC=Math.pow(2,21),qC=Math.pow(2,28),FC=Math.pow(2,35),jC=Math.pow(2,42),WC=Math.pow(2,49),GC=Math.pow(2,56),zC=Math.pow(2,63),YC=function(t){return t<$C?1:t<HC?2:t<VC?3:t<qC?4:t<FC?5:t<jC?6:t<WC?7:t<GC?8:t<zC?9:10},JC={encode:NC,decode:MC,encodingLength:YC},XC=JC,yf=XC;var Sb=(t,e=0)=>[yf.decode(t,e),yf.decode.bytes],Ab=(t,e,r=0)=>(yf.encode(t,e,r),e),Tb=t=>yf.encodingLength(t);var _b=(t,e)=>{let r=e.byteLength,n=Tb(t),i=n+Tb(r),o=new Uint8Array(i+r);return Ab(t,o,0),Ab(r,o,n),o.set(e,i),new $p(t,r,e,o)},cI=t=>{let e=gb(t),[r,n]=Sb(e),[i,o]=Sb(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new $p(r,i,s,e)};var $p=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var Bb=({name:t,code:e,encode:r})=>new Ib(t,e,r),Ib=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?_b(this.code,r):r.then(n=>_b(this.code,n))}else throw Error("Unknown type, must be binary type")}};var aI=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Hp=Bb({name:"sha2-256",code:18,encode:aI("SHA-256")}),lZ=Bb({name:"sha2-512",code:19,encode:aI("SHA-512")});var gf=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())})},Pt=class t{static hash(e,r){return gf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Hp.digest(e)).bytes;break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return gf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Hp.encode(e);break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return gf(this,void 0,void 0,function*(){let n=Nn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return gf(this,void 0,void 0,function*(){let n=Nn.canonicalizeAsBytes(e),i=yield t.hashAsNonMultihashBytes(n,r);return yield t.hashThenEncode(i,r)})}static hashThenEncode(e,r){return gf(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return vr.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=vr.decodeAsBytes(e,r);try{n=cI(i)}catch{throw new Pe(Ye.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=dr.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var Rb;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(Rb||(Rb={}));var mf=Rb;l();var Ub;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(Ub||(Ub={}));var wc=Ub;var Vp=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())})},as=class t{static createCreateRequest(e){return Vp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;Ut.validateEs256kOperationKey(r,Vr.Public),Ut.validateEs256kOperationKey(n,Vr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=dr.hashAlgorithmInMultihashCode,c=[{action:wc.Replace,document:e.document}],a={updateCommitment:yield Pt.canonicalizeThenDoubleHashThenEncode(n,s),patches:c};t.validateDeltaSize(a);let d={deltaHash:yield Pt.canonicalizeThenHashThenEncode(a,s),recoveryCommitment:yield Pt.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:mf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Vp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Ut.validateEs256kOperationKey(e.recoveryPublicKey,Vr.Public);let r=dr.hashAlgorithmInMultihashCode,n=yield Pt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},o=yield e.signer.sign({alg:"ES256K"},i);return{type:mf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return Vp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Ut.validateEs256kOperationKey(e.recoveryPublicKey,Vr.Public),Ut.validateEs256kOperationKey(e.nextRecoveryPublicKey,Vr.Public),Ut.validateEs256kOperationKey(e.nextUpdatePublicKey,Vr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=dr.hashAlgorithmInMultihashCode,n=yield Pt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:wc.Replace,document:e.document}],o=yield Pt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:o},c=yield Pt.canonicalizeThenHashThenEncode(s,r),u={recoveryCommitment:yield Pt.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:c},d=yield e.signer.sign({alg:"ES256K"},u);return{type:mf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return Vp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),Ut.validateEs256kOperationKey(e.updatePublicKey,Vr.Public),Ut.validateEs256kOperationKey(e.nextUpdatePublicKey,Vr.Public),t.validateServices(e.servicesToAdd),t.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let g of e.idsOfServicesToRemove)Ut.validateId(g);if(e.idsOfPublicKeysToRemove!==void 0)for(let g of e.idsOfPublicKeysToRemove)Ut.validateId(g);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let g={action:wc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:wc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:wc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:wc.RemovePublicKeys,ids:s};r.push(g)}let c=dr.hashAlgorithmInMultihashCode,a=yield Pt.canonicalizeThenHashThenEncode(e.updatePublicKey,c),u=yield Pt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,c),d={patches:r,updateCommitment:u},f=yield Pt.canonicalizeThenHashThenEncode(d,c),h={updateKey:e.updatePublicKey,deltaHash:f},p=yield e.signer.sign({alg:"ES256K"},h);return{type:mf.Update,didSuffix:e.didSuffix,revealValue:a,delta:d,signedData:p}})}static validateDidSuffix(e){Pt.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 Pe(Ye.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Ut.validateId(n.id),r.has(n.id))throw new Pe(Ye.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),Ut.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 Pe(Ye.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){Ut.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 Pe(Ye.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Pe(Ye.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&uI.parse(e.serviceEndpoint).error!==void 0)throw new Pe(Ye.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=Nn.canonicalizeAsBytes(e);if(r.length>dr.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${dr.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Pe(Ye.DeltaExceedsMaximumSize,n)}}};var dI=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())})},iu=class t{static createLongFormDid(e){return dI(this,void 0,void 0,function*(){let r=yield as.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;dr.network===void 0||dr.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${dr.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=Nn.canonicalizeAsBytes(o),c=vr.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return dI(this,void 0,void 0,function*(){let r=Nn.canonicalizeAsBytes(e),n=yield Pt.hash(r,dr.hashAlgorithmInMultihashCode);return vr.encode(n)})}};l();l();var fI;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(fI||(fI={}));l();var lI;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(lI||(lI={}));l();var us=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())})},pi;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(pi||(pi={}));var eL={Ed25519:pi.Ed25519,ES256K:pi.secp256k1,ES256:pi.secp256r1,"P-256":pi.secp256r1,secp256k1:pi.secp256k1,secp256r1:pi.secp256r1},hI="https://ion.tbd.engineering",Ob=class t extends hn{static create(){return us(this,arguments,void 0,function*({keyManager:e=new tr,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in eL)))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:pi.secp256k1}),g=yield e.getPublicKey({keyUri:p}),y=yield e.generateKey({algorithm:pi.secp256k1}),x=yield e.getPublicKey({keyUri:y}),S=yield bc.computeLongFormDidUri({recoveryKey:g,updateKey:x,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 xr({uri:S,document:I,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 us(this,arguments,void 0,function*({didDocument:r,methodId:n}){var i;let o=xe.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 us(this,arguments,void 0,function*({portableDid:r,keyManager:n=new tr}){let i=xe.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield xr.import({portableDid:r,keyManager:n})})}static publish(e){return us(this,arguments,void 0,function*({did:r,gatewayUri:n=hI}){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:m_({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield bc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield bc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=bc.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 us(this,arguments,void 0,function*(r,n={}){var i,o;let s=xe.parse(r);if(!s)return Object.assign(Object.assign({},gt),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},gt),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:hI;try{let a=bc.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({},gt),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({},gt),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};Ob.methodName="ion";var bc=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 us(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 iu.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return us(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield as.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return us(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 we({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 qp=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())})},Db=class t extends hn{static create(){return qp(this,arguments,void 0,function*({keyManager:e=new tr,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 xr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return qp(this,arguments,void 0,function*({didDocument:r}){var n;let i=xe.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 qp(this,arguments,void 0,function*({portableDid:r,keyManager:n=new tr}){let i=xe.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield xr.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 qp(this,void 0,void 0,function*(){let n=xe.parse(e),i;try{i=ne.base64Url(n.id).toObject()}catch{}if(!n||!i)return Object.assign(Object.assign({},gt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},gt),{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({},gt),{didDocument:o})})}};Db.methodName="jwk";l();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())})},uo;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(uo||(uo={}));var kb={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"},tL={Ed25519:uo.Ed25519,ES256K:uo.secp256k1,ES256:uo.secp256r1,"P-256":uo.secp256r1,secp256k1:uo.secp256k1,secp256r1:uo.secp256r1,X25519:uo.X25519},Nb=class t extends hn{static create(){return Cn(this,arguments,void 0,function*({keyManager:e=new tr,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 Sr.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new xr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return Cn(this,arguments,void 0,function*({didDocument:r}){var n;let i=xe.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 Cn(this,arguments,void 0,function*({portableDid:r,keyManager:n=new tr}){let i=xe.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield xr.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 Cn(this,void 0,void 0,function*(){try{let n=yield t.createDocument({didUri:e,options:r});return Object.assign(Object.assign({},gt),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},gt),{didResolutionMetadata:Object.assign({error:n.code},n.message&&{errorMessage:n.message})})}})}static createDocument(e){return Cn(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=xe.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 g_({didDocument:a}).forEach(g=>{let y=kb[g];h.push(y)}),a["@context"]=h,a})}static createEncryptionMethod(e){return Cn(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=Sr.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=Zw({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 kb))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 Sr.multicodecToJwk({code:u});c.publicKeyJwk=yield Sr.keyConverter(g).bytesToPublicKey({publicKeyBytes:a})}return c})}static createSignatureMethod(e){return Cn(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}=Qw({multibaseKeyId:n}),f=a.byteLength,h=Sr.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 Nt.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":p=yield Bt.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 kb))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 Sr.multicodecToJwk({code:u});c.publicKeyJwk=yield Sr.keyConverter(y).bytesToPublicKey({publicKeyBytes:a})}return c})}static deriveEncryptionKey(e){return Cn(this,arguments,void 0,function*({multibaseValue:r}){let n={keyBytes:new Uint8Array,multicodecCode:0},{keyBytes:i,multicodecCode:o}=Qw({multibaseKeyId:r});if(o===237){let s=yield Sr.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield Bt.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield Sr.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&&la(n)==="String"&&n.startsWith("z")}};Nb.methodName="key";var Sr=class t{static jwkToMulticodec(e){return Cn(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:Xt.getCodeFromName({name:o}),name:o}})}static keyCompressor(e){let n={"P-256":Ft.compressPublicKey,secp256k1:Nt.compressPublicKey}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static keyConverter(e){let n={Ed25519:Bt,"P-256":Ft,secp256k1:Nt,X25519:za}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static multicodecToJwk(e){return Cn(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?Xt.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 Cn(this,arguments,void 0,function*({publicKey:r}){var n;if(!(r?.crv&&r.crv in tL))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 Zw({keyBytes:i,multicodecName:o})})}};Sr.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"};Sr.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};Sr.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 rL=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())})},Cb=class t extends hn{static resolve(e,r){return rL(this,void 0,void 0,function*(){let n=xe.parse(e);if(!n)return Object.assign(Object.assign({},gt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},gt),{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({},gt),{didDocument:c})}catch{return Object.assign(Object.assign({},gt),{didResolutionMetadata:{error:"notFound"}})}})}};Cb.methodName="web";l();var aL=Kn(yI(),1),uL=Kn(dm(),1);l();l();var tt=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 capabilityInvocationEntry(e,r){let n=t.relationshipMethodId(r,e.id);if(n!==void 0)return e.capabilityInvocation?.find(i=>t.relationshipMethodId(i,e.id)===n)}static verificationMethodOfEntry(e,r){if(t.isDidVerificationMethod(r))return r;let n=t.absoluteDidUrl(r,e.id);if(n!==void 0)return e.verificationMethod?.find(i=>t.absoluteDidUrl(i?.id,e.id)===n)}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 Ve("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys($i).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=e.split(":");if(n.length!==4)throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let[i,o,s,c]=n;if(!i||i!=="urn")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!o||o!=="zcap")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!s||s!=="root")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let u=decodeURIComponent(c);return r.id=e,r.controller=u,r.invocationTarget=u,r}};l();l();l();l();l();l();l();function gI(t,e,r){return t&e^~t&r}function mI(t,e,r){return t&e^t&r^e&r}var jp=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=Ml(this.buffer)}update(e){ca(this),_e(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=Ml(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){ca(this),Wv(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=Ml(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()}},fo=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var dL=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]),ds=new Uint32Array(64),Lb=class extends jp{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)ds[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ds[f-15],p=ds[f-2],g=vn(h,7)^vn(h,18)^h>>>3,y=vn(p,17)^vn(p,19)^p>>>10;ds[f]=y+ds[f-7]+g+ds[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=vn(c,6)^vn(c,11)^vn(c,25),p=d+h+gI(c,a,u)+dL[f]+ds[f]|0,y=(vn(n,2)^vn(n,13)^vn(n,22))+mI(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(ds)}destroy(){this.set(0,0,0,0,0,0,0,0),Ns(this.buffer)}},Pb=class extends Lb{A=fo[0]|0;B=fo[1]|0;C=fo[2]|0;D=fo[3]|0;E=fo[4]|0;F=fo[5]|0;G=fo[6]|0;H=fo[7]|0;constructor(){super(32)}};var Wp=zv(()=>new Pb,Yv(1));l();l();var fr=BigInt(0),rr=BigInt(1),Ec=BigInt(2),xI=BigInt(3),EI=BigInt(4),vI=BigInt(5),fL=BigInt(7),SI=BigInt(8),lL=BigInt(9),AI=BigInt(16);function Ln(t,e){let r=t%e;return r>=fr?r:e+r}function qr(t,e,r){let n=t;for(;e-- >fr;)n*=n,n%=r;return n}function wI(t,e){if(t===fr)throw new Error("invert: expected non-zero number");if(e<=fr)throw new Error("invert: expected positive modulus, got "+e);let r=Ln(t,e),n=e,i=fr,o=rr,s=rr,c=fr;for(;r!==fr;){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!==rr)throw new Error("invert: does not exist");return Ln(i,e)}function Kb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function TI(t,e){let r=(t.ORDER+rr)/EI,n=t.pow(e,r);return Kb(t,n,e),n}function hL(t,e){let r=(t.ORDER-vI)/SI,n=t.mul(e,Ec),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,Ec),i),c=t.mul(o,t.sub(s,t.ONE));return Kb(t,c,e),c}function pL(t){let e=au(t),r=_I(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+fL)/AI;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 Kb(c,x,a),x}}function _I(t){if(t<xI)throw new Error("sqrt is not defined for small field");let e=t-rr,r=0;for(;e%Ec===fr;)e/=Ec,r++;let n=Ec,i=au(t);for(;bI(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return TI;let o=i.pow(n,e),s=(e+rr)/Ec;return function(a,u){if(a.is0(u))return u;if(bI(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=rr<<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 yL(t){return t%EI===xI?TI:t%SI===vI?hL:t%AI===lL?pL(t):_I(t)}var gL=["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=gL.reduce((n,i)=>(n[i]="function",n),e);return nd(t,r),t}function mL(t,e,r){if(r<fr)throw new Error("invalid exponent, negatives unsupported");if(r===fr)return t.ONE;if(r===rr)return e;let n=t.ONE,i=e;for(;r>fr;)r&rr&&(n=t.mul(n,i)),i=t.sqr(i),r>>=rr;return n}function Gp(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 bI(t,e){let r=(t.ORDER-rr)/Ec,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 wL(t,e){e!==void 0&&Jn(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Mb=class{ORDER;BITS;BYTES;isLE;ZERO=fr;ONE=rr;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=fr)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}=wL(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 Ln(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return fr<=e&&e<this.ORDER}is0(e){return e===fr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&rr)===rr}neg(e){return Ln(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Ln(e*e,this.ORDER)}add(e,r){return Ln(e+r,this.ORDER)}sub(e,r){return Ln(e-r,this.ORDER)}mul(e,r){return Ln(e*r,this.ORDER)}pow(e,r){return mL(this,e,r)}div(e,r){return Ln(e*wI(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 wI(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=yL(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?J0(e,this.BYTES):$l(e,this.BYTES)}fromBytes(e,r=!1){_e(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?Y0(e):Co(e);if(c&&(a=Ln(a,s)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Gp(this,e)}cmov(e,r,n){return n?r:e}};function au(t,e={}){return new Mb(t,e)}function II(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 Hb(t){let e=II(t);return e+Math.ceil(e/2)}function zp(t,e,r=!1){_e(t);let n=t.length,i=II(e),o=Hb(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?Y0(t):Co(t),c=Ln(s,e-rr)+rr;return r?J0(c,i):$l(c,i)}var uu=BigInt(0),vc=BigInt(1);function wf(t,e){let r=e.negate();return t?r:e}function jb(t,e){let r=Gp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function OI(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Vb(t,e){OI(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=rd(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function BI(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+=vc);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 qb=new WeakMap,DI=new WeakMap;function Fb(t){return DI.get(t)||1}function RI(t){if(t!==uu)throw new Error("invalid wNAF")}var Yp=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>uu;)r&vc&&(n=n.add(i)),i=i.double(),r>>=vc;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Vb(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=Vb(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=BI(n,c,s);n=a,d?o=o.add(wf(h,r[p])):i=i.add(wf(f,r[u]))}return RI(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Vb(e,this.bits);for(let s=0;s<o.windows&&n!==uu;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=BI(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return RI(n),i}getPrecomputes(e,r,n){let i=qb.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),qb.set(r,i))),i}cached(e,r,n){let i=Fb(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Fb(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){OI(r,this.bits),DI.set(e,r),qb.delete(e)}hasCache(e){return Fb(e)!==1}};function kI(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>uu||n>uu;)r&vc&&(o=o.add(i)),n&vc&&(s=s.add(i)),i=i.double(),r>>=vc,n>>=vc;return{p1:o,p2:s}}function UI(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 au(t,{isLE:r})}function NI(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>uu))throw new Error(`CURVE.${a} must be positive bigint`)}let i=UI(e.p,r.Fp,n),o=UI(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 Jp(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var Xp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(Pl(e),_e(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 ca(this),this.iHash.update(e),this}digestInto(e){ca(this),_e(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash: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()}},Wb=(t,e,r)=>new Xp(t,e).update(r).digest();Wb.create=(t,e)=>new Xp(t,e);var CI=(t,e)=>(t+(t>=0?e:-e)/LI)/e;function bL(t,e,r){let[[n,i],[o,s]]=e,c=CI(s*t,r),a=CI(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<lo,h=d<lo;f&&(u=-u),h&&(d=-d);let p=rd(Math.ceil(X0(r)/2))+du;if(u<lo||u>=p||d<lo||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function zb(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Gb(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return ed(r.lowS,"lowS"),ed(r.prehash,"prehash"),r.format!==void 0&&zb(r.format),r}var Yb=class extends Error{constructor(e=""){super(e)}},fs={Err:Yb,_tlv:{encode:(t,e)=>{let{Err:r}=fs;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=td(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?td(i.length/2|128):"";return td(t)+o+i+e},decode(t,e){let{Err:r}=fs,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}=fs;if(t<lo)throw new e("integer: negative integers are not allowed");let r=td(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}=fs;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 Co(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=fs,i=_e(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}=fs,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},lo=BigInt(0),du=BigInt(1),LI=BigInt(2),Zp=BigInt(3),xL=BigInt(4);function PI(t,e={}){let r=NI("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;nd(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=KI(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:E,y:U}=_.toAffine(),L=n.toBytes(E);if(ed(D,"isCompressed"),D){d();let N=!n.isOdd(U);return yr(MI(N),L)}else return yr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){_e(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===_&&(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=${_} 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 x(G,_){let D=n.sqr(_),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,Zp),xL),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 bL(G,a.basises,i.ORDER)}let M=Z0((G,_)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(E,_),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=Z0(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(!x(_,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,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=wf(E,_),D=wf(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,E){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:E}=_||{};if(!_||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(_e(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(Ls(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Zp),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:E,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(E,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,E=n.mul(D,Zp),{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(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(_,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:E,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,Zp),W=n.mul(D,L),Y=n.mul(E,N),X=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,X),ee=n.sub(ee,ce),ce=n.add(E,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,X),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,X),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),X=n.mul(J,X),ee=n.mul(z,ee),Y=n.add(Y,X),X=n.sub(W,X),X=n.mul(J,X),ee=n.add(ee,X),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 E,U,L=N=>Q.cached(this,N,R=>jb($,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),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);E=N,U=R}return jb($,[E,U])[0]}multiplyUnsafe(_){let{endo:D}=e,E=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===lo||E.is0())return $.ZERO;if(_===du)return E;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=kI($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,_)}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===du?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===du?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return ed(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Cs(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Z=i.BITS,Q=new Yp($,e.endo?Math.ceil(Z/2):Z);return $.BASE.precompute(8),$}function MI(t){return Uint8Array.of(t?2:3)}function KI(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function EL(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ps,i=Object.assign(KI(t.Fp,r),{seed:Hb(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 zp(_e(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(!Qu(p)||"_lengths"in r&&r._lengths||g===y)return;let S=_e(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=Jp(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function $I(t,e,r={}){Pl(e),nd(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)=>Wb(e,D,E)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=EL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*LI<o.ORDER;function x(D){let E=c>>du;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 I(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,E){zb(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return _e(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(I(),![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}=fs.toSig(_e(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(yr(MI((N&1)===0),C)),V=s.inv(R),J=M(_e(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(zb(E),E==="der")return Ls(fs.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return E==="recovered"?(I(),yr(Uint8Array.of(this.assertRecovery()),N,R)):yr(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=Co(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=rd(a);function j(D){return Qv("num < 2^"+a,D,lo,q),s.toBytes(D)}function $(D,E){return _e(D,void 0,"message"),E?_e(e(D),void 0,"prehashed message"):D}function Z(D,E,U){let{lowS:L,prehash:N,extraEntropy:R}=Gb(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(_e(Y,void 0,"extraEntropy"))}let J=yr(...V),z=C;function W(Y){let X=T(Y);if(!s.isValidNot0(X))return;let ue=s.inv(X),ee=t.BASE.multiply(X).toAffine(),ce=s.create(ee.x);if(ce===lo)return;let Oe=s.create(ue*s.create(z+ce*P));if(Oe===lo)return;let Me=(ee.x===ce?0:2)|Number(ee.y&du),Je=Oe;return L&&x(Oe)&&(Je=s.neg(Oe),Me^=1),new O(ce,Je,y?void 0:Me)}return{seed:J,k2sig:W}}function Q(D,E,U={}){let{seed:L,k2sig:N}=Z(D,E,U);return e1(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=Gb(L,g);if(U=_e(U,void 0,"publicKey"),E=$(E,R),!Qu(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),X=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(X).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,E,U={}){let{prehash:L}=Gb(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:_,Signature:O,hash:e})}var ty={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},vL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},SL=BigInt(0),Jb=BigInt(2);function AL(t){let e=ty.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=qr(d,r,e)*d%e,h=qr(f,r,e)*d%e,p=qr(h,Jb,e)*u%e,g=qr(p,i,e)*p%e,y=qr(g,o,e)*g%e,x=qr(y,c,e)*y%e,S=qr(x,a,e)*x%e,I=qr(S,c,e)*y%e,A=qr(I,r,e)*d%e,O=qr(A,s,e)*g%e,T=qr(O,n,e)*u%e,M=qr(T,Jb,e);if(!Qp.eql(Qp.sqr(M),t))throw new Error("Cannot find square root");return M}var Qp=au(ty.p,{sqrt:AL}),Sc=PI(ty,{Fp:Qp,endo:vL}),pn=$I(Sc,Wp),HI={};function ey(t,...e){let r=HI[t];if(r===void 0){let n=Wp(Zv(t));r=yr(n,n),HI[t]=r}return Wp(yr(r,...e))}var Zb=t=>t.toBytes(!0).slice(1),Qb=t=>t%Jb===SL;function Xb(t){let{Fn:e,BASE:r}=Sc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:Qb(i.y)?n:e.neg(n),bytes:Zb(i)}}function qI(t){let e=Qp;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);Qb(i)||(i=e.neg(i));let o=Sc.fromAffine({x:t,y:i});return o.assertValidity(),o}var bf=Co;function FI(...t){return Sc.Fn.create(bf(ey("BIP0340/challenge",...t)))}function VI(t){return Xb(t).bytes}function TL(t,e,r=Ps(32)){let{Fn:n}=Sc,i=_e(t,void 0,"message"),{bytes:o,scalar:s}=Xb(e),c=_e(r,32,"auxRand"),a=n.toBytes(s^bf(ey("BIP0340/aux",c))),u=ey("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Xb(u),h=FI(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!jI(p,i,o))throw new Error("sign: Invalid signature produced");return p}function jI(t,e,r){let{Fp:n,Fn:i,BASE:o}=Sc,s=_e(t,64,"signature"),c=_e(e,void 0,"message"),a=_e(r,32,"publicKey");try{let u=qI(bf(a)),d=bf(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=bf(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=FI(i.toBytes(d),Zb(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!Qb(y)||g!==d)}catch{return!1}}var ry=(()=>{let r=(n=Ps(48))=>zp(n,ty.n);return{keygen:Jp(r,VI),getPublicKey:VI,sign:TL,verify:jI,Point:Sc,utils:{randomSecretKey:r,taggedHash:ey,lift_x:qI,pointToBytes:Zb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function _L(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function GI(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 ex(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function zI(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function tx(t){if(!Array.isArray(t))throw new Error("array expected")}function YI(t,e){if(!GI(!0,e))throw new Error(`${t}: array of strings expected`)}function IL(t,e){if(!GI(!1,e))throw new Error(`${t}: array of numbers expected`)}function BL(...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 RL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;YI("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(tx(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=>(tx(i),i.map(o=>{ex("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function UL(t=""){return ex("join",t),{encode:e=>(YI("join.decode",e),e.join(t)),decode:e=>(ex("join.decode",e),e.split(t))}}function WI(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(tx(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(zI(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 OL(t){zI(t);let e=2**8;return{encode:r=>{if(!_L(r))throw new Error("radix.encode input should be Uint8Array");return WI(Array.from(r),e,t)},decode:r=>(IL("radix.decode",r),Uint8Array.from(WI(r,t,e)))}}var DL=t=>BL(OL(58),RL(t),UL("")),fu=DL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var JI=new Uint8Array([231,1]),ft=class t{#e;#t={prefix:JI,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Br(e);if(!r||r.length!==33)throw new Os("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!pn.utils.isValidPublicKey(r))throw new Os("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 pn.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 Os("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 Mt(this.compressed)}get point(){return{x:this.x,y:this.y}}bip340(){return this.xOnly}decode(){return fu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(JI);return r.push(...e),"z"+fu.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return pn.verify(e,r,this.compressed);if(n.scheme==="schnorr")return ry.verify(e,r,this.x);throw new Os(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return aa(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 XI=new Uint8Array([129,38]),kL=Mt(ke(XI)),Fr=class t{#e;#t;#n;constructor(e){let r=e instanceof Uint8Array,n=typeof e=="bigint";if(!r&&!n)throw new Gn("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<pn.Point.Fn.ORDER&&(this.#e=t.toBytes(e),this.#t=e),!this.#e||this.#e.length!==32)throw new Gn("Invalid bytes: must be a valid 32-byte secret key","CONSTRUCTOR_ERROR");if(!this.#t||this.#t<1n||this.#t>=pn.Point.Fn.ORDER)throw new Gn("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 Mt(this.bytes)}get multibase(){return this.#n}encode(){let e=Array.from(this.bytes),r=Array.from(XI);return r.push(...e),"z"+fu.encode(Uint8Array.from(r))}equals(e){return aa(this.bytes,e.bytes)}computePublicKey(){return new ft(pn.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 pn.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return pn.sign(e,this.bytes);if(r.scheme==="schnorr")return ry.sign(e,this.bytes);throw new Gn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=fu.decode(e.slice(1));if(r.length!==34)throw new Gn("Invalid argument: must be 34 byte secretKeyMultibase","DECODE_MULTIBASE_ERROR");let n=r.slice(0,2);if(Mt(ke(n))!==kL)throw new Gn(`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(!pn.utils.isValidSecretKey(r))throw new Gn("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=Rr(32);while(!pn.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var ho=class t{#e;#t;constructor(e={}){if(!e.publicKey&&!e.secretKey)throw new xn("Argument missing: must at least provide a publicKey","CONSTRUCTOR_ERROR");if(e.secretKey instanceof Uint8Array?this.#e=new Fr(e.secretKey):e.secretKey instanceof Fr&&(this.#e=e.secretKey),e.publicKey instanceof ft?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new ft(e.publicKey):this.#t=this.#e.computePublicKey(),this.#e&&e.publicKey){let r=this.#e.computePublicKey();if(!this.#t.equals(r))throw new xn("Public key does not match secret key","CONSTRUCTOR_ERROR")}}get secretKey(){if(!this.#e)throw new xn("Secret key not available","SECRET_KEY_ERROR");if(!this.#e.isValid())throw new xn("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 xn("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 xn("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:Fr.fromJSON(e.secretKey),publicKey:ft.fromJSON(e.publicKey)})}static fromSecret(e){let r=typeof e=="string"?Br(e):e;if(r.length!==32)throw new xn("Invalid arg: must be 32 byte secret key","FROM_SECRET_KEY_ERROR");let n=new Fr(r),i=n.computePublicKey();return new t({secretKey:n,publicKey:i})}static fromBigInt(e){let r=Fr.fromBigInt(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}static toHex(e){return Mt(e)}static equals(e,r){return e.publicKey.equals(r.publicKey)}static generate(){let e=Fr.random(),r=new Fr(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}};l();l();l();l();var ZI=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],Ac="Multikey",Tc="zQ3s",nr="did:btcr2:_",NL="",QI=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function eB(t){if(!tt.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===Ac&&typeof r=="string"&&r.startsWith(Tc)}var ny=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==Ac)throw new Ve(`Invalid verification method: type must be "${Ac}"`,qe,{id:e,type:r});if(typeof i!="string"||!i.startsWith(Tc))throw new Ve(`Invalid verification method: publicKeyMultibase must start with "${Tc}"`,qe,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},jr=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 Ve("DID Document must have an id",qe,e);let r=e.id.includes("k1")?tn.KEY:tn.EXTERNAL,n=e.id===nr,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new Ve(`Invalid id: ${i}`,qe,e);if(!t.isValidVerificationMethods(o))throw new Ve("Invalid verificationMethod: "+o,qe,e);if(!t.isValidServices(s))throw new Ve("Invalid service: "+s,qe,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===tn.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 ny({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 Ve('Invalid "@context"',qe,e);if(!this.isValidId(e?.id))throw new Ve('Invalid "id"',qe,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new Ve('Invalid "verificationMethod"',qe,e);if(!this.isValidServices(e?.service))throw new Ve('Invalid "service"',qe,e);if(!this.isValidVerificationRelationships(e))throw new Ve("Invalid verification relationships",qe,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:ZI.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return lr.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(eB)}static isValidServices(e){return Array.isArray(e)&&e.every(w_)}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"||tt.isDidVerificationMethod(c))})}static validate(e){return e.id===nr?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==nr)throw new Ve("Invalid GenesisDocument ID",qe,this);if(!this.verificationMethod.every(e=>e.id.includes(nr)&&e.controller===nr))throw new Ve("Invalid GenesisDocument verificationMethod",qe,this);if(!this.service.every(e=>e.id.includes(nr)))throw new Ve("Invalid GenesisDocument service",qe,this);if(!t.isValidVerificationRelationships(this))throw new Ve("Invalid GenesisDocument assertionMethod",qe,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new Ve("Cannot convert a key identifier to an intermediate document",qe,this);return new lu(this)}},lu=class t extends jr{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(nr,e),n=JSON.parse(r);return new jr(n)}static fromDidDocument(e){let r=ks.cloneReplace(e,QI,nr);return new t(r)}static create(e,r,n){return new t({id:nr,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ft(e),i=nr,o=Ni(n.compressed,No(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 Do(Kt(e))}};var tB="did:btcr2:",lr=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in tn))throw new ut('Expected "idType" to be "KEY" or "EXTERNAL"',pt,{idType:n});if(i!==1)throw new ut('Expected "version" to be 1',pt,{version:i});if(typeof o!="string")throw new ut('Expected "network" to be a known network name',pt,{network:o});let s=ia[o];if(typeof s!="number")throw new ut('Invalid "network" name',pt,{network:o});if(n==="KEY")try{new ft(e)}catch{throw new ut('Expected "genesisBytes" to be a valid compressed secp256k1 public key',pt,{genesisBytes:e})}else if(e.length!==32)throw new ut('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`${tB}${As.encodeFromBytes(c,u)}`}static decode(e){let r=e.split(":");if(r.length!==3)throw new ut(`Invalid did: ${e}`,pt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new ut(`Invalid did: ${e}`,pt,{identifier:e});if(i!=="btcr2")throw new ut(`Invalid did method: ${i}`,Sl,{identifier:e});if(!o)throw new ut(`Invalid method-specific id: ${e}`,pt,{identifier:e});if(o!==o.toLowerCase())throw new ut(`Invalid method-specific id (must be lowercase): ${e}`,pt,{identifier:e});let s,c;try{({prefix:s,bytes:c}=As.decodeToBytes(o))}catch(g){let y=g instanceof Error?g.message:String(g);throw new ut(`Invalid method-specific id (Bech32m decoding failed: ${y}): ${e}`,pt,{identifier:e,reason:y})}if(!["x","k"].includes(s))throw new ut(`Invalid hrp: ${s}`,pt,{identifier:e});if(!c||c.length<1)throw new ut(`Failed to decode id: ${o}`,pt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new ut(`Invalid btcr2_version (expected 0): ${u}`,pt,{identifier:e});let d=1,f=c[0]&15,h=ia[f];if(typeof h!="string"){let g=f>=12?"custom network not supported":"reserved";throw new ut(`Invalid network (${g}): ${f}`,pt,{identifier:e})}let p=c.slice(1);if(a==="KEY")try{new ft(p)}catch{throw new ut(`Invalid genesisBytes: ${p}`,pt,{identifier:e})}else if(p.length!==32)throw new ut(`Invalid genesisBytes: ${p}`,pt,{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,I={})=>(n.push({name:x,ok:!1,detail:S}),{did:e,valid:!1,...I,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 "${tB}" 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}=As.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"?tn.KEY:tn.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=ia[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===tn.KEY){try{new ft(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(!Eo(x,g))return o("genesisBytesMatch",`The supplied genesis bytes ${ve.encode(x)} do not equal the genesis bytes of the identifier ${ve.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===tn.KEY)return o("genesisDocument","A KEY identifier has no genesis document.",{idType:d,network:p});let S=x.id;if(S!==nr)return o("genesisDocument",`The genesis document id must be "${nr}", got ${JSON.stringify(S)}.`,{idType:d,network:p});try{lu.fromJSON(x)}catch(A){return o("genesisDocument",`Invalid genesis document: ${A instanceof Error?A.message:String(A)}`,{idType:d,network:p})}let I=ko(x);if(!Eo(I,g))return o("genesisDocument",`The genesis document hash ${ve.encode(I)} does not equal the genesis bytes ${ve.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=ho.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 ut(`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 ft(n)}static isValid(e){try{return this.decode(e),!0}catch{return!1}}};var ir=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new be("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!tt.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 Jt("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=lr.decode(e),o=No(i.network),s=i.genesisBytes,c=`${e}#initial${r.toUpperCase()}`,u=`bitcoin:${r==="p2tr"?Is(s.slice(1,33),void 0,o).address:r==="p2wpkh"?_s(s,o).address:Ni(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new Jt("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=Ni(r,n).address,s=_s(r,n).address,c=Is(r.slice(1,33),void 0,n).address;if(!o||!s||!c)throw new kt("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 Jt("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 CL=/^6a20([0-9a-f]{64})$/i;function rx(t){if(!t)return null;let e=CL.exec(t.trim());return e?e[1].toLowerCase():null}var nx=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(),o=new Map;for(let s of e){n.set(s,[]);let c=ir.parseBitcoinAddress(s.serviceEndpoint),a=await r.rest.address.getTxs(c);if(!(!a||!a.length))for(let u of a){let d=u.status;if(d.confirmed!==!0)continue;let f=u.vout.slice(-1)[0];if(!f)continue;let h=rx(f.scriptpubkey);if(!h||!await t.spendsFromAddress(u,c,r))continue;let p=i-d.block_height+1,g=await t.mediantime(d.block_hash,r,o);n.get(s)?.push({tx:u,signalBytes:h,blockMetadata:{confirmations:p,height:d.block_height,time:d.block_time,mediantime:g}})}}return n}static async mediantime(e,r,n){let i=n.get(e);if(i!==void 0)return i;let o=await r.rest.block.get({blockhash:e}),s=o?.mediantime;if(typeof s!="number"||!Number.isFinite(s))throw new le(`Block ${e} has no mediantime in the block record of the Bitcoin REST backend.`,Al,{blockhash:e,block:o});return n.set(e,s),s}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=>[ir.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===M0)continue;let d=u.vout.slice(-1)[0];if(!d)continue;let f=rx(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]===P0||!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,mediantime:a.mediantime,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();var _c=Object.freeze(["https://w3id.org/json-ld-patch/v1","https://w3id.org/zcap/v1","https://w3id.org/security/data-integrity/v2","https://btcr2.dev/context/v1"]);function iy(t,e=_c){return Array.isArray(t)&&t.length===e.length&&t.every((r,n)=>r===e[n])}var ix=Object.freeze({op:"add",path:"/deactivated",value:!0});l();l();l();l();l();l();var Dre=new Uint8Array(0);function 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();function LL(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,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<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 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(x+(I-q)),$=x;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 PL=LL,ML=PL,nB=ML;var ox=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")}},sx=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 iB(this,e)}},cx=class{decoders;constructor(e){this.decoders=e}or(e){return iB(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 iB(t,e){return new cx({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var ax=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 ox(e,r,n),this.decoder=new sx(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function KL({name:t,prefix:e,encode:r,decode:n}){return new ax(t,e,r,n)}function ux({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=nB(r,t);return KL({prefix:e,name:t,encode:n,decode:o=>rB(i(o))})}var xf=ux({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Vre=ux({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();function oB(t){return t===void 0?[]:Array.isArray(t)?t:[t]}var hu=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 bn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Oo,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new bn("Domain mismatch: proof.domain !== config.domain",Oo,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new bn("Challenge mismatch options and challenge passed",Oo,{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 bn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Ci,s);if(r&&r!==c.proofPurpose)throw new bn("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",Ci,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new bn("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){let u=oB(i),d=oB(c.domain);if(u.length!==d.length)throw new bn("Domain mismatch: expectedDomain length does not match proof.domain length",Ci,{proof:c,expectedDomain:i});if(!u.every(f=>d.includes(f))||!d.every(f=>u.includes(f)))throw new bn("Domain mismatch: expectedDomain and proof.domain do not match",Ci,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var pu=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new hu(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=xf.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=xf.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 be("Type mismatch: config.type !== this.type",Ci,{config:r,suite:this.#e()});if(r.cryptosuite!==this.cryptosuite)throw new be("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Ci,{config:r,suite:this.#e()});return Kt(e)}generateHash(e,r){let n=ke(Es(e)),i=ke(Es(r)),o=ht(n,i);return ke(o)}proofConfiguration(e){if(e.type!==this.type)throw new Uo("Type mismatch: config.type !== this.type",Oo,{config:e,suite:this.#e()});if(e.cryptosuite!==this.cryptosuite)throw new Uo("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Oo,{config:e,suite:this.#e()});if(e.created&&!Li.isValidXsdDateTime(e.created))throw new Uo('Invalid config: "created" must be a valid XMLSchema DateTime string',Oo,e);return Kt(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new Uo("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Rv,{config:r,suite:this.#e()});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new Uo("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Ci,{config:n,suite:this.#e()});return this.multikey.verify(r,e)}};l();l();l();var po=class t{static type="Multikey";id;controller;#e;#t;constructor({id:e,controller:r,keyPair:n,externalSigner:i}){if(!n)throw new En('Argument missing: "keyPair" required',"CONSTRUCTOR_ERROR");if(!n.publicKey)throw new En('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 En("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 En("Cannot get: no secretKey","PRIVATE_KEY_ERROR")}}toCryptosuite(){return new pu(this)}sign(e){if(this.#t)return this.#t.sign(e,"bip340");if(!this.signer)throw new En("Cannot sign: no secretKey","SIGN_ERROR");return Dr.sign(e,this.secretKey.bytes,Rr(32))}verify(e,r){return Dr.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 Fr(n),o=i.computePublicKey(),s=new ho({publicKey:o,secretKey:i});return new t({id:e,controller:r,keyPair:s})}static fromSigner(e,r,n){let i=new ft(n.publicKey),o=new ho({publicKey:i});return new t({id:e,controller:r,keyPair:o,externalSigner:n})}static fromPublicKey({id:e,controller:r,publicKeyBytes:n}){let i=new ft(n),o=new ho({publicKey:i});return new t({id:e,controller:r,keyPair:o})}static fromVerificationMethod({id:e,controller:r,publicKeyMultibase:n}){if(!n)throw new En("Invalid publicKeyMultibase: cannot be undefined",Tl,{publicKeyMultibase:n});let i=xf.decode(n);if(i.length!==35)throw new En(`Invalid publicKeyMultibase length: ${i.length}`,Tl,{publicKeyMultibase:n});if(i[0]!==231||i[1]!==1)throw new En(`Invalid publicKeyMultibase prefix: expected secp256k1 multicodec [0xe7, 0x01], got [0x${i[0]?.toString(16)??"??"}, 0x${i[1]?.toString(16)??"??"}]`,Tl,{publicKeyMultibase:n});let o=i.slice(2),s=new ho({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();function Ar(t){return t instanceof kt?{type:t.type,message:t.message}:t instanceof Error?{type:t.name,message:t.message}:{type:"unknown",message:String(t)}}var sB=6;function Ef(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $L(t){return Ef(t)&&Object.values(t).every(e=>typeof e=="string")}function HL(t){return Ef(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&Number.isInteger(t.targetVersionId)&&t.targetVersionId>=2&&Ef(t.proof):!1}function VL(t){return Ef(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}function qL(t){if(t===void 0)return sB;if(typeof t=="number"&&Number.isInteger(t)&&t>=1)return t;throw new le(`Invalid resolution option minConf: expected a positive integer (minimum 1), got ${dx(t)}.`,Gu,{minConf:t})}function dx(t){return typeof t=="string"?JSON.stringify(t):String(t)}var FL=/^-?[0-9]+$/;function jL(t){if(t!==void 0){if(typeof t=="string"&&FL.test(t)&&Number.isSafeInteger(Number(t)))return Number(t);throw new le(`Invalid resolution option versionId: expected an ASCII string of an integer, got ${dx(t)}.`,Gu,{versionId:t})}}var WL=/^-?\d{4,}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/,GL=/(Z|[+-]\d{2}:\d{2})$/;function zL(t){if(t!==void 0){if(typeof t=="string"&&WL.test(t)&&Li.isValidXsdDateTime(t)){let e=Date.parse(t);if(Number.isFinite(e))return e}throw new le(`Invalid resolution option versionTime: expected an XML Datetime in UTC without a fraction (for example "2026-07-01T00:00:00Z"), got ${dx(t)}.`,Gu,{versionTime:t})}}var yo=class t{#e;#t;#n;#r;#o;#i;#c=null;#l=new Map;#h=new Set;#d=new Set;#a=[];#p=null;#s=1;#y=[];#g=0;#f;#u;#m=0;#w;constructor(e,r,n,i){if(this.#e=e,this.#o=r,this.#i=n,i?.versionId!==void 0&&i?.versionTime!==void 0)throw new le("Invalid resolution options: versionId and versionTime are mutually exclusive. Pass one of them.",Gu,{versionId:i.versionId,versionTime:i.versionTime});this.#t=jL(i?.versionId),this.#n=zL(i?.versionTime);let o=i?.maxDiscoveryRounds;this.#u=typeof o=="number"&&o>0?o:1/0,this.#w=qL(i?.minConf),i?.genesisDocument&&(this.#c=i.genesisDocument),this.#r=n?"BeaconDiscovery":"GenesisDocument"}static deterministic(e){let r=e.genesisBytes,n=lr.encode(r,e),{multibase:i}=new ft(r),o=ir.generateBeaconServices({id:n,publicKey:r,network:No(e.network),beaconType:"SingletonBeacon"});return new jr({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=ko(r);if(!Eo(e.genesisBytes,n))throw new le("Initial document mismatch: genesisBytes !== genesisDocumentHash",pt,{genesisBytes:en(e.genesisBytes,"hex"),genesisDocumentHash:en(n,"hex")});let i=lr.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(nr,i));return new jr(o)}static sidecarData(e={}){let r=new Map;if(e.updates?.length)for(let o of e.updates)r.set(zn(o,{encoding:"hex"}),o);let n=new Map;if(e.casUpdates?.length)for(let o of e.casUpdates)n.set(zn(o,{encoding:"hex"}),o);let i=new Map;if(e.smtProofs?.length)for(let o of e.smtProofs)i.set(en(ta(o.id,"base64urlnopad"),"hex"),o);return{updateMap:r,casMap:n,smtMap:i}}static confirmDuplicate(e,r){if(!Number.isInteger(e.targetVersionId)||e.targetVersionId<2)throw new le("Invalid duplicate: targetVersionId must be an integer >= 2",fe,{targetVersionId:e.targetVersionId});let{proof:n,...i}=e,o=ko(i),s=r[e.targetVersionId-2];if(s===void 0)throw new le("Invalid duplicate: no applied update in history for targetVersionId",_l,{targetVersionId:e.targetVersionId,historyLength:r.length});if(!Eo(s,o))throw new le("Invalid duplicate: unsigned update hash does not match historical hash",_l,{unsignedUpdateHash:en(o,"hex"),historicalHash:en(s,"hex")})}static decodeUpdateHash(e,r){if(typeof e=="string")try{return ta(e,"base64urlnopad")}catch(n){throw new le(`Invalid update: ${r} does not decode as base64url: ${Ar(n).message}`,fe,{[r]:e,cause:Ar(n)})}throw new le(`Invalid update: ${r} is not a string`,fe,{[r]:e})}static proofInstant(e,r){let n=e[r];if(n!==void 0){if(typeof n=="string"&&GL.test(n)&&Li.isValidXsdDateTime(n)){let i=Date.parse(n);if(Number.isFinite(i))return i}throw new le(`Invalid update: proof.${r} is not an XML Datetime with a timezone`,fe,{[r]:n})}}static checkProofWindow(e,r){let n=t.proofInstant(e,"created"),i=t.proofInstant(e,"expires");if(n!==void 0&&n>r.time*1e3)throw new le("Invalid update: proof.created is after the header time of the block that contains the Beacon Signal",fe,{created:e.created,blockTime:r.time});if(i!==void 0&&i<r.mediantime*1e3)throw new le("Invalid update: proof.expires is before the mediantime of the block that contains the Beacon Signal",fe,{expires:e.expires,mediantime:r.mediantime});if(n!==void 0&&i!==void 0&&i<n)throw new le("Invalid update: proof.expires is before proof.created",fe,{created:e.created,expires:e.expires})}static applyUpdate(e,r,n){let i=ko(e),o=t.decodeUpdateHash(r.sourceHash,"sourceHash");if(!Eo(o,i))throw new le("Hash mismatch: update.sourceHash !== currentDocumentHash",fe,{sourceHash:r.sourceHash,currentDocumentHash:en(i,"hex")});if(!iy(r["@context"]))throw new le("Invalid update: @context is not the array the specification pins for a BTCR2 Update",fe,{context:r["@context"],expected:[..._c]});if(!iy(r.proof?.["@context"],r["@context"]))throw new le("Invalid update: proof @context does not equal the update @context",fe,{proofContext:r.proof?.["@context"],context:r["@context"]});let s=r.proof,c=[["type","DataIntegrityProof"],["cryptosuite","bip340-jcs-2025"],["proofPurpose","capabilityInvocation"],["capabilityAction","Write"],["capability",`urn:zcap:root:${encodeURIComponent(e.id)}`]];for(let[y,x]of c){let S=s[y];if(S!==x)throw new le(`Invalid update: proof.${y} must equal "${x}"`,fe,{field:y,expected:x,actual:S})}let a=s.verificationMethod,u=tt.capabilityInvocationEntry(e,a);if(u===void 0)throw new le("Invalid update: verificationMethod is not authorized for capabilityInvocation",fe,{verificationMethodId:a,capabilityInvocation:e.capabilityInvocation});let d=tt.verificationMethodOfEntry(e,u);if(d===void 0)throw new le("Invalid update: verificationMethod is not found in the verificationMethod of the current document",fe,{verificationMethodId:a});t.checkProofWindow(s,n);let f;try{let y=po.fromVerificationMethod({...d,id:tt.absoluteDidUrl(d.id,e.id)??d.id});f=new hu(new pu(y)).verifyProof(Kt(r),"capabilityInvocation").verified}catch(y){throw new le(`Invalid update: proof verification failed: ${Ar(y).message}`,fe,{verificationMethodId:a,cause:Ar(y)})}if(!f)throw new le("Invalid update: proof not verified",fe,{verificationMethodId:a});let h;try{h=na.apply(e,r.patch,{strict:!0})}catch(y){throw new le(`Invalid update: ${Ar(y).message}`,fe,{cause:Ar(y)})}if(h?.id!==e.id)throw new le(`Invalid update: the patch changes the document id (from "${e.id}" to "${String(h?.id)}")`,fe,{sourceId:e.id,targetId:h?.id});try{jr.validate(h)}catch(y){throw new le(`Invalid update: the patched document does not conform to DID Core: ${Ar(y).message}`,fe,{cause:Ar(y)})}let p=ko(h),g=t.decodeUpdateHash(r.targetHash,"targetHash");if(!Eo(g,p))throw new le("Invalid update: update.targetHash !== updatedDocumentHash",fe,{updateTargetHash:g,updatedDocumentHash:p});return h}resolve(){for(;;)switch(this.#r){case"GenesisDocument":{if(this.#c){this.#i=t.external(this.#e,this.#c),this.#c=null,this.#r="BeaconDiscovery";continue}return{status:"action-required",needs:[{kind:"NeedGenesisDocument",genesisHash:en(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=ir.getBeaconServices(this.#i).filter(n=>{let i=ir.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=ir.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.#l){let i=ir.parseBitcoinAddress(r.serviceEndpoint);if(this.#h.has(i)||!n.length)continue;let o=this.#x(n);if(!o.length)continue;let c=Ms.establish(r,this.#i.id).processSignals(o,this.#o);c.needs.length>0?e.push(...c.needs):(this.#a.push(...c.updates.map(([a,u])=>[a,u,i])),this.#h.add(i))}if(e.length>0)return{status:"action-required",needs:e};this.#r="ProcessUpdate";continue}case"ProcessUpdate":{let e=this.#i;if(this.#t!==void 0&&this.#s===this.#t){this.#r="Complete";continue}if(this.#a.length===0||e.deactivated){if(this.#t!==void 0)throw new le(`Version ${this.#t} of the DID does not exist: the history `+(e.deactivated?`ends with the deactivation at version ${this.#s}.`:`ends at version ${this.#s}.`),Bv,{versionId:this.#t,currentVersionId:this.#s});this.#r="Complete";continue}this.#a.sort(([c,a],[u,d])=>c.targetVersionId-u.targetVersionId||a.height-d.height);let[r,n,i]=this.#a.shift();if(!ir.getBeaconServices(e).some(c=>ir.parseBitcoinAddress(c.serviceEndpoint)===i))continue;if(r.targetVersionId<=this.#s){t.confirmDuplicate(r,this.#y);continue}if(this.#n!==void 0&&n.mediantime*1e3>this.#n){this.#r="Complete";continue}if(r.targetVersionId!==this.#s+1)throw new le("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",_l,{targetVersionId:r.targetVersionId,currentVersionId:this.#s+1});this.#i=t.applyUpdate(e,r,n);let s=ks.deleteKeys(r,["proof"]);if(this.#y.push(ko(s)),this.#s++,this.#g=n.confirmations,this.#f=Li.toISOStringNonFractional(Li.blocktimeToTimestamp(n.time)),this.#b()){if(++this.#m>this.#u)throw new le(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,Al,{maxDiscoveryRounds:this.#u,discoveryRounds:this.#m});this.#r="BeaconDiscovery"}continue}case"Complete":return this.#p??={didDocument:this.#i,metadata:{versionId:`${this.#s}`,confirmations:this.#g,...this.#f!==void 0?{updated:this.#f}:{},deactivated:this.#i.deactivated||!1}},{status:"resolved",result:this.#p}}}#b(){return ir.getBeaconServices(this.#i).some(e=>!this.#d.has(ir.parseBitcoinAddress(e.serviceEndpoint)))}#x(e){let r=[];for(let n of e){let i=n.blockMetadata,o=i?.confirmations;if(!(!Number.isInteger(o)||o<this.#w)){if(!Number.isFinite(i?.height)||!Number.isFinite(i?.time)||!Number.isFinite(i?.mediantime))throw new le(`Beacon signal ${n.signalBytes} has ${o} confirmations but no valid block height, block time, or block mediantime.`,fe,{signalBytes:n.signalBytes,confirmations:o,height:i?.height,time:i?.time,mediantime:i?.mediantime});r.push(n)}}return r}provide(e,r){switch(e.kind){case"NeedGenesisDocument":{if(!Ef(r))throw new le("Provided data for NeedGenesisDocument must be a document object.",fe,{kind:e.kind});this.#c=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new le("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",fe,{kind:e.kind});for(let[n,i]of r)this.#l.set(n,i);break}case"NeedCASAnnouncement":{if(!$L(r))throw new le("Provided data for NeedCASAnnouncement is not a CAS announcement.",fe,{kind:e.kind});let n=zn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new le(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,fe,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!HL(r))throw new le("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",fe,{kind:e.kind});let n=zn(r,{encoding:"hex"});if(n!==e.updateHash)throw new le(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,fe,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!VL(r))throw new le("Provided data for NeedSMTProof is not an SMT proof.",fe,{kind:e.kind});let n=en(ta(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new le(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,fe,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function cB(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new Ve("Cannot derive aggregation communication key: capabilityInvocation is absent",qe,{id:t.id});let r=tt.absoluteDidUrl(e,t.id),n=typeof e=="string"?r===void 0?void 0:t.verificationMethod?.find(i=>tt.absoluteDidUrl(i.id,t.id)===r):e;if(!n)throw new Ve(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,qe,{id:t.id,invocation:e});return po.fromVerificationMethod(n).publicKey}function YL(t,e){try{let r=lr.decode(t);if(r.idType==="KEY")return new ft(r.genesisBytes);if(e?.genesisDocument){let n=yo.external(r,e.genesisDocument);return cB(n)}}catch{}}l();l();l();var vf=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":[..._c],patch:r,targetHash:"",targetVersionId:n+1,sourceHash:zn(e)},o;try{o=na.apply(e,r,{strict:!0})}catch(s){throw new it(`Invalid patch: ${Ar(s).message}`,fe,{cause:Ar(s)})}if(o.id!==e.id)throw new it(`Patches must not change the DID document id (source "${e.id}" to target "${o.id}").`,fe,{sourceId:e.id,targetId:o.id});try{jr.isValid(o)}catch(s){throw new it("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),fe,o)}return i.targetHash=zn(o),i}static sign(e,r,n,i){if(!e.startsWith("did:btcr2:"))throw new it(`Expected a did:btcr2 identifier for the root capability; got "${e}".`,fe,{did:e});let o=n.controller,s=n.id.indexOf("#");if(s<0)throw new it(`Verification method id must contain a fragment (e.g. "${n.id}#initialKey"); got "${n.id}".`,fe,{verificationMethodId:n.id});let c=n.id.slice(s),a=po.fromSigner(c,o,i),u=s===0?`${e}${c}`:n.id,d=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&d!==n.publicKeyMultibase)throw new it(`Signing key does not match verification method "${n.id}": the signer's public key differs from the method's published publicKeyMultibase.`,fe,{verificationMethodId:n.id,expected:n.publicKeyMultibase,actual:d});let f={"@context":[..._c],cryptosuite:"bip340-jcs-2025",type:"DataIntegrityProof",verificationMethod:u,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"},p=a.toCryptosuite().toDataIntegrityProof().addProof(r,f),g;try{g=po.fromVerificationMethod({...n,id:u}).toCryptosuite().toDataIntegrityProof().verifyProof(Kt(p),"capabilityInvocation").verified}catch(y){throw new it(`Invalid update: the proof does not verify with the public key of "${n.id}": `+Ar(y).message,fe,{verificationMethodId:n.id,cause:Ar(y)})}if(!g)throw new it(`Invalid update: the proof does not verify with the public key of "${n.id}".`,fe,{verificationMethodId:n.id});return p}static async announce(e,r,n,i,o,s){return Ms.establish(e,r).broadcastSignal(n,i,o,s)}#c(){return t.construct(this.#t,this.#n,this.#r)}advance(){for(;;)switch(this.#e.phase){case"Construct":{let e=this.#c();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 it(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,fe,{phase:this.#e.phase});if(!r)throw new it("NeedSigningKey requires a Signer.",fe);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 it(`Cannot provide NeedFunding: updater phase is ${this.#e.phase}, expected Fund.`,fe,{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 it(`NeedFunding proof must have utxoCount >= 1; got ${String(n.utxoCount)}.`,fe,{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 it(`Cannot provide NeedBroadcast: updater phase is ${this.#e.phase}, expected Broadcast.`,fe,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};l();var fx=class{document={};constructor(e){if(!e.id)throw new Ve('Missing required "id" property',qe,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 jr(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};l();var lx=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new be("idType is required for creating a did:btcr2 identifier",qe,r);return lr.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=lr.decode(e),i=yo.sidecarData(r.sidecar),o=n.hrp===Nl.k?yo.deterministic(n):null;return new yo(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}){if(!Number.isInteger(n)||n<1)throw new it(`Invalid sourceVersionId: expected an integer of at least 1, got ${String(n)}.`,fe,{sourceVersionId:n});let s=tt.capabilityInvocationEntry(e,i);if(s===void 0)throw new it("Invalid verificationMethodId: not authorized for capabilityInvocation",fe,{verificationMethodId:i,capabilityInvocation:e.capabilityInvocation});let c=tt.verificationMethodOfEntry(e,s);if(!c)throw new it("Invalid verificationMethodId: not found in source document",fe,{verificationMethodId:i});if(c.type!==Ac)throw new it(`Invalid verificationMethod: verificationMethod.type must be "${Ac}"`,qe,c);if(!c.publicKeyMultibase?.startsWith(Tc))throw new it(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${Tc}"`,qe,c);let a=tt.absoluteDidUrl(o,e.id),u=e.service.filter(d=>a!==void 0&&tt.absoluteDidUrl(d.id,e.id)===a).filter(d=>!!d).shift();if(!u)throw new it("No beacon service found for provided beaconId",fe,{sourceDocument:e,beaconId:o});return new vf({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:c,beaconService:u})}static deactivate({sourceDocument:e,sourceVersionId:r,verificationMethodId:n,beaconId:i}){return this.update({sourceDocument:e,patches:[{...ix}],sourceVersionId:r,verificationMethodId:n,beaconId:i})}static getSigningMethod(e,r){r??="#initialKey";let n=xe.parse(e.id);if(n&&n.method!==this.methodName)throw new be(`Method not supported: ${n.method}`,Sl,{identifier:e.id});let i=tt.absoluteDidUrl(r,e.id)??tt.relationshipMethodId(e.assertionMethod?.[0],e.id),o=i===void 0?void 0:tt.getVerificationMethods(e).find(s=>tt.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}};return DB(JL);})();
1
+ "use strict";var BTCR2=(()=>{var IB=Object.create;var Cf=Object.defineProperty;var BB=Object.getOwnPropertyDescriptor;var RB=Object.getOwnPropertyNames;var UB=Object.getPrototypeOf,OB=Object.prototype.hasOwnProperty;var DB=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Tu=(t,e)=>{for(var r in e)Cf(t,r,{get:e[r],enumerable:!0})},Tx=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of RB(e))!OB.call(t,i)&&i!==r&&Cf(t,i,{get:()=>e[i],enumerable:!(n=BB(e,i))||n.enumerable});return t};var Kn=(t,e,r)=>(r=t!=null?IB(UB(t)):{},Tx(e||!t||!t.__esModule?Cf(r,"default",{value:t,enumerable:!0}):r,t)),kB=t=>Tx(Cf({},"__esModule",{value:!0}),t);var Bx=oe(Lf=>{"use strict";l();Lf.byteLength=CB;Lf.toByteArray=PB;Lf.fromByteArray=$B;var $n=[],Jr=[],NB=typeof Uint8Array<"u"?Uint8Array:Array,py="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(ws=0,_x=py.length;ws<_x;++ws)$n[ws]=py[ws],Jr[py.charCodeAt(ws)]=ws;var ws,_x;Jr[45]=62;Jr[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 CB(t){var e=Ix(t),r=e[0],n=e[1];return(r+n)*3/4-n}function LB(t,e,r){return(e+r)*3/4-r}function PB(t){var e,r=Ix(t),n=r[0],i=r[1],o=new NB(LB(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Jr[t.charCodeAt(a)]<<18|Jr[t.charCodeAt(a+1)]<<12|Jr[t.charCodeAt(a+2)]<<6|Jr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Jr[t.charCodeAt(a)]<<2|Jr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Jr[t.charCodeAt(a)]<<10|Jr[t.charCodeAt(a+1)]<<4|Jr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function MB(t){return $n[t>>18&63]+$n[t>>12&63]+$n[t>>6&63]+$n[t&63]}function KB(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 $B(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(KB(t,s,s+o>c?c:s+o));return n===1?(e=t[r-1],i.push($n[e>>2]+$n[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push($n[e>>10]+$n[e>>4&63]+$n[e<<2&63]+"=")),i.join("")}});var Rx=oe(yy=>{l();yy.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)};yy.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 _r=oe(Kc=>{"use strict";l();var gy=Bx(),Mc=Rx(),Ux=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Kc.Buffer=F;Kc.SlowBuffer=WB;Kc.INSPECT_MAX_BYTES=50;var Pf=2147483647;Kc.kMaxLength=Pf;F.TYPED_ARRAY_SUPPORT=HB();!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 HB(){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 xi(t){if(t>Pf)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 xy(t)}return kx(t,e,r)}F.poolSize=8192;function kx(t,e,r){if(typeof t=="string")return qB(t,e);if(ArrayBuffer.isView(t))return FB(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(Hn(t,ArrayBuffer)||t&&Hn(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Hn(t,SharedArrayBuffer)||t&&Hn(t.buffer,SharedArrayBuffer)))return wy(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=jB(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 kx(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function Nx(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 Nx(t),t<=0?xi(t):e!==void 0?typeof r=="string"?xi(t).fill(e,r):xi(t).fill(e):xi(t)}F.alloc=function(t,e,r){return VB(t,e,r)};function xy(t){return Nx(t),xi(t<0?0:Ey(t)|0)}F.allocUnsafe=function(t){return xy(t)};F.allocUnsafeSlow=function(t){return xy(t)};function qB(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=Cx(t,e)|0,n=xi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function my(t){for(var e=t.length<0?0:Ey(t.length)|0,r=xi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function FB(t){if(Hn(t,Uint8Array)){var e=new Uint8Array(t);return wy(e.buffer,e.byteOffset,e.byteLength)}return my(t)}function wy(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 jB(t){if(F.isBuffer(t)){var e=Ey(t.length)|0,r=xi(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||vy(t.length)?xi(0):my(t);if(t.type==="Buffer"&&Array.isArray(t.data))return my(t.data)}function Ey(t){if(t>=Pf)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Pf.toString(16)+" bytes");return t|0}function WB(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(Hn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),Hn(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(Hn(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 Cx(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Hn(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 by(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return Hx(t).length;default:if(i)return n?-1:by(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=Cx;function GB(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 n8(this,e,r);case"utf8":case"utf-8":return Px(this,e,r);case"ascii":return t8(this,e,r);case"latin1":case"binary":return r8(this,e,r);case"base64":return QB(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return i8(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function bs(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)bs(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)bs(this,r,r+3),bs(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)bs(this,r,r+7),bs(this,r+1,r+6),bs(this,r+2,r+5),bs(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):GB.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=Kc.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};Ux&&(F.prototype[Ux]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,o){if(Hn(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 Lx(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,vy(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:Ox(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):Ox(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Ox(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 Lx(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return Lx(this,e,r,n,!1)};function zB(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(vy(c))return s;t[r+s]=c}return s}function YB(t,e,r,n){return Mf(by(e,t.length-r),t,r,n)}function JB(t,e,r,n){return Mf(c8(e),t,r,n)}function XB(t,e,r,n){return Mf(Hx(e),t,r,n)}function ZB(t,e,r,n){return Mf(a8(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 zB(this,e,r,n);case"utf8":case"utf-8":return YB(this,e,r,n);case"ascii":case"latin1":case"binary":return JB(this,e,r,n);case"base64":return XB(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ZB(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 QB(t,e,r){return e===0&&r===t.length?gy.fromByteArray(t):gy.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 e8(n)}var Dx=4096;function e8(t){var e=t.length;if(e<=Dx)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Dx));return r}function t8(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 r8(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 n8(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+=u8[t[o]];return i}function i8(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),Mc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Ut(e,4,this.length),Mc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Mc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Ut(e,8,this.length),Mc.read(this,e,!1,52,8)};function lr(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;lr(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;lr(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||lr(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||lr(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||lr(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||lr(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||lr(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);lr(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);lr(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||lr(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||lr(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||lr(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||lr(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||lr(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 Mx(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 Kx(t,e,r,n,i){return e=+e,r=r>>>0,i||Mx(t,e,r,4,34028234663852886e22,-34028234663852886e22),Mc.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return Kx(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return Kx(this,e,r,!1,n)};function $x(t,e,r,n,i){return e=+e,r=r>>>0,i||Mx(t,e,r,8,17976931348623157e292,-17976931348623157e292),Mc.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return $x(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return $x(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 o8=/[^+/0-9A-Za-z-_]/g;function s8(t){if(t=t.split("=")[0],t=t.trim().replace(o8,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function by(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 c8(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function a8(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 Hx(t){return gy.toByteArray(s8(t))}function Mf(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 Hn(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function vy(t){return t!==t}var u8=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 Si=oe((pP,jx)=>{l();var lt=jx.exports={},Vn,qn;function Sy(){throw new Error("setTimeout has not been defined")}function Ay(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?Vn=setTimeout:Vn=Sy}catch{Vn=Sy}try{typeof clearTimeout=="function"?qn=clearTimeout:qn=Ay}catch{qn=Ay}})();function Vx(t){if(Vn===setTimeout)return setTimeout(t,0);if((Vn===Sy||!Vn)&&setTimeout)return Vn=setTimeout,setTimeout(t,0);try{return Vn(t,0)}catch{try{return Vn.call(null,t,0)}catch{return Vn.call(this,t,0)}}}function d8(t){if(qn===clearTimeout)return clearTimeout(t);if((qn===Ay||!qn)&&clearTimeout)return qn=clearTimeout,clearTimeout(t);try{return qn(t)}catch{try{return qn.call(null,t)}catch{return qn.call(this,t)}}}var Ei=[],$c=!1,xs,Kf=-1;function f8(){!$c||!xs||($c=!1,xs.length?Ei=xs.concat(Ei):Kf=-1,Ei.length&&qx())}function qx(){if(!$c){var t=Vx(f8);$c=!0;for(var e=Ei.length;e;){for(xs=Ei,Ei=[];++Kf<e;)xs&&xs[Kf].run();Kf=-1,e=Ei.length}xs=null,$c=!1,d8(t)}}lt.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];Ei.push(new Fx(t,e)),Ei.length===1&&!$c&&Vx(qx)};function Fx(t,e){this.fun=t,this.array=e}Fx.prototype.run=function(){this.fun.apply(null,this.array)};lt.title="browser";lt.browser=!0;lt.env={};lt.argv=[];lt.version="";lt.versions={};function vi(){}lt.on=vi;lt.addListener=vi;lt.once=vi;lt.off=vi;lt.removeListener=vi;lt.removeAllListeners=vi;lt.emit=vi;lt.prependListener=vi;lt.prependOnceListener=vi;lt.listeners=function(t){return[]};lt.binding=function(t){throw new Error("process.binding is not supported")};lt.cwd=function(){return"/"};lt.chdir=function(t){throw new Error("process.chdir is not supported")};lt.umask=function(){return 0}});var b,w,gP,l=DB(()=>{b=Kn(_r()),w=Kn(Si()),gP=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 l1=oe((ZH,f1)=>{l();var S6=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Yl=()=>S6.now(),A6=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),cg=t=>t===1/0||A6(t),ag=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&&!cg(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!cg(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-Yl());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(Yl()+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(!cg(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-Yl())):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(Yl());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()}};f1.exports=ag});var R1=oe(B1=>{"use strict";l();B1.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 Sn=oe((vq,U1)=>{"use strict";l();U1.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((Aq,O1)=>{"use strict";l();var vg=null;O1.exports=function(){return vg===null&&(vg={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),vg}});var _g=oe(D1=>{"use strict";l();var Ag=Sn(),nU=new Set(["buffer","view","utf8"]),Tg=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"||!nU.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 Ag(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new Ag(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new Ag(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};D1.Encoding=Tg});var Ug=oe(Xl=>{"use strict";l();var{Buffer:Bg}=_r()||{},{Encoding:Rg}=_g(),iU=Sg(),pd=class extends Rg{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new yd({encode:this.encode,decode:e=>this.decode(Bg.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},yd=class extends Rg{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new pd({encode:e=>{let r=this.encode(e);return Bg.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},Ig=class extends Rg{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new pd({encode:e=>Bg.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:r}=iU();return new yd({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Xl.BufferFormat=pd;Xl.ViewFormat=yd;Xl.UTF8Format=Ig});var L1=oe(Ws=>{"use strict";l();var{Buffer:Jt}=_r()||{Buffer:{isBuffer:()=>!1}},{textEncoder:N1,textDecoder:k1}=Sg()(),{BufferFormat:gd,ViewFormat:Og,UTF8Format:C1}=Ug(),Zl=t=>t;Ws.utf8=new C1({encode:function(t){return Jt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?k1.decode(t):String(t)},decode:Zl,name:"utf8",createViewTranscoder(){return new Og({encode:function(t){return ArrayBuffer.isView(t)?t:N1.encode(t)},decode:function(t){return k1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new gd({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`})}});Ws.json=new C1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Ws.buffer=new gd({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:Zl,name:"buffer",createViewTranscoder(){return new Og({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`})}});Ws.view=new Og({encode:function(t){return ArrayBuffer.isView(t)?t:N1.encode(t)},decode:Zl,name:"view",createBufferTranscoder(){return new gd({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:Zl,name:`${this.name}+buffer`})}});Ws.hex=new gd({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Ws.base64=new gd({encode:function(t){return Jt.isBuffer(t)?t:Jt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var K1=oe(M1=>{"use strict";l();var P1=Sn(),eh=L1(),{Encoding:oU}=_g(),{BufferFormat:sU,ViewFormat:cU,UTF8Format:aU}=Ug(),md=Symbol("formats"),Ql=Symbol("encodings"),uU=new Set(["buffer","view","utf8"]),Dg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>uU.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[Ql]=new Map,this[md]=new Set(e);for(let r in eh)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[Ql].values()))}encoding(e){let r=this[Ql].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=hU[e],!r)throw new P1(`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=dU(e)}let{name:n,format:i}=r;if(!this[md].has(i))if(this[md].has("view"))r=r.createViewTranscoder();else if(this[md].has("buffer"))r=r.createBufferTranscoder();else if(this[md].has("utf8"))r=r.createUTF8Transcoder();else throw new P1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[Ql].set(o,r)}return r}};M1.Transcoder=Dg;function dU(t){if(t instanceof oU)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${pU++}`;switch(fU(t)){case"view":return new cU({...t,name:r});case"utf8":return new aU({...t,name:r});case"buffer":return new sU({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function fU(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 lU={binary:eh.buffer,"utf-8":eh.utf8},hU={...eh,...lU},pU=0});var ma=oe((Nq,kg)=>{"use strict";l();var ga=typeof Reflect=="object"?Reflect:null,$1=ga&&typeof ga.apply=="function"?ga.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},th;ga&&typeof ga.ownKeys=="function"?th=ga.ownKeys:Object.getOwnPropertySymbols?th=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:th=function(e){return Object.getOwnPropertyNames(e)};function yU(t){console&&console.warn&&console.warn(t)}var V1=Number.isNaN||function(e){return e!==e};function Le(){Le.init.call(this)}kg.exports=Le;kg.exports.once=bU;Le.EventEmitter=Le;Le.prototype._events=void 0;Le.prototype._eventsCount=0;Le.prototype._maxListeners=void 0;var H1=10;function rh(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Le,"defaultMaxListeners",{enumerable:!0,get:function(){return H1},set:function(t){if(typeof t!="number"||t<0||V1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");H1=t}});Le.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};Le.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||V1(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 q1(t){return t._maxListeners===void 0?Le.defaultMaxListeners:t._maxListeners}Le.prototype.getMaxListeners=function(){return q1(this)};Le.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")$1(a,this,r);else for(var u=a.length,d=z1(a,u),n=0;n<u;++n)$1(d[n],this,r);return!0};function F1(t,e,r,n){var i,o,s;if(rh(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=q1(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,yU(c)}return t}Le.prototype.addListener=function(e,r){return F1(this,e,r,!1)};Le.prototype.on=Le.prototype.addListener;Le.prototype.prependListener=function(e,r){return F1(this,e,r,!0)};function gU(){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 j1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=gU.bind(n);return i.listener=r,n.wrapFn=i,i}Le.prototype.once=function(e,r){return rh(r),this.on(e,j1(this,e,r)),this};Le.prototype.prependOnceListener=function(e,r){return rh(r),this.prependListener(e,j1(this,e,r)),this};Le.prototype.removeListener=function(e,r){var n,i,o,s,c;if(rh(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():mU(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Le.prototype.off=Le.prototype.removeListener;Le.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 W1(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?wU(i):z1(i,i.length)}Le.prototype.listeners=function(e){return W1(this,e,!0)};Le.prototype.rawListeners=function(e){return W1(this,e,!1)};Le.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):G1.call(t,e)};Le.prototype.listenerCount=G1;function G1(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}Le.prototype.eventNames=function(){return this._eventsCount>0?th(this._events):[]};function z1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function mU(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function wU(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function bU(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))}Y1(t,e,o,{once:!0}),e!=="error"&&xU(t,i,{once:!0})})}function xU(t,e,r){typeof t.on=="function"&&Y1(t,"error",e,r)}function Y1(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 X1=oe((Lq,J1)=>{l();J1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var wd=oe(Ng=>{"use strict";l();var Z1=X1();Ng.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};Ng.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){Z1(()=>e(null,r))}).catch(function(r){Z1(()=>e(r))})}});var nh=oe(Cg=>{"use strict";l();Cg.getCallback=function(t,e){return typeof t=="function"?t:e};Cg.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Fo=oe(ch=>{"use strict";l();var{fromCallback:Lg}=wd(),Cr=Sn(),{getOptions:Pg,getCallback:Q1}=nh(),Gs=Symbol("promise"),wa=Symbol("callback"),ei=Symbol("working"),zs=Symbol("handleOne"),Fi=Symbol("handleMany"),Mg=Symbol("autoClose"),Vo=Symbol("finishWork"),ti=Symbol("returnMany"),Ko=Symbol("closing"),bd=Symbol("handleClose"),ih=Symbol("closed"),xd=Symbol("closeCallbacks"),Ho=Symbol("keyEncoding"),Ys=Symbol("valueEncoding"),Kg=Symbol("abortOnClose"),oh=Symbol("legacy"),$g=Symbol("keys"),Hg=Symbol("values"),$o=Symbol("limit"),rn=Symbol("count"),sh=Object.freeze({}),EU=()=>{},e2=!1,Ed=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[ih]=!1,this[xd]=[],this[ei]=!1,this[Ko]=!1,this[Mg]=!1,this[wa]=null,this[zs]=this[zs].bind(this),this[Fi]=this[Fi].bind(this),this[bd]=this[bd].bind(this),this[Ho]=r[Ho],this[Ys]=r[Ys],this[oh]=n,this[$o]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[rn]=0,this[Kg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[rn]}get limit(){return this[$o]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[oh]?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[Ko]?this.nextTick(e,new Cr("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[ei]?this.nextTick(e,new Cr("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[ei]=!0,this[wa]=e,this[rn]>=this[$o]?this.nextTick(this[zs],null):this._next(this[zs])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=Q1(r,n),n=Lg(n,Gs),r=Pg(r,sh),Number.isInteger(e)?(this[Ko]?this.nextTick(n,new Cr("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[ei]?this.nextTick(n,new Cr("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[$o]<1/0&&(e=Math.min(e,this[$o]-this[rn])),this[ei]=!0,this[wa]=n,e<=0?this.nextTick(this[Fi],null,[]):this._nextv(e,r,this[Fi])),n[Gs]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[Gs])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[oh]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[oh]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=Q1(e,r),r=Lg(r,Gs),e=Pg(e,sh),this[Ko]?this.nextTick(r,new Cr("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[ei]?this.nextTick(r,new Cr("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[ei]=!0,this[wa]=r,this[Mg]=!0,this[rn]>=this[$o]?this.nextTick(this[Fi],null,[]):this._all(e,this[Fi])),r[Gs]}_all(e,r){let n=this[rn],i=[],o=()=>{let c=this[$o]<1/0?Math.min(1e3,this[$o]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,sh,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Vo](){let e=this[wa];return this[Kg]&&e===null?EU:(this[ei]=!1,this[wa]=null,this[Ko]&&this._close(this[bd]),e)}[ti](e,r,n){this[Mg]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=Pg(r,sh),!this[Ko]){if(this[ei])throw new Cr("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[Ho]),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 Cr("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=Lg(e,Gs),this[ih]?this.nextTick(e):this[Ko]?this[xd].push(e):(this[Ko]=!0,this[xd].push(e),this[ei]?this[Kg]&&this[Vo]()(new Cr("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[bd])),e[Gs]}_close(e){this.nextTick(e)}[bd](){this[ih]=!0,this.db.detachResource(this);let e=this[xd];this[xd]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[ih]||await this.close()}}},ba=class extends Ed{constructor(e,r){super(e,r,!0),this[$g]=r.keys!==!1,this[Hg]=r.values!==!1}[zs](e,r,n){let i=this[Vo]();if(e)return i(e);try{r=this[$g]&&r!==void 0?this[Ho].decode(r):void 0,n=this[Hg]&&n!==void 0?this[Ys].decode(n):void 0}catch(o){return i(new qo("entry",o))}r===void 0&&n===void 0||this[rn]++,i(null,r,n)}[Fi](e,r){let n=this[Vo]();if(e)return this[ti](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[$g]&&o!==void 0?this[Ho].decode(o):void 0,i[1]=this[Hg]&&s!==void 0?this[Ys].decode(s):void 0}}catch(i){return this[ti](n,new qo("entries",i))}this[rn]+=r.length,this[ti](n,null,r)}end(e){return!e2&&typeof console<"u"&&(e2=!0,console.warn(new Cr("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)}},Vg=class extends Ed{constructor(e,r){super(e,r,!1)}[zs](e,r){let n=this[Vo]();if(e)return n(e);try{r=r!==void 0?this[Ho].decode(r):void 0}catch(i){return n(new qo("key",i))}r!==void 0&&this[rn]++,n(null,r)}[Fi](e,r){let n=this[Vo]();if(e)return this[ti](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Ho].decode(o):void 0}}catch(i){return this[ti](n,new qo("keys",i))}this[rn]+=r.length,this[ti](n,null,r)}},qg=class extends Ed{constructor(e,r){super(e,r,!1)}[zs](e,r){let n=this[Vo]();if(e)return n(e);try{r=r!==void 0?this[Ys].decode(r):void 0}catch(i){return n(new qo("value",i))}r!==void 0&&this[rn]++,n(null,r)}[Fi](e,r){let n=this[Vo]();if(e)return this[ti](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Ys].decode(o):void 0}}catch(i){return this[ti](n,new qo("values",i))}this[rn]+=r.length,this[ti](n,null,r)}},qo=class extends Cr{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(ba.prototype,t.split(" ")[0],{get(){throw new Cr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new Cr(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});ba.keyEncoding=Ho;ba.valueEncoding=Ys;ch.AbstractIterator=ba;ch.AbstractKeyIterator=Vg;ch.AbstractValueIterator=qg});var t2=oe(Fg=>{"use strict";l();var{AbstractKeyIterator:vU,AbstractValueIterator:SU}=Fo(),Js=Symbol("iterator"),vd=Symbol("callback"),xa=Symbol("handleOne"),Xs=Symbol("handleMany"),Sd=class extends vU{constructor(e,r){super(e,r),this[Js]=e.iterator({...r,keys:!0,values:!1}),this[xa]=this[xa].bind(this),this[Xs]=this[Xs].bind(this)}},ah=class extends SU{constructor(e,r){super(e,r),this[Js]=e.iterator({...r,keys:!1,values:!0}),this[xa]=this[xa].bind(this),this[Xs]=this[Xs].bind(this)}};for(let t of[Sd,ah]){let e=t===Sd,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[vd]=n,this[Js].next(this[xa])},t.prototype[xa]=function(n,i,o){let s=this[vd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[vd]=o,this[Js].nextv(n,i,this[Xs])},t.prototype._all=function(n,i){this[vd]=i,this[Js].all(n,this[Xs])},t.prototype[Xs]=function(n,i){let o=this[vd];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)}}Fg.DefaultKeyIterator=Sd;Fg.DefaultValueIterator=ah});var r2=oe(ph=>{"use strict";l();var{AbstractIterator:AU,AbstractKeyIterator:TU,AbstractValueIterator:_U}=Fo(),jg=Sn(),gr=Symbol("nut"),lh=Symbol("undefer"),hh=Symbol("factory"),uh=class extends AU{constructor(e,r){super(e,r),this[gr]=null,this[hh]=()=>e.iterator(r),this.db.defer(()=>this[lh]())}},dh=class extends TU{constructor(e,r){super(e,r),this[gr]=null,this[hh]=()=>e.keys(r),this.db.defer(()=>this[lh]())}},fh=class extends _U{constructor(e,r){super(e,r),this[gr]=null,this[hh]=()=>e.values(r),this.db.defer(()=>this[lh]())}};for(let t of[uh,dh,fh])t.prototype[lh]=function(){this.db.status==="open"&&(this[gr]=this[hh]())},t.prototype._next=function(e){this[gr]!==null?this[gr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new jg("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[gr]!==null?this[gr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new jg("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[gr]!==null?this[gr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new jg("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[gr]!==null?this[gr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[gr]!==null?this[gr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};ph.DeferredIterator=uh;ph.DeferredKeyIterator=dh;ph.DeferredValueIterator=fh});var Gg=oe(i2=>{"use strict";l();var{fromCallback:n2}=wd(),yh=Sn(),{getCallback:IU,getOptions:BU}=nh(),gh=Symbol("promise"),nn=Symbol("status"),Ea=Symbol("operations"),Ad=Symbol("finishClose"),va=Symbol("closeCallbacks"),Wg=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[Ea]=[],this[va]=[],this[nn]="open",this[Ad]=this[Ad].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[Ea].length}put(e,r,n){if(this[nn]!=="open")throw new yh("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[Ea].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[nn]!=="open")throw new yh("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[Ea].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[nn]!=="open")throw new yh("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[Ea]=[],this}_clear(){}write(e,r){return r=IU(e,r),r=n2(r,gh),e=BU(e),this[nn]!=="open"?this.nextTick(r,new yh("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[nn]="writing",this._write(e,n=>{this[nn]="closing",this[va].push(()=>r(n)),n||this.db.emit("batch",this[Ea]),this._close(this[Ad])})),r[gh]}_write(e,r){}close(e){return e=n2(e,gh),this[nn]==="closing"?this[va].push(e):this[nn]==="closed"?this.nextTick(e):(this[va].push(e),this[nn]!=="writing"&&(this[nn]="closing",this._close(this[Ad]))),e[gh]}_close(e){this.nextTick(e)}[Ad](){this[nn]="closed",this.db.detachResource(this);let e=this[va];this[va]=[];for(let r of e)r()}};i2.AbstractChainedBatch=Wg});var s2=oe(o2=>{"use strict";l();var{AbstractChainedBatch:RU}=Gg(),UU=Sn(),Sa=Symbol("encoded"),zg=class extends RU{constructor(e){super(e),this[Sa]=[]}_put(e,r,n){this[Sa].push({...n,type:"put",key:e,value:r})}_del(e,r){this[Sa].push({...r,type:"del",key:e})}_clear(){this[Sa]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[Sa].length===0?this.nextTick(r):this.db._batch(this[Sa],e,r):this.nextTick(r,new UU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};o2.DefaultChainedBatch=zg});var u2=oe((Zq,a2)=>{"use strict";l();var c2=Sn(),OU=Object.prototype.hasOwnProperty,DU=new Set(["lt","lte","gt","gte"]);a2.exports=function(t,e){let r={};for(let n in t)if(OU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new c2(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new c2("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});DU.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 Yg=oe((eF,f2)=>{l();var d2;f2.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(d2||(d2=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var p2=oe((rF,h2)=>{"use strict";l();var l2=Yg();h2.exports=function(t,...e){e.length===0?l2(t):l2(()=>t(...e))}});var y2=oe(mh=>{"use strict";l();var{AbstractIterator:kU,AbstractKeyIterator:NU,AbstractValueIterator:CU}=Fo(),Aa=Symbol("unfix"),An=Symbol("iterator"),Zs=Symbol("handleOne"),jo=Symbol("handleMany"),ji=Symbol("callback"),Td=class extends kU{constructor(e,r,n,i){super(e,r),this[An]=n,this[Aa]=i,this[Zs]=this[Zs].bind(this),this[jo]=this[jo].bind(this),this[ji]=null}[Zs](e,r,n){let i=this[ji];if(e)return i(e);r!==void 0&&(r=this[Aa](r)),i(e,r,n)}[jo](e,r){let n=this[ji];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[Aa](o))}n(e,r)}},_d=class extends NU{constructor(e,r,n,i){super(e,r),this[An]=n,this[Aa]=i,this[Zs]=this[Zs].bind(this),this[jo]=this[jo].bind(this),this[ji]=null}[Zs](e,r){let n=this[ji];if(e)return n(e);r!==void 0&&(r=this[Aa](r)),n(e,r)}[jo](e,r){let n=this[ji];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[Aa](o))}n(e,r)}},Id=class extends CU{constructor(e,r,n){super(e,r),this[An]=n}};for(let t of[Td,_d])t.prototype._next=function(e){this[ji]=e,this[An].next(this[Zs])},t.prototype._nextv=function(e,r,n){this[ji]=n,this[An].nextv(e,r,this[jo])},t.prototype._all=function(e,r){this[ji]=r,this[An].all(e,this[jo])};for(let t of[Id])t.prototype._next=function(e){this[An].next(e)},t.prototype._nextv=function(e,r,n){this[An].nextv(e,r,n)},t.prototype._all=function(e,r){this[An].all(e,r)};for(let t of[Td,_d,Id])t.prototype._seek=function(e,r){this[An].seek(e,r)},t.prototype._close=function(e){this[An].close(e)};mh.AbstractSublevelIterator=Td;mh.AbstractSublevelKeyIterator=_d;mh.AbstractSublevelValueIterator=Id});var b2=oe((sF,w2)=>{"use strict";l();var Jg=Sn(),{Buffer:Qg}=_r()||{},{AbstractSublevelIterator:LU,AbstractSublevelKeyIterator:PU,AbstractSublevelValueIterator:MU}=y2(),Wi=Symbol("prefix"),g2=Symbol("upperBound"),Bd=Symbol("prefixRange"),Lr=Symbol("parent"),Xg=Symbol("unfix"),m2=new TextEncoder,KU={separator:"!"};w2.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new Jg("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new Jg("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?KU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=HU(i,s);let u=s.charCodeAt(0)+1,d=n[Lr]||n;if(!m2.encode(i).every(p=>p>u&&p<127))throw new Jg(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super($U(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[Lr]=d,this[Wi]=new wh(f),this[g2]=new wh(h),this[Xg]=new em,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[Wi].utf8+n;if(n.byteLength===0)return this[Wi][i];if(i==="view"){let o=this[Wi].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[Wi].buffer;return Qg.concat([o,n],o.byteLength+n.byteLength)}}[Bd](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[Wi][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[g2][i]}get prefix(){return this[Wi].utf8}get db(){return this[Lr]}_open(n,i){this[Lr].open({passive:!0},i)}_put(n,i,o,s){this[Lr].put(n,i,o,s)}_get(n,i,o){this[Lr].get(n,i,o)}_getMany(n,i,o){this[Lr].getMany(n,i,o)}_del(n,i,o){this[Lr].del(n,i,o)}_batch(n,i,o){this[Lr].batch(n,i,o)}_clear(n,i){this[Bd](n,n.keyEncoding),this[Lr].clear(n,i)}_iterator(n){this[Bd](n,n.keyEncoding);let i=this[Lr].iterator(n),o=this[Xg].get(this[Wi].utf8.length,n.keyEncoding);return new LU(this,n,i,o)}_keys(n){this[Bd](n,n.keyEncoding);let i=this[Lr].keys(n),o=this[Xg].get(this[Wi].utf8.length,n.keyEncoding);return new PU(this,n,i,o)}_values(n){this[Bd](n,n.keyEncoding);let i=this[Lr].values(n);return new MU(this,n,i)}}return{AbstractSublevel:e}};var $U=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:Zg(t,"utf8"),buffer:Zg(t,"buffer"),view:Zg(t,"view")}}},Zg=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},wh=class{constructor(e){this.utf8=e,this.view=m2.encode(e),this.buffer=Qg?Qg.from(this.view.buffer,0,this.view.byteLength):{}}},em=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}},HU=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 om=oe(im=>{"use strict";l();var{supports:VU}=R1(),{Transcoder:qU}=K1(),{EventEmitter:FU}=ma(),{fromCallback:Wo}=wd(),Tn=Sn(),{AbstractIterator:Qs}=Fo(),{DefaultKeyIterator:jU,DefaultValueIterator:WU}=t2(),{DeferredIterator:GU,DeferredKeyIterator:zU,DeferredValueIterator:YU}=r2(),{DefaultChainedBatch:x2}=s2(),{getCallback:ec,getOptions:Go}=nh(),bh=u2(),ge=Symbol("promise"),Gi=Symbol("landed"),tc=Symbol("resources"),tm=Symbol("closeResources"),Rd=Symbol("operations"),Ud=Symbol("undefer"),xh=Symbol("deferOpen"),E2=Symbol("options"),Ee=Symbol("status"),rc=Symbol("defaultOptions"),Ta=Symbol("transcoder"),Eh=Symbol("keyEncoding"),rm=Symbol("valueEncoding"),JU=()=>{},Od=class extends FU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=Go(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[tc]=new Set,this[Rd]=[],this[xh]=!0,this[E2]=s,this[Ee]="opening",this.supports=VU(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[Ta]=new qU(XU(this)),this[Eh]=this[Ta].encoding(n||"utf8"),this[rm]=this[Ta].encoding(i||"utf8");for(let c of this[Ta].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[rc]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[Eh].commonName,valueEncoding:this[rm].commonName}),key:Object.freeze({keyEncoding:this[Eh].commonName})},this.nextTick(()=>{this[xh]&&this.open({passive:!1},JU)})}get status(){return this[Ee]}keyEncoding(e){return this[Ta].encoding(e??this[Eh])}valueEncoding(e){return this[Ta].encoding(e??this[rm])}open(e,r){r=ec(e,r),r=Wo(r,ge),e={...this[E2],...Go(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[Ee]==="closing"||this[Ee]==="opening"?this.once(Gi,i?()=>n(i):n):this[Ee]!=="open"?r(new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[Ee]==="opening"?this.once(Gi,n):this.nextTick(n):this[Ee]==="closed"||this[xh]?(this[xh]=!1,this[Ee]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[Ee]="closed",this[tm](()=>{this.emit(Gi),n(i)}),this[Ud]();return}this[Ee]="open",this[Ud](),this.emit(Gi),this[Ee]==="open"&&this.emit("open"),this[Ee]==="open"&&this.emit("ready"),n()})):this[Ee]==="open"?this.nextTick(n):this.once(Gi,()=>this.open(e,r)),r[ge]}_open(e,r){this.nextTick(r)}close(e){e=Wo(e,ge);let r=n=>{this[Ee]==="opening"||this[Ee]==="closing"?this.once(Gi,n?r(n):r):this[Ee]!=="closed"?e(new Tn("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[Ee]==="open"){this[Ee]="closing",this.emit("closing");let n=i=>{this[Ee]="open",this[Ud](),this.emit(Gi),r(i)};this[tm](()=>{this._close(i=>{if(i)return n(i);this[Ee]="closed",this[Ud](),this.emit(Gi),this[Ee]==="closed"&&this.emit("closed"),r()})})}else this[Ee]==="closed"?this.nextTick(r):this.once(Gi,()=>this.close(e));return e[ge]}[tm](e){if(this[tc].size===0)return this.nextTick(e);let r=this[tc].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[tc])o.close(i);n=!1,this[tc].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=ec(r,n),n=Wo(n,ge),r=Go(r,this[rc].entry),this[Ee]==="opening")return this.defer(()=>this.get(e,r,n)),n[ge];if(_a(this,n))return n[ge];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[ge];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 Tn("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[ge]}_get(e,r,n){this.nextTick(n,new Error("NotFound"))}getMany(e,r,n){if(n=ec(r,n),n=Wo(n,ge),r=Go(r,this[rc].entry),this[Ee]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[ge];if(_a(this,n))return n[ge];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[ge];if(e.length===0)return this.nextTick(n,null,[]),n[ge];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[ge];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 Tn(`Could not decode one or more of ${d.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[ge]}_getMany(e,r,n){this.nextTick(n,null,new Array(e.length).fill(void 0))}put(e,r,n,i){if(i=ec(n,i),i=Wo(i,ge),n=Go(n,this[rc].entry),this[Ee]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[ge];if(_a(this,i))return i[ge];let o=this._checkKey(e)||this._checkValue(r);if(o)return this.nextTick(i,o),i[ge];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[ge]}_put(e,r,n,i){this.nextTick(i)}del(e,r,n){if(n=ec(r,n),n=Wo(n,ge),r=Go(r,this[rc].key),this[Ee]==="opening")return this.defer(()=>this.del(e,r,n)),n[ge];if(_a(this,n))return n[ge];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[ge];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[ge]}_del(e,r,n){this.nextTick(n)}batch(e,r,n){if(!arguments.length){if(this[Ee]==="opening")return new x2(this);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=ec(r,n),n=Wo(n,ge),r=Go(r,this[rc].empty),this[Ee]==="opening")return this.defer(()=>this.batch(e,r,n)),n[ge];if(_a(this,n))return n[ge];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[ge];if(e.length===0)return this.nextTick(n),n[ge];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[ge];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[ge];let d=this._checkKey(u.key);if(d)return this.nextTick(n,d),n[ge];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[ge];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[ge]}_batch(e,r,n){this.nextTick(n)}sublevel(e,r){return this._sublevel(e,nm.defaults(r))}_sublevel(e,r){return new nm(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=ec(e,r),r=Wo(r,ge),e=Go(e,this[rc].empty),this[Ee]==="opening")return this.defer(()=>this.clear(e,r)),r[ge];if(_a(this,r))return r[ge];let n=e,i=this.keyEncoding(e.keyEncoding);return e=bh(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[ge]}_clear(e,r){this.nextTick(r)}iterator(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=bh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[Qs.keyEncoding]=r,e[Qs.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[Ee]==="opening")return new GU(this,e);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new Qs(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=bh(e,r),e[Qs.keyEncoding]=r,e[Qs.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[Ee]==="opening")return new zU(this,e);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new jU(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=bh(e,r),e[Qs.keyEncoding]=r,e[Qs.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[Ee]==="opening")return new YU(this,e);if(this[Ee]!=="open")throw new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new WU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[Rd].push(e)}[Ud](){if(this[Rd].length===0)return;let e=this[Rd];this[Rd]=[];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[tc].add(e)}detachResource(e){this[tc].delete(e)}_chainedBatch(){return new x2(this)}_checkKey(e){if(e==null)return new Tn("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new Tn("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};Od.prototype.nextTick=p2();var{AbstractSublevel:nm}=b2()({AbstractLevel:Od});im.AbstractLevel=Od;im.AbstractSublevel=nm;var _a=function(t,e){return t[Ee]!=="open"?(t.nextTick(e,new Tn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},XU=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var sm=oe(nc=>{"use strict";l();nc.AbstractLevel=om().AbstractLevel;nc.AbstractSublevel=om().AbstractSublevel;nc.AbstractIterator=Fo().AbstractIterator;nc.AbstractKeyIterator=Fo().AbstractKeyIterator;nc.AbstractValueIterator=Fo().AbstractValueIterator;nc.AbstractChainedBatch=Gg().AbstractChainedBatch});var S2=oe((lF,v2)=>{l();v2.exports=QU;var ZU=Yg();function QU(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?ZU(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 cm=oe((pF,A2)=>{"use strict";l();A2.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 am=oe((gF,T2)=>{"use strict";l();var eO=new TextEncoder;T2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):eO.encode(t)}});var U2=oe(R2=>{"use strict";l();var{AbstractIterator:tO}=sm(),_2=cm(),vh=am(),ri=Symbol("cache"),zi=Symbol("finished"),Pr=Symbol("options"),Yi=Symbol("currentOptions"),ic=Symbol("position"),um=Symbol("location"),Ia=Symbol("first"),I2={},dm=class extends tO{constructor(e,r,n){super(e,n),this[ri]=[],this[zi]=this.limit===0,this[Pr]=n,this[Yi]={...n},this[ic]=void 0,this[um]=r,this[Ia]=!0}_nextv(e,r,n){if(this[Ia]=!1,this[zi])return this.nextTick(n,null,[]);if(this[ri].length>0)return e=Math.min(e,this[ri].length),this.nextTick(n,null,this[ri].splice(0,e));this[ic]!==void 0&&(this[Pr].reverse?(this[Yi].lt=this[ic],this[Yi].lte=void 0):(this[Yi].gt=this[ic],this[Yi].gte=void 0));let i;try{i=_2(this[Yi])}catch{return this[zi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[um]],"readonly"),s=o.objectStore(this[um]),c=[];if(this[Pr].reverse){let a=!this[Pr].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[ic]=f,c.push([this[Pr].keys&&f!==void 0?vh(f):void 0,this[Pr].values&&h!==void 0?vh(h):void 0]),c.length<e?d.continue():B2(o)}else this[zi]=!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[zi]=!0:this[ic]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[Pr].keys&&p!==void 0?vh(p):void 0,this[Pr].values&&g!==void 0?vh(g):void 0]}B2(o)};this[Pr].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[Pr].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[ri].length>0){let[r,n]=this[ri].shift();this.nextTick(e,null,r,n)}else if(this[zi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[Ia]&&(this[Ia]=!1,r=1),this._nextv(r,I2,(n,i)=>{if(n)return e(n);this[ri]=i,this._next(e)})}}_all(e,r){this[Ia]=!1;let n=this[ri].splice(0,this[ri].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(r,null,n);this._nextv(i,I2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[Ia]=!0,this[ri]=[],this[zi]=!1,this[ic]=void 0,this[Yi]={...this[Pr]};let n;try{n=_2(this[Pr])}catch{this[zi]=!0;return}n!==null&&!n.includes(e)?this[zi]=!0:this[Pr].reverse?this[Yi].lte=e:this[Yi].gte=e}};R2.Iterator=dm;function B2(t){typeof t.commit=="function"&&t.commit()}});var D2=oe((xF,O2)=>{"use strict";l();O2.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 M2=oe(P2=>{"use strict";l();var{AbstractLevel:rO}=sm(),k2=Sn(),nO=S2(),{fromCallback:iO}=wd(),{Iterator:oO}=U2(),N2=am(),sO=D2(),cO=cm(),L2="level-js-",Dd=Symbol("idb"),fm=Symbol("namePrefix"),Ji=Symbol("location"),lm=Symbol("version"),oc=Symbol("store"),kd=Symbol("onComplete"),C2=Symbol("promise"),Sh=class extends rO{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new k2("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[fm]=i??L2,this[lm]=parseInt(o||1,10),this[Dd]=null}get location(){return this[Ji]}get namePrefix(){return this[fm]}get version(){return this[lm]}get db(){return this[Dd]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[fm]+this[Ji],this[lm]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[Dd]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[Ji])||o.createObjectStore(this[Ji])}}[oc](e){return this[Dd].transaction([this[Ji]],e).objectStore(this[Ji])}[kd](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[oc]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[kd](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new k2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,N2(c))})}_getMany(e,r,n){let i=this[oc]("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:N2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});nO(o,16,n)}_del(e,r,n){let i=this[oc]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[kd](o,n)}_put(e,r,n,i){let o=this[oc]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[kd](s,i)}_iterator(e){return new oO(this,this[Ji],e)}_batch(e,r,n){let i=this[oc]("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=cO(e)}catch{return this.nextTick(r)}if(e.limit>=0)return sO(this,this[Ji],n,e,r);try{let o=this[oc]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[kd](i,r)}_close(e){this[Dd].close(),this.nextTick(e)}};Sh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=L2),r=iO(r,C2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[C2]};P2.BrowserLevel=Sh});var hm=oe(K2=>{l();K2.Level=M2().BrowserLevel});var ot=oe((OF,$2)=>{"use strict";l();$2.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((kF,Th)=>{"use strict";l();var{AbortController:H2,AbortSignal:uO}=typeof self<"u"?self:typeof window<"u"?window:void 0;Th.exports=H2;Th.exports.AbortSignal=uO;Th.exports.default=H2});var Xt=oe((CF,ym)=>{"use strict";l();var dO=_r(),{kResistStopPropagation:fO,SymbolDispose:lO}=ot(),hO=globalThis.AbortSignal||Ba().AbortSignal,pO=globalThis.AbortController||Ba().AbortController,yO=Object.getPrototypeOf(async function(){}).constructor,V2=globalThis.Blob||dO.Blob,gO=typeof V2<"u"?function(e){return e instanceof V2}:function(e){return!1},q2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},mO=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},pm=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}};ym.exports={AggregateError:pm,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 yO},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:gO,deprecate(t,e){return t},addAbortListener:ma().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);q2(e,"signal"),mO(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[fO]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[lO](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:hO.any||function(e){if(e.length===1)return e[0];let r=new pO,n=()=>r.abort();return e.forEach(i=>{q2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};ym.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var sr=oe((PF,W2)=>{"use strict";l();var{format:wO,inspect:_h,AggregateError:bO}=Xt(),xO=globalThis.AggregateError||bO,EO=Symbol("kIsNodeError"),vO=["string","function","number","object","Function","Object","boolean","bigint","symbol"],SO=/^([A-Z][a-z0-9]*)+$/,AO="__node_internal_",Ih={};function cc(t,e){if(!t)throw new Ih.ERR_INTERNAL_ASSERTION(e)}function F2(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 TO(t,e,r){if(typeof e=="function")return cc(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 cc(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:wO(e,...r)}function Kt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(TO(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[EO]=!0,Ih[t]=n}function j2(t){let e=AO+t.name;return Object.defineProperty(t,"name",{value:e}),t}function _O(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new xO([e,t],e.message);return r.code=e.code,r}return t||e}var gm=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new Ih.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)=>{cc(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)cc(typeof a=="string","All expected entries have to be of type string"),vO.includes(a)?i.push(a.toLowerCase()):SO.test(a)?o.push(a):(cc(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=_h(r,{depth:-1});n+=`. Received ${a}`}}else{let a=_h(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=_h(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)=>{cc(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)=>{cc(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=F2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=F2(n)),n+="n"):n=_h(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);W2.exports={AbortError:gm,aggregateTwoErrors:j2(_O),hideStackFrames:j2,codes:Ih}});var Ua=oe((KF,rS)=>{"use strict";l();var{ArrayIsArray:wm,ArrayPrototypeIncludes:J2,ArrayPrototypeJoin:X2,ArrayPrototypeMap:IO,NumberIsInteger:bm,NumberIsNaN:BO,NumberMAX_SAFE_INTEGER:RO,NumberMIN_SAFE_INTEGER:UO,NumberParseInt:OO,ObjectPrototypeHasOwnProperty:DO,RegExpPrototypeExec:Z2,String:kO,StringPrototypeToUpperCase:NO,StringPrototypeTrim:CO}=ot(),{hideStackFrames:on,codes:{ERR_SOCKET_BAD_PORT:LO,ERR_INVALID_ARG_TYPE:Zt,ERR_INVALID_ARG_VALUE:Ra,ERR_OUT_OF_RANGE:ac,ERR_UNKNOWN_SIGNAL:G2}}=sr(),{normalizeEncoding:PO}=Xt(),{isAsyncFunction:MO,isArrayBufferView:KO}=Xt().types,z2={};function $O(t){return t===(t|0)}function HO(t){return t===t>>>0}var VO=/^[0-7]+$/,qO="must be a 32-bit unsigned integer or an octal string";function FO(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(Z2(VO,t)===null)throw new Ra(e,t,qO);t=OO(t,8)}return Q2(t,e),t}var jO=on((t,e,r=UO,n=RO)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!bm(t))throw new ac(e,"an integer",t);if(t<r||t>n)throw new ac(e,`>= ${r} && <= ${n}`,t)}),WO=on((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!bm(t))throw new ac(e,"an integer",t);if(t<r||t>n)throw new ac(e,`>= ${r} && <= ${n}`,t)}),Q2=on((t,e,r=!1)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!bm(t))throw new ac(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new ac(e,`>= ${n} && <= ${i}`,t)});function xm(t,e){if(typeof t!="string")throw new Zt(e,"string",t)}function GO(t,e,r=void 0,n){if(typeof t!="number")throw new Zt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&BO(t))throw new ac(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var zO=on((t,e,r)=>{if(!J2(r,t)){let i="must be one of: "+X2(IO(r,o=>typeof o=="string"?`'${o}'`:kO(o)),", ");throw new Ra(e,t,i)}});function eS(t,e){if(typeof t!="boolean")throw new Zt(e,"boolean",t)}function mm(t,e,r){return t==null||!DO(t,e)?r:t[e]}var YO=on((t,e,r=null)=>{let n=mm(r,"allowArray",!1),i=mm(r,"allowFunction",!1);if(!mm(r,"nullable",!1)&&t===null||!n&&wm(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new Zt(e,"Object",t)}),JO=on((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Zt(e,"a dictionary",t)}),Bh=on((t,e,r=0)=>{if(!wm(t))throw new Zt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new Ra(e,t,n)}});function XO(t,e){Bh(t,e);for(let r=0;r<t.length;r++)xm(t[r],`${e}[${r}]`)}function ZO(t,e){Bh(t,e);for(let r=0;r<t.length;r++)eS(t[r],`${e}[${r}]`)}function QO(t,e){Bh(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Zt(i,"AbortSignal",n);tS(n,i)}}function e5(t,e="signal"){if(xm(t,e),z2[t]===void 0)throw z2[NO(t)]!==void 0?new G2(t+" (signals must use all capital letters)"):new G2(t)}var t5=on((t,e="buffer")=>{if(!KO(t))throw new Zt(e,["Buffer","TypedArray","DataView"],t)});function r5(t,e){let r=PO(e),n=t.length;if(r==="hex"&&n%2!==0)throw new Ra("encoding",e,`is invalid for data of length ${n}`)}function n5(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&CO(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new LO(e,t,r);return t|0}var tS=on((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Zt(e,"AbortSignal",t)}),i5=on((t,e)=>{if(typeof t!="function")throw new Zt(e,"Function",t)}),o5=on((t,e)=>{if(typeof t!="function"||MO(t))throw new Zt(e,"Function",t)}),s5=on((t,e)=>{if(t!==void 0)throw new Zt(e,"undefined",t)});function c5(t,e,r){if(!J2(r,t))throw new Zt(e,`('${X2(r,"|")}')`,t)}var a5=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function Y2(t,e){if(typeof t>"u"||!Z2(a5,t))throw new Ra(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function u5(t){if(typeof t=="string")return Y2(t,"hints"),t;if(wm(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];Y2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new Ra("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}rS.exports={isInt32:$O,isUint32:HO,parseFileMode:FO,validateArray:Bh,validateStringArray:XO,validateBooleanArray:ZO,validateAbortSignalArray:QO,validateBoolean:eS,validateBuffer:t5,validateDictionary:JO,validateEncoding:r5,validateFunction:i5,validateInt32:WO,validateInteger:jO,validateNumber:GO,validateObject:YO,validateOneOf:zO,validatePlainFunction:o5,validatePort:n5,validateSignalName:e5,validateString:xm,validateUint32:Q2,validateUndefined:s5,validateUnion:c5,validateAbortSignal:tS,validateLinkHeaderValue:u5}});var ii=oe((HF,mS)=>{"use strict";l();var{SymbolAsyncIterator:nS,SymbolIterator:iS,SymbolFor:uc}=ot(),oS=uc("nodejs.stream.destroyed"),sS=uc("nodejs.stream.errored"),Em=uc("nodejs.stream.readable"),vm=uc("nodejs.stream.writable"),cS=uc("nodejs.stream.disturbed"),d5=uc("nodejs.webstream.isClosedPromise"),f5=uc("nodejs.webstream.controllerErrorFunction");function Rh(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 Uh(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 l5(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function ni(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function aS(t){return!!(t&&!ni(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function uS(t){return!!(t&&!ni(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function dS(t){return!!(t&&!ni(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function h5(t){return aS(t)||uS(t)||dS(t)}function p5(t,e){return t==null?!1:e===!0?typeof t[nS]=="function":e===!1?typeof t[iS]=="function":typeof t[nS]=="function"||typeof t[iS]=="function"}function Oh(t){if(!ni(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[oS]||n!=null&&n.destroyed)}function fS(t){if(!Uh(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 y5(t,e){if(!Uh(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 g5(t){if(!Rh(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 lS(t,e){if(!Rh(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 hS(t){return t&&t[Em]!=null?t[Em]:typeof t?.readable!="boolean"?null:Oh(t)?!1:Rh(t)&&t.readable&&!lS(t)}function pS(t){return t&&t[vm]!=null?t[vm]:typeof t?.writable!="boolean"?null:Oh(t)?!1:Uh(t)&&t.writable&&!fS(t)}function m5(t,e){return ni(t)?Oh(t)?!0:!(e?.readable!==!1&&hS(t)||e?.writable!==!1&&pS(t)):null}function w5(t){var e,r;return ni(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 b5(t){var e,r;return ni(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 x5(t){if(!ni(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"&&yS(t)?t._closed:null}function yS(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function gS(t){return typeof t._sent100=="boolean"&&yS(t)}function E5(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 v5(t){if(!ni(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&gS(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function S5(t){var e;return!!(t&&((e=t[cS])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function A5(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[sS])!==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))}mS.exports={isDestroyed:Oh,kIsDestroyed:oS,isDisturbed:S5,kIsDisturbed:cS,isErrored:A5,kIsErrored:sS,isReadable:hS,kIsReadable:Em,kIsClosedPromise:d5,kControllerErrorFunction:f5,kIsWritable:vm,isClosed:x5,isDuplexNodeStream:l5,isFinished:m5,isIterable:p5,isReadableNodeStream:Rh,isReadableStream:aS,isReadableEnded:g5,isReadableFinished:lS,isReadableErrored:b5,isNodeStream:ni,isWebStream:h5,isWritable:pS,isWritableNodeStream:Uh,isWritableStream:uS,isWritableEnded:fS,isWritableFinished:y5,isWritableErrored:w5,isServerRequest:E5,isServerResponse:gS,willEmitClose:v5,isTransformStream:dS}});var Xi=oe((qF,Im)=>{l();var zo=Si(),{AbortError:_S,codes:T5}=sr(),{ERR_INVALID_ARG_TYPE:_5,ERR_STREAM_PREMATURE_CLOSE:wS}=T5,{kEmptyObject:Am,once:Tm}=Xt(),{validateAbortSignal:I5,validateFunction:B5,validateObject:R5,validateBoolean:U5}=Ua(),{Promise:O5,PromisePrototypeThen:D5,SymbolDispose:IS}=ot(),{isClosed:k5,isReadable:bS,isReadableNodeStream:Sm,isReadableStream:N5,isReadableFinished:xS,isReadableErrored:ES,isWritable:vS,isWritableNodeStream:SS,isWritableStream:C5,isWritableFinished:AS,isWritableErrored:TS,isNodeStream:L5,willEmitClose:P5,kIsClosedPromise:M5}=ii(),Oa;function K5(t){return t.setHeader&&typeof t.abort=="function"}var _m=()=>{};function BS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=Am):e==null?e=Am:R5(e,"options"),B5(r,"callback"),I5(e.signal,"options.signal"),r=Tm(r),N5(t)||C5(t))return $5(t,e,r);if(!L5(t))throw new _5("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:SS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=P5(t)&&Sm(t)===o&&SS(t)===s,f=AS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=xS(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=k5(t),S=()=>{x=!0;let T=TS(t)||ES(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&Sm(t,!0)&&!xS(t,!1))return r.call(t,new wS);if(s&&!f&&!AS(t,!1))return r.call(t,new wS);r.call(t)},I=()=>{x=!0;let T=TS(t)||ES(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};K5(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?zo.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||zo.nextTick(I):(!o&&(!d||bS(t))&&(f||vS(t)===!1)||!s&&(!d||vS(t))&&(p||bS(t)===!1)||a&&t.req&&t.aborted)&&zo.nextTick(I);let O=()=>{r=_m,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 _S(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)zo.nextTick(T);else{Oa=Oa||Xt().addAbortListener;let M=Oa(e.signal,T),q=r;r=Tm((...j)=>{M[IS](),q.apply(t,j)})}}return O}function $5(t,e,r){let n=!1,i=_m;if(e.signal)if(i=()=>{n=!0,r.call(t,new _S(void 0,{cause:e.signal.reason}))},e.signal.aborted)zo.nextTick(i);else{Oa=Oa||Xt().addAbortListener;let s=Oa(e.signal,i),c=r;r=Tm((...a)=>{s[IS](),c.apply(t,a)})}let o=(...s)=>{n||zo.nextTick(()=>r.apply(t,s))};return D5(t[M5].promise,o,o),_m}function H5(t,e){var r;let n=!1;return e===null&&(e=Am),(r=e)!==null&&r!==void 0&&r.cleanup&&(U5(e.cleanup,"cleanup"),n=e.cleanup),new O5((i,o)=>{let s=BS(t,e,c=>{n&&s(),c?o(c):i()})})}Im.exports=BS;Im.exports.finished=H5});var dc=oe((jF,LS)=>{"use strict";l();var oi=Si(),{aggregateTwoErrors:V5,codes:{ERR_MULTIPLE_CALLBACK:q5},AbortError:F5}=sr(),{Symbol:OS}=ot(),{kIsDestroyed:j5,isDestroyed:W5,isFinished:G5,isServerRequest:z5}=ii(),DS=OS("kDestroy"),Bm=OS("kConstruct");function kS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function Y5(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):(kS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?RS(this,t,e):this.once(DS,function(o){RS(this,V5(o,t),e)}),this)}function RS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;kS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?oi.nextTick(J5,t,o):oi.nextTick(NS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function J5(t,e){Rm(t,e),NS(t)}function NS(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 Rm(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 X5(){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 Um(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?oi.nextTick(Rm,t,e):Rm(t,e))}function Z5(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(Bm,e),!(t.listenerCount(Bm)>1)&&oi.nextTick(Q5,t)}function Q5(t){let e=!1;function r(n){if(e){Um(t,n??new q5);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(DS,n):n?Um(t,n,!0):oi.nextTick(e3,t)}try{t._construct(n=>{oi.nextTick(r,n)})}catch(n){oi.nextTick(r,n)}}function e3(t){t.emit(Bm)}function US(t){return t?.setHeader&&typeof t.abort=="function"}function CS(t){t.emit("close")}function t3(t,e){t.emit("error",e),oi.nextTick(CS,t)}function r3(t,e){!t||W5(t)||(!e&&!G5(t)&&(e=new F5),z5(t)?(t.socket=null,t.destroy(e)):US(t)?t.abort():US(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?oi.nextTick(t3,t,e):oi.nextTick(CS,t),t.destroyed||(t[j5]=!0))}LS.exports={construct:Z5,destroyer:r3,destroy:Y5,undestroy:X5,errorOrDestroy:Um}});var Nh=oe((GF,MS)=>{"use strict";l();var{ArrayIsArray:n3,ObjectSetPrototypeOf:PS}=ot(),{EventEmitter:Dh}=ma();function kh(t){Dh.call(this,t)}PS(kh.prototype,Dh.prototype);PS(kh,Dh);kh.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(),Dh.listenerCount(this,"error")===0&&this.emit("error",d)}Om(r,"error",a),Om(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 Om(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):n3(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}MS.exports={Stream:kh,prependListener:Om}});var Nd=oe((YF,Ch)=>{"use strict";l();var{SymbolDispose:i3}=ot(),{AbortError:KS,codes:o3}=sr(),{isNodeStream:$S,isWebStream:s3,kControllerErrorFunction:c3}=ii(),a3=Xi(),{ERR_INVALID_ARG_TYPE:HS}=o3,Dm,u3=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new HS(e,"AbortSignal",t)};Ch.exports.addAbortSignal=function(e,r){if(u3(e,"signal"),!$S(r)&&!s3(r))throw new HS("stream",["ReadableStream","WritableStream","Stream"],r);return Ch.exports.addAbortSignalNoValidate(e,r)};Ch.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=$S(e)?()=>{e.destroy(new KS(void 0,{cause:t.reason}))}:()=>{e[c3](new KS(void 0,{cause:t.reason}))};if(t.aborted)r();else{Dm=Dm||Xt().addAbortListener;let n=Dm(t,r);a3(e,n[i3])}return e}});var FS=oe((ZF,qS)=>{"use strict";l();var{StringPrototypeSlice:VS,SymbolIterator:d3,TypedArrayPrototypeSet:Lh,Uint8Array:f3}=ot(),{Buffer:km}=_r(),{inspect:l3}=Xt();qS.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 km.alloc(0);let r=km.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)Lh(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}*[d3](){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+=VS(o,0,e),this.head=n,n.data=VS(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=km.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)Lh(r,s,n-e),e-=s.length;else{e===s.length?(Lh(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(Lh(r,new f3(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 l3(this,{...r,depth:0,customInspect:!1})}}});var Cd=oe((ej,zS)=>{"use strict";l();var{MathFloor:h3,NumberIsInteger:p3}=ot(),{validateInteger:y3}=Ua(),{ERR_INVALID_ARG_VALUE:g3}=sr().codes,jS=16*1024,WS=16;function m3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function GS(t){return t?WS:jS}function w3(t,e){y3(e,"value",0),t?WS=e:jS=e}function b3(t,e,r,n){let i=m3(e,n,r);if(i!=null){if(!p3(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new g3(o,i)}return h3(i)}return GS(t.objectMode)}zS.exports={getHighWaterMark:b3,getDefaultHighWaterMark:GS,setDefaultHighWaterMark:w3}});var XS=oe((Nm,JS)=>{l();var Ph=_r(),si=Ph.Buffer;function YS(t,e){for(var r in t)e[r]=t[r]}si.from&&si.alloc&&si.allocUnsafe&&si.allocUnsafeSlow?JS.exports=Ph:(YS(Ph,Nm),Nm.Buffer=fc);function fc(t,e,r){return si(t,e,r)}fc.prototype=Object.create(si.prototype);YS(si,fc);fc.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return si(t,e,r)};fc.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=si(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};fc.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return si(t)};fc.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Ph.SlowBuffer(t)}});var eA=oe(QS=>{"use strict";l();var Lm=XS().Buffer,ZS=Lm.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 x3(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 E3(t){var e=x3(t);if(typeof e!="string"&&(Lm.isEncoding===ZS||!ZS(t)))throw new Error("Unknown encoding: "+t);return e||t}QS.StringDecoder=Ld;function Ld(t){this.encoding=E3(t);var e;switch(this.encoding){case"utf16le":this.text=I3,this.end=B3,e=4;break;case"utf8":this.fillLast=A3,e=4;break;case"base64":this.text=R3,this.end=U3,e=3;break;default:this.write=O3,this.end=D3;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Lm.allocUnsafe(e)}Ld.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||""};Ld.prototype.end=_3;Ld.prototype.text=T3;Ld.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 Cm(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function v3(t,e,r){var n=e.length-1;if(n<r)return 0;var i=Cm(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=Cm(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=Cm(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function S3(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 A3(t){var e=this.lastTotal-this.lastNeed,r=S3(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 T3(t,e){var r=v3(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 _3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function I3(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 B3(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 R3(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 U3(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function O3(t){return t.toString(this.encoding)}function D3(t){return t&&t.length?this.write(t):""}});var Pm=oe((oj,iA)=>{"use strict";l();var tA=Si(),{PromisePrototypeThen:k3,SymbolAsyncIterator:rA,SymbolIterator:nA}=ot(),{Buffer:N3}=_r(),{ERR_INVALID_ARG_TYPE:C3,ERR_STREAM_NULL_VALUES:L3}=sr().codes;function P3(t,e,r){let n;if(typeof e=="string"||e instanceof N3)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[rA])i=!0,n=e[rA]();else if(e&&e[nA])i=!1,n=e[nA]();else throw new C3("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){k3(c(u),()=>tA.nextTick(d,u),f=>tA.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 L3;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}iA.exports=P3});var Md=oe((cj,vA)=>{l();var _n=Si(),{ArrayPrototypeIndexOf:M3,NumberIsInteger:K3,NumberIsNaN:$3,NumberParseInt:H3,ObjectDefineProperties:jm,ObjectKeys:V3,ObjectSetPrototypeOf:cA,Promise:aA,SafeSet:q3,SymbolAsyncDispose:F3,SymbolAsyncIterator:j3,Symbol:W3}=ot();vA.exports=me;me.ReadableState=Hh;var{EventEmitter:G3}=ma(),{Stream:Yo,prependListener:z3}=Nh(),{Buffer:Mm}=_r(),{addAbortSignal:Y3}=Nd(),uA=Xi(),Se=Xt().debuglog("stream",t=>{Se=t}),J3=FS(),Na=dc(),{getHighWaterMark:X3,getDefaultHighWaterMark:Z3}=Cd(),{aggregateTwoErrors:oA,codes:{ERR_INVALID_ARG_TYPE:Q3,ERR_METHOD_NOT_IMPLEMENTED:eD,ERR_OUT_OF_RANGE:tD,ERR_STREAM_PUSH_AFTER_EOF:rD,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:nD},AbortError:iD}=sr(),{validateObject:oD}=Ua(),lc=W3("kPaused"),{StringDecoder:dA}=eA(),sD=Pm();cA(me.prototype,Yo.prototype);cA(me,Yo);var Km=()=>{},{errorOrDestroy:Da}=Na,ka=1,cD=2,fA=4,Pd=8,lA=16,Mh=32,Kh=64,hA=128,aD=256,uD=512,dD=1024,qm=2048,Fm=4096,fD=8192,lD=16384,hD=32768,pA=65536,pD=1<<17,yD=1<<18;function At(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}jm(Hh.prototype,{objectMode:At(ka),ended:At(cD),endEmitted:At(fA),reading:At(Pd),constructed:At(lA),sync:At(Mh),needReadable:At(Kh),emittedReadable:At(hA),readableListening:At(aD),resumeScheduled:At(uD),errorEmitted:At(dD),emitClose:At(qm),autoDestroy:At(Fm),destroyed:At(fD),closed:At(lD),closeEmitted:At(hD),multiAwaitDrain:At(pA),readingMore:At(pD),dataEmitted:At(yD)});function Hh(t,e,r){typeof r!="boolean"&&(r=e instanceof ci()),this.state=qm|Fm|lA|Mh,t&&t.objectMode&&(this.state|=ka),r&&t&&t.readableObjectMode&&(this.state|=ka),this.highWaterMark=t?X3(this,t,"readableHighWaterMark",r):Z3(!1),this.buffer=new J3,this.length=0,this.pipes=[],this.flowing=null,this[lc]=null,t&&t.emitClose===!1&&(this.state&=~qm),t&&t.autoDestroy===!1&&(this.state&=~Fm),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new dA(t.encoding),this.encoding=t.encoding)}function me(t){if(!(this instanceof me))return new me(t);let e=this instanceof ci();this._readableState=new Hh(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&&Y3(t.signal,this)),Yo.call(this,t),Na.construct(this,()=>{this._readableState.needReadable&&$h(this,this._readableState)})}me.prototype.destroy=Na.destroy;me.prototype._undestroy=Na.undestroy;me.prototype._destroy=function(t,e){e(t)};me.prototype[G3.captureRejectionSymbol]=function(t){this.destroy(t)};me.prototype[F3]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new iD,this.destroy(t)),new aA((e,r)=>uA(this,n=>n&&n!==t?r(n):e(null)))};me.prototype.push=function(t,e){return yA(this,t,e,!1)};me.prototype.unshift=function(t,e){return yA(this,t,e,!0)};function yA(t,e,r,n){Se("readableAddChunk",e);let i=t._readableState,o;if(i.state&ka||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=Mm.from(e,r).toString(i.encoding):(e=Mm.from(e,r),r=""))):e instanceof Mm?r="":Yo._isUint8Array(e)?(e=Yo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new Q3("chunk",["string","Buffer","Uint8Array"],e))),o)Da(t,o);else if(e===null)i.state&=~Pd,wD(t,i);else if(i.state&ka||e&&e.length>0)if(n)if(i.state&fA)Da(t,new nD);else{if(i.destroyed||i.errored)return!1;$m(t,i,e,!0)}else if(i.ended)Da(t,new rD);else{if(i.destroyed||i.errored)return!1;i.state&=~Pd,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?$m(t,i,e,!1):$h(t,i)):$m(t,i,e,!1)}else n||(i.state&=~Pd,$h(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function $m(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&pA?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&Kh&&Vh(t)),$h(t,e)}me.prototype.isPaused=function(){let t=this._readableState;return t[lc]===!0||t.flowing===!1};me.prototype.setEncoding=function(t){let e=new dA(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 gD=1073741824;function mD(t){if(t>gD)throw new tD("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function sA(t,e){return t<=0||e.length===0&&e.ended?0:e.state&ka?1:$3(t)?e.flowing&&e.length?e.buffer.first().length:e.length:t<=e.length?t:e.ended?e.length:0}me.prototype.read=function(t){Se("read",t),t===void 0?t=NaN:K3(t)||(t=H3(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=mD(t)),t!==0&&(e.state&=~hA),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return Se("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Hm(this):Vh(this),null;if(t=sA(t,e),t===0&&e.ended)return e.length===0&&Hm(this),null;let n=(e.state&Kh)!==0;if(Se("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,Se("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,Se("reading, ended or constructing",n);else if(n){Se("do read"),e.state|=Pd|Mh,e.length===0&&(e.state|=Kh);try{this._read(e.highWaterMark)}catch(o){Da(this,o)}e.state&=~Mh,e.reading||(t=sA(r,e))}let i;return t>0?i=xA(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&&Hm(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function wD(t,e){if(Se("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?Vh(t):(e.needReadable=!1,e.emittedReadable=!0,gA(t))}}function Vh(t){let e=t._readableState;Se("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(Se("emitReadable",e.flowing),e.emittedReadable=!0,_n.nextTick(gA,t))}function gA(t){let e=t._readableState;Se("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,wA(t)}function $h(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,_n.nextTick(bD,t,e))}function bD(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(Se("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}me.prototype._read=function(t){throw new eD("_read()")};me.prototype.pipe=function(t,e){let r=this,n=this._readableState;n.pipes.length===1&&(n.multiAwaitDrain||(n.multiAwaitDrain=!0,n.awaitDrainWriters=new q3(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),Se("pipe count=%d opts=%j",n.pipes.length,e);let o=(!e||e.end!==!1)&&t!==_n.stdout&&t!==_n.stderr?c:x;n.endEmitted?_n.nextTick(o):r.once("end",o),t.on("unpipe",s);function s(S,I){Se("onunpipe"),S===r&&I&&I.hasUnpiped===!1&&(I.hasUnpiped=!0,d())}function c(){Se("onend"),t.end()}let a,u=!1;function d(){Se("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?(Se("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(Se("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=xD(r,t),t.on("drain",a))}r.on("data",h);function h(S){Se("ondata");let I=t.write(S);Se("dest.write",I),I===!1&&f()}function p(S){if(Se("onerror",S),x(),t.removeListener("error",p),t.listenerCount("error")===0){let I=t._writableState||t._readableState;I&&!I.errorEmitted?Da(t,S):t.emit("error",S)}}z3(t,"error",p);function g(){t.removeListener("finish",y),x()}t.once("close",g);function y(){Se("onfinish"),t.removeListener("close",g),x()}t.once("finish",y);function x(){Se("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(Se("pipe resume"),r.resume()),t};function xD(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(Se("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(Se("pipeOnDrain",n.awaitDrainWriters.size),n.awaitDrainWriters.delete(e)),(!n.awaitDrainWriters||n.awaitDrainWriters.size===0)&&t.listenerCount("data")&&t.resume()}}me.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=M3(e.pipes,t);return n===-1?this:(e.pipes.splice(n,1),e.pipes.length===0&&this.pause(),t.emit("unpipe",this,r),this)};me.prototype.on=function(t,e){let r=Yo.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,Se("on readable",n.length,n.reading),n.length?Vh(this):n.reading||_n.nextTick(ED,this)),r};me.prototype.addListener=me.prototype.on;me.prototype.removeListener=function(t,e){let r=Yo.prototype.removeListener.call(this,t,e);return t==="readable"&&_n.nextTick(mA,this),r};me.prototype.off=me.prototype.removeListener;me.prototype.removeAllListeners=function(t){let e=Yo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&_n.nextTick(mA,this),e};function mA(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[lc]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function ED(t){Se("readable nexttick read 0"),t.read(0)}me.prototype.resume=function(){let t=this._readableState;return t.flowing||(Se("resume"),t.flowing=!t.readableListening,vD(this,t)),t[lc]=!1,this};function vD(t,e){e.resumeScheduled||(e.resumeScheduled=!0,_n.nextTick(SD,t,e))}function SD(t,e){Se("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),wA(t),e.flowing&&!e.reading&&t.read(0)}me.prototype.pause=function(){return Se("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(Se("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[lc]=!0,this};function wA(t){let e=t._readableState;for(Se("flow",e.flowing);e.flowing&&t.read()!==null;);}me.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=>{Da(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=V3(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};me.prototype[j3]=function(){return bA(this)};me.prototype.iterator=function(t){return t!==void 0&&oD(t,"options"),bA(this,t)};function bA(t,e){typeof t.read!="function"&&(t=me.wrap(t,{objectMode:!0}));let r=AD(t,e);return r.stream=t,r}async function*AD(t,e){let r=Km;function n(s){this===t?(r(),r=Km):r=s}t.on("readable",n);let i,o=uA(t,{writable:!1},s=>{i=s?oA(i,s):null,r(),r=Km});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 aA(n)}}}catch(s){throw i=oA(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Na.destroyer(t,null):(t.off("readable",n),o())}}jm(me.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}}});jm(Hh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[lc]!==!1},set(t){this[lc]=!!t}}});me._fromList=xA;function xA(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 Hm(t){let e=t._readableState;Se("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,_n.nextTick(TD,e,t))}function TD(t,e){if(Se("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)_n.nextTick(_D,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function _D(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}me.from=function(t,e){return sD(me,t,e)};var Vm;function EA(){return Vm===void 0&&(Vm={}),Vm}me.fromWeb=function(t,e){return EA().newStreamReadableFromReadableStream(t,e)};me.toWeb=function(t,e){return EA().newReadableStreamFromStreamReadable(t,e)};me.wrap=function(t,e){var r,n;return new me({objectMode:(r=(n=t.readableObjectMode)!==null&&n!==void 0?n:t.objectMode)!==null&&r!==void 0?r:!0,...e,destroy(i,o){Na.destroyer(t,i),o(i)}}).wrap(t)}});var Gh=oe((uj,NA)=>{l();var hc=Si(),{ArrayPrototypeSlice:TA,Error:ID,FunctionPrototypeSymbolHasInstance:_A,ObjectDefineProperty:IA,ObjectDefineProperties:BD,ObjectSetPrototypeOf:BA,StringPrototypeToLowerCase:RD,Symbol:UD,SymbolHasInstance:OD}=ot();NA.exports=st;st.WritableState=Hd;var{EventEmitter:DD}=ma(),Kd=Nh().Stream,{Buffer:qh}=_r(),Wh=dc(),{addAbortSignal:kD}=Nd(),{getHighWaterMark:ND,getDefaultHighWaterMark:CD}=Cd(),{ERR_INVALID_ARG_TYPE:LD,ERR_METHOD_NOT_IMPLEMENTED:PD,ERR_MULTIPLE_CALLBACK:RA,ERR_STREAM_CANNOT_PIPE:MD,ERR_STREAM_DESTROYED:$d,ERR_STREAM_ALREADY_FINISHED:KD,ERR_STREAM_NULL_VALUES:$D,ERR_STREAM_WRITE_AFTER_END:HD,ERR_UNKNOWN_ENCODING:UA}=sr().codes,{errorOrDestroy:Ca}=Wh;BA(st.prototype,Kd.prototype);BA(st,Kd);function zm(){}var La=UD("kOnFinished");function Hd(t,e,r){typeof r!="boolean"&&(r=e instanceof ci()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?ND(this,t,"writableHighWaterMark",r):CD(!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=qD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,jh(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[La]=[]}function jh(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Hd.prototype.getBuffer=function(){return TA(this.buffered,this.bufferedIndex)};IA(Hd.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function st(t){let e=this instanceof ci();if(!e&&!_A(st,this))return new st(t);this._writableState=new Hd(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&&kD(t.signal,this)),Kd.call(this,t),Wh.construct(this,()=>{let r=this._writableState;r.writing||Jm(this,r),Xm(this,r)})}IA(st,OD,{__proto__:null,value:function(t){return _A(this,t)?!0:this!==st?!1:t&&t._writableState instanceof Hd}});st.prototype.pipe=function(){Ca(this,new MD)};function OA(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"&&!qh.isEncoding(r))throw new UA(r);typeof n!="function"&&(n=zm)}if(e===null)throw new $D;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=qh.from(e,r),r="buffer");else if(e instanceof qh)r="buffer";else if(Kd._isUint8Array(e))e=Kd._uint8ArrayToBuffer(e),r="buffer";else throw new LD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new HD:i.destroyed&&(o=new $d("write")),o?(hc.nextTick(n,o),Ca(t,o,!0),o):(i.pendingcb++,VD(t,i,e,r,n))}st.prototype.write=function(t,e,r){return OA(this,t,e,r)===!0};st.prototype.cork=function(){this._writableState.corked++};st.prototype.uncork=function(){let t=this._writableState;t.corked&&(t.corked--,t.writing||Jm(this,t))};st.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=RD(e)),!qh.isEncoding(e))throw new UA(e);return this._writableState.defaultEncoding=e,this};function VD(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!==zm&&(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 SA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new $d("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function AA(t,e,r,n){--e.pendingcb,n(r),Ym(e),Ca(t,r)}function qD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){Ca(t,new RA);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?hc.nextTick(AA,t,r,e,i):AA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&Jm(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},hc.nextTick(FD,r.afterWriteTickInfo)):DA(t,r,1,i))}function FD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,DA(t,e,r,n)}function DA(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&&Ym(e),Xm(t,e)}function Ym(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 $d("write"))}let r=t[La].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new $d("end"))}jh(t)}function Jm(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?zm:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:TA(r,s);a.allBuffers=e.allBuffers,SA(t,e,!0,e.length,a,"",c),jh(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;SA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?jh(e):s>256?(r.splice(0,s),e.bufferedIndex=0):e.bufferedIndex=s}e.bufferProcessing=!1}st.prototype._write=function(t,e,r){if(this._writev)this._writev([{chunk:t,encoding:e}],r);else throw new PD("_write()")};st.prototype._writev=null;st.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=OA(this,t,e);o instanceof ID&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,Xm(this,n,!0),n.ended=!0):n.finished?i=new KD("end"):n.destroyed&&(i=new $d("end"))),typeof r=="function"&&(i||n.finished?hc.nextTick(r,i):n[La].push(r)),this};function Fh(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 jD(t,e){let r=!1;function n(i){if(r){Ca(t,i??RA());return}if(r=!0,e.pendingcb--,i){let o=e[La].splice(0);for(let s=0;s<o.length;s++)o[s](i);Ca(t,i,e.sync)}else Fh(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,hc.nextTick(Gm,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function WD(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,jD(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function Xm(t,e,r){Fh(e)&&(WD(t,e),e.pendingcb===0&&(r?(e.pendingcb++,hc.nextTick((n,i)=>{Fh(i)?Gm(n,i):i.pendingcb--},t,e)):Fh(e)&&(e.pendingcb++,Gm(t,e))))}function Gm(t,e){e.pendingcb--,e.finished=!0;let r=e[La].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()}}BD(st.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 GD=Wh.destroy;st.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[La].length)&&hc.nextTick(Ym,r),GD.call(this,t,e),this};st.prototype._undestroy=Wh.undestroy;st.prototype._destroy=function(t,e){e(t)};st.prototype[DD.captureRejectionSymbol]=function(t){this.destroy(t)};var Wm;function kA(){return Wm===void 0&&(Wm={}),Wm}st.fromWeb=function(t,e){return kA().newStreamWritableFromWritableStream(t,e)};st.toWeb=function(t){return kA().newWritableStreamFromStreamWritable(t)}});var YA=oe((fj,zA)=>{l();var Zm=Si(),zD=_r(),{isReadable:YD,isWritable:JD,isIterable:CA,isNodeStream:XD,isReadableNodeStream:LA,isWritableNodeStream:PA,isDuplexNodeStream:ZD,isReadableStream:MA,isWritableStream:KA}=ii(),$A=Xi(),{AbortError:WA,codes:{ERR_INVALID_ARG_TYPE:QD,ERR_INVALID_RETURN_VALUE:HA}}=sr(),{destroyer:Ma}=dc(),ek=ci(),GA=Md(),tk=Gh(),{createDeferredPromise:VA}=Xt(),qA=Pm(),FA=globalThis.Blob||zD.Blob,rk=typeof FA<"u"?function(e){return e instanceof FA}:function(e){return!1},nk=globalThis.AbortController||Ba().AbortController,{FunctionPrototypeCall:jA}=ot(),Jo=class extends ek{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)}};zA.exports=function t(e,r){if(ZD(e))return e;if(LA(e))return Pa({readable:e});if(PA(e))return Pa({writable:e});if(XD(e))return Pa({writable:!1,readable:!1});if(MA(e))return Pa({readable:GA.fromWeb(e)});if(KA(e))return Pa({writable:tk.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=ik(e);if(CA(i))return qA(Jo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=jA(a,i,f=>{if(f!=null)throw new HA("nully","body",f)},f=>{Ma(u,f)});return u=new Jo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,Zm.nextTick(f,null)}catch(h){Zm.nextTick(f,h)}})},destroy:c})}throw new HA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(rk(e))return t(e.arrayBuffer());if(CA(e))return qA(Jo,e,{objectMode:!0,writable:!1});if(MA(e?.readable)&&KA(e?.writable))return Jo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?LA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?PA(e?.writable)?e?.writable:t(e.writable):void 0;return Pa({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return jA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{Ma(i,o)}),i=new Jo({objectMode:!0,writable:!1,read(){}})}throw new QD(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function ik(t){let{promise:e,resolve:r}=VA(),n=new nk,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(Zm.nextTick(u),a)return;if(i.aborted)throw new WA(void 0,{cause:i.reason});({promise:e,resolve:r}=VA()),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 Pa(t){let e=t.readable&&typeof t.readable.read!="function"?GA.wrap(t.readable):t.readable,r=t.writable,n=!!YD(e),i=!!JD(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&&($A(r,f=>{i=!1,f&&Ma(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&&($A(e,f=>{n=!1,f&&Ma(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 WA),c=null,o=null,s=null,a===null?h(f):(a=h,Ma(r,f),Ma(e,f))},u}});var ci=oe((hj,ZA)=>{"use strict";l();var{ObjectDefineProperties:ok,ObjectGetOwnPropertyDescriptor:Zi,ObjectKeys:sk,ObjectSetPrototypeOf:JA}=ot();ZA.exports=In;var tw=Md(),sn=Gh();JA(In.prototype,tw.prototype);JA(In,tw);{let t=sk(sn.prototype);for(let e=0;e<t.length;e++){let r=t[e];In.prototype[r]||(In.prototype[r]=sn.prototype[r])}}function In(t){if(!(this instanceof In))return new In(t);tw.call(this,t),sn.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}ok(In.prototype,{writable:{__proto__:null,...Zi(sn.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Zi(sn.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Zi(sn.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Zi(sn.prototype,"writableBuffer")},writableLength:{__proto__:null,...Zi(sn.prototype,"writableLength")},writableFinished:{__proto__:null,...Zi(sn.prototype,"writableFinished")},writableCorked:{__proto__:null,...Zi(sn.prototype,"writableCorked")},writableEnded:{__proto__:null,...Zi(sn.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Zi(sn.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 Qm;function XA(){return Qm===void 0&&(Qm={}),Qm}In.fromWeb=function(t,e){return XA().newStreamDuplexFromReadableWritablePair(t,e)};In.toWeb=function(t){return XA().newReadableWritablePairFromDuplex(t)};var ew;In.from=function(t){return ew||(ew=YA()),ew(t,"body")}});var iw=oe((yj,eT)=>{"use strict";l();var{ObjectSetPrototypeOf:QA,Symbol:ck}=ot();eT.exports=Qi;var{ERR_METHOD_NOT_IMPLEMENTED:ak}=sr().codes,nw=ci(),{getHighWaterMark:uk}=Cd();QA(Qi.prototype,nw.prototype);QA(Qi,nw);var Vd=ck("kCallback");function Qi(t){if(!(this instanceof Qi))return new Qi(t);let e=t?uk(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),nw.call(this,t),this._readableState.sync=!1,this[Vd]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",dk)}function rw(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 dk(){this._final!==rw&&rw.call(this)}Qi.prototype._final=rw;Qi.prototype._transform=function(t,e,r){throw new ak("_transform()")};Qi.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[Vd]=r})};Qi.prototype._read=function(){if(this[Vd]){let t=this[Vd];this[Vd]=null,t()}}});var sw=oe((mj,rT)=>{"use strict";l();var{ObjectSetPrototypeOf:tT}=ot();rT.exports=Ka;var ow=iw();tT(Ka.prototype,ow.prototype);tT(Ka,ow);function Ka(t){if(!(this instanceof Ka))return new Ka(t);ow.call(this,t)}Ka.prototype._transform=function(t,e,r){r(null,t)}});var Xh=oe((bj,cT)=>{l();var qd=Si(),{ArrayIsArray:fk,Promise:lk,SymbolAsyncIterator:hk,SymbolDispose:pk}=ot(),Jh=Xi(),{once:yk}=Xt(),gk=dc(),nT=ci(),{aggregateTwoErrors:mk,codes:{ERR_INVALID_ARG_TYPE:yw,ERR_INVALID_RETURN_VALUE:cw,ERR_MISSING_ARGS:wk,ERR_STREAM_DESTROYED:bk,ERR_STREAM_PREMATURE_CLOSE:xk},AbortError:Ek}=sr(),{validateFunction:vk,validateAbortSignal:Sk}=Ua(),{isIterable:pc,isReadable:aw,isReadableNodeStream:Yh,isNodeStream:iT,isTransformStream:$a,isWebStream:Ak,isReadableStream:uw,isReadableFinished:Tk}=ii(),_k=globalThis.AbortController||Ba().AbortController,dw,fw,lw;function oT(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Jh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,gk.destroyer(t,o||new bk("pipe")))},cleanup:i}}function Ik(t){return vk(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function hw(t){if(pc(t))return t;if(Yh(t))return Bk(t);throw new yw("val",["Readable","Iterable","AsyncIterable"],t)}async function*Bk(t){fw||(fw=Md()),yield*fw.prototype[hk].call(t)}async function zh(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new lk((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Jh(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?mk(i,u):u)}finally{a(),e.off("drain",s)}}async function pw(t,e,r,{end:n}){$a(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 Rk(...t){return sT(t,yk(Ik(t)))}function sT(t,e,r){if(t.length===1&&fk(t[0])&&(t=t[0]),t.length<2)throw new wk("streams");let n=new _k,i=n.signal,o=r?.signal,s=[];Sk(o,"options.signal");function c(){g(new Ek)}lw=lw||Xt().addAbortListener;let a;o&&(a=lw(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[pk](),n.abort(),O&&(u||s.forEach(M=>M()),qd.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(iT(O)){let $=function(Z){Z&&Z.name!=="AbortError"&&Z.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(Z)};var I=$;if(q){let{destroy:Z,cleanup:Q}=oT(O,T,M);f.push(Z),aw(O)&&j&&s.push(Q)}O.on("error",$),aw(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!pc(y))throw new cw("Iterable, AsyncIterable or Stream","source",y)}else pc(O)||Yh(O)||$a(O)?y=O:y=nT.from(O);else if(typeof O=="function"){if($a(y)){var x;y=hw((x=y)===null||x===void 0?void 0:x.readable)}else y=hw(y);if(y=O(y,{signal:i}),T){if(!pc(y,!0))throw new cw("AsyncIterable",`transform[${A-1}]`,y)}else{var S;dw||(dw=sw());let $=new dw({objectMode:!0}),Z=(S=y)===null||S===void 0?void 0:S.then;if(typeof Z=="function")h++,Z.call(y,_=>{d=_,_!=null&&$.write(_),q&&$.end(),qd.nextTick(p)},_=>{$.destroy(_),qd.nextTick(p,_)});else if(pc(y,!0))h++,zh(y,$,p,{end:q});else if(uw(y)||$a(y)){let _=y.readable||y;h++,zh(_,$,p,{end:q})}else throw new cw("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=oT(y,!1,!0);f.push(Q),j&&s.push(G)}}else if(iT(O)){if(Yh(y)){h+=2;let $=Uk(y,O,p,{end:q});aw(O)&&j&&s.push($)}else if($a(y)||uw(y)){let $=y.readable||y;h++,zh($,O,p,{end:q})}else if(pc(y))h++,zh(y,O,p,{end:q});else throw new yw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(Ak(O)){if(Yh(y))h++,pw(hw(y),O,p,{end:q});else if(uw(y)||pc(y))h++,pw(y,O,p,{end:q});else if($a(y))h++,pw(y.readable,O,p,{end:q});else throw new yw("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=nT.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&qd.nextTick(c),y}function Uk(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new xk)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;Tk(t)?qd.nextTick(s):t.once("end",s)}else r();return Jh(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)}),Jh(e,{readable:!1,writable:!0},r)}cT.exports={pipelineImpl:sT,pipeline:Rk}});var mw=oe((Ej,hT)=>{"use strict";l();var{pipeline:Ok}=Xh(),Zh=ci(),{destroyer:Dk}=dc(),{isNodeStream:Qh,isReadable:aT,isWritable:uT,isWebStream:gw,isTransformStream:yc,isWritableStream:dT,isReadableStream:fT}=ii(),{AbortError:kk,codes:{ERR_INVALID_ARG_VALUE:lT,ERR_MISSING_ARGS:Nk}}=sr(),Ck=Xi();hT.exports=function(...e){if(e.length===0)throw new Nk("streams");if(e.length===1)return Zh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=Zh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=Zh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!Qh(e[p])&&!gw(e[p]))){if(p<e.length-1&&!(aT(e[p])||fT(e[p])||yc(e[p])))throw new lT(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(uT(e[p])||dT(e[p])||yc(e[p])))throw new lT(`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=Ok(e,a),f=!!(uT(u)||dT(u)||yc(u)),h=!!(aT(d)||fT(d)||yc(d));if(c=new Zh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(Qh(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(gw(u)){let y=(yc(u)?u.writable:u).getWriter();c._write=async function(x,S,I){try{await y.ready,y.write(x).catch(()=>{}),I()}catch(A){I(A)}},c._final=async function(x){try{await y.ready,y.close().catch(()=>{}),i=x}catch(S){x(S)}}}let p=yc(d)?d.readable:d;Ck(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(Qh(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(gw(d)){let g=(yc(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 kk),o=null,n=null,i=null,s===null?g(p):(s=g,Qh(d)&&Dk(d,p))},c}});var ST=oe((Sj,xw)=>{"use strict";l();var Lk=globalThis.AbortController||Ba().AbortController,{codes:{ERR_INVALID_ARG_VALUE:Pk,ERR_INVALID_ARG_TYPE:Fd,ERR_MISSING_ARGS:Mk,ERR_OUT_OF_RANGE:Kk},AbortError:ai}=sr(),{validateAbortSignal:gc,validateInteger:pT,validateObject:mc}=Ua(),$k=ot().Symbol("kWeak"),Hk=ot().Symbol("kResistStopPropagation"),{finished:Vk}=Xi(),qk=mw(),{addAbortSignalNoValidate:Fk}=Nd(),{isWritable:jk,isNodeStream:Wk}=ii(),{deprecate:Gk}=Xt(),{ArrayPrototypePush:zk,Boolean:Yk,MathFloor:yT,Number:Jk,NumberIsNaN:Xk,Promise:gT,PromiseReject:mT,PromiseResolve:Zk,PromisePrototypeThen:wT,Symbol:xT}=ot(),ep=xT("kEmpty"),bT=xT("kEof");function Qk(t,e){if(e!=null&&mc(e,"options"),e?.signal!=null&&gc(e.signal,"options.signal"),Wk(t)&&!jk(t))throw new Pk("stream",t,"must be writable");let r=qk(this,t);return e!=null&&e.signal&&Fk(e.signal,r),r}function tp(t,e){if(typeof t!="function")throw new Fd("fn",["Function","AsyncFunction"],t);e!=null&&mc(e,"options"),e?.signal!=null&&gc(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=yT(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=yT(e.highWaterMark)),pT(r,"options.concurrency",1),pT(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Xt().AbortSignalAny([e?.signal].filter(Yk)),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 ai;try{if(S=t(S,a),S===ep)continue;S=Zk(S)}catch(I){S=mT(I)}h+=1,wT(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new gT(I=>{d=I})}c.push(bT)}catch(S){let I=mT(S);wT(I,g,p),c.push(I)}finally{f=!0,u&&(u(),u=null)}}x();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===bT)return;if(o.aborted)throw new ai;S!==ep&&(yield S),c.shift(),y()}await new gT(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function e4(t=void 0){return t!=null&&mc(t,"options"),t?.signal!=null&&gc(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 ai({cause:t.signal.reason});yield[r++,i]}}).call(this)}async function ET(t,e=void 0){for await(let r of bw.call(this,t,e))return!0;return!1}async function t4(t,e=void 0){if(typeof t!="function")throw new Fd("fn",["Function","AsyncFunction"],t);return!await ET.call(this,async(...r)=>!await t(...r),e)}async function r4(t,e){for await(let r of bw.call(this,t,e))return r}async function n4(t,e){if(typeof t!="function")throw new Fd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),ep}for await(let n of tp.call(this,r,e));}function bw(t,e){if(typeof t!="function")throw new Fd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:ep}return tp.call(this,r,e)}var ww=class extends Mk{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function i4(t,e,r){var n;if(typeof t!="function")throw new Fd("reducer",["Function","AsyncFunction"],t);r!=null&&mc(r,"options"),r?.signal!=null&&gc(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let u=new ai(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await Vk(this.destroy(u)),u}let o=new Lk,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[$k]:this,[Hk]:!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 ai;i?e=await t(e,u,{signal:s}):(e=u,i=!0)}if(!c&&!i)throw new ww}finally{o.abort()}return e}async function o4(t){t!=null&&mc(t,"options"),t?.signal!=null&&gc(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 ai(void 0,{cause:t.signal.reason});zk(e,n)}return e}function s4(t,e){let r=tp.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function vT(t){if(t=Jk(t),Xk(t))return 0;if(t<0)throw new Kk("number",">= 0",t);return t}function c4(t,e=void 0){return e!=null&&mc(e,"options"),e?.signal!=null&&gc(e.signal,"options.signal"),t=vT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new ai;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new ai;t--<=0&&(yield o)}}).call(this)}function a4(t,e=void 0){return e!=null&&mc(e,"options"),e?.signal!=null&&gc(e.signal,"options.signal"),t=vT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new ai;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new ai;if(t-- >0&&(yield o),t<=0)return}}).call(this)}xw.exports.streamReturningOperators={asIndexedPairs:Gk(e4,"readable.asIndexedPairs will be removed in a future version."),drop:c4,filter:bw,flatMap:s4,map:tp,take:a4,compose:Qk};xw.exports.promiseReturningOperators={every:t4,forEach:n4,reduce:i4,toArray:o4,some:ET,find:r4}});var Ew=oe((Tj,AT)=>{"use strict";l();var{ArrayPrototypePop:u4,Promise:d4}=ot(),{isIterable:f4,isNodeStream:l4,isWebStream:h4}=ii(),{pipelineImpl:p4}=Xh(),{finished:y4}=Xi();vw();function g4(...t){return new d4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!l4(o)&&!f4(o)&&!h4(o)){let s=u4(t);n=s.signal,i=s.end}p4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}AT.exports={finished:y4,pipeline:g4}});var vw=oe((Ij,kT)=>{l();var{Buffer:m4}=_r(),{ObjectDefineProperty:eo,ObjectKeys:IT,ReflectApply:BT}=ot(),{promisify:{custom:RT}}=Xt(),{streamReturningOperators:TT,promiseReturningOperators:_T}=ST(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:UT}}=sr(),w4=mw(),{setDefaultHighWaterMark:b4,getDefaultHighWaterMark:x4}=Cd(),{pipeline:OT}=Xh(),{destroyer:E4}=dc(),DT=Xi(),Sw=Ew(),jd=ii(),We=kT.exports=Nh().Stream;We.isDestroyed=jd.isDestroyed;We.isDisturbed=jd.isDisturbed;We.isErrored=jd.isErrored;We.isReadable=jd.isReadable;We.isWritable=jd.isWritable;We.Readable=Md();for(let t of IT(TT)){let r=function(...n){if(new.target)throw UT();return We.Readable.from(BT(e,this,n))};Aw=r;let e=TT[t];eo(r,"name",{__proto__:null,value:e.name}),eo(r,"length",{__proto__:null,value:e.length}),eo(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var Aw;for(let t of IT(_T)){let r=function(...i){if(new.target)throw UT();return BT(e,this,i)};Aw=r;let e=_T[t];eo(r,"name",{__proto__:null,value:e.name}),eo(r,"length",{__proto__:null,value:e.length}),eo(We.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var Aw;We.Writable=Gh();We.Duplex=ci();We.Transform=iw();We.PassThrough=sw();We.pipeline=OT;var{addAbortSignal:v4}=Nd();We.addAbortSignal=v4;We.finished=DT;We.destroy=E4;We.compose=w4;We.setDefaultHighWaterMark=b4;We.getDefaultHighWaterMark=x4;eo(We,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return Sw}});eo(OT,RT,{__proto__:null,enumerable:!0,get(){return Sw.pipeline}});eo(DT,RT,{__proto__:null,enumerable:!0,get(){return Sw.finished}});We.Stream=We;We._isUint8Array=function(e){return e instanceof Uint8Array};We._uint8ArrayToBuffer=function(e){return m4.from(e.buffer,e.byteOffset,e.byteLength)}});var Tw=oe((Rj,gt)=>{"use strict";l();var Tt=vw(),S4=Ew(),A4=Tt.Readable.destroy;gt.exports=Tt.Readable;gt.exports._uint8ArrayToBuffer=Tt._uint8ArrayToBuffer;gt.exports._isUint8Array=Tt._isUint8Array;gt.exports.isDisturbed=Tt.isDisturbed;gt.exports.isErrored=Tt.isErrored;gt.exports.isReadable=Tt.isReadable;gt.exports.Readable=Tt.Readable;gt.exports.Writable=Tt.Writable;gt.exports.Duplex=Tt.Duplex;gt.exports.Transform=Tt.Transform;gt.exports.PassThrough=Tt.PassThrough;gt.exports.addAbortSignal=Tt.addAbortSignal;gt.exports.finished=Tt.finished;gt.exports.destroy=Tt.destroy;gt.exports.destroy=A4;gt.exports.pipeline=Tt.pipeline;gt.exports.compose=Tt.compose;Object.defineProperty(Tt,"promises",{configurable:!0,enumerable:!0,get(){return S4}});gt.exports.Stream=Tt.Stream;gt.exports.default=gt.exports});var tI=oe((qp,eI)=>{l();(function(t,e){typeof qp=="object"&&typeof eI<"u"?e(qp):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(qp,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]"),he="[\\x0A]",Te="[\\x20]",De=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),mt="[\\:\\/\\?\\#\\[\\]\\@]",Ae="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",rt=e(mt,Ae),wt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",Xe=B?"[\\uE000-\\uF8FF]":"[]",Ie=e(v,K,"[\\-\\.\\_\\~]",wt),nt=r(v+e(v,K,"[\\+\\-\\.]")+"*"),Ne=r(r(De+"|"+e(Ie,Ae,"[\\:]"))+"*"),ys=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),Ar=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),zr=r(Ar+"\\."+Ar+"\\."+Ar+"\\."+Ar),Ke=r(te+"{1,4}"),Tr=r(r(Ke+"\\:"+Ke)+"|"+zr),Yr=r(r(Ke+"\\:")+"{6}"+Tr),Mn=r("\\:\\:"+r(Ke+"\\:")+"{5}"+Tr),gs=r(r(Ke)+"?\\:\\:"+r(Ke+"\\:")+"{4}"+Tr),mi=r(r(r(Ke+"\\:")+"{0,1}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{3}"+Tr),xu=r(r(r(Ke+"\\:")+"{0,2}"+Ke)+"?\\:\\:"+r(Ke+"\\:")+"{2}"+Tr),Df=r(r(r(Ke+"\\:")+"{0,3}"+Ke)+"?\\:\\:"+Ke+"\\:"+Tr),kf=r(r(r(Ke+"\\:")+"{0,4}"+Ke)+"?\\:\\:"+Tr),Dc=r(r(r(Ke+"\\:")+"{0,5}"+Ke)+"?\\:\\:"+Ke),kc=r(r(r(Ke+"\\:")+"{0,6}"+Ke)+"?\\:\\:"),wi=r([Yr,Mn,gs,mi,xu,Df,kf,Dc,kc].join("|")),Nc=r(r(Ie+"|"+De)+"+"),ly=r(wi+"\\%25"+Nc),ms=r(wi+r("\\%25|\\%(?!"+te+"{2})")+Nc),xB=r("[vV]"+te+"+\\."+e(Ie,Ae,"[\\:]")+"+"),EB=r("\\["+r(ms+"|"+wi+"|"+xB)+"\\]"),Ex=r(r(De+"|"+e(Ie,Ae))+"*"),Eu=r(EB+"|"+zr+"(?!"+Ex+")|"+Ex),vu=r(K+"*"),vx=r(r(Ne+"@")+"?"+Eu+r("\\:"+vu)+"?"),Su=r(De+"|"+e(Ie,Ae,"[\\:\\@]")),vB=r(Su+"*"),Sx=r(Su+"+"),SB=r(r(De+"|"+e(Ie,Ae,"[\\@]"))+"+"),bi=r(r("\\/"+vB)+"*"),Cc=r("\\/"+r(Sx+bi)+"?"),hy=r(SB+bi),Nf=r(Sx+bi),Lc="(?!"+Su+")",QL=r(bi+"|"+Cc+"|"+hy+"|"+Nf+"|"+Lc),Pc=r(r(Su+"|"+e("[\\/\\?]",Xe))+"*"),Au=r(r(Su+"|[\\/\\?]")+"*"),Ax=r(r("\\/\\/"+vx+bi)+"|"+Cc+"|"+Nf+"|"+Lc),AB=r(nt+"\\:"+Ax+r("\\?"+Pc)+"?"+r("\\#"+Au)+"?"),TB=r(r("\\/\\/"+vx+bi)+"|"+Cc+"|"+hy+"|"+Lc),_B=r(TB+r("\\?"+Pc)+"?"+r("\\#"+Au)+"?"),eP=r(AB+"|"+_B),tP=r(nt+"\\:"+Ax+r("\\?"+Pc)+"?"),rP="^("+nt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+Eu+")"+r("\\:("+vu+")")+"?)")+"?("+bi+"|"+Cc+"|"+Nf+"|"+Lc+")")+r("\\?("+Pc+")")+"?"+r("\\#("+Au+")")+"?$",nP="^(){0}"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+Eu+")"+r("\\:("+vu+")")+"?)")+"?("+bi+"|"+Cc+"|"+hy+"|"+Lc+")")+r("\\?("+Pc+")")+"?"+r("\\#("+Au+")")+"?$",iP="^("+nt+")\\:"+r(r("\\/\\/("+r("("+Ne+")@")+"?("+Eu+")"+r("\\:("+vu+")")+"?)")+"?("+bi+"|"+Cc+"|"+Nf+"|"+Lc+")")+r("\\?("+Pc+")")+"?$",oP="^"+r("\\#("+Au+")")+"?$",sP="^"+r("("+Ne+")@")+"?("+Eu+")"+r("\\:("+vu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Ie,Ae),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Ie,Ae),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Ie,Ae),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Ie,Ae),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Ie,Ae,"[\\:\\@\\/\\?]",Xe),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Ie,Ae,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Ie,Ae),"g"),UNRESERVED:new RegExp(Ie,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Ie,rt),"g"),PCT_ENCODED:new RegExp(De,"g"),IPV4ADDRESS:new RegExp("^("+zr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+wi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+Nc+")")+"?\\]?$")}}var a=c(!1),u=c(!0),d=function(){function B(v,k){var K=[],H=!0,te=!1,he=void 0;try{for(var Te=v[Symbol.iterator](),De;!(H=(De=Te.next()).done)&&(K.push(De.value),!(k&&K.length===k));H=!0);}catch(mt){te=!0,he=mt}finally{try{!H&&Te.return&&Te.return()}finally{if(te)throw he}}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,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,Z=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 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?Z(v/S):v>>1,v+=Z(v/k);v>$*y>>1;H+=p)v=Z(v/$);return Z(H+($+1)*v/(v+x))},C=function(v){var k=[],K=v.length,H=0,te=A,he=I,Te=v.lastIndexOf(O);Te<0&&(Te=0);for(var De=0;De<Te;++De)v.charCodeAt(De)>=128&&G("not-basic"),k.push(v.charCodeAt(De));for(var mt=Te>0?Te+1:0;mt<K;){for(var Ae=H,rt=1,wt=p;;wt+=p){mt>=K&&G("invalid-input");var Xe=L(v.charCodeAt(mt++));(Xe>=p||Xe>Z((h-H)/rt))&&G("overflow"),H+=Xe*rt;var Ie=wt<=he?g:wt>=he+y?y:wt-he;if(Xe<Ie)break;var nt=p-Ie;rt>Z(h/nt)&&G("overflow"),rt*=nt}var Ne=k.length+1;he=R(H-Ae,Ne,Ae==0),Z(H/Ne)>h-te&&G("overflow"),te+=Z(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,he=I,Te=!0,De=!1,mt=void 0;try{for(var Ae=v[Symbol.iterator](),rt;!(Te=(rt=Ae.next()).done);Te=!0){var wt=rt.value;wt<128&&k.push(Q(wt))}}catch(ms){De=!0,mt=ms}finally{try{!Te&&Ae.return&&Ae.return()}finally{if(De)throw mt}}var Xe=k.length,Ie=Xe;for(Xe&&k.push(O);Ie<K;){var nt=h,Ne=!0,ys=!1,Ar=void 0;try{for(var zr=v[Symbol.iterator](),Ke;!(Ne=(Ke=zr.next()).done);Ne=!0){var Tr=Ke.value;Tr>=H&&Tr<nt&&(nt=Tr)}}catch(ms){ys=!0,Ar=ms}finally{try{!Ne&&zr.return&&zr.return()}finally{if(ys)throw Ar}}var Yr=Ie+1;nt-H>Z((h-te)/Yr)&&G("overflow"),te+=(nt-H)*Yr,H=nt;var Mn=!0,gs=!1,mi=void 0;try{for(var xu=v[Symbol.iterator](),Df;!(Mn=(Df=xu.next()).done);Mn=!0){var kf=Df.value;if(kf<H&&++te>h&&G("overflow"),kf==H){for(var Dc=te,kc=p;;kc+=p){var wi=kc<=he?g:kc>=he+y?y:kc-he;if(Dc<wi)break;var Nc=Dc-wi,ly=p-wi;k.push(Q(N(wi+Nc%ly,0))),Dc=Z(Nc/ly)}k.push(Q(N(Dc,0))),he=R(te,Yr,Ie==Xe),te=0,++Ie}}}catch(ms){gs=!0,mi=ms}finally{try{!Mn&&xu.return&&xu.return()}finally{if(gs)throw mi}}++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 X(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 he=parseInt(B.substr(k+4,2),16),Te=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(he&63)<<6|Te&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=X(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 Oe(B,v){var k=B.match(v.IPV6ADDRESS)||[],K=d(k,3),H=K[1],te=K[2];if(H){for(var he=H.toLowerCase().split("::").reverse(),Te=d(he,2),De=Te[0],mt=Te[1],Ae=mt?mt.split(":").map(ee):[],rt=De.split(":").map(ee),wt=v.IPV4ADDRESS.test(rt[rt.length-1]),Xe=wt?7:8,Ie=rt.length-Xe,nt=Array(Xe),Ne=0;Ne<Xe;++Ne)nt[Ne]=Ae[Ne]||rt[Ie+Ne]||"";wt&&(nt[Xe-1]=ce(nt[Xe-1],v));var ys=nt.reduce(function(Yr,Mn,gs){if(!Mn||Mn==="0"){var mi=Yr[Yr.length-1];mi&&mi.index+mi.length===gs?mi.length++:Yr.push({index:gs,length:1})}return Yr},[]),Ar=ys.sort(function(Yr,Mn){return Mn.length-Yr.length})[0],zr=void 0;if(Ar&&Ar.length>1){var Ke=nt.slice(0,Ar.index),Tr=nt.slice(Ar.index+Ar.length);zr=Ke.join(":")+"::"+Tr.join(":")}else zr=nt.join(":");return te&&(zr+="%"+te),zr}else return B}var Me=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Je="".match(/(){0}/)[1]===void 0;function xt(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(Me);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=Oe(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,X).toLowerCase())}catch(he){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+he}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 gi(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(Oe(ce(String(B.host),k),k).replace(k.IPV6ADDRESS,function(H,te,he){return"["+te+(he?"%25"+he:"")+"]"})),(typeof B.port=="number"||typeof B.port=="string")&&(K.push(":"),K.push(String(B.port))),K.length?K.join(""):void 0}var wo=/^\.\.?\//,gu=/^\/\.(\/|$)/,_f=/^\/\.\.(\/|$)/,uy=/^\/?(?:.|\n)*?(?=\/|$)/;function bo(B){for(var v=[];B.length;)if(B.match(wo))B=B.replace(wo,"");else if(B.match(gu))B=B.replace(gu,"/");else if(B.match(_f))B=B.replace(_f,"/"),v.pop();else if(B==="."||B==="..")B="";else{var k=B.match(uy);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 Wr(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,X).toLowerCase())}catch(Te){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Te}}ue(B,k),v.reference!=="suffix"&&B.scheme&&(K.push(B.scheme),K.push(":"));var te=gi(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 he=B.path;!v.absolutePath&&(!H||!H.absolutePath)&&(he=bo(he)),te===void 0&&(he=he.replace(/^\/\//,"/%2F")),K.push(he)}return B.query!==void 0&&(K.push("?"),K.push(B.query)),B.fragment!==void 0&&(K.push("#"),K.push(B.fragment)),K.join("")}function mu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=xt(Wr(B,k),k),v=xt(Wr(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=bo(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=bo(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=bo(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=bo(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 If(B,v,k){var K=s({scheme:"null"},k);return Wr(mu(xt(B,K),xt(v,K),K,!0),K)}function wu(B,v){return typeof B=="string"?B=Wr(xt(B,v),v):n(B)==="object"&&(B=xt(Wr(B,v),v)),B}function Bf(B,v,k){return typeof B=="string"?B=Wr(xt(B,k),k):n(B)==="object"&&(B=Wr(B,k)),typeof v=="string"?v=Wr(xt(v,k),k):n(v)==="object"&&(v=Wr(v,k)),B===v}function Rf(B,v){return B&&B.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function Gr(B,v){return B&&B.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,X)}var xo={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}},bu={scheme:"https",domainHost:xo.domainHost,parse:xo.parse,serialize:xo.serialize};function Uf(B){return typeof B.secure=="boolean"?B.secure:String(B.scheme).toLowerCase()==="wss"}var ps={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=Uf(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===(Uf(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],he=H[1];v.path=te&&te!=="/"?te:void 0,v.query=he,v.resourceName=void 0}return v.fragment=void 0,v}},Of={scheme:"wss",domainHost:ps.domainHost,parse:ps.parse,serialize:ps.serialize},dy={},uB=!0,gx="[A-Za-z0-9\\-\\.\\_\\~"+(uB?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Pn="[0-9A-Fa-f]",dB=r(r("%[EFef]"+Pn+"%"+Pn+Pn+"%"+Pn+Pn)+"|"+r("%[89A-Fa-f]"+Pn+"%"+Pn+Pn)+"|"+r("%"+Pn+Pn)),fB="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",lB="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",hB=e(lB,'[\\"\\\\]'),pB="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",yB=new RegExp(gx,"g"),Oc=new RegExp(dB,"g"),gB=new RegExp(e("[^]",fB,"[\\.]",'[\\"]',hB),"g"),mx=new RegExp(e("[^]",gx,pB),"g"),mB=mx;function fy(B){var v=X(B);return v.match(yB)?v:B}var wx={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,he={},Te=K.query.split("&"),De=0,mt=Te.length;De<mt;++De){var Ae=Te[De].split("=");switch(Ae[0]){case"to":for(var rt=Ae[1].split(","),wt=0,Xe=rt.length;wt<Xe;++wt)H.push(rt[wt]);break;case"subject":K.subject=Gr(Ae[1],k);break;case"body":K.body=Gr(Ae[1],k);break;default:te=!0,he[Gr(Ae[0],k)]=Gr(Ae[1],k);break}}te&&(K.headers=he)}K.query=void 0;for(var Ie=0,nt=H.length;Ie<nt;++Ie){var Ne=H[Ie].split("@");if(Ne[0]=Gr(Ne[0]),k.unicodeSupport)Ne[1]=Gr(Ne[1],k).toLowerCase();else try{Ne[1]=z.toASCII(Gr(Ne[1],k).toLowerCase())}catch(ys){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ys}H[Ie]=Ne.join("@")}return K},serialize:function(v,k){var K=v,H=o(v.to);if(H){for(var te=0,he=H.length;te<he;++te){var Te=String(H[te]),De=Te.lastIndexOf("@"),mt=Te.slice(0,De).replace(Oc,fy).replace(Oc,i).replace(gB,Y),Ae=Te.slice(De+1);try{Ae=k.iri?z.toUnicode(Ae):z.toASCII(Gr(Ae,k).toLowerCase())}catch(Ie){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Ie}H[te]=mt+"@"+Ae}K.path=H.join(",")}var rt=v.headers=v.headers||{};v.subject&&(rt.subject=v.subject),v.body&&(rt.body=v.body);var wt=[];for(var Xe in rt)rt[Xe]!==dy[Xe]&&wt.push(Xe.replace(Oc,fy).replace(Oc,i).replace(mx,Y)+"="+rt[Xe].replace(Oc,fy).replace(Oc,i).replace(mB,Y));return wt.length&&(K.query=wt.join("&")),K}},wB=/^([^\:]+)\:(.*)/,bx={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(wB),H=v;if(K){var te=k.scheme||H.scheme||"urn",he=K[1].toLowerCase(),Te=K[2],De=te+":"+(k.nid||he),mt=W[De];H.nid=he,H.nss=Te,H.path=void 0,mt&&(H=mt.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),he=W[te];he&&(v=he.serialize(v,k));var Te=v,De=v.nss;return Te.path=(H||k.nid)+":"+De,Te}},bB=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,xx={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(bB))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[xo.scheme]=xo,W[bu.scheme]=bu,W[ps.scheme]=ps,W[Of.scheme]=Of,W[wx.scheme]=wx,W[bx.scheme]=bx,W[xx.scheme]=xx,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=X,t.parse=xt,t.removeDotSegments=bo,t.serialize=Wr,t.resolveComponents=mu,t.resolve=If,t.normalize=wu,t.equal=Bf,t.escapeComponent=Rf,t.unescapeComponent=Gr,Object.defineProperty(t,"__esModule",{value:!0})})});var nI=oe((tZ,rI)=>{"use strict";l();rI.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 gI=oe((iee,yI)=>{l();var su=1e3,cu=su*60,au=cu*60,Ac=au*24,oL=Ac*7,sL=Ac*365.25;yI.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return cL(t);if(r==="number"&&isFinite(t))return e.long?uL(t):aL(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function cL(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*sL;case"weeks":case"week":case"w":return r*oL;case"days":case"day":case"d":return r*Ac;case"hours":case"hour":case"hrs":case"hr":case"h":return r*au;case"minutes":case"minute":case"mins":case"min":case"m":return r*cu;case"seconds":case"second":case"secs":case"sec":case"s":return r*su;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function aL(t){var e=Math.abs(t);return e>=Ac?Math.round(t/Ac)+"d":e>=au?Math.round(t/au)+"h":e>=cu?Math.round(t/cu)+"m":e>=su?Math.round(t/su)+"s":t+"ms"}function uL(t){var e=Math.abs(t);return e>=Ac?zp(t,e,Ac,"day"):e>=au?zp(t,e,au,"hour"):e>=cu?zp(t,e,cu,"minute"):e>=su?zp(t,e,su,"second"):t+" ms"}function zp(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var ZL={};Tu(ZL,{AggregateBeaconError:()=>M0,Appendix:()=>tt,BECH32M_CHARS:()=>LL,BTCR2_DID_DOCUMENT_CONTEXT:()=>QI,BTCR2_UPDATE_CONTEXT:()=>Uc,BeaconError:()=>zt,BeaconFactory:()=>Vs,BeaconSignalDiscovery:()=>sx,BeaconUtils:()=>rr,CASBeacon:()=>Zu,CASBeaconError:()=>K0,CHANGE_OUTPUT_VBYTES:()=>F0,DEACTIVATION_PATCH:()=>cx,DEFAULT_FEE_ESTIMATOR:()=>Ml,DEFAULT_MIN_CONF:()=>cB,DID_REGEX:()=>eB,DUST_LIMIT_SATS:()=>j0,DidBtcr2:()=>yx,DidDocument:()=>jr,DidDocumentBuilder:()=>px,DidVerificationMethod:()=>cy,GenesisDocument:()=>hu,ID_PLACEHOLDER_VALUE:()=>tr,Identifier:()=>fr,MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX:()=>Rc,MULTIKEY_VERIFICATION_METHOD_TYPE:()=>Bc,P2PKH_BEACON_TX_VSIZE:()=>Vv,P2TR_BEACON_TX_VSIZE:()=>$v,P2WPKH_BEACON_TX_VSIZE:()=>Hv,Resolver:()=>mo,SINGLETON_BEACON_TX_VSIZE:()=>qv,SMTBeacon:()=>ad,SMTBeaconError:()=>aa,SPENDABLE_DUST_LIMIT_SATS:()=>Kl,SinglePartyBeacon:()=>Ki,SingletonBeacon:()=>Qu,SingletonBeaconError:()=>P0,StaticFeeEstimator:()=>ua,Updater:()=>Tf,beaconTxVsize:()=>W0,buildAggregationBeaconTx:()=>p6,deriveSingletonAddress:()=>Fv,detectSingletonScriptKind:()=>G0,extractOpReturnSignalHash:()=>ox,getAggregationCommunicationKey:()=>aB,isBtcr2UpdateContext:()=>ay,isMultikeyVerificationMethod:()=>tB,opReturnScript:()=>Y0,resolveBtcr2SenderPk:()=>XL,resolveChangeAddress:()=>z0,selectSpendableUtxo:()=>Wv});l();l();l();l();var Es=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function vs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function _u(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function yn(t,...e){if(!vs(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 $f(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");_u(t.outputLen),_u(t.blockLen)}function Vc(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 Gx(t,e){yn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Fn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Hf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function gn(t,e){return t<<32-e|t>>>e}function Iu(t,e){return t<<e|t>>>32-e>>>0}var zx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",l8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Pt(t){if(yn(t),zx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=l8[t[r]];return e}var Ai={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wx(t){if(t>=Ai._0&&t<=Ai._9)return t-Ai._0;if(t>=Ai.A&&t<=Ai.F)return t-(Ai.A-10);if(t>=Ai.a&&t<=Ai.f)return t-(Ai.a-10)}function Ir(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(zx)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=Wx(t.charCodeAt(o)),c=Wx(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 Ss(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=Ss(t)),yn(t),t}function ht(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];yn(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 Hc=class{};function Vf(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 Br(t=32){if(Es&&typeof Es.getRandomValues=="function")return Es.getRandomValues(new Uint8Array(t));if(Es&&typeof Es.randomBytes=="function")return Uint8Array.from(Es.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}l();l();l();l();l();function h8(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 Ty(t,e,r){return t&e^~t&r}function _y(t,e,r){return t&e^t&r^e&r}var qc=class extends Hc{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=Hf(this.buffer)}update(e){Vc(this),e=Bu(e),yn(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=Hf(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){Vc(this),Gx(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Fn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;h8(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Hf(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()}},Ti=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var p8=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]),Eo=new Uint32Array(64),Iy=class extends qc{constructor(e=32){super(64,e,8,!1),this.A=Ti[0]|0,this.B=Ti[1]|0,this.C=Ti[2]|0,this.D=Ti[3]|0,this.E=Ti[4]|0,this.F=Ti[5]|0,this.G=Ti[6]|0,this.H=Ti[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)Eo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=Eo[f-15],p=Eo[f-2],g=gn(h,7)^gn(h,18)^h>>>3,y=gn(p,17)^gn(p,19)^p>>>10;Eo[f]=y+Eo[f-7]+g+Eo[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=gn(c,6)^gn(c,11)^gn(c,25),p=d+h+Ty(c,a,u)+p8[f]+Eo[f]|0,y=(gn(n,2)^gn(n,13)^gn(n,22))+_y(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(){Fn(Eo)}destroy(){this.set(0,0,0,0,0,0,0,0),Fn(this.buffer)}};var ke=Vf(()=>new Iy);l();l();l();var qf=class extends Hc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,$f(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),Fn(o)}update(e){return Vc(this),this.iHash.update(e),this}digestInto(e){Vc(this),yn(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()}},By=(t,e,r)=>new qf(t,e).update(r).digest();By.create=(t,e)=>new qf(t,e);l();var Oy=BigInt(0),Uy=BigInt(1);function Ru(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function vo(t,e,r=""){let n=vs(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 Uu(t){let e=t.toString(16);return e.length&1?"0"+e:e}function Yx(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Oy:BigInt("0x"+t)}function _i(t){return Yx(Pt(t))}function Dy(t){return yn(t),Yx(Pt(Uint8Array.from(t).reverse()))}function Fc(t,e){return Ir(t.toString(16).padStart(e*2,"0"))}function ky(t,e){return Fc(t,e).reverse()}function ct(t,e,r){let n;if(typeof e=="string")try{n=Ir(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(vs(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 So(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 Ry=t=>typeof t=="bigint"&&Oy<=t;function Ou(t,e,r){return Ry(t)&&Ry(e)&&Ry(r)&&e<=t&&t<r}function Jx(t,e,r,n){if(!Ou(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Ff(t){let e;for(e=0;t>Oy;t>>=Uy,e+=1);return e}var Ao=t=>(Uy<<BigInt(t))-Uy;function Xx(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 ht(...g)};return(p,g)=>{a(),d(p);let y;for(;!(y=g(f()));)d();return a(),y}}function Du(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 Ny(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 nr=BigInt(0),Ft=BigInt(1),As=BigInt(2),eE=BigInt(3),tE=BigInt(4),rE=BigInt(5),y8=BigInt(7),nE=BigInt(8),g8=BigInt(9),iE=BigInt(16);function Rr(t,e){let r=t%e;return r>=nr?r:e+r}function Ur(t,e,r){let n=t;for(;e-- >nr;)n*=n,n%=r;return n}function Zx(t,e){if(t===nr)throw new Error("invert: expected non-zero number");if(e<=nr)throw new Error("invert: expected positive modulus, got "+e);let r=Rr(t,e),n=e,i=nr,o=Ft,s=Ft,c=nr;for(;r!==nr;){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 Rr(i,e)}function Cy(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function oE(t,e){let r=(t.ORDER+Ft)/tE,n=t.pow(e,r);return Cy(t,n,e),n}function m8(t,e){let r=(t.ORDER-rE)/nE,n=t.mul(e,As),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,As),i),c=t.mul(o,t.sub(s,t.ONE));return Cy(t,c,e),c}function w8(t){let e=To(t),r=sE(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+y8)/iE;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 Cy(c,x,a),x}}function sE(t){if(t<eE)throw new Error("sqrt is not defined for small field");let e=t-Ft,r=0;for(;e%As===nr;)e/=As,r++;let n=As,i=To(t);for(;Qx(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return oE;let o=i.pow(n,e),s=(e+Ft)/As;return function(a,u){if(a.is0(u))return u;if(Qx(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 b8(t){return t%tE===eE?oE:t%nE===rE?m8:t%iE===g8?w8(t):sE(t)}var x8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ly(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=x8.reduce((n,i)=>(n[i]="function",n),e);return Du(t,r),t}function E8(t,e,r){if(r<nr)throw new Error("invalid exponent, negatives unsupported");if(r===nr)return t.ONE;if(r===Ft)return e;let n=t.ONE,i=e;for(;r>nr;)r&Ft&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Ft;return n}function jf(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 Qx(t,e){let r=(t.ORDER-Ft)/As,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 Wf(t,e){e!==void 0&&_u(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function To(t,e,r=!1,n={}){if(t<=nr)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}=Wf(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:Ao(a),ZERO:nr,ONE:Ft,allowedLengths:c,create:h=>Rr(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return nr<=h&&h<t},is0:h=>h===nr,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ft)===Ft,neg:h=>Rr(-h,t),eql:(h,p)=>h===p,sqr:h=>Rr(h*h,t),add:(h,p)=>Rr(h+p,t),sub:(h,p)=>Rr(h-p,t),mul:(h,p)=>Rr(h*p,t),pow:(h,p)=>E8(f,h,p),div:(h,p)=>Rr(h*Zx(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Zx(h,t),sqrt:o||(h=>(d||(d=b8(t)),d(f,h))),toBytes:h=>r?ky(h,u):Fc(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?Dy(h):_i(h);if(s&&(g=Rr(g,t)),!p&&!f.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>jf(f,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(f)}function cE(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 Py(t){let e=cE(t);return e+Math.ceil(e/2)}function Gf(t,e,r=!1){let n=t.length,i=cE(e),o=Py(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?Dy(t):_i(t),c=Rr(s,e-Ft)+Ft;return r?ky(c,i):Fc(c,i)}var jc=BigInt(0),Ts=BigInt(1);function ku(t,e){let r=e.negate();return t?r:e}function Yf(t,e){let r=jf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function fE(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function My(t,e){fE(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Ao(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function aE(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+=Ts);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 v8(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 S8(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 Ky=new WeakMap,lE=new WeakMap;function $y(t){return lE.get(t)||1}function uE(t){if(t!==jc)throw new Error("invalid wNAF")}var zf=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>jc;)r&Ts&&(n=n.add(i)),i=i.double(),r>>=Ts;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=My(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=My(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=aE(n,c,s);n=a,d?o=o.add(ku(h,r[p])):i=i.add(ku(f,r[u]))}return uE(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=My(e,this.bits);for(let s=0;s<o.windows&&n!==jc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=aE(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return uE(n),i}getPrecomputes(e,r,n){let i=Ky.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Ky.set(r,i))),i}cached(e,r,n){let i=$y(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=$y(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){fE(r,this.bits),lE.set(e,r),Ky.delete(e)}hasCache(e){return $y(e)!==1}};function hE(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>jc||n>jc;)r&Ts&&(o=o.add(i)),n&Ts&&(s=s.add(i)),i=i.double(),r>>=Ts,n>>=Ts;return{p1:o,p2:s}}function pE(t,e,r,n){v8(r,t),S8(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=Ff(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=Ao(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 dE(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ly(e),e}else return To(t,{isLE:r})}function yE(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>jc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=dE(e.p,r.Fp,n),o=dE(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 gE=(t,e)=>(t+(t>=0?e:-e)/mE)/e;function A8(t,e,r){let[[n,i],[o,s]]=e,c=gE(s*t,r),a=gE(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<Bi,h=d<Bi;f&&(u=-u),h&&(d=-d);let p=Ao(Math.ceil(Ff(r)/2))+Wc;if(u<Bi||u>=p||d<Bi||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Vy(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Hy(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Ru(r.lowS,"lowS"),Ru(r.prehash,"prehash"),r.format!==void 0&&Vy(r.format),r}var qy=class extends Error{constructor(e=""){super(e)}},Ii={Err:qy,_tlv:{encode:(t,e)=>{let{Err:r}=Ii;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=Uu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Uu(i.length/2|128):"";return Uu(t)+o+i+e},decode(t,e){let{Err:r}=Ii,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}=Ii;if(t<Bi)throw new e("integer: negative integers are not allowed");let r=Uu(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}=Ii;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 _i(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ii,i=ct("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}=Ii,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},Bi=BigInt(0),Wc=BigInt(1),mE=BigInt(2),Jf=BigInt(3),T8=BigInt(4);function _o(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=ct("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 _8(t,e={}){let r=yE("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Du(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=bE(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:E,y:U}=_.toAffine(),L=n.toBytes(E);if(Ru(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ht(wE(N),L)}else return ht(Uint8Array.of(4),L,n.toBytes(U))}function h(G){vo(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===_&&(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=${_} 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 x(G,_){let D=n.sqr(_),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,Jf),T8),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 A8(G,a.basises,i.ORDER)}let M=Ny((G,_)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(E,_),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=Ny(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(!x(_,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,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=ku(E,_),D=ku(U,D),_.add(D)}class ${constructor(_,D,E){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:E}=_||{};if(!_||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(vo(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ct("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Jf),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:E,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(E,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,E=n.mul(D,Jf),{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(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(_,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:E,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,Jf),W=n.mul(D,L),Y=n.mul(E,N),X=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,X),ee=n.sub(ee,ce),ce=n.add(E,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,X),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,X),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),X=n.mul(J,X),ee=n.mul(z,ee),Y=n.add(Y,X),X=n.sub(W,X),X=n.mul(J,X),ee=n.add(ee,X),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 E,U,L=N=>Q.cached(this,N,R=>Yf($,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),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);E=N,U=R}return Yf($,[E,U])[0]}multiplyUnsafe(_){let{endo:D}=e,E=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===Bi||E.is0())return $.ZERO;if(_===Wc)return E;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=hE($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,_)}multiplyAndAddUnsafe(_,D,E){let U=this.multiplyUnsafe(D).add(_.multiplyUnsafe(E));return U.is0()?void 0:U}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===Wc?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===Wc?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Ru(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Pt(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 Yf($,_)}static msm(_,D){return pE($,i,_,D)}static fromPrivateKey(_){return $.BASE.multiply(_o(i,_))}}$.BASE=new $(o.Gx,o.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;let Z=i.BITS,Q=new zf($,e.endo?Math.ceil(Z/2):Z);return $.BASE.precompute(8),$}function wE(t){return Uint8Array.of(t?2:3)}function bE(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function I8(t,e={}){let{Fn:r}=t,n=e.randomBytes||Br,i=Object.assign(bE(t.Fp,r),{seed:Py(r.ORDER)});function o(p){try{return!!_o(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 Gf(vo(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(_o(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=ct("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=_o(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=>_o(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function B8(t,e,r={}){$f(e),Du(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Br,i=r.hmac||((D,...E)=>By(e,D,ht(...E))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=I8(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>>Wc;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 I(D,E){Vy(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return vo(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){I(E,U);let L;if(U==="der"){let{r:P,s:V}=Ii.toSig(vo(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(Ir(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*mE<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(ht(wE((R&1)===0),V)),z=s.inv(P),W=T(ct("msgHash",E)),Y=s.create(-W*z),X=s.create(N*z),ue=t.BASE.multiplyUnsafe(Y).add(J.multiplyUnsafe(X));if(ue.is0())throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return x(this.s)}toBytes(E=y){if(Vy(E),E==="der")return Ir(Ii.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 ht(Uint8Array.of(this.recovery),U,L)}return ht(U,L)}toHex(E){return Pt(this.toBytes(E))}assertValidity(){}static fromCompact(E){return A.fromBytes(ct("sig",E),"compact")}static fromDER(E){return A.fromBytes(ct("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=_i(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=Ao(a);function q(D){return Jx("num < 2^"+a,D,Bi,M),s.toBytes(D)}function j(D,E){return vo(D,void 0,"message"),E?vo(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}=Hy(U,g);D=j(D,N);let C=T(D),P=_o(s,E),V=[q(P),q(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ct("extraEntropy",Y))}let J=ht(...V),z=C;function W(Y){let X=O(Y);if(!s.isValidNot0(X))return;let ue=s.inv(X),ee=t.BASE.multiply(X).toAffine(),ce=s.create(ee.x);if(ce===Bi)return;let Oe=s.create(ue*s.create(z+ce*P));if(Oe===Bi)return;let Me=(ee.x===ce?0:2)|Number(ee.y&Wc),Je=Oe;return L&&x(Oe)&&(Je=s.neg(Oe),Me^=1),new A(ce,Je,Me)}return{seed:J,k2sig:W}}function Z(D,E,U={}){D=ct("message",D);let{seed:L,k2sig:N}=$(D,E,U);return Xx(e.outputLen,s.BYTES,i)(L,N)}function Q(D){let E,U=typeof D=="string"||vs(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(ct("sig",D),"der")}catch(N){if(!(N instanceof Ii.Err))throw N}if(!E)try{E=A.fromBytes(ct("sig",D),"compact")}catch{return!1}}return E||!1}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=Hy(L,g);if(U=ct("publicKey",U),E=j(ct("message",E),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(ct("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),X=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(X).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,E,U={}){let{prehash:L}=Hy(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:Z,verify:G,recoverPublicKey:_,Signature:A,hash:e})}function R8(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=To(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}=R8(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 O8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Wf(r.Fn.ORDER,r.Fn.BITS))})}function xE(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=U8(t),o=_8(e,r),s=B8(o,n,i);return O8(t,s)}function EE(t,e){let r=n=>xE({...t,hash:n});return{...r(e),create:r}}var Gc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},D8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},k8=BigInt(0),vE=BigInt(1),Fy=BigInt(2);function N8(t){let e=Gc.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=Ur(d,r,e)*d%e,h=Ur(f,r,e)*d%e,p=Ur(h,Fy,e)*u%e,g=Ur(p,i,e)*p%e,y=Ur(g,o,e)*g%e,x=Ur(y,c,e)*y%e,S=Ur(x,a,e)*x%e,I=Ur(S,c,e)*y%e,A=Ur(I,r,e)*d%e,O=Ur(A,s,e)*g%e,T=Ur(O,n,e)*u%e,M=Ur(T,Fy,e);if(!Xf.eql(Xf.sqr(M),t))throw new Error("Cannot find square root");return M}var Xf=To(Gc.p,{sqrt:N8}),Io=EE({...Gc,Fp:Xf,lowS:!0,endo:D8},ke),SE={};function Zf(t,...e){let r=SE[t];if(r===void 0){let n=ke(Ss(t));r=ht(n,n),SE[t]=r}return ke(ht(r,...e))}var Wy=t=>t.toBytes(!0).slice(1),zc=Io.Point,Gy=t=>t%Fy===k8;function jy(t){let{Fn:e,BASE:r}=zc,n=_o(e,t),i=r.multiply(n);return{scalar:Gy(i.y)?n:e.neg(n),bytes:Wy(i)}}function TE(t){let e=Xf;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);Gy(i)||(i=e.neg(i));let o=zc.fromAffine({x:t,y:i});return o.assertValidity(),o}var Nu=_i;function _E(...t){return zc.Fn.create(Nu(Zf("BIP0340/challenge",...t)))}function AE(t){return jy(t).bytes}function C8(t,e,r=Br(32)){let{Fn:n}=zc,i=ct("message",t),{bytes:o,scalar:s}=jy(e),c=ct("auxRand",r,32),a=n.toBytes(s^Nu(Zf("BIP0340/aux",c))),u=Zf("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=jy(u),h=_E(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}=zc,o=ct("signature",t,64),s=ct("message",e),c=ct("publicKey",r,32);try{let a=TE(Nu(c)),u=Nu(o.subarray(0,32));if(!Ou(u,vE,Gc.p))return!1;let d=Nu(o.subarray(32,64));if(!Ou(d,vE,Gc.n))return!1;let f=_E(n.toBytes(u),Wy(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!Gy(g)||p!==u)}catch{return!1}}var Or=(()=>{let r=(i=Br(48))=>Gf(i,Gc.n);Io.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:AE(o)}}return{keygen:n,getPublicKey:AE,sign:C8,verify:IE,Point:zc,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Zf,lift_x:TE,pointToBytes:Wy,numberToBytesBE:Fc,bytesToNumberBE:_i,mod:Rr},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var L8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),RE=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),P8=RE.map(t=>(9*t+5)%16),UE=(()=>{let r=[[RE],[P8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>L8[o]));return r})(),OE=UE[0],DE=UE[1],kE=[[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=OE.map((t,e)=>t.map(r=>kE[e][r])),K8=DE.map((t,e)=>t.map(r=>kE[e][r])),$8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),H8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function BE(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 Qf=new Uint32Array(16),zy=class extends qc{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)Qf[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=$8[p],x=H8[p],S=OE[p],I=DE[p],A=M8[p],O=K8[p];for(let T=0;T<16;T++){let M=Iu(n+BE(p,o,c,u)+Qf[S[T]]+y,A[T])+f|0;n=f,f=u,u=Iu(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=Iu(i+BE(g,s,a,d)+Qf[I[T]]+x,O[T])+h|0;i=h,h=d,d=Iu(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(){Fn(Qf)}destroy(){this.destroyed=!0,Fn(this.buffer),this.set(0,0,0,0,0)}},NE=Vf(()=>new zy);l();l();function Yc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function V8(t,...e){if(!Yc(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 KE(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 Xy(t){if(typeof t!="function")throw new Error("function expected");return!0}function Jc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Lu(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function tl(t){if(!Array.isArray(t))throw new Error("array expected")}function $E(t,e){if(!KE(!0,e))throw new Error(`${t}: array of strings expected`)}function Zy(t,e){if(!KE(!1,e))throw new Error(`${t}: array of numbers expected`)}function Pu(...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 nl(t){let e=typeof t=="string"?t.split(""):t,r=e.length;$E("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(tl(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=>(tl(i),i.map(o=>{Jc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function il(t=""){return Jc("join",t),{encode:e=>($E("join.decode",e),e.join(t)),decode:e=>(Jc("join.decode",e),e.split(t))}}function q8(t){return Xy(t),{encode:e=>e,decode:e=>t(e)}}function CE(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(tl(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Lu(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 HE=(t,e)=>e===0?t:HE(e,t%e),rl=(t,e)=>t+(e-HE(t,e)),el=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Yy(t,e,r,n){if(tl(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(rl(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${rl(e,r)}`);let i=0,o=0,s=el[e],c=el[r]-1,a=[];for(let u of t){if(Lu(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=el[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 F8(t){Lu(t);let e=2**8;return{encode:r=>{if(!Yc(r))throw new Error("radix.encode input should be Uint8Array");return CE(Array.from(r),e,t)},decode:r=>(Zy("radix.decode",r),Uint8Array.from(CE(r,t,e)))}}function Qy(t,e=!1){if(Lu(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(rl(8,t)>32||rl(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Yc(r))throw new Error("radix2.encode input should be Uint8Array");return Yy(Array.from(r),8,t,!e)},decode:r=>(Zy("radix2.decode",r),Uint8Array.from(Yy(r,t,8,e)))}}function LE(t){return Xy(t),function(...e){try{return t.apply(null,e)}catch{}}}function j8(t,e){return Lu(t),Xy(e),{encode(r){if(!Yc(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(!Yc(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 Ri=Pu(Qy(6),nl("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),il("")),W8=t=>Pu(F8(58),nl(t),il("")),ol=W8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var VE=t=>Pu(j8(4,e=>t(t(e))),ol);var Jy=Pu(nl("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),il("")),PE=[996825010,642813549,513874426,1027748829,705979059];function Cu(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 ME(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=Cu(i)^s>>5}i=Cu(i);for(let o=0;o<n;o++)i=Cu(i)^t.charCodeAt(o)&31;for(let o of e)i=Cu(i)^o;for(let o=0;o<6;o++)i=Cu(i);return i^=r,Jy.encode(Yy([i%el[30]],30,5,!1))}function qE(t){let e=t==="bech32"?1:734539939,r=Qy(5),n=r.decode,i=r.encode,o=LE(n);function s(f,h,p=90){Jc("bech32.encode prefix",f),Yc(h)&&(h=Array.from(h)),Zy("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=ME(x,h,e);return`${x}1${Jy.encode(h)}${S}`}function c(f,h=90){Jc("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 I=Jy.decode(S).slice(0,-6),A=ME(x,I,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:x,words:I}}let a=LE(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 sl=qE("bech32"),_s=qE("bech32m"),FE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},G8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",z8={encode(t){return V8(t),t.toHex()},decode(t){return Jc("hex",t),Uint8Array.fromHex(t)}},ve=G8?z8:Pu(Qy(4),nl("0123456789abcdef"),il(""),q8(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 He=new Uint8Array,n0=new Uint8Array([0]);function Xc(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 Xr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Y8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!Xr(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 i0=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Zc(t){return Object.prototype.toString.call(t)==="[object Object]"}function jn(t){return Number.isSafeInteger(t)}var cl={equalBytes:Xc,isBytes:Xr,isCoder:Dr,checkBounds:WE,concatBytes:Y8,createView:i0,isPlainObject:Zc},jE=t=>{if(t!==null&&typeof t!="string"&&!Dr(t)&&!Xr(t)&&!jn(t))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${t} (${typeof t})`);return{encodeStream(e,r){if(t===null)return;if(Dr(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=Ui.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(Dr(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=Ui.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))}},Ui={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}(${Ui.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}},e0=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=i0(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 Ui.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: ${ve.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})[${ve.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: ${ve.encode(this.data.slice(this.pos))}`)}}err(e){return Ui.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(!Xr(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(Xc(e,this.data.subarray(n,n+e.length)))return n}}},t0=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=i0(this.viewBuf)}pushObj(e,r){return Ui.pushObj(this.stack,e,r)}writeView(e,r){if(this.finished)throw this.err("buffer: finished");if(!jn(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 Ui.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++)}}},r0=t=>Uint8Array.from(t).reverse();function WE(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 GE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new t0;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new e0(e,r),i=t.decodeStream(n);return n.finish(),i}}}function jt(t,e){if(!Dr(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return GE({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=GE(t);return t.validate?jt(e,t.validate):e},al=t=>Zc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Dr(t){return Zc(t)&&al(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||jn(t.size))}function J8(){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(!Zc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var X8={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(!jn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function Z8(t){if(!Zc(t))throw new Error("plain object expected");return{encode:e=>{if(!jn(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 Q8(t,e=!1){if(!jn(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 eR(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!al(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 zE=t=>{if(!al(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Oi={dict:J8,numberBigint:X8,tsEnum:Z8,decimal:Q8,match:eR,reverse:zE};var o0=(t,e=!1,r=!1,n=!0)=>{if(!jn(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:r0(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 WE(s,8n*i,!!r),s}})};var YE=o0(32,!1);var Qc=o0(8,!0);var JE=o0(8,!0,!0);var tR=(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}}),Mu=(t,e,r)=>{let n=t*8,i=2**(n-1),o=a=>{if(!jn(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(!jn(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 tR(t,{write:r.write,read:r.read,validate:e?o:c})},Be=Mu(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),XE=Mu(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),Bo=Mu(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var s0=Mu(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var wn=Mu(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=jE(t),n=Xr(t);return Wt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?r0(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?r0(o):o},validate:i=>{if(!Xr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function ZE(t,e){if(!Dr(e))throw new Error(`prefix: invalid inner value ${e}`);return mn(Fe(t),zE(e))}var ul=(t,e=!1)=>jt(mn(Fe(t,e),FE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var QE=(t,e={isLE:!1,with0x:!1})=>{let r=mn(Fe(t,e.isLE),ve),n=e.with0x;if(typeof n!="boolean")throw new Error(`hex/with0x: expected boolean, got ${typeof n}`);return n&&(r=mn(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 mn(t,e){if(!Dr(t))throw new Error(`apply: invalid inner value ${t}`);if(!al(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 ev=(t,e=!1)=>{if(!Xr(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=Xc(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 tv(t,e,r){if(!Dr(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Dr(e))throw new Error(`flagged: wrong path=${t}`);return Wt({encodeStream:(n,i)=>{typeof t=="string"?Ui.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=!!Ui.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function dl(t,e,r=!0){if(!Dr(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||Xr(e)&&!Xc(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 rv(t){let e=0;for(let r of t){if(r.size===void 0)return;if(!jn(r.size))throw new Error(`sizeof: wrong element size=${e}`);e+=r.size}return e}function Et(t){if(!Zc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Dr(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return Wt({size:rv(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 nv(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(!Dr(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return Wt({size:rv(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(!Dr(e))throw new Error(`array: invalid inner value ${e}`);let r=jE(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=>{Xr(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),Xr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(Xc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),Xr(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(Xr(t))for(let s=0;;s++){if(Xc(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 hl=Io.ProjectivePoint,ll=Io.CURVE.n,Ce=cl.isBytes,Wn=cl.concatBytes,at=cl.equalBytes;var ea=t=>NE(ke(t)),Di=(...t)=>ke(ke(Wn(...t))),_M=Or.utils.randomPrivateKey,pl=Or.getPublicKey,c0=Io.getPublicKey,iv=t=>t.r<ll/2n;function ov(t,e,r=!1){let n=Io.sign(t,e);if(r&&!iv(n)){let i=new Uint8Array(32),o=0;for(;!iv(n);)if(i.set(Be.encode(o++)),n=Io.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var a0=Or.sign,Ku=Or.utils.taggedHash,vt;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(vt||(vt={}));function Ro(t,e){let r=t.length;if(e===vt.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return hl.fromHex(t),t}else if(e===vt.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Or.utils.lift_x(Or.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function sv(t,e){let r=Or.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=ll)throw new Error("tweak higher than curve order");return i}function cv(t,e=Uint8Array.of()){let r=Or.utils,n=r.bytesToNumberBE(t),i=hl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,ll),s=r.pointToBytes(i),c=sv(s,e);return r.numberToBytesBE(r.mod(o+c,ll),32)}function $u(t,e){let r=Or.utils,n=sv(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(hl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var yl=ke(hl.BASE.toRawBytes(!1)),Zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},u0={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function Hu(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 bt;(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"})(bt||(bt={}));function d0(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 dv(t,e=4,r=!0){if(typeof t=="number")return t;if(Ce(t))try{let n=d0(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Ze=Wt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(bt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(bt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(bt.OP_1-1+r);continue}}if(typeof r=="number"&&(r=d0().encode(BigInt(r))),!Ce(r))throw new Error(`Wrong Script OP=${r} (${typeof r})`);let n=r.length;n<bt.PUSHDATA1?t.byte(n):n<=255?(t.byte(bt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(bt.PUSHDATA2),t.bytes(s0.encode(n))):(t.byte(bt.PUSHDATA4),t.bytes(Be.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(bt.OP_0<r&&r<=bt.PUSHDATA4){let n;if(r<bt.PUSHDATA1)n=r;else if(r===bt.PUSHDATA1)n=wn.decodeStream(t);else if(r===bt.PUSHDATA2)n=s0.decodeStream(t);else if(r===bt.PUSHDATA4)n=Be.decodeStream(t);else throw new Error("Should be not possible");e.push(t.bytes(n))}else if(r===0)e.push(0);else if(bt.OP_1<=r&&r<=bt.OP_16)e.push(r-(bt.OP_1-1));else{let n=bt[r];if(n===void 0)throw new Error(`Unknown opcode=${r.toString(16)}`);e.push(n)}}return e}}),uv={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},ta=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(uv))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]=uv[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}}),kr=mn(ta,Oi.numberBigint),hr=Fe(ta),ra=Gt(kr,hr),gl=t=>Gt(ta,t),fv=Et({txid:Fe(32,!0),index:Be,finalScriptSig:hr,sequence:Be}),ki=Et({amount:Qc,script:hr}),rR=Et({version:Bo,segwitFlag:ev(new Uint8Array([0,1])),inputs:gl(fv),outputs:gl(ki),witnesses:tv("segwitFlag",Gt("inputs/length",ra)),lockTime:Be});function nR(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Ni=jt(rR,nR),Is=Et({version:Bo,inputs:gl(fv),outputs:gl(ki),lockTime:Be});var l0=jt(Fe(null),t=>Ro(t,vt.ecdsa)),ml=jt(Fe(32),t=>Ro(t,vt.schnorr)),lv=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}),wl=Et({fingerprint:XE,path:Gt(null,Be)}),yv=Et({hashes:Gt(kr,Fe(32)),der:wl}),iR=Fe(78),oR=Et({pubKey:ml,leafHash:Fe(32)}),sR=Et({version:wn,internalKey:Fe(32),merklePath:Gt(null,Fe(32))}),Ci=jt(sR,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),cR=Gt(null,Et({depth:wn,version:wn,script:hr})),St=Fe(null),hv=Fe(20),Vu=Fe(32),bl={unsignedTx:[0,!1,Is,[0],[0],!1],xpub:[1,iR,wl,[],[0,2],!1],txVersion:[2,!1,Be,[2],[2],!1],fallbackLocktime:[3,!1,Be,[],[2],!1],inputCount:[4,!1,kr,[2],[2],!1],outputCount:[5,!1,kr,[2],[2],!1],txModifiable:[6,!1,wn,[],[2],!1],version:[251,!1,Be,[],[0,2],!1],proprietary:[252,St,St,[],[0,2],!1]},qu={nonWitnessUtxo:[0,!1,Ni,[],[0,2],!1],witnessUtxo:[1,!1,ki,[],[0,2],!1],partialSig:[2,l0,St,[],[0,2],!1],sighashType:[3,!1,Be,[],[0,2],!1],redeemScript:[4,!1,St,[],[0,2],!1],witnessScript:[5,!1,St,[],[0,2],!1],bip32Derivation:[6,l0,wl,[],[0,2],!1],finalScriptSig:[7,!1,St,[],[0,2],!1],finalScriptWitness:[8,!1,ra,[],[0,2],!1],porCommitment:[9,!1,St,[],[0,2],!1],ripemd160:[10,hv,St,[],[0,2],!1],sha256:[11,Vu,St,[],[0,2],!1],hash160:[12,hv,St,[],[0,2],!1],hash256:[13,Vu,St,[],[0,2],!1],txid:[14,!1,Vu,[2],[2],!0],index:[15,!1,Be,[2],[2],!0],sequence:[16,!1,Be,[],[2],!0],requiredTimeLocktime:[17,!1,Be,[],[2],!1],requiredHeightLocktime:[18,!1,Be,[],[2],!1],tapKeySig:[19,!1,lv,[],[0,2],!1],tapScriptSig:[20,oR,lv,[],[0,2],!1],tapLeafScript:[21,Ci,St,[],[0,2],!1],tapBip32Derivation:[22,Vu,yv,[],[0,2],!1],tapInternalKey:[23,!1,ml,[],[0,2],!1],tapMerkleRoot:[24,!1,Vu,[],[0,2],!1],proprietary:[252,St,St,[],[0,2],!1]},gv=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],mv=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Fu={redeemScript:[0,!1,St,[],[0,2],!1],witnessScript:[1,!1,St,[],[0,2],!1],bip32Derivation:[2,l0,wl,[],[0,2],!1],amount:[3,!1,JE,[2],[2],!0],script:[4,!1,St,[2],[2],!0],tapInternalKey:[5,!1,ml,[],[0,2],!1],tapTree:[6,!1,cR,[],[0,2],!1],tapBip32Derivation:[7,ml,yv,[],[0,2],!1],proprietary:[252,St,St,[],[0,2],!1]},wv=[],pv=Gt(n0,Et({key:ZE(kr,Et({type:kr,key:Fe(null)})),value:Fe(kr)}));function h0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var NM=Et({type:kr,key:Fe(null)});function p0(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:He},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>Hu(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)=>Hu(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}pv.encodeStream(r,i)},decodeStream:r=>{let n=pv.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=${ve.encode(a)} value=${ve.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 xl=jt(p0(qu),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)Ro(e,vt.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)Ro(e,vt.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}),El=jt(p0(Fu),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)Ro(e,vt.ecdsa);return t}),bv=jt(p0(bl),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}),aR=Et({magic:dl(ul(new Uint8Array([255])),"psbt"),global:bv,inputs:Gt("global/unsignedTx/inputs/length",xl),outputs:Gt(null,El)}),uR=Et({magic:dl(ul(new Uint8Array([255])),"psbt"),global:bv,inputs:Gt("global/inputCount",xl),outputs:Gt("global/outputCount",El)}),CM=Et({magic:dl(ul(new Uint8Array([255])),"psbt"),items:Gt(null,mn(Gt(n0,nv([QE(kr),Fe(ta)])),Oi.dict()))});function f0(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=h0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=h0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function y0(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}=h0(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 xv(t){let e=t&&t.global&&t.global.version||0;f0(e,bl,t.global);for(let s of t.inputs)f0(e,qu,s);for(let s of t.outputs)f0(e,Fu,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 vl(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(ve.decode(x[0])):x[0],typeof x[1]=="string"?d.decode(ve.decode(x[1])):x[1]]});let g={},y=(x,S,I)=>{if(g[x]===void 0){g[x]=[S,I];return}let A=ve.encode(d.encode(g[x][1])),O=ve.encode(d.encode(I));if(A!==O)throw new Error(`keyMap(${c}): same key=${x} oldVal=${A} newVal=${O}`)};for(let[x,S]of h){let I=ve.encode(u.encode(x));y(I,x,S)}for(let[x,S]of p){let I=ve.encode(u.encode(x));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${x}`);delete g[I]}else y(I,x,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(ve.decode(o[s]));else if(f&&s in e&&r&&r[s]!==void 0&&!at(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 g0=jt(aR,xv),m0=jt(uR,xv);var fR={encode(t){if(!(t.length!==2||t[0]!==1||!Ce(t[1])||ve.encode(t[1])!=="4e73"))return{type:"p2a",script:Ze.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,ve.decode("4e73")]}};function Uo(t,e){try{return Ro(t,e),!0}catch{return!1}}var lR={encode(t){if(!(t.length!==2||!Ce(t[0])||!Uo(t[0],vt.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},hR={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},pR={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},yR={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},gR={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},mR={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},wR={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},bR={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}},xR={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=dv(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:Ze.encode(t)}},decode:t=>t.type==="unknown"?Ze.decode(t.script):void 0},vR=[fR,lR,hR,pR,yR,gR,mR,wR,bR,xR,ER],SR=mn(Ze,Oi.match(vR)),Qe=jt(SR,t=>{if(t.type==="pk"&&!Uo(t.pubkey,vt.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)||!Uo(t.pubkey,vt.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(!Uo(r,vt.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(!Uo(e,vt.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 Ev(t,e){if(!at(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 S0(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(!at(n.hash,ea(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&&Ev(n,r)}if(e){let n=Qe.decode(e);n.type==="wsh"&&r&&Ev(n,r)}}var Li=(t,e=Zr)=>{if(!Uo(t,vt.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=ea(t);return{type:"pkh",script:Qe.encode({type:"pkh",hash:r}),address:Qr(e).encode({type:"pkh",hash:r}),hash:r}};var Bs=(t,e=Zr)=>{if(!Uo(t,vt.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=ea(t);return{type:"wpkh",script:Qe.encode({type:"wpkh",hash:r}),address:Qr(e).encode({type:"wpkh",hash:r}),hash:r}};function AR(t,e,r=!1,n){let i=Qe.decode(t);if(i.type==="unknown"){if(n){let c=mn(Ze,Oi.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(at(s,yl))throw new Error("Unspendable taproot key in leaf script");if(at(s,e))throw new Error("Using P2TR with leaf script with same key as internal key is not supported")}}function Sv(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 b0(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:b0(t.left,[t.right.hash,...e]),right:b0(t.right,[t.left.hash,...e])}}function x0(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[...x0(t.left),...x0(t.right)]}function E0(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&&!at(t.tapMerkleRoot,He))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?ve.decode(u):u;if(!Ce(d))throw new Error(`checkScript: wrong script type=${d}`);return AR(d,e,r,n),{type:"leaf",version:a,script:d,hash:ju(d,a)}}if(t.length!==2&&(t=Sv(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=E0(t[0],e,r,n),o=E0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return Hu(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Ku("TapBranch",s,c)}}var v0=192,ju=(t,e=v0)=>Ku("TapLeaf",new Uint8Array([e]),hr.encode(t));function Rs(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"?ve.decode(t):t||yl;if(!Uo(o,vt.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=b0(E0(e,o,n,i)),c=s.hash,[a,u]=$u(o,c),d=x0(s).map(f=>({...f,controlBlock:Ci.encode({version:(f.version||v0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Qe.encode({type:"tr",pubkey:a}),address:Qr(r).encode({type:"tr",pubkey:a}),tweakedPubkey:a,tapInternalKey:o,leaves:d,tapLeafScript:d.map(f=>[Ci.decode(f.controlBlock),Wn(f.script,new Uint8Array([f.version||v0]))]),tapMerkleRoot:c}}else{let s=$u(o,He)[0];return{type:"tr",script:Qe.encode({type:"tr",pubkey:s}),address:Qr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var Av=VE(ke);function Tv(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 w0(t,e,r=Zr){Tv(t,e);let n=t===0?sl:_s;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function vv(t,e){return Av.encode(Wn(Uint8Array.from(e),t))}function Qr(t=Zr){return{encode(e){let{type:r}=e;if(r==="wpkh")return w0(0,e.hash,t);if(r==="wsh")return w0(0,e.hash,t);if(r==="tr")return w0(1,e.pubkey,t);if(r==="pkh")return vv(e.hash,[t.pubKeyHash]);if(r==="sh")return vv(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=sl.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=_s.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=sl.fromWords(o);if(Tv(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=Av.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 Sl=new Uint8Array(32),TR={amount:0xffffffffffffffffn,script:He},_R=t=>Math.ceil(t/4),IR=8,BR=2,Us=0,I0=4294967295,RR=Oi.decimal(IR),Gu=(t,e)=>t===void 0?e:t;function Tl(t){if(Array.isArray(t))return t.map(e=>Tl(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,Tl(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 Oo;(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"})(Oo||(Oo={}));function UR(t,e,r,n=He){return at(r,e)&&(t=cv(t,n),e=pl(t)),{privKey:t,pubKey:e}}function Os(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 Wu(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:Gu(t.sequence,I0),finalScriptSig:Gu(t.finalScriptSig,He)}}function A0(t){for(let e in t){let r=e;gv.includes(r)||delete t[r]}}var T0=Et({txid:Fe(32,!0),index:Be});function OR(t){if(typeof t!="number"||typeof Oo[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function _v(t){let e=t&31;return{isAny:!!(t&je.ANYONECANPAY),isNone:e===je.NONE,isSingle:e===je.SINGLE}}function DR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:Gu(t.version,BR),lockTime:Gu(t.lockTime,0),PSBTVersion:Gu(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(Be.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&&(!at(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=Ds.fromRaw(Ni.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=ve.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function Al(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 Bv(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=ve.decode(o)),Ce(o)&&(o=Ni.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=ve.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=I0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=vl(qu,c,e,r,i),xl.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&S0(a&&a.script,c.redeemScript,c.witnessScript),c}function _0(t,e=!1){let r="legacy",n=je.ALL,i=Al(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 Ds=class t{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];let r=this.opts=DR(e);r.lockTime!==Us&&(this.global.fallbackLocktime=r.lockTime),this.global.txVersion=r.version}static fromRaw(e,r={}){let n=Ni.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=g0.decode(e)}catch(f){try{n=m0.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:He,...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!==Us&&(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(y0(e,qu,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=>y0(e,Fu,o)),i={...this.global};return e===0?(i.unsignedTx=Is.decode(Is.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Wu).map(o=>({...o,finalScriptSig:He})),outputs:this.outputs.map(Os)})),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===Us&&delete i.fallbackLocktime),this.opts.bip174jsCompat&&(r.length||r.push({}),n.length||n.push({})),(e===0?g0:m0).encode({global:i,inputs:r,outputs:n})}get lockTime(){let e=Us,r=0,n=Us,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!==Us?n:this.global.fallbackLocktime||Us}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(Os);e+=4*kr.encode(this.outputs.length).length;for(let n of r)e+=32+4*hr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*kr.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*hr.encode(n.finalScriptSig||He).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=ra.encode(n.finalScriptWitness).length);return e}get vsize(){return _R(this.weight)}toBytes(e=!1,r=!1){return Ni.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Wu).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||He})),outputs:this.outputs.map(Os),witnesses:this.inputs.map(n=>n.finalScriptWitness||[]),segwitFlag:r&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return ve.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return ve.encode(Di(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return ve.encode(Di(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),Tl(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(Bv(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=mv)}this.inputs[e]=Bv(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),Tl(this.outputs[e])}getOutputAddress(e,r=Zr){let n=this.getOutput(e);if(n.script)return Qr(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=ve.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=vl(Fu,s,r,n,this.opts.allowUnknown),El.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||S0(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=wv)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=Zr){return this.addOutput({script:Qe.encode(Qr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=Al(n);if(!i)throw new Error("Empty input amount");e+=i.amount}let r=this.outputs.map(Os);for(let n of r)e-=n.amount;return e}preimageLegacy(e,r,n){let{isAny:i,isNone:o,isSingle:s}=_v(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 YE.encode(1n);r=Ze.encode(Ze.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(Wu).map((d,f)=>({...d,finalScriptSig:f===e?r:He}));i?c=[c[e]]:(o||s)&&(c=c.map((d,f)=>({...d,sequence:f===e?d.sequence:0})));let a=this.outputs.map(Os);o?a=[]:s&&(a=a.slice(0,e).fill(TR).concat([a[e]]));let u=Ni.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Di(u,Bo.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=_v(n),a=Sl,u=Sl,d=Sl,f=this.inputs.map(Wu),h=this.outputs.map(Os);o||(a=Di(...f.map(T0.encode))),!o&&!c&&!s&&(u=Di(...f.map(g=>Be.encode(g.sequence)))),!c&&!s?d=Di(...h.map(ki.encode)):c&&e<h.length&&(d=Di(ki.encode(h[e])));let p=f[e];return Di(Bo.encode(this.version),a,u,Fe(32,!0).encode(p.txid),Be.encode(p.index),hr.encode(r),Qc.encode(i),Be.encode(p.sequence),d,Be.encode(this.lockTime),Be.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=[wn.encode(0),wn.encode(n),Bo.encode(this.version),Be.encode(this.lockTime)],d=n===je.DEFAULT?je.ALL:n&3,f=n&je.ANYONECANPAY,h=this.inputs.map(Wu),p=this.outputs.map(Os);f!==je.ANYONECANPAY&&u.push(...[h.map(T0.encode),i.map(Qc.encode),r.map(hr.encode),h.map(y=>Be.encode(y.sequence))].map(y=>ke(Wn(...y)))),d===je.ALL&&u.push(ke(Wn(...p.map(ki.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===je.ANYONECANPAY){let y=h[e];u.push(T0.encode(y),Qc.encode(i[e]),hr.encode(r[e]),Be.encode(y.sequence))}else u.push(Be.encode(e));return g&1&&u.push(ke(hr.encode(a||He))),d===je.SINGLE&&u.push(e<p.length?ke(ki.encode(p[e])):Sl),s&&u.push(ju(s,c),wn.encode(0),Bo.encode(o)),Ku("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=_0(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(!at(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(OR):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=Al(o);if(s.txType==="taproot"){let d=this.inputs.map(Al),f=d.map(x=>x.script),h=d.map(x=>x.amount),p=!1,g=pl(e),y=o.tapMerkleRoot||He;if(o.tapInternalKey){let{pubKey:x,privKey:S}=UR(e,g,o.tapInternalKey,y),[I,A]=$u(o.tapInternalKey,y);if(at(I,x)){let O=this.preimageWitnessV1(r,f,c,h),T=Wn(a0(O,S,i),c!==je.DEFAULT?new Uint8Array([c]):He);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[x,S]of o.tapLeafScript){let I=S.subarray(0,-1),A=Ze.decode(I),O=S[S.length-1],T=ju(I,O);if(A.findIndex($=>Ce($)&&at($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,I,O),j=Wn(a0(q,e,i),c!==je.DEFAULT?new Uint8Array([c]):He);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=c0(e),f=!1,h=ea(d);for(let y of Ze.decode(s.lastScript))Ce(y)&&(at(y,d)||at(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=ov(p,e,this.opts.lowR);this.updateInput(r,{partialSig:[[d,Wn(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=_0(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)=>Ci.encode(u[0]).length-Ci.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=ju(f,h),y=r.tapScriptSig.filter(S=>at(S[0].leafHash,g)),x=[];if(p.type==="tr_ms"){let S=p.m,I=p.pubkeys,A=0;for(let O of I){let T=y.findIndex(M=>at(M[0].pubKey,O));if(A===S||T===-1){x.push(He);continue}x.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=>at(A[0].pubKey,S));I!==-1&&x.push(y[I][1])}if(x.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Ze.decode(f);if(x=y.map(([{pubKey:I},A])=>{let O=S.findIndex(T=>Ce(T)&&at(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),!x.length)continue}else{let S=this.opts.customScripts;if(S)for(let I of S){if(!I.finalizeTaproot)continue;let A=Ze.decode(f),O=I.encode(A);if(O===void 0)continue;let T=I.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(Ci.encode(u)),r.finalScriptSig=He,A0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=x.reverse().concat([f,Ci.encode(u)]);break}if(!r.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}else throw new Error("finalize/taproot: unknown input");r.finalScriptSig=He,A0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=He,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=>at(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=Ze.encode([0,...d])}else if(n.last.type==="pk")i=Ze.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Ze.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=He,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=Ze.decode(i).map(a=>{if(a===0)return He;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=Ze.encode([Ze.encode([0,ke(n.lastScript)])]):n.type.startsWith("sh-")?s=Ze.encode([...Ze.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),A0(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?Is.encode(this.global.unsignedTx):He,n=e.global.unsignedTx?Is.encode(e.global.unsignedTx):He;if(!at(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=vl(bl,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 Rv(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 x=Object.keys(d);c&&(x=x.filter(function(I){return d[I]!==void 0})),x.sort(),x.forEach(function(I){y(I)})}r+="}"}}}function Uv(t,e){return Rv(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var B0;(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_SIGNAL_DATA="INVALID_SIGNAL_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"})(B0||(B0={}));var{INVALID_DID:pt,METHOD_NOT_SUPPORTED:_l,INTERNAL_ERROR:Il,INVALID_DID_DOCUMENT:qe,INVALID_DID_UPDATE:le,INVALID_DID_URL:AK,INVALID_PREVIOUS_DID_PROOF:TK,INVALID_PUBLIC_KEY:_K,INVALID_PUBLIC_KEY_MULTIBASE:IK,INVALID_PUBLIC_KEY_LENGTH:BK,INVALID_PUBLIC_KEY_TYPE:RK,INVALID_SIGNATURE:UK,NOT_FOUND:Ov,PROOF_VERIFICATION_ERROR:Pi,PROOF_GENERATION_ERROR:ko,PROOF_SERIALIZATION_ERROR:Dv,PROOF_PARSING_ERROR:OK,VERIFICATION_METHOD_ERROR:Bl,LATE_PUBLISHING_ERROR:Rl,INVALID_SIDECAR_DATA:DK,MISSING_UPDATE_DATA:kv,INVALID_SIGNAL_DATA:Ns,MISSING_RESOLUTION_OPTIONS:kK,INVALID_OPTIONS:zu}=B0,Dt=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)}},be=class extends Dt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}};var ut=class extends Dt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},it=class extends Dt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},fe=class extends Dt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var Ve=class extends Dt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},Do=class extends Dt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},bn=class extends Dt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},xn=class extends Dt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},Gn=class extends Dt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},ks=class extends Dt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},En=class extends Dt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var na=class extends Dt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var kR=new Set(["jcs"]),NR=new Set(["hex","base58","base64urlnopad"]);function R0(t){let e=t.toLowerCase();if(!kR.has(e))throw new na(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function U0(t){let e=t.toLowerCase();if(!NR.has(e))throw new na(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function ir(t,e="jcs"){switch(R0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return Uv(n)}default:throw new na(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function No(t){return ke(t)}function en(t,e="base64urlnopad"){switch(U0(e)){case"hex":return ve.encode(t);case"base58":return ol.encode(t);case"base64urlnopad":return Ri.encode(t)}}function ia(t,e="base64urlnopad"){switch(U0(e)){case"hex":return ve.decode(t);case"base58":return ol.decode(t);case"base64urlnopad":return Ri.decode(t)}}function zn(t,e="jcs"){return No(ir(t,R0(e)))}function Yn(t,e){let r=R0(e?.algorithm??"jcs"),n=U0(e?.encoding??"base64urlnopad");return en(No(ir(t,r)),n)}l();l();var O0={};Tu(O0,{JsonPatchError:()=>dt,_areEquals:()=>Xu,applyOperation:()=>Cs,applyPatch:()=>Ll,applyReducer:()=>KR,deepClone:()=>PR,getValueByPointer:()=>Nl,validate:()=>Cv,validator:()=>Cl});l();l();var CR=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)}}(),LR=Object.prototype.hasOwnProperty;function Ol(t,e){return LR.call(t,e)}function Dl(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)Ol(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 kl(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 Jn(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Yu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Ul(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(Ul(t[e]))return!0}else if(typeof t=="object"){for(var n=Dl(t),i=n.length,o=0;o<i;o++)if(Ul(t[n[o]]))return!0}}return!1}function Nv(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 Ju=function(t){CR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,Nv(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=Nv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var dt=Ju,PR=Mt,oa={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=Nl(r,this.path);n&&(n=Mt(n));var i=Cs(r,{op:"remove",path:this.from}).removed;return Cs(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=Nl(r,this.from);return Cs(r,{op:"add",path:this.path,value:Mt(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Xu(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},MR={add:function(t,e,r){return kl(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:oa.move,copy:oa.copy,test:oa.test,_get:oa._get};function Nl(t,e){if(e=="")return t;var r={op:"_get",path:e};return Cs(t,r),r.value}function Cs(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):Cl(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=Nl(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Xu(t,e.value),s.test===!1)throw new dt("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 dt("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=Cl;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=Yu(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&&!kl(p))throw new dt("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);kl(p)&&(p=~~p)}if(d>=f){if(r&&e.op==="add"&&p>u.length)throw new dt("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 dt("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(d>=f){var s=oa[e.op].call(e,u,p,t);if(s.test===!1)throw new dt("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new dt("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function Ll(t,e,r,n,i){if(n===void 0&&(n=!0),i===void 0&&(i=!0),r&&!Array.isArray(e))throw new dt("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]=Cs(t,e[s],r,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function KR(t,e,r){var n=Cs(t,e);if(n.test===!1)throw new dt("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function Cl(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new dt("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(oa[t.op]){if(typeof t.path!="string")throw new dt("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new dt('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 dt("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 dt("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")&&Ul(t.value))throw new dt("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 dt("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 dt("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=Cv([s],r);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new dt("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new dt("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function Cv(t,e,r){try{if(!Array.isArray(t))throw new dt("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ll(Mt(e),Mt(t),r||!0);else{r=r||Cl;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof dt)return i;throw i}}function Xu(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(!Xu(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],!Xu(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var C0={};Tu(C0,{compare:()=>GR,generate:()=>D0,observe:()=>WR,unobserve:()=>jR});l();var k0=new WeakMap,$R=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),HR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function VR(t){return k0.get(t)}function qR(t,e){return t.observers.get(e)}function FR(t,e){t.observers.delete(e.callback)}function jR(t,e){e.unobserve()}function WR(t,e){var r=[],n,i=VR(t);if(!i)i=new $R(t),k0.set(t,i);else{var o=qR(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(){D0(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(){D0(n),clearTimeout(n.next),FR(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 HR(e,n)),n}function D0(t,e){e===void 0&&(e=!1);var r=k0.get(t.object);N0(r.value,t.object,t.patches,"",e),t.patches.length&&Ll(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function N0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Dl(e),s=Dl(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(Ol(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)?N0(f,h,r,n+"/"+Jn(d),i):f!==h&&(c=!0,i&&r.push({op:"test",path:n+"/"+Jn(d),value:Mt(f)}),r.push({op:"replace",path:n+"/"+Jn(d),value:Mt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+Jn(d),value:Mt(f)}),r.push({op:"remove",path:n+"/"+Jn(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];!Ol(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+Jn(d),value:Mt(e[d])})}}}function GR(t,e,r){r===void 0&&(r=!1);var n=[];return N0(t,e,n,"",r),n}var Lv=Object.assign({},O0,C0,{JsonPatchError:Ju,deepClone:Mt,escapePathComponent:Jn,unescapePathComponent:Yu});var{applyPatch:zR,compare:YR,deepClone:JR}=Lv,XR=new Set(["__proto__","constructor","prototype"]);function Pv(t){return t.split("/").map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")).find(e=>XR.has(e))}var ZR=new Set(["add","remove","replace","move","copy","test"]),QR=new Set(["add","replace","test"]);function e6(t){if(!(t instanceof Error))return"";let{index:e,operation:r}=t;return`${typeof e=="number"&&r&&typeof r=="object"?` at operation ${e} (${String(r.op)} ${String(r.path)})`:""}: ${t.message}`}var sa=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.strict??!1,s=n.clone??JR,c=i?e:s(e),a=this.validateOperations(r,o);if(a)throw new be(`Invalid JSON Patch operations: ${a.message}`,"JSON_PATCH_APPLY_ERROR",{error:a});let u;try{u=zR(c,r,o,i)}catch(d){throw new be(`JSON Patch application failed${e6(d)}`,"JSON_PATCH_APPLY_ERROR",{error:d})}if(u.newDocument===void 0)throw new be("JSON Patch application failed: no document","JSON_PATCH_APPLY_ERROR",{result:u});return u.newDocument}static diff(e,r,n=""){let i=YR(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,r=!1){if(!Array.isArray(e))return new be("Operations must be an array","JSON_PATCH_VALIDATION_ERROR");for(let n of e){if(!n||typeof n!="object")return new be("Operation must be an object","JSON_PATCH_VALIDATION_ERROR");if(typeof n.op!="string")return new be("Operation.op must be a string","JSON_PATCH_VALIDATION_ERROR");if(typeof n.path!="string")return new be("Operation.path must be a string","JSON_PATCH_VALIDATION_ERROR");if(r&&!ZR.has(n.op))return new be(`Operation.op is not an RFC 6902 operation: ${n.op}`,"JSON_PATCH_VALIDATION_ERROR");if(r&&QR.has(n.op)&&n.value===void 0)return new be(`Operation.value is required for op=${n.op}`,"JSON_PATCH_VALIDATION_ERROR");let i=Pv(n.path);if(i)return new be(`Operation.path traverses prototype machinery: ${i}`,"JSON_PATCH_VALIDATION_ERROR");if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")return new be(`Operation.from must be a string for op=${n.op}`,"JSON_PATCH_VALIDATION_ERROR");if(typeof n.from=="string"){let o=Pv(n.from);if(o)return new be(`Operation.from traverses prototype machinery: ${o}`,"JSON_PATCH_VALIDATION_ERROR")}}return null}};l();var tn;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(tn||(tn={}));var Pl;(function(t){t.k="k",t.x="x"})(Pl||(Pl={}));var ca;(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"})(ca||(ca={}));l();var Mi=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new be(`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 be(`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],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||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 L0(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}var Ls=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 be("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)||L0(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&&L0(i,o,c)}return i}return n};return r(e)}static cloneInternal(e,r={},n=new WeakMap,i=0){if(i>1024)throw new be("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 be("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))L0(s,c,this.cloneInternal(e[c],r,n,i+1));return s}};l();var zt=class extends be{constructor(e,r="BeaconError",n){super(e,r,n)}},P0=class extends be{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},M0=class extends be{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},K0=class extends be{constructor(e,r="CASBeaconError",n){super(e,r,n)}},aa=class extends be{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 u6={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Co(t){switch(t){case"bitcoin":return Zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return u0;case"regtest":return u6;default:throw new Error(`Unknown network "${t}"`)}}l();var ua=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 H0="0000000000000000000000000000000000000000000000000000000000000000",V0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var q0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(q0||(q0={}));var Ml=new ua(5);var $v=160,Hv=155,Vv=240,qv={p2pkh:Vv,p2wpkh:Hv,p2tr:$v},F0={p2pkh:34,p2wpkh:31,p2tr:43},j0={p2pkh:546,p2wpkh:294,p2tr:330};function W0(t,e){return qv[t]-F0[t]+F0[e]}function G0(t,e){let r=Qr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new zt(`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 Fv(t,e,r){return t==="p2pkh"?Li(e,r).address:t==="p2wpkh"?Bs(e,r).address:Rs(e.slice(1,33),void 0,r).address}function z0(t,e,r){if(!r||r===t)return t;try{Qr(e).decode(r)}catch{throw new zt(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function jv(t,e){try{return G0(t,e)}catch{return"p2tr"}}function Y0(t){return Ze.encode(["RETURN",t])}var Kl=546;function l6(t){return t.status.confirmed===!0}function h6(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 Wv(t,e){if(!t.length)throw new zt("No UTXOs found, please fund address!","UNFUNDED_BEACON_ADDRESS",{address:e});let r=t.filter(l6),n=r.filter(i=>i.value>Kl);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 ${Kl}-sat dust limit`;throw new zt(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:Kl})}return[...n].sort(h6)[0]}async function Gv(t,e){let r=await e.rest.address.getUtxos(t),n=Wv(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:Ir(i)}}async function p6(t){let e=t.feeEstimator??Ml,{utxo:r,prevTxBytes:n}=await Gv(t.beaconAddress,t.bitcoin),i=z0(t.beaconAddress,t.network,t.changeAddress),o=Qe.encode(Qr(t.network).decode(t.beaconAddress)),s=jv(i,t.network),c=await e.estimateFee(W0("p2tr",s));if(BigInt(r.value)<=c)throw new zt(`UTXO value (${r.value}) insufficient to cover fee (${c}).`,"INSUFFICIENT_FUNDS",{address:t.beaconAddress,valueSats:r.value,feeSats:c});let a=new Ds({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(j0[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:Y0(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 y6(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=Oo.ALL,d=t.preimageLegacy(e,i,u),f=n.sign(d,"ecdsa"),h=ht(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 zt(`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=Oo.ALL,h=t.preimageWitnessV0(e,d,f,o),p=n.sign(h,"ecdsa"),g=ht(p,new Uint8Array([f]));return t.updateInput(e,{partialSig:[[s,g]]},!0),t.finalize(),t.hex}let c=t.preimageWitnessV1(e,[i],Oo.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Ki=class{service;did;constructor(e,r){this.service=e,this.did=r}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??Ml,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await Gv(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=G0(e.beaconAddress,r),o=z0(e.beaconAddress,r,e.changeAddress),s=Fv(i,n,r);if(s!==e.beaconAddress)throw new zt(`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=jv(o,r),a=await e.feeEstimator.estimateFee(W0(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new zt(`UTXO value (${e.utxo.value}) insufficient to cover fee (${a}).`,"INSUFFICIENT_FUNDS",{address:e.beaconAddress,valueSats:e.utxo.value,feeSats:a});let d=new Ds({allowUnknownOutputs:!0}),f;if(i==="p2pkh")f=Li(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes});else if(i==="p2wpkh")f=Bs(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=Rs(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(j0[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:Y0(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 y6(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var Zu=class extends Ki{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=en(ia(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=Yn(e),c={[o]:s},a=No(ir(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 Qu=class extends Ki{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=No(ir(e)),s=await this.buildSignAndBroadcast(o,r,n,i);return{signedUpdate:e,txid:s}}};l();l();l();var g6=new Uint8Array(32),J0=1n<<BigInt(256),zv=(()=>{let t=new Array(257),e=J0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function ed(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Xn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function _e(t,e,r=""){let n=ed(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 $l(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Xn(t.outputLen),Xn(t.blockLen)}function da(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 Jv(t,e){_e(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 Ps(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Hl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function vn(t,e){return t<<32-e|t>>>e}var Xv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",m6=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ms(t){if(_e(t),Xv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=m6[t[r]];return e}var $i={_0:48,_9:57,A:65,F:70,a:97,f:102};function Yv(t){if(t>=$i._0&&t<=$i._9)return t-$i._0;if(t>=$i.A&&t<=$i.F)return t-($i.A-10);if(t>=$i.a&&t<=$i.f)return t-($i.a-10)}function Ks(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Xv)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=Yv(t.charCodeAt(o)),c=Yv(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 pr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];_e(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 Zv(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 $s(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 Qv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var Z0=BigInt(0),X0=BigInt(1);function td(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function e1(t){if(typeof t=="bigint"){if(!Vl(t))throw new Error("positive bigint expected, got "+t)}else Xn(t);return t}function rd(t){let e=e1(t).toString(16);return e.length&1?"0"+e:e}function t1(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Z0:BigInt("0x"+t)}function Lo(t){return t1(Ms(t))}function Q0(t){return t1(Ms(w6(_e(t)).reverse()))}function ql(t,e){Xn(e),t=e1(t);let r=Ks(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function eg(t,e){return ql(t,e).reverse()}function fa(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 w6(t){return Uint8Array.from(t)}function r1(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 Vl=t=>typeof t=="bigint"&&Z0<=t;function b6(t,e,r){return Vl(t)&&Vl(e)&&Vl(r)&&e<=t&&t<r}function n1(t,e,r,n){if(!b6(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function tg(t){let e;for(e=0;t>Z0;t>>=X0,e+=1);return e}var nd=t=>(X0<<BigInt(t))-X0;function i1(t,e,r){if(Xn(t,"hashLen"),Xn(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,pr(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 I=a.slice();S.push(I),x+=a.length}return pr(...S)};return(x,S)=>{f(),p(x);let I;for(;!(I=S(g()));)p();return f(),I}}function id(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 rg(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 ng(t){return t.length===32}function Po(t){if(!ng(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function Nr(...t){return ke(ht(...t))}function od(t){Po(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function ig(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 Fl(t){Po(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function og(t,e){return!ng(t)||!ng(e)?!1:fa(t,e)}function sd(t){return Po(t),Ri.encode(t)}function Mo(t){let e=Ri.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var o1;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(o1||(o1={}));l();l();var Zn=256;function Hs(t,e){return Number(t>>BigInt(Zn-1-e)&1n)}var Wl=(()=>{let t=new Array(Zn+1),e=new Uint8Array(32);for(let r=0;r<=Zn;r++)e=Nr(e,e),t[r]=e;return t})();function jl(t,e){if(t.length===0)return Wl[e];if(e===0)return t[0].leaf;let r=Zn-e,n=[],i=[];for(let o of t)(Hs(o.index,r)===0?n:i).push(o);return Nr(jl(n,e-1),jl(i,e-1))}function s1(t){return jl(t,Zn)}function c1(t,e){let r=0n,n=[];for(let i=1;i<=Zn;i++){let o=Zn-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(Hs(c.index,u)!==Hs(e,u)){a=!1;break}a&&Hs(c.index,o)!==Hs(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(Zn-1-o):n.push(jl(s,i-1))}return{collapsed:r,hashes:n}}function a1(t,e,r,n,i){let o=n,s=0;for(let c=0;c<Zn;c++){let a=Zn-1-c,u;if(Hs(t,a)===1)u=Wl[c];else{if(s>=e.length)return!1;u=e[s++]}o=Hs(r,a)===1?Nr(u,o):Nr(o,u)}return s===e.length&&og(o,i)}l();var x6=new TextEncoder;function cd(t){return od(Nr(x6.encode(t)))}function Gl(t,e){return e!==void 0&&Po(e),t!==void 0&&e!==void 0?Nr(Nr(t),e):t!==void 0?Nr(Nr(t)):e!==void 0?e:Wl[0]}l();function u1(t,e,r){let n={id:sd(t),collapsed:sd(ig(e.collapsed)),hashes:e.hashes.map(i=>sd(i))};return r?.nonce!==void 0&&(n.nonce=Ri.encode(r.nonce)),r?.updateId!==void 0&&(n.updateId=sd(r.updateId)),n}function E6(t){let e={rootHash:Mo(t.id),collapsed:od(Mo(t.collapsed)),hashes:t.hashes.map(r=>Mo(r))};return t.nonce!==void 0&&(e.nonce=Ri.decode(t.nonce)),t.updateId!==void 0&&(e.updateId=Mo(t.updateId)),e}function d1(t,e){let r;try{r=E6(t)}catch{return!1}let n=Gl(r.nonce,r.updateId);return a1(r.collapsed,r.hashes,cd(e),n,r.rootHash)}l();var zl=class{#e=new Map;#t=null;#r=null;addEntries(e){for(let r of e){r.updateId!==void 0&&Po(r.updateId);let n=cd(r.did);if(this.#e.has(n))throw new RangeError(`Duplicate DID index for: ${r.did}`);this.#e.set(n,r)}this.#t=null,this.#r=null}finalize(){let e=[];for(let[r,n]of this.#e)n.nonce===void 0&&n.updateId===void 0||e.push({index:r,leaf:Gl(n.nonce,n.updateId)});this.#t=e,this.#r=s1(e)}get rootHash(){if(this.#r===null)throw new Error("Tree not finalized: call finalize() first");return this.#r}proof(e){if(this.#t===null||this.#r===null)throw new Error("Tree not finalized: call finalize() first");let r=cd(e),n=this.#e.get(r),i=c1(this.#t,r);return u1(this.#r,i,{nonce:n?.nonce,updateId:n?.updateId})}reset(){this.#t=null,this.#r=null}};function v6(t){try{return Fl(Mo(t.id))}catch{return}}var ad=class extends Ki{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(v6(c)!==s.signalBytes)throw new aa(`SMT proof id does not equal the signal root ${s.signalBytes}.`,Ns,{smtProof:c,did:o,smtRootHash:s.signalBytes});if(!d1(c,o))throw new aa(`SMT proof verification failed for the signal root ${s.signalBytes}.`,Ns,{smtProof:c,did:o,smtRootHash:s.signalBytes});if(c.updateId===void 0)continue;let a=Fl(Mo(c.updateId)),u=r.updateMap.get(a);if(!u){i.push({kind:"NeedSignedUpdate",updateHash:a,beaconServiceId:this.service.id});continue}n.push([u,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.did,s=Br(32),c=new zl;c.addEntries([{did:o,nonce:s,updateId:zn(e)}]),c.finalize();let a=c.proof(o),u=await this.buildSignAndBroadcast(c.rootHash,r,n,i);return{signedUpdate:e,txid:u,proof:a}}};var Vs=class{static establish(e,r){switch(e.type){case"SingletonBeacon":return new Qu(e,r);case"CASBeacon":return new Zu(e,r);case"SMTBeacon":return new ad(e,r);default:throw new be("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Vi;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Vi||(Vi={}));l();var yt={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};l();var xe=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}};xe.METHOD_PATTERN="([a-z0-9]+)";xe.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})";xe.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${xe.PCT_ENCODED_PATTERN})`;xe.METHOD_ID_PATTERN=`((?:${xe.ID_CHAR_PATTERN}*:)*(${xe.ID_CHAR_PATTERN}+))`;xe.PATH_PATTERN="(/[^#?]*)?";xe.QUERY_PATTERN="([?][^#]*)?";xe.FRAGMENT_PATTERN="(#.*)?";xe.DID_URI_PATTERN=new RegExp(`^did:(?<method>${xe.METHOD_PATTERN}):(?<id>${xe.METHOD_ID_PATTERN})(?<path>${xe.PATH_PATTERN})(?<query>${xe.QUERY_PATTERN})(?<fragment>${xe.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 T6=Kn(l1(),1);l();l();l();l();var rV=new Uint8Array(0);function h1(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 la(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 I6(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,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<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 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(x+(I-q)),$=x;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 B6=I6,R6=B6,p1=R6;var ug=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")}},dg=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 y1(this,e)}},fg=class{decoders;constructor(e){this.decoders=e}or(e){return y1(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 y1(t,e){return new fg({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var lg=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 ug(e,r,n),this.decoder=new dg(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function g1({name:t,prefix:e,encode:r,decode:n}){return new lg(t,e,r,n)}function hg({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=p1(r,t);return g1({prefix:e,name:t,encode:n,decode:o=>la(i(o))})}function U6(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 O6(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 or({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return g1({prefix:e,name:t,encode(i){return O6(i,n,r)},decode(i){return U6(i,n,r,t)}})}var ud=or({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fV=or({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lV=or({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hV=or({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),pV=or({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),yV=or({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),gV=or({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mV=or({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pg=or({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var yr=hg({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),EV=hg({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var TV=or({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_V=or({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qn=or({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),IV=or({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function m1(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function w1(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function ha(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var dd=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())})},b1=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)}},Jl=new TextEncoder,qs=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(!w1(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 yr.baseDecode(this.data).buffer;case"Base64Url":return Qn.baseDecode(this.data).buffer;case"BufferSource":{if(ha(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return m1(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 dd(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 pg.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 yr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return yr.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 Qn.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Qn.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=Jl.encode(e);return Qn.baseEncode(r)}case"String":{let e=Jl.encode(this.data);return Qn.baseEncode(e)}case"Uint8Array":return Qn.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return dd(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=b1(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=Qn.baseDecode(this.data),r=qs.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=qs.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return dd(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 qs.decode(this.data);case"Base64Url":{let e=Qn.baseDecode(this.data);return qs.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return qs.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return dd(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=b1(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+=qs.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+=qs.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 pg.baseDecode(this.data);case"Base58Btc":return yr.baseDecode(this.data);case"Base64Url":return Qn.baseDecode(this.data);case"BufferSource":{let e=ha(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 Jl.encode(e)}case"String":return Jl.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return dd(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 fd;(function(t){t.Debug="debug",t.Silent="silent"})(fd||(fd={}));var yg=class{constructor(){this.logLevel=fd.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==fd.Silent&&console.info(e)}error(e){this.logLevel!==fd.Silent&&console.error(e)}},D6=new yg;typeof window<"u"&&(window.web5logger=D6);l();l();l();l();var qi={};Tu(qi,{decode:()=>pa,encodeTo:()=>Fs,encodingLength:()=>js});l();l();var k6=v1,x1=128,N6=127,C6=~N6,L6=Math.pow(2,31);function v1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=L6;)e[r++]=t&255|x1,t/=128;for(;t&C6;)e[r++]=t&255|x1,t>>>=7;return e[r]=t|0,v1.bytes=r-n+1,e}var P6=gg,M6=128,E1=127;function gg(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw gg.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&E1)<<i:(s&E1)*Math.pow(2,i),i+=7}while(s>=M6);return gg.bytes=o-n,r}var K6=Math.pow(2,7),$6=Math.pow(2,14),H6=Math.pow(2,21),V6=Math.pow(2,28),q6=Math.pow(2,35),F6=Math.pow(2,42),j6=Math.pow(2,49),W6=Math.pow(2,56),G6=Math.pow(2,63),z6=function(t){return t<K6?1:t<$6?2:t<H6?3:t<V6?4:t<q6?5:t<F6?6:t<j6?7:t<W6?8:t<G6?9:10},Y6={encode:k6,decode:P6,encodingLength:z6},J6=Y6,ld=J6;function pa(t,e=0){return[ld.decode(t,e),ld.decode.bytes]}function Fs(t,e,r=0){return ld.encode(t,e,r),e}function js(t){return ld.encodingLength(t)}function mg(t,e){let r=e.byteLength,n=js(t),i=n+js(r),o=new Uint8Array(i+r);return Fs(t,o,0),Fs(r,o,n),o.set(e,i),new ya(t,r,e,o)}function S1(t){let e=la(t),[r,n]=pa(e),[i,o]=pa(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new ya(r,i,s,e)}function A1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&h1(t.bytes,r.bytes)}}var ya=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function T1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return Z6(r,bg(t),e??yr.encoder);default:return Q6(r,bg(t),e??ud.encoder)}}var _1=new WeakMap;function bg(t){let e=_1.get(t);if(e==null){let r=new Map;return _1.set(t,r),r}return e}var xg=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!==hd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==eU)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=mg(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&&A1(e.multihash,n.multihash)}toString(e){return T1(this,e)}toJSON(){return{"/":T1(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??I1(n,i,o.bytes))}else if(r[tU]===!0){let{version:n,multihash:i,code:o}=r,s=S1(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!==hd)throw new Error(`Version 0 CID must use dag-pb (code: ${hd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=I1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,hd,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=la(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 ya(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]=pa(e.subarray(r));return r+=h,f},i=n(),o=hd;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]=X6(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 bg(o).set(n,e),o}};function X6(t,e){switch(t[0]){case"Q":{let r=e??yr;return[yr.prefix,r.decode(`${yr.prefix}${t}`)]}case yr.prefix:{let r=e??yr;return[yr.prefix,r.decode(t)]}case ud.prefix:{let r=e??ud;return[ud.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 Z6(t,e,r){let{prefix:n}=r;if(n!==yr.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 Q6(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 hd=112,eU=18;function I1(t,e,r){let n=js(t),i=n+js(e),o=new Uint8Array(i+r.byteLength);return Fs(t,o,0),Fs(e,o,n),o.set(r,i),o}var tU=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=qi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),qi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=qi.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]=qi.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 Eg(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&Eg(t[e])})}l();var aO=Kn(hm(),1),sc=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 Ah=class{constructor(){this.store=new Map}clear(){return sc(this,void 0,void 0,function*(){this.store.clear()})}close(){return sc(this,void 0,void 0,function*(){})}delete(e){return sc(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return sc(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return sc(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return sc(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return sc(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var T4=Kn(Tw(),1);var _4=Kn(Tw(),1);l();l();l();l();l();function I4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function _w(t,...e){if(!I4(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 Iw(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 NT(t,e){_w(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Ha=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var np=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e;var Qj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function B4(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Bw(t){return typeof t=="string"&&(t=B4(t)),_w(t),t}var rp=class{clone(){return this._cloneInto()}},eW={}.toString;function CT(t){let e=n=>t().update(Bw(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function LT(t=32){if(Ha&&typeof Ha.getRandomValues=="function")return Ha.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function R4(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 PT=(t,e,r)=>t&e^~t&r,MT=(t,e,r)=>t&e^t&r^e&r,ip=class extends rp{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=np(this.buffer)}update(e){Iw(this);let{view:r,buffer:n,blockLen:i}=this;e=Bw(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=np(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){Iw(this),NT(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;R4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=np(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 U4=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]),Xo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zo=new Uint32Array(64),Rw=class extends ip{constructor(){super(64,32,8,!1),this.A=Xo[0]|0,this.B=Xo[1]|0,this.C=Xo[2]|0,this.D=Xo[3]|0,this.E=Xo[4]|0,this.F=Xo[5]|0,this.G=Xo[6]|0,this.H=Xo[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=Bn(h,7)^Bn(h,18)^h>>>3,y=Bn(p,17)^Bn(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=Bn(c,6)^Bn(c,11)^Bn(c,25),p=d+h+PT(c,a,u)+U4[f]+Zo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+MT(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 Qo=CT(()=>new Rw);var O4=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())})},Va=class{static digest(e){return O4(this,arguments,void 0,function*({data:r}){return Qo(r)})}};l();var ui=class{};var D4=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())})},op=class extends ui{digest(e){return D4(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield Va.digest({data:n})}})}};l();l();l();l();l();l();function KT(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function k4(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Uw(t,...e){if(!k4(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 $T(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");KT(t.outputLen),KT(t.blockLen)}function qa(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 HT(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 sp=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function VT(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var cp=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Rn=(t,e)=>t<<32-e|t>>>e,N4=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!N4)throw new Error("Non little-endian hardware is not supported");function Ow(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Wd(t){if(typeof t=="string"&&(t=Ow(t)),!VT(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function ap(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!VT(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 Fa=class{clone(){return this._cloneInto()}},TW={}.toString;function up(t){let e=n=>t().update(Wd(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Gd(t=32){if(sp&&typeof sp.getRandomValues=="function")return sp.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function C4(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 ja=class extends Fa{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=cp(this.buffer)}update(e){qa(this);let{view:r,buffer:n,blockLen:i}=this;e=Wd(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=cp(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){qa(this),HT(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;C4(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=cp(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=(t,e,r)=>t&e^~t&r,P4=(t,e,r)=>t&e^t&r^e&r,M4=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]),es=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ts=new Uint32Array(64),Dw=class extends ja{constructor(){super(64,32,8,!1),this.A=es[0]|0,this.B=es[1]|0,this.C=es[2]|0,this.D=es[3]|0,this.E=es[4]|0,this.F=es[5]|0,this.G=es[6]|0,this.H=es[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)ts[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ts[f-15],p=ts[f-2],g=Rn(h,7)^Rn(h,18)^h>>>3,y=Rn(p,17)^Rn(p,19)^p>>>10;ts[f]=y+ts[f-7]+g+ts[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=Rn(c,6)^Rn(c,11)^Rn(c,25),p=d+h+L4(c,a,u)+M4[f]+ts[f]|0,y=(Rn(n,2)^Rn(n,13)^Rn(n,22))+P4(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(){ts.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var dp=up(()=>new Dw);l();var lp={};Tu(lp,{bitGet:()=>j4,bitLen:()=>F4,bitMask:()=>zd,bitSet:()=>W4,bytesToHex:()=>ro,bytesToNumberBE:()=>no,bytesToNumberLE:()=>On,concatBytes:()=>oo,createHmacDrbg:()=>Cw,ensureBytes:()=>Ge,equalBytes:()=>V4,hexToBytes:()=>wc,hexToNumber:()=>Nw,isBytes:()=>Un,numberToBytesBE:()=>mr,numberToBytesLE:()=>io,numberToHexUnpadded:()=>WT,numberToVarBytesBE:()=>H4,utf8ToBytes:()=>q4,validateObject:()=>cn});l();var jT=BigInt(0),fp=BigInt(1),K4=BigInt(2);function Un(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var $4=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ro(t){if(!Un(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=$4[t[r]];return e}function WT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function Nw(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var to={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function qT(t){if(t>=to._0&&t<=to._9)return t-to._0;if(t>=to._A&&t<=to._F)return t-(to._A-10);if(t>=to._a&&t<=to._f)return t-(to._a-10)}function wc(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=qT(t.charCodeAt(o)),c=qT(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 no(t){return Nw(ro(t))}function On(t){if(!Un(t))throw new Error("Uint8Array expected");return Nw(ro(Uint8Array.from(t).reverse()))}function mr(t,e){return wc(t.toString(16).padStart(e*2,"0"))}function io(t,e){return mr(t,e).reverse()}function H4(t){return wc(WT(t))}function Ge(t,e,r){let n;if(typeof e=="string")try{n=wc(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(Un(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 oo(...t){let e=0;for(let i=0;i<t.length;i++){let o=t[i];if(!Un(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 V4(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 q4(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function F4(t){let e;for(e=0;t>jT;t>>=fp,e+=1);return e}function j4(t,e){return t>>BigInt(e)&fp}var W4=(t,e,r)=>t|(r?fp:jT)<<BigInt(e),zd=t=>(K4<<BigInt(t-1))-fp,kw=t=>new Uint8Array(t),FT=t=>Uint8Array.from(t);function Cw(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=kw(t),i=kw(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=kw())=>{i=c(FT([0]),f),n=c(),f.length!==0&&(i=c(FT([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 oo(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var G4={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"||Un(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 cn(t,e,r={}){let n=(i,o,s)=>{let c=G4[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),bc=BigInt(2),z4=BigInt(3),Lw=BigInt(4),GT=BigInt(5),zT=BigInt(8),Y4=BigInt(9),J4=BigInt(16);function Re(t,e){let r=t%e;return r>=_t?r:e+r}function Pw(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 hp(t,e){if(t===_t||e<=_t)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=Re(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 Re(i,e)}function X4(t){let e=(t-et)/bc,r,n,i;for(r=t-et,n=0;r%bc===_t;r/=bc,n++);for(i=bc;i<t&&Pw(i,e,t)!==t-et;i++);if(n===1){let s=(t+et)/Lw;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)/bc;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 Z4(t){if(t%Lw===z4){let e=(t+et)/Lw;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%zT===GT){let e=(t-GT)/zT;return function(n,i){let o=n.mul(i,bc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,bc),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%J4,X4(t)}var YT=(t,e)=>(Re(t,e)&et)===et,Q4=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mw(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Q4.reduce((n,i)=>(n[i]="function",n),e);return cn(t,r)}function eN(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 tN(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 Kw(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Wa(t,e,r=!1,n={}){if(t<=_t)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=Kw(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Z4(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:zd(i),ZERO:_t,ONE:et,create:a=>Re(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=>Re(-a,t),eql:(a,u)=>a===u,sqr:a=>Re(a*a,t),add:(a,u)=>Re(a+u,t),sub:(a,u)=>Re(a-u,t),mul:(a,u)=>Re(a*u,t),pow:(a,u)=>eN(c,a,u),div:(a,u)=>Re(a*hp(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>hp(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>tN(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?io(a,o):mr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?On(a):no(a)}});return Object.freeze(c)}function JT(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 XT(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 $w(t){let e=XT(t);return e+Math.ceil(e/2)}function ZT(t,e,r=!1){let n=t.length,i=XT(e),o=$w(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?no(t):On(t),c=Re(s,e-et)+et;return r?io(c,i):mr(c,i)}l();l();var nN=BigInt(0),Hw=BigInt(1);function pp(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>nN;)o&Hw&&(s=s.add(c)),c=c.double(),o>>=Hw;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+=Hw);let S=y,I=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[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 Yd(t){return Mw(t.Fp),cn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Kw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function iN(t){let e=Yd(t);cn(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:oN,hexToBytes:sN}=lp,xc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=xc;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:oN(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=xc,r=typeof t=="string"?sN(t):t;if(!Un(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}=xc._parseInt(r.subarray(2)),{d:s,l:c}=xc._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}`}},so=BigInt(0),an=BigInt(1),WW=BigInt(2),QT=BigInt(3),GW=BigInt(4);function cN(t){let e=iN(t),{Fp:r}=e,n=e.toBytes||((g,y,x)=>{let S=y.toAffine();return oo(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),I=r.mul(S,g);return r.add(r.add(I,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"&&so<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:I}=e;if(y&&typeof g!="bigint"){if(Un(g)&&(g=ro(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:no(Ge("private key",g,x))}catch{throw new Error(`private key must be ${x} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=Re(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,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 I=A=>r.eql(A,r.ZERO);return I(x)&&I(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,I)=>S.toAffine(x[I])).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),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:x,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(x,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:x}=e,S=r.mul(x,QT),{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),Z=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,Z),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),Z=r.mul(y,Z),Q=r.sub(j,Z),Q=r.mul(y,Q),Q=r.add(Q,q),q=r.add(j,j),j=r.add(q,j),j=r.add(j,Z),j=r.mul(j,Q),M=r.add(M,j),Z=r.mul(A,O),Z=r.add(Z,Z),j=r.mul(Z,Q),T=r.sub(T,j),q=r.mul(Z,$),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:I}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,Z=r.mul(e.b,QT),Q=r.mul(x,A),G=r.mul(S,O),_=r.mul(I,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,I);let U=r.add(A,T);return E=r.mul(E,U),U=r.add(Q,_),E=r.sub(E,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($,E),M=r.mul(Z,_),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($,_),E=r.mul(Z,E),G=r.add(G,_),_=r.sub(Q,_),_=r.mul($,_),E=r.add(E,_),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(I=>I.pz));return x.map((I,A)=>I.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let x=f.ZERO;if(y===so)return x;if(c(y),y===an)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=x,q=x,j=this;for(;A>so||T>so;)A&an&&(M=M.add(j)),T&an&&(q=q.add(j)),j=j.double(),A>>=an,T>>=an;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 x=y,S,I,{endo:A}=e;if(A){let{k1neg:O,k1:T,k2neg:M,k2:q}=A.splitScalar(x),{p:j,f:$}=this.wNAF(T),{p:Z,f:Q}=this.wNAF(q);j=p.constTimeNegate(O,j),Z=p.constTimeNegate(M,Z),Z=new f(r.mul(Z.px,A.beta),Z.py,Z.pz),S=j.add(Z),I=$.add(Q)}else{let{p:O,f:T}=this.wNAF(x);S=O,I=T}return f.normalizeZ([S,I])[0]}multiplyAndAddUnsafe(y,x,S){let I=f.BASE,A=(T,M)=>M===so||M===an||!T.equals(I)?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:I}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(I));let O=r.mul(x,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:x}=e;if(y===an)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===an?this:x?x(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return ro(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=pp(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function aN(t){let e=Yd(t);return cn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function e_(t){let e=aN(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(E){return so<E&&E<r.ORDER}function c(E){return Re(E,n)}function a(E){return hp(E,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=cN({...e,toBytes(E,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=oo;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=no(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&an)===an;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=>ro(mr(E,e.nByteLength));function g(E){let U=n>>an;return E>U}function y(E){return g(E)?c(-E):E}let x=(E,U,L)=>no(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}=xc.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),X=u.BASE.multiplyAndAddUnsafe(J,W,Y);if(!X)throw new Error("point at infinify");return X.assertValidity(),X}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return wc(this.toDERHex())}toDERHex(){return xc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return wc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let I={isValidPrivateKey(E){try{return d(E),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let E=$w(e.n);return ZT(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=Un(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=no(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=zd(e.nBitLength);function $(E){if(typeof E!="bigint")throw new Error("bigint expected");if(!(so<=E&&E<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return mr(E,e.nByteLength)}function Z(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=oo(...W),X=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Oe=a(ce),Me=u.BASE.multiply(ce).toAffine(),Je=c(Me.x);if(Je===so)return;let xt=c(Oe*c(X+Je*z));if(xt===so)return;let gi=(Me.x===Je?0:2)|Number(Me.y&an),wo=xt;return C&&g(xt)&&(wo=y(xt),gi^=1),new S(Je,wo,gi)}return{seed:Y,k2sig:ue}}let Q={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function _(E,U,L=Q){let{seed:N,k2sig:R}=Z(E,U,L),C=e;return Cw(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"||Un(R))try{V=S.fromDER(R)}catch(Me){if(!(Me instanceof xc.Err))throw Me;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Me,s:Je}=R;V=new S(Me,Je)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Me){if(Me.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),X=a(W),ue=c(Y*X),ee=c(z*X),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 yp=class extends Fa{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,$T(e);let n=Wd(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 qa(this),this.iHash.update(e),this}digestInto(e){qa(this),Uw(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()}},Vw=(t,e,r)=>new yp(t,e).update(r).digest();Vw.create=(t,e)=>new yp(t,e);function uN(t){return{hash:t,hmac:(e,...r)=>Vw(t,e,ap(...r)),randomBytes:Gd}}function gp(t,e){let r=n=>e_({...t,...uN(n)});return Object.freeze({...r(e),create:r})}var n_=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),t_=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),dN=BigInt(1),qw=BigInt(2),r_=(t,e)=>(t+e/qw)/e;function fN(t){let e=n_,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,qw,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,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,qw,e);if(!Fw.eql(Fw.sqr(M),t))throw new Error("Cannot find square root");return M}var Fw=Wa(n_,void 0,void 0,{sqrt:fN}),wr=gp({a:BigInt(0),b:BigInt(7),Fp:Fw,n:t_,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=t_,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-dN*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=r_(o*t,e),a=r_(-n*t,e),u=Re(t-c*r-a*i,e),d=Re(-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}}}},dp),aG=BigInt(0);var uG=wr.ProjectivePoint;l();l();function i_(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 lN=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())})},jw="urn:jwk:";function we(t){return lN(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}`);Eg(n);let i=i_(n),o=ne.string(i).toUint8Array(),s=yield Va.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function di(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 Ga(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 fi(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 za(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 o_(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())})},hN=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=wr.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 we({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 we({jwk:i}),i})}static compressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return wr.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 we({jwk:o}),o})}static convertDerToCompactSignature(e){return $t(this,arguments,void 0,function*({derSignature:r}){return wr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return wr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=wr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return $t(this,arguments,void 0,function*({key:r}){var n;if(!(di(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=hN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return $t(this,arguments,void 0,function*({privateKey:r}){if(!di(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(!(Ga(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 wr.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=Qo(r);return wr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return wr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{wr.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=Qo(i);return wr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=wr.getPublicKey(r));let n=wr.ProjectivePoint.fromHex(r),i=mr(n.x,32),o=mr(n.y,32);return{x:i,y:o}})}};l();l();var s_=Wa(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),pN=s_.create(BigInt("-3")),yN=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),gN=gp({a:pN,b:yN,Fp:s_,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},dp),Mr=gN;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())})},mN=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=Mr.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 we({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 we({jwk:i}),i})}static compressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Mr.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 we({jwk:o}),o})}static convertDerToCompactSignature(e){return Ht(this,arguments,void 0,function*({derSignature:r}){return Mr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){return Mr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Ht(this,void 0,void 0,function*(){let e=Mr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return Ht(this,arguments,void 0,function*({key:r}){var n;if(!(di(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,o=mN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return Ht(this,arguments,void 0,function*({privateKey:r}){if(!di(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(!(Ga(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 Mr.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=Qo(r);return Mr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Ht(this,arguments,void 0,function*({privateKeyBytes:r}){return Mr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Ht(this,arguments,void 0,function*({publicKeyBytes:r}){try{Mr.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=Qo(i);return Mr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Ht(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Mr.getPublicKey(r));let n=Mr.ProjectivePoint.fromHex(r),i=mr(n.x,32),o=mr(n.y,32);return{x:i,y:o}})}};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())})},Xd=class extends ui{computePublicKey(e){return Jd(this,arguments,void 0,function*({key:r}){if(!di(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 Jd(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 Jd(this,arguments,void 0,function*({key:r}){if(!di(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 Jd(this,arguments,void 0,function*({key:r,data:n}){if(!di(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 Jd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ga(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 mp=BigInt(4294967295),Ww=BigInt(32);function c_(t,e=!1){return e?{h:Number(t&mp),l:Number(t>>Ww&mp)}:{h:Number(t>>Ww&mp)|0,l:Number(t&mp)|0}}function wN(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}=c_(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var bN=(t,e)=>BigInt(t>>>0)<<Ww|BigInt(e>>>0),xN=(t,e,r)=>t>>>r,EN=(t,e,r)=>t<<32-r|e>>>r,vN=(t,e,r)=>t>>>r|e<<32-r,SN=(t,e,r)=>t<<32-r|e>>>r,AN=(t,e,r)=>t<<64-r|e>>>r-32,TN=(t,e,r)=>t>>>r-32|e<<64-r,_N=(t,e)=>e,IN=(t,e)=>t,BN=(t,e,r)=>t<<r|e>>>32-r,RN=(t,e,r)=>e<<r|t>>>32-r,UN=(t,e,r)=>e<<r-32|t>>>64-r,ON=(t,e,r)=>t<<r-32|e>>>64-r;function DN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var kN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),NN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,CN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),LN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,PN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),MN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var KN={fromBig:c_,split:wN,toBig:bN,shrSH:xN,shrSL:EN,rotrSH:vN,rotrSL:SN,rotrBH:AN,rotrBL:TN,rotr32H:_N,rotr32L:IN,rotlSH:BN,rotlSL:RN,rotlBH:UN,rotlBL:ON,add:DN,add3L:kN,add3H:NN,add4L:CN,add4H:LN,add5H:MN,add5L:PN},pe=KN;var[$N,HN]=pe.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))),rs=new Uint32Array(80),ns=new Uint32Array(80),Gw=class extends ja{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)rs[A]=e.getUint32(r),ns[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=rs[A-15]|0,T=ns[A-15]|0,M=pe.rotrSH(O,T,1)^pe.rotrSH(O,T,8)^pe.shrSH(O,T,7),q=pe.rotrSL(O,T,1)^pe.rotrSL(O,T,8)^pe.shrSL(O,T,7),j=rs[A-2]|0,$=ns[A-2]|0,Z=pe.rotrSH(j,$,19)^pe.rotrBH(j,$,61)^pe.shrSH(j,$,6),Q=pe.rotrSL(j,$,19)^pe.rotrBL(j,$,61)^pe.shrSL(j,$,6),G=pe.add4L(q,Q,ns[A-7],ns[A-16]),_=pe.add4H(G,M,Z,rs[A-7],rs[A-16]);rs[A]=_|0,ns[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:I}=this;for(let A=0;A<80;A++){let O=pe.rotrSH(f,h,14)^pe.rotrSH(f,h,18)^pe.rotrBH(f,h,41),T=pe.rotrSL(f,h,14)^pe.rotrSL(f,h,18)^pe.rotrBL(f,h,41),M=f&p^~f&y,q=h&g^~h&x,j=pe.add5L(I,T,q,HN[A],ns[A]),$=pe.add5H(j,S,O,M,$N[A],rs[A]),Z=j|0,Q=pe.rotrSH(n,i,28)^pe.rotrBH(n,i,34)^pe.rotrBH(n,i,39),G=pe.rotrSL(n,i,28)^pe.rotrBL(n,i,34)^pe.rotrBL(n,i,39),_=n&o^n&c^o&c,D=i&s^i&a^s&a;S=y|0,I=x|0,y=p|0,x=g|0,p=f|0,g=h|0,{h:f,l:h}=pe.add(u|0,d|0,$|0,Z|0),u=c|0,d=a|0,c=o|0,a=s|0,o=n|0,s=i|0;let E=pe.add3L(Z,G,D);n=pe.add3H(E,$,Q,_),i=E|0}({h:n,l:i}=pe.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=pe.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:c,l:a}=pe.add(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:d}=pe.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:h}=pe.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:g}=pe.add(this.Fh|0,this.Fl|0,p|0,g|0),{h:y,l:x}=pe.add(this.Gh|0,this.Gl|0,y|0,x|0),{h:S,l:I}=pe.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,x,S,I)}roundClean(){rs.fill(0),ns.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 zw=up(()=>new Gw);l();var Dn=BigInt(0),Kr=BigInt(1),wp=BigInt(2),VN=BigInt(8),qN={zip215:!0};function FN(t){let e=Yd(t);return cn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function bp(t){let e=FN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=wp<<BigInt(c*8)-Kr,d=r.create,f=e.uvRatio||((N,R)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(R))}}catch{return{isValid:!1,value:Dn}}}),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"&&Dn<N,y=(N,R)=>g(N)&&g(R)&&N<R,x=N=>N===Dn||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===Dn?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,Kr,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),X=d(J*J),ue=d(X*X),ee=d(W*R),ce=d(X*d(ee+Y)),Oe=d(ue+d(C*d(W*Y)));if(ce!==Oe)throw new Error("bad point: equation left != right (1)");let Me=d(P*V),Je=d(J*z);if(Me!==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),X=d(J*V),ue=d(P*W),ee=d(z*V);return Y===X&&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(wp*d(V*V)),Y=d(R*J),X=C+P,ue=d(d(X*X)-J-z),ee=Y+z,ce=ee-W,Oe=Y-z,Me=d(ue*ce),Je=d(ee*Oe),xt=d(ue*Oe),gi=d(ce*ee);return new T(Me,Je,gi,xt)}add(R){O(R);let{a:C,d:P}=e,{ex:V,ey:J,ez:z,et:W}=this,{ex:Y,ey:X,ez:ue,et:ee}=R;if(C===BigInt(-1)){let mu=d((J-V)*(X+Y)),If=d((J+V)*(X-Y)),wu=d(If-mu);if(wu===Dn)return this.double();let Bf=d(z*wp*ee),Rf=d(W*wp*ue),Gr=Rf+Bf,xo=If+mu,bu=Rf-Bf,Uf=d(Gr*wu),ps=d(xo*bu),Of=d(Gr*bu),dy=d(wu*xo);return new T(Uf,ps,dy,Of)}let ce=d(V*Y),Oe=d(J*X),Me=d(W*P*ee),Je=d(z*ue),xt=d((V+J)*(Y+X)-ce-Oe),gi=Je-Me,wo=Je+Me,gu=d(Oe-C*ce),_f=d(xt*gi),uy=d(wo*gu),bo=d(xt*gu),Wr=d(gi*wo);return new T(_f,uy,Wr,bo)}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===Dn?q:this.equals(q)||C===Kr?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?VN:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:Dn,y:Kr};if(Y!==Kr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Kr?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=On(z);Y===Dn||(C?S(Y,u):S(Y,r.ORDER));let X=d(Y*Y),ue=d(X-Kr),ee=d(P*X-V),{isValid:ce,value:Oe}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Me=(Oe&Kr)===Kr,Je=(W&128)!==0;if(!C&&Oe===Dn&&Je)throw new Error("Point.fromHex: x=0 and x_0=1");return Je!==Me&&(Oe=d(-Oe)),T.fromAffine({x:Oe,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=io(C,r.BYTES);return P[P.length-1]|=R&Kr?128:0,P}toHex(){return ro(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Kr,d(e.Gx*e.Gy)),T.ZERO=new T(Dn,Kr,Kr,Dn);let{BASE:M,ZERO:q}=T,j=pp(T,c*8);function $(N){return Re(N,n)}function Z(N){return $(On(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=Z(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=oo(...R);return Z(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),X=$(z+Y*V);I(X);let ue=oo(W,io(X,r.BYTES));return Ge("result",ue,c*2)}let E=qN;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=On(N.slice(z,2*z)),Y,X,ue;try{Y=T.fromHex(C,J),X=T.fromHex(N.slice(0,z),J),ue=M.multiplyUnsafe(W)}catch{return!1}if(!J&&Y.isSmallOrder())return!1;let ee=_(V,X.toRawBytes(),Y.toRawBytes(),R);return X.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 Zd=BigInt(0),Yw=BigInt(1);function jN(t){return cn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function a_(t){let e=jN(t),{P:r}=e,n=A=>Re(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>Pw(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"&&Zd<=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=Yw,$=Zd,Z=T,Q=Yw,G=Zd,_;for(let E=BigInt(i-1);E>=Zd;E--){let U=M>>E&Yw;G^=U,_=u(G,j,Z),j=_[0],Z=_[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=Z+Q,J=Z-Q,z=n(J*L),W=n(V*R),Y=z+W,X=z-W;Z=n(Y*Y),Q=n(q*n(X*X)),j=n(N*C),$=n(P*(N+n(f*P)))}_=u(G,j,Z),j=_[0],Z=_[1],_=u(G,$,Q),$=_[0],Q=_[1];let D=a($);return n(j*D)}function p(A){return io(n(A),o)}function g(A){let O=Ge("u coordinate",A,o);return s===32&&(O[31]&=127),On(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 On(c(O))}function x(A,O){let T=g(O),M=y(A),q=h(T,M);if(q===Zd)throw new Error("Invalid private or public key received");return p(q)}let S=p(e.Gu);function I(A){return x(A,S)}return{scalarMult:x,scalarMultBase:I,getSharedSecret:(A,O)=>x(A,O),getPublicKey:A=>I(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Qd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),u_=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),fz=BigInt(0),WN=BigInt(1),Jw=BigInt(2),GN=BigInt(5),d_=BigInt(10),zN=BigInt(20),YN=BigInt(40),f_=BigInt(80);function l_(t){let e=Qd,n=t*t%e*t%e,i=ze(n,Jw,e)*n%e,o=ze(i,WN,e)*t%e,s=ze(o,GN,e)*o%e,c=ze(s,d_,e)*s%e,a=ze(c,zN,e)*c%e,u=ze(a,YN,e)*a%e,d=ze(u,f_,e)*u%e,f=ze(d,f_,e)*u%e,h=ze(f,d_,e)*s%e;return{pow_p_5_8:ze(h,Jw,e)*t%e,b2:n}}function h_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function JN(t,e){let r=Qd,n=Re(e*e*e,r),i=Re(n*n*e,r),o=l_(t*i).pow_p_5_8,s=Re(t*n*o,r),c=Re(e*s*s,r),a=s,u=Re(s*u_,r),d=c===t,f=c===Re(-t,r),h=c===Re(-t*u_,r);return d&&(s=a),(f||h)&&(s=u),YT(s,r)&&(s=Re(-s,r)),{isValid:d||f,value:s}}var un=Wa(Qd,void 0,!0),ef={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:un,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:zw,randomBytes:Gd,adjustScalarBytes:h_,uvRatio:JN},is=bp(ef);function p_(t,e,r){if(e.length>255)throw new Error("Context is too big");return ap(Ow("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var lz=bp({...ef,domain:p_}),hz=bp({...ef,domain:p_,prehash:zw}),Ec=a_({P:Qd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Qd,{pow_p_5_8:r,b2:n}=l_(t);return Re(ze(r,BigInt(3),e)*n,e)},adjustScalarBytes:h_,randomBytes:Gd});function y_(t){let{y:e}=is.ExtendedPoint.fromHex(t),r=BigInt(1);return un.toBytes(un.create((r+e)*un.inv(r-e)))}function g_(t){let e=ef.hash(t.subarray(0,32));return ef.adjustScalarBytes(e).subarray(0,32)}var XN=(un.ORDER+BigInt(3))/BigInt(8),pz=un.pow(Jw,XN),yz=un.sqrt(un.neg(un.ONE)),gz=(un.ORDER-BigInt(5))/BigInt(8),mz=BigInt(486662);var wz=JT(un,un.neg(BigInt(486664)));var bz=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),xz=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Ez=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),vz=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var Sz=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var dn=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())})},ZN=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 dn(this,arguments,void 0,function*({privateKeyBytes:r}){let n=is.getPublicKey(r),i={crv:"Ed25519",d:ne.uint8Array(r).toBase64Url(),kty:"OKP",x:ne.uint8Array(n).toBase64Url()};return i.kid=yield we({jwk:i}),i})}static bytesToPublicKey(e){return dn(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield we({jwk:n}),n})}static computePublicKey(e){return dn(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=is.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield we({jwk:o}),o})}static convertPrivateKeyToX25519(e){return dn(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=g_(n),o=Ec.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:ne.uint8Array(i).toBase64Url(),x:ne.uint8Array(o).toBase64Url()};return s.kid=yield we({jwk:s}),s})}static convertPublicKeyToX25519(e){return dn(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=y_(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield we({jwk:s}),s})}static generateKey(){return dn(this,void 0,void 0,function*(){let e=is.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return dn(this,arguments,void 0,function*({key:r}){var n;if(!(fi(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,o=ZN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return dn(this,arguments,void 0,function*({privateKey:r}){if(!fi(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 dn(this,arguments,void 0,function*({publicKey:r}){if(!za(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 dn(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return is.sign(n,i)})}static validatePublicKey(e){return dn(this,arguments,void 0,function*({publicKeyBytes:r}){try{is.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return dn(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return is.verify(n,i,o)})}};var tf=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())})},xp=class extends ui{computePublicKey(e){return tf(this,arguments,void 0,function*({key:r}){if(!fi(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 tf(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield It.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return tf(this,arguments,void 0,function*({key:r}){if(!fi(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 tf(this,arguments,void 0,function*({key:r,data:n}){if(!fi(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 tf(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!za(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 co=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())})},Xw={Ed25519:{implementation:xp,names:["Ed25519"]},secp256k1:{implementation:Xd,names:["ES256K","secp256k1"]},secp256r1:{implementation:Xd,names:["ES256","secp256r1"]},"SHA-256":{implementation:op,names:["SHA-256"]}},Qt=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new Ah}digest(e){return co(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return co(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return co(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=`${jw}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return co(this,arguments,void 0,function*({key:r}){let n=yield we({jwk:r});return`${jw}${n}`})}getPublicKey(e){return co(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 co(this,arguments,void 0,function*({key:r}){var n;if(!o_(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 we({jwk:i}));let o=yield this.getKeyUri({key:i});return yield this._keyStore.set(o,i),o})}sign(e){return co(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 co(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=Xw[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 Xw){let o=Xw[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 co(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 Ep=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 LT(e)}static randomUuid(){return Ha.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 os=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())})},QN=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},Ya=class t{static bytesToPrivateKey(e){return os(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Ec.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n).toBase64Url()};return i.kid=yield we({jwk:i}),i})}static bytesToPublicKey(e){return os(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield we({jwk:n}),n})}static computePublicKey(e){return os(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=Ec.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield we({jwk:o}),o})}static generateKey(){return os(this,void 0,void 0,function*(){let e=Ec.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield we({jwk:r}),r})}static getPublicKey(e){return os(this,arguments,void 0,function*({key:r}){var n;if(!(fi(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,o=QN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield we({jwk:o})),o})}static privateKeyToBytes(e){return os(this,arguments,void 0,function*({privateKey:r}){if(!fi(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 os(this,arguments,void 0,function*({publicKey:r}){if(!za(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 os(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 Ec.getSharedSecret(i,o)})}};l();l();l();function $r(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function eb({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(Qw))!==null&&r!==void 0?r:[]),Object.keys(Vi).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(Qw))!==null&&s!==void 0?s:[])}),n}function m_({didDocument:t}){let r=eb({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function w_({didDocument:t,methodId:e}){let r=[];return Object.keys(Vi).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=$r(e);i.some(c=>{let a=$r(c)===o,u=Qw(c)&&$r(c.id)===o;return a||u})&&r.push(n)}}),r}function b_(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Qw(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 tb({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 rb({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 rf=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())})},br=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 rf(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 rf(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 $r(a.id)===((u=$r(e?.methodId))!==null&&u!==void 0?u:$r((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:Ep.getJoseSignatureAlgorithmFromPublicKey(o),keyId:n.id,sign(a){return rf(this,arguments,void 0,function*({data:u}){return yield s.sign({data:u,keyUri:i})})},verify(a){return rf(this,arguments,void 0,function*({data:u,signature:d}){return yield s.verify({data:u,key:o,signature:d})})}}})}static import(e){return rf(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){var i;let o=eb({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 nb="0123456789abcdef",E_=[],x_=[];for(let t=0;t<256;t++)E_[t]=nb[t>>4&15]+nb[t&15],t<16&&(t<10?x_[48+t]=t:x_[87+t]=t);var ib=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=E_[t[n++]];return r};var v_=(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 S_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",tC=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(nf=0;nf<S_.length;nf++)tC[S_.charCodeAt(nf)]=nf;var nf;var rC=new TextDecoder,ob=(t,e)=>e?new TextDecoder(e).decode(t):rC.decode(t),nC=new TextEncoder,fn=t=>nC.encode(t);var A_=typeof window<"u"?window:self,T_=A_.crypto||A_.msCrypto||{},SJ=T_.subtle||T_.webkitSubtle;l();function Ja(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function vp(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 Ue(t,e,r){let n=[],i=null;return Ue._encode(n,t),i=v_(n),Ue.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Ue.bytes=-1;Ue._floatConversionDetected=!1;Ue._encode=function(t,e){if(e!=null)switch(vp(e)){case"object":Ue.dict(t,e);break;case"map":Ue.dictMap(t,e);break;case"array":Ue.list(t,e);break;case"set":Ue.listSet(t,e);break;case"string":Ue.string(t,e);break;case"number":Ue.number(t,e);break;case"boolean":Ue.number(t,e);break;case"arraybufferview":Ue.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Ue.buffer(t,new Uint8Array(e));break}};var Sp=new Uint8Array([101]),__=new Uint8Array([100]),I_=new Uint8Array([108]);Ue.buffer=function(t,e){t.push(fn(e.length+":"),e)};Ue.string=function(t,e){t.push(fn(fn(e).byteLength+":"+e))};Ue.number=function(t,e){if(Number.isInteger(e))return t.push(fn("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(fn("i"+o+"e")),o!==e&&!Ue._floatConversionDetected&&(Ue._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())};Ue.dict=function(t,e){t.push(__);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Ue.string(t,n),Ue._encode(t,e[n]));t.push(Sp)};Ue.dictMap=function(t,e){t.push(__);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Ue._encode(t,n):Ue.string(t,String(n)),Ue._encode(t,e.get(n)));t.push(Sp)};Ue.list=function(t,e){let r=0,n=e.length;for(t.push(I_);r<n;r++)e[r]!=null&&Ue._encode(t,e[r]);t.push(Sp)};Ue.listSet=function(t,e){t.push(I_);for(let r of e)r!=null&&Ue._encode(t,r);t.push(Sp)};var B_=Ue;l();var iC=105,oC=58,sC=100,cC=108,sb=101;function R_(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)):fn(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 sC:return de.dictionary();case cC:return de.list();case iC: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]!==sb;){let e=de.buffer(),r=ob(e);r.includes("\uFFFD")&&(r=ib(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==sb;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find(sb),e=R_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find(oC),e=R_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?ob(de.data.slice(t,r)):de.data.slice(t,r)};var U_=de;l();function aC(t){let e=2;for(let r of t)e+=Ap(r);return e}function uC(t){let e=2;for(let[r,n]of t){let i=fn(r).byteLength;e+=Ja(i)+1+i,e+=Ap(n)}return e}function dC(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=fn(r[n]).byteLength;e+=Ja(i)+1+i,e+=Ap(t[r[n]])}return e}function fC(t){let e=fn(t).byteLength;return Ja(e)+1+e}function lC(t){let e=t.byteLength-t.byteOffset;return Ja(e)+1+e}function Ap(t){if(t==null)return 0;let r=vp(t);switch(r){case"arraybufferview":return lC(t);case"string":return fC(t);case"array":case"set":return aC(t);case"number":return 1+Ja(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return dC(t);case"map":return uC(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var cb=Ap;var hC=cb,ab={encode:B_,decode:U_,byteLength:cb,encodingLength:hC};l();l();var pC=/^(\d{1,3}\.){3,3}\d{1,3}$/;var yC=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var kn={name:"v4",size:4,isFormat:t=>pC.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]}`}},ao={name:"v6",size:16,isFormat:t=>t.length>0&&yC.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 O_(t){if(kn.isFormat(t))return kn.size;if(ao.isFormat(t))return ao.size;throw Error(`Invalid ip address: ${t}`)}function D_(t){return O_(t)===kn.size?1:2}function k_(t,e,r){r=~~r;let n=O_(t);return typeof e=="function"&&(e=e(r+n)),n===kn.size?kn.encode(t,e,r):ao.encode(t,e,r)}function N_(t,e,r){if(e=~~e,r=r||t.length-e,r===kn.size)return kn.decode(t,e,r);if(r===ao.size)return ao.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${kn.size} for v4 or ${ao.size} for v6.`)}l();function of(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 Xa(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 C_(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 L_(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 ub(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 db(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 P_(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 fb(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 lb(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 Za(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(lb(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 Za.bytes=i-r,e}Za.bytes=0;function Qa(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 Qa.bytes=r-e,n}Qa.bytes=0;var ss=t=>t instanceof Uint8Array;function uo(t){return typeof t=="string"?lb(t):t.byteLength}function Tp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):Za(t)}function _p(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return Za(e,t,r),Za.bytes}var sf={},M_=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}`;M_[s]=c,sf[c]=s,sf[`${r}${i}`]=s,sf[`${e}${o}`]=s,sf[`${r}${o}`]=s}}function K_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=M_[o]}return n}function hb(t){return t.length>>>1}function $_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=sf[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var SC=Math.pow(2,24),AC=Math.pow(2,16),TC=Math.pow(2,8),li=(t,e)=>t[e]*SC+t[e+1]*AC+t[e+2]*TC+t[e+3],ye=(t,e)=>t[e]<<8|t[e+1],hi=(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 xr(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:_C(t,e,r,n,i)}function _C(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 BC=0,H_=32768,yb=32768,RC=~yb,q_=32768,UC=~q_;function $e({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=$e({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=_p(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=ye(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(Qa(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:uo(t.replace(/^\.|\.$/gm,""))+2}}),Bt=$e({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=_p(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=Qa(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return uo(t)+1}}),eu=$e({bytes:12,encode(t,e,r){e||(e=new Uint8Array(eu.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?H_:BC;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=ye(t,e+2);return{id:ye(t,e),type:r&H_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:L_(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:C_(r&15),questions:new Array(ye(t,e+4)),answers:new Array(ye(t,e+6)),authorities:new Array(ye(t,e+8)),additionals:new Array(ye(t,e+10))}},encodingLength(){return 12}}),Bp=$e({encode(t,e,r){e||(e=new Uint8Array(Bp.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),xr(t,e,r+2,0,n),Bp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=ye(t,e),n=t.slice(e+2,e+2+r);return Bp.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),Rp=$e({encode(t,e,r){return e||(e=new Uint8Array(Rp.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),Rp.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=ye(t,e),n=se.decode(t,e+2);return Rp.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),Up=$e({encode(t,e,r){e||(e=new Uint8Array(Up.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,hi(e,t.serial||0,r),r+=4,hi(e,t.refresh||0,r),r+=4,hi(e,t.retry||0,r),r+=4,hi(e,t.expire||0,r),r+=4,hi(e,t.minimum||0,r),r+=4,ae(e,r-n-2,n),Up.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=li(t,e),e+=4,n.refresh=li(t,e),e+=4,n.retry=li(t,e),e+=4,n.expire=li(t,e),e+=4,n.minimum=li(t,e),e+=4,Up.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),Op=$e({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=Tp(t[i])),!ss(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(Op.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,xr(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),Op.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=ye(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 Op.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=uo(r)+1:e+=r.length+1}),e}}),Dp=$e({encode(t,e,r){e||(e=new Uint8Array(Dp.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=Tp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return xr(t,e,r,0,i),r+=i,ae(e,r-n-2,n),Dp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=ye(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,Dp.decode.bytes=e-r,i},encodingLength(t){return t?(ss(t)?t.length:uo(t))+2:2}}),kp=$e({encode(t,e,r){e||(e=new Uint8Array(kp.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),kp.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,kp.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),nu=$e({encode(t,e,r){return e||(e=new Uint8Array(nu.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),nu.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return nu.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),Np=$e({encode(t,e,r){e||(e=new Uint8Array(Np.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),Np.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=ye(t,e),n={};return n.priority=ye(t,e+2),n.weight=ye(t,e+4),n.port=ye(t,e+6),n.target=se.decode(t,e+8),Np.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),cs=$e({encode(t,e,r){let n=cs.encodingLength(t);return e||(e=new Uint8Array(cs.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=cs.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,_p(e,t.value,r),r+=uo(t.value),cs.encode.bytes=n,e},decode(t,e){e||(e=0);let r=ye(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=Qa(t,e,n+r),i.issuerCritical=!!(i.flags&cs.ISSUER_CRITICAL),cs.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});cs.ISSUER_CRITICAL=128;var Cp=$e({encode(t,e,r){e||(e=new Uint8Array(Cp.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),Cp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=ye(t,e),e+=2,n.exchange=se.decode(t,e),e+=se.decode.bytes,Cp.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),F_=$e({encode(t,e,r){return e||(e=new Uint8Array(F_.encodingLength(t))),r||(r=0),ae(e,4,r),r+=2,kn.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,kn.decode(t,e)},bytes:6}),Lp=$e({encode(t,e,r){return e||(e=new Uint8Array(Lp.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,ao.encode(t,e,r),Lp.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=ao.decode(t,e);return Lp.decode.bytes=18,r},bytes:18}),V_=t=>new Uint8Array(t),fo=$e({encode(t,e,r){e||(e=new Uint8Array(fo.encodingLength(t))),r||(r=0);let n=r,i=fb(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,xr(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||D_(t.ip,V_),c=k_(t.ip,V_),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,xr(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 fo.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=ye(t,e),r.type=P_(r.code),e+=2;let n=ye(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=ye(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);xr(t,i,0,e,e+n-4),r.ip=N_(i)}break;case 11:n>0&&(r.timeout=ye(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(ye(t,e)),e+=2}return fo.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(fb(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}`)}}),as=$e({encode(t,e,r){e||(e=new Uint8Array(as.encodingLength(t))),r||(r=0);let n=r,i=ru(t,fo);return ae(e,i,r),r=lf(t,fo,e,r+2),as.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=ye(t,e);e+=2;let o=0;for(;i>0;)n[o++]=fo.decode(t,e),e+=fo.decode.bytes,i-=fo.decode.bytes;return as.decode.bytes=e-r,n},encodingLength(t){return 2+ru(t||[],fo)}}),pi=$e({encode(t,e,r){e||(e=new Uint8Array(pi.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!ss(i))throw new Error("Key must be a Buffer");return r+=2,ae(e,t.flags,r),r+=2,e[r]=pi.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,xr(i,e,r,0,i.length),r+=i.length,pi.encode.bytes=r-n,ae(e,pi.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);if(e+=2,n.flags=ye(t,e),e+=2,t[e]!==pi.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,pi.decode.bytes=e-r,n},encodingLength(t){return 6+uo(t.key)}});pi.PROTOCOL_DNSSEC=3;pi.ZONE_KEY=128;pi.SECURE_ENTRYPOINT=32768;var cf=$e({encode(t,e,r){e||(e=new Uint8Array(cf.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!ss(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Xa(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,hi(e,t.originalTTL,r),r+=4,hi(e,t.expiration,r),r+=4,hi(e,t.inception,r),r+=4,ae(e,t.keyTag,r),r+=2,se.encode(t.signersName,e,r),r+=se.encode.bytes,xr(i,e,r,0,i.length),r+=i.length,cf.encode.bytes=r-n,ae(e,cf.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);return e+=2,n.typeCovered=of(ye(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=li(t,e),e+=4,n.expiration=li(t,e),e+=4,n.inception=li(t,e),e+=4,n.keyTag=ye(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,cf.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+uo(t.signature)}}),af=$e({encode(t,e,r){e||(e=new Uint8Array(af.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,af.encode.bytes=r-n,ae(e,af.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,af.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Hr=$e({encode(t,e,r){e||(e=new Uint8Array(Hr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Xa(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=Tp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,xr(s,e,r,0,s.length),r+=s.length}return Hr.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=of(o<<8|c<<3|u);i.push(d)}}e+=s}return Hr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Xa(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}}),uf=$e({encode(t,e,r){e||(e=new Uint8Array(uf.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Hr.encode(t.rrtypes,e,r),r+=Hr.encode.bytes,uf.encode.bytes=r-n,ae(e,uf.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);return e+=2,n.nextDomain=se.decode(t,e),e+=se.decode.bytes,n.rrtypes=Hr.decode(t,e,i-(e-r)),e+=Hr.decode.bytes,uf.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Hr.encodingLength(t.rrtypes)}}),df=$e({encode(t,e,r){e||(e=new Uint8Array(df.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!ss(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!ss(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,xr(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,xr(o,e,r,0,o.length),r+=o.length,Hr.encode(t.rrtypes,e,r),r+=Hr.encode.bytes,df.encode.bytes=r-n,ae(e,df.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=ye(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=Hr.decode(t,e,i-(e-r)),e+=Hr.decode.bytes,df.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Hr.encodingLength(t.rrtypes)}}),ff=$e({encode(t,e,r){e||(e=new Uint8Array(ff.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!ss(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,xr(i,e,r,0,i.length),r+=i.length,ff.encode.bytes=r-n,ae(e,ff.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=ye(t,e);return e+=2,n.keyTag=ye(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,ff.decode.bytes=e-r,n},encodingLength(t){return 6+uo(t.digest)}}),tu=$e({encode(t,e,r){e||(e=new Uint8Array(tu.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=hb(t.fingerprint),o=gb(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return $_(e,t.fingerprint,r,r+=i),tu.encode.bytes=r-n,ae(e,tu.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=gb(n.hash);return n.fingerprint=K_(t,e,e+i),e+=i,tu.decode.bytes=e-r,n},encodingLength(t){return 4+hb(t.fingerprint)}});function gb(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}tu.getFingerprintLengthForHashType=gb;function pb(t){switch(t.toUpperCase()){case"A":return F_;case"PTR":return nu;case"CNAME":return nu;case"DNAME":return nu;case"TXT":return Op;case"NULL":return Dp;case"AAAA":return Lp;case"SRV":return Np;case"HINFO":return kp;case"CAA":return cs;case"NS":return Rp;case"SOA":return Up;case"MX":return Cp;case"OPT":return as;case"DNSKEY":return pi;case"RRSIG":return cf;case"RP":return af;case"NSEC":return uf;case"NSEC3":return df;case"SSHFP":return tu;case"DS":return ff}return Bp}var ln=$e({encode(t,e,r){e||(e=new Uint8Array(ln.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Xa(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,as.encode(t.options||[],e,r),r+=as.encode.bytes}else{let i=db(t.class===void 0?"IN":t.class);t.flush&&(i|=yb),ae(e,i,r+2),hi(e,t.ttl||0,r+4),r+=8;let o=pb(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return ln.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=of(ye(t,e)),r.type==="OPT")r.udpPayloadSize=ye(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=ye(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=as.decode(t,e+8),e+=8+as.decode.bytes;else{let i=ye(t,e+2);r.ttl=li(t,e+4),r.class=ub(i&RC),r.flush=!!(i&yb);let o=pb(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return ln.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+pb(t.type).encodingLength(e)}}),iu=$e({encode(t,e,r){e||(e=new Uint8Array(iu.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Xa(t.type),r),r+=2,ae(e,db(t.class===void 0?"IN":t.class),r),r+=2,iu.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=of(ye(t,e)),e+=2,n.class=ub(ye(t,e)),e+=2,!!(n.class&q_)&&(n.class&=UC),iu.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var j_=1024;var qt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(OC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),eu.encode(t,e,r),r+=eu.encode.bytes,r=lf(t.questions,iu,e,r),r=lf(t.answers,ln,e,r),r=lf(t.authorities,ln,e,r),r=lf(t.additionals,ln,e,r),qt.encode.bytes=r-i,n&&hf.bytes!==e.length?e.slice(0,hf.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=eu.decode(t,e);return e+=eu.decode.bytes,e=Ip(n.questions,iu,t,e),e=Ip(n.answers,ln,t,e),e=Ip(n.authorities,ln,t,e),e=Ip(n.additionals,ln,t,e),qt.decode.bytes=e-r,n},encodingLength:function(t){return eu.encodingLength(t)+ru(t.questions||[],iu)+ru(t.answers||[],ln)+ru(t.authorities||[],ln)+ru(t.additionals||[],ln)}};qt.encode.bytes=0;qt.decode.bytes=0;function Pp(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 Mp={encode:function(t,e,r){return e=qt.encode(Pp(t,"query"),e,r),Mp.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Mp.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Pp(t,"query"))}};Mp.encode.bytes=0;Mp.decode.bytes=0;var Kp={encode:function(t,e,r){return e=qt.encode(Pp(t,"response"),e,r),Kp.encode.bytes=qt.encode.bytes,e},decode:function(t,e){let r=qt.decode(t,e);return Kp.decode.bytes=qt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return qt.encodingLength(Pp(t,"response"))}};Kp.encode.bytes=0;Kp.decode.bytes=0;var hf=qt.encode,$p=qt.decode,OC=qt.encodingLength;function W_(t){let e=hf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),xr(e,r,2,0,e.length),W_.bytes=r.byteLength,r}W_.bytes=0;function G_(t){let e=ye(t,0);if(t.byteLength<e+2)return null;let r=$p(t.slice(2));return G_.bytes=$p.bytes,r}G_.bytes=0;function ru(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function lf(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 Ip(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 z_=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())})},hn=class{static getSigningMethod(e){return z_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return z_(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())})},Y_=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},J_="https://diddht.tbddev.org",DC=0,us=7200,Hp=";",cr=",",mb;(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"})(mb||(mb={}));var ar;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(ar||(ar={}));var wb;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(wb||(wb={}));var Z_={Ed25519:ar.Ed25519,ES256K:ar.secp256k1,ES256:ar.secp256r1,"P-256":ar.secp256r1,secp256k1:ar.secp256k1,secp256r1:ar.secp256r1,X25519:ar.X25519},X_={[ar.Ed25519]:"EdDSA",[ar.secp256k1]:"ES256K",[ar.secp256r1]:"ES256",[ar.X25519]:"ECDH-ES+A256KW"},pf=class t extends hn{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 Z_)))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}),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 we({jwk:q});j=`${S}#${$r(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 br({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 Ct(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){var i;let o=xe.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield br.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=xe.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 $r(c.id)===((a=$r(n))!==null&&a!==void 0?a:$r((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=J_}){return yield Vp.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:J_;try{yield Nt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Vp.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},yt),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},yt),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};pf.methodName="dht";var Vp=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(cr);break}case f.startsWith("cnt"):{let h=Nt.parseTxtDataToString(d.data);c.controller=h.includes(cr)?h.split(cr):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(),I=ar[Number(p)],A=yield Nt.keyConverter(I).bytesToPublicKey({publicKeyBytes:S});A.alg=x||X_[Number(p)];let O=f==="k0"?"0":h!==void 0?h:yield we({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=Y_(h,["id","t","se"]),S=y.includes(cr)?y.split(cr):[y],I=Object.fromEntries(Object.entries(x).map(([A,O])=>[A,O.includes(cr)?O.split(cr):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}=Nt.parseTxtDataToObject(d.data);a.types=h.split(cr).map(p=>Number(p));break}case f.startsWith("did"):{let h=I=>I.split(cr).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:I,previousDid:A}=o;yield Nt.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:us,data:`id=${A};s=${I}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:us,data:r.alsoKnownAs.join(cr)}),r.controller){let I=Array.isArray(r.controller)?r.controller.join(cr):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:us,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 Z_))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=ar[M.crv],j=yield Nt.keyConverter(M.crv).publicKeyToBytes({publicKey:M}),$=ne.uint8Array(j).toBase64Url(),Z=[`t=${q}`,`k=${$}`];T!=="0"&&(yield we({jwk:M}))!==T&&Z.unshift(`id=${T}`),M.alg!==X_[q]&&Z.push(`a=${M.alg}`),A.controller!==r.id&&Z.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:us,data:Z.join(Hp)})}(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=Y_(I,["id","type","serviceEndpoint"]);T=$r(T),q=Array.isArray(q)?q.join(","):q;let Z=Object.entries(Object.assign({id:T,t:M,se:q},j)).map(([G,_])=>`${G}=${_}`).join(Hp),Q=Nt.chunkDataIfNeeded(Z);f.push({type:"TXT",name:`_${O}._did.`,ttl:us,data:Q})});let x=[`v=${DC}`];if(y.length&&x.push(`vm=${y.join(cr)}`),Object.keys(Vi).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=wb[I];x.push(`${T}=${O.join(cr)}`)}}),g.length&&x.push(`svc=${g.join(cr)}`),!((d=n.types)===null||d===void 0)&&d.length){let A=n.types.map(O=>typeof O=="string"?mb[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:us,data:`id=${A.join(cr)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:us,data:x.join(Hp)});for(let I of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:us,data:I+"."});return{id:0,type:"response",flags:j_,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=hf(r),c=ab.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=xe.parse(e);if(!r)throw new re(ie.InvalidDid,`Invalid DID URI: ${e}`);if(r.method!==pf.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:${pf.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:Ya}[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=ab.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 $p(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(Hp).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 Pe=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var SX=new Uint8Array(0);var bb=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 xb=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")}},Eb=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 Q_(this,e)}},vb=class{constructor(e){this.decoders=e}or(e){return Q_(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`)}},Q_=(t,e)=>new vb({...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 xb(e,r,n),this.decoder=new Eb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},kC=({name:t,prefix:e,encode:r,decode:n})=>new Sb(t,e,r,n);var NC=(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},CC=(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},yf=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>kC({prefix:e,name:t,encode(i){return CC(i,n,r)},decode(i){return NC(i,n,r,t)}});var NX=yf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),CX=yf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),gf=yf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),LX=yf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Er=class t{static encode(e){return gf.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Pe(Ye.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return gf.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 dI=Kn(tI(),1);l();l();var Ab;(function(t){t.Public="public",t.Private="private"})(Ab||(Ab={}));var Vr=Ab;var Rt=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===Vr.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Pe(Ye.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Pe(Ye.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Pe(Ye.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===Vr.Private&&(e.d===void 0||e.d.length!==43))throw new Pe(Ye.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Pe(Ye.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!Er.isBase64UrlString(e))throw new Pe(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 Pe(Ye.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var mf=class{};mf.hashAlgorithmInMultihashCode=18;mf.maxCanonicalizedDeltaSizeInBytes=1e3;var ur=mf;l();var iI=Kn(nI(),1);var Nn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=iI.default(r);return Er.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 LC=cI,oI=128,PC=127,MC=~PC,KC=Math.pow(2,31);function cI(t,e,r){e=e||[],r=r||0;for(var n=r;t>=KC;)e[r++]=t&255|oI,t/=128;for(;t&MC;)e[r++]=t&255|oI,t>>>=7;return e[r]=t|0,cI.bytes=r-n+1,e}var $C=Tb,HC=128,sI=127;function Tb(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw Tb.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&sI)<<i:(s&sI)*Math.pow(2,i),i+=7}while(s>=HC);return Tb.bytes=o-n,r}var VC=Math.pow(2,7),qC=Math.pow(2,14),FC=Math.pow(2,21),jC=Math.pow(2,28),WC=Math.pow(2,35),GC=Math.pow(2,42),zC=Math.pow(2,49),YC=Math.pow(2,56),JC=Math.pow(2,63),XC=function(t){return t<VC?1:t<qC?2:t<FC?3:t<jC?4:t<WC?5:t<GC?6:t<zC?7:t<YC?8:t<JC?9:10},ZC={encode:LC,decode:$C,encodingLength:XC},QC=ZC,wf=QC;var _b=(t,e=0)=>[wf.decode(t,e),wf.decode.bytes],Ib=(t,e,r=0)=>(wf.encode(t,e,r),e),Bb=t=>wf.encodingLength(t);var Rb=(t,e)=>{let r=e.byteLength,n=Bb(t),i=n+Bb(r),o=new Uint8Array(i+r);return Ib(t,o,0),Ib(r,o,n),o.set(e,i),new Fp(t,r,e,o)},aI=t=>{let e=bb(t),[r,n]=_b(e),[i,o]=_b(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Fp(r,i,s,e)};var Fp=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var Ob=({name:t,code:e,encode:r})=>new Ub(t,e,r),Ub=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?Rb(this.code,r):r.then(n=>Rb(this.code,n))}else throw Error("Unknown type, must be binary type")}};var uI=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),jp=Ob({name:"sha2-256",code:18,encode:uI("SHA-256")}),gZ=Ob({name:"sha2-512",code:19,encode:uI("SHA-512")});var bf=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 bf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield jp.digest(e)).bytes;break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return bf(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield jp.encode(e);break;default:throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return bf(this,void 0,void 0,function*(){let n=Nn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return bf(this,void 0,void 0,function*(){let n=Nn.canonicalizeAsBytes(e),i=yield t.hashAsNonMultihashBytes(n,r);return yield t.hashThenEncode(i,r)})}static hashThenEncode(e,r){return bf(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return Er.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=Er.decodeAsBytes(e,r);try{n=aI(i)}catch{throw new Pe(Ye.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=ur.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Pe(Ye.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var Db;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(Db||(Db={}));var xf=Db;l();var kb;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(kb||(kb={}));var vc=kb;var Wp=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())})},ds=class t{static createCreateRequest(e){return Wp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;Rt.validateEs256kOperationKey(r,Vr.Public),Rt.validateEs256kOperationKey(n,Vr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=ur.hashAlgorithmInMultihashCode,c=[{action:vc.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:xf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Wp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,Vr.Public);let r=ur.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:xf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return Wp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.recoveryPublicKey,Vr.Public),Rt.validateEs256kOperationKey(e.nextRecoveryPublicKey,Vr.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,Vr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=ur.hashAlgorithmInMultihashCode,n=yield Lt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:vc.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:xf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return Wp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),Rt.validateEs256kOperationKey(e.updatePublicKey,Vr.Public),Rt.validateEs256kOperationKey(e.nextUpdatePublicKey,Vr.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:vc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:vc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:vc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:vc.RemovePublicKeys,ids:s};r.push(g)}let c=ur.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:xf.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 Pe(Ye.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(Rt.validateId(n.id),r.has(n.id))throw new Pe(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 Pe(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 Pe(Ye.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Pe(Ye.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&dI.parse(e.serviceEndpoint).error!==void 0)throw new Pe(Ye.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=Nn.canonicalizeAsBytes(e);if(r.length>ur.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${ur.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Pe(Ye.DeltaExceedsMaximumSize,n)}}};var fI=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())})},ou=class t{static createLongFormDid(e){return fI(this,void 0,void 0,function*(){let r=yield ds.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;ur.network===void 0||ur.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${ur.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=Nn.canonicalizeAsBytes(o),c=Er.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return fI(this,void 0,void 0,function*(){let r=Nn.canonicalizeAsBytes(e),n=yield Lt.hash(r,ur.hashAlgorithmInMultihashCode);return Er.encode(n)})}};l();l();var lI;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(lI||(lI={}));l();var hI;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(hI||(hI={}));l();var fs=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())})},yi;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(yi||(yi={}));var rL={Ed25519:yi.Ed25519,ES256K:yi.secp256k1,ES256:yi.secp256r1,"P-256":yi.secp256r1,secp256k1:yi.secp256k1,secp256r1:yi.secp256r1},pI="https://ion.tbd.engineering",Nb=class t extends hn{static create(){return fs(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 rL)))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:yi.secp256k1}),g=yield e.getPublicKey({keyUri:p}),y=yield e.generateKey({algorithm:yi.secp256k1}),x=yield e.getPublicKey({keyUri:y}),S=yield Sc.computeLongFormDidUri({recoveryKey:g,updateKey:x,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 br({uri:S,document:I,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 fs(this,arguments,void 0,function*({didDocument:r,methodId:n}){var i;let o=xe.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 fs(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=xe.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield br.import({portableDid:r,keyManager:n})})}static publish(e){return fs(this,arguments,void 0,function*({did:r,gatewayUri:n=pI}){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:w_({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield Sc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield Sc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=Sc.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 fs(this,arguments,void 0,function*(r,n={}){var i,o;let s=xe.parse(r);if(!s)return Object.assign(Object.assign({},yt),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},yt),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:pI;try{let a=Sc.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({},yt),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({},yt),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};Nb.methodName="ion";var Sc=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 fs(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 ou.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return fs(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield ds.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return fs(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 we({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 Gp=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())})},Cb=class t extends hn{static create(){return Gp(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 br({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return Gp(this,arguments,void 0,function*({didDocument:r}){var n;let i=xe.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 Gp(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=xe.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield br.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 Gp(this,void 0,void 0,function*(){let n=xe.parse(e),i;try{i=ne.base64Url(n.id).toObject()}catch{}if(!n||!i)return Object.assign(Object.assign({},yt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},yt),{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({},yt),{didDocument:o})})}};Cb.methodName="jwk";l();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())})},lo;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(lo||(lo={}));var Lb={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"},nL={Ed25519:lo.Ed25519,ES256K:lo.secp256k1,ES256:lo.secp256r1,"P-256":lo.secp256r1,secp256k1:lo.secp256k1,secp256r1:lo.secp256r1,X25519:lo.X25519},Pb=class t extends hn{static create(){return Cn(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 vr.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new br({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return Cn(this,arguments,void 0,function*({didDocument:r}){var n;let i=xe.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 Cn(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Qt}){let i=xe.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield br.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 Cn(this,void 0,void 0,function*(){try{let n=yield t.createDocument({didUri:e,options:r});return Object.assign(Object.assign({},yt),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},yt),{didResolutionMetadata:Object.assign({error:n.code},n.message&&{errorMessage:n.message})})}})}static createDocument(e){return Cn(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=xe.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 m_({didDocument:a}).forEach(g=>{let y=Lb[g];h.push(y)}),a["@context"]=h,a})}static createEncryptionMethod(e){return Cn(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=vr.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=tb({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 Lb))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 vr.multicodecToJwk({code:u});c.publicKeyJwk=yield vr.keyConverter(g).bytesToPublicKey({publicKeyBytes:a})}return c})}static createSignatureMethod(e){return Cn(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}=rb({multibaseKeyId:n}),f=a.byteLength,h=vr.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 Lb))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 vr.multicodecToJwk({code:u});c.publicKeyJwk=yield vr.keyConverter(y).bytesToPublicKey({publicKeyBytes:a})}return c})}static deriveEncryptionKey(e){return Cn(this,arguments,void 0,function*({multibaseValue:r}){let n={keyBytes:new Uint8Array,multicodecCode:0},{keyBytes:i,multicodecCode:o}=rb({multibaseKeyId:r});if(o===237){let s=yield vr.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield It.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield vr.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&&ha(n)==="String"&&n.startsWith("z")}};Pb.methodName="key";var vr=class t{static jwkToMulticodec(e){return Cn(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:Ya}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static multicodecToJwk(e){return Cn(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 Cn(this,arguments,void 0,function*({publicKey:r}){var n;if(!(r?.crv&&r.crv in nL))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 tb({keyBytes:i,multicodecName:o})})}};vr.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"};vr.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};vr.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 iL=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 hn{static resolve(e,r){return iL(this,void 0,void 0,function*(){let n=xe.parse(e);if(!n)return Object.assign(Object.assign({},yt),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},yt),{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({},yt),{didDocument:c})}catch{return Object.assign(Object.assign({},yt),{didResolutionMetadata:{error:"notFound"}})}})}};Mb.methodName="web";l();var dL=Kn(gI(),1),fL=Kn(hm(),1);l();l();var tt=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 capabilityInvocationEntry(e,r){let n=t.relationshipMethodId(r,e.id);if(n!==void 0)return e.capabilityInvocation?.find(i=>t.relationshipMethodId(i,e.id)===n)}static verificationMethodOfEntry(e,r){if(t.isDidVerificationMethod(r))return r;let n=t.absoluteDidUrl(r,e.id);if(n!==void 0)return e.verificationMethod?.find(i=>t.absoluteDidUrl(i?.id,e.id)===n)}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 Ve("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys(Vi).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=e.split(":");if(n.length!==4)throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let[i,o,s,c]=n;if(!i||i!=="urn")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!o||o!=="zcap")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!s||s!=="root")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let u=decodeURIComponent(c);return r.id=e,r.controller=u,r.invocationTarget=u,r}};l();l();l();l();l();l();l();function mI(t,e,r){return t&e^~t&r}function wI(t,e,r){return t&e^t&r^e&r}var Yp=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=Hl(this.buffer)}update(e){da(this),_e(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=Hl(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){da(this),Jv(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Ps(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=Hl(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()}},ho=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var lL=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]),ls=new Uint32Array(64),Kb=class extends Yp{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)ls[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ls[f-15],p=ls[f-2],g=vn(h,7)^vn(h,18)^h>>>3,y=vn(p,17)^vn(p,19)^p>>>10;ls[f]=y+ls[f-7]+g+ls[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=vn(c,6)^vn(c,11)^vn(c,25),p=d+h+mI(c,a,u)+lL[f]+ls[f]|0,y=(vn(n,2)^vn(n,13)^vn(n,22))+wI(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(){Ps(ls)}destroy(){this.set(0,0,0,0,0,0,0,0),Ps(this.buffer)}},$b=class extends Kb{A=ho[0]|0;B=ho[1]|0;C=ho[2]|0;D=ho[3]|0;E=ho[4]|0;F=ho[5]|0;G=ho[6]|0;H=ho[7]|0;constructor(){super(32)}};var Jp=Zv(()=>new $b,Qv(1));l();l();var dr=BigInt(0),er=BigInt(1),Tc=BigInt(2),EI=BigInt(3),vI=BigInt(4),SI=BigInt(5),hL=BigInt(7),AI=BigInt(8),pL=BigInt(9),TI=BigInt(16);function Ln(t,e){let r=t%e;return r>=dr?r:e+r}function qr(t,e,r){let n=t;for(;e-- >dr;)n*=n,n%=r;return n}function bI(t,e){if(t===dr)throw new Error("invert: expected non-zero number");if(e<=dr)throw new Error("invert: expected positive modulus, got "+e);let r=Ln(t,e),n=e,i=dr,o=er,s=er,c=dr;for(;r!==dr;){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 Ln(i,e)}function Vb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function _I(t,e){let r=(t.ORDER+er)/vI,n=t.pow(e,r);return Vb(t,n,e),n}function yL(t,e){let r=(t.ORDER-SI)/AI,n=t.mul(e,Tc),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,Tc),i),c=t.mul(o,t.sub(s,t.ONE));return Vb(t,c,e),c}function gL(t){let e=uu(t),r=II(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+hL)/TI;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 Vb(c,x,a),x}}function II(t){if(t<EI)throw new Error("sqrt is not defined for small field");let e=t-er,r=0;for(;e%Tc===dr;)e/=Tc,r++;let n=Tc,i=uu(t);for(;xI(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return _I;let o=i.pow(n,e),s=(e+er)/Tc;return function(a,u){if(a.is0(u))return u;if(xI(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 mL(t){return t%vI===EI?_I:t%AI===SI?yL:t%TI===pL?gL(t):II(t)}var wL=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qb(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=wL.reduce((n,i)=>(n[i]="function",n),e);return id(t,r),t}function bL(t,e,r){if(r<dr)throw new Error("invalid exponent, negatives unsupported");if(r===dr)return t.ONE;if(r===er)return e;let n=t.ONE,i=e;for(;r>dr;)r&er&&(n=t.mul(n,i)),i=t.sqr(i),r>>=er;return n}function Xp(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 xI(t,e){let r=(t.ORDER-er)/Tc,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 xL(t,e){e!==void 0&&Xn(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Hb=class{ORDER;BITS;BYTES;isLE;ZERO=dr;ONE=er;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=dr)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}=xL(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 Ln(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return dr<=e&&e<this.ORDER}is0(e){return e===dr}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&er)===er}neg(e){return Ln(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Ln(e*e,this.ORDER)}add(e,r){return Ln(e+r,this.ORDER)}sub(e,r){return Ln(e-r,this.ORDER)}mul(e,r){return Ln(e*r,this.ORDER)}pow(e,r){return bL(this,e,r)}div(e,r){return Ln(e*bI(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 bI(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=mL(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?eg(e,this.BYTES):ql(e,this.BYTES)}fromBytes(e,r=!1){_e(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?Q0(e):Lo(e);if(c&&(a=Ln(a,s)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Xp(this,e)}cmov(e,r,n){return n?r:e}};function uu(t,e={}){return new Hb(t,e)}function BI(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 Fb(t){let e=BI(t);return e+Math.ceil(e/2)}function Zp(t,e,r=!1){_e(t);let n=t.length,i=BI(e),o=Fb(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?Q0(t):Lo(t),c=Ln(s,e-er)+er;return r?eg(c,i):ql(c,i)}var du=BigInt(0),_c=BigInt(1);function Ef(t,e){let r=e.negate();return t?r:e}function zb(t,e){let r=Xp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function DI(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function jb(t,e){DI(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=nd(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function RI(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+=_c);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 Wb=new WeakMap,kI=new WeakMap;function Gb(t){return kI.get(t)||1}function UI(t){if(t!==du)throw new Error("invalid wNAF")}var Qp=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>du;)r&_c&&(n=n.add(i)),i=i.double(),r>>=_c;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=jb(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=jb(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=RI(n,c,s);n=a,d?o=o.add(Ef(h,r[p])):i=i.add(Ef(f,r[u]))}return UI(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=jb(e,this.bits);for(let s=0;s<o.windows&&n!==du;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=RI(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return UI(n),i}getPrecomputes(e,r,n){let i=Wb.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Wb.set(r,i))),i}cached(e,r,n){let i=Gb(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Gb(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){DI(r,this.bits),kI.set(e,r),Wb.delete(e)}hasCache(e){return Gb(e)!==1}};function NI(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>du||n>du;)r&_c&&(o=o.add(i)),n&_c&&(s=s.add(i)),i=i.double(),r>>=_c,n>>=_c;return{p1:o,p2:s}}function OI(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return qb(e),e}else return uu(t,{isLE:r})}function CI(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>du))throw new Error(`CURVE.${a} must be positive bigint`)}let i=OI(e.p,r.Fp,n),o=OI(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 ey(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var ty=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if($l(e),_e(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),Ps(i)}update(e){return da(this),this.iHash.update(e),this}digestInto(e){da(this),_e(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash: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()}},Yb=(t,e,r)=>new ty(t,e).update(r).digest();Yb.create=(t,e)=>new ty(t,e);var LI=(t,e)=>(t+(t>=0?e:-e)/PI)/e;function EL(t,e,r){let[[n,i],[o,s]]=e,c=LI(s*t,r),a=LI(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<po,h=d<po;f&&(u=-u),h&&(d=-d);let p=nd(Math.ceil(tg(r)/2))+fu;if(u<po||u>=p||d<po||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Xb(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Jb(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return td(r.lowS,"lowS"),td(r.prehash,"prehash"),r.format!==void 0&&Xb(r.format),r}var Zb=class extends Error{constructor(e=""){super(e)}},hs={Err:Zb,_tlv:{encode:(t,e)=>{let{Err:r}=hs;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=rd(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?rd(i.length/2|128):"";return rd(t)+o+i+e},decode(t,e){let{Err:r}=hs,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}=hs;if(t<po)throw new e("integer: negative integers are not allowed");let r=rd(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}=hs;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 Lo(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=hs,i=_e(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}=hs,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},po=BigInt(0),fu=BigInt(1),PI=BigInt(2),ry=BigInt(3),vL=BigInt(4);function MI(t,e={}){let r=CI("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;id(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=$I(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:E,y:U}=_.toAffine(),L=n.toBytes(E);if(td(D,"isCompressed"),D){d();let N=!n.isOdd(U);return pr(KI(N),L)}else return pr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){_e(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,E=G.length,U=G[0],L=G.subarray(1);if(E===_&&(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=${_} 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 x(G,_){let D=n.sqr(_),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,ry),vL),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 EL(G,a.basises,i.ORDER)}let M=rg((G,_)=>{let{X:D,Y:E,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:E};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(E,_),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=rg(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(!x(_,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,E,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=Ef(E,_),D=Ef(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,E){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",E),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:E}=_||{};if(!_||!n.isValid(D)||!n.isValid(E))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(E)?$.ZERO:new $(D,E,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(_e(_,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(ry),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:E,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(E,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,E=n.mul(D,ry),{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(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(_,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:E,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,ry),W=n.mul(D,L),Y=n.mul(E,N),X=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,X),ee=n.sub(ee,ce),ce=n.add(E,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,X),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,X),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),X=n.mul(J,X),ee=n.mul(z,ee),Y=n.add(Y,X),X=n.sub(W,X),X=n.mul(J,X),ee=n.add(ee,X),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 E,U,L=N=>Q.cached(this,N,R=>zb($,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),E=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);E=N,U=R}return zb($,[E,U])[0]}multiplyUnsafe(_){let{endo:D}=e,E=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===po||E.is0())return $.ZERO;if(_===fu)return E;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=NI($,E,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(E,_)}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===fu?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===fu?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return td(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Ms(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let Z=i.BITS,Q=new Qp($,e.endo?Math.ceil(Z/2):Z);return $.BASE.precompute(8),$}function KI(t){return Uint8Array.of(t?2:3)}function $I(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function SL(t,e={}){let{Fn:r}=t,n=e.randomBytes||$s,i=Object.assign($I(t.Fp,r),{seed:Fb(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 Zp(_e(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(!ed(p)||"_lengths"in r&&r._lengths||g===y)return;let S=_e(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=ey(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function HI(t,e,r={}){$l(e),id(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||$s,i=r.hmac||((D,E)=>Yb(e,D,E)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=SL(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*PI<o.ORDER;function x(D){let E=c>>fu;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 I(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,E){Xb(E);let U=p.signature,L=E==="compact"?U:E==="recovered"?U+1:void 0;return _e(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(I(),![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}=hs.toSig(_e(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(Ks(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(pr(KI((N&1)===0),C)),V=s.inv(R),J=M(_e(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(Xb(E),E==="der")return Ks(hs.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return E==="recovered"?(I(),pr(Uint8Array.of(this.assertRecovery()),N,R)):pr(N,R)}toHex(E){return Ms(this.toBytes(E))}}let T=r.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");let U=Lo(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=nd(a);function j(D){return n1("num < 2^"+a,D,po,q),s.toBytes(D)}function $(D,E){return _e(D,void 0,"message"),E?_e(e(D),void 0,"prehashed message"):D}function Z(D,E,U){let{lowS:L,prehash:N,extraEntropy:R}=Jb(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(_e(Y,void 0,"extraEntropy"))}let J=pr(...V),z=C;function W(Y){let X=T(Y);if(!s.isValidNot0(X))return;let ue=s.inv(X),ee=t.BASE.multiply(X).toAffine(),ce=s.create(ee.x);if(ce===po)return;let Oe=s.create(ue*s.create(z+ce*P));if(Oe===po)return;let Me=(ee.x===ce?0:2)|Number(ee.y&fu),Je=Oe;return L&&x(Oe)&&(Je=s.neg(Oe),Me^=1),new O(ce,Je,y?void 0:Me)}return{seed:J,k2sig:W}}function Q(D,E,U={}){let{seed:L,k2sig:N}=Z(D,E,U);return i1(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,E,U,L={}){let{lowS:N,prehash:R,format:C}=Jb(L,g);if(U=_e(U,void 0,"publicKey"),E=$(E,R),!ed(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),X=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(X).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,E,U={}){let{prehash:L}=Jb(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:_,Signature:O,hash:e})}var oy={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},AL={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},TL=BigInt(0),Qb=BigInt(2);function _L(t){let e=oy.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=qr(d,r,e)*d%e,h=qr(f,r,e)*d%e,p=qr(h,Qb,e)*u%e,g=qr(p,i,e)*p%e,y=qr(g,o,e)*g%e,x=qr(y,c,e)*y%e,S=qr(x,a,e)*x%e,I=qr(S,c,e)*y%e,A=qr(I,r,e)*d%e,O=qr(A,s,e)*g%e,T=qr(O,n,e)*u%e,M=qr(T,Qb,e);if(!ny.eql(ny.sqr(M),t))throw new Error("Cannot find square root");return M}var ny=uu(oy.p,{sqrt:_L}),Ic=MI(oy,{Fp:ny,endo:AL}),pn=HI(Ic,Jp),VI={};function iy(t,...e){let r=VI[t];if(r===void 0){let n=Jp(r1(t));r=pr(n,n),VI[t]=r}return Jp(pr(r,...e))}var tx=t=>t.toBytes(!0).slice(1),rx=t=>t%Qb===TL;function ex(t){let{Fn:e,BASE:r}=Ic,n=e.fromBytes(t),i=r.multiply(n);return{scalar:rx(i.y)?n:e.neg(n),bytes:tx(i)}}function FI(t){let e=ny;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);rx(i)||(i=e.neg(i));let o=Ic.fromAffine({x:t,y:i});return o.assertValidity(),o}var vf=Lo;function jI(...t){return Ic.Fn.create(vf(iy("BIP0340/challenge",...t)))}function qI(t){return ex(t).bytes}function IL(t,e,r=$s(32)){let{Fn:n}=Ic,i=_e(t,void 0,"message"),{bytes:o,scalar:s}=ex(e),c=_e(r,32,"auxRand"),a=n.toBytes(s^vf(iy("BIP0340/aux",c))),u=iy("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=ex(u),h=jI(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!WI(p,i,o))throw new Error("sign: Invalid signature produced");return p}function WI(t,e,r){let{Fp:n,Fn:i,BASE:o}=Ic,s=_e(t,64,"signature"),c=_e(e,void 0,"message"),a=_e(r,32,"publicKey");try{let u=FI(vf(a)),d=vf(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=vf(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=jI(i.toBytes(d),tx(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!rx(y)||g!==d)}catch{return!1}}var sy=(()=>{let r=(n=$s(48))=>Zp(n,oy.n);return{keygen:ey(r,qI),getPublicKey:qI,sign:IL,verify:WI,Point:Ic,utils:{randomSecretKey:r,taggedHash:iy,lift_x:FI,pointToBytes:tx},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function BL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function zI(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 nx(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function YI(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function ix(t){if(!Array.isArray(t))throw new Error("array expected")}function JI(t,e){if(!zI(!0,e))throw new Error(`${t}: array of strings expected`)}function RL(t,e){if(!zI(!1,e))throw new Error(`${t}: array of numbers expected`)}function UL(...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 OL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;JI("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(ix(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=>(ix(i),i.map(o=>{nx("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function DL(t=""){return nx("join",t),{encode:e=>(JI("join.decode",e),e.join(t)),decode:e=>(nx("join.decode",e),e.split(t))}}function GI(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(ix(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(YI(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 kL(t){YI(t);let e=2**8;return{encode:r=>{if(!BL(r))throw new Error("radix.encode input should be Uint8Array");return GI(Array.from(r),e,t)},decode:r=>(RL("radix.decode",r),Uint8Array.from(GI(r,t,e)))}}var NL=t=>UL(kL(58),OL(t),DL("")),lu=NL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var XI=new Uint8Array([231,1]),ft=class t{#e;#t={prefix:XI,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Ir(e);if(!r||r.length!==33)throw new ks("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!pn.utils.isValidPublicKey(r))throw new ks("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 pn.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 ks("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 lu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(XI);return r.push(...e),"z"+lu.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return pn.verify(e,r,this.compressed);if(n.scheme==="schnorr")return sy.verify(e,r,this.x);throw new ks(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return fa(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 ZI=new Uint8Array([129,38]),CL=Pt(ke(ZI)),Fr=class t{#e;#t;#r;constructor(e){let r=e instanceof Uint8Array,n=typeof e=="bigint";if(!r&&!n)throw new Gn("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<pn.Point.Fn.ORDER&&(this.#e=t.toBytes(e),this.#t=e),!this.#e||this.#e.length!==32)throw new Gn("Invalid bytes: must be a valid 32-byte secret key","CONSTRUCTOR_ERROR");if(!this.#t||this.#t<1n||this.#t>=pn.Point.Fn.ORDER)throw new Gn("Invalid seed: must be valid bigint","CONSTRUCTOR_ERROR");this.#r=this.encode()}destroy(){this.#e&&this.#e.fill(0),this.#t=void 0,this.#r=""}get bytes(){return new Uint8Array(this.#e)}get seed(){return BigInt(this.#t)}get hex(){return Pt(this.bytes)}get multibase(){return this.#r}encode(){let e=Array.from(this.bytes),r=Array.from(ZI);return r.push(...e),"z"+lu.encode(Uint8Array.from(r))}equals(e){return fa(this.bytes,e.bytes)}computePublicKey(){return new ft(pn.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 pn.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return pn.sign(e,this.bytes);if(r.scheme==="schnorr")return sy.sign(e,this.bytes);throw new Gn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=lu.decode(e.slice(1));if(r.length!==34)throw new Gn("Invalid argument: must be 34 byte secretKeyMultibase","DECODE_MULTIBASE_ERROR");let n=r.slice(0,2);if(Pt(ke(n))!==CL)throw new Gn(`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(!pn.utils.isValidSecretKey(r))throw new Gn("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=Br(32);while(!pn.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var yo=class t{#e;#t;constructor(e={}){if(!e.publicKey&&!e.secretKey)throw new xn("Argument missing: must at least provide a publicKey","CONSTRUCTOR_ERROR");if(e.secretKey instanceof Uint8Array?this.#e=new Fr(e.secretKey):e.secretKey instanceof Fr&&(this.#e=e.secretKey),e.publicKey instanceof ft?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new ft(e.publicKey):this.#t=this.#e.computePublicKey(),this.#e&&e.publicKey){let r=this.#e.computePublicKey();if(!this.#t.equals(r))throw new xn("Public key does not match secret key","CONSTRUCTOR_ERROR")}}get secretKey(){if(!this.#e)throw new xn("Secret key not available","SECRET_KEY_ERROR");if(!this.#e.isValid())throw new xn("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 xn("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 xn("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:Fr.fromJSON(e.secretKey),publicKey:ft.fromJSON(e.publicKey)})}static fromSecret(e){let r=typeof e=="string"?Ir(e):e;if(r.length!==32)throw new xn("Invalid arg: must be 32 byte secret key","FROM_SECRET_KEY_ERROR");let n=new Fr(r),i=n.computePublicKey();return new t({secretKey:n,publicKey:i})}static fromBigInt(e){let r=Fr.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=Fr.random(),r=new Fr(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}};l();l();l();l();var QI=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],Bc="Multikey",Rc="zQ3s",tr="did:btcr2:_",LL="",eB=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function tB(t){if(!tt.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===Bc&&typeof r=="string"&&r.startsWith(Rc)}var cy=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==Bc)throw new Ve(`Invalid verification method: type must be "${Bc}"`,qe,{id:e,type:r});if(typeof i!="string"||!i.startsWith(Rc))throw new Ve(`Invalid verification method: publicKeyMultibase must start with "${Rc}"`,qe,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},jr=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 Ve("DID Document must have an id",qe,e);let r=e.id.includes("k1")?tn.KEY:tn.EXTERNAL,n=e.id===tr,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new Ve(`Invalid id: ${i}`,qe,e);if(!t.isValidVerificationMethods(o))throw new Ve("Invalid verificationMethod: "+o,qe,e);if(!t.isValidServices(s))throw new Ve("Invalid service: "+s,qe,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===tn.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 cy({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 Ve('Invalid "@context"',qe,e);if(!this.isValidId(e?.id))throw new Ve('Invalid "id"',qe,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new Ve('Invalid "verificationMethod"',qe,e);if(!this.isValidServices(e?.service))throw new Ve('Invalid "service"',qe,e);if(!this.isValidVerificationRelationships(e))throw new Ve("Invalid verification relationships",qe,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:QI.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return fr.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(tB)}static isValidServices(e){return Array.isArray(e)&&e.every(b_)}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"||tt.isDidVerificationMethod(c))})}static validate(e){return e.id===tr?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==tr)throw new Ve("Invalid GenesisDocument ID",qe,this);if(!this.verificationMethod.every(e=>e.id.includes(tr)&&e.controller===tr))throw new Ve("Invalid GenesisDocument verificationMethod",qe,this);if(!this.service.every(e=>e.id.includes(tr)))throw new Ve("Invalid GenesisDocument service",qe,this);if(!t.isValidVerificationRelationships(this))throw new Ve("Invalid GenesisDocument assertionMethod",qe,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new Ve("Cannot convert a key identifier to an intermediate document",qe,this);return new hu(this)}},hu=class t extends jr{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(tr,e),n=JSON.parse(r);return new jr(n)}static fromDidDocument(e){let r=Ls.cloneReplace(e,eB,tr);return new t(r)}static create(e,r,n){return new t({id:tr,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ft(e),i=tr,o=Li(n.compressed,Co(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 No(ir(e))}};var rB="did:btcr2:",fr=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in tn))throw new ut('Expected "idType" to be "KEY" or "EXTERNAL"',pt,{idType:n});if(i!==1)throw new ut('Expected "version" to be 1',pt,{version:i});if(typeof o!="string")throw new ut('Expected "network" to be a known network name',pt,{network:o});let s=ca[o];if(typeof s!="number")throw new ut('Invalid "network" name',pt,{network:o});if(n==="KEY")try{new ft(e)}catch{throw new ut('Expected "genesisBytes" to be a valid compressed secp256k1 public key',pt,{genesisBytes:e})}else if(e.length!==32)throw new ut('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`${rB}${_s.encodeFromBytes(c,u)}`}static decode(e){let r=e.split(":");if(r.length!==3)throw new ut(`Invalid did: ${e}`,pt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new ut(`Invalid did: ${e}`,pt,{identifier:e});if(i!=="btcr2")throw new ut(`Invalid did method: ${i}`,_l,{identifier:e});if(!o)throw new ut(`Invalid method-specific id: ${e}`,pt,{identifier:e});if(o!==o.toLowerCase())throw new ut(`Invalid method-specific id (must be lowercase): ${e}`,pt,{identifier:e});let s,c;try{({prefix:s,bytes:c}=_s.decodeToBytes(o))}catch(g){let y=g instanceof Error?g.message:String(g);throw new ut(`Invalid method-specific id (Bech32m decoding failed: ${y}): ${e}`,pt,{identifier:e,reason:y})}if(!["x","k"].includes(s))throw new ut(`Invalid hrp: ${s}`,pt,{identifier:e});if(!c||c.length<1)throw new ut(`Failed to decode id: ${o}`,pt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new ut(`Invalid btcr2_version (expected 0): ${u}`,pt,{identifier:e});let d=1,f=c[0]&15,h=ca[f];if(typeof h!="string"){let g=f>=12?"custom network not supported":"reserved";throw new ut(`Invalid network (${g}): ${f}`,pt,{identifier:e})}let p=c.slice(1);if(a==="KEY")try{new ft(p)}catch{throw new ut(`Invalid genesisBytes: ${p}`,pt,{identifier:e})}else if(p.length!==32)throw new ut(`Invalid genesisBytes: ${p}`,pt,{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,I={})=>(n.push({name:x,ok:!1,detail:S}),{did:e,valid:!1,...I,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 "${rB}" 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}=_s.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"?tn.KEY:tn.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=ca[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===tn.KEY){try{new ft(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(!So(x,g))return o("genesisBytesMatch",`The supplied genesis bytes ${ve.encode(x)} do not equal the genesis bytes of the identifier ${ve.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===tn.KEY)return o("genesisDocument","A KEY identifier has no genesis document.",{idType:d,network:p});let S=x.id;if(S!==tr)return o("genesisDocument",`The genesis document id must be "${tr}", got ${JSON.stringify(S)}.`,{idType:d,network:p});try{hu.fromJSON(x)}catch(A){return o("genesisDocument",`Invalid genesis document: ${A instanceof Error?A.message:String(A)}`,{idType:d,network:p})}let I=zn(x);if(!So(I,g))return o("genesisDocument",`The genesis document hash ${ve.encode(I)} does not equal the genesis bytes ${ve.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=yo.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 ut(`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 ft(n)}static isValid(e){try{return this.decode(e),!0}catch{return!1}}};var rr=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new be("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!tt.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 zt("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=fr.decode(e),o=Co(i.network),s=i.genesisBytes,c=`${e}#initial${r.toUpperCase()}`,u=`bitcoin:${r==="p2tr"?Rs(s.slice(1,33),void 0,o).address:r==="p2wpkh"?Bs(s,o).address:Li(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new zt("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=Li(r,n).address,s=Bs(r,n).address,c=Rs(r.slice(1,33),void 0,n).address;if(!o||!s||!c)throw new Dt("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 zt("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 PL=/^6a20([0-9a-f]{64})$/i;function ox(t){if(!t)return null;let e=PL.exec(t.trim());return e?e[1].toLowerCase():null}var sx=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(),o=new Map;for(let s of e){n.set(s,[]);let c=rr.parseBitcoinAddress(s.serviceEndpoint),a=await r.rest.address.getTxs(c);if(!(!a||!a.length))for(let u of a){let d=u.status;if(d.confirmed!==!0)continue;let f=u.vout.slice(-1)[0];if(!f)continue;let h=ox(f.scriptpubkey);if(!h||!await t.spendsFromAddress(u,c,r))continue;let p=i-d.block_height+1,g=await t.mediantime(d.block_hash,r,o);n.get(s)?.push({tx:u,signalBytes:h,blockMetadata:{confirmations:p,height:d.block_height,time:d.block_time,mediantime:g}})}}return n}static async mediantime(e,r,n){let i=n.get(e);if(i!==void 0)return i;let o=await r.rest.block.get({blockhash:e}),s=o?.mediantime;if(typeof s!="number"||!Number.isFinite(s))throw new fe(`Block ${e} has no mediantime in the block record of the Bitcoin REST backend.`,Il,{blockhash:e,block:o});return n.set(e,s),s}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 fe("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=new Map(e.map(u=>[rr.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===V0)continue;let d=u.vout.slice(-1)[0];if(!d)continue;let f=ox(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]===H0||!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,mediantime:a.mediantime,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();var Uc=Object.freeze(["https://w3id.org/json-ld-patch/v1","https://w3id.org/zcap/v1","https://w3id.org/security/data-integrity/v2","https://btcr2.dev/context/v1"]);function ay(t,e=Uc){return Array.isArray(t)&&t.length===e.length&&t.every((r,n)=>r===e[n])}var cx=Object.freeze({op:"add",path:"/deactivated",value:!0});l();l();l();l();l();l();var Lre=new Uint8Array(0);function nB(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 ML(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,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<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 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(x+(I-q)),$=x;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 KL=ML,$L=KL,iB=$L;var ax=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")}},ux=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 oB(this,e)}},dx=class{decoders;constructor(e){this.decoders=e}or(e){return oB(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 oB(t,e){return new dx({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var fx=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 ax(e,r,n),this.decoder=new ux(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function HL({name:t,prefix:e,encode:r,decode:n}){return new fx(t,e,r,n)}function lx({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=iB(r,t);return HL({prefix:e,name:t,encode:n,decode:o=>nB(i(o))})}var Sf=lx({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Wre=lx({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();function sB(t){return t===void 0?[]:Array.isArray(t)?t:[t]}var pu=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 bn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",ko,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new bn("Domain mismatch: proof.domain !== config.domain",ko,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new bn("Challenge mismatch options and challenge passed",ko,{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 bn("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Pi,s);if(r&&r!==c.proofPurpose)throw new bn("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",Pi,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new bn("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){let u=sB(i),d=sB(c.domain);if(u.length!==d.length)throw new bn("Domain mismatch: expectedDomain length does not match proof.domain length",Pi,{proof:c,expectedDomain:i});if(!u.every(f=>d.includes(f))||!d.every(f=>u.includes(f)))throw new bn("Domain mismatch: expectedDomain and proof.domain do not match",Pi,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var yu=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new pu(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=Sf.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=Sf.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 be("Type mismatch: config.type !== this.type",Pi,{config:r,suite:this.#e()});if(r.cryptosuite!==this.cryptosuite)throw new be("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Pi,{config:r,suite:this.#e()});return ir(e)}generateHash(e,r){let n=ke(Ss(e)),i=ke(Ss(r)),o=ht(n,i);return ke(o)}proofConfiguration(e){if(e.type!==this.type)throw new Do("Type mismatch: config.type !== this.type",ko,{config:e,suite:this.#e()});if(e.cryptosuite!==this.cryptosuite)throw new Do("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",ko,{config:e,suite:this.#e()});if(e.created&&!Mi.isValidXsdDateTime(e.created))throw new Do('Invalid config: "created" must be a valid XMLSchema DateTime string',ko,e);return ir(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new Do("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Dv,{config:r,suite:this.#e()});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new Do("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Pi,{config:n,suite:this.#e()});return this.multikey.verify(r,e)}};l();l();l();var go=class t{static type="Multikey";id;controller;#e;#t;constructor({id:e,controller:r,keyPair:n,externalSigner:i}){if(!n)throw new En('Argument missing: "keyPair" required',"CONSTRUCTOR_ERROR");if(!n.publicKey)throw new En('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 En("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 En("Cannot get: no secretKey","PRIVATE_KEY_ERROR")}}toCryptosuite(){return new yu(this)}sign(e){if(this.#t)return this.#t.sign(e,"bip340");if(!this.signer)throw new En("Cannot sign: no secretKey","SIGN_ERROR");return Or.sign(e,this.secretKey.bytes,Br(32))}verify(e,r){return Or.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 Fr(n),o=i.computePublicKey(),s=new yo({publicKey:o,secretKey:i});return new t({id:e,controller:r,keyPair:s})}static fromSigner(e,r,n){let i=new ft(n.publicKey),o=new yo({publicKey:i});return new t({id:e,controller:r,keyPair:o,externalSigner:n})}static fromPublicKey({id:e,controller:r,publicKeyBytes:n}){let i=new ft(n),o=new yo({publicKey:i});return new t({id:e,controller:r,keyPair:o})}static fromVerificationMethod({id:e,controller:r,publicKeyMultibase:n}){if(!n)throw new En("Invalid publicKeyMultibase: cannot be undefined",Bl,{publicKeyMultibase:n});let i=Sf.decode(n);if(i.length!==35)throw new En(`Invalid publicKeyMultibase length: ${i.length}`,Bl,{publicKeyMultibase:n});if(i[0]!==231||i[1]!==1)throw new En(`Invalid publicKeyMultibase prefix: expected secp256k1 multicodec [0xe7, 0x01], got [0x${i[0]?.toString(16)??"??"}, 0x${i[1]?.toString(16)??"??"}]`,Bl,{publicKeyMultibase:n});let o=i.slice(2),s=new yo({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();function Sr(t){return t instanceof Dt?{type:t.type,message:t.message}:t instanceof Error?{type:t.name,message:t.message}:{type:"unknown",message:String(t)}}var cB=6;function Af(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function VL(t){return Af(t)&&Object.values(t).every(e=>typeof e=="string")}function qL(t){return Af(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&Number.isInteger(t.targetVersionId)&&t.targetVersionId>=2&&Af(t.proof):!1}function FL(t){return Af(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes)&&t.hashes.every(e=>typeof e=="string")&&(t.nonce===void 0||typeof t.nonce=="string")&&(t.updateId===void 0||typeof t.updateId=="string"):!1}function jL(t){if(t===void 0)return cB;if(typeof t=="number"&&Number.isInteger(t)&&t>=1)return t;throw new fe(`Invalid resolution option minConf: expected a positive integer (minimum 1), got ${hx(t)}.`,zu,{minConf:t})}function hx(t){return typeof t=="string"?JSON.stringify(t):String(t)}var WL=/^-?[0-9]+$/;function GL(t){if(t!==void 0){if(typeof t=="string"&&WL.test(t)&&Number.isSafeInteger(Number(t)))return Number(t);throw new fe(`Invalid resolution option versionId: expected an ASCII string of an integer, got ${hx(t)}.`,zu,{versionId:t})}}var zL=/^-?\d{4,}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/,YL=/(Z|[+-]\d{2}:\d{2})$/;function JL(t){if(t!==void 0){if(typeof t=="string"&&zL.test(t)&&Mi.isValidXsdDateTime(t)){let e=Date.parse(t);if(Number.isFinite(e))return e}throw new fe(`Invalid resolution option versionTime: expected an XML Datetime in UTC without a fraction (for example "2026-07-01T00:00:00Z"), got ${hx(t)}.`,zu,{versionTime:t})}}var mo=class t{#e;#t;#r;#i;#o;#n;#c=null;#l=new Map;#h=new Set;#d=new Set;#a=[];#p=null;#s=1;#y=[];#g=0;#f;#m=0;#u;#w=0;#b;constructor(e,r,n,i){if(this.#e=e,this.#o=r,this.#n=n,i?.versionId!==void 0&&i?.versionTime!==void 0)throw new fe("Invalid resolution options: versionId and versionTime are mutually exclusive. Pass one of them.",zu,{versionId:i.versionId,versionTime:i.versionTime});this.#t=GL(i?.versionId),this.#r=JL(i?.versionTime);let o=i?.maxDiscoveryRounds;this.#u=typeof o=="number"&&o>0?o:1/0,this.#b=jL(i?.minConf),i?.genesisDocument&&(this.#c=i.genesisDocument),this.#i=n?"BeaconDiscovery":"GenesisDocument"}static deterministic(e){let r=e.genesisBytes,n=fr.encode(r,e),{multibase:i}=new ft(r),o=rr.generateBeaconServices({id:n,publicKey:r,network:Co(e.network),beaconType:"SingletonBeacon"});return new jr({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=zn(r);if(!So(e.genesisBytes,n))throw new fe("Initial document mismatch: genesisBytes !== genesisDocumentHash",pt,{genesisBytes:en(e.genesisBytes,"hex"),genesisDocumentHash:en(n,"hex")});let i=fr.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(tr,i));return new jr(o)}static sidecarData(e={}){let r=new Map;if(e.updates?.length)for(let o of e.updates)r.set(Yn(o,{encoding:"hex"}),o);let n=new Map;if(e.casUpdates?.length)for(let o of e.casUpdates)n.set(Yn(o,{encoding:"hex"}),o);let i=new Map;if(e.smtProofs?.length)for(let o of e.smtProofs)i.set(en(ia(o.id,"base64urlnopad"),"hex"),o);return{updateMap:r,casMap:n,smtMap:i}}static confirmDuplicate(e,r){if(!Number.isInteger(e.targetVersionId)||e.targetVersionId<2)throw new fe("Invalid duplicate: targetVersionId must be an integer >= 2",le,{targetVersionId:e.targetVersionId});let{proof:n,...i}=e,o=zn(i),s=r[e.targetVersionId-2];if(s===void 0)throw new fe("Invalid duplicate: no applied update in history for targetVersionId",Rl,{targetVersionId:e.targetVersionId,historyLength:r.length});if(!So(s,o))throw new fe("Invalid duplicate: unsigned update hash does not match historical hash",Rl,{unsignedUpdateHash:en(o,"hex"),historicalHash:en(s,"hex")})}static decodeUpdateHash(e,r){if(typeof e=="string")try{return ia(e,"base64urlnopad")}catch(n){throw new fe(`Invalid update: ${r} does not decode as base64url: ${Sr(n).message}`,le,{[r]:e,cause:Sr(n)})}throw new fe(`Invalid update: ${r} is not a string`,le,{[r]:e})}static proofInstant(e,r){let n=e[r];if(n!==void 0){if(typeof n=="string"&&YL.test(n)&&Mi.isValidXsdDateTime(n)){let i=Date.parse(n);if(Number.isFinite(i))return i}throw new fe(`Invalid update: proof.${r} is not an XML Datetime with a timezone`,le,{[r]:n})}}static checkProofWindow(e,r){let n=t.proofInstant(e,"created"),i=t.proofInstant(e,"expires");if(n!==void 0&&n>r.time*1e3)throw new fe("Invalid update: proof.created is after the header time of the block that contains the Beacon Signal",le,{created:e.created,blockTime:r.time});if(i!==void 0&&i<r.mediantime*1e3)throw new fe("Invalid update: proof.expires is before the mediantime of the block that contains the Beacon Signal",le,{expires:e.expires,mediantime:r.mediantime});if(n!==void 0&&i!==void 0&&i<n)throw new fe("Invalid update: proof.expires is before proof.created",le,{created:e.created,expires:e.expires})}static applyUpdate(e,r,n){let i=zn(e),o=t.decodeUpdateHash(r.sourceHash,"sourceHash");if(!So(o,i))throw new fe("Hash mismatch: update.sourceHash !== currentDocumentHash",le,{sourceHash:r.sourceHash,currentDocumentHash:en(i,"hex")});if(!ay(r["@context"]))throw new fe("Invalid update: @context is not the array the specification pins for a BTCR2 Update",le,{context:r["@context"],expected:[...Uc]});if(!ay(r.proof?.["@context"],r["@context"]))throw new fe("Invalid update: proof @context does not equal the update @context",le,{proofContext:r.proof?.["@context"],context:r["@context"]});let s=r.proof,c=[["type","DataIntegrityProof"],["cryptosuite","bip340-jcs-2025"],["proofPurpose","capabilityInvocation"],["capabilityAction","Write"],["capability",`urn:zcap:root:${encodeURIComponent(e.id)}`]];for(let[y,x]of c){let S=s[y];if(S!==x)throw new fe(`Invalid update: proof.${y} must equal "${x}"`,le,{field:y,expected:x,actual:S})}let a=s.verificationMethod,u=tt.capabilityInvocationEntry(e,a);if(u===void 0)throw new fe("Invalid update: verificationMethod is not authorized for capabilityInvocation",le,{verificationMethodId:a,capabilityInvocation:e.capabilityInvocation});let d=tt.verificationMethodOfEntry(e,u);if(d===void 0)throw new fe("Invalid update: verificationMethod is not found in the verificationMethod of the current document",le,{verificationMethodId:a});t.checkProofWindow(s,n);let f;try{let y=go.fromVerificationMethod({...d,id:tt.absoluteDidUrl(d.id,e.id)??d.id});f=new pu(new yu(y)).verifyProof(ir(r),"capabilityInvocation").verified}catch(y){throw new fe(`Invalid update: proof verification failed: ${Sr(y).message}`,le,{verificationMethodId:a,cause:Sr(y)})}if(!f)throw new fe("Invalid update: proof not verified",le,{verificationMethodId:a});let h;try{h=sa.apply(e,r.patch,{strict:!0})}catch(y){throw new fe(`Invalid update: ${Sr(y).message}`,le,{cause:Sr(y)})}if(h?.id!==e.id)throw new fe(`Invalid update: the patch changes the document id (from "${e.id}" to "${String(h?.id)}")`,le,{sourceId:e.id,targetId:h?.id});try{jr.validate(h)}catch(y){throw new fe(`Invalid update: the patched document does not conform to DID Core: ${Sr(y).message}`,le,{cause:Sr(y)})}let p=zn(h),g=t.decodeUpdateHash(r.targetHash,"targetHash");if(!So(g,p))throw new fe("Invalid update: update.targetHash !== updatedDocumentHash",le,{updateTargetHash:g,updatedDocumentHash:p});return h}resolve(){for(;;)switch(this.#i){case"GenesisDocument":{if(this.#c){this.#n=t.external(this.#e,this.#c),this.#c=null,this.#i="BeaconDiscovery";continue}return{status:"action-required",needs:[{kind:"NeedGenesisDocument",genesisHash:en(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=rr.getBeaconServices(this.#n).filter(n=>{let i=rr.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=rr.parseBitcoinAddress(n.serviceEndpoint);this.#d.add(i)}return{status:"action-required",needs:[{kind:"NeedBeaconSignals",beaconServices:r}]}}this.#i="BeaconProcess";continue}case"BeaconProcess":{let e=[];for(let[r,n]of this.#l){let i=rr.parseBitcoinAddress(r.serviceEndpoint);if(this.#h.has(i)||!n.length)continue;let o=this.#E(n);if(!o.length)continue;let c=Vs.establish(r,this.#n.id).processSignals(o,this.#o);c.needs.length>0?e.push(...c.needs):(this.#a.push(...c.updates.map(([a,u])=>[a,u,i])),this.#h.add(i))}if(e.length>0)return{status:"action-required",needs:e};this.#i="ProcessUpdate";continue}case"ProcessUpdate":{let e=this.#n;if(this.#t!==void 0&&this.#s===this.#t){this.#i="Complete";continue}if(this.#a.length===0||e.deactivated){if(this.#t!==void 0)throw new fe(`Version ${this.#t} of the DID does not exist: the history `+(e.deactivated?`ends with the deactivation at version ${this.#s}.`:`ends at version ${this.#s}.`),Ov,{versionId:this.#t,currentVersionId:this.#s});this.#i="Complete";continue}this.#a.sort(([c,a],[u,d])=>c.targetVersionId-u.targetVersionId||a.height-d.height);let[r,n,i]=this.#a.shift();if(!rr.getBeaconServices(e).some(c=>rr.parseBitcoinAddress(c.serviceEndpoint)===i))continue;if(r.targetVersionId<=this.#s){t.confirmDuplicate(r,this.#y);continue}if(this.#r!==void 0&&n.mediantime*1e3>this.#r){this.#i="Complete";continue}if(r.targetVersionId!==this.#s+1)throw new fe("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",Rl,{targetVersionId:r.targetVersionId,currentVersionId:this.#s+1});this.#n=t.applyUpdate(e,r,n);let s=Ls.deleteKeys(r,["proof"]);if(this.#y.push(zn(s)),this.#s++,this.#g=n.confirmations,this.#m=n.height,this.#f=Mi.toISOStringNonFractional(Mi.blocktimeToTimestamp(n.time)),this.#x()){if(++this.#w>this.#u)throw new fe(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,Il,{maxDiscoveryRounds:this.#u,discoveryRounds:this.#w});this.#i="BeaconDiscovery"}continue}case"Complete":return this.#p??={didDocument:this.#n,metadata:{versionId:`${this.#s}`,confirmations:this.#g,...this.#f!==void 0?{updated:this.#f}:{},deactivated:this.#n.deactivated||!1}},{status:"resolved",result:this.#p}}}#x(){return rr.getBeaconServices(this.#n).some(e=>!this.#d.has(rr.parseBitcoinAddress(e.serviceEndpoint)))}#E(e){let r=[];for(let n of e){let i=n.blockMetadata,o=i?.confirmations;if(!(!Number.isInteger(o)||o<this.#b)){if(!Number.isFinite(i?.height)||!Number.isFinite(i?.time)||!Number.isFinite(i?.mediantime))throw new fe(`Beacon signal ${n.signalBytes} has ${o} confirmations but no valid block height, block time, or block mediantime.`,le,{signalBytes:n.signalBytes,confirmations:o,height:i?.height,time:i?.time,mediantime:i?.mediantime});i.height<this.#m||r.push(n)}}return r}provide(e,r){switch(e.kind){case"NeedGenesisDocument":{if(!Af(r))throw new fe("Provided data for NeedGenesisDocument must be a document object.",le,{kind:e.kind});this.#c=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new fe("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",le,{kind:e.kind});for(let[n,i]of r)this.#l.set(n,i);break}case"NeedCASAnnouncement":{if(!VL(r))throw new fe("Provided data for NeedCASAnnouncement is not a CAS announcement.",le,{kind:e.kind});let n=Yn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new fe(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,kv,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!qL(r))throw new fe("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",le,{kind:e.kind});let n=Yn(r,{encoding:"hex"});if(n!==e.updateHash)throw new fe(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,Ns,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!FL(r))throw new fe("Provided data for NeedSMTProof is not an SMT proof.",Ns,{kind:e.kind});let n;try{n=en(ia(r.id,"base64urlnopad"),"hex")}catch{n=void 0}if(n!==e.smtRootHash)throw new fe(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n??"an id that does not decode"}.`,Ns,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function aB(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new Ve("Cannot derive aggregation communication key: capabilityInvocation is absent",qe,{id:t.id});let r=tt.absoluteDidUrl(e,t.id),n=typeof e=="string"?r===void 0?void 0:t.verificationMethod?.find(i=>tt.absoluteDidUrl(i.id,t.id)===r):e;if(!n)throw new Ve(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,qe,{id:t.id,invocation:e});return go.fromVerificationMethod(n).publicKey}function XL(t,e){try{let r=fr.decode(t);if(r.idType==="KEY")return new ft(r.genesisBytes);if(e?.genesisDocument){let n=mo.external(r,e.genesisDocument);return aB(n)}}catch{}}l();l();l();var Tf=class t{#e={phase:"Construct"};#t;#r;#i;#o;#n;constructor(e){this.#t=e.sourceDocument,this.#r=e.patches,this.#i=e.sourceVersionId,this.#o=e.verificationMethod,this.#n=e.beaconService}static construct(e,r,n){let i={"@context":[...Uc],patch:r,targetHash:"",targetVersionId:n+1,sourceHash:Yn(e)},o;try{o=sa.apply(e,r,{strict:!0})}catch(s){throw new it(`Invalid patch: ${Sr(s).message}`,le,{cause:Sr(s)})}if(o.id!==e.id)throw new it(`Patches must not change the DID document id (source "${e.id}" to target "${o.id}").`,le,{sourceId:e.id,targetId:o.id});try{jr.isValid(o)}catch(s){throw new it("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),le,o)}return i.targetHash=Yn(o),i}static sign(e,r,n,i){if(!e.startsWith("did:btcr2:"))throw new it(`Expected a did:btcr2 identifier for the root capability; got "${e}".`,le,{did:e});let o=n.controller,s=n.id.indexOf("#");if(s<0)throw new it(`Verification method id must contain a fragment (e.g. "${n.id}#initialKey"); got "${n.id}".`,le,{verificationMethodId:n.id});let c=n.id.slice(s),a=go.fromSigner(c,o,i),u=s===0?`${e}${c}`:n.id,d=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&d!==n.publicKeyMultibase)throw new it(`Signing key does not match verification method "${n.id}": the signer's public key differs from the method's published publicKeyMultibase.`,le,{verificationMethodId:n.id,expected:n.publicKeyMultibase,actual:d});let f={"@context":[...Uc],cryptosuite:"bip340-jcs-2025",type:"DataIntegrityProof",verificationMethod:u,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"},p=a.toCryptosuite().toDataIntegrityProof().addProof(r,f),g;try{g=go.fromVerificationMethod({...n,id:u}).toCryptosuite().toDataIntegrityProof().verifyProof(ir(p),"capabilityInvocation").verified}catch(y){throw new it(`Invalid update: the proof does not verify with the public key of "${n.id}": `+Sr(y).message,le,{verificationMethodId:n.id,cause:Sr(y)})}if(!g)throw new it(`Invalid update: the proof does not verify with the public key of "${n.id}".`,le,{verificationMethodId:n.id});return p}static async announce(e,r,n,i,o,s){return Vs.establish(e,r).broadcastSignal(n,i,o,s)}#c(){return t.construct(this.#t,this.#r,this.#i)}advance(){for(;;)switch(this.#e.phase){case"Construct":{let e=this.#c();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.#n.serviceEndpoint.replace("bitcoin:",""),beaconService:this.#n}]};case"Broadcast":return{status:"action-required",needs:[{kind:"NeedBroadcast",beaconService:this.#n,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 it(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,le,{phase:this.#e.phase});if(!r)throw new it("NeedSigningKey requires a Signer.",le);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 it(`Cannot provide NeedFunding: updater phase is ${this.#e.phase}, expected Fund.`,le,{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 it(`NeedFunding proof must have utxoCount >= 1; got ${String(n.utxoCount)}.`,le,{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 it(`Cannot provide NeedBroadcast: updater phase is ${this.#e.phase}, expected Broadcast.`,le,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};l();var px=class{document={};constructor(e){if(!e.id)throw new Ve('Missing required "id" property',qe,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 jr(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};l();var yx=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new be("idType is required for creating a did:btcr2 identifier",qe,r);return fr.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=fr.decode(e),i=mo.sidecarData(r.sidecar),o=n.hrp===Pl.k?mo.deterministic(n):null;return new mo(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}){if(!Number.isInteger(n)||n<1)throw new it(`Invalid sourceVersionId: expected an integer of at least 1, got ${String(n)}.`,le,{sourceVersionId:n});let s=tt.capabilityInvocationEntry(e,i);if(s===void 0)throw new it("Invalid verificationMethodId: not authorized for capabilityInvocation",le,{verificationMethodId:i,capabilityInvocation:e.capabilityInvocation});let c=tt.verificationMethodOfEntry(e,s);if(!c)throw new it("Invalid verificationMethodId: not found in source document",le,{verificationMethodId:i});if(c.type!==Bc)throw new it(`Invalid verificationMethod: verificationMethod.type must be "${Bc}"`,qe,c);if(!c.publicKeyMultibase?.startsWith(Rc))throw new it(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${Rc}"`,qe,c);let a=tt.absoluteDidUrl(o,e.id),u=e.service.filter(d=>a!==void 0&&tt.absoluteDidUrl(d.id,e.id)===a).filter(d=>!!d).shift();if(!u)throw new it("No beacon service found for provided beaconId",le,{sourceDocument:e,beaconId:o});return new Tf({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:c,beaconService:u})}static deactivate({sourceDocument:e,sourceVersionId:r,verificationMethodId:n,beaconId:i}){return this.update({sourceDocument:e,patches:[{...cx}],sourceVersionId:r,verificationMethodId:n,beaconId:i})}static getSigningMethod(e,r){r??="#initialKey";let n=xe.parse(e.id);if(n&&n.method!==this.methodName)throw new be(`Method not supported: ${n.method}`,_l,{identifier:e.id});let i=tt.absoluteDidUrl(r,e.id)??tt.relationshipMethodId(e.assertionMethod?.[0],e.id),o=i===void 0?void 0:tt.getVerificationMethods(e).find(s=>tt.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}};return kB(ZL);})();
4
4
  /*! Bundled license information:
5
5
 
6
6
  ieee754/index.js: