nostr-web-components
Version:
collection of web components that provide quick access to basic nostr things
1 lines • 88.8 kB
JavaScript
var nostr_text=(function(){"use strict";var Nr=Object.defineProperty;var qr=(ue,Z,L)=>Z in ue?Nr(ue,Z,{enumerable:!0,configurable:!0,writable:!0,value:L}):ue[Z]=L;var h=(ue,Z,L)=>qr(ue,typeof Z!="symbol"?Z+"":Z,L);/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ue(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Z(t,e=""){if(!Number.isSafeInteger(t)||t<0){const n=e&&`"${e}" `;throw new Error(`${n}expected integer >= 0, got ${t}`)}}function L(t,e,n=""){const i=ue(t),r=t==null?void 0:t.length,s=e!==void 0;if(!i||s&&r!==e){const a=n&&`"${n}" `,o=s?` of length ${e}`:"",c=i?`length=${r}`:`type=${typeof t}`;throw new Error(a+"expected Uint8Array"+o+", got "+c)}return t}function Tt(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 In(t,e){L(t,void 0,"digestInto() output");const n=e.outputLen;if(t.length<n)throw new Error('"digestInto() output" expected to be of length >='+n)}function je(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ke(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Y(t,e){return t<<32-e|t>>>e}const kt=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$n=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function P(t){if(L(t),kt)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=$n[t[n]];return e}const ne={_0:48,_9:57,A:65,F:70,a:97,f:102};function At(t){if(t>=ne._0&&t<=ne._9)return t-ne._0;if(t>=ne.A&&t<=ne.F)return t-(ne.A-10);if(t>=ne.a&&t<=ne.f)return t-(ne.a-10)}function N(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(kt)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(n);for(let r=0,s=0;r<n;r++,s+=2){const a=At(t.charCodeAt(s)),o=At(t.charCodeAt(s+1));if(a===void 0||o===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}i[r]=a*16+o}return i}function Ee(...t){let e=0;for(let i=0;i<t.length;i++){const r=t[i];L(r),e+=r.length}const n=new Uint8Array(e);for(let i=0,r=0;i<t.length;i++){const s=t[i];n.set(s,r),r+=s.length}return n}function Ln(t,e={}){const n=(r,s)=>t(s).update(r).digest(),i=t(void 0);return n.outputLen=i.outputLen,n.blockLen=i.blockLen,n.create=r=>t(r),Object.assign(n,e),Object.freeze(n)}function Ot(t=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}const Hn=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function _t(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ct(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function Nn(t){if(typeof t!="function")throw new Error("function expected");return!0}function xe(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Pt(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function ze(t){if(!Array.isArray(t))throw new Error("array expected")}function Bt(t,e){if(!Ct(!0,e))throw new Error(`${t}: array of strings expected`)}function It(t,e){if(!Ct(!1,e))throw new Error(`${t}: array of numbers expected`)}function qn(...t){const e=s=>s,n=(s,a)=>o=>s(a(o)),i=t.map(s=>s.encode).reduceRight(n,e),r=t.map(s=>s.decode).reduce(n,e);return{encode:i,decode:r}}function Un(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Bt("alphabet",e);const i=new Map(e.map((r,s)=>[r,s]));return{encode:r=>(ze(r),r.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:r=>(ze(r),r.map(s=>{xe("alphabet.decode",s);const a=i.get(s);if(a===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return a}))}}function Mn(t=""){return xe("join",t),{encode:e=>(Bt("join.decode",e),e.join(t)),decode:e=>(xe("join.decode",e),e.split(t))}}const $t=(t,e)=>e===0?t:$t(e,t%e),Ce=(t,e)=>t+(e-$t(t,e)),Pe=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Ye(t,e,n,i){if(ze(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Ce(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Ce(e,n)}`);let r=0,s=0;const a=Pe[e],o=Pe[n]-1,c=[];for(const u of t){if(Pt(u),u>=a)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(r=r<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((r>>s-n&o)>>>0);const f=Pe[s];if(f===void 0)throw new Error("invalid carry");r&=f-1}if(r=r<<n-s&o,!i&&s>=e)throw new Error("Excess padding");if(!i&&r>0)throw new Error(`Non-zero padding: ${r}`);return i&&s>0&&c.push(r>>>0),c}function Vn(t,e=!1){if(Pt(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ce(8,t)>32||Ce(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!_t(n))throw new Error("radix2.encode input should be Uint8Array");return Ye(Array.from(n),8,t,!e)},decode:n=>(It("radix2.decode",n),Uint8Array.from(Ye(n,t,8,e)))}}function Lt(t){return Nn(t),function(...e){try{return t.apply(null,e)}catch{}}}const Ge=qn(Un("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Mn("")),Ht=[996825010,642813549,513874426,1027748829,705979059];function ve(t){const e=t>>25;let n=(t&33554431)<<5;for(let i=0;i<Ht.length;i++)(e>>i&1)===1&&(n^=Ht[i]);return n}function Nt(t,e,n=1){const i=t.length;let r=1;for(let s=0;s<i;s++){const a=t.charCodeAt(s);if(a<33||a>126)throw new Error(`Invalid prefix (${t})`);r=ve(r)^a>>5}r=ve(r);for(let s=0;s<i;s++)r=ve(r)^t.charCodeAt(s)&31;for(let s of e)r=ve(r)^s;for(let s=0;s<6;s++)r=ve(r);return r^=n,Ge.encode(Ye([r%Pe[30]],30,5,!1))}function Wn(t){const e=t==="bech32"?1:734539939,n=Vn(5),i=n.decode,r=n.encode,s=Lt(i);function a(l,b,d=90){xe("bech32.encode prefix",l),_t(b)&&(b=Array.from(b)),It("bech32.encode",b);const y=l.length;if(y===0)throw new TypeError(`Invalid prefix length ${y}`);const w=y+7+b.length;if(d!==!1&&w>d)throw new TypeError(`Length ${w} exceeds limit ${d}`);const p=l.toLowerCase(),T=Nt(p,b,e);return`${p}1${Ge.encode(b)}${T}`}function o(l,b=90){xe("bech32.decode input",l);const d=l.length;if(d<8||b!==!1&&d>b)throw new TypeError(`invalid string length: ${d} (${l}). Expected (8..${b})`);const y=l.toLowerCase();if(l!==y&&l!==l.toUpperCase())throw new Error("String must be lowercase or uppercase");const w=y.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');const p=y.slice(0,w),T=y.slice(w+1);if(T.length<6)throw new Error("Data must be at least 6 characters long");const I=Ge.decode(T).slice(0,-6),V=Nt(p,I,e);if(!T.endsWith(V))throw new Error(`Invalid checksum in ${l}: expected "${V}"`);return{prefix:p,words:I}}const c=Lt(o);function u(l){const{prefix:b,words:d}=o(l,!1);return{prefix:b,words:d,bytes:i(d)}}function f(l,b){return a(l,r(b))}return{encode:a,decode:o,encodeFromBytes:f,decodeToBytes:u,decodeUnsafe:c,fromWords:i,fromWordsUnsafe:s,toWords:r}}const re=Wn("bech32"),Be=new TextDecoder("utf-8"),Se=new TextEncoder;function Re(t){try{t.indexOf("://")===-1&&(t="wss://"+t);let e=new URL(t);return e.protocol==="http:"?e.protocol="ws:":e.protocol==="https:"&&(e.protocol="wss:"),e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}catch{throw new Error(`Invalid URL: ${t}`)}}const qt=5e3;function Dn(t){const e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=t&255,e}function Fn(t){var r,s,a,o,c,u,f;let{prefix:e,words:n}=re.decode(t,qt),i=new Uint8Array(re.fromWords(n));switch(e){case"nprofile":{let l=Je(i);if(!((r=l[0])!=null&&r[0]))throw new Error("missing TLV 0 for nprofile");if(l[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:P(l[0][0]),relays:l[1]?l[1].map(b=>Be.decode(b)):[]}}}case"nevent":{let l=Je(i);if(!((s=l[0])!=null&&s[0]))throw new Error("missing TLV 0 for nevent");if(l[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(l[2]&&l[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(l[3]&&l[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:P(l[0][0]),relays:l[1]?l[1].map(b=>Be.decode(b)):[],author:(a=l[2])!=null&&a[0]?P(l[2][0]):void 0,kind:(o=l[3])!=null&&o[0]?parseInt(P(l[3][0]),16):void 0}}}case"naddr":{let l=Je(i);if(!((c=l[0])!=null&&c[0]))throw new Error("missing TLV 0 for naddr");if(!((u=l[2])!=null&&u[0]))throw new Error("missing TLV 2 for naddr");if(l[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((f=l[3])!=null&&f[0]))throw new Error("missing TLV 3 for naddr");if(l[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Be.decode(l[0][0]),pubkey:P(l[2][0]),kind:parseInt(P(l[3][0]),16),relays:l[1]?l[1].map(b=>Be.decode(b)):[]}}}case"nsec":return{type:e,data:i};case"npub":case"note":return{type:e,data:P(i)};default:throw new Error(`unknown prefix ${e}`)}}function Je(t){let e={},n=t;for(;n.length>0;){let i=n[0],r=n[1],s=n.slice(2,2+r);if(n=n.slice(2+r),s.length<r)throw new Error(`not enough data to read on TLV ${i}`);e[i]=e[i]||[],e[i].push(s)}return e}function Zn(t){return jn("npub",N(t))}function Ie(t,e){let n=re.toWords(e);return re.encode(t,n,qt)}function jn(t,e){return Ie(t,e)}function Kn(t){let e=Xe({0:[N(t.pubkey)],1:(t.relays||[]).map(n=>Se.encode(n))});return Ie("nprofile",e)}function zn(t){let e;t.kind!==void 0&&(e=Dn(t.kind));let n=Xe({0:[N(t.id)],1:(t.relays||[]).map(i=>Se.encode(i)),2:t.author?[N(t.author)]:[],3:e?[new Uint8Array(e)]:[]});return Ie("nevent",n)}function Yn(t){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,t.kind,!1);let n=Xe({0:[Se.encode(t.identifier)],1:(t.relays||[]).map(i=>Se.encode(i)),2:[N(t.pubkey)],3:[new Uint8Array(e)]});return Ie("naddr",n)}function Xe(t){let e=[];return Object.entries(t).reverse().forEach(([n,i])=>{i.forEach(r=>{let s=new Uint8Array(r.length+2);s.set([parseInt(n)],0),s.set([r.length],1),s.set(r,2),e.push(s)})}),Ee(...e)}const Qe=/\W/m,Ut=/[^\w\/] |[^\w\/]$|$|,| /m,Gn=42;function*Jn(t){let e=[];if(typeof t!="string"){for(let s=0;s<t.tags.length;s++){const a=t.tags[s];a[0]==="emoji"&&a.length>=3&&e.push({type:"emoji",shortcode:a[1],url:a[2]})}t=t.content}const n=t.length;let i=0,r=0;e:for(;r<n;){const s=t.indexOf(":",r),a=t.indexOf("#",r);if(s===-1&&a===-1)break e;if(s===-1||a>=0&&a<s){if(a===0||t[a-1].match(Qe)){const o=t.slice(a+1,a+Gn).match(Qe),c=o?a+1+o.index:n;yield{type:"text",text:t.slice(i,a)},yield{type:"hashtag",value:t.slice(a+1,c)},r=c,i=r;continue e}r=a+1;continue e}if(t.slice(s-5,s)==="nostr"){const o=t.slice(s+60).match(Qe),c=o?s+60+o.index:n;try{let u,{data:f,type:l}=Fn(t.slice(s+1,c));switch(l){case"npub":u={pubkey:f};break;case"note":u={id:f};break;case"nsec":r=c+1;continue;default:u=f}i!==s-5&&(yield{type:"text",text:t.slice(i,s-5)}),yield{type:"reference",pointer:u},r=c,i=r;continue e}catch{r=s+1;continue e}}else if(t.slice(s-5,s)==="https"||t.slice(s-4,s)==="http"){const o=t.slice(s+4).match(Ut),c=o?s+4+o.index:n,u=t[s-1]==="s"?5:4;try{let f=new URL(t.slice(s-u,c));if(f.hostname.indexOf(".")===-1)throw new Error("invalid url");if(i!==s-u&&(yield{type:"text",text:t.slice(i,s-u)}),/\.(png|jpe?g|gif|webp|heic|svg)$/i.test(f.pathname)){yield{type:"image",url:f.toString()},r=c,i=r;continue e}if(/\.(mp4|avi|webm|mkv|mov)$/i.test(f.pathname)){yield{type:"video",url:f.toString()},r=c,i=r;continue e}if(/\.(mp3|aac|ogg|opus|wav|flac)$/i.test(f.pathname)){yield{type:"audio",url:f.toString()},r=c,i=r;continue e}yield{type:"url",url:f.toString()},r=c,i=r;continue e}catch{r=c+1;continue e}}else if(t.slice(s-3,s)==="wss"||t.slice(s-2,s)==="ws"){const o=t.slice(s+4).match(Ut),c=o?s+4+o.index:n,u=t[s-1]==="s"?3:2;try{let f=new URL(t.slice(s-u,c));if(f.hostname.indexOf(".")===-1)throw new Error("invalid ws url");i!==s-u&&(yield{type:"text",text:t.slice(i,s-u)}),yield{type:"relay",url:f.toString()},r=c,i=r;continue e}catch{r=c+1;continue e}}else{for(let o=0;o<e.length;o++){const c=e[o];if(t[s+c.shortcode.length+1]===":"&&t.slice(s+1,s+c.shortcode.length+1)===c.shortcode){i!==s&&(yield{type:"text",text:t.slice(i,s)}),yield c,r=s+c.shortcode.length+2,i=r;continue e}}r=s+1;continue e}}i!==n&&(yield{type:"text",text:t.slice(i)})}function et(t){var n,i;let e=(i=(n=window.nwc)==null?void 0:n.nostrLink)==null?void 0:i.call(n,t);return e||"https://njump.me/"+t}function Xn(t){var n,i;let e=(i=(n=window.nwc)==null?void 0:n.relayLink)==null?void 0:i.call(n,t);return e||"https://njump.me/r/"+encodeURIComponent(t)}function tt(t){let e=t.indexOf("1");return t.substring(0,e+3)+"…"+t.substring(t.length-5)}function Qn(t){if(t.length<=30)return t;try{let e=new URL(t);if(t.length<=40)return`${e.host}${e.pathname}${e.search.length?"?":""}${e.search}`;if(t.length<=50&&e.pathname.length<20)return`${e.host}${e.pathname}`;let n=e.pathname,i=e.pathname.split("/"),r=i[i.length-1];return r.length>10&&(r=`…${r.substring(r.length-6)}`),i.length>2?n=`/…/${r}`:n=`/${r}`,`${e.host}${n}`}catch{return t}}function ei(t,e,n){return t&e^~t&n}function ti(t,e,n){return t&e^t&n^e&n}class ni{constructor(e,n,i,r){h(this,"blockLen");h(this,"outputLen");h(this,"padOffset");h(this,"isLE");h(this,"buffer");h(this,"view");h(this,"finished",!1);h(this,"length",0);h(this,"pos",0);h(this,"destroyed",!1);this.blockLen=e,this.outputLen=n,this.padOffset=i,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Ke(this.buffer)}update(e){Tt(this),L(e);const{view:n,buffer:i,blockLen:r}=this,s=e.length;for(let a=0;a<s;){const o=Math.min(r-this.pos,s-a);if(o===r){const c=Ke(e);for(;r<=s-a;a+=r)this.process(c,a);continue}i.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===r&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Tt(this),In(e,this),this.finished=!0;const{buffer:n,view:i,blockLen:r,isLE:s}=this;let{pos:a}=this;n[a++]=128,je(this.buffer.subarray(a)),this.padOffset>r-a&&(this.process(i,0),a=0);for(let l=a;l<r;l++)n[l]=0;i.setBigUint64(r-8,BigInt(this.length*8),s),this.process(i,0);const o=Ke(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)o.setUint32(4*l,f[l],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const i=e.slice(0,n);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:i,length:r,finished:s,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=s,e.length=r,e.pos=o,r%n&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const se=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ii=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]),oe=new Uint32Array(64);class ri extends ni{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:n,C:i,D:r,E:s,F:a,G:o,H:c}=this;return[e,n,i,r,s,a,o,c]}set(e,n,i,r,s,a,o,c){this.A=e|0,this.B=n|0,this.C=i|0,this.D=r|0,this.E=s|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,n){for(let l=0;l<16;l++,n+=4)oe[l]=e.getUint32(n,!1);for(let l=16;l<64;l++){const b=oe[l-15],d=oe[l-2],y=Y(b,7)^Y(b,18)^b>>>3,w=Y(d,17)^Y(d,19)^d>>>10;oe[l]=w+oe[l-7]+y+oe[l-16]|0}let{A:i,B:r,C:s,D:a,E:o,F:c,G:u,H:f}=this;for(let l=0;l<64;l++){const b=Y(o,6)^Y(o,11)^Y(o,25),d=f+b+ei(o,c,u)+ii[l]+oe[l]|0,w=(Y(i,2)^Y(i,13)^Y(i,22))+ti(i,r,s)|0;f=u,u=c,c=o,o=a+d|0,a=s,s=r,r=i,i=d+w|0}i=i+this.A|0,r=r+this.B|0,s=s+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(i,r,s,a,o,c,u,f)}roundClean(){je(oe)}destroy(){this.set(0,0,0,0,0,0,0,0),je(this.buffer)}}class si extends ri{constructor(){super(32);h(this,"A",se[0]|0);h(this,"B",se[1]|0);h(this,"C",se[2]|0);h(this,"D",se[3]|0);h(this,"E",se[4]|0);h(this,"F",se[5]|0);h(this,"G",se[6]|0);h(this,"H",se[7]|0)}}const $e=Ln(()=>new si,Hn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nt=BigInt(0),it=BigInt(1);function Mt(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}" `;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function oi(t){if(typeof t=="bigint"){if(!li(t))throw new Error("positive bigint expected, got "+t)}else Z(t);return t}function Vt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?nt:BigInt("0x"+t)}function rt(t){return Vt(P(t))}function Wt(t){return Vt(P(ci(L(t)).reverse()))}function st(t,e){Z(e),t=oi(t);const n=N(t.toString(16).padStart(e*2,"0"));if(n.length!==e)throw new Error("number too large");return n}function Dt(t,e){return st(t,e).reverse()}function ci(t){return Uint8Array.from(t)}function ai(t){return Uint8Array.from(t,(e,n)=>{const i=e.charCodeAt(0);if(e.length!==1||i>127)throw new Error(`string contains non-ASCII character "${t[n]}" with code ${i} at position ${n}`);return i})}const li=t=>typeof t=="bigint"&&nt<=t;function ui(t){let e;for(e=0;t>nt;t>>=it,e+=1);return e}const Ft=t=>(it<<BigInt(t))-it;function Zt(t,e={},n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function i(s,a,o){const c=t[s];if(o&&c===void 0)return;const u=typeof c;if(u!==a||c===null)throw new Error(`param "${s}" is invalid: expected ${a}, got ${u}`)}const r=(s,a)=>Object.entries(s).forEach(([o,c])=>i(o,c,a));r(e,!1),r(n,!0)}function jt(t){const e=new WeakMap;return(n,...i)=>{const r=e.get(n);if(r!==void 0)return r;const s=t(n,...i);return e.set(n,s),s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const M=BigInt(0),q=BigInt(1),he=BigInt(2),Kt=BigInt(3),zt=BigInt(4),Yt=BigInt(5),hi=BigInt(7),Gt=BigInt(8),fi=BigInt(9),Jt=BigInt(16);function j(t,e){const n=t%e;return n>=M?n:e+n}function W(t,e,n){let i=t;for(;e-- >M;)i*=i,i%=n;return i}function Xt(t,e){if(t===M)throw new Error("invert: expected non-zero number");if(e<=M)throw new Error("invert: expected positive modulus, got "+e);let n=j(t,e),i=e,r=M,s=q;for(;n!==M;){const o=i/n,c=i%n,u=r-s*o;i=n,n=c,r=s,s=u}if(i!==q)throw new Error("invert: does not exist");return j(r,e)}function ot(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Qt(t,e){const n=(t.ORDER+q)/zt,i=t.pow(e,n);return ot(t,i,e),i}function di(t,e){const n=(t.ORDER-Yt)/Gt,i=t.mul(e,he),r=t.pow(i,n),s=t.mul(e,r),a=t.mul(t.mul(s,he),r),o=t.mul(s,t.sub(a,t.ONE));return ot(t,o,e),o}function yi(t){const e=Le(t),n=en(t),i=n(e,e.neg(e.ONE)),r=n(e,i),s=n(e,e.neg(i)),a=(t+hi)/Jt;return(o,c)=>{let u=o.pow(c,a),f=o.mul(u,i);const l=o.mul(u,r),b=o.mul(u,s),d=o.eql(o.sqr(f),c),y=o.eql(o.sqr(l),c);u=o.cmov(u,f,d),f=o.cmov(b,l,y);const w=o.eql(o.sqr(f),c),p=o.cmov(u,f,w);return ot(o,p,c),p}}function en(t){if(t<Kt)throw new Error("sqrt is not defined for small field");let e=t-q,n=0;for(;e%he===M;)e/=he,n++;let i=he;const r=Le(t);for(;nn(r,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Qt;let s=r.pow(i,e);const a=(e+q)/he;return function(c,u){if(c.is0(u))return u;if(nn(c,u)!==1)throw new Error("Cannot find square root");let f=n,l=c.mul(c.ONE,s),b=c.pow(u,e),d=c.pow(u,a);for(;!c.eql(b,c.ONE);){if(c.is0(b))return c.ZERO;let y=1,w=c.sqr(b);for(;!c.eql(w,c.ONE);)if(y++,w=c.sqr(w),y===f)throw new Error("Cannot find square root");const p=q<<BigInt(f-y-1),T=c.pow(l,p);f=y,l=c.sqr(T),b=c.mul(b,l),d=c.mul(d,T)}return d}}function bi(t){return t%zt===Kt?Qt:t%Gt===Yt?di:t%Jt===fi?yi(t):en(t)}const wi=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gi(t){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},n=wi.reduce((i,r)=>(i[r]="function",i),e);return Zt(t,n),t}function pi(t,e,n){if(n<M)throw new Error("invalid exponent, negatives unsupported");if(n===M)return t.ONE;if(n===q)return e;let i=t.ONE,r=e;for(;n>M;)n&q&&(i=t.mul(i,r)),r=t.sqr(r),n>>=q;return i}function tn(t,e,n=!1){const i=new Array(e.length).fill(n?t.ZERO:void 0),r=e.reduce((a,o,c)=>t.is0(o)?a:(i[c]=a,t.mul(a,o)),t.ONE),s=t.inv(r);return e.reduceRight((a,o,c)=>t.is0(o)?a:(i[c]=t.mul(a,i[c]),t.mul(a,o)),s),i}function nn(t,e){const n=(t.ORDER-q)/he,i=t.pow(e,n),r=t.eql(i,t.ONE),s=t.eql(i,t.ZERO),a=t.eql(i,t.neg(t.ONE));if(!r&&!s&&!a)throw new Error("invalid Legendre symbol result");return r?1:s?0:-1}function mi(t,e){e!==void 0&&Z(e);const n=e!==void 0?e:t.toString(2).length,i=Math.ceil(n/8);return{nBitLength:n,nByteLength:i}}class Ei{constructor(e,n={}){h(this,"ORDER");h(this,"BITS");h(this,"BYTES");h(this,"isLE");h(this,"ZERO",M);h(this,"ONE",q);h(this,"_lengths");h(this,"_sqrt");h(this,"_mod");var a;if(e<=M)throw new Error("invalid field: expected ORDER > 0, got "+e);let i;this.isLE=!1,n!=null&&typeof n=="object"&&(typeof n.BITS=="number"&&(i=n.BITS),typeof n.sqrt=="function"&&(this.sqrt=n.sqrt),typeof n.isLE=="boolean"&&(this.isLE=n.isLE),n.allowedLengths&&(this._lengths=(a=n.allowedLengths)==null?void 0:a.slice()),typeof n.modFromBytes=="boolean"&&(this._mod=n.modFromBytes));const{nBitLength:r,nByteLength:s}=mi(e,i);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=r,this.BYTES=s,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return j(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return M<=e&&e<this.ORDER}is0(e){return e===M}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&q)===q}neg(e){return j(-e,this.ORDER)}eql(e,n){return e===n}sqr(e){return j(e*e,this.ORDER)}add(e,n){return j(e+n,this.ORDER)}sub(e,n){return j(e-n,this.ORDER)}mul(e,n){return j(e*n,this.ORDER)}pow(e,n){return pi(this,e,n)}div(e,n){return j(e*Xt(n,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,n){return e+n}subN(e,n){return e-n}mulN(e,n){return e*n}inv(e){return Xt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=bi(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Dt(e,this.BYTES):st(e,this.BYTES)}fromBytes(e,n=!1){L(e);const{_lengths:i,BYTES:r,isLE:s,ORDER:a,_mod:o}=this;if(i){if(!i.includes(e.length)||e.length>r)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);const u=new Uint8Array(r);u.set(e,s?0:u.length-e.length),e=u}if(e.length!==r)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=s?Wt(e):rt(e);if(o&&(c=j(c,a)),!n&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return tn(this,e)}cmov(e,n,i){return i?n:e}}function Le(t,e={}){return new Ei(t,e)}function rn(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function xi(t){const e=rn(t);return e+Math.ceil(e/2)}function vi(t,e,n=!1){L(t);const i=t.length,r=rn(e),s=xi(e);if(i<16||i<s||i>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+i);const a=n?Wt(t):rt(t),o=j(a,e-q)+q;return n?Dt(o,r):st(o,r)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const we=BigInt(0),fe=BigInt(1);function He(t,e){const n=e.negate();return t?n:e}function sn(t,e){const n=tn(t.Fp,e.map(i=>i.Z));return e.map((i,r)=>t.fromAffine(i.toAffine(n[r])))}function on(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ct(t,e){on(t,e);const n=Math.ceil(e/t)+1,i=2**(t-1),r=2**t,s=Ft(t),a=BigInt(t);return{windows:n,windowSize:i,mask:s,maxNumber:r,shiftBy:a}}function cn(t,e,n){const{windowSize:i,mask:r,maxNumber:s,shiftBy:a}=n;let o=Number(t&r),c=t>>a;o>i&&(o-=s,c+=fe);const u=e*i,f=u+Math.abs(o)-1,l=o===0,b=o<0,d=e%2!==0;return{nextN:c,offset:f,isZero:l,isNeg:b,isNegF:d,offsetF:u}}const at=new WeakMap,an=new WeakMap;function lt(t){return an.get(t)||1}function ln(t){if(t!==we)throw new Error("invalid wNAF")}class Si{constructor(e,n){h(this,"BASE");h(this,"ZERO");h(this,"Fn");h(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,i=this.ZERO){let r=e;for(;n>we;)n&fe&&(i=i.add(r)),r=r.double(),n>>=fe;return i}precomputeWindow(e,n){const{windows:i,windowSize:r}=ct(n,this.bits),s=[];let a=e,o=a;for(let c=0;c<i;c++){o=a,s.push(o);for(let u=1;u<r;u++)o=o.add(a),s.push(o);a=o.double()}return s}wNAF(e,n,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let r=this.ZERO,s=this.BASE;const a=ct(e,this.bits);for(let o=0;o<a.windows;o++){const{nextN:c,offset:u,isZero:f,isNeg:l,isNegF:b,offsetF:d}=cn(i,o,a);i=c,f?s=s.add(He(b,n[d])):r=r.add(He(l,n[u]))}return ln(i),{p:r,f:s}}wNAFUnsafe(e,n,i,r=this.ZERO){const s=ct(e,this.bits);for(let a=0;a<s.windows&&i!==we;a++){const{nextN:o,offset:c,isZero:u,isNeg:f}=cn(i,a,s);if(i=o,!u){const l=n[c];r=r.add(f?l.negate():l)}}return ln(i),r}getPrecomputes(e,n,i){let r=at.get(n);return r||(r=this.precomputeWindow(n,e),e!==1&&(typeof i=="function"&&(r=i(r)),at.set(n,r))),r}cached(e,n,i){const r=lt(e);return this.wNAF(r,this.getPrecomputes(r,e,i),n)}unsafe(e,n,i,r){const s=lt(e);return s===1?this._unsafeLadder(e,n,r):this.wNAFUnsafe(s,this.getPrecomputes(s,e,i),n,r)}createCache(e,n){on(n,this.bits),an.set(e,n),at.delete(e)}hasCache(e){return lt(e)!==1}}function Ri(t,e,n,i){let r=e,s=t.ZERO,a=t.ZERO;for(;n>we||i>we;)n&fe&&(s=s.add(r)),i&fe&&(a=a.add(r)),r=r.double(),n>>=fe,i>>=fe;return{p1:s,p2:a}}function un(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return gi(e),e}else return Le(t,{isLE:n})}function Ti(t,e,n={},i){if(i===void 0&&(i=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>we))throw new Error(`CURVE.${c} must be positive bigint`)}const r=un(e.p,n.Fp,i),s=un(e.n,n.Fn,i),o=["Gx","Gy","a","b"];for(const c of o)if(!r.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:r,Fn:s}}function ki(t,e){return function(i){const r=t(i);return{secretKey:r,publicKey:e(r)}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hn=(t,e)=>(t+(t>=0?e:-e)/Oi)/e;function Ai(t,e,n){const[[i,r],[s,a]]=e,o=hn(a*t,n),c=hn(-r*t,n);let u=t-o*i-c*s,f=-o*r-c*a;const l=u<Te,b=f<Te;l&&(u=-u),b&&(f=-f);const d=Ft(Math.ceil(ui(n)/2))+Ne;if(u<Te||u>=d||f<Te||f>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:u,k2neg:b,k2:f}}const Te=BigInt(0),Ne=BigInt(1),Oi=BigInt(2),qe=BigInt(3),_i=BigInt(4);function Ci(t,e={}){const n=Ti("weierstrass",t,e),{Fp:i,Fn:r}=n;let s=n.CURVE;const{h:a,n:o}=s;Zt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!i.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Bi(i,r);function f(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(O,g,m){const{x,y:v}=g.toAffine(),_=i.toBytes(x);if(Mt(m,"isCompressed"),m){f();const k=!i.isOdd(v);return Ee(Pi(k),_)}else return Ee(Uint8Array.of(4),_,i.toBytes(v))}function b(O){L(O,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=u,x=O.length,v=O[0],_=O.subarray(1);if(x===g&&(v===2||v===3)){const k=i.fromBytes(_);if(!i.isValid(k))throw new Error("bad point: is not on curve, wrong x");const S=w(k);let E;try{E=i.sqrt(S)}catch(F){const H=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}f();const R=i.isOdd(E);return(v&1)===1!==R&&(E=i.neg(E)),{x:k,y:E}}else if(x===m&&v===4){const k=i.BYTES,S=i.fromBytes(_.subarray(0,k)),E=i.fromBytes(_.subarray(k,k*2));if(!p(S,E))throw new Error("bad point: is not on curve");return{x:S,y:E}}else throw new Error(`bad point: got length ${x}, expected compressed=${g} or uncompressed=${m}`)}const d=e.toBytes||l,y=e.fromBytes||b;function w(O){const g=i.sqr(O),m=i.mul(g,O);return i.add(i.add(m,i.mul(O,s.a)),s.b)}function p(O,g){const m=i.sqr(g),x=w(O);return i.eql(m,x)}if(!p(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const T=i.mul(i.pow(s.a,qe),_i),I=i.mul(i.sqr(s.b),BigInt(27));if(i.is0(i.add(T,I)))throw new Error("bad curve params: a or b");function V(O,g,m=!1){if(!i.isValid(g)||m&&i.is0(g))throw new Error(`bad point coordinate ${O}`);return g}function ee(O){if(!(O instanceof be))throw new Error("Weierstrass Point expected")}function $(O){if(!c||!c.basises)throw new Error("no endo");return Ai(O,c.basises,r.ORDER)}const D=jt((O,g)=>{const{X:m,Y:x,Z:v}=O;if(i.eql(v,i.ONE))return{x:m,y:x};const _=O.is0();g==null&&(g=_?i.ONE:i.inv(v));const k=i.mul(m,g),S=i.mul(x,g),E=i.mul(v,g);if(_)return{x:i.ZERO,y:i.ZERO};if(!i.eql(E,i.ONE))throw new Error("invZ was invalid");return{x:k,y:S}}),Hr=jt(O=>{if(O.is0()){if(e.allowInfinityPoint&&!i.is0(O.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=O.toAffine();if(!i.isValid(g)||!i.isValid(m))throw new Error("bad point: x or y not field elements");if(!p(g,m))throw new Error("bad point: equation left != right");if(!O.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Cn(O,g,m,x,v){return m=new be(i.mul(m.X,O),m.Y,m.Z),g=He(x,g),m=He(v,m),g.add(m)}const B=class B{constructor(g,m,x){h(this,"X");h(this,"Y");h(this,"Z");this.X=V("x",g),this.Y=V("y",m,!0),this.Z=V("z",x),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){const{x:m,y:x}=g||{};if(!g||!i.isValid(m)||!i.isValid(x))throw new Error("invalid affine point");if(g instanceof B)throw new Error("projective point not allowed");return i.is0(m)&&i.is0(x)?B.ZERO:new B(m,x,i.ONE)}static fromBytes(g){const m=B.fromAffine(y(L(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return B.fromBytes(N(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return _e.createCache(this,g),m||this.multiply(qe),this}assertValidity(){Hr(this)}hasEvenY(){const{y:g}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(g)}equals(g){ee(g);const{X:m,Y:x,Z:v}=this,{X:_,Y:k,Z:S}=g,E=i.eql(i.mul(m,S),i.mul(_,v)),R=i.eql(i.mul(x,S),i.mul(k,v));return E&&R}negate(){return new B(this.X,i.neg(this.Y),this.Z)}double(){const{a:g,b:m}=s,x=i.mul(m,qe),{X:v,Y:_,Z:k}=this;let S=i.ZERO,E=i.ZERO,R=i.ZERO,A=i.mul(v,v),F=i.mul(_,_),H=i.mul(k,k),C=i.mul(v,_);return C=i.add(C,C),R=i.mul(v,k),R=i.add(R,R),S=i.mul(g,R),E=i.mul(x,H),E=i.add(S,E),S=i.sub(F,E),E=i.add(F,E),E=i.mul(S,E),S=i.mul(C,S),R=i.mul(x,R),H=i.mul(g,H),C=i.sub(A,H),C=i.mul(g,C),C=i.add(C,R),R=i.add(A,A),A=i.add(R,A),A=i.add(A,H),A=i.mul(A,C),E=i.add(E,A),H=i.mul(_,k),H=i.add(H,H),A=i.mul(H,C),S=i.sub(S,A),R=i.mul(H,F),R=i.add(R,R),R=i.add(R,R),new B(S,E,R)}add(g){ee(g);const{X:m,Y:x,Z:v}=this,{X:_,Y:k,Z:S}=g;let E=i.ZERO,R=i.ZERO,A=i.ZERO;const F=s.a,H=i.mul(s.b,qe);let C=i.mul(m,_),K=i.mul(x,k),z=i.mul(v,S),me=i.add(m,x),U=i.add(_,k);me=i.mul(me,U),U=i.add(C,K),me=i.sub(me,U),U=i.add(m,v);let te=i.add(_,S);return U=i.mul(U,te),te=i.add(C,z),U=i.sub(U,te),te=i.add(x,v),E=i.add(k,S),te=i.mul(te,E),E=i.add(K,z),te=i.sub(te,E),A=i.mul(F,U),E=i.mul(H,z),A=i.add(E,A),E=i.sub(K,A),A=i.add(K,A),R=i.mul(E,A),K=i.add(C,C),K=i.add(K,C),z=i.mul(F,z),U=i.mul(H,U),K=i.add(K,z),z=i.sub(C,z),z=i.mul(F,z),U=i.add(U,z),C=i.mul(K,U),R=i.add(R,C),C=i.mul(te,U),E=i.mul(me,E),E=i.sub(E,C),C=i.mul(me,K),A=i.mul(te,A),A=i.add(A,C),new B(E,R,A)}subtract(g){return this.add(g.negate())}is0(){return this.equals(B.ZERO)}multiply(g){const{endo:m}=e;if(!r.isValidNot0(g))throw new Error("invalid scalar: out of range");let x,v;const _=k=>_e.cached(this,k,S=>sn(B,S));if(m){const{k1neg:k,k1:S,k2neg:E,k2:R}=$(g),{p:A,f:F}=_(S),{p:H,f:C}=_(R);v=F.add(C),x=Cn(m.beta,A,H,k,E)}else{const{p:k,f:S}=_(g);x=k,v=S}return sn(B,[x,v])[0]}multiplyUnsafe(g){const{endo:m}=e,x=this;if(!r.isValid(g))throw new Error("invalid scalar: out of range");if(g===Te||x.is0())return B.ZERO;if(g===Ne)return x;if(_e.hasCache(this))return this.multiply(g);if(m){const{k1neg:v,k1:_,k2neg:k,k2:S}=$(g),{p1:E,p2:R}=Ri(B,x,_,S);return Cn(m.beta,E,R,v,k)}else return _e.unsafe(x,g)}toAffine(g){return D(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return a===Ne?!0:g?g(B,this):_e.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:g}=e;return a===Ne?this:g?g(B,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(g=!0){return Mt(g,"isCompressed"),this.assertValidity(),d(B,this,g)}toHex(g=!0){return P(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};h(B,"BASE",new B(s.Gx,s.Gy,i.ONE)),h(B,"ZERO",new B(i.ZERO,i.ONE,i.ZERO)),h(B,"Fp",i),h(B,"Fn",r);let be=B;const Pn=r.BITS,_e=new Si(be,e.endo?Math.ceil(Pn/2):Pn);return be.BASE.precompute(8),be}function Pi(t){return Uint8Array.of(t?2:3)}function Bi(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ue={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ii={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},$i=BigInt(0),ut=BigInt(2);function Li(t){const e=Ue.p,n=BigInt(3),i=BigInt(6),r=BigInt(11),s=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=t*t*t%e,f=u*u*t%e,l=W(f,n,e)*f%e,b=W(l,n,e)*f%e,d=W(b,ut,e)*u%e,y=W(d,r,e)*d%e,w=W(y,s,e)*y%e,p=W(w,o,e)*w%e,T=W(p,c,e)*p%e,I=W(T,o,e)*w%e,V=W(I,n,e)*f%e,ee=W(V,a,e)*y%e,$=W(ee,i,e)*u%e,D=W($,ut,e);if(!Me.eql(Me.sqr(D),t))throw new Error("Cannot find square root");return D}const Me=Le(Ue.p,{sqrt:Li}),ge=Ci(Ue,{Fp:Me,endo:Ii}),fn={};function Ve(t,...e){let n=fn[t];if(n===void 0){const i=$e(ai(t));n=Ee(i,i),fn[t]=n}return $e(Ee(n,...e))}const ht=t=>t.toBytes(!0).slice(1),ft=t=>t%ut===$i;function dt(t){const{Fn:e,BASE:n}=ge,i=e.fromBytes(t),r=n.multiply(i);return{scalar:ft(r.y)?i:e.neg(i),bytes:ht(r)}}function dn(t){const e=Me;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x ≥ p");const n=e.create(t*t),i=e.create(n*t+BigInt(7));let r=e.sqrt(i);ft(r)||(r=e.neg(r));const s=ge.fromAffine({x:t,y:r});return s.assertValidity(),s}const ke=rt;function yn(...t){return ge.Fn.create(ke(Ve("BIP0340/challenge",...t)))}function bn(t){return dt(t).bytes}function Hi(t,e,n=Ot(32)){const{Fn:i}=ge,r=L(t,void 0,"message"),{bytes:s,scalar:a}=dt(e),o=L(n,32,"auxRand"),c=i.toBytes(a^ke(Ve("BIP0340/aux",o))),u=Ve("BIP0340/nonce",c,s,r),{bytes:f,scalar:l}=dt(u),b=yn(f,s,r),d=new Uint8Array(64);if(d.set(f,0),d.set(i.toBytes(i.create(l+b*a)),32),!wn(d,r,s))throw new Error("sign: Invalid signature produced");return d}function wn(t,e,n){const{Fp:i,Fn:r,BASE:s}=ge,a=L(t,64,"signature"),o=L(e,void 0,"message"),c=L(n,32,"publicKey");try{const u=dn(ke(c)),f=ke(a.subarray(0,32));if(!i.isValidNot0(f))return!1;const l=ke(a.subarray(32,64));if(!r.isValidNot0(l))return!1;const b=yn(r.toBytes(f),ht(u),o),d=s.multiplyUnsafe(l).add(u.multiplyUnsafe(r.neg(b))),{x:y,y:w}=d.toAffine();return!(d.is0()||!ft(w)||y!==f)}catch{return!1}}const G=(()=>{const n=(i=Ot(48))=>vi(i,Ue.n);return{keygen:ki(n,bn),getPublicKey:bn,sign:Hi,verify:wn,Point:ge,utils:{randomSecretKey:n,taggedHash:Ve,lift_x:dn,pointToBytes:ht},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),de=Symbol("verified"),Ni=t=>t instanceof Object;function qi(t){if(!Ni(t)||typeof t.kind!="number"||typeof t.content!="string"||typeof t.created_at!="number"||typeof t.pubkey!="string"||!t.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(t.tags))return!1;for(let e=0;e<t.tags.length;e++){let n=t.tags[e];if(!Array.isArray(n))return!1;for(let i=0;i<n.length;i++)if(typeof n[i]!="string")return!1}return!0}let Ui=class{generateSecretKey(){return G.utils.randomSecretKey()}getPublicKey(e){return P(G.getPublicKey(e))}finalizeEvent(e,n){const i=e;return i.pubkey=P(G.getPublicKey(n)),i.id=yt(i),i.sig=P(G.sign(N(yt(i)),n)),i[de]=!0,i}verifyEvent(e){if(typeof e[de]=="boolean")return e[de];const n=yt(e);if(n!==e.id)return e[de]=!1,!1;try{const i=G.verify(N(e.sig),N(n),N(e.pubkey));return e[de]=i,i}catch{return e[de]=!1,!1}}};function Mi(t){if(!qi(t))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content])}function yt(t){let e=$e(Se.encode(Mi(t)));return P(e)}const We=new Ui;We.generateSecretKey,We.getPublicKey,We.finalizeEvent;const Vi=We.verifyEvent,Wi=22242;function Di(t,e){if(t.ids&&t.ids.indexOf(e.id)===-1||t.kinds&&t.kinds.indexOf(e.kind)===-1||t.authors&&t.authors.indexOf(e.pubkey)===-1)return!1;for(let n in t)if(n[0]==="#"){let i=n.slice(1),r=t[`#${i}`];if(r&&!e.tags.find(([s,a])=>s===n.slice(1)&&r.indexOf(a)!==-1))return!1}return!(t.since&&e.created_at<t.since||t.until&&e.created_at>t.until)}function Fi(t,e){for(let n=0;n<t.length;n++)if(Di(t[n],e))return!0;return!1}function Zi(t,e){let n=e.length+3,i=t.indexOf(`"${e}":`)+n,r=t.slice(i).indexOf('"')+i+1;return t.slice(r,r+64)}function ji(t){let e=t.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let n=t.slice(e+7+1).indexOf('"');if(n===-1)return null;let i=e+7+1+n,r=t.slice(i+1,80).indexOf('"');if(r===-1)return null;let s=i+1+r;return t.slice(i+1,s)}function Ki(t,e){return{kind:Wi,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}let gn=class extends Error{constructor(e,n){super(`Tried to send message '${e} on a closed connection to ${n}.`),this.name="SendingOnClosedConnection"}},zi=class Bn{constructor(e,n){h(this,"url");h(this,"_connected",!1);h(this,"onclose",null);h(this,"onnotice",e=>console.debug(`NOTICE from ${this.url}: ${e}`));h(this,"onauth");h(this,"baseEoseTimeout",4400);h(this,"publishTimeout",4400);h(this,"pingFrequency",29e3);h(this,"pingTimeout",2e4);h(this,"resubscribeBackoff",[1e4,1e4,1e4,2e4,2e4,3e4,6e4]);h(this,"openSubs",new Map);h(this,"enablePing");h(this,"enableReconnect");h(this,"idleSince",Date.now());h(this,"ongoingOperations",0);h(this,"reconnectTimeoutHandle");h(this,"pingIntervalHandle");h(this,"reconnectAttempts",0);h(this,"skipReconnection",!1);h(this,"connectionPromise");h(this,"openCountRequests",new Map);h(this,"openEventPublishes",new Map);h(this,"ws");h(this,"challenge");h(this,"authPromise");h(this,"serial",0);h(this,"verifyEvent");h(this,"_WebSocket");this.url=Re(e),this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation||WebSocket,this.enablePing=n.enablePing,this.enableReconnect=n.enableReconnect||!1}static async connect(e,n){const i=new Bn(e,n);return await i.connect(n),i}closeAllSubscriptions(e){for(let[n,i]of this.openSubs)i.close(e);this.openSubs.clear();for(let[n,i]of this.openEventPublishes)i.reject(new Error(e));this.openEventPublishes.clear();for(let[n,i]of this.openCountRequests)i.reject(new Error(e));this.openCountRequests.clear()}get connected(){return this._connected}async reconnect(){const e=this.resubscribeBackoff[Math.min(this.reconnectAttempts,this.resubscribeBackoff.length-1)];this.reconnectAttempts++,this.reconnectTimeoutHandle=setTimeout(async()=>{try{await this.connect()}catch{}},e)}handleHardClose(e){var n;this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this._connected=!1,this.connectionPromise=void 0,this.idleSince=void 0,this.enableReconnect&&!this.skipReconnection?this.reconnect():((n=this.onclose)==null||n.call(this),this.closeAllSubscriptions(e))}async connect(e){let n;return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.skipReconnection=!1,this.connectionPromise=new Promise((i,r)=>{e!=null&&e.timeout&&(n=setTimeout(()=>{var s;r("connection timed out"),this.connectionPromise=void 0,this.skipReconnection=!0,(s=this.onclose)==null||s.call(this),this.handleHardClose("relay connection timed out")},e.timeout)),e!=null&&e.abort&&(e.abort.onabort=r);try{this.ws=new this._WebSocket(this.url)}catch(s){clearTimeout(n),r(s);return}this.ws.onopen=()=>{this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),clearTimeout(n),this._connected=!0;const s=this.reconnectAttempts>0;this.reconnectAttempts=0;for(const a of this.openSubs.values()){if(a.eosed=!1,s)for(let o=0;o<a.filters.length;o++)a.lastEmitted&&(a.filters[o].since=a.lastEmitted+1);a.fire()}this.enablePing&&(this.pingIntervalHandle=setInterval(()=>this.pingpong(),this.pingFrequency)),i()},this.ws.onerror=()=>{var s;clearTimeout(n),r("connection failed"),this.connectionPromise=void 0,this.skipReconnection=!0,(s=this.onclose)==null||s.call(this),this.handleHardClose("relay connection failed")},this.ws.onclose=s=>{clearTimeout(n),r(s.message||"websocket closed"),this.handleHardClose("relay connection closed")},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}waitForPingPong(){return new Promise(e=>{this.ws.once("pong",()=>e(!0)),this.ws.ping()})}waitForDummyReq(){return new Promise((e,n)=>{if(!this.connectionPromise)return n(new Error(`no connection to ${this.url}, can't ping`));try{const i=this.subscribe([{ids:["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],limit:0}],{label:"<forced-ping>",oneose:()=>{e(!0),i.close()},onclose(){e(!0)},eoseTimeout:this.pingTimeout+1e3})}catch(i){n(i)}})}async pingpong(){var e,n,i;((e=this.ws)==null?void 0:e.readyState)===1&&(await Promise.any([this.ws&&this.ws.ping&&this.ws.once?this.waitForPingPong():this.waitForDummyReq(),new Promise(s=>setTimeout(()=>s(!1),this.pingTimeout))])||((n=this.ws)==null?void 0:n.readyState)===this._WebSocket.OPEN&&((i=this.ws)==null||i.close()))}async send(e){if(!this.connectionPromise)throw new gn(e,this.url);this.connectionPromise.then(()=>{var n;(n=this.ws)==null||n.send(e)})}async auth(e){const n=this.challenge;if(!n)throw new Error("can't perform auth, no challenge was received");return this.authPromise?this.authPromise:(this.authPromise=new Promise(async(i,r)=>{try{let s=await e(Ki(this.url,n)),a=setTimeout(()=>{let o=this.openEventPublishes.get(s.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(s.id))},this.publishTimeout);this.openEventPublishes.set(s.id,{resolve:i,reject:r,timeout:a}),this.send('["AUTH",'+JSON.stringify(s)+"]")}catch(s){console.warn("subscribe auth function failed:",s)}}),this.authPromise)}async publish(e){this.idleSince=void 0,this.ongoingOperations++;const n=new Promise((i,r)=>{const s=setTimeout(()=>{const a=this.openEventPublishes.get(e.id);a&&(a.reject(new Error("publish timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:i,reject:r,timeout:s})});return this.send('["EVENT",'+JSON.stringify(e)+"]"),this.ongoingOperations--,this.ongoingOperations===0&&(this.idleSince=Date.now()),n}async count(e,n){this.serial++;const i=(n==null?void 0:n.id)||"count:"+this.serial,r=new Promise((s,a)=>{this.openCountRequests.set(i,{resolve:s,reject:a})});return this.send('["COUNT","'+i+'",'+JSON.stringify(e).substring(1)),r}subscribe(e,n){n.label!=="<forced-ping>"&&(this.idleSince=void 0,this.ongoingOperations++);const i=this.prepareSubscription(e,n);return i.fire(),n.abort&&(n.abort.onabort=()=>i.close(String(n.abort.reason||"<aborted>"))),i}prepareSubscription(e,n){this.serial++;const i=n.id||(n.label?n.label+":":"sub:")+this.serial,r=new Yi(this,i,e,n);return this.openSubs.set(i,r),r}close(){var e,n,i;this.skipReconnection=!0,this.reconnectTimeoutHandle&&(clearTimeout(this.reconnectTimeoutHandle),this.reconnectTimeoutHandle=void 0),this.pingIntervalHandle&&(clearInterval(this.pingIntervalHandle),this.pingIntervalHandle=void 0),this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.idleSince=void 0,(e=this.onclose)==null||e.call(this),((n=this.ws)==null?void 0:n.readyState)===this._WebSocket.OPEN&&((i=this.ws)==null||i.close())}_onmessage(e){var r,s,a;const n=e.data;if(!n)return;const i=ji(n);if(i){const o=this.openSubs.get(i);if(!o)return;const c=Zi(n,"id"),u=(r=o.alreadyHaveEvent)==null?void 0:r.call(o,c);if((s=o.receivedEvent)==null||s.call(o,this,c),u)return}try{let o=JSON.parse(n);switch(o[0]){case"EVENT":{const c=this.openSubs.get(o[1]),u=o[2];this.verifyEvent(u)&&Fi(c.filters,u)&&c.onevent(u),(!c.lastEmitted||c.lastEmitted<u.created_at)&&(c.lastEmitted=u.created_at);return}case"COUNT":{const c=o[1],u=o[2],f=this.openCountRequests.get(c);f&&(f.resolve(u.count),this.openCountRequests.delete(c));return}case"EOSE":{const c=this.openSubs.get(o[1]);if(!c)return;c.receivedEose();return}case"OK":{const c=o[1],u=o[2],f=o[3],l=this.openEventPublishes.get(c);l&&(clearTimeout(l.timeout),u?l.resolve(f):l.reject(new Error(f)),this.openEventPublishes.delete(c));return}case"CLOSED":{const c=o[1],u=this.openSubs.get(c);if(!u)return;u.closed=!0,u.close(o[2]);return}case"NOTICE":{this.onnotice(o[1]);return}case"AUTH":{this.challenge=o[1],this.onauth&&this.auth(this.onauth);return}default:{const c=this.openSubs.get(o[1]);(a=c==null?void 0:c.oncustom)==null||a.call(c,o);return}}}catch(o){const[c,u,f]=JSON.parse(n);window.printer.maybe(f.pubkey,":: caught err",f,this.url,o);return}}},Yi=class{constructor(e,n,i,r){h(this,"relay");h(this,"id");h(this,"lastEmitted");h(this,"closed",!1);h(this,"eosed",!1);h(this,"filters");h(this,"alreadyHaveEvent");h(this,"receivedEvent");h(this,"onevent");h(this,"oneose");h(this,"onclose");h(this,"oncustom");h(this,"eoseTimeout");h(this,"eoseTimeoutHandle");if(i.length===0)throw new Error("subscription can't be created with zero filters");this.relay=e,this.filters=i,this.id=n,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||e.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.onevent=r.onevent||(s=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,s)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){var e;this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,(e=this.oneose)==null||e.call(this))}close(e="closed by caller"){var n;if(!this.closed&&this.relay.connected){try{this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]")}catch(i){if(!(i instanceof gn))throw i}this.closed=!0}this.relay.openSubs.delete(this.id),this.relay.ongoingOperations--,this.relay.ongoingOperations===0&&(this.relay.idleSince=Date.now()),(n=this.onclose)==null||n.call(this,e)}};const Gi=t=>(t[de]=!0,!0);let Ji=class{constructor(e){h(this,"relays",new Map);h(this,"seenOn",new Map);h(this,"trackRelays",!1);h(this,"verifyEvent");h(this,"enablePing");h(this,"enableReconnect");h(this,"automaticallyAuth");h(this,"trustedRelayURLs",new Set);h(this,"onRelayConnectionFailure");h(this,"onRelayConnectionSuccess");h(this,"allowConnectingToRelay");h(this,"maxWaitForConnection");h(this,"_WebSocket");this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation,this.enablePing=e.enablePing,this.enableReconnect=e.enableReconnect||!1,this.automaticallyAuth=e.automaticallyAuth,this.onRelayConnectionFailure=e.onRelayConnectionFailure,this.onRelayConnectionSuccess=e.onRelayConnectionSuccess,this.allowConnectingToRelay=e.allowConnectingToRelay,this.maxWaitForConnection=e.maxWaitForConnection||3e3}async ensureRelay(e,n){e=Re(e);let i=this.relays.get(e);if(i||(i=new zi(e,{verifyEvent:this.trustedRelayURLs.has(e)?Gi:this.verifyEvent,websocketImplementation:this._WebSocket,enablePing:this.enablePing,enableReconnect:this.enableReconnect}),i.onclose=()=>{this.relays.delete(e)},this.relays.set(e,i)),this.automaticallyAuth){const r=this.automaticallyAuth(e);r&&(i.onauth=r)}try{await i.connect({timeout:n==null?void 0:n.connectionTimeout,abort:n==null?void 0:n.abort})}catch(r){throw this.relays.delete(e),r}return i}close(e){e.map(Re).forEach(n=>{var i;(i=this.relays.get(n))==null||i.close(),this.relays.delete(n)})}subscribe(e,n,i){const r=[],s=[];for(let a=0;a<e.length;a++){const o=Re(e[a]);r.find(c=>c.url===o)||s.indexOf(o)===-1&&(s.push(o),r.push({url:o,filter:n