diff --git a/js/nostr.js b/js/nostr.js index 4ef33572..75d4d0b4 100644 --- a/js/nostr.js +++ b/js/nostr.js @@ -217,6 +217,76 @@ async function ensureNostrTools() { return cachedNostrTools || null; } +function isSimplePoolConstructor(candidate) { + if (typeof candidate !== "function") { + return false; + } + + const prototype = candidate.prototype; + if (!prototype || typeof prototype !== "object") { + return false; + } + + return typeof prototype.sub === "function" && typeof prototype.close === "function"; +} + +function unwrapSimplePool(candidate) { + if (!candidate) { + return null; + } + + if (isSimplePoolConstructor(candidate)) { + return candidate; + } + + if (typeof candidate === "object") { + if (isSimplePoolConstructor(candidate.SimplePool)) { + return candidate.SimplePool; + } + if (isSimplePoolConstructor(candidate.default)) { + return candidate.default; + } + } + + return null; +} + +function resolveSimplePoolConstructor(tools, scope = globalScope) { + const candidates = [ + tools?.SimplePool, + tools?.pool?.SimplePool, + tools?.pool, + tools?.SimplePool?.SimplePool, + tools?.SimplePool?.default, + tools?.pool?.default, + tools?.default?.SimplePool, + tools?.default?.pool?.SimplePool, + tools?.default?.pool, + ]; + + if (scope && typeof scope === "object") { + candidates.push(scope?.SimplePool); + candidates.push(scope?.pool?.SimplePool); + candidates.push(scope?.pool); + const scopedTools = + scope?.NostrTools && scope.NostrTools !== tools ? scope.NostrTools : null; + if (scopedTools) { + candidates.push(scopedTools.SimplePool); + candidates.push(scopedTools.pool?.SimplePool); + candidates.push(scopedTools.pool); + } + } + + for (const candidate of candidates) { + const resolved = unwrapSimplePool(candidate); + if (resolved) { + return resolved; + } + } + + return null; +} + let ingestLocalViewEventRef = null; async function loadIngestLocalViewEvent() { @@ -4292,10 +4362,34 @@ class NostrClient { } const tools = await ensureNostrTools(); - const SimplePool = tools?.SimplePool; + const SimplePool = resolveSimplePoolConstructor(tools); if (typeof SimplePool !== "function") { - const error = new Error("NostrTools SimplePool is unavailable."); + if (isDevMode) { + if (tools && typeof tools === "object") { + const availableKeys = Object.keys(tools).join(", "); + console.warn( + "[nostr] NostrTools helpers did not expose SimplePool. Available keys:", + availableKeys + ); + } else { + console.warn( + "[nostr] NostrTools helpers were unavailable. Check that nostr-tools bundles can load on this domain." + ); + } + if (nostrToolsBootstrapFailure) { + console.warn( + "[nostr] nostr-tools bootstrap failure details:", + nostrToolsBootstrapFailure + ); + } + } + const error = new Error( + "NostrTools SimplePool is unavailable. Verify that nostr-tools resources can load on this domain." + ); error.code = "nostr-simplepool-unavailable"; + if (nostrToolsBootstrapFailure) { + error.bootstrapFailure = nostrToolsBootstrapFailure; + } this.poolPromise = null; throw error; } diff --git a/js/nostrToolsBootstrap.js b/js/nostrToolsBootstrap.js index 6e496f68..2797b217 100644 --- a/js/nostrToolsBootstrap.js +++ b/js/nostrToolsBootstrap.js @@ -1,7 +1,38 @@ const REMOTE_IMPORT_TIMEOUT = 4500; const LOCAL_IMPORT_TIMEOUT = 2500; const SCRIPT_FALLBACK_TIMEOUT = 6000; -const CDN_BUNDLE_URL = "https://cdn.jsdelivr.net/npm/nostr-tools@2.10.4/lib/nostr.bundle.min.js"; +const CDN_BUNDLE_URL = + "https://cdn.jsdelivr.net/npm/nostr-tools@2.10.4/lib/nostr.bundle.min.js"; +const LOCAL_BUNDLE_RELATIVE_URL = "../vendor/nostr-tools.bundle.min.js"; + +const moduleUrl = + typeof import.meta !== "undefined" && import.meta?.url ? import.meta.url : null; + +const resolveRelativeUrl = (relativePath) => { + if (!relativePath) { + return relativePath; + } + if (/^[a-zA-Z][a-zA-Z\d+.-]*:/.test(relativePath)) { + return relativePath; + } + if (moduleUrl) { + try { + return new URL(relativePath, moduleUrl).href; + } catch (error) { + // Fall through to other resolution strategies + } + } + if (typeof window !== "undefined" && window?.location?.href) { + try { + return new URL(relativePath, window.location.href).href; + } catch (error) { + return relativePath; + } + } + return relativePath; +}; + +const LOCAL_BUNDLE_URL = resolveRelativeUrl(LOCAL_BUNDLE_RELATIVE_URL); let bootstrapPromise = null; @@ -137,6 +168,60 @@ const ensureGlobalReadyPromise = (scope, promise) => { } }; +const loadScriptBundle = (scope, url, label) => { + if (!scope?.document) { + return Promise.resolve({ + label, + ok: false, + timedOut: false, + duration: 0, + error: new Error("Document is unavailable for script loading."), + }); + } + + return withTimeout( + () => + new Promise((resolve, reject) => { + const { document } = scope; + const target = document.head || document.body || document.documentElement; + if (!target) { + reject(new Error("Unable to locate a DOM target for script injection.")); + return; + } + + const script = document.createElement("script"); + script.async = true; + script.src = url; + script.crossOrigin = "anonymous"; + + const cleanup = () => { + script.onload = null; + script.onerror = null; + if (script.parentNode) { + script.parentNode.removeChild(script); + } + }; + + script.onload = () => { + cleanup(); + resolve(scope?.NostrTools || null); + }; + script.onerror = (event) => { + cleanup(); + if (event?.error instanceof Error) { + reject(event.error); + } else { + reject(new Error(`nostr-tools bundle failed to load: ${url}`)); + } + }; + + target.appendChild(script); + }), + SCRIPT_FALLBACK_TIMEOUT, + label + ); +}; + export function bootstrapNostrTools() { if (bootstrapPromise) { return bootstrapPromise; @@ -256,38 +341,41 @@ export function bootstrapNostrTools() { !!scope.document && (resolvedModules.length === 0 || allDynamicTimedOut); if (shouldAttemptScriptFallback) { - const scriptLoadResult = await withTimeout( - () => - new Promise((resolve, reject) => { - const script = scope.document.createElement("script"); - script.src = CDN_BUNDLE_URL; - script.async = true; - script.onload = () => resolve(scope?.NostrTools || null); - script.onerror = () => - reject(new Error("nostr-tools CDN bundle failed to load")); - scope.document.head.appendChild(script); - }), - SCRIPT_FALLBACK_TIMEOUT, - "cdn-bundle" - ); + const scriptSources = [ + LOCAL_BUNDLE_URL + ? { url: LOCAL_BUNDLE_URL, label: "local-bundle" } + : null, + { url: CDN_BUNDLE_URL, label: "cdn-bundle" }, + ].filter(Boolean); - attempts.push({ - target: scriptLoadResult.label, - ok: scriptLoadResult.ok, - timedOut: !!scriptLoadResult.timedOut, - duration: scriptLoadResult.duration, - error: scriptLoadResult.ok - ? null - : toSerializableError(scriptLoadResult.error), - }); + for (const source of scriptSources) { + const scriptLoadResult = await loadScriptBundle( + scope, + source.url, + source.label + ); + + attempts.push({ + target: scriptLoadResult.label, + ok: scriptLoadResult.ok, + timedOut: !!scriptLoadResult.timedOut, + duration: scriptLoadResult.duration, + error: scriptLoadResult.ok + ? null + : toSerializableError(scriptLoadResult.error), + }); + + if (!scriptLoadResult.ok) { + continue; + } - if (scriptLoadResult.ok) { const extracted = extractToolsFromModule(scriptLoadResult.value); if (extracted && Object.keys(extracted).length > 0) { - resolvedModules.push({ source: "cdn-bundle", tools: extracted }); + resolvedModules.push({ source: source.label, tools: extracted }); if (!resolvedNip04 && hasWorkingNip04(extracted?.nip04)) { resolvedNip04 = extracted.nip04; } + break; } } } diff --git a/vendor/nostr-tools.LICENSE b/vendor/nostr-tools.LICENSE new file mode 100644 index 00000000..3c577b03 --- /dev/null +++ b/vendor/nostr-tools.LICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to \ No newline at end of file diff --git a/vendor/nostr-tools.bundle.min.js b/vendor/nostr-tools.bundle.min.js new file mode 100644 index 00000000..346a2699 --- /dev/null +++ b/vendor/nostr-tools.bundle.min.js @@ -0,0 +1,8 @@ +/** + * Minified by jsDelivr using Terser v5.37.0. + * Original file: /npm/nostr-tools@2.10.4/lib/nostr.bundle.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +"use strict";var NostrTools=(()=>{var t=Object.defineProperty,e=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,o=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},i={};function s(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function a(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function c(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")}o(i,{Relay:()=>Pr,SimplePool:()=>qr,finalizeEvent:()=>qe,fj:()=>xr,generateSecretKey:()=>Pe,getEventHash:()=>$e,getFilterLimit:()=>vr,getPublicKey:()=>Ce,kinds:()=>je,matchFilter:()=>br,matchFilters:()=>mr,mergeFilters:()=>Er,nip04:()=>Ro,nip05:()=>Oi,nip10:()=>Ci,nip11:()=>Mi,nip13:()=>Di,nip18:()=>Wi,nip19:()=>Mr,nip21:()=>Yi,nip25:()=>es,nip27:()=>os,nip28:()=>cs,nip30:()=>ps,nip39:()=>Es,nip42:()=>Lr,nip44:()=>As,nip47:()=>oa,nip57:()=>ca,nip59:()=>pa,nip98:()=>Ua,parseReferences:()=>Oo,serializeEvent:()=>Ne,sortEvents:()=>de,utils:()=>Se,validateEvent:()=>fe,verifiedSymbol:()=>le,verifyEvent:()=>Me});var u="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,l=t=>t instanceof Uint8Array,h=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),f=(t,e)=>t<<32-e|t>>>e;if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");function d(t){if("string"==typeof t&&(t=function(t){if("string"!=typeof t)throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}(t)),!l(t))throw new Error("expected Uint8Array, got "+typeof t);return t}var p=class{clone(){return this._cloneInto()}};function g(t){const e=e=>t().update(d(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function y(t=32){if(u&&"function"==typeof u.getRandomValues)return u.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}var w=class extends p{constructor(t,e,n,r){super(),this.blockLen=t,this.outputLen=e,this.padOffset=n,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=h(this.buffer)}update(t){c(this);const{view:e,buffer:n,blockLen:r}=this,o=(t=d(t)).length;for(let i=0;ir-i&&(this.process(n,0),i=0);for(let t=i;t>o&i),a=Number(n&i),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}(n,r-8,BigInt(8*this.length),o),this.process(n,0);const s=h(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=u/4,f=this.get();if(l>f.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;tt&e^t&n^e&n,m=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),v=new Uint32Array(64),x=class extends w{constructor(){super(64,32,8,!1),this.A=0|E[0],this.B=0|E[1],this.C=0|E[2],this.D=0|E[3],this.E=0|E[4],this.F=0|E[5],this.G=0|E[6],this.H=0|E[7]}get(){const{A:t,B:e,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[t,e,n,r,o,i,s,a]}set(t,e,n,r,o,i,s,a){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(t,e){for(let n=0;n<16;n++,e+=4)v[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=v[t-15],n=v[t-2],r=f(e,7)^f(e,18)^e>>>3,o=f(n,17)^f(n,19)^n>>>10;v[t]=o+v[t-7]+r+v[t-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let t=0;t<64;t++){const e=u+(f(s,6)^f(s,11)^f(s,25))+((l=s)&a^~l&c)+m[t]+v[t]|0,h=(f(n,2)^f(n,13)^f(n,22))+b(n,r,o)|0;u=c,c=a,a=s,s=i+e|0,i=o,o=r,r=n,n=e+h|0}var l;n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,o,i,s,a,c,u)}roundClean(){v.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},A=g((()=>new x)),k={};o(k,{bitGet:()=>F,bitLen:()=>D,bitMask:()=>V,bitSet:()=>K,bytesToHex:()=>O,bytesToNumberBE:()=>N,bytesToNumberLE:()=>$,concatBytes:()=>M,createHmacDrbg:()=>G,ensureBytes:()=>q,equalBytes:()=>j,hexToBytes:()=>_,hexToNumber:()=>T,numberToBytesBE:()=>H,numberToBytesLE:()=>P,numberToHexUnpadded:()=>R,numberToVarBytesBE:()=>C,utf8ToBytes:()=>z,validateObject:()=>Y});var S=BigInt(0),B=BigInt(1),U=BigInt(2),I=t=>t instanceof Uint8Array,L=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function O(t){if(!I(t))throw new Error("Uint8Array expected");let e="";for(let n=0;nt+e.length),0));let n=0;return t.forEach((t=>{if(!I(t))throw new Error("Uint8Array expected");e.set(t,n),n+=t.length})),e}function j(t,e){if(t.length!==e.length)return!1;for(let n=0;nS;t>>=B,e+=1);return e}function F(t,e){return t>>BigInt(e)&B}var K=(t,e,n)=>t|(n?B:S)<(U<new Uint8Array(t),Z=t=>Uint8Array.from(t);function G(t,e,n){if("number"!=typeof t||t<2)throw new Error("hashLen must be a number");if("number"!=typeof e||e<2)throw new Error("qByteLen must be a number");if("function"!=typeof n)throw new Error("hmacFn must be a function");let r=W(t),o=W(t),i=0;const s=()=>{r.fill(1),o.fill(0),i=0},a=(...t)=>n(o,r,...t),c=(t=W())=>{o=a(Z([0]),t),r=a(),0!==t.length&&(o=a(Z([1]),t),r=a())},u=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let t=0;const n=[];for(;t{let n;for(s(),c(t);!(n=e(u()));)c();return s(),n}}var J={bigint:t=>"bigint"==typeof t,function:t=>"function"==typeof t,boolean:t=>"boolean"==typeof t,string:t=>"string"==typeof t,stringOrUint8Array:t=>"string"==typeof t||t instanceof Uint8Array,isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>"function"==typeof t&&Number.isSafeInteger(t.outputLen)};function Y(t,e,n={}){const r=(e,n,r)=>{const o=J[n];if("function"!=typeof o)throw new Error(`Invalid validator "${n}", expected function`);const i=t[e];if(!(r&&void 0===i||o(i,t)))throw new Error(`Invalid param ${String(e)}=${i} (${typeof i}), expected ${n}`)};for(const[t,n]of Object.entries(e))r(t,n,!1);for(const[t,e]of Object.entries(n))r(t,e,!0);return t}var Q=BigInt(0),X=BigInt(1),tt=BigInt(2),et=BigInt(3),nt=BigInt(4),rt=BigInt(5),ot=BigInt(8);BigInt(9),BigInt(16);function it(t,e){const n=t%e;return n>=Q?n:e+n}function st(t,e,n){if(n<=Q||e 0");if(n===X)return Q;let r=X;for(;e>Q;)e&X&&(r=r*t%n),t=t*t%n,e>>=X;return r}function at(t,e,n){let r=t;for(;e-- >Q;)r*=r,r%=n;return r}function ct(t,e){if(t===Q||e<=Q)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let n=it(t,e),r=e,o=Q,i=X,s=X,a=Q;for(;n!==Q;){const t=r/n,e=r%n,c=o-s*t,u=i-a*t;r=n,n=e,o=s,i=a,s=c,a=u}if(r!==X)throw new Error("invert: does not exist");return it(o,e)}function ut(t){if(t%nt===et){const e=(t+X)/nt;return function(t,n){const r=t.pow(n,e);if(!t.eql(t.sqr(r),n))throw new Error("Cannot find square root");return r}}if(t%ot===rt){const e=(t-rt)/ot;return function(t,n){const r=t.mul(n,tt),o=t.pow(r,e),i=t.mul(n,o),s=t.mul(t.mul(i,tt),o),a=t.mul(i,t.sub(s,t.ONE));if(!t.eql(t.sqr(a),n))throw new Error("Cannot find square root");return a}}return function(t){const e=(t-X)/tt;let n,r,o;for(n=t-X,r=0;n%tt===Q;n/=tt,r++);for(o=tt;o(t[e]="function",t)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"})),Y(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ht(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}var{bytesToNumberBE:wt,hexToBytes:bt}=k,mt={Err:class extends Error{constructor(t=""){super(t)}},_parseInt(t){const{Err:e}=mt;if(t.length<2||2!==t[0])throw new e("Invalid signature integer tag");const n=t[1],r=t.subarray(2,n+2);if(!n||r.length!==n)throw new e("Invalid signature integer: wrong length");if(128&r[0])throw new e("Invalid signature integer: negative");if(0===r[0]&&!(128&r[1]))throw new e("Invalid signature integer: unnecessary leading zero");return{d:wt(r),l:t.subarray(n+2)}},toSig(t){const{Err:e}=mt,n="string"==typeof t?bt(t):t;if(!(n instanceof Uint8Array))throw new Error("ui8a expected");let r=n.length;if(r<2||48!=n[0])throw new e("Invalid signature tag");if(n[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:o,l:i}=mt._parseInt(n.subarray(2)),{d:s,l:a}=mt._parseInt(i);if(a.length)throw new e("Invalid signature: left bytes after parsing");return{r:o,s:s}},hexFromSig(t){const e=t=>8&Number.parseInt(t[0],16)?"00"+t:t,n=t=>{const e=t.toString(16);return 1&e.length?`0${e}`:e},r=e(n(t.s)),o=e(n(t.r)),i=r.length/2,s=o.length/2,a=n(i),c=n(s);return`30${n(s+i+4)}02${c}${o}02${a}${r}`}},Et=BigInt(0),vt=BigInt(1),xt=(BigInt(2),BigInt(3));BigInt(4);function At(t){const e=function(t){const e=yt(t);Y(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:n,Fp:r,a:o}=e;if(n){if(!r.eql(o,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}(t),{Fp:n}=e,r=e.toBytes||((t,e,r)=>{const o=e.toAffine();return M(Uint8Array.from([4]),n.toBytes(o.x),n.toBytes(o.y))}),o=e.fromBytes||(t=>{const e=t.subarray(1);return{x:n.fromBytes(e.subarray(0,n.BYTES)),y:n.fromBytes(e.subarray(n.BYTES,2*n.BYTES))}});function i(t){const{a:r,b:o}=e,i=n.sqr(t),s=n.mul(i,t);return n.add(n.add(s,n.mul(t,r)),o)}if(!n.eql(n.sqr(e.Gy),i(e.Gx)))throw new Error("bad generator point: equation left != right");function s(t){return"bigint"==typeof t&&Etn.eql(t,n.ZERO);return o(e)&&o(r)?h.ZERO:new h(e,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(t){const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(h.fromAffine)}static fromHex(t){const e=h.fromAffine(o(q("pointHex",t)));return e.assertValidity(),e}static fromPrivateKey(t){return h.BASE.multiply(c(t))}_setWindowSize(t){this._WINDOW_SIZE=t,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!n.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:t,y:r}=this.toAffine();if(!n.isValid(t)||!n.isValid(r))throw new Error("bad point: x or y not FE");const o=n.sqr(r),s=i(t);if(!n.eql(o,s))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:t}=this.toAffine();if(n.isOdd)return!n.isOdd(t);throw new Error("Field doesn't support isOdd")}equals(t){l(t);const{px:e,py:r,pz:o}=this,{px:i,py:s,pz:a}=t,c=n.eql(n.mul(e,a),n.mul(i,o)),u=n.eql(n.mul(r,a),n.mul(s,o));return c&&u}negate(){return new h(this.px,n.neg(this.py),this.pz)}double(){const{a:t,b:r}=e,o=n.mul(r,xt),{px:i,py:s,pz:a}=this;let c=n.ZERO,u=n.ZERO,l=n.ZERO,f=n.mul(i,i),d=n.mul(s,s),p=n.mul(a,a),g=n.mul(i,s);return g=n.add(g,g),l=n.mul(i,a),l=n.add(l,l),c=n.mul(t,l),u=n.mul(o,p),u=n.add(c,u),c=n.sub(d,u),u=n.add(d,u),u=n.mul(c,u),c=n.mul(g,c),l=n.mul(o,l),p=n.mul(t,p),g=n.sub(f,p),g=n.mul(t,g),g=n.add(g,l),l=n.add(f,f),f=n.add(l,f),f=n.add(f,p),f=n.mul(f,g),u=n.add(u,f),p=n.mul(s,a),p=n.add(p,p),f=n.mul(p,g),c=n.sub(c,f),l=n.mul(p,d),l=n.add(l,l),l=n.add(l,l),new h(c,u,l)}add(t){l(t);const{px:r,py:o,pz:i}=this,{px:s,py:a,pz:c}=t;let u=n.ZERO,f=n.ZERO,d=n.ZERO;const p=e.a,g=n.mul(e.b,xt);let y=n.mul(r,s),w=n.mul(o,a),b=n.mul(i,c),m=n.add(r,o),E=n.add(s,a);m=n.mul(m,E),E=n.add(y,w),m=n.sub(m,E),E=n.add(r,i);let v=n.add(s,c);return E=n.mul(E,v),v=n.add(y,b),E=n.sub(E,v),v=n.add(o,i),u=n.add(a,c),v=n.mul(v,u),u=n.add(w,b),v=n.sub(v,u),d=n.mul(p,E),u=n.mul(g,b),d=n.add(u,d),u=n.sub(w,d),d=n.add(w,d),f=n.mul(u,d),w=n.add(y,y),w=n.add(w,y),b=n.mul(p,b),E=n.mul(g,E),w=n.add(w,b),b=n.sub(y,b),b=n.mul(p,b),E=n.add(E,b),y=n.mul(w,E),f=n.add(f,y),y=n.mul(v,E),u=n.mul(m,u),u=n.sub(u,y),y=n.mul(m,w),d=n.mul(v,d),d=n.add(d,y),new h(u,f,d)}subtract(t){return this.add(t.negate())}is0(){return this.equals(h.ZERO)}wNAF(t){return d.wNAFCached(this,u,t,(t=>{const e=n.invertBatch(t.map((t=>t.pz)));return t.map(((t,n)=>t.toAffine(e[n]))).map(h.fromAffine)}))}multiplyUnsafe(t){const r=h.ZERO;if(t===Et)return r;if(a(t),t===vt)return this;const{endo:o}=e;if(!o)return d.unsafeLadder(this,t);let{k1neg:i,k1:s,k2neg:c,k2:u}=o.splitScalar(t),l=r,f=r,p=this;for(;s>Et||u>Et;)s&vt&&(l=l.add(p)),u&vt&&(f=f.add(p)),p=p.double(),s>>=vt,u>>=vt;return i&&(l=l.negate()),c&&(f=f.negate()),f=new h(n.mul(f.px,o.beta),f.py,f.pz),l.add(f)}multiply(t){a(t);let r,o,i=t;const{endo:s}=e;if(s){const{k1neg:t,k1:e,k2neg:a,k2:c}=s.splitScalar(i);let{p:u,f:l}=this.wNAF(e),{p:f,f:p}=this.wNAF(c);u=d.constTimeNegate(t,u),f=d.constTimeNegate(a,f),f=new h(n.mul(f.px,s.beta),f.py,f.pz),r=u.add(f),o=l.add(p)}else{const{p:t,f:e}=this.wNAF(i);r=t,o=e}return h.normalizeZ([r,o])[0]}multiplyAndAddUnsafe(t,e,n){const r=h.BASE,o=(t,e)=>e!==Et&&e!==vt&&t.equals(r)?t.multiply(e):t.multiplyUnsafe(e),i=o(this,e).add(o(t,n));return i.is0()?void 0:i}toAffine(t){const{px:e,py:r,pz:o}=this,i=this.is0();null==t&&(t=i?n.ONE:n.inv(o));const s=n.mul(e,t),a=n.mul(r,t),c=n.mul(o,t);if(i)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw new Error("invZ was invalid");return{x:s,y:a}}isTorsionFree(){const{h:t,isTorsionFree:n}=e;if(t===vt)return!0;if(n)return n(h,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:t,clearCofactor:n}=e;return t===vt?this:n?n(h,this):this.multiplyUnsafe(e.h)}toRawBytes(t=!0){return this.assertValidity(),r(h,this,t)}toHex(t=!0){return O(this.toRawBytes(t))}}h.BASE=new h(e.Gx,e.Gy,n.ONE),h.ZERO=new h(n.ZERO,n.ONE,n.ZERO);const f=e.nBitLength,d=function(t,e){const n=(t,e)=>{const n=e.negate();return t?n:e},r=t=>({windows:Math.ceil(e/t)+1,windowSize:2**(t-1)});return{constTimeNegate:n,unsafeLadder(e,n){let r=t.ZERO,o=e;for(;n>pt;)n>&&(r=r.add(o)),o=o.double(),n>>=gt;return r},precomputeWindow(t,e){const{windows:n,windowSize:o}=r(e),i=[];let s=t,a=s;for(let t=0;t>=f,r>a&&(r-=h,i+=gt);const s=e,d=e+Math.abs(r)-1,p=t%2!=0,g=r<0;0===r?u=u.add(n(p,o[s])):c=c.add(n(g,o[d]))}return{p:c,f:u}},wNAFCached(t,e,n,r){const o=t._WINDOW_SIZE||1;let i=e.get(t);return i||(i=this.precomputeWindow(t,o),1!==o&&e.set(t,r(i))),this.wNAF(o,i,n)}}}(h,e.endo?Math.ceil(f/2):f);return{CURVE:e,ProjectivePoint:h,normPrivateKeyToScalar:c,weierstrassEquation:i,isWithinCurveOrder:s}}function kt(t){const e=function(t){const e=yt(t);return Y(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}(t),{Fp:n,n:r}=e,o=n.BYTES+1,i=2*n.BYTES+1;function s(t){return it(t,r)}function a(t){return ct(t,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=At({...e,toBytes(t,e,r){const o=e.toAffine(),i=n.toBytes(o.x),s=M;return r?s(Uint8Array.from([e.hasEvenY()?2:3]),i):s(Uint8Array.from([4]),i,n.toBytes(o.y))},fromBytes(t){const e=t.length,r=t[0],s=t.subarray(1);if(e!==o||2!==r&&3!==r){if(e===i&&4===r){return{x:n.fromBytes(s.subarray(0,n.BYTES)),y:n.fromBytes(s.subarray(n.BYTES,2*n.BYTES))}}throw new Error(`Point of length ${e} was invalid. Expected ${o} compressed bytes or ${i} uncompressed bytes`)}{const t=N(s);if(!(Et<(a=t)&&aO(H(t,e.nByteLength));function d(t){return t>r>>vt}const p=(t,e,n)=>N(t.slice(e,n));class g{constructor(t,e,n){this.r=t,this.s=e,this.recovery=n,this.assertValidity()}static fromCompact(t){const n=e.nByteLength;return t=q("compactSignature",t,2*n),new g(p(t,0,n),p(t,n,2*n))}static fromDER(t){const{r:e,s:n}=mt.toSig(q("DER",t));return new g(e,n)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(t){return new g(this.r,this.s,t)}recoverPublicKey(t){const{r:r,s:o,recovery:i}=this,u=m(q("msgHash",t));if(null==i||![0,1,2,3].includes(i))throw new Error("recovery id invalid");const l=2===i||3===i?r+e.n:r;if(l>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const h=1&i?"03":"02",d=c.fromHex(h+f(l)),p=a(l),g=s(-u*p),y=s(o*p),w=c.BASE.multiplyAndAddUnsafe(d,g,y);if(!w)throw new Error("point at infinify");return w.assertValidity(),w}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,s(-this.s),this.recovery):this}toDERRawBytes(){return _(this.toDERHex())}toDERHex(){return mt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return _(this.toCompactHex())}toCompactHex(){return f(this.r)+f(this.s)}}const y={isValidPrivateKey(t){try{return u(t),!0}catch(t){return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const t=dt(e.n);return function(t,e,n=!1){const r=t.length,o=ft(e),i=dt(e);if(r<16||r1024)throw new Error(`expected ${i}-1024 bytes of input, got ${r}`);const s=it(n?N(t):$(t),e-X)+X;return n?P(s,o):H(s,o)}(e.randomBytes(t),e.n)},precompute:(t=8,e=c.BASE)=>(e._setWindowSize(t),e.multiply(BigInt(3)),e)};function w(t){const e=t instanceof Uint8Array,n="string"==typeof t,r=(e||n)&&t.length;return e?r===o||r===i:n?r===2*o||r===2*i:t instanceof c}const b=e.bits2int||function(t){const n=N(t),r=8*t.length-e.nBitLength;return r>0?n>>BigInt(r):n},m=e.bits2int_modN||function(t){return s(b(t))},E=V(e.nBitLength);function v(t){if("bigint"!=typeof t)throw new Error("bigint expected");if(!(Et<=t&&tt in o)))throw new Error("sign() legacy options not supported");const{hash:i,randomBytes:l}=e;let{lowS:f,prehash:p,extraEntropy:y}=o;null==f&&(f=!0),t=q("msgHash",t),p&&(t=q("prehashed msgHash",i(t)));const w=m(t),E=u(r),x=[v(E),v(w)];if(null!=y){const t=!0===y?l(n.BYTES):y;x.push(q("extraEntropy",t))}const k=M(...x),S=w;return{seed:k,k2sig:function(t){const e=b(t);if(!h(e))return;const n=a(e),r=c.BASE.multiply(e).toAffine(),o=s(r.x);if(o===Et)return;const i=s(n*s(S+o*E));if(i===Et)return;let u=(r.x===o?0:2)|Number(r.y&vt),l=i;return f&&d(i)&&(l=function(t){return d(t)?s(-t):t}(i),u^=1),new g(o,l,u)}}}const A={lowS:e.lowS,prehash:!1},k={lowS:e.lowS,prehash:!1};return c.BASE._setWindowSize(8),{CURVE:e,getPublicKey:function(t,e=!0){return c.fromPrivateKey(t).toRawBytes(e)},getSharedSecret:function(t,e,n=!0){if(w(t))throw new Error("first arg must be private key");if(!w(e))throw new Error("second arg must be public key");return c.fromHex(e).multiply(u(t)).toRawBytes(n)},sign:function(t,n,r=A){const{seed:o,k2sig:i}=x(t,n,r),s=e;return G(s.hash.outputLen,s.nByteLength,s.hmac)(o,i)},verify:function(t,n,r,o=k){const i=t;if(n=q("msgHash",n),r=q("publicKey",r),"strict"in o)throw new Error("options.strict was renamed to lowS");const{lowS:u,prehash:l}=o;let h,f;try{if("string"==typeof i||i instanceof Uint8Array)try{h=g.fromDER(i)}catch(t){if(!(t instanceof mt.Err))throw t;h=g.fromCompact(i)}else{if("object"!=typeof i||"bigint"!=typeof i.r||"bigint"!=typeof i.s)throw new Error("PARSE");{const{r:t,s:e}=i;h=new g(t,e)}}f=c.fromHex(r)}catch(t){if("PARSE"===t.message)throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(u&&h.hasHighS())return!1;l&&(n=e.hash(n));const{r:d,s:p}=h,y=m(n),w=a(p),b=s(y*w),E=s(d*w),v=c.BASE.multiplyAndAddUnsafe(f,b,E)?.toAffine();return!!v&&s(v.x)===d},ProjectivePoint:c,Signature:g,utils:y}}var St=class extends p{constructor(t,e){super(),this.finished=!1,this.destroyed=!1,function(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");s(t.outputLen),s(t.blockLen)}(t);const n=d(e);if(this.iHash=t.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,o=new Uint8Array(r);o.set(n.length>r?t.create().update(n).digest():n);for(let t=0;tnew St(t,e).update(n).digest();function Ut(t){return{hash:t,hmac:(e,...n)=>Bt(t,e,function(...t){const e=new Uint8Array(t.reduce(((t,e)=>t+e.length),0));let n=0;return t.forEach((t=>{if(!l(t))throw new Error("Uint8Array expected");e.set(t,n),n+=t.length})),e}(...n)),randomBytes:y}}Bt.create=(t,e)=>new St(t,e);var It=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Lt=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ot=BigInt(1),Rt=BigInt(2),Tt=(t,e)=>(t+e/Rt)/e;function _t(t){const e=It,n=BigInt(3),r=BigInt(6),o=BigInt(11),i=BigInt(22),s=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,h=at(l,n,e)*l%e,f=at(h,n,e)*l%e,d=at(f,Rt,e)*u%e,p=at(d,o,e)*d%e,g=at(p,i,e)*p%e,y=at(g,a,e)*g%e,w=at(y,c,e)*y%e,b=at(w,a,e)*g%e,m=at(b,n,e)*l%e,E=at(m,s,e)*p%e,v=at(E,r,e)*u%e,x=at(v,Rt,e);if(!Nt.eql(Nt.sqr(x),t))throw new Error("Cannot find square root");return x}var Nt=function(t,e,n=!1,r={}){if(t<=Q)throw new Error(`Expected Field ORDER > 0, got ${t}`);const{nBitLength:o,nByteLength:i}=ht(t,e);if(i>2048)throw new Error("Field lengths over 2048 bytes are not supported");const s=ut(t),a=Object.freeze({ORDER:t,BITS:o,BYTES:i,MASK:V(o),ZERO:Q,ONE:X,create:e=>it(e,t),isValid:e=>{if("bigint"!=typeof e)throw new Error("Invalid field element: expected bigint, got "+typeof e);return Q<=e&&et===Q,isOdd:t=>(t&X)===X,neg:e=>it(-e,t),eql:(t,e)=>t===e,sqr:e=>it(e*e,t),add:(e,n)=>it(e+n,t),sub:(e,n)=>it(e-n,t),mul:(e,n)=>it(e*n,t),pow:(t,e)=>function(t,e,n){if(n 0");if(n===Q)return t.ONE;if(n===X)return e;let r=t.ONE,o=e;for(;n>Q;)n&X&&(r=t.mul(r,o)),o=t.sqr(o),n>>=X;return r}(a,t,e),div:(e,n)=>it(e*ct(n,t),t),sqrN:t=>t*t,addN:(t,e)=>t+e,subN:(t,e)=>t-e,mulN:(t,e)=>t*e,inv:e=>ct(e,t),sqrt:r.sqrt||(t=>s(a,t)),invertBatch:t=>function(t,e){const n=new Array(e.length),r=e.reduce(((e,r,o)=>t.is0(r)?e:(n[o]=e,t.mul(e,r))),t.ONE),o=t.inv(r);return e.reduceRight(((e,r,o)=>t.is0(r)?e:(n[o]=t.mul(e,n[o]),t.mul(e,r))),o),n}(a,t),cmov:(t,e,n)=>n?e:t,toBytes:t=>n?P(t,i):H(t,i),fromBytes:t=>{if(t.length!==i)throw new Error(`Fp.fromBytes: expected ${i}, got ${t.length}`);return n?$(t):N(t)}});return Object.freeze(a)}(It,void 0,void 0,{sqrt:_t}),$t=function(t,e){const n=e=>kt({...t,...Ut(e)});return Object.freeze({...n(e),create:n})}({a:BigInt(0),b:BigInt(7),Fp:Nt,n:Lt,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Lt,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-Ot*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),o=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,s=BigInt("0x100000000000000000000000000000000"),a=Tt(i*t,e),c=Tt(-r*t,e);let u=it(t-a*n-c*o,e),l=it(-a*r-c*i,e);const h=u>s,f=l>s;if(h&&(u=e-u),f&&(l=e-l),u>s||l>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:u,k2neg:f,k2:l}}}},A),Ht=BigInt(0),Pt=t=>"bigint"==typeof t&&Htt.charCodeAt(0))));n=M(e,e),Ct[t]=n}return A(M(n,...e))}var Mt=t=>t.toRawBytes(!0).slice(1),jt=t=>H(t,32),zt=t=>it(t,It),Dt=t=>it(t,Lt),Ft=$t.ProjectivePoint;function Kt(t){let e=$t.utils.normPrivateKeyToScalar(t),n=Ft.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:Dt(-e),bytes:Mt(n)}}function Vt(t){if(!Pt(t))throw new Error("bad x: need 0 < x < p");const e=zt(t*t);let n=_t(zt(e*t+BigInt(7)));n%Rt!==Ht&&(n=zt(-n));const r=new Ft(t,n,Ot);return r.assertValidity(),r}function Wt(...t){return Dt(N(qt("BIP0340/challenge",...t)))}function Zt(t){return Kt(t).bytes}function Gt(t,e,n=y(32)){const r=q("message",t),{bytes:o,scalar:i}=Kt(e),s=q("auxRand",n,32),a=jt(i^N(qt("BIP0340/aux",s))),c=qt("BIP0340/nonce",a,o,r),u=Dt(N(c));if(u===Ht)throw new Error("sign failed: k is zero");const{bytes:l,scalar:h}=Kt(u),f=Wt(l,o,r),d=new Uint8Array(64);if(d.set(l,0),d.set(jt(Dt(h+f*i)),32),!Jt(d,r,o))throw new Error("sign: Invalid signature produced");return d}function Jt(t,e,n){const r=q("signature",t,64),o=q("message",e),i=q("publicKey",n,32);try{const t=Vt(N(i)),e=N(r.subarray(0,32));if(!Pt(e))return!1;const n=N(r.subarray(32,64));if(!("bigint"==typeof(u=n)&&Ht({getPublicKey:Zt,sign:Gt,verify:Jt,utils:{randomPrivateKey:$t.utils.randomPrivateKey,lift_x:Vt,pointToBytes:Mt,numberToBytesBE:H,bytesToNumberBE:N,taggedHash:qt,mod:it}}))(),Qt="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0,Xt=t=>t instanceof Uint8Array,te=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),ee=(t,e)=>t<<32-e|t>>>e;if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");var ne=Array.from({length:256},((t,e)=>e.toString(16).padStart(2,"0")));function re(t){if(!Xt(t))throw new Error("Uint8Array expected");let e="";for(let n=0;nt+e.length),0));let n=0;return t.forEach((t=>{if(!Xt(t))throw new Error("Uint8Array expected");e.set(t,n),n+=t.length})),e}var ae=class{clone(){return this._cloneInto()}};function ce(t){const e=e=>t().update(ie(e)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function ue(t=32){if(Qt&&"function"==typeof Qt.getRandomValues)return Qt.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}var le=Symbol("verified"),he=t=>t instanceof Object;function fe(t){if(!he(t))return!1;if("number"!=typeof t.kind)return!1;if("string"!=typeof t.content)return!1;if("number"!=typeof t.created_at)return!1;if("string"!=typeof t.pubkey)return!1;if(!t.pubkey.match(/^[a-f0-9]{64}$/))return!1;if(!Array.isArray(t.tags))return!1;for(let e=0;et.created_at!==e.created_at?e.created_at-t.created_at:t.id.localeCompare(e.id)))}function pe(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function ge(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}var ye={number:pe,bool:function(t){if("boolean"!=typeof t)throw new Error(`Expected boolean, not ${t}`)},bytes:ge,hash:function(t){if("function"!=typeof t||"function"!=typeof t.create)throw new Error("Hash should be wrapped by utils.wrapConstructor");pe(t.outputLen),pe(t.blockLen)},exists:function(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")},output:function(t,e){ge(t);const n=e.outputLen;if(t.lengthr-i&&(this.process(n,0),i=0);for(let t=i;t>o&i),a=Number(n&i),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}(n,r-8,BigInt(8*this.length),o),this.process(n,0);const s=te(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let t=0;tt&e^t&n^e&n,me=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ee=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ve=new Uint32Array(64),xe=class extends we{constructor(){super(64,32,8,!1),this.A=0|Ee[0],this.B=0|Ee[1],this.C=0|Ee[2],this.D=0|Ee[3],this.E=0|Ee[4],this.F=0|Ee[5],this.G=0|Ee[6],this.H=0|Ee[7]}get(){const{A:t,B:e,C:n,D:r,E:o,F:i,G:s,H:a}=this;return[t,e,n,r,o,i,s,a]}set(t,e,n,r,o,i,s,a){this.A=0|t,this.B=0|e,this.C=0|n,this.D=0|r,this.E=0|o,this.F=0|i,this.G=0|s,this.H=0|a}process(t,e){for(let n=0;n<16;n++,e+=4)ve[n]=t.getUint32(e,!1);for(let t=16;t<64;t++){const e=ve[t-15],n=ve[t-2],r=ee(e,7)^ee(e,18)^e>>>3,o=ee(n,17)^ee(n,19)^n>>>10;ve[t]=o+ve[t-7]+r+ve[t-16]|0}let{A:n,B:r,C:o,D:i,E:s,F:a,G:c,H:u}=this;for(let t=0;t<64;t++){const e=u+(ee(s,6)^ee(s,11)^ee(s,25))+((l=s)&a^~l&c)+me[t]+ve[t]|0,h=(ee(n,2)^ee(n,13)^ee(n,22))+be(n,r,o)|0;u=c,c=a,a=s,s=i+e|0,i=o,o=r,r=n,n=e+h|0}var l;n=n+this.A|0,r=r+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,o,i,s,a,c,u)}roundClean(){ve.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}},Ae=class extends xe{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}},ke=ce((()=>new xe)),Se=(ce((()=>new Ae)),{});o(Se,{Queue:()=>_e,QueueNode:()=>Te,binarySearch:()=>Re,insertEventIntoAscendingList:()=>Oe,insertEventIntoDescendingList:()=>Le,normalizeURL:()=>Ie,utf8Decoder:()=>Be,utf8Encoder:()=>Ue});var Be=new TextDecoder("utf-8"),Ue=new TextEncoder;function Ie(t){-1===t.indexOf("://")&&(t="wss://"+t);let e=new URL(t);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),("80"===e.port&&"ws:"===e.protocol||"443"===e.port&&"wss:"===e.protocol)&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}function Le(t,e){const[n,r]=Re(t,(t=>e.id===t.id?0:e.created_at===t.created_at?-1:t.created_at-e.created_at));return r||t.splice(n,0,e),t}function Oe(t,e){const[n,r]=Re(t,(t=>e.id===t.id?0:e.created_at===t.created_at?-1:e.created_at-t.created_at));return r||t.splice(n,0,e),t}function Re(t,e){let n=0,r=t.length-1;for(;n<=r;){const o=Math.floor((n+r)/2),i=e(t[o]);if(0===i)return[o,!0];i<0?r=o-1:n=o+1}return[n,!1]}var Te=class{value;next=null;prev=null;constructor(t){this.value=t}},_e=class{first;last;constructor(){this.first=null,this.last=null}enqueue(t){const e=new Te(t);return this.last?this.last===this.first?(this.last=e,this.last.prev=this.first,this.first.next=e):(e.prev=this.last,this.last.next=e,this.last=e):(this.first=e,this.last=e),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const t=this.first;return this.first=t.next,t.value}};function Ne(t){if(!fe(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 $e(t){return re(ke(Ue.encode(Ne(t))))}var He=new class{generateSecretKey(){return Yt.utils.randomPrivateKey()}getPublicKey(t){return re(Yt.getPublicKey(t))}finalizeEvent(t,e){const n=t;return n.pubkey=re(Yt.getPublicKey(e)),n.id=$e(n),n.sig=re(Yt.sign($e(n),e)),n[le]=!0,n}verifyEvent(t){if("boolean"==typeof t[le])return t[le];const e=$e(t);if(e!==t.id)return t[le]=!1,!1;try{const n=Yt.verify(t.sig,e,t.pubkey);return t[le]=n,n}catch(e){return t[le]=!1,!1}}},Pe=He.generateSecretKey,Ce=He.getPublicKey,qe=He.finalizeEvent,Me=He.verifyEvent,je={};function ze(t){return 1e3<=t&&t<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(t)}function De(t){return[0,3].includes(t)||1e4<=t&&t<2e4}function Fe(t){return 2e4<=t&&t<3e4}function Ke(t){return 3e4<=t&&t<4e4}function Ve(t){return ze(t)?"regular":De(t)?"replaceable":Fe(t)?"ephemeral":Ke(t)?"parameterized":"unknown"}function We(t,e){const n=e instanceof Array?e:[e];return fe(t)&&n.includes(t.kind)||!1}o(je,{Application:()=>sr,BadgeAward:()=>nn,BadgeDefinition:()=>Xn,BlockedRelaysList:()=>Nn,BookmarkList:()=>Rn,Bookmarksets:()=>Jn,Calendar:()=>dr,CalendarEventRSVP:()=>pr,ChannelCreation:()=>an,ChannelHideMessage:()=>ln,ChannelMessage:()=>un,ChannelMetadata:()=>cn,ChannelMuteUser:()=>hn,ClassifiedListing:()=>ur,ClientAuth:()=>zn,CommunitiesList:()=>Tn,CommunityDefinition:()=>wr,CommunityPostApproval:()=>En,Contacts:()=>Ye,CreateOrUpdateProduct:()=>nr,CreateOrUpdateStall:()=>er,Curationsets:()=>Yn,Date:()=>hr,DirectMessageRelaysList:()=>Cn,DraftClassifiedListing:()=>lr,DraftLong:()=>or,Emojisets:()=>ir,EncryptedDirectMessage:()=>Qe,EventDeletion:()=>Xe,FileMetadata:()=>pn,FileServerPreference:()=>qn,Followsets:()=>Wn,GenericRepost:()=>sn,Genericlists:()=>Zn,GiftWrap:()=>dn,HTTPAuth:()=>Vn,Handlerinformation:()=>yr,Handlerrecommendation:()=>gr,Highlights:()=>Un,InterestsList:()=>Hn,Interestsets:()=>tr,JobFeedback:()=>An,JobRequest:()=>vn,JobResult:()=>xn,Label:()=>mn,LightningPubRPC:()=>jn,LiveChatMessage:()=>gn,LiveEvent:()=>ar,LongFormArticle:()=>rr,Metadata:()=>Ze,Mutelist:()=>In,NWCWalletInfo:()=>Mn,NWCWalletRequest:()=>Dn,NWCWalletResponse:()=>Fn,NostrConnect:()=>Kn,OpenTimestamps:()=>fn,Pinlist:()=>Ln,PrivateDirectMessage:()=>on,ProblemTracker:()=>yn,ProfileBadges:()=>Qn,PublicChatsList:()=>_n,Reaction:()=>en,RecommendRelay:()=>Je,RelayList:()=>On,Relaysets:()=>Gn,Report:()=>wn,Reporting:()=>bn,Repost:()=>tn,Seal:()=>rn,SearchRelaysList:()=>$n,ShortTextNote:()=>Ge,Time:()=>fr,UserEmojiList:()=>Pn,UserStatuses:()=>cr,Zap:()=>Bn,ZapGoal:()=>kn,ZapRequest:()=>Sn,classifyKind:()=>Ve,isEphemeralKind:()=>Fe,isKind:()=>We,isParameterizedReplaceableKind:()=>Ke,isRegularKind:()=>ze,isReplaceableKind:()=>De});var Ze=0,Ge=1,Je=2,Ye=3,Qe=4,Xe=5,tn=6,en=7,nn=8,rn=13,on=14,sn=16,an=40,cn=41,un=42,ln=43,hn=44,fn=1040,dn=1059,pn=1063,gn=1311,yn=1971,wn=1984,bn=1984,mn=1985,En=4550,vn=5999,xn=6999,An=7e3,kn=9041,Sn=9734,Bn=9735,Un=9802,In=1e4,Ln=10001,On=10002,Rn=10003,Tn=10004,_n=10005,Nn=10006,$n=10007,Hn=10015,Pn=10030,Cn=10050,qn=10096,Mn=13194,jn=21e3,zn=22242,Dn=23194,Fn=23195,Kn=24133,Vn=27235,Wn=3e4,Zn=30001,Gn=30002,Jn=30003,Yn=30004,Qn=30008,Xn=30009,tr=30015,er=30017,nr=30018,rr=30023,or=30024,ir=30030,sr=30078,ar=30311,cr=30315,ur=30402,lr=30403,hr=31922,fr=31923,dr=31924,pr=31925,gr=31989,yr=31990,wr=34550;function br(t,e){if(t.ids&&-1===t.ids.indexOf(e.id))return!1;if(t.kinds&&-1===t.kinds.indexOf(e.kind))return!1;if(t.authors&&-1===t.authors.indexOf(e.pubkey))return!1;for(let n in t)if("#"===n[0]){let r=t[`#${n.slice(1)}`];if(r&&!e.tags.find((([t,e])=>t===n.slice(1)&&-1!==r.indexOf(e))))return!1}return!(t.since&&e.created_att.until)}function mr(t,e){for(let n=0;n{if("kinds"===t||"ids"===t||"authors"===t||"#"===t[0]){e[t]=e[t]||[];for(let r=0;re.limit)&&(e.limit=r.limit),r.until&&(!e.until||r.until>e.until)&&(e.until=r.until),r.since&&(!e.since||r.sinceDe(t)))?t.authors.length*t.kinds.length:1/0,t.authors?.length&&t.kinds?.every((t=>Ke(t)))&&t["#d"]?.length?t.authors.length*t.kinds.length*t["#d"].length:1/0)}var xr={};function Ar(t,e){let n=e.length+3,r=t.indexOf(`"${e}":`)+n,o=t.slice(r).indexOf('"')+r+1;return t.slice(o,o+64)}function kr(t,e){let n=e.length,r=t.indexOf(`"${e}":`)+n+3,o=t.slice(r),i=Math.min(o.indexOf(","),o.indexOf("}"));return parseInt(o.slice(0,i),10)}function Sr(t){let e=t.slice(0,22).indexOf('"EVENT"');if(-1===e)return null;let n=t.slice(e+7+1).indexOf('"');if(-1===n)return null;let r=e+7+1+n,o=t.slice(r+1,80).indexOf('"');if(-1===o)return null;let i=r+1+o;return t.slice(r+1,i)}function Br(t,e){return e===Ar(t,"id")}function Ur(t,e){return e===Ar(t,"pubkey")}function Ir(t,e){return e===kr(t,"kind")}o(xr,{getHex64:()=>Ar,getInt:()=>kr,getSubscriptionId:()=>Sr,matchEventId:()=>Br,matchEventKind:()=>Ir,matchEventPubkey:()=>Ur});var Lr={};function Or(t,e){return{kind:zn,created_at:Math.floor(Date.now()/1e3),tags:[["relay",t],["challenge",e]],content:""}}async function Rr(){return new Promise((t=>{const e=new MessageChannel,n=()=>{e.port1.removeEventListener("message",n),t()};e.port1.addEventListener("message",n),e.port2.postMessage(0),e.port1.start()}))}o(Lr,{makeAuthEvent:()=>Or});var Tr,_r=t=>(t[le]=!0,!0),Nr=class{url;_connected=!1;onclose=null;onnotice=t=>console.debug(`NOTICE from ${this.url}: ${t}`);_onauth=null;baseEoseTimeout=4400;connectionTimeout=4400;publishTimeout=4400;openSubs=new Map;connectionTimeoutHandle;connectionPromise;openCountRequests=new Map;openEventPublishes=new Map;ws;incomingMessageQueue=new _e;queueRunning=!1;challenge;serial=0;verifyEvent;_WebSocket;constructor(t,e){this.url=Ie(t),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket}static async connect(t,e){const n=new Nr(t,e);return await n.connect(),n}closeAllSubscriptions(t){for(let[e,n]of this.openSubs)n.close(t);this.openSubs.clear();for(let[e,n]of this.openEventPublishes)n.reject(new Error(t));this.openEventPublishes.clear();for(let[e,n]of this.openCountRequests)n.reject(new Error(t));this.openCountRequests.clear()}get connected(){return this._connected}async connect(){return this.connectionPromise||(this.challenge=void 0,this.connectionPromise=new Promise(((t,e)=>{this.connectionTimeoutHandle=setTimeout((()=>{e("connection timed out"),this.connectionPromise=void 0,this.onclose?.(),this.closeAllSubscriptions("relay connection timed out")}),this.connectionTimeout);try{this.ws=new this._WebSocket(this.url)}catch(t){return void e(t)}this.ws.onopen=()=>{clearTimeout(this.connectionTimeoutHandle),this._connected=!0,t()},this.ws.onerror=t=>{e(t.message||"websocket error"),this._connected&&(this._connected=!1,this.connectionPromise=void 0,this.onclose?.(),this.closeAllSubscriptions("relay connection errored"))},this.ws.onclose=async()=>{this._connected&&(this._connected=!1,this.connectionPromise=void 0,this.onclose?.(),this.closeAllSubscriptions("relay connection closed"))},this.ws.onmessage=this._onmessage.bind(this)}))),this.connectionPromise}async runQueue(){for(this.queueRunning=!0;!1!==this.handleNext();)await Rr();this.queueRunning=!1}handleNext(){const t=this.incomingMessageQueue.dequeue();if(!t)return!1;const e=Sr(t);if(e){const n=this.openSubs.get(e);if(!n)return;const r=Ar(t,"id"),o=n.alreadyHaveEvent?.(r);if(n.receivedEvent?.(this,r),o)return}try{let e=JSON.parse(t);switch(e[0]){case"EVENT":{const t=this.openSubs.get(e[1]),n=e[2];return void(this.verifyEvent(n)&&mr(t.filters,n)&&t.onevent(n))}case"COUNT":{const t=e[1],n=e[2],r=this.openCountRequests.get(t);return void(r&&(r.resolve(n.count),this.openCountRequests.delete(t)))}case"EOSE":{const t=this.openSubs.get(e[1]);if(!t)return;return void t.receivedEose()}case"OK":{const t=e[1],n=e[2],r=e[3],o=this.openEventPublishes.get(t);return void(o&&(n?o.resolve(r):o.reject(new Error(r)),this.openEventPublishes.delete(t)))}case"CLOSED":{const t=e[1],n=this.openSubs.get(t);if(!n)return;return n.closed=!0,void n.close(e[2])}case"NOTICE":return void this.onnotice(e[1]);case"AUTH":return this.challenge=e[1],void this._onauth?.(e[1])}}catch(t){return}}async send(t){if(!this.connectionPromise)throw new Error("sending on closed connection");this.connectionPromise.then((()=>{this.ws?.send(t)}))}async auth(t){if(!this.challenge)throw new Error("can't perform auth, no challenge was received");const e=await t(Or(this.url,this.challenge)),n=new Promise(((t,n)=>{this.openEventPublishes.set(e.id,{resolve:t,reject:n})}));return this.send('["AUTH",'+JSON.stringify(e)+"]"),n}async publish(t){const e=new Promise(((e,n)=>{this.openEventPublishes.set(t.id,{resolve:e,reject:n})}));return this.send('["EVENT",'+JSON.stringify(t)+"]"),setTimeout((()=>{const e=this.openEventPublishes.get(t.id);e&&(e.reject(new Error("publish timed out")),this.openEventPublishes.delete(t.id))}),this.publishTimeout),e}async count(t,e){this.serial++;const n=e?.id||"count:"+this.serial,r=new Promise(((t,e)=>{this.openCountRequests.set(n,{resolve:t,reject:e})}));return this.send('["COUNT","'+n+'",'+JSON.stringify(t).substring(1)),r}subscribe(t,e){const n=this.prepareSubscription(t,e);return n.fire(),n}prepareSubscription(t,e){this.serial++;const n=e.id||"sub:"+this.serial,r=new $r(this,n,t,e);return this.openSubs.set(n,r),r}close(){this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,this.ws?.close()}_onmessage(t){this.incomingMessageQueue.enqueue(t.data),this.queueRunning||this.runQueue()}},$r=class{relay;id;closed=!1;eosed=!1;filters;alreadyHaveEvent;receivedEvent;onevent;oneose;onclose;eoseTimeout;eoseTimeoutHandle;constructor(t,e,n,r){this.relay=t,this.filters=n,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||t.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.onevent=r.onevent||(t=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,t)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,this.oneose?.())}close(t="closed by caller"){!this.closed&&this.relay.connected&&(this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]"),this.closed=!0),this.relay.openSubs.delete(this.id),this.onclose?.(t)}};try{Tr=WebSocket}catch{}var Hr,Pr=class extends Nr{constructor(t){super(t,{verifyEvent:Me,websocketImplementation:Tr})}static async connect(t){const e=new Pr(t);return await e.connect(),e}},Cr=class{relays=new Map;seenOn=new Map;trackRelays=!1;verifyEvent;trustedRelayURLs=new Set;_WebSocket;constructor(t){this.verifyEvent=t.verifyEvent,this._WebSocket=t.websocketImplementation}async ensureRelay(t,e){t=Ie(t);let n=this.relays.get(t);return n||(n=new Nr(t,{verifyEvent:this.trustedRelayURLs.has(t)?_r:this.verifyEvent,websocketImplementation:this._WebSocket}),e?.connectionTimeout&&(n.connectionTimeout=e.connectionTimeout),this.relays.set(t,n)),await n.connect(),n}close(t){t.map(Ie).forEach((t=>{this.relays.get(t)?.close()}))}subscribeMany(t,e,n){return this.subscribeManyMap(Object.fromEntries(t.map((t=>[t,e]))),n)}subscribeManyMap(t,e){this.trackRelays&&(e.receivedEvent=(t,e)=>{let n=this.seenOn.get(e);n||(n=new Set,this.seenOn.set(e,n)),n.add(t)});const n=new Set,r=[],o=Object.keys(t).length,i=[];let s=t=>{i[t]=!0,i.filter((t=>t)).length===o&&(e.oneose?.(),s=()=>{})};const a=[];let c=(t,n)=>{s(t),a[t]=n,a.filter((t=>t)).length===o&&(e.onclose?.(a),c=()=>{})};const u=t=>{if(e.alreadyHaveEvent?.(t))return!0;const r=n.has(t);return n.add(t),r},l=Promise.all(Object.entries(t).map((async(t,n,o)=>{if(o.indexOf(t)!==n)return void c(n,"duplicate url");let i,[a,l]=t;a=Ie(a);try{i=await this.ensureRelay(a,{connectionTimeout:e.maxWait?Math.max(.8*e.maxWait,e.maxWait-1e3):void 0})}catch(t){return void c(n,t?.message||String(t))}let h=i.subscribe(l,{...e,oneose:()=>s(n),onclose:t=>c(n,t),alreadyHaveEvent:u,eoseTimeout:e.maxWait});r.push(h)})));return{async close(){await l,r.forEach((t=>{t.close()}))}}}subscribeManyEose(t,e,n){const r=this.subscribeMany(t,e,{...n,oneose(){r.close()}});return r}async querySync(t,e,n){return new Promise((async r=>{const o=[];this.subscribeManyEose(t,[e],{...n,onevent(t){o.push(t)},onclose(t){r(o)}})}))}async get(t,e,n){e.limit=1;const r=await this.querySync(t,e,n);return r.sort(((t,e)=>e.created_at-t.created_at)),r[0]||null}publish(t,e){return t.map(Ie).map((async(t,n,r)=>{if(r.indexOf(t)!==n)return Promise.reject("duplicate url");let o=await this.ensureRelay(t);return o.publish(e).then((t=>{if(this.trackRelays){let t=this.seenOn.get(e.id);t||(t=new Set,this.seenOn.set(e.id,t)),t.add(o)}return t}))}))}listConnectionStatus(){const t=new Map;return this.relays.forEach(((e,n)=>t.set(n,e.connected))),t}destroy(){this.relays.forEach((t=>t.close())),this.relays=new Map}};try{Hr=WebSocket}catch{}var qr=class extends Cr{constructor(){super({verifyEvent:Me,websocketImplementation:Hr})}},Mr={};function jr(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function zr(...t){const e=(t,e)=>n=>t(e(n));return{encode:Array.from(t).reverse().reduce(((t,n)=>t?e(t,n.encode):n.encode),void 0),decode:t.reduce(((t,n)=>t?e(t,n.decode):n.decode),void 0)}}function Dr(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&"number"!=typeof e[0])throw new Error("alphabet.encode input should be an array of numbers");return e.map((e=>{if(jr(e),e<0||e>=t.length)throw new Error(`Digit index outside alphabet: ${e} (alphabet: ${t.length})`);return t[e]}))},decode:e=>{if(!Array.isArray(e)||e.length&&"string"!=typeof e[0])throw new Error("alphabet.decode input should be array of strings");return e.map((e=>{if("string"!=typeof e)throw new Error(`alphabet.decode: not string element=${e}`);const n=t.indexOf(e);if(-1===n)throw new Error(`Unknown letter: "${e}". Allowed: ${t}`);return n}))}}}function Fr(t=""){if("string"!=typeof t)throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&"string"!=typeof e[0])throw new Error("join.encode input should be array of strings");for(let t of e)if("string"!=typeof t)throw new Error(`join.encode: non-string input=${t}`);return e.join(t)},decode:e=>{if("string"!=typeof e)throw new Error("join.decode input should be string");return e.split(t)}}}function Kr(t,e="="){if(jr(t),"string"!=typeof e)throw new Error("padding chr should be string");return{encode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let t of n)if("string"!=typeof t)throw new Error(`padding.encode: non-string input=${t}`);for(;n.length*t%8;)n.push(e);return n},decode(n){if(!Array.isArray(n)||n.length&&"string"!=typeof n[0])throw new Error("padding.encode input should be array of strings");for(let t of n)if("string"!=typeof t)throw new Error(`padding.decode: non-string input=${t}`);let r=n.length;if(r*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if(!((r-1)*t%8))throw new Error("Invalid padding: string has too much padding");return n.slice(0,r)}}}function Vr(t){if("function"!=typeof t)throw new Error("normalize fn should be function");return{encode:t=>t,decode:e=>t(e)}}function Wr(t,e,n){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let r=0;const o=[],i=Array.from(t);for(i.forEach((t=>{if(jr(t),t<0||t>=e)throw new Error(`Wrong integer: ${t}`)}));;){let t=0,s=!0;for(let o=r;owo,Bech32MaxSize:()=>yo,NostrTypeGuard:()=>go,decode:()=>bo,encodeBytes:()=>ko,naddrEncode:()=>Uo,neventEncode:()=>Bo,noteEncode:()=>xo,nprofileEncode:()=>So,npubEncode:()=>vo,nsecEncode:()=>Eo});var Zr=(t,e)=>e?Zr(e,t%e):t,Gr=(t,e)=>t+(e-Zr(t,e));function Jr(t,e,n,r){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Gr(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Gr(e,n)}`);let o=0,i=0;const s=2**n-1,a=[];for(const r of t){if(jr(r),r>=2**e)throw new Error(`convertRadix2: invalid data word=${r} from=${e}`);if(o=o<32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)a.push((o>>i-n&s)>>>0);o&=2**i-1}if(o=o<=e)throw new Error("Excess padding");if(!r&&o)throw new Error(`Non-zero padding: ${o}`);return r&&i>0&&a.push(o>>>0),a}function Yr(t,e=!1){if(jr(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Gr(8,t)>32||Gr(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!(n instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return Jr(Array.from(n),8,t,!e)},decode:n=>{if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(Jr(n,t,8,e))}}}function Qr(t){if("function"!=typeof t)throw new Error("unsafeWrapper fn should be function");return function(...e){try{return t.apply(null,e)}catch(t){}}}var Xr=zr(Yr(4),Dr("0123456789ABCDEF"),Fr("")),to=zr(Yr(5),Dr("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Kr(5),Fr("")),eo=(zr(Yr(5),Dr("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Kr(5),Fr("")),zr(Yr(5),Dr("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),Fr(""),Vr((t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")))),zr(Yr(6),Dr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Kr(6),Fr(""))),no=zr(Yr(6),Dr("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Kr(6),Fr("")),ro=t=>{return zr((jr(e=58),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return Wr(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(Wr(t,e,256))}}),Dr(t),Fr(""));var e},oo=ro("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),io=(ro("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),ro("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"),[0,2,3,5,6,7,9,10,11]),so={encode(t){let e="";for(let n=0;n>25;let n=(33554431&t)<<5;for(let t=0;t>t&1)&&(n^=co[t]);return n}function lo(t,e,n=1){const r=t.length;let o=1;for(let e=0;e126)throw new Error(`Invalid prefix (${t})`);o=uo(o)^n>>5}o=uo(o);for(let e=0;en)throw new TypeError(`Wrong string length: ${t.length} (${t}). Expected (8..${n})`);const r=t.toLowerCase();if(t!==r&&t!==t.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(t=r).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=t.slice(0,o),s=t.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=ao.decode(s).slice(0,-6),c=lo(i,a,e);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${t}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(t,n,r=90){if("string"!=typeof t)throw new Error("bech32.encode prefix should be string, not "+typeof t);if(!Array.isArray(n)||n.length&&"number"!=typeof n[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof n);const o=t.length+7+n.length;if(!1!==r&&o>r)throw new TypeError(`Length ${o} exceeds limit ${r}`);return`${t=t.toLowerCase()}1${ao.encode(n)}${lo(t,n,e)}`},decode:s,decodeToBytes:function(t){const{prefix:e,words:n}=s(t,!1);return{prefix:e,words:n,bytes:r(n)}},decodeUnsafe:Qr(s),fromWords:r,fromWordsUnsafe:i,toWords:o}}var fo=ho("bech32"),po=(ho("bech32m"),{utf8:{encode:t=>(new TextDecoder).decode(t),decode:t=>(new TextEncoder).encode(t)},hex:zr(Yr(4),Dr("0123456789abcdef"),Fr(""),Vr((t=>{if("string"!=typeof t||t.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}))),base16:Xr,base32:to,base64:eo,base64url:no,base58:oo,base58xmr:so}),go=(Object.keys(po).join(", "),{isNProfile:t=>/^nprofile1[a-z\d]+$/.test(t||""),isNEvent:t=>/^nevent1[a-z\d]+$/.test(t||""),isNAddr:t=>/^naddr1[a-z\d]+$/.test(t||""),isNSec:t=>/^nsec1[a-z\d]{58}$/.test(t||""),isNPub:t=>/^npub1[a-z\d]{58}$/.test(t||""),isNote:t=>/^note1[a-z\d]+$/.test(t||""),isNcryptsec:t=>/^ncryptsec1[a-z\d]+$/.test(t||"")}),yo=5e3,wo=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function bo(t){let{prefix:e,words:n}=fo.decode(t,yo),r=new Uint8Array(fo.fromWords(n));switch(e){case"nprofile":{let t=mo(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:re(t[0][0]),relays:t[1]?t[1].map((t=>Be.decode(t))):[]}}}case"nevent":{let t=mo(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(t[2]&&32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(t[3]&&4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:re(t[0][0]),relays:t[1]?t[1].map((t=>Be.decode(t))):[],author:t[2]?.[0]?re(t[2][0]):void 0,kind:t[3]?.[0]?parseInt(re(t[3][0]),16):void 0}}}case"naddr":{let t=mo(r);if(!t[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!t[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!t[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:Be.decode(t[0][0]),pubkey:re(t[2][0]),kind:parseInt(re(t[3][0]),16),relays:t[1]?t[1].map((t=>Be.decode(t))):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:re(r)};default:throw new Error(`unknown prefix ${e}`)}}function mo(t){let e={},n=t;for(;n.length>0;){let t=n[0],r=n[1],o=n.slice(2,2+r);if(n=n.slice(2+r),o.lengthUe.encode(t)))}))}function Bo(t){let e;return void 0!==t.kind&&(e=function(t){const e=new Uint8Array(4);return e[0]=t>>24&255,e[1]=t>>16&255,e[2]=t>>8&255,e[3]=255&t,e}(t.kind)),Ao("nevent",Io({0:[oe(t.id)],1:(t.relays||[]).map((t=>Ue.encode(t))),2:t.author?[oe(t.author)]:[],3:e?[new Uint8Array(e)]:[]}))}function Uo(t){let e=new ArrayBuffer(4);return new DataView(e).setUint32(0,t.kind,!1),Ao("naddr",Io({0:[Ue.encode(t.identifier)],1:(t.relays||[]).map((t=>Ue.encode(t))),2:[oe(t.pubkey)],3:[new Uint8Array(e)]}))}function Io(t){let e=[];return Object.entries(t).reverse().forEach((([t,n])=>{n.forEach((n=>{let r=new Uint8Array(n.length+2);r.set([parseInt(t)],0),r.set([n.length],1),r.set(n,2),e.push(r)}))})),se(...e)}var Lo=/\bnostr:((note|npub|naddr|nevent|nprofile)1\w+)\b|#\[(\d+)\]/g;function Oo(t){let e=[];for(let n of t.content.matchAll(Lo))if(n[2])try{let{type:t,data:r}=bo(n[1]);switch(t){case"npub":e.push({text:n[0],profile:{pubkey:r,relays:[]}});break;case"nprofile":e.push({text:n[0],profile:r});break;case"note":e.push({text:n[0],event:{id:r,relays:[]}});break;case"nevent":e.push({text:n[0],event:r});break;case"naddr":e.push({text:n[0],address:r})}}catch(t){}else if(n[3]){let r=parseInt(n[3],10),o=t.tags[r];if(!o)continue;switch(o[0]){case"p":e.push({text:n[0],profile:{pubkey:o[1],relays:o[2]?[o[2]]:[]}});break;case"e":e.push({text:n[0],event:{id:o[1],relays:o[2]?[o[2]]:[]}});break;case"a":try{let[t,r,i]=o[1].split(":");e.push({text:n[0],address:{identifier:i,pubkey:r,kind:parseInt(t,10),relays:o[2]?[o[2]]:[]}})}catch(t){}}}return e}var Ro={};function To(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function _o(t){if("boolean"!=typeof t)throw new Error(`boolean expected, not ${t}`)}function No(t){return t instanceof Uint8Array||null!=t&&"object"==typeof t&&"Uint8Array"===t.constructor.name}function $o(t,...e){if(!No(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function Ho(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 Po(t,e){$o(t);const n=e.outputLen;if(t.lengthIi,encrypt:()=>Ui});var Co=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength),qo=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),Mo=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);if(!(68===new Uint8Array(new Uint32Array([287454020]).buffer)[0]))throw new Error("Non little-endian hardware is not supported");function jo(t){if("string"!=typeof t)throw new Error("string expected, got "+typeof t);return new Uint8Array((new TextEncoder).encode(t))}function zo(t){if("string"==typeof t)t=jo(t);else{if(!No(t))throw new Error("Uint8Array expected, got "+typeof t);t=t.slice()}return t}function Do(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r(Object.assign(e,t),e);function Ko(t,e,n,r){if("function"==typeof t.setBigUint64)return t.setBigUint64(e,n,r);const o=BigInt(32),i=BigInt(4294967295),s=Number(n>>o&i),a=Number(n&i),c=r?4:0,u=r?0:4;t.setUint32(e+c,s,r),t.setUint32(e+u,a,r)}var Vo=16,Wo=new Uint8Array(16),Zo=qo(Wo),Go=t=>(t>>>0&255)<<24|(t>>>8&255)<<16|(t>>>16&255)<<8|t>>>24&255;var Jo=class{constructor(t,e){this.blockLen=Vo,this.outputLen=Vo,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,$o(t=zo(t),16);const n=Mo(t);let r=n.getUint32(0,!1),o=n.getUint32(4,!1),i=n.getUint32(8,!1),s=n.getUint32(12,!1);const a=[];for(let t=0;t<128;t++)a.push({s0:Go(r),s1:Go(o),s2:Go(i),s3:Go(s)}),({s0:r,s1:o,s2:i,s3:s}={s3:(l=i)<<31|(h=s)>>>1,s2:(u=o)<<31|l>>>1,s1:(c=r)<<31|u>>>1,s0:c>>>1^225<<24&-(1&h)});var c,u,l,h;const f=(d=e||1024)>65536?8:d>1024?4:2;var d;if(![1,2,4,8].includes(f))throw new Error(`ghash: wrong window size=${f}, should be 2, 4 or 8`);this.W=f;const p=128/f,g=this.windowSize=2**f,y=[];for(let t=0;t>>f-s-1&1))continue;const{s0:c,s1:u,s2:l,s3:h}=a[f*t+s];n^=c,r^=u,o^=l,i^=h}y.push({s0:n,s1:r,s2:o,s3:i})}this.t=y}_updateBlock(t,e,n,r){t^=this.s0,e^=this.s1,n^=this.s2,r^=this.s3;const{W:o,t:i,windowSize:s}=this;let a=0,c=0,u=0,l=0;const h=(1<>>8*t&255;for(let t=8/o-1;t>=0;t--){const n=e>>>o*t&h,{s0:r,s1:d,s2:p,s3:g}=i[f*s+n];a^=r,c^=d,u^=p,l^=g,f+=1}}this.s0=a,this.s1=c,this.s2=u,this.s3=l}update(t){t=zo(t),Ho(this);const e=qo(t),n=Math.floor(t.length/Vo),r=t.length%Vo;for(let t=0;t>>1|n,n=(1&r)<<7}return t[0]^=225&-e,t}((t=zo(t)).slice());super(n,e),n.fill(0)}update(t){t=zo(t),Ho(this);const e=qo(t),n=t.length%Vo,r=Math.floor(t.length/Vo);for(let t=0;tt(n,e.length).update(zo(e)).digest(),n=t(new Uint8Array(16),0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=(e,n)=>t(e,n),e}var Xo=Qo(((t,e)=>new Jo(t,e))),ti=Qo(((t,e)=>new Yo(t,e))),ei=16,ni=new Uint8Array(ei);function ri(t){return t<<1^283&-(t>>7)}function oi(t,e){let n=0;for(;e>0;e>>=1)n^=t&-(1&e),t=ri(t);return n}var ii=(()=>{let t=new Uint8Array(256);for(let e=0,n=1;e<256;e++,n^=ri(n))t[e]=n;const e=new Uint8Array(256);e[0]=99;for(let n=0;n<255;n++){let r=t[255-n];r|=r<<8,e[t[n]]=255&(r^r>>4^r>>5^r>>6^r>>7^99)}return e})(),si=ii.map(((t,e)=>ii.indexOf(e))),ai=t=>t<<8|t>>>24;function ci(t,e){if(256!==t.length)throw new Error("Wrong sbox length");const n=new Uint32Array(256).map(((n,r)=>e(t[r]))),r=n.map(ai),o=r.map(ai),i=o.map(ai),s=new Uint32Array(65536),a=new Uint32Array(65536),c=new Uint16Array(65536);for(let e=0;e<256;e++)for(let u=0;u<256;u++){const l=256*e+u;s[l]=n[e]^r[u],a[l]=o[e]^i[u],c[l]=t[e]<<8|t[u]}return{sbox:t,sbox2:c,T0:n,T1:r,T2:o,T3:i,T01:s,T23:a}}var ui=ci(ii,(t=>oi(t,3)<<24|t<<16|t<<8|oi(t,2))),li=ci(si,(t=>oi(t,11)<<24|oi(t,13)<<16|oi(t,9)<<8|oi(t,14))),hi=(()=>{const t=new Uint8Array(16);for(let e=0,n=1;e<16;e++,n=ri(n))t[e]=n;return t})();function fi(t){$o(t);const e=t.length;if(![16,24,32].includes(e))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);const{sbox2:n}=ui,r=qo(t),o=r.length,i=t=>gi(n,t,t,t,t),s=new Uint32Array(e+28);s.set(r);for(let t=o;t>>8)^hi[t/o-1]:o>6&&t%o==4&&(e=i(e)),s[t]=s[t-o]^e}var a;return s}function di(t){const e=fi(t),n=e.slice(),r=e.length,{sbox2:o}=ui,{T0:i,T1:s,T2:a,T3:c}=li;for(let t=0;t>>8&255]^a[r>>>16&255]^c[r>>>24]}return n}function pi(t,e,n,r,o,i){return t[n<<8&65280|r>>>8&255]^e[o>>>8&65280|i>>>24&255]}function gi(t,e,n,r,o){return t[255&e|65280&n]|t[r>>>16&255|o>>>16&65280]<<16}function yi(t,e,n,r,o){const{sbox2:i,T01:s,T23:a}=ui;let c=0;e^=t[c++],n^=t[c++],r^=t[c++],o^=t[c++];const u=t.length/4-2;for(let i=0;i>>0,a.setUint32(l,f,e),({s0:d,s1:p,s2:g,s3:y}=yi(t,s[0],s[1],s[2],s[3]));const w=ei*Math.floor(c.length/4);if(w=0;t--)n=n+(255&i[t])|0,i[t]=255&n,n>>>=8;({s0:a,s1:c,s2:u,s3:l}=yi(t,s[0],s[1],s[2],s[3]))}const d=ei*Math.floor(h.length/4);if(dn(t,e),decrypt:(t,e)=>n(t,e)}}));function Ei(t){if($o(t),t.length%ei!=0)throw new Error("aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size 16")}function vi(t,e,n){let r=t.length;const o=r%ei;if(!e&&0!==o)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const i=qo(t);if(e){let t=ei-o;t||(t=ei),r+=t}const s=bi(r,n);return{b:i,o:qo(s),out:s}}function xi(t,e){if(!e)return t;const n=t.length;if(!n)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=t[n-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const o=t.subarray(0,-r);for(let e=0;e{$o(e);const{b:o,o:i,out:s}=vi(e,n,r),a=fi(t);let c=0;for(;c+4<=o.length;){const{s0:t,s1:e,s2:n,s3:r}=yi(a,o[c+0],o[c+1],o[c+2],o[c+3]);i[c++]=t,i[c++]=e,i[c++]=n,i[c++]=r}if(n){const t=Ai(e.subarray(4*c)),{s0:n,s1:r,s2:o,s3:s}=yi(a,t[0],t[1],t[2],t[3]);i[c++]=n,i[c++]=r,i[c++]=o,i[c++]=s}return a.fill(0),s},decrypt:(e,r)=>{Ei(e);const o=di(t),i=bi(e.length,r),s=qo(e),a=qo(i);for(let t=0;t+4<=s.length;){const{s0:e,s1:n,s2:r,s3:i}=wi(o,s[t+0],s[t+1],s[t+2],s[t+3]);a[t++]=e,a[t++]=n,a[t++]=r,a[t++]=i}return o.fill(0),xi(i,n)}}}));var ki=Fo({blockSize:16,nonceLength:16},(function(t,e,n={}){$o(t),$o(e,16);const r=!n.disablePadding;return{encrypt:(n,o)=>{const i=fi(t),{b:s,o:a,out:c}=vi(n,r,o),u=qo(e);let l=u[0],h=u[1],f=u[2],d=u[3],p=0;for(;p+4<=s.length;)l^=s[p+0],h^=s[p+1],f^=s[p+2],d^=s[p+3],({s0:l,s1:h,s2:f,s3:d}=yi(i,l,h,f,d)),a[p++]=l,a[p++]=h,a[p++]=f,a[p++]=d;if(r){const t=Ai(n.subarray(4*p));l^=t[0],h^=t[1],f^=t[2],d^=t[3],({s0:l,s1:h,s2:f,s3:d}=yi(i,l,h,f,d)),a[p++]=l,a[p++]=h,a[p++]=f,a[p++]=d}return i.fill(0),c},decrypt:(n,o)=>{Ei(n);const i=di(t),s=qo(e),a=bi(n.length,o),c=qo(n),u=qo(a);let l=s[0],h=s[1],f=s[2],d=s[3];for(let t=0;t+4<=c.length;){const e=l,n=h,r=f,o=d;l=c[t+0],h=c[t+1],f=c[t+2],d=c[t+3];const{s0:s,s1:a,s2:p,s3:g}=wi(i,l,h,f,d);u[t++]=s^e,u[t++]=a^n,u[t++]=p^r,u[t++]=g^o}return i.fill(0),xi(a,r)}}}));function Si(t,e,n,r,o){const i=t.create(n,r.length+(o?.length||0));o&&i.update(o),i.update(r);const s=new Uint8Array(16),a=Mo(s);return o&&Ko(a,0,BigInt(8*o.length),e),Ko(a,8,BigInt(8*r.length),e),i.update(s),i.digest()}Fo({blockSize:16,nonceLength:12,tagLength:16},(function(t,e,n){if($o(e),0===e.length)throw new Error("aes/gcm: empty nonce");const r=16;function o(t,e,r){const o=Si(Xo,!1,t,r,n);for(let t=0;t{$o(t);const{xk:e,authKey:n,counter:s,tagMask:a}=i(),c=new Uint8Array(t.length+r);mi(e,!1,s,t,c);const u=o(n,a,c.subarray(0,c.length-r));return c.set(u,t.length),e.fill(0),c},decrypt:t=>{if($o(t),t.lengthr=>{if(!Number.isSafeInteger(r)||e>r||r>n)throw new Error(`${t}: invalid value=${r}, must be [${e}..${n}]`)};Fo({blockSize:16,nonceLength:12,tagLength:16},(function(t,e,n){const r=Bi("AAD",0,2**36),o=Bi("plaintext",0,2**36),i=Bi("nonce",12,12),s=Bi("ciphertext",16,2**36+16);function a(){const n=t.length;if(16!==n&&24!==n&&32!==n)throw new Error(`key length must be 16, 24 or 32 bytes, got: ${n} bytes`);const r=fi(t),o=new Uint8Array(n),i=new Uint8Array(16),s=qo(e);let a=0,c=s[0],u=s[1],l=s[2],h=0;for(const t of[i,o].map(qo)){const e=qo(t);for(let t=0;t{$o(t),o(t.length);const{encKey:e,authKey:n}=a(),r=c(e,n,t),i=new Uint8Array(t.length+16);return i.set(r,t.length),i.set(u(e,r,t)),e.fill(0),n.fill(0),i},decrypt:t=>{$o(t),s(t.length);const e=t.subarray(-16),{encKey:n,authKey:r}=a(),o=u(n,e,t.subarray(0,-16)),i=c(n,r,o);if(n.fill(0),r.fill(0),!Do(e,i))throw new Error("invalid polyval tag");return o}}}));async function Ui(t,e,n){const r=t instanceof Uint8Array?re(t):t,o=Li($t.getSharedSecret(r,"02"+e));let i=Uint8Array.from(ue(16)),s=Ue.encode(n),a=ki(o,i).encrypt(s);return`${eo.encode(new Uint8Array(a))}?iv=${eo.encode(new Uint8Array(i.buffer))}`}async function Ii(t,e,n){const r=t instanceof Uint8Array?re(t):t;let[o,i]=n.split("?iv="),s=Li($t.getSharedSecret(r,"02"+e)),a=eo.decode(i),c=eo.decode(o),u=ki(s,a).decrypt(c);return Be.decode(u)}function Li(t){return t.slice(1,33)}var Oi={};o(Oi,{NIP05_REGEX:()=>Ti,isNip05:()=>_i,isValid:()=>Pi,queryProfile:()=>Hi,searchDomain:()=>$i,useFetchImplementation:()=>Ni});var Ri,Ti=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,_i=t=>Ti.test(t||"");try{Ri=fetch}catch(t){}function Ni(t){Ri=t}async function $i(t,e=""){try{const n=`https://${t}/.well-known/nostr.json?name=${e}`,r=await Ri(n,{redirect:"manual"});if(200!==r.status)throw Error("Wrong response code");return(await r.json()).names}catch(t){return{}}}async function Hi(t){const e=t.match(Ti);if(!e)return null;const[,n="_",r]=e;try{const t=`https://${r}/.well-known/nostr.json?name=${n}`,e=await Ri(t,{redirect:"manual"});if(200!==e.status)throw Error("Wrong response code");const o=await e.json(),i=o.names[n];return i?{pubkey:i,relays:o.relays?.[i]}:null}catch(t){return null}}async function Pi(t,e){const n=await Hi(e);return!!n&&n.pubkey===t}var Ci={};function qi(t){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let n,r;for(let o=t.tags.length-1;o>=0;o--){const i=t.tags[o];if("e"===i[0]&&i[1]){const[t,o,s,a,c]=i,u={id:o,relays:s?[s]:[],author:c};if("root"===a){e.root=u;continue}if("reply"===a){e.reply=u;continue}if("mention"===a){e.mentions.push(u);continue}n?r=u:n=u,e.mentions.push(u)}else{if("q"===i[0]&&i[1]){const[t,n,r]=i;e.quotes.push({id:n,relays:r?[r]:[]})}"p"===i[0]&&i[1]&&e.profiles.push({pubkey:i[1],relays:i[2]?[i[2]]:[]})}}return e.root||(e.root=r||n||e.reply),e.reply||(e.reply=n||e.root),[e.reply,e.root].forEach((t=>{if(!t)return;let n=e.mentions.indexOf(t);if(-1!==n&&e.mentions.splice(n,1),t.author){let n=e.profiles.find((e=>e.pubkey===t.author));n&&n.relays&&(t.relays||(t.relays=[]),n.relays.forEach((e=>{-1===t.relays?.indexOf(e)&&t.relays.push(e)})),n.relays=t.relays)}})),e.mentions.forEach((t=>{if(t.author){let n=e.profiles.find((e=>e.pubkey===t.author));n&&n.relays&&(t.relays||(t.relays=[]),n.relays.forEach((e=>{-1===t.relays.indexOf(e)&&t.relays.push(e)})),n.relays=t.relays)}})),e}o(Ci,{parse:()=>qi});var Mi={};o(Mi,{fetchRelayInformation:()=>zi,useFetchImplementation:()=>ji});try{fetch}catch{}function ji(t){0}async function zi(t){return await(await fetch(t.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var Di={};function Fi(t){let e=0;for(let n=0;n<64;n+=8){const r=parseInt(t.substring(n,n+8),16);if(0!==r){e+=Math.clz32(r);break}e+=32}return e}function Ki(t,e){let n=0;const r=t,o=["nonce",n.toString(),e.toString()];for(r.tags.push(o);;){const t=Math.floor((new Date).getTime()/1e3);if(t!==r.created_at&&(n=0,r.created_at=t),o[1]=(++n).toString(),r.id=Vi(r),Fi(r.id)>=e)break}return r}function Vi(t){return re(ke(Ue.encode(JSON.stringify([0,t.pubkey,t.created_at,t.kind,t.tags,t.content]))))}o(Di,{fastEventHash:()=>Vi,getPow:()=>Fi,minePow:()=>Ki});var Wi={};function Zi(t,e,n,r){return qe({kind:tn,tags:[...t.tags??[],["e",e.id,n],["p",e.pubkey]],content:""===t.content?"":JSON.stringify(e),created_at:t.created_at},r)}function Gi(t){if(t.kind!==tn)return;let e,n;for(let r=t.tags.length-1;r>=0&&(void 0===e||void 0===n);r--){const o=t.tags[r];o.length>=2&&("e"===o[0]&&void 0===e?e=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==e?{id:e[1],relays:[e[2],n?.[2]].filter((t=>"string"==typeof t)),author:n?.[1]}:void 0}function Ji(t,{skipVerification:e}={}){const n=Gi(t);if(void 0===n||""===t.content)return;let r;try{r=JSON.parse(t.content)}catch(t){return}return r.id===n.id&&(e||Me(r))?r:void 0}o(Wi,{finishRepostEvent:()=>Zi,getRepostedEvent:()=>Ji,getRepostedEventPointer:()=>Gi});var Yi={};o(Yi,{NOSTR_URI_REGEX:()=>Qi,parse:()=>ts,test:()=>Xi});var Qi=new RegExp(`nostr:(${wo.source})`);function Xi(t){return"string"==typeof t&&new RegExp(`^${Qi.source}$`).test(t)}function ts(t){const e=t.match(new RegExp(`^${Qi.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${t}`);return{uri:e[0],value:e[1],decoded:bo(e[1])}}var es={};function ns(t,e,n){const r=e.tags.filter((t=>t.length>=2&&("e"===t[0]||"p"===t[0])));return qe({...t,kind:en,tags:[...t.tags??[],...r,["e",e.id],["p",e.pubkey]],content:t.content??"+"},n)}function rs(t){if(t.kind!==en)return;let e,n;for(let r=t.tags.length-1;r>=0&&(void 0===e||void 0===n);r--){const o=t.tags[r];o.length>=2&&("e"===o[0]&&void 0===e?e=o:"p"===o[0]&&void 0===n&&(n=o))}return void 0!==e&&void 0!==n?{id:e[1],relays:[e[2],n[2]].filter((t=>void 0!==t)),author:n[1]}:void 0}o(es,{finishReactionEvent:()=>ns,getReactedEventPointer:()=>rs});var os={};o(os,{matchAll:()=>ss,regex:()=>is,replaceAll:()=>as});var is=()=>new RegExp(`\\b${Qi.source}\\b`,"g");function*ss(t){const e=t.matchAll(is());for(const t of e)try{const[e,n]=t;yield{uri:e,value:n,decoded:bo(n),start:t.index,end:t.index+e.length}}catch(t){}}function as(t,e){return t.replaceAll(is(),((t,n)=>e({uri:t,value:n,decoded:bo(n)})))}var cs={};o(cs,{channelCreateEvent:()=>us,channelHideMessageEvent:()=>fs,channelMessageEvent:()=>hs,channelMetadataEvent:()=>ls,channelMuteUserEvent:()=>ds});var us=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return qe({kind:an,tags:[...t.tags??[]],content:n,created_at:t.created_at},e)},ls=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return qe({kind:cn,tags:[["e",t.channel_create_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},hs=(t,e)=>{const n=[["e",t.channel_create_event_id,t.relay_url,"root"]];return t.reply_to_channel_message_event_id&&n.push(["e",t.reply_to_channel_message_event_id,t.relay_url,"reply"]),qe({kind:un,tags:[...n,...t.tags??[]],content:t.content,created_at:t.created_at},e)},fs=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return qe({kind:ln,tags:[["e",t.channel_message_event_id],...t.tags??[]],content:n,created_at:t.created_at},e)},ds=(t,e)=>{let n;if("object"==typeof t.content)n=JSON.stringify(t.content);else{if("string"!=typeof t.content)return;n=t.content}return qe({kind:hn,tags:[["p",t.pubkey_to_mute],...t.tags??[]],content:n,created_at:t.created_at},e)},ps={};o(ps,{EMOJI_SHORTCODE_REGEX:()=>gs,matchAll:()=>ws,regex:()=>ys,replaceAll:()=>bs});var gs=/:(\w+):/,ys=()=>new RegExp(`\\B${gs.source}\\B`,"g");function*ws(t){const e=t.matchAll(ys());for(const t of e)try{const[e,n]=t;yield{shortcode:e,name:n,start:t.index,end:t.index+e.length}}catch(t){}}function bs(t,e){return t.replaceAll(ys(),((t,n)=>e({shortcode:t,name:n})))}var ms,Es={};o(Es,{useFetchImplementation:()=>vs,validateGithub:()=>xs});try{ms=fetch}catch{}function vs(t){ms=t}async function xs(t,e,n){try{return await(await ms(`https://gist.github.com/${e}/${n}/raw`)).text()===`Verifying that I control the following Nostr public key: ${t}`}catch(t){return!1}}var As={};o(As,{decrypt:()=>na,encrypt:()=>ea,getConversationKey:()=>Js,v2:()=>ra});var ks=(t,e)=>255&t[e++]|(255&t[e++])<<8,Ss=class{constructor(t){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,$o(t=zo(t),32);const e=ks(t,0),n=ks(t,2),r=ks(t,4),o=ks(t,6),i=ks(t,8),s=ks(t,10),a=ks(t,12),c=ks(t,14);this.r[0]=8191&e,this.r[1]=8191&(e>>>13|n<<3),this.r[2]=7939&(n>>>10|r<<6),this.r[3]=8191&(r>>>7|o<<9),this.r[4]=255&(o>>>4|i<<12),this.r[5]=i>>>1&8190,this.r[6]=8191&(i>>>14|s<<2),this.r[7]=8065&(s>>>11|a<<5),this.r[8]=8191&(a>>>8|c<<8),this.r[9]=c>>>5&127;for(let e=0;e<8;e++)this.pad[e]=ks(t,16+2*e)}process(t,e,n=!1){const r=n?0:2048,{h:o,r:i}=this,s=i[0],a=i[1],c=i[2],u=i[3],l=i[4],h=i[5],f=i[6],d=i[7],p=i[8],g=i[9],y=ks(t,e+0),w=ks(t,e+2),b=ks(t,e+4),m=ks(t,e+6),E=ks(t,e+8),v=ks(t,e+10),x=ks(t,e+12),A=ks(t,e+14);let k=o[0]+(8191&y),S=o[1]+(8191&(y>>>13|w<<3)),B=o[2]+(8191&(w>>>10|b<<6)),U=o[3]+(8191&(b>>>7|m<<9)),I=o[4]+(8191&(m>>>4|E<<12)),L=o[5]+(E>>>1&8191),O=o[6]+(8191&(E>>>14|v<<2)),R=o[7]+(8191&(v>>>11|x<<5)),T=o[8]+(8191&(x>>>8|A<<8)),_=o[9]+(A>>>5|r),N=0,$=N+k*s+S*(5*g)+B*(5*p)+U*(5*d)+I*(5*f);N=$>>>13,$&=8191,$+=L*(5*h)+O*(5*l)+R*(5*u)+T*(5*c)+_*(5*a),N+=$>>>13,$&=8191;let H=N+k*a+S*s+B*(5*g)+U*(5*p)+I*(5*d);N=H>>>13,H&=8191,H+=L*(5*f)+O*(5*h)+R*(5*l)+T*(5*u)+_*(5*c),N+=H>>>13,H&=8191;let P=N+k*c+S*a+B*s+U*(5*g)+I*(5*p);N=P>>>13,P&=8191,P+=L*(5*d)+O*(5*f)+R*(5*h)+T*(5*l)+_*(5*u),N+=P>>>13,P&=8191;let C=N+k*u+S*c+B*a+U*s+I*(5*g);N=C>>>13,C&=8191,C+=L*(5*p)+O*(5*d)+R*(5*f)+T*(5*h)+_*(5*l),N+=C>>>13,C&=8191;let q=N+k*l+S*u+B*c+U*a+I*s;N=q>>>13,q&=8191,q+=L*(5*g)+O*(5*p)+R*(5*d)+T*(5*f)+_*(5*h),N+=q>>>13,q&=8191;let M=N+k*h+S*l+B*u+U*c+I*a;N=M>>>13,M&=8191,M+=L*s+O*(5*g)+R*(5*p)+T*(5*d)+_*(5*f),N+=M>>>13,M&=8191;let j=N+k*f+S*h+B*l+U*u+I*c;N=j>>>13,j&=8191,j+=L*a+O*s+R*(5*g)+T*(5*p)+_*(5*d),N+=j>>>13,j&=8191;let z=N+k*d+S*f+B*h+U*l+I*u;N=z>>>13,z&=8191,z+=L*c+O*a+R*s+T*(5*g)+_*(5*p),N+=z>>>13,z&=8191;let D=N+k*p+S*d+B*f+U*h+I*l;N=D>>>13,D&=8191,D+=L*u+O*c+R*a+T*s+_*(5*g),N+=D>>>13,D&=8191;let F=N+k*g+S*p+B*d+U*f+I*h;N=F>>>13,F&=8191,F+=L*l+O*u+R*c+T*a+_*s,N+=F>>>13,F&=8191,N=(N<<2)+N|0,N=N+$|0,$=8191&N,N>>>=13,H+=N,o[0]=$,o[1]=H,o[2]=P,o[3]=C,o[4]=q,o[5]=M,o[6]=j,o[7]=z,o[8]=D,o[9]=F}finalize(){const{h:t,pad:e}=this,n=new Uint16Array(10);let r=t[1]>>>13;t[1]&=8191;for(let e=2;e<10;e++)t[e]+=r,r=t[e]>>>13,t[e]&=8191;t[0]+=5*r,r=t[0]>>>13,t[0]&=8191,t[1]+=r,r=t[1]>>>13,t[1]&=8191,t[2]+=r,n[0]=t[0]+5,r=n[0]>>>13,n[0]&=8191;for(let e=1;e<10;e++)n[e]=t[e]+r,r=n[e]>>>13,n[e]&=8191;n[9]-=8192;let o=(1^r)-1;for(let t=0;t<10;t++)n[t]&=o;o=~o;for(let e=0;e<10;e++)t[e]=t[e]&o|n[e];t[0]=65535&(t[0]|t[1]<<13),t[1]=65535&(t[1]>>>3|t[2]<<10),t[2]=65535&(t[2]>>>6|t[3]<<7),t[3]=65535&(t[3]>>>9|t[4]<<4),t[4]=65535&(t[4]>>>12|t[5]<<1|t[6]<<14),t[5]=65535&(t[6]>>>2|t[7]<<11),t[6]=65535&(t[7]>>>5|t[8]<<8),t[7]=65535&(t[8]>>>8|t[9]<<5);let i=t[0]+e[0];t[0]=65535&i;for(let n=1;n<8;n++)i=(t[n]+e[n]|0)+(i>>>16)|0,t[n]=65535&i}update(t){Ho(this);const{buffer:e,blockLen:n}=this,r=(t=zo(t)).length;for(let o=0;o>>0,t[o++]=n[e]>>>8;return t}digest(){const{buffer:t,outputLen:e}=this;this.digestInto(t);const n=t.slice(0,e);return this.destroy(),n}};var Bs=function(t){const e=(e,n)=>t(n).update(zo(e)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=e=>t(e),e}((t=>new Ss(t))),Us=jo("expand 16-byte k"),Is=jo("expand 32-byte k"),Ls=qo(Us),Os=qo(Is);function Rs(t,e){return t<>>32-e}function Ts(t){return t.byteOffset%4==0}var _s=2**32-1,Ns=new Uint32Array;function $s(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:o,counterRight:i,rounds:s}=function(t,e){if(null==e||"object"!=typeof e)throw new Error("options must be defined");return Object.assign(t,e)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if("function"!=typeof t)throw new Error("core must be a function");return To(o),To(s),_o(i),_o(n),(e,a,c,u,l=0)=>{$o(e),$o(a),$o(c);const h=c.length;if(u||(u=new Uint8Array(h)),$o(u),To(l),l<0||l>=_s)throw new Error("arx: counter overflow");if(u.length=_s)throw new Error("arx: counter overflow");const g=Math.min(64,c-p);if(h&&64===g){const t=p/4;if(p%4!=0)throw new Error("arx: invalid block position");for(let e,n=0;n<16;n++)e=t+n,d[e]=f[e]^l[n];p+=64}else{for(let t,e=0;e0;)f.pop().fill(0);return u}}function Hs(t,e,n,r,o,i=20){let s=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],f=e[2],d=e[3],p=e[4],g=e[5],y=e[6],w=e[7],b=o,m=n[0],E=n[1],v=n[2],x=s,A=a,k=c,S=u,B=l,U=h,I=f,L=d,O=p,R=g,T=y,_=w,N=b,$=m,H=E,P=v;for(let t=0;t{t.update(e);const n=e.length%16;n&&t.update(qs.subarray(n))},js=new Uint8Array(32);function zs(t,e,n,r,o){const i=t(e,n,js),s=Bs.create(i);o&&Ms(s,o),Ms(s,r);const a=new Uint8Array(16),c=Mo(a);Ko(c,0,BigInt(o?o.length:0),!0),Ko(c,8,BigInt(r.length),!0),s.update(a);const u=s.digest();return i.fill(0),u}var Ds=t=>(e,n,r)=>{const o=16;return $o(e,32),$o(n),{encrypt:(i,s)=>{const a=i.length,c=a+o;s?$o(s,c):s=new Uint8Array(c),t(e,n,i,s,1);const u=zs(t,e,n,s.subarray(0,-16),r);return s.set(u,a),s},decrypt:(i,s)=>{const a=i.length,c=a-o;if(ar?t.create().update(n).digest():n);for(let t=0;tnew Fs(t,e).update(n).digest();Ks.create=(t,e)=>new Fs(t,e);var Vs=new Uint8Array([0]),Ws=new Uint8Array;var Zs=1,Gs=65535;function Js(t,e){const n=$t.getSharedSecret(t,"02"+e).subarray(1,33);return r=ke,o=n,i="nip44-v2",ye.hash(r),void 0===i&&(i=new Uint8Array(r.outputLen)),Ks(r,ie(i),ie(o));var r,o,i}function Ys(t,e){const n=function(t,e,n,r=32){if(ye.hash(t),ye.number(r),r>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const o=Math.ceil(r/t.outputLen);void 0===n&&(n=Ws);const i=new Uint8Array(o*t.outputLen),s=Ks.create(t,e),a=s._cloneInto(),c=new Uint8Array(s.outputLen);for(let e=0;eGs)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,t,!1),e}(n),e,new Uint8Array(Qs(n)-n))}function ta(t,e,n){if(32!==n.length)throw new Error("AAD associated data must be 32 bytes");const r=se(n,e);return Ks(ke,t,r)}function ea(t,e,n=ue(32)){const{chacha_key:r,chacha_nonce:o,hmac_key:i}=Ys(e,n),s=Xs(t),a=Ps(r,o,s),c=ta(i,a,n);return eo.encode(se(new Uint8Array([2]),n,a,c))}function na(t,e){const{nonce:n,ciphertext:r,mac:o}=function(t){if("string"!=typeof t)throw new Error("payload must be a valid string");const e=t.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if("#"===t[0])throw new Error("unknown encryption version");let n;try{n=eo.decode(t)}catch(t){throw new Error("invalid base64: "+t.message)}const r=n.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const o=n[0];if(2!==o)throw new Error("unknown encryption version "+o);return{nonce:n.subarray(1,33),ciphertext:n.subarray(33,-32),mac:n.subarray(-32)}}(t),{chacha_key:i,chacha_nonce:s,hmac_key:a}=Ys(e,n);if(!Do(ta(a,r,n),o))throw new Error("invalid MAC");return function(t){const e=new DataView(t.buffer).getUint16(0),n=t.subarray(2,2+e);if(eGs||n.length!==e||t.length!==2+Qs(e))throw new Error("invalid padding");return Be.decode(n)}(Ps(i,s,r))}var ra={utils:{getConversationKey:Js,calcPaddedLen:Qs},encrypt:ea,decrypt:na},oa={};function ia(t){const{pathname:e,searchParams:n}=new URL(t),r=e,o=n.get("relay"),i=n.get("secret");if(!r||!o||!i)throw new Error("invalid connection string");return{pubkey:r,relay:o,secret:i}}async function sa(t,e,n){const r={method:"pay_invoice",params:{invoice:n}},o=await Ui(e,t,JSON.stringify(r)),i={kind:Dn,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",t]]};return qe(i,e)}o(oa,{makeNwcRequestEvent:()=>sa,parseConnectionString:()=>ia});var aa,ca={};o(ca,{getZapEndpoint:()=>la,makeZapReceipt:()=>da,makeZapRequest:()=>ha,useFetchImplementation:()=>ua,validateZapRequest:()=>fa});try{aa=fetch}catch{}function ua(t){aa=t}async function la(t){try{let e="",{lud06:n,lud16:r}=JSON.parse(t.content);if(n){let{words:t}=fo.decode(n,1e3),r=fo.fromWords(t);e=Be.decode(r)}else{if(!r)return null;{let[t,n]=r.split("@");e=new URL(`/.well-known/lnurlp/${t}`,`https://${n}`).toString()}}let o=await aa(e),i=await o.json();if(i.allowsNostr&&i.nostrPubkey)return i.callback}catch(t){}return null}function ha({profile:t,event:e,amount:n,relays:r,comment:o=""}){if(!n)throw new Error("amount not given");if(!t)throw new Error("profile not given");let i={kind:9734,created_at:Math.round(Date.now()/1e3),content:o,tags:[["p",t],["amount",n.toString()],["relays",...r]]};return e&&i.tags.push(["e",e]),i}function fa(t){let e;try{e=JSON.parse(t)}catch(t){return"Invalid zap request JSON."}if(!fe(e))return"Zap request is not a valid Nostr event.";if(!Me(e))return"Invalid signature on zap request.";let n=e.tags.find((([t,e])=>"p"===t&&e));if(!n)return"Zap request doesn't have a 'p' tag.";if(!n[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=e.tags.find((([t,e])=>"e"===t&&e));return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":e.tags.find((([t,e])=>"relays"===t&&e))?null:"Zap request doesn't have a 'relays' tag."}function da({zapRequest:t,preimage:e,bolt11:n,paidAt:r}){let o=JSON.parse(t),i=o.tags.filter((([t])=>"e"===t||"p"===t||"a"===t)),s={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...i,["P",o.pubkey],["bolt11",n],["description",t]]};return e&&s.tags.push(["preimage",e]),s}var pa={};o(pa,{createRumor:()=>Ea,createSeal:()=>va,createWrap:()=>xa,unwrapEvent:()=>Sa,unwrapManyEvents:()=>Ba,wrapEvent:()=>Aa,wrapManyEvents:()=>ka});var ga=()=>Math.round(Date.now()/1e3),ya=()=>Math.round(ga()-172800*Math.random()),wa=(t,e)=>Js(t,e),ba=(t,e,n)=>ea(JSON.stringify(t),wa(e,n)),ma=(t,e)=>JSON.parse(na(t.content,wa(e,t.pubkey)));function Ea(t,e){const n={created_at:ga(),content:"",tags:[],...t,pubkey:Ce(e)};return n.id=$e(n),n}function va(t,e,n){return qe({kind:rn,content:ba(t,e,n),created_at:ya(),tags:[]},e)}function xa(t,e){const n=Pe();return qe({kind:dn,content:ba(t,n,e),created_at:ya(),tags:[["p",e]]},n)}function Aa(t,e,n){return xa(va(Ea(t,e),e,n),n)}function ka(t,e,n){if(!n||0===n.length)throw new Error("At least one recipient is required.");const r=Ce(e),o=[Aa(t,e,r)];return n.forEach((n=>{o.push(Aa(t,e,n))})),o}function Sa(t,e){const n=ma(t,e);return ma(n,e)}function Ba(t,e){let n=[];return t.forEach((t=>{n.push(Sa(t,e))})),n.sort(((t,e)=>t.created_at-e.created_at)),n}var Ua={};o(Ua,{getToken:()=>Oa,hashPayload:()=>Pa,unpackEventFromToken:()=>Ta,validateEvent:()=>qa,validateEventKind:()=>Na,validateEventMethodTag:()=>Ha,validateEventPayloadTag:()=>Ca,validateEventTimestamp:()=>_a,validateEventUrlTag:()=>$a,validateToken:()=>Ra});var Ia,La="Nostr ";async function Oa(t,e,n,r=!1,o){const i={kind:Vn,tags:[["u",t],["method",e]],created_at:Math.round((new Date).getTime()/1e3),content:""};o&&i.tags.push(["payload",Pa(o)]);const s=await n(i);return(r?La:"")+eo.encode(Ue.encode(JSON.stringify(s)))}async function Ra(t,e,n){const r=await Ta(t).catch((t=>{throw t}));return await qa(r,e,n).catch((t=>{throw t}))}async function Ta(t){if(!t)throw new Error("Missing token");t=t.replace(La,"");const e=Be.decode(eo.decode(t));if(!e||0===e.length||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function _a(t){return!!t.created_at&&Math.round((new Date).getTime()/1e3)-t.created_at<60}function Na(t){return t.kind===Vn}function $a(t,e){const n=t.tags.find((t=>"u"===t[0]));return!!n&&(n.length>0&&n[1]===e)}function Ha(t,e){const n=t.tags.find((t=>"method"===t[0]));return!!n&&(n.length>0&&n[1].toLowerCase()===e.toLowerCase())}function Pa(t){return re(ke(Ue.encode(JSON.stringify(t))))}function Ca(t,e){const n=t.tags.find((t=>"payload"===t[0]));if(!n)return!1;const r=Pa(e);return n.length>0&&n[1]===r}async function qa(t,e,n,r){if(!Me(t))throw new Error("Invalid nostr event, signature invalid");if(!Na(t))throw new Error("Invalid nostr event, kind invalid");if(!_a(t))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!$a(t,e))throw new Error("Invalid nostr event, url tag invalid");if(!Ha(t,n))throw new Error("Invalid nostr event, method tag invalid");if(Boolean(r)&&"object"==typeof r&&Object.keys(r).length>0&&!Ca(t,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}return Ia=i,((o,i,s,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let c of n(i))r.call(o,c)||c===s||t(o,c,{get:()=>i[c],enumerable:!(a=e(i,c))||a.enumerable});return o})(t({},"__esModule",{value:!0}),Ia)})(); +//# sourceMappingURL=/sm/f29f5f5418a4e9d4df57df00b6b51f97de02afef7a8d582c6c8814bdab32efb1.map \ No newline at end of file