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