|
|
Object.defineProperty(e,"__esModule",{value:!0}),e.bytes=e.stringToBytes=e.str=e.bytesToString=e.hex=e.utf8=e.bech32m=e.bech32=e.base58check=e.base58xmr=e.base58xrp=e.base58flickr=e.base58=e.base64url=e.base64=e.base32crockford=e.base32hex=e.base32=e.base16=e.utils=e.assertNumber=void 0,e.assertNumber=t;const c=(e,t)=>t?c(t,e%t):e,l=(e,t)=>e+(t-c(e,t));function u(e,n,s,r){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(n<=0||n>32)throw new Error(`convertRadix2: wrong from=${n}`);if(s<=0||s>32)throw new Error(`convertRadix2: wrong to=${s}`);if(l(n,s)>32)throw new Error(`convertRadix2: carry overflow from=${n} to=${s} carryBits=${l(n,s)}`);let i=0,o=0;const a=2**s-1,c=[];for(const r of e){if(t(r),r>=2**n)throw new Error(`convertRadix2: invalid data word=${r} from=${n}`);if(i=i<<n|r,o+n>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${n}`);for(o+=n;o>=s;o-=s)c.push((i>>o-s&a)>>>0);i&=2**o-1}if(i=i<<s-o&a,!r&&o>=n)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&o>0&&c.push(i>>>0),c}function d(e){return t(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return a(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(a(t,e,256))}}}function h(e,n=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return u(Array.from(t),8,e,!n)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(u(t,e,8,n))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function f(e,n){if(t(e),"function"!=typeof n)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const s=n(t).slice(0,e),r=new Uint8Array(t.length+e);return r.set(t),r.set(s,t.length),r},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const s=t.slice(0,-e),r=n(s).slice(0,e),i=t.slice(-e);for(let t=0;t<e;t++)if(r[t]!==i[t])throw new Error("Invalid checksum");return s}}}e.utils={alphabet:s,chain:n,checksum:f,radix:d,radix2:h,join:r,padding:i},e.base16=n(h(4),s("0123456789ABCDEF"),r("")),e.base32=n(h(5),s("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),i(5),r("")),e.base32hex=n(h(5),s("0123456789ABCDEFGHIJKLMNOPQRSTUV"),i(5),r("")),e.base32crockford=n(h(5),s("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),r(""),o(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),e.base64=n(h(6),s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),i(6),r("")),e.base64url=n(h(6),s("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),i(6),r(""));const g=e=>n(d(58),s(e),r(""));e.base58=g("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),e.base58flickr=g("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),e.base58xrp=g("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const y=[0,2,3,5,6,7,9,10,11];e.base58xmr={encode(t){let n="";for(let s=0;s<t.length;s+=8){const r=t.subarray(s,s+8);n+=e.base58.encode(r).padStart(y[r.length],"1")}return n},decode(t){let n=[];for(let s=0;s<t.length;s+=11){const r=t.slice(s,s+11),i=y.indexOf(r.length),o=e.base58.decode(r);for(let e=0;e<o.length-i;e++)if(0!==o[e])throw new Error("base58xmr: wrong padding");n=n.concat(Array.from(o.slice(o.length-i)))}return Uint8Array.from(n)}};e.base58check=t=>n(f(4,e=>t(t(e))),e.base58);const m=n(s("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),r("")),b=[996825010,642813549,513874426,1027748829,705979059];function v(e){const t=e>>25;let n=(33554431&e)<<5;for(let e=0;e<b.length;e++)1==(t>>e&1)&&(n^=b[e]);return n}function w(e,t,n=1){const s=e.length;let r=1;for(let t=0;t<s;t++){const n=e.charCodeAt(t);if(n<33||n>126)throw new Error(`Invalid prefix (${e})`);r=v(r)^n>>5}r=v(r);for(let t=0;t<s;t++)r=v(r)^31&e.charCodeAt(t);for(let e of t)r=v(r)^e;for(let e=0;e<6;e++)r=v(r);return r^=n,m.encode(u([r%2**30],30,5,!1))}function _(e){const t="bech32"===e?1:734539939,n=h(5),s=n.decode,r=n.encode,i=p(s);function o(e,n=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==n&&e.length>n)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${n})`);const s=e.toLowerCase();if(e!==s&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const r=(e=s).lastIndexOf("1");if(0===r||-1===r)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,r),o=e.slice(r+1);if(o.length<6)throw new Error("Data must be at least 6 characters long");const a=m.decode(o).slice(0,-6),c=w(i,a,t);if(!o.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,n,s=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);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 r=e.length+7+n.length;if(!1!==s&&r>s)throw new TypeError(`Length ${r} exceeds limit ${s}`);return`${e=e.toLowerCase()}1${m.encode(n)}${w(e,n,t)}`},decode:o,decodeToBytes:function(e){const{prefix:t,words:n}=o(e,!1);return{prefix:t,words:n,bytes:s(n)}},decodeUnsafe:p(o),fromWords:s,fromWordsUnsafe:i,toWords:r}}e.bech32=_("bech32"),e.bech32m=_("bech32m"),e.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},e.hex=n(h(4),s("0123456789abcdef"),r(""),o(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const E={utf8:e.utf8,hex:e.hex,base16:e.base16,base32:e.base32,base64:e.base64,base64url:e.base64url,base58:e.base58,base58xmr:e.base58xmr},k=`Invalid encoding type. Available types: ${Object.keys(E).join(", ")}`;e.bytesToString=(e,t)=>{if("string"!=typeof e||!E.hasOwnProperty(e))throw new TypeError(k);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return E[e].encode(t)},e.str=e.bytesToString;e.stringToBytes=(e,t)=>{if(!E.hasOwnProperty(e))throw new TypeError(k);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return E[e].decode(t)},e.bytes=e.stringToBytes}(lib),BigInt(1e3),BigInt(1e6),BigInt(1e9),BigInt(1e12),BigInt("2100000000000000000"),BigInt(1e11);const TAGCODES={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27};for(let e=0,t=Object.keys(TAGCODES);e<t.length;e++)t[e],TAGCODES[t[e]].toString();var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__copyProps=(e,t,n,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of __getOwnPropNames(t))__hasOwnProp.call(e,r)||r===n||__defProp(e,r,{get:()=>t[r],enumerable:!(s=__getOwnPropDesc(t,r))||s.enumerable});return e},__reExport=(e,t,n)=>(__copyProps(e,t,"default"),n&&__copyProps(n,t,"default"));function getRelaysForSync(e,t,n="write"){if(!e.outboxTracker)return;const s=e.outboxTracker.data.get(t);return s?"write"===n?s.writeRelays:s.readRelays:void 0}async function getWriteRelaysFor(e,t,n="write"){if(e.outboxTracker)return e.outboxTracker.data.has(t)||await e.outboxTracker.trackUsers([t]),getRelaysForSync(e,t,n)}function getTopRelaysForAuthors(e,t){const n=new Map;t.forEach(t=>{const s=getRelaysForSync(e,t);s&&s.forEach(e=>{const t=n.get(e)||0;n.set(e,t+1)})});return Array.from(n.entries()).sort((e,t)=>t[1]-e[1]).map(e=>e[0])}function getAllRelaysForAllPubkeys(e,t,n="read"){const s=new Map,r=new Set;return t.forEach(t=>{const i=getRelaysForSync(e,t,n);i&&i.size>0?(i.forEach(e=>{(s.get(e)||new Set).add(t)}),s.set(t,i)):r.add(t)}),{pubkeysToRelays:s,authorsMissingRelays:r}}function chooseRelayCombinationForPubkeys(e,t,n,{count:s,preferredRelays:r}={}){s??=2,r??=new Set;const i=e.pool,o=i.connectedRelays();o.forEach(e=>{r?.add(e.url)});const a=new Map,{pubkeysToRelays:c,authorsMissingRelays:l}=getAllRelaysForAllPubkeys(e,t,n),u=getTopRelaysForAuthors(e,t),d=(e,t)=>{const n=a.get(t)||[];n.push(e),a.set(t,n)};for(const[e,t]of c.entries()){let n=s;const r=new Set;for(const s of o)t.has(s.url)&&(d(e,s.url),r.add(s.url),n--);for(const s of t)r.has(s)||a.has(s)&&(d(e,s),r.add(s),n--);if(!(n<=0))for(const s of u){if(n<=0)break;r.has(s)||t.has(s)&&(d(e,s),r.add(s),n--)}}for(const e of l)i.permanentAndConnectedRelays().forEach(t=>{const n=a.get(t.url)||[];n.push(e),a.set(t.url,n)});return a}function getRelaysForFilterWithAuthors(e,t,n=2){return chooseRelayCombinationForPubkeys(e,t,"write",{count:n})}function tryNormalizeRelayUrl(e){try{return normalizeRelayUrl(e)}catch{return}}function normalizeRelayUrl(e){let t=normalizeUrl(e,{stripAuthentication:!1,stripWWW:!1,stripHash:!0});return t.endsWith("/")||(t+="/"),t}function normalize(e){const t=new Set;for(const n of e)try{t.add(normalizeRelayUrl(n))}catch{}return Array.from(t)}var DATA_URL_DEFAULT_MIME_TYPE="text/plain",DATA_URL_DEFAULT_CHARSET="us-ascii",testParameter=(e,t)=>t.some(t=>t instanceof RegExp?t.test(e):t===e),supportedProtocols=new Set(["https:","http:","file:"]),hasCustomProtocol=e=>{try{const{protocol:t}=new URL(e);return t.endsWith(":")&&!t.includes(".")&&!supportedProtocols.has(t)}catch{return!1}},normalizeDataURL=(e,{stripHash:t})=>{const n=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(e);if(!n)throw new Error(`Invalid URL: ${e}`);const s=n.groups?.type??"",r=n.groups?.data??"";let i=n.groups?.hash??"";const o=s.split(";");i=t?"":i;let a=!1;"base64"===o[o.length-1]&&(o.pop(),a=!0);const c=o.shift()?.toLowerCase()??"",l=[...o.map(e=>{let[t,n=""]=e.split("=").map(e=>e.trim());return"charset"===t&&(n=n.toLowerCase(),n===DATA_URL_DEFAULT_CHARSET)?"":`${t}${n?`=${n}`:""}`}).filter(Boolean)];return a&&l.push("base64"),(l.length>0||c&&c!==DATA_URL_DEFAULT_MIME_TYPE)&&l.unshift(c),`data:${l.join(";")},${a?r.trim():r}${i?`#${i}`:""}`};function normalizeUrl(e,t={}){if("string"!=typeof(t={defaultProtocol:"http",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,removeExplicitPort:!1,sortQueryParameters:!0,...t}).defaultProtocol||t.defaultProtocol.endsWith(":")||(t.defaultProtocol=`${t.defaultProtocol}:`),e=e.trim(),/^data:/i.test(e))return normalizeDataURL(e,t);if(hasCustomProtocol(e))return e;const n=e.startsWith("//");!n&&/^\.*\//.test(e)||(e=e.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,t.defaultProtocol));const s=new URL(e);if(s.hostname=s.hostname.toLowerCase(),t.forceHttp&&t.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(t.forceHttp&&"https:"===s.protocol&&(s.protocol="http:"),t.forceHttps&&"http:"===s.protocol&&(s.protocol="https:"),t.stripAuthentication&&(s.username="",s.password=""),t.stripHash?s.hash="":t.stripTextFragment&&(s.hash=s.hash.replace(/#?:~:text.*?$/i,"")),s.pathname){const e=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let t=0,n="";for(;;){const r=e.exec(s.pathname);if(!r)break;const i=r[0],o=r.index;n+=s.pathname.slice(t,o).replace(/\/{2,}/g,"/"),n+=i,t=o+i.length}n+=s.pathname.slice(t,s.pathname.length).replace(/\/{2,}/g,"/"),s.pathname=n}if(s.pathname)try{s.pathname=decodeURI(s.pathname)}catch{}if(!0===t.removeDirectoryIndex&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let e=s.pathname.split("/");const n=e[e.length-1];testParameter(n,t.removeDirectoryIndex)&&(e=e.slice(0,-1),s.pathname=`${e.slice(1).join("/")}/`)}if(s.hostname&&(s.hostname=s.hostname.replace(/\.$/,""),t.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(s.hostname)&&(s.hostname=s.hostname.replace(/^www\./,""))),Array.isArray(t.removeQueryParameters))for(const e of[...s.searchParams.keys()])testParameter(e,t.removeQueryParameters)&&s.searchParams.delete(e);if(Array.isArray(t.keepQueryParameters)||!0!==t.removeQueryParameters||(s.search=""),Array.isArray(t.keepQueryParameters)&&t.keepQueryParameters.length>0)for(const e of[...s.searchParams.keys()])testParameter(e,t.keepQueryParameters)||s.searchParams.delete(e);if(t.sortQueryParameters){s.searchParams.sort();try{s.search=decodeURIComponent(s.search)}catch{}}t.removeTrailingSlash&&(s.pathname=s.pathname.replace(/\/$/,"")),t.removeExplicitPort&&s.port&&(s.port="");const r=e;return e=s.toString(),t.removeSingleSlash||"/"!==s.pathname||r.endsWith("/")||""!==s.hash||(e=e.replace(/\/$/,"")),(t.removeTrailingSlash||"/"===s.pathname)&&""===s.hash&&t.removeSingleSlash&&(e=e.replace(/\/$/,"")),n&&!t.normalizeProtocol&&(e=e.replace(/^http:\/\//,"//")),t.stripProtocol&&(e=e.replace(/^(?:https?:)?\/\//,"")),e}var NDKRelayKeepalive=class{constructor(e=3e4,t){this.onSilenceDetected=t,this.timeout=e}lastActivity=Date.now();timer;timeout;isRunning=!1;recordActivity(){this.lastActivity=Date.now(),this.isRunning&&this.resetTimer()}start(){this.isRunning||(this.isRunning=!0,this.lastActivity=Date.now(),this.resetTimer())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}resetTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{const e=Date.now()-this.lastActivity;if(e>=this.timeout)this.onSilenceDetected();else{const t=this.timeout-e;this.timer=setTimeout(()=>{this.onSilenceDetected()},t)}},this.timeout)}};async function probeRelayConnection(e){const t=`probe-${Math.random().toString(36).substring(7)}`;return new Promise(n=>{let s=!1;const r=setTimeout(()=>{s||(s=!0,e.send(["CLOSE",t]),n(!1))},5e3);e.once("message",()=>{s||(s=!0,clearTimeout(r),e.send(["CLOSE",t]),n(!0))}),e.send(["REQ",t,{kinds:[99999],limit:0}])})}var MAX_RECONNECT_ATTEMPTS=5,FLAPPING_THRESHOLD_MS=1e3,NDKRelayConnectivity=class{ndkRelay;ws;_status;timeoutMs;connectedAt;_connectionStats={attempts:0,success:0,durations:[]};debug;netDebug;connectTimeout;reconnectTimeout;ndk;openSubs=new Map;openCountRequests=new Map;openEventPublishes=new Map;serial=0;baseEoseTimeout=4400;keepalive;wsStateMonitor;sleepDetector;lastSleepCheck=Date.now();lastMessageSent=Date.now();wasIdle=!1;constructor(e,t){this.ndkRelay=e,this._status=1;const n=Math.floor(1e3*Math.random());this.debug=this.ndkRelay.debug.extend(`connectivity${n}`),this.ndk=t,this.setupMonitoring()}setupMonitoring(){this.keepalive=new NDKRelayKeepalive(12e4,async()=>{this.debug("Relay silence detected, probing connection");await probeRelayConnection({send:e=>this.send(JSON.stringify(e)),once:(e,t)=>{const n=e=>{try{const s=JSON.parse(e.data);"EOSE"!==s[0]&&"EVENT"!==s[0]&&"NOTICE"!==s[0]||(t(),this.ws?.removeEventListener("message",n))}catch{}};this.ws?.addEventListener("message",n)}})||(this.debug("Probe failed, connection is stale"),this.handleStaleConnection())}),this.wsStateMonitor=setInterval(()=>{5===this._status&&(this.ws&&this.ws.readyState===WebSocket.OPEN||(this.debug("WebSocket died silently, reconnecting"),this.handleStaleConnection()))},5e3),this.sleepDetector=setInterval(()=>{const e=Date.now(),t=e-this.lastSleepCheck;t>15e3&&(this.debug(`Detected possible sleep/wake (${t}ms gap)`),this.handlePossibleWake()),this.lastSleepCheck=e},1e4)}handleStaleConnection(){this._status=1,this.wasIdle=!0,this.onDisconnect()}handlePossibleWake(){this.debug("System wake detected, checking all connections"),this.wasIdle=!0,this._status>=5&&(this.ws&&this.ws.readyState===WebSocket.OPEN?probeRelayConnection({send:e=>this.send(JSON.stringify(e)),once:(e,t)=>{const n=e=>{try{const s=JSON.parse(e.data);"EOSE"!==s[0]&&"EVENT"!==s[0]&&"NOTICE"!==s[0]||(t(),this.ws?.removeEventListener("message",n))}catch{}};this.ws?.addEventListener("message",n)}}).then(e=>{e||this.handleStaleConnection()}):this.handleStaleConnection())}resetReconnectionState(){this.wasIdle=!0,this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}async connect(e,t=!0){if(this.ws&&this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING){this.debug("Cleaning up stale WebSocket connection");try{this.ws.close()}catch(e){}this.ws=void 0,this._status=1}if(2!==this._status&&1!==this._status||this.reconnectTimeout)this.debug("Relay requested to be connected but was in state %s or it had a reconnect timeout",this._status);else{this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),e??=this.timeoutMs,!this.timeoutMs&&e&&(this.timeoutMs=e),this.timeoutMs&&(this.connectTimeout=setTimeout(()=>this.onConnectionError(t),this.timeoutMs));try{this.updateConnectionStats.attempt(),1===this._status?this._status=4:this._status=2,this.ws=new WebSocket(this.ndkRelay.url),this.ws.onopen=this.onConnect.bind(this),this.ws.onclose=this.onDisconnect.bind(this),this.ws.onmessage=this.onMessage.bind(this),this.ws.onerror=this.onError.bind(this)}catch(e){throw this.debug(`Failed to connect to ${this.ndkRelay.url}`,e),this._status=1,t?this.handleReconnection():this.ndkRelay.emit("delayed-connect",1728e5),e}}}disconnect(){this._status=0,this.keepalive?.stop(),this.wsStateMonitor&&(clearInterval(this.wsStateMonitor),this.wsStateMonitor=void 0),this.sleepDetector&&(clearInterval(this.sleepDetector),this.sleepDetector=void 0);try{this.ws?.close()}catch(e){this.debug("Failed to disconnect",e),this._status=1}}onConnectionError(e){this.debug(`Error connecting to ${this.ndkRelay.url}`,this.timeoutMs),e&&!this.reconnectTimeout&&this.handleReconnection()}onConnect(){this.netDebug?.("connected",this.ndkRelay),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.updateConnectionStats.connected(),this._status=5,this.keepalive?.start(),this.wasIdle=!1,this.ndkRelay.emit("connect"),this.ndkRelay.emit("ready")}onDisconnect(){this.netDebug?.("disconnected",this.ndkRelay),this.updateConnectionStats.disconnected(),this.keepalive?.stop(),5===this._status&&this.handleReconnection(),this._status=1,this.ndkRelay.emit("disconnect")}onMessage(e){this.netDebug?.(e.data,this.ndkRelay,"recv"),this.keepalive?.recordActivity();try{const t=JSON.parse(e.data),[n,s,...r]=t,i=this.ndkRelay.getProtocolHandler(n);if(i)return void i(this.ndkRelay,t);switch(n){case"EVENT":{const e=this.openSubs.get(s),n=t[2];return e?void e.onevent(n):void this.debug(`Received event for unknown subscription ${s}`)}case"COUNT":{const e=t[2],n=this.openCountRequests.get(s);return void(n&&(n.resolve(e.count),this.openCountRequests.delete(s)))}case"EOSE":{const e=this.openSubs.get(s);if(!e)return;return void e.oneose(s)}case"OK":{const e=t[2],n=t[3],r=this.openEventPublishes.get(s),i=r?.pop();return r&&i?(e?i.resolve(n):i.reject(new Error(n)),void(0===r.length?this.openEventPublishes.delete(s):this.openEventPublishes.set(s,r))):void this.debug("Received OK for unknown event publish",s)}case"CLOSED":{const e=this.openSubs.get(s);if(!e)return;return void e.onclosed(t[2])}case"NOTICE":return void this.onNotice(t[1]);case"AUTH":return void this.onAuthRequested(t[1])}}catch(e){return void this.debug(`Error parsing message from ${this.ndkRelay.url}: ${e.message}`,e?.stack)}}async onAuthRequested(e){const t=this.ndkRelay.authPolicy??this.ndk?.relayAuthDefaultPolicy;if(this.debug("Relay requested authentication",{havePolicy:!!t}),7!==this._status)if(this._status=6,t){if(this._status>=5){let n;this._status=7;try{n=await t(this.ndkRelay,e)}catch(e){this.debug("Authentication policy threw an error",e),n=!1}if(this.debug("Authentication policy returned",!!n),n instanceof NDKEvent||!0===n){n instanceof NDKEvent&&await this.auth(n);const t=async()=>{if(this._status>=5&&this._status<8){const t=new NDKEvent(this.ndk);t.kind=22242,t.tags=[["relay",this.ndkRelay.url],["challenge",e]],await t.sign(),this.auth(t).then(()=>{this._status=8,this.ndkRelay.emit("authed"),this.debug("Authentication successful")}).catch(e=>{this._status=6,this.ndkRelay.emit("auth:failed",e),this.debug("Authentication failed",e)})}else this.debug("Authentication failed, it changed status, status is %d",this._status)};!0===n&&(this.ndk?.signer?t().catch(e=>{console.error("Error authenticating",e)}):(this.debug("No signer available for authentication localhost"),this.ndk?.once("signer:ready",t))),this._status=5,this.ndkRelay.emit("authed")}}}else this.ndkRelay.emit("auth",e);else this.debug("Already authenticating, ignoring")}onError(e){this.debug(`WebSocket error on ${this.ndkRelay.url}:`,e)}get status(){return this._status}isAvailable(){return 5===this._status}isFlapping(){const e=this._connectionStats.durations;if(e.length%3!=0)return!1;const t=e.reduce((e,t)=>e+t,0)/e.length,n=e.map(e=>(e-t)**2).reduce((e,t)=>e+t,0)/e.length;return Math.sqrt(n)<FLAPPING_THRESHOLD_MS}async onNotice(e){this.ndkRelay.emit("notice",e)}handleReconnection(e=0){if(this.reconnectTimeout)return;if(this.isFlapping())return this.ndkRelay.emit("flapping",this._connectionStats),void(this._status=3);let t;if(this.wasIdle){const n=[0,1e3,2e3,5e3,1e4,3e4];t=n[Math.min(e,n.length-1)],this.debug(`Using aggressive reconnect after idle, attempt ${e}, delay ${t}ms`)}else this.connectedAt?t=Math.max(0,6e4-(Date.now()-this.connectedAt)):(t=Math.min(1e3*2**e,3e4),this.debug(`Using standard backoff, attempt ${e}, delay ${t}ms`));this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=void 0,this._status=2,this.connect().catch(t=>{e<MAX_RECONNECT_ATTEMPTS?this.handleReconnection(e+1):(this.debug("Max reconnect attempts reached"),this.wasIdle=!1)})},t),this.ndkRelay.emit("delayed-connect",t),this.debug("Reconnecting in",t),this._connectionStats.nextReconnectAt=Date.now()+t}async send(e){Date.now()-this.lastMessageSent>12e4&&(this.wasIdle=!0),this._status>=5&&this.ws?.readyState===WebSocket.OPEN?(this.ws?.send(e),this.netDebug?.(e,this.ndkRelay,"send"),this.lastMessageSent=Date.now()):(this.debug(`Not connected to ${this.ndkRelay.url} (%d), not sending message ${e}`,this._status),this._status>=5&&this.ws?.readyState!==WebSocket.OPEN&&(this.debug(`Stale connection detected, WebSocket state: ${this.ws?.readyState}`),this.handleStaleConnection()))}async auth(e){const t=new Promise((t,n)=>{const s=this.openEventPublishes.get(e.id)??[];s.push({resolve:t,reject:n}),this.openEventPublishes.set(e.id,s)});return this.send(`["AUTH",${JSON.stringify(e.rawEvent())}]`),t}async publish(e){const t=new Promise((t,n)=>{const s=this.openEventPublishes.get(e.id)??[];s.length>0&&console.warn(`Duplicate event publishing detected, you are publishing event ${e.id} twice`),s.push({resolve:t,reject:n}),this.openEventPublishes.set(e.id,s)});return this.send(`["EVENT",${JSON.stringify(e)}]`),t}async count(e,t){this.serial++;const n=t?.id||`count:${this.serial}`,s=new Promise((e,t)=>{this.openCountRequests.set(n,{resolve:e,reject:t})});return this.send(`["COUNT","${n}",${JSON.stringify(e).substring(1)}`),s}close(e,t){this.send(`["CLOSE","${e}"]`);const n=this.openSubs.get(e);this.openSubs.delete(e),n&&n.onclose(t)}req(e){this.send(`["REQ","${e.subId}",${JSON.stringify(e.executeFilters).substring(1)}`),this.openSubs.set(e.subId,e)}updateConnectionStats={connected:()=>{this._connectionStats.success++,this._connectionStats.connectedAt=Date.now()},disconnected:()=>{this._connectionStats.connectedAt&&(this._connectionStats.durations.push(Date.now()-this._connectionStats.connectedAt),this._connectionStats.durations.length>100&&this._connectionStats.durations.shift()),this._connectionStats.connectedAt=void 0},attempt:()=>{this._connectionStats.attempts++,this._connectionStats.connectedAt=Date.now()}};get connectionStats(){return this._connectionStats}get url(){return this.ndkRelay.url}get connected(){return this._status>=5&&this.ws?.readyState===WebSocket.OPEN}};async function fetchRelayInformation(e){const t=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://"),n=await fetch(t,{headers:{Accept:"application/nostr+json"}});if(!n.ok)throw new Error(`Failed to fetch relay information: ${n.status} ${n.statusText}`);return await n.json()}var NDKRelayPublisher=class{ndkRelay;debug;constructor(e){this.ndkRelay=e,this.debug=e.debug.extend("publisher")}async publish(e,t=2500){let n;const s=()=>new Promise((t,n)=>{try{this.publishEvent(e).then(n=>{this.ndkRelay.emit("published",e),e.emit("relay:published",this.ndkRelay),t(!0)}).catch(n)}catch(e){n(e)}}),r=new Promise((e,s)=>{n=setTimeout(()=>{n=void 0,s(new Error(`Timeout: ${t}ms`))},t)}),i=()=>{s().then(e=>o(e)).catch(e=>a(e))};let o,a;const c=t=>{throw this.ndkRelay.debug("Publish failed",t,e.id),this.ndkRelay.emit("publish:failed",e,t),e.emit("relay:publish:failed",this.ndkRelay,t),t},l=()=>{n&&clearTimeout(n),this.ndkRelay.removeListener("connect",i)};return this.ndkRelay.status>=5?Promise.race([s(),r]).catch(c).finally(l):(this.ndkRelay.status<=1?(console.warn("Relay is disconnected, trying to connect to publish an event",this.ndkRelay.url),this.ndkRelay.connect()):console.warn("Relay not connected, waiting for connection to publish an event",this.ndkRelay.url),Promise.race([new Promise((e,t)=>{o=e,a=t,this.ndkRelay.on("connect",i)}),r]).catch(c).finally(l))}async publishEvent(e){return this.ndkRelay.connectivity.publish(e.rawEvent())}};function filterFingerprint(e,t){const n=[];for(const t of e){const e=Object.entries(t||{}).map(([e,t])=>["since","until"].includes(e)?`${e}:${t}`:e).sort().join("-");n.push(e)}let s=t?"+":"";return s+=n.join("|"),s}function mergeFilters(e){const t=[],n={};return e.filter(e=>!!e.limit).forEach(e=>t.push(e)),0===(e=e.filter(e=>!e.limit)).length?t:(e.forEach(e=>{Object.entries(e).forEach(([e,t])=>{Array.isArray(t)?void 0===n[e]?n[e]=[...t]:n[e]=Array.from(new Set([...n[e],...t])):n[e]=t})}),[...t,n])}var MAX_ITEMS=3;function formatArray(e,t){const n=(t?e.slice(0,MAX_ITEMS).map(t):e.slice(0,MAX_ITEMS)).join(",");return e.length>MAX_ITEMS?`${n}+${e.length-MAX_ITEMS}`:n}function formatFilters(e){return e.map(e=>{const t=[];e.ids?.length&&t.push(`ids:[${formatArray(e.ids,e=>String(e).slice(0,8))}]`),e.kinds?.length&&t.push(`kinds:[${formatArray(e.kinds)}]`),e.authors?.length&&t.push(`authors:[${formatArray(e.authors,e=>String(e).slice(0,8))}]`),e.since&&t.push(`since:${e.since}`),e.until&&t.push(`until:${e.until}`),e.limit&&t.push(`limit:${e.limit}`),e.search&&t.push(`search:"${String(e.search).slice(0,20)}"`);for(const[n,s]of Object.entries(e))n.startsWith("#")&&Array.isArray(s)&&s.length>0&&t.push(`${n}:[${formatArray(s,e=>String(e).slice(0,8))}]`);return`{${t.join(" ")}}`}).join(", ")}var NDKRelaySubscription=class{fingerprint;items=new Map;topSubManager;debug;status=0;onClose;relay;eosed=!1;executionTimer;fireTime;delayType;executeFilters;id=Math.random().toString(36).substring(7);constructor(e,t,n){this.relay=e,this.topSubManager=n,this.debug=e.debug.extend(`sub[${this.id}]`),this.fingerprint=t||Math.random().toString(36).substring(7)}_subId;get subId(){return this._subId||(this._subId=this.fingerprint.slice(0,15)),this._subId}subIdParts=new Set;addSubIdPart(e){this.subIdParts.add(e)}addItem(e,t){if(this.debug("Adding item",{filters:formatFilters(t),internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,id:this.subId,itemsSize:this.items.size}),!this.items.has(e.internalId))switch(e.on("close",this.removeItem.bind(this,e)),this.items.set(e.internalId,{subscription:e,filters:t}),3!==this.status&&e.subId&&(!this._subId||this._subId.length<48)&&(0!==this.status&&1!==this.status||this.addSubIdPart(e.subId)),this.status){case 0:case 1:this.evaluateExecutionPlan(e);break;case 3:break;case 4:throw this.debug("Subscription is closed, cannot add new items",{filters:formatFilters(t),subId:e.subId,internalId:e.internalId}),new Error("Cannot add new items to a closed subscription")}}removeItem(e){if(this.items.delete(e.internalId),0===this.items.size){if(!this.eosed)return;this.close(),this.cleanup()}}close(){if(4===this.status)return;const e=this.status;if(this.status=4,3===e)try{this.relay.close(this.subId)}catch(e){this.debug("Error closing subscription",e,this)}else this.debug("Subscription wanted to close but it wasn't running, this is probably ok",{subId:this.subId,prevStatus:e,sub:this});this.cleanup()}cleanup(){this.executionTimer&&clearTimeout(this.executionTimer),this.relay.off("ready",this.executeOnRelayReady),this.relay.off("authed",this.reExecuteAfterAuth),this.onClose&&this.onClose(this)}evaluateExecutionPlan(e){if(!e.isGroupable())return this.status=1,void this.execute();if(e.filters.find(e=>!!e.limit)&&(this.executeFilters=this.compileFilters(),this.executeFilters.length>=10))return this.status=1,void this.execute();const t=e.groupableDelay,n=e.groupableDelayType;if(!t)throw new Error("Cannot group a subscription without a delay");if(0===this.status)this.schedule(t,n);else{const e=this.delayType,s=this.fireTime-Date.now();if("at-least"===e&&"at-least"===n)s<t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else if("at-least"===e&&"at-most"===n)s>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else if("at-most"===e&&"at-most"===n)s>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else{if("at-most"!==e||"at-least"!==n)throw new Error(`Unknown delay type combination ${e} ${n}`);s>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n))}}}schedule(e,t){this.status=1;const n=Date.now();this.fireTime=n+e,this.delayType=t;const s=setTimeout(this.execute.bind(this),e);"at-least"===t&&(this.executionTimer=s)}executeOnRelayReady=()=>{if(2===this.status){if(0===this.items.size)return this.debug("No items to execute; this relay was probably too slow to respond and the caller gave up",{status:this.status,fingerprint:this.fingerprint,id:this.id,subId:this.subId}),void this.cleanup();this.debug("Executing on relay ready",{status:this.status,fingerprint:this.fingerprint,itemsSize:this.items.size,filters:formatFilters(this.compileFilters())}),this.status=1,this.execute()}};finalizeSubId(){this.subIdParts.size>0?this._subId=Array.from(this.subIdParts).join("-"):this._subId=this.fingerprint.slice(0,15),this._subId+=`-${Math.random().toString(36).substring(2,7)}`}reExecuteAfterAuth=(()=>{const e=this.subId;this.debug("Re-executing after auth",this.items.size),this.eosed?this.relay.close(this.subId):this.debug("We are abandoning an opened subscription, once it EOSE's, the handler will close it",{oldSubId:e}),this._subId=void 0,this.status=1,this.execute(),this.debug("Re-executed after auth %s 👉 %s",e,this.subId)}).bind(this);execute(){if(1===this.status){if(!this.relay.connected)return this.status=2,this.debug("Waiting for relay to be ready",{status:this.status,id:this.subId,fingerprint:this.fingerprint,itemsSize:this.items.size}),void this.relay.once("ready",this.executeOnRelayReady);this.relay.status<8&&this.relay.once("authed",this.reExecuteAfterAuth),this.status=3,this.finalizeSubId(),this.executeFilters=this.compileFilters(),this.relay.req(this)}}onstart(){}onevent(e){this.topSubManager.dispatchEvent(e,this.relay)}oneose(e){if(this.eosed=!0,e!==this.subId)return this.debug("Received EOSE for an abandoned subscription",e,this.subId),void this.relay.close(e);0===this.items.size&&this.close();for(const{subscription:e}of this.items.values())e.eoseReceived(this.relay),e.closeOnEose&&(this.debug("Removing item because of EOSE",{filters:formatFilters(e.filters),internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,itemsSize:this.items.size}),this.removeItem(e))}onclose(e){this.status=4}onclosed(e){if(e)for(const{subscription:t}of this.items.values())t.closedReceived(this.relay,e)}compileFilters(){const e=[],t=Array.from(this.items.values()).map(e=>e.filters);if(!t[0])return this.debug("👀 No filters to merge",{itemsSize:this.items.size}),[];const n=t[0].length;for(let s=0;s<n;s++){const n=mergeFilters(t.map(e=>e[s]));e.push(...n)}return e}},NDKRelaySubscriptionManager=class{relay;subscriptions;generalSubManager;constructor(e,t){this.relay=e,this.subscriptions=new Map,this.generalSubManager=t}addSubscription(e,t){let n;if(e.isGroupable()){const s=filterFingerprint(t,e.closeOnEose);if(s){n=(this.subscriptions.get(s)||[]).find(e=>e.status<3)}n??=this.createSubscription(e,t,s)}else n=this.createSubscription(e,t);n.addItem(e,t)}createSubscription(e,t,n){const s=new NDKRelaySubscription(this.relay,n||null,this.generalSubManager);s.onClose=this.onRelaySubscriptionClose.bind(this);const r=this.subscriptions.get(s.fingerprint)??[];return this.subscriptions.set(s.fingerprint,[...r,s]),s}onRelaySubscriptionClose(e){let t=this.subscriptions.get(e.fingerprint)??[];t?1===t.length?this.subscriptions.delete(e.fingerprint):(t=t.filter(t=>t.id!==e.id),this.subscriptions.set(e.fingerprint,t)):console.warn("Unexpectedly did not find a subscription with fingerprint",e.fingerprint)}},NDKRelay=class e extends lib$1.EventEmitter{url;scores;connectivity;subs;publisher;authPolicy;protocolHandlers=new Map;_relayInfo;lowestValidationRatio;targetValidationRatio;validationRatioFn;validatedEventCount=0;nonValidatedEventCount=0;trusted=!1;complaining=!1;debug;static defaultValidationRatioUpdateFn=(e,t,n)=>{if(void 0===e.lowestValidationRatio||void 0===e.targetValidationRatio)return 1;let s=e.validationRatio;if(e.validationRatio>e.targetValidationRatio){const n=t/100;s=Math.max(e.lowestValidationRatio,e.validationRatio-n)}return s<e.validationRatio?s:e.validationRatio};constructor(t,n,s){super(),this.url=normalizeRelayUrl(t),this.scores=new Map,this.debug=createDebug5(`ndk:relay:${t}`),this.connectivity=new NDKRelayConnectivity(this,s),this.connectivity.netDebug=s?.netDebug,this.req=this.connectivity.req.bind(this.connectivity),this.close=this.connectivity.close.bind(this.connectivity),this.subs=new NDKRelaySubscriptionManager(this,s.subManager),this.publisher=new NDKRelayPublisher(this),this.authPolicy=n,this.targetValidationRatio=s?.initialValidationRatio,this.lowestValidationRatio=s?.lowestValidationRatio,this.validationRatioFn=(s?.validationRatioFn??e.defaultValidationRatioUpdateFn).bind(this),this.updateValidationRatio(),s||console.trace("relay created without ndk")}updateValidationRatio(){if(this.validationRatioFn&&this.validatedEventCount>0){const e=this.validationRatioFn(this,this.validatedEventCount,this.nonValidatedEventCount);this.targetValidationRatio=e}setTimeout(()=>{this.updateValidationRatio()},3e4)}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(e,t=!0){return this.connectivity.connect(e,t)}disconnect(){1!==this.status&&this.connectivity.disconnect()}subscribe(e,t){this.subs.addSubscription(e,t)}async publish(e,t=2500){return this.publisher.publish(e,t)}referenceTags(){return[["r",this.url]]}addValidatedEvent(){this.validatedEventCount++}addNonValidatedEvent(){this.nonValidatedEventCount++}get validationRatio(){return 0===this.nonValidatedEventCount?1:this.validatedEventCount/(this.validatedEventCount+this.nonValidatedEventCount)}shouldValidateEvent(){return!this.trusted&&(void 0===this.targetValidationRatio||(this.targetValidationRatio>=1||Math.random()<this.targetValidationRatio))}get connected(){return this.connectivity.connected}req;close;registerProtocolHandler(e,t){this.protocolHandlers.set(e,t)}unregisterProtocolHandler(e){this.protocolHandlers.delete(e)}getProtocolHandler(e){return this.protocolHandlers.get(e)}async fetchInfo(e=!1){const t=this.connectivity.ndk;if(!e&&t?.cacheAdapter?.getRelayStatus){const e=await t.cacheAdapter.getRelayStatus(this.url);if(e?.nip11&&Date.now()-e.nip11.fetchedAt<864e5)return this._relayInfo=e.nip11.data,e.nip11.data}return!e&&this._relayInfo||(this._relayInfo=await fetchRelayInformation(this.url),t?.cacheAdapter?.updateRelayStatus&&await t.cacheAdapter.updateRelayStatus(this.url,{nip11:{data:this._relayInfo,fetchedAt:Date.now()}})),this._relayInfo}get info(){return this._relayInfo}},NDKPublishError=class extends Error{errors;publishedToRelays;intendedRelaySet;constructor(e,t,n,s){super(e),this.errors=t,this.publishedToRelays=n,this.intendedRelaySet=s}get relayErrors(){const e=[];for(const[t,n]of this.errors)e.push(`${t.url}: ${n}`);return e.join("\n")}},NDKRelaySet=class e{relays;debug;ndk;pool;constructor(e,t,n){this.relays=e,this.ndk=t,this.pool=n??t.pool,this.debug=t.debug.extend("relayset")}addRelay(e){this.relays.add(e)}get relayUrls(){return Array.from(this.relays).map(e=>e.url)}static fromRelayUrls(t,n,s=!0,r){if(!(r=r??n.pool))throw new Error("No pool provided");const i=new Set;for(const e of t){const o=r.relays.get(normalizeRelayUrl(e));if(o)o.status<5&&s&&o.connect(),i.add(o);else{const s=new NDKRelay(normalizeRelayUrl(e),n?.relayAuthDefaultPolicy,n);r.useTemporaryRelay(s,void 0,`requested from fromRelayUrls ${t}`),i.add(s)}}return new e(new Set(i),n,r)}async publish(e,t,n=1){const s=new Set,r=new Map,i=e.isEphemeral();e.publishStatus="pending";const o=e=>{s.add(e)};e.on("relay:published",o);try{const o=Array.from(this.relays).map(n=>new Promise(o=>{const a=t?setTimeout(()=>{s.has(n)||(r.set(n,new Error(`Publish timeout after ${t}ms`)),o(!1))},t):null;n.publish(e,t).then(e=>{a&&clearTimeout(a),e?(s.add(n),o(!0)):o(!1)}).catch(e=>{a&&clearTimeout(a),i||r.set(n,e),o(!1)})}));if(await Promise.all(o),s.size<n){if(!i){const t=new NDKPublishError("Not enough relays received the event ("+s.size+" published, "+n+" required)",r,s,this);throw e.publishStatus="error",e.publishError=t,this.ndk?.emit("event:publish-failed",e,t,this.relayUrls),t}}else e.publishStatus="success",e.emit("published",{relaySet:this,publishedToRelays:s});return s}finally{e.off("relay:published",o)}}get size(){return this.relays.size}},d=createDebug5("ndk:outbox:calculate");async function calculateRelaySetFromEvent(e,t,n){const s=new Set,r=await getWriteRelaysFor(e,t.pubkey);r&&r.forEach(t=>{const n=e.pool?.getRelay(t);n&&s.add(n)});let i=t.tags.filter(e=>["a","e"].includes(e[0])).map(e=>e[2]).filter(e=>e?.startsWith("wss://")).filter(e=>{try{return new URL(e),!0}catch{return!1}}).map(e=>normalizeRelayUrl(e));i=Array.from(new Set(i)).slice(0,5),i.forEach(t=>{const n=e.pool?.getRelay(t,!0,!0);n&&(d("Adding relay hint %s",t),s.add(n))});const o=t.getMatchingTags("p").map(e=>e[1]);if(o.length<5){Array.from(chooseRelayCombinationForPubkeys(e,o,"read",{preferredRelays:new Set(r)}).keys()).forEach(t=>{const n=e.pool?.getRelay(t,!1,!0);n&&(d("Adding p-tagged relay %s",t),s.add(n))})}else d("Too many p-tags to consider %d",o.length);if(e.pool?.permanentAndConnectedRelays().forEach(e=>s.add(e)),n&&s.size<n){const t=e.explicitRelayUrls?.filter(e=>!Array.from(s).some(t=>t.url===e)).slice(0,n-s.size);t?.forEach(t=>{const n=e.pool?.getRelay(t,!1,!0);n&&(d("Adding explicit relay %s",t),s.add(n))})}return new NDKRelaySet(s,e)}function calculateRelaySetsFromFilter(e,t,n,s){const r=new Map,i=new Set;if(t.forEach(e=>{e.authors&&e.authors.forEach(e=>i.add(e))}),i.size>0){const n=getRelaysForFilterWithAuthors(e,Array.from(i),s);for(const e of n.keys())r.set(e,[]);for(const e of t)if(e.authors)for(const[t,s]of n.entries()){const n=e.authors.filter(e=>s.includes(e));r.set(t,[...r.get(t),{...e,authors:n}])}else for(const t of n.keys())r.set(t,[...r.get(t),e])}else e.explicitRelayUrls&&e.explicitRelayUrls.forEach(e=>{r.set(e,t)});return 0===r.size&&n.permanentAndConnectedRelays().slice(0,5).forEach(e=>{r.set(e.url,t)}),r}function calculateRelaySetsFromFilters(e,t,n,s){return calculateRelaySetsFromFilter(e,t,n,s)}function checkMissingKind(e,t){void 0!==e.kind&&null!==e.kind||t("event-missing-kind",`Cannot sign event without 'kind'.\n\n📦 Event data:\n • content: ${e.content?`"${e.content.substring(0,50)}${e.content.length>50?"...":""}"`:"(empty)"}\n • tags: ${e.tags.length} tag${1!==e.tags.length?"s":""}\n • kind: ${e.kind} ❌\n\nSet event.kind before signing.`,"Example: event.kind = 1; // for text note",!1)}function checkContentIsObject(e,t){if("object"==typeof e.content){const n=JSON.stringify(e.content,null,2).substring(0,200);t("event-content-is-object",`Event content is an object. Content must be a string.\n\n📦 Your content (${typeof e.content}):\n${n}${JSON.stringify(e.content).length>200?"...":""}\n\n❌ event.content = { ... } // WRONG\n✅ event.content = JSON.stringify({ ... }) // CORRECT`,"Use JSON.stringify() for structured data: event.content = JSON.stringify(data)",!1)}}function checkCreatedAtMilliseconds(e,t){if(e.created_at&&e.created_at>1e10){const n=Math.floor(e.created_at/1e3),s=new Date(e.created_at).toISOString();t("event-created-at-milliseconds",`Event created_at is in milliseconds, not seconds.\n\n📦 Your value:\n • created_at: ${e.created_at} ❌\n • Interpreted as: ${s}\n • Should be: ${n} ✅\n\nNostr timestamps MUST be in seconds since Unix epoch.`,"Use Math.floor(Date.now() / 1000) instead of Date.now()",!1)}}function checkInvalidPTags(e,t){e.getMatchingTags("p").forEach((e,n)=>{if(e[1]&&!/^[0-9a-f]{64}$/i.test(e[1])){const s=JSON.stringify(e);t("tag-invalid-p-tag",`p-tag[${n}] has invalid pubkey.\n\n📦 Your tag:\n ${s}\n\n❌ Invalid value: "${e[1]}"\n • Length: ${e[1].length} (expected 64)\n • Format: ${e[1].startsWith("npub")?"bech32 (npub)":"unknown"}\n\np-tags MUST contain 64-character hex pubkeys.`,e[1].startsWith("npub")?"Use ndkUser.pubkey instead of npub:\n ✅ event.tags.push(['p', ndkUser.pubkey])\n ❌ event.tags.push(['p', 'npub1...'])":"p-tags must contain valid hex pubkeys (64 characters, 0-9a-f)",!1)}})}function checkInvalidETags(e,t){e.getMatchingTags("e").forEach((e,n)=>{if(e[1]&&!/^[0-9a-f]{64}$/i.test(e[1])){const s=JSON.stringify(e),r=e[1].startsWith("note")||e[1].startsWith("nevent");t("tag-invalid-e-tag",`e-tag[${n}] has invalid event ID.\n\n📦 Your tag:\n ${s}\n\n❌ Invalid value: "${e[1]}"\n • Length: ${e[1].length} (expected 64)\n • Format: ${r?"bech32 (note/nevent)":"unknown"}\n\ne-tags MUST contain 64-character hex event IDs.`,r?"Use event.id instead of bech32:\n ✅ event.tags.push(['e', referencedEvent.id])\n ❌ event.tags.push(['e', 'note1...'])":"e-tags must contain valid hex event IDs (64 characters, 0-9a-f)",!1)}})}function checkManualReplyMarkers(e,t,n){if(1!==e.kind)return;if(n.has(e))return;const s=e.tags.filter(e=>"e"===e[0]&&("reply"===e[3]||"root"===e[3]));if(s.length>0){const e=s.map((e,t)=>` ${t+1}. ${JSON.stringify(e)}`).join("\n");t("event-manual-reply-markers",`Event has ${s.length} e-tag(s) with manual reply/root markers.\n\n📦 Your tags with markers:\n${e}\n\n⚠️ Manual reply markers detected! This will cause incorrect threading.`,"Reply events MUST be created using .reply():\n\n ✅ CORRECT:\n const replyEvent = originalEvent.reply();\n replyEvent.content = 'good point!';\n await replyEvent.publish();\n\n ❌ WRONG:\n event.tags.push(['e', eventId, '', 'reply']);\n\nNDK handles all reply threading automatically - never add reply/root markers manually.")}}function signing(e,t,n,s){checkMissingKind(e,t),checkContentIsObject(e,t),checkCreatedAtMilliseconds(e,t),checkInvalidPTags(e,t),checkInvalidETags(e,t),checkManualReplyMarkers(e,n,s)}function isNip33Pattern(e){const t=Array.isArray(e)?e:[e];if(1!==t.length)return!1;const n=t[0];return n.kinds&&Array.isArray(n.kinds)&&1===n.kinds.length&&n.authors&&Array.isArray(n.authors)&&1===n.authors.length&&n["#d"]&&Array.isArray(n["#d"])&&1===n["#d"].length}function isSingleIdLookup(e){const t=Array.isArray(e)?e:[e];if(1!==t.length)return!1;const n=t[0];return n.ids&&Array.isArray(n.ids)&&1===n.ids.length}function isReplaceableEventFilter(e){const t=Array.isArray(e)?e:[e];return 0!==t.length&&t.every(e=>{if(!e.kinds||!Array.isArray(e.kinds)||0===e.kinds.length)return!1;if(!e.authors||!Array.isArray(e.authors)||0===e.authors.length)return!1;return e.kinds.every(e=>0===e||3===e||e>=1e4&&e<=19999)})}function formatFilter(e){return JSON.stringify(e,null,2).split("\n").map((e,t)=>0===t?e:` ${e}`).join("\n")}function fetchingEvents(e,t,n){if("ONLY_CACHE"===t?.cacheUsage)return;const s=Array.isArray(e)?e:[e],r=s.map(formatFilter).join("\n\n ---\n\n ");if(isNip33Pattern(e))s[0],n("fetch-events-usage","For fetching a NIP-33 addressable event, use fetchEvent() with the naddr directly.\n\n📦 Your filter:\n "+r+"\n\n ❌ BAD: const decoded = nip19.decode(naddr);\n const events = await ndk.fetchEvents({\n kinds: [decoded.data.kind],\n authors: [decoded.data.pubkey],\n \"#d\": [decoded.data.identifier]\n });\n const event = Array.from(events)[0];\n\n ✅ GOOD: const event = await ndk.fetchEvent(naddr);\n ✅ GOOD: const event = await ndk.fetchEvent('naddr1...');\n\nfetchEvent() handles naddr decoding automatically and returns the event directly.");else if(isSingleIdLookup(e)){n("fetch-events-usage","For fetching a single event, use fetchEvent() instead.\n\n📦 Your filter:\n "+r+"\n\n💡 Looking for event: "+s[0].ids[0]+"\n\n ❌ BAD: const events = await ndk.fetchEvents({ ids: [eventId] });\n ✅ GOOD: const event = await ndk.fetchEvent(eventId);\n ✅ GOOD: const event = await ndk.fetchEvent('note1...');\n ✅ GOOD: const event = await ndk.fetchEvent('nevent1...');\n\nfetchEvent() is optimized for single event lookups and returns the event directly.")}else{if(isReplaceableEventFilter(e))return;{let e="";const t=s.some(e=>void 0!==e.limit),i=new Set(s.flatMap(e=>e.kinds||[])).size,o=new Set(s.flatMap(e=>e.authors||[])).size;if(t){const t=Math.max(...s.map(e=>e.limit||0));e+=`\n • Limit: ${t} event${1!==t?"s":""}`}i>0&&(e+=`\n • Kinds: ${i} type${1!==i?"s":""}`),o>0&&(e+=`\n • Authors: ${o} author${1!==o?"s":""}`),n("fetch-events-usage","fetchEvents() is a BLOCKING operation that waits for EOSE.\nIn most cases, you should use subscribe() instead.\n\n📦 Your filter"+(s.length>1?"s":"")+":\n "+r+(e?"\n\n📊 Filter analysis:"+e:"")+"\n\n ❌ BAD: const events = await ndk.fetchEvents(filter);\n ✅ GOOD: ndk.subscribe(filter, { onEvent: (e) => ... });\n\nOnly use fetchEvents() when you MUST block until data arrives.","For one-time queries, use fetchEvent() instead of fetchEvents() when expecting a single result.")}}}var GuardrailCheckId={NDK_NO_CACHE:"ndk-no-cache",FILTER_BECH32_IN_ARRAY:"filter-bech32-in-array",FILTER_INVALID_HEX:"filter-invalid-hex",FILTER_ONLY_LIMIT:"filter-only-limit",FILTER_LARGE_LIMIT:"filter-large-limit",FILTER_EMPTY:"filter-empty",FILTER_SINCE_AFTER_UNTIL:"filter-since-after-until",FILTER_INVALID_A_TAG:"filter-invalid-a-tag",FETCH_EVENTS_USAGE:"fetch-events-usage",EVENT_MISSING_KIND:"event-missing-kind",EVENT_PARAM_REPLACEABLE_NO_DTAG:"event-param-replaceable-no-dtag",EVENT_CREATED_AT_MILLISECONDS:"event-created-at-milliseconds",EVENT_NO_NDK_INSTANCE:"event-no-ndk-instance",EVENT_CONTENT_IS_OBJECT:"event-content-is-object",EVENT_MODIFIED_AFTER_SIGNING:"event-modified-after-signing",EVENT_MANUAL_REPLY_MARKERS:"event-manual-reply-markers",TAG_E_FOR_PARAM_REPLACEABLE:"tag-e-for-param-replaceable",TAG_BECH32_VALUE:"tag-bech32-value",TAG_DUPLICATE:"tag-duplicate",TAG_INVALID_P_TAG:"tag-invalid-p-tag",TAG_INVALID_E_TAG:"tag-invalid-e-tag",SUBSCRIBE_NOT_STARTED:"subscribe-not-started",SUBSCRIBE_CLOSE_ON_EOSE_NO_HANDLER:"subscribe-close-on-eose-no-handler",SUBSCRIBE_PASSED_EVENT_NOT_FILTER:"subscribe-passed-event-not-filter",SUBSCRIBE_AWAITED:"subscribe-awaited",RELAY_INVALID_URL:"relay-invalid-url",RELAY_HTTP_INSTEAD_OF_WS:"relay-http-instead-of-ws",RELAY_NO_ERROR_HANDLERS:"relay-no-error-handlers",VALIDATION_PUBKEY_IS_NPUB:"validation-pubkey-is-npub",VALIDATION_PUBKEY_WRONG_LENGTH:"validation-pubkey-wrong-length",VALIDATION_EVENT_ID_IS_BECH32:"validation-event-id-is-bech32",VALIDATION_EVENT_ID_WRONG_LENGTH:"validation-event-id-wrong-length"};function checkCachePresence(e,t){t(GuardrailCheckId.NDK_NO_CACHE)&&setTimeout(()=>{if(!e.cacheAdapter){const e=`\n🤖 AI_GUARDRAILS WARNING: NDK initialized without a cache adapter. Apps perform significantly better with caching.\n\n💡 ${"undefined"!=typeof window?"Consider using @nostr-dev-kit/ndk-cache-dexie or @nostr-dev-kit/ndk-cache-sqlite-wasm":"Consider using @nostr-dev-kit/ndk-cache-redis or @nostr-dev-kit/ndk-cache-sqlite"}\n\n🔇 To disable this check:\n ndk.aiGuardrails.skip('${GuardrailCheckId.NDK_NO_CACHE}')\n or set: ndk.aiGuardrails = { skip: new Set(['${GuardrailCheckId.NDK_NO_CACHE}']) }`;console.warn(e)}},2500)}var AIGuardrails=class{enabled=!1;skipSet=new Set;extensions=new Map;_nextCallDisabled=null;_replyEvents=new WeakSet;constructor(e=!1){this.setMode(e)}register(e,t){this.extensions.has(e)&&console.warn(`AIGuardrails: Extension '${e}' already registered, overwriting`);const n={};for(const[e,s]of Object.entries(t))"function"==typeof s&&(n[e]=(...e)=>{this.enabled&&s(...e,this.shouldCheck.bind(this),this.error.bind(this),this.warn.bind(this))});this.extensions.set(e,n),this[e]=n}setMode(e){"boolean"==typeof e?(this.enabled=e,this.skipSet.clear()):e&&"object"==typeof e&&(this.enabled=!0,this.skipSet=e.skip||new Set)}isEnabled(){return this.enabled}shouldCheck(e){return!!this.enabled&&(!this.skipSet.has(e)&&("all"!==this._nextCallDisabled&&(!this._nextCallDisabled||!this._nextCallDisabled.has(e))))}skip(e){this.skipSet.add(e)}enable(e){this.skipSet.delete(e)}getSkipped(){return Array.from(this.skipSet)}captureAndClearNextCallDisabled(){const e=this._nextCallDisabled;return this._nextCallDisabled=null,e}error(e,t,n,s=!0){if(!this.shouldCheck(e))return;const r=this.formatMessage(e,"ERROR",t,n,s);throw console.error(r),new Error(r)}warn(e,t,n){if(!this.shouldCheck(e))return;const s=this.formatMessage(e,"WARNING",t,n,!0);throw console.error(s),new Error(s)}formatMessage(e,t,n,s,r=!0){let i=`\n🤖 AI_GUARDRAILS ${t}: ${n}`;return s&&(i+=`\n\n💡 ${s}`),r&&(i+=`\n\n🔇 To disable this check:\n ndk.guardrailOff('${e}').yourMethod() // For one call`,i+=`\n ndk.aiGuardrails.skip('${e}') // Permanently`,i+=`\n or set: ndk.aiGuardrails = { skip: new Set(['${e}']) }`),i}ndkInstantiated(e){this.enabled&&checkCachePresence(e,this.shouldCheck.bind(this))}ndk={fetchingEvents:(e,t)=>{this.enabled&&fetchingEvents(e,t,this.warn.bind(this))}};event={signing:e=>{this.enabled&&signing(e,this.error.bind(this),this.warn.bind(this),this._replyEvents)},publishing:e=>{this.enabled},received:(e,t)=>{this.enabled},creatingReply:e=>{this.enabled&&this._replyEvents.add(e)}};subscription={created:(e,t)=>{this.enabled}};relay={connected:e=>{this.enabled}}};function isValidPubkey(e){return"string"==typeof e&&/^[0-9a-f]{64}$/i.test(e)}function processFilters(e,t="validate",n,s){if("ignore"===t)return e;const r=[],i=e.map((e,i)=>{s?.aiGuardrails.isEnabled()&&runAIGuardrailsForFilter(e,i,s);return processFilter(e,t,i,r,n)});if("validate"===t&&r.length>0)throw new Error(`Invalid filter(s) detected:\n${r.join("\n")}`);return i}function processFilter(e,t,n,s,r){const i="validate"===t,o=i?e:{...e};if(e.ids){const t=[];e.ids.forEach((e,o)=>{void 0===e?i?s.push(`Filter[${n}].ids[${o}] is undefined`):r?.(`Fixed: Removed undefined value at ids[${o}]`):"string"!=typeof e?i?s.push(`Filter[${n}].ids[${o}] is not a string (got ${typeof e})`):r?.(`Fixed: Removed non-string value at ids[${o}] (was ${typeof e})`):/^[0-9a-f]{64}$/i.test(e)?t.push(e):i?s.push(`Filter[${n}].ids[${o}] is not a valid 64-char hex string: "${e}"`):r?.(`Fixed: Removed invalid hex string at ids[${o}]`)}),i||(o.ids=t.length>0?t:void 0)}if(e.authors){const t=[];e.authors.forEach((e,o)=>{void 0===e?i?s.push(`Filter[${n}].authors[${o}] is undefined`):r?.(`Fixed: Removed undefined value at authors[${o}]`):"string"!=typeof e?i?s.push(`Filter[${n}].authors[${o}] is not a string (got ${typeof e})`):r?.(`Fixed: Removed non-string value at authors[${o}] (was ${typeof e})`):/^[0-9a-f]{64}$/i.test(e)?t.push(e):i?s.push(`Filter[${n}].authors[${o}] is not a valid 64-char hex pubkey: "${e}"`):r?.(`Fixed: Removed invalid hex pubkey at authors[${o}]`)}),i||(o.authors=t.length>0?t:void 0)}if(e.kinds){const t=[];e.kinds.forEach((e,o)=>{void 0===e?i?s.push(`Filter[${n}].kinds[${o}] is undefined`):r?.(`Fixed: Removed undefined value at kinds[${o}]`):"number"!=typeof e?i?s.push(`Filter[${n}].kinds[${o}] is not a number (got ${typeof e})`):r?.(`Fixed: Removed non-number value at kinds[${o}] (was ${typeof e})`):Number.isInteger(e)?e<0||e>65535?i?s.push(`Filter[${n}].kinds[${o}] is out of valid range (0-65535): ${e}`):r?.(`Fixed: Removed out-of-range kind at kinds[${o}]: ${e}`):t.push(e):i?s.push(`Filter[${n}].kinds[${o}] is not an integer: ${e}`):r?.(`Fixed: Removed non-integer value at kinds[${o}]: ${e}`)}),i||(o.kinds=t.length>0?t:void 0)}for(const t in e)if(t.startsWith("#")&&2===t.length){const a=e[t];if(Array.isArray(a)){const e=[];a.forEach((o,a)=>{void 0===o?i?s.push(`Filter[${n}].${t}[${a}] is undefined`):r?.(`Fixed: Removed undefined value at ${t}[${a}]`):"string"!=typeof o?i?s.push(`Filter[${n}].${t}[${a}] is not a string (got ${typeof o})`):r?.(`Fixed: Removed non-string value at ${t}[${a}] (was ${typeof o})`):"#e"!==t&&"#p"!==t||/^[0-9a-f]{64}$/i.test(o)?e.push(o):i?s.push(`Filter[${n}].${t}[${a}] is not a valid 64-char hex string: "${o}"`):r?.(`Fixed: Removed invalid hex string at ${t}[${a}]`)}),i||(o[t]=e.length>0?e:void 0)}}return i||Object.keys(o).forEach(e=>{void 0===o[e]&&delete o[e]}),o}function runAIGuardrailsForFilter(e,t,n){const s=n.aiGuardrails,r=JSON.stringify(e,null,2);if(1===Object.keys(e).length&&void 0!==e.limit&&s.error(GuardrailCheckId.FILTER_ONLY_LIMIT,`Filter[${t}] contains only 'limit' without any filtering criteria.\n\n📦 Your filter:\n${r}\n\n⚠️ This will fetch random events from relays without any criteria.`,"Add filtering criteria:\n ✅ { kinds: [1], limit: 10 }\n ✅ { authors: [pubkey], limit: 10 }\n ❌ { limit: 10 }"),0===Object.keys(e).length&&s.error(GuardrailCheckId.FILTER_EMPTY,`Filter[${t}] is empty.\n\n📦 Your filter:\n${r}\n\n⚠️ This will request ALL events from relays, which is never what you want.`,"Add filtering criteria like 'kinds', 'authors', or tags.",!1),void 0!==e.since&&void 0!==e.until&&e.since>e.until){const n=new Date(1e3*e.since).toISOString(),i=new Date(1e3*e.until).toISOString();s.error(GuardrailCheckId.FILTER_SINCE_AFTER_UNTIL,`Filter[${t}] has 'since' AFTER 'until'.\n\n📦 Your filter:\n${r}\n\n❌ since: ${e.since} (${n})\n❌ until: ${e.until} (${i})\n\nNo events can match this time range!`,"'since' must be BEFORE 'until'. Both are Unix timestamps in seconds.",!1)}const i=/^n(addr|event|ote|pub|profile)1/,o=/^[0-9a-f]{64}$/i;e.ids&&e.ids.forEach((e,n)=>{"string"==typeof e&&(i.test(e)?s.error(GuardrailCheckId.FILTER_BECH32_IN_ARRAY,`Filter[${t}].ids[${n}] contains bech32: "${e}". IDs must be hex, not bech32.`,'Use filterFromId() to decode bech32 first: import { filterFromId } from "@nostr-dev-kit/ndk"',!1):o.test(e)||s.error(GuardrailCheckId.FILTER_INVALID_HEX,`Filter[${t}].ids[${n}] is not a valid 64-char hex string: "${e}"`,"Event IDs must be 64-character hexadecimal strings. Invalid IDs often come from corrupted data in user-generated lists. Always validate hex strings before using them in filters:\n\n const validIds = ids.filter(id => /^[0-9a-f]{64}$/i.test(id));",!1))}),e.authors&&e.authors.forEach((e,n)=>{"string"==typeof e&&(i.test(e)?s.error(GuardrailCheckId.FILTER_BECH32_IN_ARRAY,`Filter[${t}].authors[${n}] contains bech32: "${e}". Authors must be hex pubkeys, not npub.`,"Use ndkUser.pubkey instead. Example: { authors: [ndkUser.pubkey] }",!1):o.test(e)||s.error(GuardrailCheckId.FILTER_INVALID_HEX,`Filter[${t}].authors[${n}] is not a valid 64-char hex pubkey: "${e}"`,'Kind:3 follow lists can contain invalid entries like labels ("Follow List"), partial strings ("highlig"), or other corrupted data. You MUST validate all pubkeys before using them in filters.\n\n Example:\n const validPubkeys = pubkeys.filter(p => /^[0-9a-f]{64}$/i.test(p));\n ndk.subscribe({ authors: validPubkeys, kinds: [1] });',!1))});for(const n in e)if(n.startsWith("#")&&2===n.length){const r=e[n];Array.isArray(r)&&r.forEach((e,r)=>{"string"==typeof e&&("#e"!==n&&"#p"!==n||(i.test(e)?s.error(GuardrailCheckId.FILTER_BECH32_IN_ARRAY,`Filter[${t}].${n}[${r}] contains bech32: "${e}". Tag values must be decoded.`,"Use filterFromId() or nip19.decode() to get the hex value first.",!1):o.test(e)||s.error(GuardrailCheckId.FILTER_INVALID_HEX,`Filter[${t}].${n}[${r}] is not a valid 64-char hex string: "${e}"`,("#e"===n?"Event IDs":"Public keys")+" in tag filters must be 64-character hexadecimal strings. Kind:3 follow lists and other user-generated content can contain invalid data. Always filter before using:\n\n const validValues = values.filter(v => /^[0-9a-f]{64}$/i.test(v));",!1)))})}if(e["#a"]){const n=e["#a"];n?.forEach((e,n)=>{if("string"==typeof e)if(/^\d+:[0-9a-f]{64}:.*$/.test(e)){const r=Number.parseInt(e.split(":")[0],10);(r<3e4||r>39999)&&s.error(GuardrailCheckId.FILTER_INVALID_A_TAG,`Filter[${t}].#a[${n}] uses non-addressable kind ${r}: "${e}". #a filters are only for addressable events (kinds 30000-39999).`,`Addressable events include:\n • 30000-30039: Parameterized Replaceable Events (profiles, settings, etc.)\n • 30040-39999: Other addressable events\n\nFor regular events (kind ${r}), use:\n • #e filter for specific event IDs\n • kinds + authors filters for event queries`,!1)}else s.error(GuardrailCheckId.FILTER_INVALID_A_TAG,`Filter[${t}].#a[${n}] has invalid format: "${e}". Must be "kind:pubkey:d-tag".`,'Example: "30023:fa984bd7dbb282f07e16e7ae87b26a2a7b9b90b7246a44771f0cf5ae58018f52:my-article"',!1)})}}function mergeTags(e,t){const n=new Map,s=(e,t)=>e.every((e,n)=>e===t[n]);return e.concat(t).forEach(e=>{for(const[t,r]of n)if(s(r,e)||s(e,r))return void(e.length>=r.length&&n.set(t,e));n.set((e=>e.join(","))(e),e)}),Array.from(n.values())}var hashtagRegex=/(?<=\s|^)(#[^\s!@#$%^&*()=+./,[{\]};:'"?><]+)/g;function generateHashtags(e){const t=e.match(hashtagRegex),n=new Set,s=new Set;if(t)for(const e of t)n.has(e.slice(1))||(s.add(e.slice(1)),n.add(e.slice(1)));return Array.from(s)}async function generateContentTags(e,t=[],n,s){if(n?.skipContentTagging)return{content:e,tags:t};const r=[],i=e=>{t.find(t=>["q",e[0]].includes(t[0])&&t[1]===e[1])||t.push(e)};if(e=e.replace(/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,e=>{try{const t=e.split(/(@|nostr:)/)[2],{type:s,data:o}=nip19_exports$1.decode(t);let a;if(n?.filters){const t=!n.filters.includeTypes||n.filters.includeTypes.includes(s),r=n.filters.excludeTypes?.includes(s);if(!t||r)return e}switch(s){case"npub":!1!==n?.pTags&&(a=["p",o]);break;case"nprofile":!1!==n?.pTags&&(a=["p",o.pubkey]);break;case"note":r.push(new Promise(async e=>{const n=await maybeGetEventRelayUrl(t);i(["q",o,n]),e()}));break;case"nevent":r.push(new Promise(async e=>{const{id:s,author:r}=o;let{relays:a}=o;a&&0!==a.length||(a=[await maybeGetEventRelayUrl(t)]),i(["q",s,a[0]]),r&&!1!==n?.pTags&&!1!==n?.pTagOnQTags&&i(["p",r]),e()}));break;case"naddr":r.push(new Promise(async e=>{const s=[o.kind,o.pubkey,o.identifier].join(":");let r=o.relays??[];0===r.length&&(r=[await maybeGetEventRelayUrl(t)]),i(["q",s,r[0]]),!1!==n?.pTags&&!1!==n?.pTagOnQTags&&!1!==n?.pTagOnATags&&i(["p",o.pubkey]),e()}));break;default:return e}return a&&i(a),`nostr:${t}`}catch(t){return e}}),await Promise.all(r),!n?.filters?.excludeTypes?.includes("hashtag")){const n=generateHashtags(e).map(e=>["t",e]);t=mergeTags(t,n)}if(!1!==n?.pTags&&n?.copyPTagsFromTarget&&s){const e=s.getMatchingTags("p");for(const n of e)n[1]&&isValidPubkey(n[1])&&(t.find(e=>"p"===e[0]&&e[1]===n[1])||t.push(n))}return{content:e,tags:t}}async function maybeGetEventRelayUrl(e){return""}async function encrypt(e,t,n="nip44"){let s;if(!this.ndk)throw new Error("No NDK instance found!");let r=t;if(r||(this.ndk.assertSigner(),r=this.ndk.signer),!r)throw new Error("no NDK signer");const i=e||(()=>{const e=this.getMatchingTags("p");if(1!==e.length)throw new Error("No recipient could be determined and no explicit recipient was provided");return this.ndk.getUser({pubkey:e[0][1]})})();if("nip44"===n&&await isEncryptionEnabled(r,"nip44")&&(s=await r.encrypt(i,this.content,"nip44")),s&&"nip04"!==n||!await isEncryptionEnabled(r,"nip04")||(s=await r.encrypt(i,this.content,"nip04")),!s)throw new Error("Failed to encrypt event.");this.content=s}async function decrypt(e,t,n){if(this.ndk?.cacheAdapter?.getDecryptedEvent){const e=await this.ndk.cacheAdapter.getDecryptedEvent(this.id);if(e)return void(this.content=e.content)}let s;if(!this.ndk)throw new Error("No NDK instance found!");let r=t;if(r||(this.ndk.assertSigner(),r=this.ndk.signer),!r)throw new Error("no NDK signer");const i=e||this.author;if(!i)throw new Error("No sender provided and no author available");const o=n||(this.content.match(/\\?iv=/)?"nip04":"nip44");if(("nip04"===o||4===this.kind)&&await isEncryptionEnabled(r,"nip04")&&this.content.search("\\?iv=")&&(s=await r.decrypt(i,this.content,"nip04")),!s&&"nip44"===o&&await isEncryptionEnabled(r,"nip44")&&(s=await r.decrypt(i,this.content,"nip44")),!s)throw new Error("Failed to decrypt event.");this.content=s,this.ndk?.cacheAdapter?.addDecryptedEvent&&this.ndk.cacheAdapter.addDecryptedEvent(this)}async function isEncryptionEnabled(e,t){return!!e.encryptionEnabled&&(!t||Boolean(await e.encryptionEnabled(t)))}function eventHasETagMarkers(e){for(const t of e.tags)if("e"===t[0]&&(t[3]??"").length>0)return!0;return!1}function getRootTag(e,t){t??=e.tagType();const n=e.tags.find(isTagRootTag);if(!n){if(eventHasETagMarkers(e))return;const n=e.getMatchingTags(t);if(n.length<3)return n[0]}return n}var nip22RootTags=new Set(["A","E","I"]),nip22ReplyTags=new Set(["a","e","i"]);function getReplyTag(e,t){if(1111===e.kind){let t;for(const n of e.tags)if(nip22RootTags.has(n[0]))t=n;else if(nip22ReplyTags.has(n[0])){t=n;break}return t}t??=e.tagType();let n,s=!1;for(const r of e.tags)if(r[0]===t){if((r[3]??"").length>0&&(s=!0),s&&"reply"===r[3])return r;s&&"root"===r[3]&&(n=r),s||(n=r)}return n}function isTagRootTag(e){return"E"===e[0]||"root"===e[3]}async function fetchTaggedEvent(e,t){if(!this.ndk)throw new Error("NDK instance not found");const n=this.getMatchingTags(e,t);if(0===n.length)return;const[s,r,i]=n[0],o=""!==i?this.ndk.pool.getRelay(i):void 0;return await this.ndk.fetchEvent(r,{},o)}async function fetchRootEvent(e){if(!this.ndk)throw new Error("NDK instance not found");const t=getRootTag(this);if(t)return this.ndk.fetchEventFromTag(t,this,e)}async function fetchReplyEvent(e){if(!this.ndk)throw new Error("NDK instance not found");const t=getReplyTag(this);if(t)return this.ndk.fetchEventFromTag(t,this,e)}function isReplaceable(){if(void 0===this.kind)throw new Error("Kind not set");return[0,3].includes(this.kind)||this.kind>=1e4&&this.kind<2e4||this.kind>=3e4&&this.kind<4e4}function isEphemeral(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function isParamReplaceable(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}var DEFAULT_RELAY_COUNT=2,worker;function encode(e=DEFAULT_RELAY_COUNT){let t=[];return this.onRelays.length>0?t=this.onRelays.map(e=>e.url):this.relay&&(t=[this.relay.url]),t.length>e&&(t=t.slice(0,e)),this.isParamReplaceable()?nip19_exports$1.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:t}):t.length>0?nip19_exports$1.neventEncode({id:this.tagId(),relays:t,author:this.pubkey}):nip19_exports$1.noteEncode(this.tagId())}async function repost(e=!0,t){if(!t&&e){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t=this.ndk.signer}const n=new NDKEvent(this.ndk,{kind:getKind(this)});return this.isProtected||(n.content=JSON.stringify(this.rawEvent())),n.tag(this),1!==this.kind&&n.tags.push(["k",`${this.kind}`]),t&&await n.sign(t),e&&await n.publish(),n}function getKind(e){return 1===e.kind?6:16}function serialize(e=!1,t=!1){const n=[0,this.pubkey,this.created_at,this.kind,this.tags,this.content];return e&&n.push(this.sig),t&&n.push(this.id),JSON.stringify(n)}function deserialize(e){const t=JSON.parse(e),n={pubkey:t[1],created_at:t[2],kind:t[3],tags:t[4],content:t[5]};if(t.length>=7){const e=t[6],s=t[7];e&&128===e.length?(n.sig=e,s&&64===s.length&&(n.id=s)):e&&64===e.length&&(n.id=e,s&&128===s.length&&(n.sig=s))}return n}var processingQueue={};function signatureVerificationInit(e){(worker=e).onmessage=e=>{const[t,n]=e.data,s=processingQueue[t];if(s){delete processingQueue[t];for(const e of s.resolves)e(n)}else console.error("No record found for event",t)}}async function verifySignatureAsync(e,t,n){const s=e.ndk,r=Date.now();let i;return i=s.signatureVerificationFunction?await s.signatureVerificationFunction(e):await new Promise(t=>{const s=e.serialize();let r=!1;processingQueue[e.id]||(processingQueue[e.id]={event:e,resolves:[],relay:n},r=!0),processingQueue[e.id].resolves.push(t),r&&worker?.postMessage({serialized:s,id:e.id,sig:e.sig,pubkey:e.pubkey})}),s.signatureVerificationTimeMs+=Date.now()-r,i}var PUBKEY_REGEX=/^[a-f0-9]{64}$/;function validate(){if("number"!=typeof this.kind)return!1;if("string"!=typeof this.content)return!1;if("number"!=typeof this.created_at)return!1;if("string"!=typeof this.pubkey)return!1;if(!this.pubkey.match(PUBKEY_REGEX))return!1;if(!Array.isArray(this.tags))return!1;for(let e=0;e<this.tags.length;e++){const t=this.tags[e];if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if("object"==typeof t[e])return!1}return!0}var verifiedSignatures=new dist.LRUCache({maxSize:1e3,entryExpirationTimeInMS:6e4});function verifySignature(e){if("boolean"==typeof this.signatureVerified)return this.signatureVerified;const t=verifiedSignatures.get(this.id);if(null!==t)return this.signatureVerified=!!t,this.signatureVerified;try{if(!this.ndk?.asyncSigVerification){const e=sha256((new TextEncoder).encode(this.serialize())),t=schnorr.verify(this.sig,e,this.pubkey);return t?verifiedSignatures.set(this.id,this.sig):verifiedSignatures.set(this.id,!1),this.signatureVerified=t,t}{const t=this.relay;verifySignatureAsync(this,e,t).then(n=>{e&&(this.signatureVerified=n,n&&verifiedSignatures.set(this.id,this.sig)),n?t&&t.addValidatedEvent():(t?this.ndk?.reportInvalidSignature(this,t):this.ndk?.reportInvalidSignature(this),verifiedSignatures.set(this.id,!1))}).catch(e=>{console.error("signature verification error",this.id,e)})}}catch(e){return this.signatureVerified=!1,!1}}function getEventHash(){return getEventHashFromSerializedEvent(this.serialize())}function getEventHashFromSerializedEvent(e){return bytesToHex(sha256((new TextEncoder).encode(e)))}var skipClientTagOnKinds=new Set([0,4,1059,13,3,9734,5]),NDKEvent=class e extends lib$1.EventEmitter{ndk;created_at;content="";tags=[];kind;id="";sig;pubkey="";signatureVerified;_author=void 0;relay;get onRelays(){let e=[];return this.ndk?e=this.ndk.subManager.seenEvents.get(this.id)||[]:this.relay&&e.push(this.relay),e}publishStatus="success";publishError;constructor(t,n){super(),this.ndk=t,this.created_at=n?.created_at,this.content=n?.content||"",this.tags=n?.tags||[],this.id=n?.id||"",this.sig=n?.sig,this.pubkey=n?.pubkey||"",this.kind=n?.kind,n instanceof e&&(this.relay&&(this.relay=n.relay,this.ndk?.subManager.seenEvent(n.id,this.relay)),this.publishStatus=n.publishStatus,this.publishError=n.publishError)}static deserialize(t,n){return new e(t,deserialize(n))}rawEvent(){return{created_at:this.created_at,content:this.content,tags:this.tags,kind:this.kind,pubkey:this.pubkey,id:this.id,sig:this.sig}}set author(e){this.pubkey=e.pubkey,this._author=e,this._author.ndk??=this.ndk}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const e=this.ndk.getUser({pubkey:this.pubkey});return this._author=e,e}tagExternal(e,t,n){const s=["i"],r=["k"];switch(t){case"url":{const t=new URL(e);t.hash="",s.push(t.toString()),r.push(`${t.protocol}//${t.host}`);break}case"hashtag":s.push(`#${e.toLowerCase()}`),r.push("#");break;case"geohash":s.push(`geo:${e.toLowerCase()}`),r.push("geo");break;case"isbn":s.push(`isbn:${e.replace(/-/g,"")}`),r.push("isbn");break;case"podcast:guid":s.push(`podcast:guid:${e}`),r.push("podcast:guid");break;case"podcast:item:guid":s.push(`podcast:item:guid:${e}`),r.push("podcast:item:guid");break;case"podcast:publisher:guid":s.push(`podcast:publisher:guid:${e}`),r.push("podcast:publisher:guid");break;case"isan":s.push(`isan:${e.split("-").slice(0,4).join("-")}`),r.push("isan");break;case"doi":s.push(`doi:${e.toLowerCase()}`),r.push("doi");break;default:throw new Error(`Unsupported NIP-73 entity type: ${t}`)}n&&s.push(n),this.tags.push(s),this.tags.push(r)}tag(t,n,s,r,i){let o=[];if(void 0!==t.fetchProfile){if(r??="p","p"===r&&!1===i?.pTags)return;const e=[r,t.pubkey];n&&e.push("",n),o.push(e)}else if(t instanceof e){const e=t;if(s??=e?.pubkey===this.pubkey,o=e.referenceTags(n,s,r,i),!1!==i?.pTags)for(const t of e.getMatchingTags("p"))t[1]&&isValidPubkey(t[1])&&t[1]!==this.pubkey&&(this.tags.find(e=>"p"===e[0]&&e[1]===t[1])||this.tags.push(["p",t[1]]))}else{if(!Array.isArray(t))throw new Error("Invalid argument",t);o=[t]}this.tags=mergeTags(this.tags,o)}async toNostrEvent(e,t){if(!e&&""===this.pubkey){const e=await(this.ndk?.signer?.user());this.pubkey=e?.pubkey||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const{content:n,tags:s}=await this.generateTags(t);this.content=n||"",this.tags=s;try{this.id=this.getEventHash()}catch(e){}return this.rawEvent()}serialize=serialize.bind(this);getEventHash=getEventHash.bind(this);validate=validate.bind(this);verifySignature=verifySignature.bind(this);isReplaceable=isReplaceable.bind(this);isEphemeral=isEphemeral.bind(this);isDvm=()=>this.kind&&this.kind>=5e3&&this.kind<=7e3;isParamReplaceable=isParamReplaceable.bind(this);encode=encode.bind(this);encrypt=encrypt.bind(this);decrypt=decrypt.bind(this);getMatchingTags(e,t){const n=this.tags.filter(t=>t[0]===e);return void 0===t?n:n.filter(e=>e[3]===t)}hasTag(e,t){return this.tags.some(n=>n[0]===e&&(!t||n[3]===t))}tagValue(e,t){const n=this.getMatchingTags(e,t);if(0!==n.length)return n[0][1]}get alt(){return this.tagValue("alt")}set alt(e){this.removeTag("alt"),e&&this.tags.push(["alt",e])}get dTag(){return this.tagValue("d")}set dTag(e){this.removeTag("d"),e&&this.tags.push(["d",e])}removeTag(e,t){const n=Array.isArray(e)?e:[e];this.tags=this.tags.filter(e=>{const s=n.includes(e[0]),r=!t||e[3]===t;return!(s&&r)})}replaceTag(e){this.removeTag(e[0]),this.tags.push(e)}async sign(e,t){this.ndk?.aiGuardrails?.event?.signing(this),e?this.author=await e.user():(this.ndk?.assertSigner(),e=this.ndk?.signer);const n=await this.toNostrEvent(void 0,t);return this.sig=await e.sign(n),this.sig}async publishReplaceable(e,t,n){return this.id="",this.created_at=Math.floor(Date.now()/1e3),this.sig="",this.publish(e,t,n)}async publish(e,t,n,s){if(n||(n=1),this.sig||await this.sign(void 0,s),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");if(e&&0!==e.size||(e=this.ndk.devWriteRelaySet||await calculateRelaySetFromEvent(this.ndk,this,n)),5===this.kind&&this.ndk.cacheAdapter?.deleteEventIds){const e=this.getMatchingTags("e").map(e=>e[1]);this.ndk.cacheAdapter.deleteEventIds(e)}const r=this.rawEvent();if(this.ndk.cacheAdapter?.addUnpublishedEvent&&shouldTrackUnpublishedEvent(this))try{this.ndk.cacheAdapter.addUnpublishedEvent(this,e.relayUrls)}catch(e){console.error("Error adding unpublished event to cache",e)}5===this.kind&&this.ndk.cacheAdapter?.deleteEventIds&&this.ndk.cacheAdapter.deleteEventIds(this.getMatchingTags("e").map(e=>e[1])),this.ndk.subManager.dispatchEvent(r,void 0,!0);const i=await e.publish(this,t,n);return i.forEach(e=>this.ndk?.subManager.seenEvent(this.id,e)),i}async generateTags(e){let t=[];const n=await generateContentTags(this.content,this.tags,e,this),s=n.content;if(t=n.tags,this.kind&&this.isParamReplaceable()){if(!this.getMatchingTags("d")[0]){const e=this.tagValue("title");let n=[...Array(e?6:16)].map(()=>Math.random().toString(36)[2]).join("");e&&e.length>0&&(n=`${e.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")}-${n}`),t.push(["d",n])}}if(this.shouldAddClientTag){const e=["client",this.ndk?.clientName??""];this.ndk?.clientNip89&&e.push(this.ndk?.clientNip89),t.push(e)}else this.shouldStripClientTag&&(t=t.filter(e=>"client"!==e[0]));return{content:s||"",tags:t}}get shouldAddClientTag(){return!(!this.ndk?.clientName&&!this.ndk?.clientNip89)&&(!skipClientTagOnKinds.has(this.kind)&&(!this.isEphemeral()&&(!(this.isReplaceable()&&!this.isParamReplaceable())&&(!this.isDvm()&&!this.hasTag("client")))))}get shouldStripClientTag(){return skipClientTagOnKinds.has(this.kind)}muted(){return this.ndk?.muteFilter&&this.ndk.muteFilter(this)?"muted":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const e=this.getMatchingTags("d")[0];return e?e[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return 0===this.kind||3===this.kind||this.kind&&this.kind>=1e4&&this.kind<2e4?`${this.kind}:${this.pubkey}`:this.tagId()}tagId(){return this.isParamReplaceable()?this.tagAddress():this.id}tagAddress(){if(this.isParamReplaceable()){const e=this.dTag??"";return`${this.kind}:${this.pubkey}:${e}`}if(this.isReplaceable())return`${this.kind}:${this.pubkey}:`;throw new Error("Event is not a replaceable event")}tagType(){return this.isParamReplaceable()?"a":"e"}tagReference(e){let t;return t=this.isParamReplaceable()?["a",this.tagAddress()]:["e",this.tagId()],this.relay?t.push(this.relay.url):t.push(""),t.push(e??""),this.isParamReplaceable()||t.push(this.pubkey),t}referenceTags(e,t,n,s){let r=[];return r=this.isParamReplaceable()?[[n??"a",this.tagAddress()],[n??"e",this.id]]:[[n??"e",this.id]],r=r.map(t=>("e"===t[0]||e?t.push(this.relay?.url??""):this.relay?.url&&t.push(this.relay?.url),t)),r.forEach(t=>{"e"===t[0]?(t.push(e??""),t.push(this.pubkey)):e&&t.push(e)}),r=[...r,...this.getMatchingTags("h")],t||!1===s?.pTags||r.push(...this.author.referenceTags()),r}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}nip22Filter(){return this.isParamReplaceable()?{"#A":[this.tagId()]}:{"#E":[this.tagId()]}}async delete(t,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new e(this.ndk,{kind:5,content:t||""});return s.tag(this,void 0,!0),s.tags.push(["k",this.kind?.toString()]),n&&(this.emit("deleted"),await s.publish()),s}set isProtected(e){this.removeTag("-"),e&&this.tags.push(["-"])}get isProtected(){return this.hasTag("-")}fetchTaggedEvent=fetchTaggedEvent.bind(this);fetchRootEvent=fetchRootEvent.bind(this);fetchReplyEvent=fetchReplyEvent.bind(this);repost=repost.bind(this);async react(t,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new e(this.ndk,{kind:7,content:t});return s.tag(this),1!==this.kind&&s.tags.push(["k",`${this.kind}`]),n&&await s.publish(),s}get isValid(){return this.validate()}get inspect(){return JSON.stringify(this.rawEvent(),null,4)}dump(){console.debug(JSON.stringify(this.rawEvent(),null,4)),console.debug("Event on relays:",this.onRelays.map(e=>e.url).join(", "))}reply(t,n){const s=new e(this.ndk);if(this.ndk?.aiGuardrails?.event?.creatingReply(s),1!==this.kind||t){s.kind=1111;const e=["A","E","I","P"],t=this.tags.filter(t=>e.includes(t[0]));if(t.length>0){const e=this.tagValue("K");let n;if(s.tags.push(...t),e&&s.tags.push(["K",e]),this.isParamReplaceable()){n=["a",this.tagAddress()];const e=this.relay?.url??"";e&&n.push(e)}else{n=["e",this.tagId()];const e=this.relay?.url??"";n.push(e),n.push(this.pubkey)}s.tags.push(n)}else{let e,t;const r=this.relay?.url??"";this.isParamReplaceable()?(e=["a",this.tagAddress(),r],t=["A",this.tagAddress(),r]):(e=["e",this.tagId(),r,this.pubkey],t=["E",this.tagId(),r,this.pubkey]),s.tags.push(e),s.tags.push(t),s.tags.push(["K",this.kind?.toString()]),!1!==n?.pTags&&!1!==n?.pTagOnATags&&s.tags.push(["P",this.pubkey])}s.tags.push(["k",this.kind?.toString()]),!1!==n?.pTags&&(s.tags.push(...this.getMatchingTags("p")),s.tags.push(["p",this.pubkey]))}else{s.kind=1;this.hasTag("e")?s.tags=[...s.tags,...this.getMatchingTags("e"),...this.getMatchingTags("p"),...this.getMatchingTags("a"),...this.referenceTags("reply",!1,void 0,n)]:s.tag(this,"root",!1,void 0,n)}return s}},untrackedUnpublishedEvents=new Set([24133,13194,23194,23195]);function shouldTrackUnpublishedEvent(e){return!untrackedUnpublishedEvents.has(e.kind)}var NDKPool=class extends lib$1.EventEmitter{_relays=new Map;status="idle";autoConnectRelays=new Set;debug;temporaryRelayTimers=new Map;flappingRelays=new Set;backoffTimes=new Map;ndk;disconnectionTimes=new Map;systemEventDetector;constructor(e,t,{debug:n,name:s}={}){super(),this.debug=n??t.debug.extend("pool"),s&&(this._name=s),this.ndk=t,this.relayUrls=e,this.ndk.pools&&this.ndk.pools.push(this)}get relays(){return this._relays}set relayUrls(e){this._relays.clear();for(const t of e){const e=new NDKRelay(t,void 0,this.ndk);e.connectivity.netDebug=this.ndk.netDebug,this.addRelay(e)}}_name="unnamed";get name(){return this._name}set name(e){this._name=e,this.debug=this.debug.extend(e)}useTemporaryRelay(e,t=3e4,n){const s=this.relays.has(e.url);s||(this.addRelay(e),this.debug("Adding temporary relay %s for filters %o",e.url,n));const r=this.temporaryRelayTimers.get(e.url);if(r&&clearTimeout(r),!s||r){const n=setTimeout(()=>{this.ndk.explicitRelayUrls?.includes(e.url)||this.removeRelay(e.url)},t);this.temporaryRelayTimers.set(e.url,n)}}addRelay(e,t=!0){const n=this.relays.has(e.url),s=e.url.includes("/npub1");let r=!0;const i=e.url;if(n)return;if(this.ndk.relayConnectionFilter&&!this.ndk.relayConnectionFilter(i))return void this.debug(`Refusing to add relay ${i}: blocked by relayConnectionFilter`);if(s)return void this.debug(`Refusing to add relay ${i}: is a filter relay`);if(this.ndk.cacheAdapter?.getRelayStatus){const n=this.ndk.cacheAdapter.getRelayStatus(i),s=n instanceof Promise?void 0:n;if(s?.dontConnectBefore){if(s.dontConnectBefore>Date.now()){const n=s.dontConnectBefore-Date.now();return this.debug(`Refusing to add relay ${i}: delayed connect for ${n}ms`),void setTimeout(()=>{this.addRelay(e,t)},n)}r=!1}}const o=t=>this.emit("notice",e,t),a=()=>this.handleRelayConnect(i),c=()=>this.handleRelayReady(e),l=()=>{this.recordDisconnection(e),this.emit("relay:disconnect",e)},u=()=>this.handleFlapping(e),d=t=>this.emit("relay:auth",e,t),h=()=>this.emit("relay:authed",e);e.off("notice",o),e.off("connect",a),e.off("ready",c),e.off("disconnect",l),e.off("flapping",u),e.off("auth",d),e.off("authed",h),e.on("notice",o),e.on("connect",a),e.on("ready",c),e.on("disconnect",l),e.on("flapping",u),e.on("auth",d),e.on("authed",h),e.on("delayed-connect",t=>{this.ndk.cacheAdapter?.updateRelayStatus&&this.ndk.cacheAdapter.updateRelayStatus(e.url,{dontConnectBefore:Date.now()+t})}),this._relays.set(i,e),t&&this.autoConnectRelays.add(i),t&&"active"===this.status&&(this.emit("relay:connecting",e),e.connect(void 0,r).catch(e=>{this.debug(`Failed to connect to relay ${i}`,e)}))}removeRelay(e){const t=this.relays.get(e);if(t)return t.disconnect(),this.relays.delete(e),this.autoConnectRelays.delete(e),this.emit("relay:disconnect",t),!0;const n=this.temporaryRelayTimers.get(e);return n&&(clearTimeout(n),this.temporaryRelayTimers.delete(e)),!1}isRelayConnected(e){const t=normalizeRelayUrl(e),n=this.relays.get(t);return!!n&&5===n.status}getRelay(e,t=!0,n=!1,s){let r=this.relays.get(normalizeRelayUrl(e));return r||(r=new NDKRelay(e,void 0,this.ndk),r.connectivity.netDebug=this.ndk.netDebug,n?this.useTemporaryRelay(r,3e4,s):this.addRelay(r,t)),r}handleRelayConnect(e){const t=this.relays.get(e);t?(this.emit("relay:connect",t),this.stats().connected===this.relays.size&&this.emit("connect")):console.error("NDK BUG: relay not found in pool",{relayUrl:e})}handleRelayReady(e){this.emit("relay:ready",e)}async connect(e){this.status="active",this.debug(`Connecting to ${this.relays.size} relays${e?`, timeout ${e}ms`:""}...`);const t=Array.from(this.autoConnectRelays.keys()).map(e=>this.relays.get(e)).filter(e=>!!e);for(const e of t)5!==e.status&&4!==e.status&&(this.emit("relay:connecting",e),e.connect().catch(t=>{this.debug(`Failed to connect to relay ${e.url}: ${t??"No reason specified"}`)}));const n=()=>t.every(e=>5===e.status),s=new Promise(e=>{if(n())return void e();const s=[];for(const r of t){const i=()=>{if(n()){for(let e=0;e<t.length;e++)t[e].off("connect",s[e]);e()}};s.push(i),r.on("connect",i)}}),r=new Promise("number"==typeof e?t=>setTimeout(t,e):()=>{});await Promise.race([s,r])}checkOnFlappingRelays(){if(this.flappingRelays.size/this.relays.size>=.8)for(const e of this.flappingRelays)this.backoffTimes.set(e,0)}recordDisconnection(e){const t=Date.now();this.disconnectionTimes.set(e.url,t);for(const[e,n]of this.disconnectionTimes.entries())t-n>1e4&&this.disconnectionTimes.delete(e);this.checkForSystemWideDisconnection()}checkForSystemWideDisconnection(){const e=Date.now(),t=[];for(const n of this.disconnectionTimes.values())e-n<5e3&&t.push(n);t.length>this.relays.size/2&&this.relays.size>1&&(this.debug(`System-wide disconnection detected: ${t.length}/${this.relays.size} relays disconnected`),this.handleSystemWideReconnection())}handleSystemWideReconnection(){if(this.systemEventDetector)this.debug("System-wide reconnection already in progress, skipping");else{this.debug("Initiating system-wide reconnection with reset backoff"),this.systemEventDetector=setTimeout(()=>{this.systemEventDetector=void 0},1e4);for(const e of this.relays.values())e.connectivity&&(e.connectivity.resetReconnectionState(),5!==e.status&&4!==e.status&&e.connect().catch(t=>{this.debug(`Failed to reconnect relay ${e.url} after system event: ${t}`)}));this.disconnectionTimes.clear()}}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;t*=2,this.backoffTimes.set(e.url,t),this.debug(`Backoff time for ${e.url} is ${t}ms`),setTimeout(()=>{this.debug(`Attempting to reconnect to ${e.url}`),this.emit("relay:connecting",e),e.connect(),this.checkOnFlappingRelays()},t),e.disconnect(),this.emit("flapping",e)}size(){return this.relays.size}stats(){const e={total:0,connected:0,disconnected:0,connecting:0};for(const t of this.relays.values())e.total++,5===t.status?e.connected++:1===t.status?e.disconnected++:4===t.status&&e.connecting++;return e}connectedRelays(){return Array.from(this.relays.values()).filter(e=>e.status>=5)}permanentAndConnectedRelays(){return Array.from(this.relays.values()).filter(e=>e.status>=5&&!this.temporaryRelayTimers.has(e.url))}urls(){return Array.from(this.relays.keys())}},NDKDVMJobFeedback=class e extends NDKEvent{static kinds=[7e3];constructor(e,t){super(e,t),this.kind??=7e3}static async from(t){const n=new e(t.ndk,t.rawEvent());return n.encrypted&&await n.dvmDecrypt(),n}get status(){return this.tagValue("status")}set status(e){this.removeTag("status"),void 0!==e&&this.tags.push(["status",e])}get encrypted(){return!!this.getMatchingTags("encrypted")[0]}async dvmDecrypt(){await this.decrypt();const e=JSON.parse(this.content);this.tags.push(...e)}},NDKCashuMintList=class e extends NDKEvent{static kind=10019;static kinds=[10019];_p2pk;constructor(e,t){super(e,t),this.kind??=10019}static from(t){return new e(t.ndk,t)}set relays(e){this.tags=this.tags.filter(e=>"relay"!==e[0]);for(const t of e)this.tags.push(["relay",t])}get relays(){const e=[];for(const t of this.tags)"relay"===t[0]&&e.push(t[1]);return e}set mints(e){this.tags=this.tags.filter(e=>"mint"!==e[0]);for(const t of e)this.tags.push(["mint",t])}get mints(){const e=[];for(const t of this.tags)"mint"===t[0]&&e.push(t[1]);return Array.from(new Set(e))}get p2pk(){return this._p2pk||(this._p2pk=this.tagValue("pubkey")??this.pubkey),this._p2pk}set p2pk(e){this._p2pk=e,this.removeTag("pubkey"),e&&this.tags.push(["pubkey",e])}get relaySet(){return NDKRelaySet.fromRelayUrls(this.relays,this.ndk)}},NDKArticle=class e extends NDKEvent{static kind=30023;static kinds=[30023];constructor(e,t){super(e,t),this.kind??=30023}static from(t){return new e(t.ndk,t)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get image(){return this.tagValue("image")}set image(e){this.removeTag("image"),e&&this.tags.push(["image",e])}get summary(){return this.tagValue("summary")}set summary(e){this.removeTag("summary"),e&&this.tags.push(["summary",e])}get published_at(){const e=this.tagValue("published_at");if(e){let t=Number.parseInt(e);return t>1e12&&(t=Math.floor(t/1e3)),t}}set published_at(e){this.removeTag("published_at"),void 0!==e&&this.tags.push(["published_at",e.toString()])}async generateTags(){return super.generateTags(),this.published_at||(this.published_at=this.created_at),super.generateTags()}get url(){return this.tagValue("url")}set url(e){e?this.tags.push(["url",e]):this.removeTag("url")}},NDKBlossomList=class e extends NDKEvent{static kinds=[10063];constructor(e,t){super(e,t),this.kind??=10063}static from(t){return new e(t.ndk,t.rawEvent())}get servers(){return this.tags.filter(e=>"server"===e[0]).map(e=>e[1])}set servers(e){this.tags=this.tags.filter(e=>"server"!==e[0]);for(const t of e)this.tags.push(["server",t])}get default(){const e=this.servers;return e.length>0?e[0]:void 0}set default(e){if(!e)return;const t=this.servers.filter(t=>t!==e);this.servers=[e,...t]}addServer(e){if(!e)return;const t=this.servers;t.includes(e)||(this.servers=[...t,e])}removeServer(e){if(!e)return;const t=this.servers;this.servers=t.filter(t=>t!==e)}},NDKFedimintMint=class e extends NDKEvent{static kind=38173;static kinds=[38173];constructor(e,t){super(e,t),this.kind??=38173}static async from(t){return new e(t.ndk,t)}get identifier(){return this.tagValue("d")}set identifier(e){this.removeTag("d"),e&&this.tags.push(["d",e])}get inviteCodes(){return this.getMatchingTags("u").map(e=>e[1])}set inviteCodes(e){this.removeTag("u");for(const t of e)this.tags.push(["u",t])}get modules(){return this.getMatchingTags("modules").map(e=>e[1])}set modules(e){this.removeTag("modules");for(const t of e)this.tags.push(["modules",t])}get network(){return this.tagValue("n")}set network(e){this.removeTag("n"),e&&this.tags.push(["n",e])}get metadata(){if(this.content)try{return JSON.parse(this.content)}catch{return}}set metadata(e){this.content=e?JSON.stringify(e):""}},NDKCashuMintAnnouncement=class e extends NDKEvent{static kind=38172;static kinds=[38172];constructor(e,t){super(e,t),this.kind??=38172}static async from(t){return new e(t.ndk,t)}get identifier(){return this.tagValue("d")}set identifier(e){this.removeTag("d"),e&&this.tags.push(["d",e])}get url(){return this.tagValue("u")}set url(e){this.removeTag("u"),e&&this.tags.push(["u",e])}get nuts(){return this.getMatchingTags("nuts").map(e=>e[1])}set nuts(e){this.removeTag("nuts");for(const t of e)this.tags.push(["nuts",t])}get network(){return this.tagValue("n")}set network(e){this.removeTag("n"),e&&this.tags.push(["n",e])}get metadata(){if(this.content)try{return JSON.parse(this.content)}catch{return}}set metadata(e){this.content=e?JSON.stringify(e):""}},NDKMintRecommendation=class e extends NDKEvent{static kind=38e3;static kinds=[38e3];constructor(e,t){super(e,t),this.kind??=38e3}static async from(t){return new e(t.ndk,t)}get recommendedKind(){const e=this.tagValue("k");return e?Number(e):void 0}set recommendedKind(e){this.removeTag("k"),e&&this.tags.push(["k",e.toString()])}get identifier(){return this.tagValue("d")}set identifier(e){this.removeTag("d"),e&&this.tags.push(["d",e])}get urls(){return this.getMatchingTags("u").map(e=>e[1])}set urls(e){this.removeTag("u");for(const t of e)this.tags.push(["u",t])}get mintEventPointers(){return this.getMatchingTags("a").map(e=>({kind:Number(e[1].split(":")[0]),identifier:e[1].split(":")[2],relay:e[2]}))}addMintEventPointer(e,t,n,s){const r=["a",`${e}:${t}:${n}`];s&&r.push(s),this.tags.push(r)}get review(){return this.content}set review(e){this.content=e}},NDKClassified=class e extends NDKEvent{static kinds=[30402];constructor(e,t){super(e,t),this.kind??=30402}static from(t){return new e(t.ndk,t)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get summary(){return this.tagValue("summary")}set summary(e){this.removeTag("summary"),e&&this.tags.push(["summary",e])}get published_at(){const e=this.tagValue("published_at");if(e)return Number.parseInt(e)}set published_at(e){this.removeTag("published_at"),void 0!==e&&this.tags.push(["published_at",e.toString()])}get location(){return this.tagValue("location")}set location(e){this.removeTag("location"),e&&this.tags.push(["location",e])}get price(){const e=this.tags.find(e=>"price"===e[0]);if(e)return{amount:Number.parseFloat(e[1]),currency:e[2],frequency:e[3]}}set price(e){if("string"==typeof e&&(e={amount:Number.parseFloat(e)}),e?.amount){const t=["price",e.amount.toString()];e.currency&&t.push(e.currency),e.frequency&&t.push(e.frequency),this.tags.push(t)}else this.removeTag("price")}async generateTags(){return super.generateTags(),this.published_at||(this.published_at=this.created_at),super.generateTags()}},NDKDraft=class e extends NDKEvent{_event;static kind=31234;static kinds=[31234,1234];counterparty;constructor(e,t){super(e,t),this.kind??=31234}static from(t){return new e(t.ndk,t)}set identifier(e){this.removeTag("d"),this.tags.push(["d",e])}get identifier(){return this.dTag}set event(e){this._event=e instanceof NDKEvent?e:new NDKEvent(void 0,e),this.prepareEvent()}set checkpoint(e){e?(this.tags.push(e.tagReference()),this.kind=1234):(this.removeTag("a"),this.kind=31234)}get isCheckpoint(){return 1234===this.kind}get isProposal(){const e=this.tagValue("p");return!!e&&e!==this.pubkey}async getEvent(e){if(this._event)return this._event;if(e??=this.ndk?.signer,!e)throw new Error("No signer available");if(!(this.content&&this.content.length>0))return null;try{const t=e.pubkey,n=[this.tagValue("p"),this.pubkey].filter(Boolean).find(e=>e!==t);let s;s=new NDKUser({pubkey:n??t}),await this.decrypt(s,e);const r=JSON.parse(this.content);return this._event=await wrapEvent(new NDKEvent(this.ndk,r)),this._event}catch(e){return void console.error(e)}}prepareEvent(){if(!this._event)throw new Error("No event has been provided");this.removeTag("k"),this._event.kind&&this.tags.push(["k",this._event.kind.toString()]),this.content=JSON.stringify(this._event.rawEvent())}async save({signer:e,publish:t,relaySet:n}){if(e??=this.ndk?.signer,!e)throw new Error("No signer available");const s=this.counterparty||await e.user();if(await this.encrypt(s,e),this.counterparty){const e=this.counterparty.pubkey;this.removeTag("p"),this.tags.push(["p",e])}if(!1!==t)return this.publishReplaceable(n)}};function mapImetaTag(e){const t={};if(2===e.length){const n=e[1].split(" ");for(let e=0;e<n.length;e+=2){const s=n[e],r=n[e+1];"fallback"===s?(t.fallback||(t.fallback=[]),t.fallback.push(r)):t[s]=r}return t}const n=e.slice(1);for(const e of n){const n=e.split(" "),s=n[0],r=n.slice(1).join(" ");"fallback"===s?(t.fallback||(t.fallback=[]),t.fallback.push(r)):t[s]=r}return t}function imetaTagToTag(e){const t=["imeta"];for(const[n,s]of Object.entries(e))if(Array.isArray(s))for(const e of s)t.push(`${n} ${e}`);else s&&t.push(`${n} ${s}`);return t}var NDKFollowPack=class e extends NDKEvent{static kind=39089;static kinds=[39089,39092];constructor(e,t){super(e,t),this.kind??=39089}static from(t){return new e(t.ndk,t)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get image(){const e=this.tags.find(e=>"imeta"===e[0]);if(e){const t=mapImetaTag(e);if(t.url)return t.url}return this.tagValue("image")}set image(e){this.tags=this.tags.filter(e=>"imeta"!==e[0]&&"image"!==e[0]),"string"==typeof e?void 0!==e&&this.tags.push(["image",e]):e&&"object"==typeof e&&(this.tags.push(imetaTagToTag(e)),e.url&&this.tags.push(["image",e.url]))}get pubkeys(){return Array.from(new Set(this.tags.filter(e=>"p"===e[0]&&e[1]&&isValidPubkey(e[1])).map(e=>e[1])))}set pubkeys(e){this.tags=this.tags.filter(e=>"p"!==e[0]);for(const t of e)this.tags.push(["p",t])}get description(){return this.tagValue("description")}set description(e){this.removeTag("description"),e&&this.tags.push(["description",e])}},NDKHighlight=class e extends NDKEvent{_article;static kind=9802;static kinds=[9802];constructor(e,t){super(e,t),this.kind??=9802}static from(t){return new e(t.ndk,t)}get url(){return this.tagValue("r")}set context(e){void 0===e?this.tags=this.tags.filter(([e,t])=>"context"!==e):(this.tags=this.tags.filter(([e,t])=>"context"!==e),this.tags.push(["context",e]))}get context(){return this.tags.find(([e,t])=>"context"===e)?.[1]??void 0}get article(){return this._article}set article(e){this._article=e,"string"==typeof e?this.tags.push(["r",e]):this.tag(e)}getArticleTag(){return this.getMatchingTags("a")[0]||this.getMatchingTags("e")[0]||this.getMatchingTags("r")[0]}async getArticle(){if(void 0!==this._article)return this._article;let e;const t=this.getArticleTag();if(t){switch(t[0]){case"a":{const[n,s,r]=t[1].split(":");e=nip19_exports$1.naddrEncode({kind:Number.parseInt(n),pubkey:s,identifier:r});break}case"e":e=nip19_exports$1.noteEncode(t[1]);break;case"r":this._article=t[1]}if(e){let t=await(this.ndk?.fetchEvent(e));t&&(30023===t.kind&&(t=NDKArticle.from(t)),this._article=t)}return this._article}}},NDKImage=class e extends NDKEvent{static kind=20;static kinds=[20];_imetas;constructor(e,t){super(e,t),this.kind??=20}static from(t){return new e(t.ndk,t.rawEvent())}get isValid(){return this.imetas.length>0}get imetas(){return this._imetas||(this._imetas=this.tags.filter(e=>"imeta"===e[0]).map(mapImetaTag).filter(e=>!!e.url)),this._imetas}set imetas(e){this._imetas=e,this.tags=this.tags.filter(e=>"imeta"!==e[0]),this.tags.push(...e.map(imetaTagToTag))}},NDKList=class e extends NDKEvent{_encryptedTags;static kinds=[30001,10004,10050,10030,10015,10001,10002,10007,10006,10003];encryptedTagsLength;constructor(e,t){super(e,t),this.kind??=30001}static from(t){return new e(t.ndk,t)}get title(){const e=this.tagValue("title")||this.tagValue("name");return e||(3===this.kind?"Contacts":1e4===this.kind?"Mute":10001===this.kind?"Pinned Notes":10002===this.kind?"Relay Metadata":10003===this.kind?"Bookmarks":10004===this.kind?"Communities":10005===this.kind?"Public Chats":10006===this.kind?"Blocked Relays":10007===this.kind?"Search Relays":10050===this.kind?"Direct Message Receive Relays":10015===this.kind?"Interests":10030===this.kind?"Emojis":this.tagValue("d"))}set title(e){this.removeTag(["title","name"]),e&&this.tags.push(["title",e])}get name(){return this.title}set name(e){this.title=e}get description(){return this.tagValue("description")}set description(e){this.removeTag("description"),e&&this.tags.push(["description",e])}get image(){return this.tagValue("image")}set image(e){this.removeTag("image"),e&&this.tags.push(["image",e])}isEncryptedTagsCacheValid(){return!(!this._encryptedTags||this.encryptedTagsLength!==this.content.length)}async encryptedTags(e=!0){if(e&&this.isEncryptedTagsCacheValid())return this._encryptedTags;if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const t=await this.ndk.signer.user();try{if(this.content.length>0)try{const e=await this.ndk.signer.decrypt(t,this.content),n=JSON.parse(e);return n?.[0]?(this.encryptedTagsLength=this.content.length,this._encryptedTags=n):(this.encryptedTagsLength=this.content.length,this._encryptedTags=[])}catch(e){}}catch(e){}return[]}validateTag(e){return!0}getItems(e){return this.tags.filter(t=>t[0]===e)}get items(){return this.tags.filter(e=>!["d","L","l","title","name","description","published_at","summary","image","thumb","alt","expiration","subject","client"].includes(e[0]))}async addItem(e,t=void 0,n=!1,s="bottom"){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");let r;if(e instanceof NDKEvent)r=[e.tagReference(t)];else if(e instanceof NDKUser)r=e.referenceTags();else if(e instanceof NDKRelay)r=e.referenceTags();else{if(!Array.isArray(e))throw new Error("Invalid object type");r=[e]}if(t&&r[0].push(t),n){const e=await this.ndk.signer.user(),t=await this.encryptedTags();"top"===s?t.unshift(...r):t.push(...r),this._encryptedTags=t,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(t),await this.encrypt(e)}else"top"===s?this.tags.unshift(...r):this.tags.push(...r);this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItemByValue(e,t=!0){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const n=this.tags.findIndex(t=>t[1]===e);n>=0&&this.tags.splice(n,1);const s=await this.ndk.signer.user(),r=await this.encryptedTags(),i=r.findIndex(t=>t[1]===e);if(i>=0&&(r.splice(i,1),this._encryptedTags=r,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(r),await this.encrypt(s)),t)return this.publishReplaceable();this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItem(e,t){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");if(t){const t=await this.ndk.signer.user(),n=await this.encryptedTags();n.splice(e,1),this._encryptedTags=n,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(n),await this.encrypt(t)}else this.tags.splice(e,1);return this.created_at=Math.floor(Date.now()/1e3),this.emit("change"),this}has(e){return this.items.some(t=>t[1]===e)}filterForItems(){const e=new Set,t=new Map,n=[];for(const n of this.items)if("e"===n[0]&&n[1])e.add(n[1]);else if("a"===n[0]&&n[1]){const[e,s,r]=n[1].split(":");if(!e||!s)continue;const i=`${e}:${s}`,o=t.get(i)||[];o.push(r||""),t.set(i,o)}if(e.size>0&&n.push({ids:Array.from(e)}),t.size>0)for(const[e,s]of t.entries()){const[t,r]=e.split(":");n.push({kinds:[Number.parseInt(t)],authors:[r],"#d":s})}return n}},NDKAppHandlerEvent=class e extends NDKEvent{profile;static kinds=[31990];constructor(e,t){super(e,t),this.kind??=31990}static from(t){const n=new e(t.ndk,t.rawEvent());return n.isValid?n:null}get isValid(){const e=new Map,t=e=>[e[0],e[2]].join(":").toLowerCase(),n=["web","android","ios"];for(const s of this.tags)if(n.includes(s[0])){const n=t(s);if(e.has(n)&&e.get(n)!==s[1].toLowerCase())return!1;e.set(n,s[1].toLowerCase())}return!0}async fetchProfile(){if(void 0===this.profile&&this.content.length>0)try{const e=JSON.parse(this.content);if(e?.name)return e;this.profile=null}catch(e){this.profile=null}return new Promise((e,t)=>{const n=this.author;n.fetchProfile().then(()=>{e(n.profile)}).catch(t)})}},NDKNutzap=class e extends NDKEvent{debug;_proofs=[];static kind=9321;static kinds=[e.kind];constructor(e,t){super(e,t),this.kind??=9321,this.debug=e?.debug.extend("nutzap")??createDebug5("ndk:nutzap"),this.alt||(this.alt="This is a nutzap");try{const e=this.getMatchingTags("proof");e.length?this._proofs=e.map(e=>JSON.parse(e[1])):this._proofs=JSON.parse(this.content)}catch{return}}static from(t){const n=new e(t.ndk,t);if(n._proofs&&n._proofs.length)return n}set comment(e){this.content=e??""}get comment(){const e=this.tagValue("comment");return e||this.content}set proofs(e){this._proofs=e,this.tags=this.tags.filter(e=>"proof"!==e[0]);for(const t of e)this.tags.push(["proof",JSON.stringify(t)])}get proofs(){return this._proofs}get rawP2pk(){const e=this.proofs[0];try{const t=JSON.parse(e.secret);let n;if("string"==typeof t?(n=JSON.parse(t),this.debug("stringified payload",e.secret)):"object"==typeof t&&(n=t),Array.isArray(n)&&"P2PK"===n[0]&&n.length>1&&"object"==typeof n[1]&&null!==n[1])return n[1].data;if("object"==typeof n&&null!==n&&"string"==typeof n[1]?.data)return n[1].data}catch(e){this.debug("error parsing p2pk pubkey",e,this.proofs[0])}}get p2pk(){const e=this.rawP2pk;if(e)return e.startsWith("02")?e.slice(2):e}get mint(){return this.tagValue("u")}set mint(e){this.replaceTag(["u",e])}get unit(){let e=this.tagValue("unit")??"sat";return e?.startsWith("msat")&&(e="sat"),e}set unit(e){if(this.removeTag("unit"),e?.startsWith("msat"))throw new Error("msat is not allowed, use sat denomination instead");e&&this.tag(["unit",e])}get amount(){return this.proofs.reduce((e,t)=>e+t.amount,0)}sender=this.author;set target(e){this.tags=this.tags.filter(e=>"p"!==e[0]),e instanceof NDKEvent&&this.tags.push(e.tagReference())}set recipientPubkey(e){this.removeTag("p"),this.tag(["p",e])}get recipientPubkey(){return this.tagValue("p")}get recipient(){const e=this.recipientPubkey;return this.ndk?this.ndk.getUser({pubkey:e}):new NDKUser({pubkey:e})}async toNostrEvent(){"msat"===this.unit&&(this.unit="sat"),this.removeTag("amount"),this.tags.push(["amount",this.amount.toString()]);const e=await super.toNostrEvent();return e.content=this.comment,e}get isValid(){let e=0,t=0,n=0;for(const s of this.tags)"e"===s[0]&&e++,"p"===s[0]&&t++,"u"===s[0]&&n++;return 1===t&&1===n&&e<=1&&this.proofs.length>0}},NDKProject=class e extends NDKEvent{static kind=31933;static kinds=[31933];_signer;constructor(e,t){super(e,t),this.kind=31933}static from(t){return new e(t.ndk,t.rawEvent())}set repo(e){this.removeTag("repo"),e&&this.tags.push(["repo",e])}set hashtags(e){this.removeTag("hashtags"),e.filter(e=>e.length>0).length&&this.tags.push(["hashtags",...e])}get hashtags(){const e=this.tags.find(e=>"hashtags"===e[0]);return e?e.slice(1):[]}get repo(){return this.tagValue("repo")}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get picture(){return this.tagValue("picture")}set picture(e){this.removeTag("picture"),e&&this.tags.push(["picture",e])}set description(e){this.content=e}get description(){return this.content}get slug(){return this.dTag??"empty-dtag"}async getSigner(){if(this._signer)return this._signer;const e=this.tagValue("key");if(e){const t=await(this.ndk?.signer?.decrypt(this.ndk.activeUser,e));if(!t)throw new Error("Failed to decrypt project key or missing signer context.");this._signer=new NDKPrivateKeySigner(t)}else this._signer=NDKPrivateKeySigner.generate(),await this.encryptAndSaveNsec();return this._signer}async getNsec(){return(await this.getSigner()).privateKey}async setNsec(e){this._signer=new NDKPrivateKeySigner(e),await this.encryptAndSaveNsec()}async encryptAndSaveNsec(){if(!this._signer)throw new Error("Signer is not set.");const e=this._signer.privateKey,t=await(this.ndk?.signer?.encrypt(this.ndk.activeUser,e));t&&(this.removeTag("key"),this.tags.push(["key",t]))}},NDKProjectTemplate=class e extends NDKEvent{static kind=30717;static kinds=[30717];constructor(e,t){super(e,t),this.kind=30717}static from(t){return new e(t.ndk,t.rawEvent())}get templateId(){return this.dTag??""}set templateId(e){this.dTag=e}get name(){return this.tagValue("title")??""}set name(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get description(){return this.tagValue("description")??""}set description(e){this.removeTag("description"),e&&this.tags.push(["description",e])}get repoUrl(){return this.tagValue("uri")??""}set repoUrl(e){this.removeTag("uri"),e&&this.tags.push(["uri",e])}get image(){return this.tagValue("image")}set image(e){this.removeTag("image"),e&&this.tags.push(["image",e])}get command(){return this.tagValue("command")}set command(e){this.removeTag("command"),e&&this.tags.push(["command",e])}get agentConfig(){const e=this.tagValue("agent");if(e)try{return JSON.parse(e)}catch{return}}set agentConfig(e){this.removeTag("agent"),e&&this.tags.push(["agent",JSON.stringify(e)])}get templateTags(){return this.getMatchingTags("t").map(e=>e[1]).filter(Boolean)}set templateTags(e){this.tags=this.tags.filter(e=>"t"!==e[0]),e.forEach(e=>{e&&this.tags.push(["t",e])})}},READ_MARKER="read",WRITE_MARKER="write",NDKRelayList=class e extends NDKEvent{static kinds=[10002];constructor(e,t){super(e,t),this.kind??=10002}static from(t){return new e(t.ndk,t.rawEvent())}get readRelayUrls(){return this.tags.filter(e=>"r"===e[0]||"relay"===e[0]).filter(e=>!e[2]||e[2]&&e[2]===READ_MARKER).map(e=>tryNormalizeRelayUrl(e[1])).filter(e=>!!e)}set readRelayUrls(e){for(const t of e)this.tags.push(["r",t,READ_MARKER])}get writeRelayUrls(){return this.tags.filter(e=>"r"===e[0]||"relay"===e[0]).filter(e=>!e[2]||e[2]&&e[2]===WRITE_MARKER).map(e=>tryNormalizeRelayUrl(e[1])).filter(e=>!!e)}set writeRelayUrls(e){for(const t of e)this.tags.push(["r",t,WRITE_MARKER])}get bothRelayUrls(){return this.tags.filter(e=>"r"===e[0]||"relay"===e[0]).filter(e=>!e[2]).map(e=>e[1])}set bothRelayUrls(e){for(const t of e)this.tags.push(["r",t])}get relays(){return this.tags.filter(e=>"r"===e[0]||"relay"===e[0]).map(e=>e[1])}get relaySet(){if(!this.ndk)throw new Error("NDKRelayList has no NDK instance");return new NDKRelaySet(new Set(this.relays.map(e=>this.ndk?.pool.getRelay(e)).filter(e=>!!e)),this.ndk)}};function relayListFromKind3(e,t){try{const n=JSON.parse(t.content),s=new NDKRelayList(e),r=new Set,i=new Set;for(let[e,t]of Object.entries(n)){try{e=normalizeRelayUrl(e)}catch{continue}if(t){const n=t;n.write&&i.add(e),n.read&&r.add(e)}else r.add(e),i.add(e)}return s.readRelayUrls=Array.from(r),s.writeRelayUrls=Array.from(i),s}catch{}}var NDKRepost=class e extends NDKEvent{_repostedEvents;static kinds=[6,16];static from(t){return new e(t.ndk,t.rawEvent())}async repostedEvents(e,t){const n=[];if(!this.ndk)throw new Error("NDK instance not set");if(void 0!==this._repostedEvents)return this._repostedEvents;for(const s of this.repostedEventIds()){const r=filterForId(s),i=await this.ndk.fetchEvent(r,t);i&&n.push(e?e.from(i):i)}return n}repostedEventIds(){return this.tags.filter(e=>"e"===e[0]||"a"===e[0]).map(e=>e[1])}};function filterForId(e){if(e.match(/:/)){const[t,n,s]=e.split(":");return{kinds:[Number.parseInt(t)],authors:[n],"#d":[s]}}return{ids:[e]}}var NDKSimpleGroupMemberList=class e extends NDKEvent{relaySet;memberSet=new Set;static kind=39002;static kinds=[39002];constructor(e,t){super(e,t),this.kind??=39002,this.memberSet=new Set(this.members)}static from(t){return new e(t.ndk,t)}get members(){return this.getMatchingTags("p").map(e=>e[1])}hasMember(e){return this.memberSet.has(e)}async publish(e,t,n){return e??=this.relaySet,super.publishReplaceable(e,t,n)}},NDKSimpleGroupMetadata=class e extends NDKEvent{static kind=39e3;static kinds=[39e3];constructor(e,t){super(e,t),this.kind??=39e3}static from(t){return new e(t.ndk,t)}get name(){return this.tagValue("name")}get picture(){return this.tagValue("picture")}get about(){return this.tagValue("about")}get scope(){return this.getMatchingTags("public").length>0?"public":this.getMatchingTags("public").length>0?"private":void 0}set scope(e){this.removeTag("public"),this.removeTag("private"),"public"===e?this.tags.push(["public",""]):"private"===e&&this.tags.push(["private",""])}get access(){return this.getMatchingTags("open").length>0?"open":this.getMatchingTags("closed").length>0?"closed":void 0}set access(e){this.removeTag("open"),this.removeTag("closed"),"open"===e?this.tags.push(["open",""]):"closed"===e&&this.tags.push(["closed",""])}};function strToPosition(e){const[t,n]=e.split(",").map(Number);return{x:t,y:n}}function strToDimension(e){const[t,n]=e.split("x").map(Number);return{width:t,height:n}}var NDKStorySticker=class e{static Text="text";static Pubkey="pubkey";static Event="event";static Prompt="prompt";static Countdown="countdown";type;value;position;dimension;properties;constructor(e){if(Array.isArray(e)){const t=e;if("sticker"!==t[0]||t.length<5)throw new Error("Invalid sticker tag");this.type=t[1],this.value=t[2],this.position=strToPosition(t[3]),this.dimension=strToDimension(t[4]);const n={};for(let e=5;e<t.length;e++){const[s,...r]=t[e].split(" ");n[s]=r.join(" ")}Object.keys(n).length>0&&(this.properties=n)}else this.type=e,this.value=void 0,this.position={x:0,y:0},this.dimension={width:0,height:0}}static fromTag(t){try{return new e(t)}catch{return null}}get style(){return this.properties?.style}set style(e){e?this.properties={...this.properties,style:e}:delete this.properties?.style}get rotation(){return this.properties?.rot?Number.parseFloat(this.properties.rot):void 0}set rotation(e){void 0!==e?this.properties={...this.properties,rot:e.toString()}:delete this.properties?.rot}get isValid(){return this.hasValidDimensions()&&this.hasValidPosition()}hasValidDimensions=()=>"number"==typeof this.dimension.width&&"number"==typeof this.dimension.height&&!Number.isNaN(this.dimension.width)&&!Number.isNaN(this.dimension.height);hasValidPosition=()=>"number"==typeof this.position.x&&"number"==typeof this.position.y&&!Number.isNaN(this.position.x)&&!Number.isNaN(this.position.y);toTag(){if(!this.isValid){const e=[this.hasValidDimensions()?void 0:"dimensions is invalid",this.hasValidPosition()?void 0:"position is invalid"].filter(Boolean);throw new Error(`Invalid sticker: ${e.join(", ")}`)}let e;switch(this.type){case"event":e=this.value.tagId();break;case"pubkey":e=this.value.pubkey;break;default:e=this.value}const t=["sticker",this.type,e,coordinates(this.position),dimension(this.dimension)];if(this.properties)for(const[e,n]of Object.entries(this.properties))t.push(`${e} ${n}`);return t}},NDKStory=class e extends NDKEvent{static kind=23;static kinds=[23];_imeta;_dimensions;constructor(e,t){if(super(e,t),this.kind??=23,t)for(const e of t.tags)switch(e[0]){case"imeta":this._imeta=mapImetaTag(e);break;case"dim":this.dimensions=strToDimension(e[1])}}static from(t){return new e(t.ndk,t)}get isValid(){return!!this.imeta}get imeta(){return this._imeta}set imeta(e){this._imeta=e,this.tags=this.tags.filter(e=>"imeta"!==e[0]),e&&this.tags.push(imetaTagToTag(e))}get dimensions(){const e=this.tagValue("dim");if(e)return strToDimension(e)}set dimensions(e){this.removeTag("dim"),e&&this.tags.push(["dim",`${e.width}x${e.height}`])}get duration(){const e=this.tagValue("dur");if(e)return Number.parseInt(e)}set duration(e){this.removeTag("dur"),void 0!==e&&this.tags.push(["dur",e.toString()])}get stickers(){const e=[];for(const t of this.tags){if("sticker"!==t[0]||t.length<5)continue;const n=NDKStorySticker.fromTag(t);n&&e.push(n)}return e}addSticker(e){let t;if(e instanceof NDKStorySticker)t=e;else{const n=["sticker",e.type,"string"==typeof e.value?e.value:"",coordinates(e.position),dimension(e.dimension)];if(e.properties)for(const[t,s]of Object.entries(e.properties))n.push(`${t} ${s}`);t=new NDKStorySticker(n),t.value=e.value}("pubkey"===t.type||"event"===t.type)&&this.tag(t.value),this.tags.push(t.toTag())}removeSticker(e){const t=this.stickers;if(e<0||e>=t.length)return;let n=0;for(let t=0;t<this.tags.length;t++)if("sticker"===this.tags[t][0]){if(n===e){this.tags.splice(t,1);break}n++}}},coordinates=e=>`${e.x},${e.y}`,dimension=e=>`${e.width}x${e.height}`,NDKSubscriptionReceipt=class e extends NDKEvent{debug;static kinds=[7003];constructor(e,t){super(e,t),this.kind??=7003,this.debug=e?.debug.extend("subscription-start")??createDebug5("ndk:subscription-start")}static from(t){return new e(t.ndk,t.rawEvent())}get recipient(){const e=this.getMatchingTags("p")?.[0];if(!e)return;return new NDKUser({pubkey:e[1]})}set recipient(e){this.removeTag("p"),e&&this.tags.push(["p",e.pubkey])}get subscriber(){const e=this.getMatchingTags("P")?.[0];if(!e)return;return new NDKUser({pubkey:e[1]})}set subscriber(e){this.removeTag("P"),e&&this.tags.push(["P",e.pubkey])}set subscriptionStart(e){this.debug(`before setting subscription start: ${this.rawEvent}`),this.removeTag("e"),this.tag(e,"subscription",!0),this.debug(`after setting subscription start: ${this.rawEvent}`)}get tierName(){const e=this.getMatchingTags("tier")?.[0];return e?.[1]}get isValid(){const e=this.validPeriod;if(!e)return!1;if(e.start>e.end)return!1;const t=this.getMatchingTags("p"),n=this.getMatchingTags("P");return 1===t.length&&1===n.length}get validPeriod(){const e=this.getMatchingTags("valid")?.[0];if(e)try{return{start:new Date(1e3*Number.parseInt(e[1])),end:new Date(1e3*Number.parseInt(e[2]))}}catch{return}}set validPeriod(e){this.removeTag("valid"),e&&this.tags.push(["valid",Math.floor(e.start.getTime()/1e3).toString(),Math.floor(e.end.getTime()/1e3).toString()])}get startPeriod(){return this.validPeriod?.start}get endPeriod(){return this.validPeriod?.end}isActive(e){e??=new Date;const t=this.validPeriod;return!!t&&(!(e<t.start)&&!(e>t.end))}},possibleIntervalFrequencies=["daily","weekly","monthly","quarterly","yearly"];function newAmount(e,t,n){return["amount",e.toString(),t,n]}function parseTagToSubscriptionAmount(e){const t=Number.parseInt(e[1]);if(Number.isNaN(t)||null==t||t<=0)return;const n=e[2];if(void 0===n||""===n)return;const s=e[3];return void 0!==s&&possibleIntervalFrequencies.includes(s)?{amount:t,currency:n,term:s}:void 0}var NDKSubscriptionTier=class e extends NDKArticle{static kind=37001;static kinds=[37001];constructor(e,t){const n=t?.kind??37001;super(e,t),this.kind=n}static from(t){return new e(t.ndk,t)}get perks(){return this.getMatchingTags("perk").map(e=>e[1]).filter(e=>void 0!==e)}addPerk(e){this.tags.push(["perk",e])}get amounts(){return this.getMatchingTags("amount").map(e=>parseTagToSubscriptionAmount(e)).filter(e=>void 0!==e)}addAmount(e,t,n){this.tags.push(newAmount(e,t,n))}set relayUrl(e){this.tags.push(["r",e])}get relayUrls(){return this.getMatchingTags("r").map(e=>e[1]).filter(e=>void 0!==e)}get verifierPubkey(){return this.tagValue("p")}set verifierPubkey(e){this.removeTag("p"),e&&this.tags.push(["p",e])}get isValid(){return void 0!==this.title&&this.amounts.length>0}},NDKSubscriptionStart=class e extends NDKEvent{debug;static kinds=[7001];constructor(e,t){super(e,t),this.kind??=7001,this.debug=e?.debug.extend("subscription-start")??createDebug5("ndk:subscription-start")}static from(t){return new e(t.ndk,t.rawEvent())}get recipient(){const e=this.getMatchingTags("p")?.[0];if(!e)return;return new NDKUser({pubkey:e[1]})}set recipient(e){this.removeTag("p"),e&&this.tags.push(["p",e.pubkey])}get amount(){const e=this.getMatchingTags("amount")?.[0];if(e)return parseTagToSubscriptionAmount(e)}set amount(e){this.removeTag("amount"),e&&this.tags.push(newAmount(e.amount,e.currency,e.term))}get tierId(){const e=this.getMatchingTags("e")?.[0],t=this.getMatchingTags("a")?.[0];if(e&&t)return e[1]??t[1]}set tier(e){this.removeTag("e"),this.removeTag("a"),this.removeTag("event"),e&&(this.tag(e),this.removeTag("p"),this.tags.push(["p",e.pubkey]),this.tags.push(["event",JSON.stringify(e.rawEvent())]))}async fetchTier(){const e=this.tagValue("event");if(e)try{const t=JSON.parse(e);return new NDKSubscriptionTier(this.ndk,t)}catch{this.debug("Failed to parse event tag")}const t=this.tierId;if(!t)return;const n=await(this.ndk?.fetchEvent(t));return n?NDKSubscriptionTier.from(n):void 0}get isValid(){return 1!==this.getMatchingTags("amount").length?(this.debug("Invalid # of amount tag"),!1):this.amount?1!==this.getMatchingTags("p").length?(this.debug("Invalid # of p tag"),!1):!!this.recipient||(this.debug("Invalid p tag"),!1):(this.debug("Invalid amount tag"),!1)}},NDKTask=class e extends NDKEvent{static kind=1934;static kinds=[1934];constructor(e,t){super(e,t),this.kind=1934}static from(t){return new e(t.ndk,t.rawEvent())}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get title(){return this.tagValue("title")}set project(e){this.removeTag("a"),this.tags.push(e.tagReference())}get projectSlug(){const e=this.getMatchingTags("a")[0];return e?e[1].split(/:/)?.[2]:void 0}},NDKThread=class e extends NDKEvent{static kind=11;static kinds=[11];constructor(e,t){super(e,t),this.kind??=11}static from(t){return new e(t.ndk,t)}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}},NDKVideo=class e extends NDKEvent{static kind=21;static kinds=[34235,34236,22,21];_imetas;static from(t){return new e(t.ndk,t.rawEvent())}get title(){return this.tagValue("title")}set title(e){this.removeTag("title"),e&&this.tags.push(["title",e])}get thumbnail(){let e;return this.imetas&&this.imetas.length>0&&(e=this.imetas[0].image?.[0]),e??this.tagValue("thumb")}get imetas(){return this._imetas||(this._imetas=this.tags.filter(e=>"imeta"===e[0]).map(mapImetaTag)),this._imetas}set imetas(e){this._imetas=e,this.tags=this.tags.filter(e=>"imeta"!==e[0]),this.tags.push(...e.map(imetaTagToTag))}get url(){return this.imetas&&this.imetas.length>0?this.imetas[0].url:this.tagValue("url")}get published_at(){const e=this.tagValue("published_at");if(e)return Number.parseInt(e)}async generateTags(){if(super.generateTags(),!this.kind&&this.imetas?.[0]?.dim){const[e,t]=this.imetas[0].dim.split("x"),n=e&&t&&Number.parseInt(e)<Number.parseInt(t),s=this.duration&&this.duration<120;this.kind=s&&n?22:21}return super.generateTags()}get duration(){const e=this.tagValue("duration");if(e)return Number.parseInt(e)}set duration(e){this.removeTag("duration"),void 0!==e&&this.tags.push(["duration",Math.floor(e).toString()])}},NDKWiki=class e extends NDKArticle{static kind=30818;static kinds=[30818];static from(t){return new e(t.ndk,t.rawEvent())}get isDefered(){return this.hasTag("a","defer")}get deferedId(){return this.tagValue("a","defer")}set defer(e){this.removeTag("a","defer"),this.tag(e,"defer")}},NDKWikiMergeRequest=class e extends NDKEvent{static kinds=[818];static from(t){return new e(t.ndk,t.rawEvent())}get targetId(){return this.tagValue("a")}set target(e){this.tags=this.tags.filter(e=>"a"===e[0]||("e"===e[0]&&"source"!==e[3]||void 0)),this.tag(e)}get sourceId(){return this.tagValue("e","source")}set source(e){this.removeTag("e","source"),this.tag(e,"source",!1,"e")}},registeredEventClasses=new Set;function wrapEvent(e){const t=new Map,n=[...[NDKImage,NDKVideo,NDKCashuMintList,NDKArticle,NDKHighlight,NDKDraft,NDKWiki,NDKWikiMergeRequest,NDKNutzap,NDKProject,NDKTask,NDKProjectTemplate,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKSubscriptionTier,NDKSubscriptionStart,NDKSubscriptionReceipt,NDKList,NDKRelayList,NDKStory,NDKBlossomList,NDKFollowPack,NDKThread,NDKRepost,NDKClassified,NDKAppHandlerEvent,NDKDVMJobFeedback,NDKCashuMintAnnouncement,NDKFedimintMint,NDKMintRecommendation],...registeredEventClasses];for(const e of n)for(const n of e.kinds)t.set(n,e);const s=t.get(e.kind);return s?s.from(e):e}function queryFullyFilled(e){return!(!filterIncludesIds(e.filter)||!resultHasAllRequestedIds(e))}function filterIncludesIds(e){return!!e.ids}function resultHasAllRequestedIds(e){const t=e.filter.ids;return!!t&&t.length===e.eventFirstSeen.size}function filterFromId(e){let t;if(e.match(NIP33_A_REGEX)){const[t,n,s]=e.split(":"),r={authors:[n],kinds:[Number.parseInt(t)]};return s&&(r["#d"]=[s]),r}if(e.match(BECH32_REGEX))try{switch(t=nip19_exports$1.decode(e),t.type){case"nevent":{const e={ids:[t.data.id]};return t.data.author&&(e.authors=[t.data.author]),t.data.kind&&(e.kinds=[t.data.kind]),e}case"note":return{ids:[t.data]};case"naddr":{const e={authors:[t.data.pubkey],kinds:[t.data.kind]};return t.data.identifier&&(e["#d"]=[t.data.identifier]),e}}}catch(t){console.error("Error decoding",e,t)}return{ids:[e]}}function isNip33AValue(e){return null!==e.match(NIP33_A_REGEX)}var NIP33_A_REGEX=/^(\d+):([0-9A-Fa-f]+)(?::(.*))?$/,BECH32_REGEX=/^n(event|ote|profile|pub|addr)1[\d\w]+$/;function relaysFromBech32(e,t){try{const n=nip19_exports$1.decode(e);if(["naddr","nevent"].includes(n?.type)){const e=n.data;if(e?.relays)return e.relays.map(e=>new NDKRelay(e,t.relayAuthDefaultPolicy,t))}}catch(e){}return[]}var defaultOpts={closeOnEose:!1,cacheUsage:"CACHE_FIRST",dontSaveToCache:!1,groupable:!0,groupableDelay:100,groupableDelayType:"at-most",cacheUnconstrainFilter:["limit","since","until"],includeMuted:!1},NDKSubscription=class extends lib$1.EventEmitter{subId;filters;opts;pool;skipVerification=!1;skipValidation=!1;relayFilters;relaySet;ndk;debug;eventFirstSeen=new Map;eosesSeen=new Set;lastEventReceivedAt;mostRecentCacheEventTimestamp;internalId;closeOnEose;poolMonitor;skipOptimisticPublishEvent=!1;cacheUnconstrainFilter;constructor(e,t,n,s){super(),this.ndk=e,this.opts={...defaultOpts,...n||{}},this.pool=this.opts.pool||e.pool;const r=Array.isArray(t)?t:[t],i="validate"===e.filterValidationMode?"validate":"fix"===e.filterValidationMode?"fix":"ignore";if(this.filters=processFilters(r,i,e.debug,e),0===this.filters.length)throw new Error("Subscription must have at least one filter");this.subId=s||this.opts.subId,this.internalId=Math.random().toString(36).substring(7),this.debug=e.debug.extend(`subscription[${this.opts.subId??this.internalId}]`),this.opts.relaySet?this.relaySet=this.opts.relaySet:this.opts.relayUrls&&(this.relaySet=NDKRelaySet.fromRelayUrls(this.opts.relayUrls,this.ndk)),this.skipVerification=this.opts.skipVerification||!1,this.skipValidation=this.opts.skipValidation||!1,this.closeOnEose=this.opts.closeOnEose||!1,this.skipOptimisticPublishEvent=this.opts.skipOptimisticPublishEvent||!1,this.cacheUnconstrainFilter=this.opts.cacheUnconstrainFilter,this.opts.onEvent&&this.on("event",this.opts.onEvent),this.opts.onEose&&this.on("eose",this.opts.onEose),this.opts.onClose&&this.on("close",this.opts.onClose)}relaysMissingEose(){if(!this.relayFilters)return[];return Array.from(this.relayFilters?.keys()).filter(e=>!this.eosesSeen.has(this.pool.getRelay(e,!1,!1)))}get filter(){return this.filters[0]}get groupableDelay(){if(this.isGroupable())return this.opts?.groupableDelay}get groupableDelayType(){return this.opts?.groupableDelayType||"at-most"}isGroupable(){return this.opts?.groupable||!1}shouldQueryCache(){if(this.opts.addSinceFromCache)return!0;if("ONLY_RELAY"===this.opts?.cacheUsage)return!1;this.filters.some(e=>e.kinds?.some(e=>kindIsEphemeral(e)));return!0}shouldQueryRelays(){return"ONLY_CACHE"!==this.opts?.cacheUsage}shouldWaitForCache(){return!!this.opts.addSinceFromCache||!!this.opts.closeOnEose&&!!this.ndk.cacheAdapter?.locking&&"PARALLEL"!==this.opts.cacheUsage}start(e=!0){let t;const n=n=>{for(const e of n)e.created_at&&(!this.mostRecentCacheEventTimestamp||e.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=e.created_at),this.eventReceived(e,void 0,!0,!1);e||(t=n)},s=()=>{this.shouldQueryRelays()?(this.startWithRelays(),this.startPoolMonitor()):this.emit("eose",this)};return this.shouldQueryCache()?(t=this.startWithCache(),t instanceof Promise?this.shouldWaitForCache()?(t.then(e=>{n(e),queryFullyFilled(this)?this.emit("eose",this):s()}),null):(t.then(e=>{n(e),this.shouldQueryRelays()||this.emit("eose",this)}),this.shouldQueryRelays()&&s(),null):(n(t),queryFullyFilled(this)?this.emit("eose",this):s(),t)):(s(),null)}startPoolMonitor(){this.debug.extend("pool-monitor"),this.poolMonitor=e=>{if(this.relayFilters?.has(e.url))return;calculateRelaySetsFromFilters(this.ndk,this.filters,this.pool,this.opts.relayGoalPerAuthor).get(e.url)&&(this.relayFilters?.set(e.url,this.filters),e.subscribe(this,this.filters))},this.pool.on("relay:connect",this.poolMonitor)}onStopped;stop(){this.emit("close",this),this.poolMonitor&&this.pool.off("relay:connect",this.poolMonitor),this.onStopped?.()}hasAuthorsFilter(){return this.filters.some(e=>e.authors?.length)}startWithCache(){return this.ndk.cacheAdapter?.query?this.ndk.cacheAdapter.query(this):[]}startWithRelays(){let e=this.filters;if(this.opts.addSinceFromCache&&this.mostRecentCacheEventTimestamp){const t=this.mostRecentCacheEventTimestamp+1;e=e.map(e=>({...e,since:Math.max(e.since||0,t)}))}if(this.relaySet&&0!==this.relaySet.relays.size){this.relayFilters=new Map;for(const t of this.relaySet.relays)this.relayFilters.set(t.url,e)}else this.relayFilters=calculateRelaySetsFromFilters(this.ndk,e,this.pool,this.opts.relayGoalPerAuthor);for(const[e,t]of this.relayFilters){this.pool.getRelay(e,!0,!0,t).subscribe(this,t)}}refreshRelayConnections(){if(this.relaySet&&this.relaySet.relays.size>0)return;const e=calculateRelaySetsFromFilters(this.ndk,this.filters,this.pool,this.opts.relayGoalPerAuthor);for(const[t,n]of e)if(!this.relayFilters?.has(t)){this.relayFilters?.set(t,n);this.pool.getRelay(t,!0,!0,n).subscribe(this,n)}}eventReceived(e,t,n=!1,s=!1){const r=e.id,i=this.eventFirstSeen.has(r);let o;if(e instanceof NDKEvent&&(o=e),i){const i=Date.now()-(this.eventFirstSeen.get(r)||0);if(this.emit("event:dup",e,t,i,this,n,s),this.opts?.onEventDup&&this.opts.onEventDup(e,t,i,this,n,s),n||s||!t||!this.ndk.cacheAdapter?.setEventDup||this.opts.dontSaveToCache||(o??=e instanceof NDKEvent?e:new NDKEvent(this.ndk,e),this.ndk.cacheAdapter.setEventDup(o,t)),t){const n=verifiedSignatures.get(r);if(n&&"string"==typeof n)if(e.sig===n)t.addValidatedEvent();else{const n=e instanceof NDKEvent?e:new NDKEvent(this.ndk,e);this.ndk.reportInvalidSignature(n,t)}}}else{if(o??=new NDKEvent(this.ndk,e),o.ndk=this.ndk,o.relay=t,!n&&!s){if(!this.skipValidation&&!o.isValid)return void this.debug("Event failed validation %s from relay %s",r,t?.url);if(t){if(t.shouldValidateEvent()&&!this.skipVerification)if(o.relay=t,this.ndk.asyncSigVerification)o.verifySignature(!0);else{if(!o.verifySignature(!0))return this.debug("Event failed signature validation",e),void this.ndk.reportInvalidSignature(o,t);t.addValidatedEvent()}else t.addNonValidatedEvent()}this.ndk.cacheAdapter&&!this.opts.dontSaveToCache&&this.ndk.cacheAdapter.setEvent(o,this.filters,t)}if(!this.opts.includeMuted&&this.ndk.muteFilter&&this.ndk.muteFilter(o))return void this.debug("Event muted, skipping");s&&!0===this.skipOptimisticPublishEvent||(this.emitEvent(this.opts?.wrap??!1,o,t,n,s),this.eventFirstSeen.set(r,Date.now()))}this.lastEventReceivedAt=Date.now()}emitEvent(e,t,n,s,r){const i=e?wrapEvent(t):t;i instanceof Promise?i.then(e=>this.emitEvent(!1,e,n,s,r)):i&&this.emit("event",i,n,this,s,r)}closedReceived(e,t){this.emit("closed",e,t)}eoseTimeout;eosed=!1;eoseReceived(e){this.debug("EOSE received from %s",e.url),this.eosesSeen.add(e);let t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0;const n=this.eosesSeen.size===this.relayFilters?.size,s=queryFullyFilled(this),r=e=>{this.debug("Performing EOSE: %s %d",e,this.eosed),this.eosed||(this.eoseTimeout&&clearTimeout(this.eoseTimeout),this.emit("eose",this),this.eosed=!0,this.opts?.closeOnEose&&this.stop())};if(s||n)r("query filled or seen all");else if(this.relayFilters){let e=1e3;const n=new Set(this.pool.connectedRelays().map(e=>e.url)),s=Array.from(this.relayFilters.keys()).filter(e=>n.has(e));if(0===s.length)return void this.debug("No connected relays, waiting for all relays to connect",Array.from(this.relayFilters.keys()).join(", "));const i=this.eosesSeen.size/s.length;if(this.debug("Percentage of relays that have sent EOSE",{subId:this.subId,percentageOfRelaysThatHaveSentEose:i,seen:this.eosesSeen.size,total:s.length}),this.eosesSeen.size>=2&&i>=.5){if(e*=1-i,0===e)return void r("time to wait was 0");this.eoseTimeout&&clearTimeout(this.eoseTimeout);const n=()=>{t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0,void 0!==t&&t<20?this.eoseTimeout=setTimeout(n,e):r(`send eose timeout: ${e}`)};this.eoseTimeout=setTimeout(n,e)}}}},kindIsEphemeral=e=>e>=2e4&&e<3e4;async function follows(e,t,n=3){if(!this.ndk)throw new Error("NDK not set");const s=await this.ndk.fetchEvent({kinds:[n],authors:[this.pubkey]},e||{groupable:!1});if(s){const e=new Set;return s.tags.forEach(t=>{"p"===t[0]&&t[1]&&isValidPubkey(t[1])&&e.add(t[1])}),t&&this.ndk?.outboxTracker?.trackUsers(Array.from(e)),[...e].reduce((e,t)=>{const n=new NDKUser({pubkey:t});return n.ndk=this.ndk,e.add(n),e},new Set)}return new Set}var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function getNip05For(e,t,n=fetch,s={}){return await e.queuesNip05.add({id:t,func:async()=>{if(e.cacheAdapter?.loadNip05){const n=await e.cacheAdapter.loadNip05(t);if("missing"!==n){if(n){const t=new NDKUser({pubkey:n.pubkey,relayUrls:n.relays,nip46Urls:n.nip46});return t.ndk=e,t}if("no-cache"!==s.cache)return null}}const r=t.match(NIP05_REGEX);if(!r)return null;const[i,o="_",a]=r;try{const r=await n(`https://${a}/.well-known/nostr.json?name=${o}`,s),{names:i,relays:c,nip46:l}=parseNIP05Result(await r.json()),u=i[o.toLowerCase()];let d=null;return u&&(d={pubkey:u,relays:c?.[u],nip46:l?.[u]}),e?.cacheAdapter?.saveNip05&&e.cacheAdapter.saveNip05(t,d),d}catch(n){return e?.cacheAdapter?.saveNip05&&e?.cacheAdapter.saveNip05(t,null),console.error("Failed to fetch NIP05 for",t,n),null}}})}function parseNIP05Result(e){const t={names:{}};for(const[n,s]of Object.entries(e.names))"string"==typeof n&&"string"==typeof s&&(t.names[n.toLowerCase()]=s);if(e.relays){t.relays={};for(const[n,s]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(s)&&(t.relays[n]=s.filter(e=>"string"==typeof e))}if(e.nip46){t.nip46={};for(const[n,s]of Object.entries(e.nip46))"string"==typeof n&&Array.isArray(s)&&(t.nip46[n]=s.filter(e=>"string"==typeof e))}return t}function profileFromEvent(e){const t={};let n;try{n=JSON.parse(e.content)}catch(e){throw new Error(`Failed to parse profile event: ${e}`)}t.profileEvent=JSON.stringify(e.rawEvent());for(const e of Object.keys(n))switch(e){case"name":t.name=n.name;break;case"display_name":t.displayName=n.display_name;break;case"image":case"picture":t.picture=n.picture||n.image,t.image=t.picture;break;case"banner":t.banner=n.banner;break;case"bio":t.bio=n.bio;break;case"nip05":t.nip05=n.nip05;break;case"lud06":t.lud06=n.lud06;break;case"lud16":t.lud16=n.lud16;break;case"about":t.about=n.about;break;case"website":t.website=n.website;break;default:t[e]=n[e]}return t.created_at=e.created_at,t}function serializeProfile(e){const t={};for(const[n,s]of Object.entries(e))switch(n){case"username":case"name":t.name=s;break;case"displayName":t.display_name=s;break;case"image":case"picture":t.picture=s;break;case"bio":case"about":t.about=s;break;default:t[n]=s}return JSON.stringify(t)}var NDKUser=class e{ndk;profile;profileEvent;_npub;_pubkey;relayUrls=[];nip46Urls=[];constructor(e){if(e.npub&&(this._npub=e.npub),e.hexpubkey&&(this._pubkey=e.hexpubkey),e.pubkey&&(this._pubkey=e.pubkey),e.relayUrls&&(this.relayUrls=e.relayUrls),e.nip46Urls&&(this.nip46Urls=e.nip46Urls),e.nprofile)try{const t=nip19_exports$1.decode(e.nprofile);"nprofile"===t.type&&(this._pubkey=t.data.pubkey,t.data.relays&&t.data.relays.length>0&&this.relayUrls.push(...t.data.relays))}catch(e){console.error("Failed to decode nprofile",e)}}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("pubkey not set");this._npub=nip19_exports$1.npubEncode(this.pubkey)}return this._npub}get nprofile(){const e=this.profileEvent?.onRelays?.map(e=>e.url);return nip19_exports$1.nprofileEncode({pubkey:this.pubkey,relays:e})}set npub(e){this._npub=e}get pubkey(){if(!this._pubkey){if(!this._npub)throw new Error("npub not set");this._pubkey=nip19_exports$1.decode(this.npub).data}return this._pubkey}set pubkey(e){this._pubkey=e}filter(){return{"#p":[this.pubkey]}}async getZapInfo(e){if(!this.ndk)throw new Error("No NDK instance found");const t=async t=>{if(!e)return t;let n;const s=new Promise((t,s)=>{n=setTimeout(()=>s(new Error("Timeout")),e)});try{const e=await Promise.race([t,s]);return n&&clearTimeout(n),e}catch(e){if(e instanceof Error&&"Timeout"===e.message)try{return await t}catch(e){return}return}},[n,s]=await Promise.all([t(this.fetchProfile()),t(this.ndk.fetchEvent({kinds:[10019],authors:[this.pubkey]}))]),r=new Map;if(s){const e=NDKCashuMintList.from(s);e.mints.length>0&&r.set("nip61",{mints:e.mints,relays:e.relays,p2pk:e.p2pk})}if(n){const{lud06:e,lud16:t}=n;r.set("nip57",{lud06:e,lud16:t})}return r}static async fromNip05(t,n,s=!1){if(!n)throw new Error("No NDK instance found");const r={};s&&(r.cache="no-cache");const i=await getNip05For(n,t,n?.httpFetch,r);if(i){const t=new e({pubkey:i.pubkey,relayUrls:i.relays,nip46Urls:i.nip46});return t.ndk=n,t}}async fetchProfile(e,t=!1){if(!this.ndk)throw new Error("NDK not set");let n=null;if(this.ndk.cacheAdapter&&(this.ndk.cacheAdapter.fetchProfile||this.ndk.cacheAdapter.fetchProfileSync)&&"ONLY_RELAY"!==e?.cacheUsage){let e=null;if(this.ndk.cacheAdapter.fetchProfileSync?e=this.ndk.cacheAdapter.fetchProfileSync(this.pubkey):this.ndk.cacheAdapter.fetchProfile&&(e=await this.ndk.cacheAdapter.fetchProfile(this.pubkey)),e)return this.profile=e,e}return e??={},e.cacheUsage??="ONLY_RELAY",e.closeOnEose??=!0,e.groupable??=!0,e.groupableDelay??=250,n||(n=await this.ndk.fetchEvent({kinds:[0],authors:[this.pubkey]},e)),n?(this.profile=profileFromEvent(n),t&&this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile):null}follows=follows.bind(this);async followSet(e,t,n=3){const s=await this.follows(e,t,n);return new Set(Array.from(s).map(e=>e.pubkey))}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e?(t[0].push("",e),t):t}async publish(){if(!this.ndk)throw new Error("No NDK instance found");if(!this.profile)throw new Error("No profile available");this.ndk.assertSigner();const e=new NDKEvent(this.ndk,{kind:0,content:serializeProfile(this.profile)});await e.publish()}async follow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n)),t.has(e))return!1;t.add(e);const s=new NDKEvent(this.ndk,{kind:n});for(const e of t)s.tag(e);return await s.publish(),!0}async unfollow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n));const s=new Set;let r=!1;for(const n of t)n.pubkey!==e.pubkey?s.add(n):r=!0;if(!r)return!1;const i=new NDKEvent(this.ndk,{kind:n});for(const e of s)i.tag(e);return await i.publish()}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(this.ndk,e);return null===t?null:t.pubkey===this.pubkey}},signerRegistry=new Map;function registerSigner(e,t){signerRegistry.set(e,t)}var NDKPrivateKeySigner=class e{_user;_privateKey;_pubkey;constructor(e,t){if("string"==typeof e)if(e.startsWith("nsec1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("nsec"!==t)throw new Error("Invalid private key provided.");this._privateKey=n}else{if(64!==e.length)throw new Error("Invalid private key provided.");this._privateKey=hexToBytes(e)}else this._privateKey=e;this._pubkey=getPublicKey(this._privateKey),t&&(this._user=t.getUser({pubkey:this._pubkey})),this._user??=new NDKUser({pubkey:this._pubkey})}get privateKey(){if(!this._privateKey)throw new Error("Not ready");return bytesToHex(this._privateKey)}get pubkey(){if(!this._pubkey)throw new Error("Not ready");return this._pubkey}get nsec(){if(!this._privateKey)throw new Error("Not ready");return nip19_exports$1.nsecEncode(this._privateKey)}get npub(){if(!this._pubkey)throw new Error("Not ready");return nip19_exports$1.npubEncode(this._pubkey)}encryptToNcryptsec(e,t=16,n=2){if(!this._privateKey)throw new Error("Private key not available");return encrypt$1(this._privateKey,e,t,n)}static generate(){const t=generateSecretKey();return new e(t)}static fromNcryptsec(t,n,s){const r=decrypt$1(t,n);return new e(r,s)}async blockUntilReady(){return this._user}async user(){return this._user}get userSync(){return this._user}async sign(e){if(!this._privateKey)throw Error("Attempted to sign without a private key");return finalizeEvent(e,this._privateKey).sig}async encryptionEnabled(e){const t=[];return e&&"nip04"!==e||t.push("nip04"),e&&"nip44"!==e||t.push("nip44"),t}async encrypt(e,t,n){if(!this._privateKey||!this.privateKey)throw Error("Attempted to encrypt without a private key");const s=e.pubkey;if("nip44"===n){const e=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.encrypt(t,e)}return await nip04_exports.encrypt(this._privateKey,s,t)}async decrypt(e,t,n){if(!this._privateKey||!this.privateKey)throw Error("Attempted to decrypt without a private key");const s=e.pubkey;if("nip44"===n){const e=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.decrypt(t,e)}return await nip04_exports.decrypt(this._privateKey,s,t)}toPayload(){if(!this._privateKey)throw new Error("Private key not available");const e={type:"private-key",payload:this.privateKey};return JSON.stringify(e)}static async fromPayload(t,n){const s=JSON.parse(t);if("private-key"!==s.type)throw new Error(`Invalid payload type: expected 'private-key', got ${s.type}`);if(!s.payload||"string"!=typeof s.payload)throw new Error("Invalid payload content for private-key signer");return new e(s.payload,n)}};function dedup(e,t){return e.created_at>t.created_at?e:t}async function getRelayListForUser(e,t){return(await getRelayListForUsers([e],t)).get(e)}async function getRelayListForUsers(e,t,n=!1,s=1e3,r){const i=t.outboxPool||t.pool,o=new Set;for(const e of i.relays.values())o.add(e);if(r)for(const e of r.values())for(const t of e){const e=i.getRelay(t,!0,!0);e&&o.add(e)}const a=new Map,c=new Map,l=new NDKRelaySet(o,t);if(t.cacheAdapter?.locking&&!n){const n=await t.fetchEvents({kinds:[3,10002],authors:Array.from(new Set(e))},{cacheUsage:"ONLY_CACHE",subId:"ndk-relay-list-fetch"});for(const e of n)10002===e.kind&&a.set(e.pubkey,NDKRelayList.from(e));for(const e of n)if(3===e.kind){if(a.has(e.pubkey))continue;const n=relayListFromKind3(t,e);n&&c.set(e.pubkey,n)}e=e.filter(e=>!a.has(e)&&!c.has(e))}if(0===e.length)return a;const u=new Map,d=new Map;return new Promise(n=>{let r=!1;(async()=>{const c={closeOnEose:!0,pool:i,groupable:!0,subId:"ndk-relay-list-fetch",addSinceFromCache:!0,relaySet:l};l&&(c.relaySet=l),t.subscribe({kinds:[3,10002],authors:e},c,{onEvent:e=>{if(10002===e.kind){const t=u.get(e.pubkey);if(t&&t.created_at>e.created_at)return;u.set(e.pubkey,e)}else if(3===e.kind){const t=d.get(e.pubkey);if(t&&t.created_at>e.created_at)return;d.set(e.pubkey,e)}},onEose:()=>{if(!r){r=!0,t.debug(`[getRelayListForUsers] EOSE - relayListEvents: ${u.size}, contactListEvents: ${d.size}`);for(const e of u.values())a.set(e.pubkey,NDKRelayList.from(e));for(const n of e){if(a.has(n))continue;const e=d.get(n);if(!e)continue;const s=relayListFromKind3(t,e);s&&a.set(n,s)}t.debug(`[getRelayListForUsers] Returning ${a.size} relay lists for ${e.length} pubkeys`),n(a)}}});const h=Array.from(o).some(e=>e.status<=2),p=Array.from(o).some(e=>4===e.status);let f=s;(h||p)&&(f=s+3e3),t.debug(`[getRelayListForUsers] Setting fallback timeout to ${f}ms (disconnected: ${h}, connecting: ${p})`,{pubkeys:e}),setTimeout(()=>{r||(r=!0,t.debug(`[getRelayListForUsers] Timeout reached, returning ${a.size} relay lists`),n(a))},f)})()})}registerSigner("private-key",NDKPrivateKeySigner);var OutboxItem=class{type;relayUrlScores;readRelays;writeRelays;constructor(e){this.type=e,this.relayUrlScores=new Map,this.readRelays=new Set,this.writeRelays=new Set}},OutboxTracker=class extends lib$1.EventEmitter{data;ndk;debug;constructor(e){super(),this.ndk=e,this.debug=e.debug.extend("outbox-tracker"),this.data=new dist.LRUCache({maxSize:1e5,entryExpirationTimeInMS:12e4})}async trackUsers(e,t=!1){const n=[];for(let s=0;s<e.length;s+=400){const r=e.slice(s,s+400),i=r.map(e=>getKeyFromItem(e)).filter(e=>!this.data.has(e));if(0===i.length)continue;for(const e of i)this.data.set(e,new OutboxItem("user"));const o=new Map;for(const e of r)e instanceof NDKUser&&e.relayUrls.length>0&&o.set(e.pubkey,e.relayUrls);n.push(new Promise(e=>{getRelayListForUsers(i,this.ndk,t,1e3,o).then(e=>{this.debug(`Received relay lists for ${e.size} pubkeys out of ${i.length} requested`);for(const[t,n]of e){let e=this.data.get(t);if(e??=new OutboxItem("user"),n){if(e.readRelays=new Set(normalize(n.readRelayUrls)),e.writeRelays=new Set(normalize(n.writeRelayUrls)),this.ndk.relayConnectionFilter){for(const t of e.readRelays)this.ndk.relayConnectionFilter(t)||e.readRelays.delete(t);for(const t of e.writeRelays)this.ndk.relayConnectionFilter(t)||e.writeRelays.delete(t)}this.data.set(t,e),this.emit("user:relay-list-updated",t,e),this.debug(`Adding ${e.readRelays.size} read relays and ${e.writeRelays.size} write relays for ${t}`,n?.rawEvent())}}}).finally(e)}))}return Promise.all(n)}track(e,t,n=!0){const s=getKeyFromItem(e);t??=getTypeFromItem(e);let r=this.data.get(s);return r||(r=new OutboxItem(t),e instanceof NDKUser&&this.trackUsers([e])),r}};function getKeyFromItem(e){return e instanceof NDKUser?e.pubkey:e}function getTypeFromItem(e){return e instanceof NDKUser?"user":"kind"}function correctRelaySet(e,t){const n=t.connectedRelays();if(!Array.from(e.relays).some(e=>n.map(e=>e.url).includes(e.url)))for(const t of n)e.addRelay(t);if(0===n.length)for(const n of t.relays.values())e.addRelay(n);return e}var NDKSubscriptionManager=class{subscriptions;seenEvents=new dist.LRUCache({maxSize:1e4,entryExpirationTimeInMS:3e5});constructor(){this.subscriptions=new Map}add(e){this.subscriptions.set(e.internalId,e),e.onStopped,e.onStopped=()=>{this.subscriptions.delete(e.internalId)},e.on("close",()=>{this.subscriptions.delete(e.internalId)})}seenEvent(e,t){const n=this.seenEvents.get(e)||[];n.some(e=>e.url===t.url)||n.push(t),this.seenEvents.set(e,n)}dispatchEvent(e,t,n=!1){t&&this.seenEvent(e.id,t);const s=this.subscriptions.values(),r=[];for(const t of s)matchFilters(t.filters,e)&&r.push(t);for(const s of r)s.eventReceived(e,t,!1,n)}},debug6=createDebug5("ndk:active-user");async function getUserRelayList(e){if(!this.autoConnectUserRelays)return;const t=await getRelayListForUser(e.pubkey,this);if(t){for(const e of t.relays){let t=this.pool.relays.get(e);t||(t=new NDKRelay(e,this.relayAuthDefaultPolicy,this),this.pool.addRelay(t))}return debug6("Connected to %d user relays",t.relays.length),t}}async function setActiveUser(e){if(!this.autoConnectUserRelays)return;const t=this.outboxPool||this.pool;t.connectedRelays.length>0?await getUserRelayList.call(this,e):t.once("connect",async()=>{await getUserRelayList.call(this,e)})}function getEntity(e){try{const t=nip19_exports$1.decode(e);return"npub"===t.type?npub(this,t.data):"nprofile"===t.type?nprofile(this,t.data):t}catch(e){return null}}function npub(e,t){return e.getUser({pubkey:t})}function nprofile(e,t){const n=e.getUser({pubkey:t.pubkey});return t.relays&&(n.relayUrls=t.relays),n}function isValidHint(e){if(!e||""===e)return!1;try{return new URL(e),!0}catch(e){return!1}}async function fetchEventFromTag(e,t,n,s={type:"timeout"}){const r=this.debug.extend("fetch-event-from-tag"),[i,o,a]=e;r("fetching event from tag",e,n={},s);const c=getRelaysForSync(this,t.pubkey);if(c&&c.size>0){r("fetching event from author relays %o",Array.from(c));const e=NDKRelaySet.fromRelayUrls(Array.from(c),this),t=await this.fetchEvent(o,n,e);if(t)return t}else r("no author relays found for %s",t.pubkey,t);const l=calculateRelaySetsFromFilters(this,[{ids:[o]}],this.pool);r("fetching event without relay hint",l);const u=await this.fetchEvent(o,n);if(u)return u;if(a&&""!==a){const e=await this.fetchEvent(o,n,this.pool.getRelay(a,!0,!0,[{ids:[o]}]));if(e)return e}let d;const h=isValidHint(a)?this.pool.getRelay(a,!1,!0,[{ids:[o]}]):void 0,p=new Promise(e=>{this.fetchEvent(o,n,h).then(e)});if(!isValidHint(a)||"none"===s.type)return p;const f=new Promise(async e=>{const t=s.relaySet,i=s.timeout??1500,a=new Promise(e=>setTimeout(e,i));if("timeout"===s.type&&await a,d)e(d);else{r("fallback fetch triggered");e(await this.fetchEvent(o,n,t))}});switch(s.type){case"timeout":return Promise.race([p,f]);case"eose":return d=await p,d||f}}var Queue=class{queue=[];maxConcurrency;processing=new Set;promises=new Map;constructor(e,t){this.maxConcurrency=t}add(e){if(this.promises.has(e.id))return this.promises.get(e.id);const t=new Promise((t,n)=>{this.queue.push({...e,func:()=>e.func().then(e=>(t(e),e),e=>{throw n(e),e})}),this.process()});return this.promises.set(e.id,t),t.finally(()=>{this.promises.delete(e.id),this.processing.delete(e.id),this.process()}),t}process(){if(this.processing.size>=this.maxConcurrency||0===this.queue.length)return;const e=this.queue.shift();e&&!this.processing.has(e.id)&&(this.processing.add(e.id),e.func())}clear(){this.queue=[]}clearProcessing(){this.processing.clear()}clearAll(){this.clear(),this.clearProcessing()}length(){return this.queue.length}},DEFAULT_OUTBOX_RELAYS=["wss://purplepag.es/","wss://nos.lol/"],NDK=class extends lib$1.EventEmitter{_explicitRelayUrls;pool;outboxPool;_signer;_activeUser;cacheAdapter;debug;devWriteRelaySet;outboxTracker;muteFilter;relayConnectionFilter;clientName;clientNip89;queuesZapConfig;queuesNip05;asyncSigVerification=!1;initialValidationRatio=1;lowestValidationRatio=.1;validationRatioFn;filterValidationMode="validate";subManager;aiGuardrails;_signatureVerificationFunction;_signatureVerificationWorker;signatureVerificationTimeMs=0;publishingFailureHandled=!1;pools=[];relayAuthDefaultPolicy;httpFetch;netDebug;autoConnectUserRelays=!0;walletConfig;constructor(e={}){super(),this.debug=e.debug||createDebug5("ndk"),this.netDebug=e.netDebug,this._explicitRelayUrls=e.explicitRelayUrls||[],this.subManager=new NDKSubscriptionManager,this.pool=new NDKPool(e.explicitRelayUrls||[],this),this.pool.name="Main",this.pool.on("relay:auth",async(e,t)=>{this.relayAuthDefaultPolicy&&await this.relayAuthDefaultPolicy(e,t)}),this.autoConnectUserRelays=e.autoConnectUserRelays??!0,this.clientName=e.clientName,this.clientNip89=e.clientNip89,this.relayAuthDefaultPolicy=e.relayAuthDefaultPolicy,!1!==e.enableOutboxModel&&(this.outboxPool=new NDKPool(e.outboxRelayUrls||DEFAULT_OUTBOX_RELAYS,this,{debug:this.debug.extend("outbox-pool"),name:"Outbox Pool"}),this.outboxTracker=new OutboxTracker(this),this.outboxTracker.on("user:relay-list-updated",(e,t)=>{this.debug(`Outbox relay list updated for ${e}`);for(const t of this.subManager.subscriptions.values()){t.filters.some(t=>t.authors?.includes(e))&&"function"==typeof t.refreshRelayConnections&&(this.debug(`Refreshing relay connections for subscription ${t.internalId}`),t.refreshRelayConnections())}})),this.signer=e.signer,this.cacheAdapter=e.cacheAdapter,this.muteFilter=e.muteFilter,this.relayConnectionFilter=e.relayConnectionFilter,e.devWriteRelayUrls&&(this.devWriteRelaySet=NDKRelaySet.fromRelayUrls(e.devWriteRelayUrls,this)),this.queuesZapConfig=new Queue("zaps",3),this.queuesNip05=new Queue("nip05",10),e.signatureVerificationWorker&&(this.signatureVerificationWorker=e.signatureVerificationWorker),e.signatureVerificationFunction&&(this.signatureVerificationFunction=e.signatureVerificationFunction),this.initialValidationRatio=e.initialValidationRatio||1,this.lowestValidationRatio=e.lowestValidationRatio||.1,this.validationRatioFn=e.validationRatioFn||this.defaultValidationRatioFn,this.filterValidationMode=e.filterValidationMode||"validate",this.aiGuardrails=new AIGuardrails(e.aiGuardrails||!1),this.aiGuardrails.ndkInstantiated(this);try{this.httpFetch=fetch}catch{}}set explicitRelayUrls(e){this._explicitRelayUrls=e.map(normalizeRelayUrl),this.pool.relayUrls=e}get explicitRelayUrls(){return this._explicitRelayUrls||[]}set signatureVerificationWorker(e){this._signatureVerificationWorker=e,e?(signatureVerificationInit(e),this.asyncSigVerification=!0):this.asyncSigVerification=!1}set signatureVerificationFunction(e){this._signatureVerificationFunction=e,this.asyncSigVerification=!!e}get signatureVerificationFunction(){return this._signatureVerificationFunction}addExplicitRelay(e,t,n=!0){let s;return s="string"==typeof e?new NDKRelay(e,t,this):e,this.pool.addRelay(s,n),this.explicitRelayUrls?.push(s.url),s}toJSON(){return{relayCount:this.pool.relays.size}.toString()}get activeUser(){return this._activeUser}set activeUser(e){const t=this._activeUser?.pubkey!==e?.pubkey;this._activeUser=e,t&&this.emit("activeUser:change",e),e&&t&&setActiveUser.call(this,e)}get signer(){return this._signer}set signer(e){this._signer=e,e&&this.emit("signer:ready",e),e?.user().then(e=>{e.ndk=this,this.activeUser=e})}async connect(e){if(this._signer&&this.autoConnectUserRelays&&(this.debug("Attempting to connect to user relays specified by signer %o",await(this._signer.relays?.(this))),this._signer.relays)){(await this._signer.relays(this)).forEach(e=>this.pool.addRelay(e))}const t=[this.pool.connect(e)];return this.outboxPool&&t.push(this.outboxPool.connect(e)),Promise.allSettled(t).then(()=>{})}reportInvalidSignature(e,t){this.debug(`Invalid signature detected for event ${e.id}${t?` from relay ${t.url}`:""}`),this.emit("event:invalid-sig",e,t)}defaultValidationRatioFn(e,t,n){if(t<10)return this.initialValidationRatio;const s=Math.min(t/100,1),r=this.initialValidationRatio*(1-s)+this.lowestValidationRatio*s;return Math.max(r,this.lowestValidationRatio)}getUser(e){if("string"==typeof e){if(e.startsWith("npub1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("npub"!==t)throw new Error(`Invalid npub: ${e}`);return this.getUser({pubkey:n})}if(e.startsWith("nprofile1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("nprofile"!==t)throw new Error(`Invalid nprofile: ${e}`);return this.getUser({pubkey:n.pubkey,relayUrls:n.relays})}return this.getUser({pubkey:e})}const t=new NDKUser(e);return t.ndk=this,t}async getUserFromNip05(e,t=!1){return NDKUser.fromNip05(e,this,t)}async fetchUser(e,t=!1){if(e.includes("@")||e.includes(".")&&!e.startsWith("n"))return NDKUser.fromNip05(e,this,t);if(e.startsWith("npub1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("npub"!==t)throw new Error(`Invalid npub: ${e}`);const s=new NDKUser({pubkey:n});return s.ndk=this,s}if(e.startsWith("nprofile1")){const{type:t,data:n}=nip19_exports$1.decode(e);if("nprofile"!==t)throw new Error(`Invalid nprofile: ${e}`);const s=new NDKUser({pubkey:n.pubkey,relayUrls:n.relays});return s.ndk=this,s}{const t=new NDKUser({pubkey:e});return t.ndk=this,t}}subscribe(e,t,n=!0,s=!0){let r,i=t?.relaySet,o=s;n instanceof NDKRelaySet?(console.warn("relaySet is deprecated, use opts.relaySet instead. This will be removed in version v2.14.0"),i=n,o=s):"boolean"!=typeof n&&"object"!=typeof n||(o=n);const a={relaySet:i,...t};o&&"object"==typeof o&&(o.onEvent&&(a.onEvent=o.onEvent),o.onEose&&(a.onEose=o.onEose),o.onClose&&(a.onClose=o.onClose),o.onEvents&&(r=o.onEvents));const c=new NDKSubscription(this,e,a);this.subManager.add(c);const l=c.pool;if(c.relaySet)for(const e of c.relaySet.relays)l.useTemporaryRelay(e,void 0,c.filters);if(this.outboxPool&&c.hasAuthorsFilter()){const e=c.filters.filter(e=>e.authors&&e.authors?.length>0).flatMap(e=>e.authors);this.outboxTracker?.trackUsers(e)}return o&&setTimeout(()=>{const e=c.start(!r);e&&e.length>0&&r&&r(e)},0),c}fetchEventFromTag=fetchEventFromTag.bind(this);fetchEventSync(e){if(!this.cacheAdapter)throw new Error("Cache adapter not set");let t;t="string"==typeof e?[filterFromId(e)]:e;const n=new NDKSubscription(this,t),s=this.cacheAdapter.query(n);if(s instanceof Promise)throw new Error("Cache adapter is async");return s.map(e=>(e.ndk=this,e))}async fetchEvent(e,t,n){let s,r;if(n instanceof NDKRelay?r=new NDKRelaySet(new Set([n]),this):n instanceof NDKRelaySet&&(r=n),!n&&"string"==typeof e&&!isNip33AValue(e)){const t=relaysFromBech32(e,this);t.length>0&&(r=new NDKRelaySet(new Set(t),this),r=correctRelaySet(r,this.pool))}if(s="string"==typeof e?[filterFromId(e)]:Array.isArray(e)?e:[e],"string"!=typeof e&&this.aiGuardrails?.ndk?.fetchingEvents(s),0===s.length)throw new Error(`Invalid filter: ${JSON.stringify(e)}`);return new Promise((e,n)=>{let i=null;const o={...t||{},closeOnEose:!0};r&&(o.relaySet=r);const a=setTimeout(()=>{c.stop(),this.aiGuardrails._nextCallDisabled=null,e(i)},1e4),c=this.subscribe(s,o,{onEvent:t=>{t.ndk=this,t.isReplaceable()?(!i||i.created_at<t.created_at)&&(i=t):(clearTimeout(a),this.aiGuardrails._nextCallDisabled=null,e(t))},onEose:()=>{clearTimeout(a),this.aiGuardrails._nextCallDisabled=null,e(i)}})})}async fetchEvents(e,t,n){return this.aiGuardrails?.ndk?.fetchingEvents(e,t),new Promise(s=>{const r=new Map,i={...t||{},closeOnEose:!0};n&&(i.relaySet=n);this.subscribe(e,{...i,onEvent:e=>{let t;t=e instanceof NDKEvent?e:new NDKEvent(void 0,e);const n=t.deduplicationKey(),s=r.get(n);s&&(t=dedup(s,t)),t.ndk=this,r.set(n,t)},onEose:()=>{this.aiGuardrails._nextCallDisabled=null,s(new Set(r.values()))}})})}assertSigner(){if(!this.signer)throw this.emit("signer:required"),new Error("Signer required")}getEntity=getEntity.bind(this);guardrailOff(e){return this.aiGuardrails._nextCallDisabled=e?"string"==typeof e?new Set([e]):new Set(e):"all",this}set wallet(e){e?(this.walletConfig??={},this.walletConfig.lnPay=e?.lnPay?.bind(e),this.walletConfig.cashuPay=e?.cashuPay?.bind(e)):this.walletConfig=void 0}},nip19_exports={};__reExport(nip19_exports,nip19_star);var nip49_exports={};function disconnect(e,t){return t??=createDebug5("ndk:relay:auth-policies:disconnect"),async n=>{t?.(`Relay ${n.url} requested authentication, disconnecting`),e.removeRelay(n.url)}}async function signAndAuth(e,t,n,s,r,i){try{await e.sign(n),r(e)}catch(n){s?.(`Failed to publish auth event to relay ${t.url}`,n),i(e)}}function signIn({ndk:e,signer:t,debug:n}={}){return n??=createDebug5("ndk:auth-policies:signIn"),async(s,r)=>{n?.(`Relay ${s.url} requested authentication, signing in`);const i=new NDKEvent(e);return i.kind=22242,i.tags=[["relay",s.url],["challenge",r]],t??=e?.signer,new Promise(async(r,o)=>{t?await signAndAuth(i,s,t,n,r,o):e?.once("signer:ready",async e=>{await signAndAuth(i,s,e,n,r,o)})})}}__reExport(nip49_exports,nip49_star);var NDKRelayAuthPolicies={disconnect:disconnect,signIn:signIn};async function ndkSignerFromPayload(e,t){let n;try{n=JSON.parse(e)}catch(t){return void console.error("Failed to parse signer payload string",e,t)}if(!n||"string"!=typeof n.type)return void console.error("Failed to parse signer payload string",e,new Error("Missing type field"));const s=signerRegistry.get(n.type);if(!s)throw new Error(`Unknown signer type: ${n.type}`);try{return await s.fromPayload(e,t)}catch(e){const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to deserialize signer type ${n.type}: ${t}`)}}var NDKNip07Signer=class e{_userPromise;encryptionQueue=[];encryptionProcessing=!1;debug;waitTimeout;_pubkey;ndk;_user;constructor(e=1e3,t){this.debug=createDebug5("ndk:nip07"),this.waitTimeout=e,this.ndk=t}get pubkey(){if(!this._pubkey)throw new Error("Not ready");return this._pubkey}async blockUntilReady(){await this.waitForExtension();const e=await(window.nostr?.getPublicKey());if(!e)throw new Error("User rejected access");let t;return this._pubkey=e,t=this.ndk?this.ndk.getUser({pubkey:e}):new NDKUser({pubkey:e}),this._user=t,t}async user(){return this._userPromise||(this._userPromise=this.blockUntilReady()),this._userPromise}get userSync(){if(!this._user)throw new Error("User not ready");return this._user}async sign(e){await this.waitForExtension();const t=await(window.nostr?.signEvent(e));if(!t)throw new Error("Failed to sign event");return t.sig}async relays(e){await this.waitForExtension();const t=await(window.nostr?.getRelays?.())||{},n=[];for(const e of Object.keys(t))t[e].read&&t[e].write&&n.push(e);return n.map(t=>new NDKRelay(t,e?.relayAuthDefaultPolicy,e))}async encryptionEnabled(e){const t=[];return e&&"nip04"!==e||!Boolean(window.nostr?.nip04)||t.push("nip04"),e&&"nip44"!==e||!Boolean(window.nostr?.nip44)||t.push("nip44"),t}async encrypt(e,t,n="nip04"){if(!await this.encryptionEnabled(n))throw new Error(`${n}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(n,"encrypt",s,t)}async decrypt(e,t,n="nip04"){if(!await this.encryptionEnabled(n))throw new Error(`${n}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(n,"decrypt",s,t)}async queueEncryption(e,t,n,s){return new Promise((r,i)=>{this.encryptionQueue.push({scheme:e,method:t,counterpartyHexpubkey:n,value:s,resolve:r,reject:i}),this.encryptionProcessing||this.processEncryptionQueue()})}async processEncryptionQueue(e,t=0){if(!e&&0===this.encryptionQueue.length)return void(this.encryptionProcessing=!1);this.encryptionProcessing=!0;const n=e||this.encryptionQueue.shift();if(!n)return void(this.encryptionProcessing=!1);const{scheme:s,method:r,counterpartyHexpubkey:i,value:o,resolve:a,reject:c}=n;this.debug("Processing encryption queue item",{method:r,counterpartyHexpubkey:i,value:o});try{const e=await(window.nostr?.[s]?.[r](i,o));if(!e)throw new Error("Failed to encrypt/decrypt");a(e)}catch(e){const s=e instanceof Error?e.message:String(e);if(s.includes("call already executing")&&t<5)return this.debug("Retrying encryption queue item",{method:r,counterpartyHexpubkey:i,value:o,retries:t}),void setTimeout(()=>{this.processEncryptionQueue(n,t+1)},50*t);c(e instanceof Error?e:new Error(s))}this.processEncryptionQueue()}waitForExtension(){return new Promise((e,t)=>{if(window.nostr)return void e();let n;const s=setInterval(()=>{window.nostr&&(clearTimeout(n),clearInterval(s),e())},100);n=setTimeout(()=>{clearInterval(s),t(new Error("NIP-07 extension not available"))},this.waitTimeout)})}toPayload(){return JSON.stringify({type:"nip07",payload:""})}static async fromPayload(t,n){const s=JSON.parse(t);if("nip07"!==s.type)throw new Error(`Invalid payload type: expected 'nip07', got ${s.type}`);return new e(void 0,n)}};registerSigner("nip07",NDKNip07Signer);var NDKNostrRpc=class extends lib$1.EventEmitter{ndk;signer;relaySet;debug;encryptionType="nip04";pool;constructor(e,t,n,s){if(super(),this.ndk=e,this.signer=t,s){this.pool=new NDKPool(s,e,{debug:n.extend("rpc-pool"),name:"Nostr RPC"}),this.relaySet=new NDKRelaySet(new Set,e,this.pool);for(const r of s){const s=this.pool.getRelay(r,!1,!1);s.authPolicy=NDKRelayAuthPolicies.signIn({ndk:e,signer:t,debug:n}),this.relaySet.addRelay(s),s.connect()}}this.debug=n.extend("rpc")}subscribe(e){return new Promise(t=>{const n=this.ndk.subscribe(e,{closeOnEose:!1,groupable:!1,cacheUsage:"ONLY_RELAY",pool:this.pool,relaySet:this.relaySet,onEvent:async e=>{try{const t=await this.parseEvent(e);t.method?this.emit("request",t):(this.emit(`response-${t.id}`,t),this.emit("response",t))}catch(t){this.debug("error parsing event",t,e.rawEvent())}},onEose:()=>{this.debug("eosed"),t(n)}})})}async parseEvent(e){"nip44"===this.encryptionType&&e.content.includes("?iv=")?this.encryptionType="nip04":"nip04"!==this.encryptionType||e.content.includes("?iv=")||(this.encryptionType="nip44");const t=this.ndk.getUser({pubkey:e.pubkey});let n;t.ndk=this.ndk;try{n=await this.signer.decrypt(t,e.content,this.encryptionType)}catch(s){const r="nip04"===this.encryptionType?"nip44":"nip04";n=await this.signer.decrypt(t,e.content,r),this.encryptionType=r}const s=JSON.parse(n),{id:r,method:i,params:o,result:a,error:c}=s;return i?{id:r,pubkey:e.pubkey,method:i,params:o,event:e}:{id:r,result:a,error:c,event:e}}async sendResponse(e,t,n,s=24133,r){const i={id:e,result:n};r&&(i.error=r);const o=await this.signer.user(),a=this.ndk.getUser({pubkey:t}),c=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(i),tags:[["p",t]],pubkey:o.pubkey});c.content=await this.signer.encrypt(a,c.content,this.encryptionType),await c.sign(this.signer),await c.publish(this.relaySet)}async sendRequest(e,t,n=[],s=24133,r){const i=Math.random().toString(36).substring(7),o=await this.signer.user(),a=this.ndk.getUser({pubkey:e}),c={id:i,method:t,params:n},l=new Promise(()=>{const e=t=>{"auth_url"===t.result?(this.once(`response-${i}`,e),this.emit("authUrl",t.error)):r&&r(t)};this.once(`response-${i}`,e)}),u=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(c),tags:[["p",e]],pubkey:o.pubkey});return u.content=await this.signer.encrypt(a,u.content,this.encryptionType),await u.sign(this.signer),await u.publish(this.relaySet),l}};function nostrConnectGenerateSecret(){return Math.random().toString(36).substring(2,15)}function generateNostrConnectUri(e,t,n,s){const r=s?.name?encodeURIComponent(s.name):"",i=s?.url?encodeURIComponent(s.url):"";let o=`nostrconnect://${e}?image=${s?.image?encodeURIComponent(s.image):""}&url=${i}&name=${r}&perms=${s?.perms?encodeURIComponent(s.perms):""}&secret=${encodeURIComponent(t)}`;return n&&(o+=`&relay=${encodeURIComponent(n)}`),o}var NDKNip46Signer=class e extends lib$1.EventEmitter{ndk;_user;bunkerPubkey;userPubkey;get pubkey(){if(!this.userPubkey)throw new Error("Not ready");return this.userPubkey}secret;localSigner;nip05;rpc;debug;relayUrls;subscription;nostrConnectUri;nostrConnectSecret;constructor(e,t,n,s,r){super(),this.ndk=e,this.debug=e.debug.extend("nip46:signer"),this.relayUrls=s,this.localSigner=n?"string"==typeof n?new NDKPrivateKeySigner(n):n:NDKPrivateKeySigner.generate(),!1===t||(t?t.startsWith("bunker://")?this.bunkerFlowInit(t):this.nip05Init(t):this.nostrconnectFlowInit(r)),this.rpc=new NDKNostrRpc(this.ndk,this.localSigner,this.debug,this.relayUrls)}static bunker(t,n,s){return new e(t,n,s)}static nostrconnect(t,n,s,r){return new e(t,void 0,s,[n],r)}nostrconnectFlowInit(e){this.nostrConnectSecret=nostrConnectGenerateSecret();const t=this.localSigner.pubkey;this.nostrConnectUri=generateNostrConnectUri(t,this.nostrConnectSecret,this.relayUrls?.[0],e)}bunkerFlowInit(e){const t=new URL(e),n=t.hostname||t.pathname.replace(/^\/\//,""),s=t.searchParams.get("pubkey"),r=t.searchParams.getAll("relay"),i=t.searchParams.get("secret");this.bunkerPubkey=n,this.userPubkey=s,this.relayUrls=r,this.secret=i}nip05Init(e){this.nip05=e}async startListening(){if(this.subscription)return;const e=await this.localSigner.user();if(!e)throw new Error("Local signer not ready");this.subscription=await this.rpc.subscribe({kinds:[24133],"#p":[e.pubkey]})}async user(){return this._user?this._user:this.blockUntilReady()}get userSync(){if(!this._user)throw new Error("Remote user not ready synchronously");return this._user}async blockUntilReadyNostrConnect(){return new Promise((e,t)=>{const n=t=>{t.result===this.nostrConnectSecret&&(this._user=t.event.author,this.userPubkey=t.event.pubkey,this.bunkerPubkey=t.event.pubkey,this.rpc.off("response",n),e(this._user))};this.startListening(),this.rpc.on("response",n)})}async blockUntilReady(){if(!this.bunkerPubkey&&!this.nostrConnectSecret&&!this.nip05)throw new Error("Bunker pubkey not set");if(this.nostrConnectSecret)return this.blockUntilReadyNostrConnect();if(this.nip05&&!this.userPubkey){const e=await NDKUser.fromNip05(this.nip05,this.ndk);e&&(this._user=e,this.userPubkey=e.pubkey,this.relayUrls=e.nip46Urls,this.rpc=new NDKNostrRpc(this.ndk,this.localSigner,this.debug,this.relayUrls))}if(!this.bunkerPubkey&&this.userPubkey)this.bunkerPubkey=this.userPubkey;else if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");return await this.startListening(),this.rpc.on("authUrl",(...e)=>{this.emit("authUrl",...e)}),new Promise((e,t)=>{const n=[this.userPubkey??""];if(this.secret&&n.push(this.secret),!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"connect",n,24133,n=>{"ack"===n.result?this.getPublicKey().then(t=>{this.userPubkey=t,this._user=this.ndk.getUser({pubkey:t}),e(this._user)}):t(n.error)})})}stop(){this.subscription?.stop(),this.subscription=void 0}async getPublicKey(){return this.userPubkey?this.userPubkey:new Promise((e,t)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,t=>{e(t.result)})})}async encryptionEnabled(e){return e?[e]:Promise.resolve(["nip04","nip44"])}async encrypt(e,t,n="nip04"){return this.encryption(e,t,n,"encrypt")}async decrypt(e,t,n="nip04"){return this.encryption(e,t,n,"decrypt")}async encryption(e,t,n,s){return new Promise((r,i)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,`${n}_${s}`,[e.pubkey,t],24133,e=>{e.error?i(e.error):r(e.result)})})}async sign(e){return new Promise((t,n)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[JSON.stringify(e)],24133,e=>{if(e.error)n(e.error);else{const n=JSON.parse(e.result);t(n.sig)}})})}async createAccount(e,t,n){await this.startListening();const s=[];return e&&s.push(e),t&&s.push(t),n&&s.push(n),new Promise((e,t)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"create_account",s,24133,n=>{if(n.error)t(n.error);else{const t=n.result;e(t)}})})}toPayload(){if(!this.bunkerPubkey||!this.userPubkey)throw new Error("NIP-46 signer is not fully initialized for serialization");const e={type:"nip46",payload:{bunkerPubkey:this.bunkerPubkey,userPubkey:this.userPubkey,relayUrls:this.relayUrls,secret:this.secret,localSignerPayload:this.localSigner.toPayload(),nip05:this.nip05||null}};return JSON.stringify(e)}static async fromPayload(t,n){if(!n)throw new Error("NDK instance is required to deserialize NIP-46 signer");const s=JSON.parse(t);if("nip46"!==s.type)throw new Error(`Invalid payload type: expected 'nip46', got ${s.type}`);const r=s.payload;if(!r||"object"!=typeof r||!r.localSignerPayload)throw new Error("Invalid payload content for nip46 signer");const i=await ndkSignerFromPayload(r.localSignerPayload,n);if(!i)throw new Error("Failed to deserialize local signer for NIP-46");if(!(i instanceof NDKPrivateKeySigner))throw new Error("Local signer must be an instance of NDKPrivateKeySigner");let o;return o=new e(n,!1,i,r.relayUrls),o.userPubkey=r.userPubkey,o.bunkerPubkey=r.bunkerPubkey,o.relayUrls=r.relayUrls,o.secret=r.secret,r.userPubkey&&(o._user=new NDKUser({pubkey:r.userPubkey}),o._user&&(o._user.ndk=n)),o}};registerSigner("nip46",NDKNip46Signer),createDebug5("ndk:zapper:ln"),createDebug5("ndk:zapper");const{window:window_1}=globals;function create_if_block$2(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b;function v(e,t){return"extension"===e[2]?create_if_block_3$2:create_else_block$2}let w=v(e),_=w(e),E=e[5]&&create_if_block_2$2(e),k=e[6]&&create_if_block_1$2(e);return{c(){t=element("div"),n=element("div"),s=element("div"),r=element("h2"),r.textContent="Login to Nostr",i=space(),o=element("button"),o.textContent="×",a=space(),c=element("div"),l=element("div"),u=element("button"),u.textContent="Extension",d=space(),h=element("button"),h.textContent="Nsec",p=space(),f=element("div"),_.c(),g=space(),E&&E.c(),y=space(),k&&k.c(),attr(r,"class","svelte-9yzcwg"),attr(o,"class","close-btn svelte-9yzcwg"),attr(s,"class","modal-header svelte-9yzcwg"),attr(u,"class","tab-btn svelte-9yzcwg"),toggle_class(u,"active","extension"===e[2]),attr(h,"class","tab-btn svelte-9yzcwg"),toggle_class(h,"active","nsec"===e[2]),attr(l,"class","tabs svelte-9yzcwg"),attr(f,"class","tab-content svelte-9yzcwg"),attr(c,"class","tab-container svelte-9yzcwg"),attr(n,"class","modal svelte-9yzcwg"),toggle_class(n,"dark-theme",e[1]),attr(t,"class","modal-overlay svelte-9yzcwg"),attr(t,"role","button"),attr(t,"tabindex","0")},m(v,w){insert(v,t,w),append(t,n),append(n,s),append(s,r),append(s,i),append(s,o),append(n,a),append(n,c),append(c,l),append(l,u),append(l,d),append(l,h),append(c,p),append(c,f),_.m(f,null),append(f,g),E&&E.m(f,null),append(f,y),k&&k.m(f,null),m||(b=[listen(o,"click",e[7]),listen(u,"click",e[14]),listen(h,"click",e[15]),listen(n,"click",stop_propagation(e[12])),listen(n,"keydown",stop_propagation(e[13])),listen(t,"click",e[7]),listen(t,"keydown",e[17])],m=!0)},p(e,t){4&t&&toggle_class(u,"active","extension"===e[2]),4&t&&toggle_class(h,"active","nsec"===e[2]),w===(w=v(e))&&_?_.p(e,t):(_.d(1),_=w(e),_&&(_.c(),_.m(f,g))),e[5]?E?E.p(e,t):(E=create_if_block_2$2(e),E.c(),E.m(f,y)):E&&(E.d(1),E=null),e[6]?k?k.p(e,t):(k=create_if_block_1$2(e),k.c(),k.m(f,null)):k&&(k.d(1),k=null),2&t&&toggle_class(n,"dark-theme",e[1])},d(e){e&&detach(t),_.d(),E&&E.d(),k&&k.d(),m=!1,run_all(b)}}}function create_else_block$2(e){let t,n,s,r,i,o,a,c,l,u,d=e[4]?"Logging in...":"Log in with nsec";return{c(){t=element("div"),n=element("p"),n.textContent="Enter your nsec (private key) to login. This will be stored securely in your browser.",s=space(),r=element("input"),i=space(),o=element("button"),a=text(d),attr(n,"class","svelte-9yzcwg"),attr(r,"type","password"),attr(r,"placeholder","nsec1..."),r.disabled=e[4],attr(r,"class","nsec-input svelte-9yzcwg"),attr(o,"class","login-nsec-btn svelte-9yzcwg"),o.disabled=c=e[4]||!e[3].trim(),attr(t,"class","nsec-login svelte-9yzcwg")},m(c,d){insert(c,t,d),append(t,n),append(t,s),append(t,r),set_input_value(r,e[3]),append(t,i),append(t,o),append(o,a),l||(u=[listen(r,"input",e[16]),listen(o,"click",e[10])],l=!0)},p(e,t){16&t&&(r.disabled=e[4]),8&t&&r.value!==e[3]&&set_input_value(r,e[3]),16&t&&d!==(d=e[4]?"Logging in...":"Log in with nsec")&&set_data(a,d),24&t&&c!==(c=e[4]||!e[3].trim())&&(o.disabled=c)},d(e){e&&detach(t),l=!1,run_all(u)}}}function create_if_block_3$2(e){let t,n,s,r,i,o,a,c=e[4]?"Connecting...":"Log in using extension";return{c(){t=element("div"),n=element("p"),n.textContent="Login using a NIP-07 compatible browser extension like nos2x or Alby.",s=space(),r=element("button"),i=text(c),attr(n,"class","svelte-9yzcwg"),attr(r,"class","login-extension-btn svelte-9yzcwg"),r.disabled=e[4],attr(t,"class","extension-login svelte-9yzcwg")},m(c,l){insert(c,t,l),append(t,n),append(t,s),append(t,r),append(r,i),o||(a=listen(r,"click",e[9]),o=!0)},p(e,t){16&t&&c!==(c=e[4]?"Connecting...":"Log in using extension")&&set_data(i,c),16&t&&(r.disabled=e[4])},d(e){e&&detach(t),o=!1,a()}}}function create_if_block_2$2(e){let t,n;return{c(){t=element("div"),n=text(e[5]),attr(t,"class","message error-message svelte-9yzcwg")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){32&t&&set_data(n,e[5])},d(e){e&&detach(t)}}}function create_if_block_1$2(e){let t,n;return{c(){t=element("div"),n=text(e[6]),attr(t,"class","message success-message svelte-9yzcwg")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){64&t&&set_data(n,e[6])},d(e){e&&detach(t)}}}function create_fragment$2(e){let t,n,s,r=e[0]&&create_if_block$2(e);return{c(){r&&r.c(),t=empty()},m(i,o){r&&r.m(i,o),insert(i,t,o),n||(s=listen(window_1,"keydown",e[11]),n=!0)},p(e,[n]){e[0]?r?r.p(e,n):(r=create_if_block$2(e),r.c(),r.m(t.parentNode,t)):r&&(r.d(1),r=null)},i:noop,o:noop,d(e){r&&r.d(e),e&&detach(t),n=!1,s()}}}function validateNsec(e){return!!e.startsWith("nsec1")&&!(e.length<60||e.length>70)}function instance$2(e,t,n){const s=createEventDispatcher();let{showModal:r=!1}=t,{isDarkTheme:i=!1}=t,o="extension",a="",c=!1,l="",u="";function d(){n(0,r=!1),n(3,a=""),n(5,l=""),n(6,u=""),s("close")}function h(e){n(2,o=e),n(5,l=""),n(6,u="")}async function p(){n(4,c=!0),n(5,l=""),n(6,u="");try{if(!a.trim())throw new Error("Please enter your nsec");if(!validateNsec(a.trim()))throw new Error('Invalid nsec format. Must start with "nsec1"');const e=new NDKPrivateKeySigner(a.trim()),t=await e.user().then(e=>e.pubkey);localStorage.setItem("nostr_auth_method","nsec"),localStorage.setItem("nostr_pubkey",t),localStorage.setItem("nostr_privkey",a.trim()),n(6,u="Successfully logged in with nsec!"),s("login",{method:"nsec",pubkey:t,privateKey:a.trim(),signer:e}),setTimeout(()=>{d()},1500)}catch(e){n(5,l=e.message)}finally{n(4,c=!1)}}return e.$$set=e=>{"showModal"in e&&n(0,r=e.showModal),"isDarkTheme"in e&&n(1,i=e.isDarkTheme)},[r,i,o,a,c,l,u,d,h,async function(){n(4,c=!0),n(5,l=""),n(6,u="");try{if(!window.nostr)throw new Error("No Nostr extension found. Please install a NIP-07 compatible extension like nos2x or Alby.");const e=await window.nostr.getPublicKey();e&&(localStorage.setItem("nostr_auth_method","extension"),localStorage.setItem("nostr_pubkey",e),n(6,u="Successfully logged in with extension!"),s("login",{method:"extension",pubkey:e,signer:window.nostr}),setTimeout(()=>{d()},1500))}catch(e){n(5,l=e.message)}finally{n(4,c=!1)}},p,function(e){"Escape"===e.key&&d(),"Enter"===e.key&&"nsec"===o&&p()},function(t){bubble.call(this,e,t)},function(t){bubble.call(this,e,t)},()=>h("extension"),()=>h("nsec"),function(){a=this.value,n(3,a)},e=>"Escape"===e.key&&d()]}class LoginModal extends SvelteComponent{constructor(e){super(),init(this,e,instance$2,create_fragment$2,safe_not_equal,{showModal:0,isDarkTheme:1})}}function get_each_context$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_1$1(e,t,n){const s=e.slice();return s[75]=t[n],s}function get_each_context_2$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_3$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_4$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_5$1(e,t,n){const s=e.slice();return s[72]=t[n],s}function get_each_context_6(e,t,n){const s=e.slice();return s[72]=t[n],s}function create_if_block_20$1(e){let t,n,s;return{c(){t=element("div"),n=text(e[3]),attr(t,"class",s="message "+e[4]+" svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,r){8&r[0]&&set_data(n,e[3]),16&r[0]&&s!==(s="message "+e[4]+" svelte-1smaj3x")&&attr(t,"class",s)},d(e){e&&detach(t)}}}function create_if_block_15$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,S,T,A;function R(e,t){return e[5]&&e[5].length>0?create_if_block_18$1:create_else_block_7$1}let N=R(e),C=N(e);function I(e,t){return e[8]&&e[8].length>0?create_if_block_16$1:create_else_block_6$1}let B=I(e),P=B(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Banned Pubkeys",r=space(),i=element("div"),o=element("input"),a=space(),c=element("input"),l=space(),u=element("button"),d=text("Ban Pubkey"),h=space(),p=element("div"),C.c(),f=space(),g=element("div"),y=element("h3"),y.textContent="Allowed Pubkeys",m=space(),b=element("div"),v=element("input"),w=space(),_=element("input"),E=space(),k=element("button"),$=text("Allow Pubkey"),x=space(),S=element("div"),P.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","text"),attr(o,"placeholder","Pubkey (64 hex chars)"),attr(o,"class","svelte-1smaj3x"),attr(c,"type","text"),attr(c,"placeholder","Reason (optional)"),attr(c,"class","svelte-1smaj3x"),u.disabled=e[2],attr(u,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(p,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(y,"class","svelte-1smaj3x"),attr(v,"type","text"),attr(v,"placeholder","Pubkey (64 hex chars)"),attr(v,"class","svelte-1smaj3x"),attr(_,"type","text"),attr(_,"placeholder","Reason (optional)"),attr(_,"class","svelte-1smaj3x"),k.disabled=e[2],attr(k,"class","svelte-1smaj3x"),attr(b,"class","add-form svelte-1smaj3x"),attr(S,"class","list svelte-1smaj3x"),attr(g,"class","section svelte-1smaj3x"),attr(t,"class","pubkeys-section")},m(R,N){insert(R,t,N),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[6]),append(i,a),append(i,c),set_input_value(c,e[7]),append(i,l),append(i,u),append(u,d),append(n,h),append(n,p),C.m(p,null),append(t,f),append(t,g),append(g,y),append(g,m),append(g,b),append(b,v),set_input_value(v,e[9]),append(b,w),append(b,_),set_input_value(_,e[10]),append(b,E),append(b,k),append(k,$),append(g,x),append(g,S),P.m(S,null),T||(A=[listen(o,"input",e[43]),listen(c,"input",e[44]),listen(u,"click",e[25]),listen(v,"input",e[45]),listen(_,"input",e[46]),listen(k,"click",e[26])],T=!0)},p(e,t){64&t[0]&&o.value!==e[6]&&set_input_value(o,e[6]),128&t[0]&&c.value!==e[7]&&set_input_value(c,e[7]),4&t[0]&&(u.disabled=e[2]),N===(N=R(e))&&C?C.p(e,t):(C.d(1),C=N(e),C&&(C.c(),C.m(p,null))),512&t[0]&&v.value!==e[9]&&set_input_value(v,e[9]),1024&t[0]&&_.value!==e[10]&&set_input_value(_,e[10]),4&t[0]&&(k.disabled=e[2]),B===(B=I(e))&&P?P.p(e,t):(P.d(1),P=B(e),P&&(P.c(),P.m(S,null)))},d(e){e&&detach(t),C.d(),P.d(),T=!1,run_all(A)}}}function create_else_block_7$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No banned pubkeys configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_18$1(e){let t,n=e[5],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_6(get_each_context_6(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(32&r[0]){let i;for(n=e[5],i=0;i<n.length;i+=1){const o=get_each_context_6(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_6(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_19$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){32&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_6(e){let t,n,s,r,i,o=e[72].pubkey+"",a=e[72].reason&&create_if_block_19$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","pubkey svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){32&n[0]&&o!==(o=e[72].pubkey+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_19$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_else_block_6$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No allowed pubkeys configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_16$1(e){let t,n=e[8],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_5$1(get_each_context_5$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(256&r[0]){let i;for(n=e[8],i=0;i<n.length;i+=1){const o=get_each_context_5$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_5$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_17$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){256&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_5$1(e){let t,n,s,r,i,o=e[72].pubkey+"",a=e[72].reason&&create_if_block_17$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","pubkey svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){256&n[0]&&o!==(o=e[72].pubkey+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_17$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_if_block_10$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,S,T,A;function R(e,t){return e[11]&&e[11].length>0?create_if_block_13$1:create_else_block_5$1}let N=R(e),C=N(e);let I=function(e){return e[22]&&e[22].length>0?create_if_block_11$1:create_else_block_4$1}(e),B=I(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Banned Events",r=space(),i=element("div"),o=element("input"),a=space(),c=element("input"),l=space(),u=element("button"),d=text("Ban Event"),h=space(),p=element("div"),C.c(),f=space(),g=element("div"),y=element("h3"),y.textContent="Allowed Events",m=space(),b=element("div"),v=element("input"),w=space(),_=element("input"),E=space(),k=element("button"),$=text("Allow Event"),x=space(),S=element("div"),B.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","text"),attr(o,"placeholder","Event ID (64 hex chars)"),attr(o,"class","svelte-1smaj3x"),attr(c,"type","text"),attr(c,"placeholder","Reason (optional)"),attr(c,"class","svelte-1smaj3x"),u.disabled=e[2],attr(u,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(p,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(y,"class","svelte-1smaj3x"),attr(v,"type","text"),attr(v,"placeholder","Event ID (64 hex chars)"),attr(v,"class","svelte-1smaj3x"),attr(_,"type","text"),attr(_,"placeholder","Reason (optional)"),attr(_,"class","svelte-1smaj3x"),k.disabled=e[2],attr(k,"class","svelte-1smaj3x"),attr(b,"class","add-form svelte-1smaj3x"),attr(S,"class","list svelte-1smaj3x"),attr(g,"class","section svelte-1smaj3x"),attr(t,"class","events-section")},m(R,N){insert(R,t,N),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[12]),append(i,a),append(i,c),set_input_value(c,e[13]),append(i,l),append(i,u),append(u,d),append(n,h),append(n,p),C.m(p,null),append(t,f),append(t,g),append(g,y),append(g,m),append(g,b),append(b,v),set_input_value(v,e[14]),append(b,w),append(b,_),set_input_value(_,e[15]),append(b,E),append(b,k),append(k,$),append(g,x),append(g,S),B.m(S,null),T||(A=[listen(o,"input",e[47]),listen(c,"input",e[48]),listen(u,"click",e[27]),listen(v,"input",e[49]),listen(_,"input",e[50]),listen(k,"click",e[28])],T=!0)},p(e,t){4096&t[0]&&o.value!==e[12]&&set_input_value(o,e[12]),8192&t[0]&&c.value!==e[13]&&set_input_value(c,e[13]),4&t[0]&&(u.disabled=e[2]),N===(N=R(e))&&C?C.p(e,t):(C.d(1),C=N(e),C&&(C.c(),C.m(p,null))),16384&t[0]&&v.value!==e[14]&&set_input_value(v,e[14]),32768&t[0]&&_.value!==e[15]&&set_input_value(_,e[15]),4&t[0]&&(k.disabled=e[2]),B.p(e,t)},d(e){e&&detach(t),C.d(),B.d(),T=!1,run_all(A)}}}function create_else_block_5$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No banned events configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_13$1(e){let t,n=e[11],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_4$1(get_each_context_4$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(2048&r[0]){let i;for(n=e[11],i=0;i<n.length;i+=1){const o=get_each_context_4$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_4$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_14$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){2048&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_4$1(e){let t,n,s,r,i,o=e[72].id+"",a=e[72].reason&&create_if_block_14$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","event-id svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){2048&n[0]&&o!==(o=e[72].id+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_14$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_else_block_4$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No allowed events configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_11$1(e){let t,n=e[22],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_3$1(get_each_context_3$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(4194304&r[0]){let i;for(n=e[22],i=0;i<n.length;i+=1){const o=get_each_context_3$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_3$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_12$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p:noop,d(e){e&&detach(t)}}}function create_each_block_3$1(e){let t,n,s,r,i,o=e[72].id+"",a=e[72].reason&&create_if_block_12$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","event-id svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,t){e[72].reason&&a.p(e,t)},d(e){e&&detach(t),a&&a.d()}}}function create_if_block_7$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g;function y(e,t){return e[16]&&e[16].length>0?create_if_block_8$1:create_else_block_3$1}let m=y(e),b=m(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Blocked IPs",r=space(),i=element("div"),o=element("input"),a=space(),c=element("input"),l=space(),u=element("button"),d=text("Block IP"),h=space(),p=element("div"),b.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","text"),attr(o,"placeholder","IP Address"),attr(o,"class","svelte-1smaj3x"),attr(c,"type","text"),attr(c,"placeholder","Reason (optional)"),attr(c,"class","svelte-1smaj3x"),u.disabled=e[2],attr(u,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(p,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","ips-section")},m(y,m){insert(y,t,m),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[17]),append(i,a),append(i,c),set_input_value(c,e[18]),append(i,l),append(i,u),append(u,d),append(n,h),append(n,p),b.m(p,null),f||(g=[listen(o,"input",e[51]),listen(c,"input",e[52]),listen(u,"click",e[29])],f=!0)},p(e,t){131072&t[0]&&o.value!==e[17]&&set_input_value(o,e[17]),262144&t[0]&&c.value!==e[18]&&set_input_value(c,e[18]),4&t[0]&&(u.disabled=e[2]),m===(m=y(e))&&b?b.p(e,t):(b.d(1),b=m(e),b&&(b.c(),b.m(p,null)))},d(e){e&&detach(t),b.d(),f=!1,run_all(g)}}}function create_else_block_3$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No blocked IPs configured.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_8$1(e){let t,n=e[16],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_2$1(get_each_context_2$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(65536&r[0]){let i;for(n=e[16],i=0;i<n.length;i+=1){const o=get_each_context_2$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_2$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_9$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){65536&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block_2$1(e){let t,n,s,r,i,o=e[72].ip+"",a=e[72].reason&&create_if_block_9$1(e);return{c(){t=element("div"),n=element("span"),s=text(o),r=space(),a&&a.c(),i=space(),attr(n,"class","ip svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(t,r),a&&a.m(t,null),append(t,i)},p(e,n){65536&n[0]&&o!==(o=e[72].ip+"")&&set_data(s,o),e[72].reason?a?a.p(e,n):(a=create_if_block_9$1(e),a.c(),a.m(t,i)):a&&(a.d(1),a=null)},d(e){e&&detach(t),a&&a.d()}}}function create_if_block_5$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p;function f(e,t){return e[19]&&e[19].length>0?create_if_block_6$1:create_else_block_2$1}let g=f(e),y=g(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Allowed Event Kinds",r=space(),i=element("div"),o=element("input"),a=space(),c=element("button"),l=text("Allow Kind"),u=space(),d=element("div"),y.c(),attr(s,"class","svelte-1smaj3x"),attr(o,"type","number"),attr(o,"placeholder","Kind number"),attr(o,"class","svelte-1smaj3x"),c.disabled=e[2],attr(c,"class","svelte-1smaj3x"),attr(i,"class","add-form svelte-1smaj3x"),attr(d,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","kinds-section")},m(f,g){insert(f,t,g),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),set_input_value(o,e[20]),append(i,a),append(i,c),append(c,l),append(n,u),append(n,d),y.m(d,null),h||(p=[listen(o,"input",e[53]),listen(c,"click",e[30])],h=!0)},p(e,t){1048576&t[0]&&to_number(o.value)!==e[20]&&set_input_value(o,e[20]),4&t[0]&&(c.disabled=e[2]),g===(g=f(e))&&y?y.p(e,t):(y.d(1),y=g(e),y&&(y.c(),y.m(d,null)))},d(e){e&&detach(t),y.d(),h=!1,run_all(p)}}}function create_else_block_2$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No allowed kinds configured. All kinds are\n allowed by default.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_6$1(e){let t,n=e[19],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_1$1(get_each_context_1$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(524288&r[0]|1&r[1]){let i;for(n=e[19],i=0;i<n.length;i+=1){const o=get_each_context_1$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_1$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_each_block_1$1(e){let t,n,s,r,i,o,a,c,l,u=e[75]+"";function d(){return e[54](e[75])}return{c(){t=element("div"),n=element("span"),s=text("Kind "),r=text(u),i=space(),o=element("button"),o.textContent="Remove",a=space(),attr(n,"class","kind svelte-1smaj3x"),attr(o,"class","remove-btn svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,u){insert(e,t,u),append(t,n),append(n,s),append(n,r),append(t,i),append(t,o),append(t,a),c||(l=listen(o,"click",d),c=!0)},p(t,n){e=t,524288&n[0]&&u!==(u=e[75]+"")&&set_data(r,u)},d(e){e&&detach(t),c=!1,l()}}}function create_if_block_2$1(e){let t,n,s,r,i,o,a,c,l,u;function d(e,t){return e[21]&&e[21].length>0?create_if_block_3$1:create_else_block_1$1}let h=d(e),p=h(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Events Needing Moderation",r=space(),i=element("button"),o=text("Refresh"),a=space(),c=element("div"),p.c(),attr(s,"class","svelte-1smaj3x"),i.disabled=e[2],attr(c,"class","list svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","moderation-section")},m(d,h){insert(d,t,h),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(n,a),append(n,c),p.m(c,null),l||(u=listen(i,"click",e[24]),l=!0)},p(e,t){4&t[0]&&(i.disabled=e[2]),h===(h=d(e))&&p?p.p(e,t):(p.d(1),p=h(e),p&&(p.c(),p.m(c,null)))},d(e){e&&detach(t),p.d(),l=!1,u()}}}function create_else_block_1$1(e){let t;return{c(){t=element("div"),t.innerHTML="<p>No events need moderation at this time.</p>",attr(t,"class","no-items svelte-1smaj3x")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_3$1(e){let t,n=e[21],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block$1(get_each_context$1(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(2097152&r[0]|12&r[1]){let i;for(n=e[21],i=0;i<n.length;i+=1){const o=get_each_context$1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block$1(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_4$1(e){let t,n,s=e[72].reason+"";return{c(){t=element("span"),n=text(s),attr(t,"class","reason svelte-1smaj3x")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){2097152&t[0]&&s!==(s=e[72].reason+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_each_block$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p=e[72].id+"",f=e[72].reason&&create_if_block_4$1(e);function g(){return e[55](e[72])}function y(){return e[56](e[72])}return{c(){t=element("div"),n=element("span"),s=text(p),r=space(),f&&f.c(),i=space(),o=element("div"),a=element("button"),a.textContent="Allow",c=space(),l=element("button"),l.textContent="Ban",u=space(),attr(n,"class","event-id svelte-1smaj3x"),attr(a,"class","svelte-1smaj3x"),attr(l,"class","svelte-1smaj3x"),attr(o,"class","actions svelte-1smaj3x"),attr(t,"class","list-item svelte-1smaj3x")},m(e,p){insert(e,t,p),append(t,n),append(n,s),append(t,r),f&&f.m(t,null),append(t,i),append(t,o),append(o,a),append(o,c),append(o,l),append(t,u),d||(h=[listen(a,"click",g),listen(l,"click",y)],d=!0)},p(n,r){e=n,2097152&r[0]&&p!==(p=e[72].id+"")&&set_data(s,p),e[72].reason?f?f.p(e,r):(f=create_if_block_4$1(e),f.c(),f.m(t,i)):f&&(f.d(1),f=null)},d(e){e&&detach(t),f&&f.d(),d=!1,run_all(h)}}}function create_if_block$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,S,T,A;function R(e,t){return e[2]?create_if_block_1$1:create_else_block$1}let N=R(e),C=N(e);return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Relay Configuration",r=space(),i=element("div"),o=element("button"),a=text("🔄 Refresh from Relay Info"),c=space(),l=element("div"),u=element("div"),d=element("label"),d.textContent="Relay Name",h=space(),p=element("input"),f=space(),g=element("div"),y=element("label"),y.textContent="Relay Description",m=space(),b=element("textarea"),v=space(),w=element("div"),_=element("label"),_.textContent="Relay Icon URL",E=space(),k=element("input"),$=space(),x=element("div"),S=element("button"),C.c(),attr(s,"class","svelte-1smaj3x"),o.disabled=e[2],attr(o,"class","refresh-btn svelte-1smaj3x"),attr(i,"class","config-actions svelte-1smaj3x"),attr(d,"class","svelte-1smaj3x"),attr(p,"type","text"),attr(p,"placeholder","Enter relay name"),attr(p,"class","svelte-1smaj3x"),attr(u,"class","form-group svelte-1smaj3x"),attr(y,"class","svelte-1smaj3x"),attr(b,"placeholder","Enter relay description"),attr(b,"class","svelte-1smaj3x"),attr(g,"class","form-group svelte-1smaj3x"),attr(_,"class","svelte-1smaj3x"),attr(k,"type","url"),attr(k,"placeholder","Enter icon URL"),attr(k,"class","svelte-1smaj3x"),attr(w,"class","form-group svelte-1smaj3x"),S.disabled=e[2],attr(S,"class","update-all-btn svelte-1smaj3x"),attr(x,"class","config-update-section svelte-1smaj3x"),attr(l,"class","config-form svelte-1smaj3x"),attr(n,"class","section svelte-1smaj3x"),attr(t,"class","relay-section")},m(R,N){insert(R,t,N),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(n,c),append(n,l),append(l,u),append(u,d),append(u,h),append(u,p),set_input_value(p,e[0].relay_name),append(l,f),append(l,g),append(g,y),append(g,m),append(g,b),set_input_value(b,e[0].relay_description),append(l,v),append(l,w),append(w,_),append(w,E),append(w,k),set_input_value(k,e[0].relay_icon),append(l,$),append(l,x),append(x,S),C.m(S,null),T||(A=[listen(o,"click",e[23]),listen(p,"input",e[57]),listen(b,"input",e[58]),listen(k,"input",e[59]),listen(S,"click",e[32])],T=!0)},p(e,t){4&t[0]&&(o.disabled=e[2]),1&t[0]&&p.value!==e[0].relay_name&&set_input_value(p,e[0].relay_name),1&t[0]&&set_input_value(b,e[0].relay_description),1&t[0]&&k.value!==e[0].relay_icon&&set_input_value(k,e[0].relay_icon),N!==(N=R(e))&&(C.d(1),C=N(e),C&&(C.c(),C.m(S,null))),4&t[0]&&(S.disabled=e[2])},d(e){e&&detach(t),C.d(),T=!1,run_all(A)}}}function create_else_block$1(e){let t;return{c(){t=text("💾 Update Configuration")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_1$1(e){let t;return{c(){t=text("⏳ Updating...")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_fragment$1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,S,T,A,R,N,C,I,B,P,D,L,F,O=e[3]&&create_if_block_20$1(e),U="pubkeys"===e[1]&&create_if_block_15$1(e),z="events"===e[1]&&create_if_block_10$1(e),M="ips"===e[1]&&create_if_block_7$1(e),K="kinds"===e[1]&&create_if_block_5$1(e),H="moderation"===e[1]&&create_if_block_2$1(e),j="relay"===e[1]&&create_if_block$1(e);return{c(){t=element("div"),n=element("div"),n.innerHTML='<h2 class="svelte-1smaj3x">Managed ACL Configuration</h2> \n <p class="svelte-1smaj3x">Configure access control using NIP-86 management API</p> \n <div class="owner-only-notice svelte-1smaj3x"><strong>Owner Only:</strong> This interface is restricted to relay owners\n only.</div>',s=space(),O&&O.c(),r=space(),i=element("div"),o=element("button"),a=text("Pubkeys"),l=space(),u=element("button"),d=text("Events"),p=space(),f=element("button"),g=text("IPs"),m=space(),b=element("button"),v=text("Kinds"),_=space(),E=element("button"),k=text("Moderation"),x=space(),S=element("button"),T=text("Relay Config"),R=space(),N=element("div"),U&&U.c(),C=space(),z&&z.c(),I=space(),M&&M.c(),B=space(),K&&K.c(),P=space(),H&&H.c(),D=space(),j&&j.c(),attr(n,"class","header svelte-1smaj3x"),attr(o,"class",c="tab "+("pubkeys"===e[1]?"active":"")+" svelte-1smaj3x"),attr(u,"class",h="tab "+("events"===e[1]?"active":"")+" svelte-1smaj3x"),attr(f,"class",y="tab "+("ips"===e[1]?"active":"")+" svelte-1smaj3x"),attr(b,"class",w="tab "+("kinds"===e[1]?"active":"")+" svelte-1smaj3x"),attr(E,"class",$="tab "+("moderation"===e[1]?"active":"")+" svelte-1smaj3x"),attr(S,"class",A="tab "+("relay"===e[1]?"active":"")+" svelte-1smaj3x"),attr(i,"class","tabs svelte-1smaj3x"),attr(N,"class","tab-content svelte-1smaj3x")},m(c,h){insert(c,t,h),append(t,n),append(t,s),O&&O.m(t,null),append(t,r),append(t,i),append(i,o),append(o,a),append(i,l),append(i,u),append(u,d),append(i,p),append(i,f),append(f,g),append(i,m),append(i,b),append(b,v),append(i,_),append(i,E),append(E,k),append(i,x),append(i,S),append(S,T),append(t,R),append(t,N),U&&U.m(N,null),append(N,C),z&&z.m(N,null),append(N,I),M&&M.m(N,null),append(N,B),K&&K.m(N,null),append(N,P),H&&H.m(N,null),append(N,D),j&&j.m(N,null),L||(F=[listen(o,"click",e[37]),listen(u,"click",e[38]),listen(f,"click",e[39]),listen(b,"click",e[40]),listen(E,"click",e[41]),listen(S,"click",e[42])],L=!0)},p(e,n){e[3]?O?O.p(e,n):(O=create_if_block_20$1(e),O.c(),O.m(t,r)):O&&(O.d(1),O=null),2&n[0]&&c!==(c="tab "+("pubkeys"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(o,"class",c),2&n[0]&&h!==(h="tab "+("events"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(u,"class",h),2&n[0]&&y!==(y="tab "+("ips"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(f,"class",y),2&n[0]&&w!==(w="tab "+("kinds"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(b,"class",w),2&n[0]&&$!==($="tab "+("moderation"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(E,"class",$),2&n[0]&&A!==(A="tab "+("relay"===e[1]?"active":"")+" svelte-1smaj3x")&&attr(S,"class",A),"pubkeys"===e[1]?U?U.p(e,n):(U=create_if_block_15$1(e),U.c(),U.m(N,C)):U&&(U.d(1),U=null),"events"===e[1]?z?z.p(e,n):(z=create_if_block_10$1(e),z.c(),z.m(N,I)):z&&(z.d(1),z=null),"ips"===e[1]?M?M.p(e,n):(M=create_if_block_7$1(e),M.c(),M.m(N,B)):M&&(M.d(1),M=null),"kinds"===e[1]?K?K.p(e,n):(K=create_if_block_5$1(e),K.c(),K.m(N,P)):K&&(K.d(1),K=null),"moderation"===e[1]?H?H.p(e,n):(H=create_if_block_2$1(e),H.c(),H.m(N,D)):H&&(H.d(1),H=null),"relay"===e[1]?j?j.p(e,n):(j=create_if_block$1(e),j.c(),j.m(N,null)):j&&(j.d(1),j=null)},i:noop,o:noop,d(e){e&&detach(t),O&&O.d(),U&&U.d(),z&&z.d(),M&&M.d(),K&&K.d(),H&&H.d(),j&&j.d(),L=!1,run_all(F)}}}function instance$1(e,t,n){let{userSigner:s}=t,{userPubkey:r}=t,i="pubkeys",o=!1,a="",c="info",l=[],u="",d="",h=[],p="",f="",g=[],y="",m="",b="",v="",w=[],_="",E="",k=[],$="",x=[],S={relay_name:"",relay_description:"",relay_icon:""};async function T(){try{n(2,o=!0),console.log("Fetching relay info from /");const e=await fetch(window.location.origin+"/",{headers:{Accept:"application/nostr+json"}});if(console.log("Response status:",e.status),console.log("Response headers:",e.headers),e.ok){const t=await e.json();console.log("Raw relay info:",t),n(0,S={relay_name:t.name||"",relay_description:t.description||"",relay_icon:t.icon||""}),console.log("Updated relayConfig:",S),console.log("Loaded relay info:",t),n(3,a="Relay configuration loaded successfully"),n(4,c="success")}else console.error("Failed to fetch relay info, status:",e.status),n(3,a=`Failed to fetch relay info: ${e.status}`),n(4,c="error")}catch(e){console.error("Failed to fetch relay info:",e),n(3,a=`Failed to fetch relay info: ${e.message}`),n(4,c="error")}finally{n(2,o=!1)}}async function A(e,t=[]){try{n(2,o=!0),n(3,a="");const i={method:e,params:t},c=await async function(e,t){if(!s)throw new Error("No signer available for authentication. Please log in with a Nostr extension.");if(!r)throw new Error("No user pubkey available for authentication.");const n=window.location.origin+t,i={kind:27235,created_at:Math.floor(Date.now()/1e3),tags:[["u",n],["method",e]],content:"",pubkey:r},o=await s.signEvent(i),a=JSON.stringify(o);return`Nostr ${btoa(a)}`}("POST","/api/nip86"),l=await fetch("/api/nip86",{method:"POST",headers:{"Content-Type":"application/nostr+json+rpc",Authorization:c},body:JSON.stringify(i)});if(!l.ok)throw new Error(`HTTP ${l.status}: ${l.statusText}`);const u=await l.json();if(u.error)throw new Error(u.error);return u.result}catch(e){throw console.error("NIP-86 API error:",e),n(3,a=e.message),n(4,c="error"),e}finally{n(2,o=!1)}}async function R(){try{n(5,l=await A("listbannedpubkeys"))}catch(e){console.error("Failed to load banned pubkeys:",e)}}async function N(){try{n(8,h=await A("listallowedpubkeys"))}catch(e){console.error("Failed to load allowed pubkeys:",e)}}async function C(){try{n(11,g=await A("listbannedevents"))}catch(e){console.error("Failed to load banned events:",e)}}async function I(){try{n(16,w=await A("listblockedips"))}catch(e){console.error("Failed to load blocked IPs:",e)}}async function B(){try{n(19,k=await A("listallowedkinds"))}catch(e){console.error("Failed to load allowed kinds:",e)}}async function P(){try{n(2,o=!0),n(21,x=await A("listeventsneedingmoderation")),console.log("Loaded events needing moderation:",x)}catch(e){console.error("Failed to load events needing moderation:",e),n(3,a=`Failed to load moderation events: ${e.message}`),n(4,c="error"),n(21,x=[])}finally{n(2,o=!1)}}async function D(e){try{await A("disallowkind",[e]),n(3,a="Kind disallowed successfully"),n(4,c="success"),await B()}catch(e){console.error("Failed to disallow kind:",e)}}async function L(e){try{await A("allowevent",[e,"Approved from moderation queue"]),n(3,a="Event allowed successfully"),n(4,c="success"),await P()}catch(e){console.error("Failed to allow event from moderation:",e)}}async function F(e){try{await A("banevent",[e,"Banned from moderation queue"]),n(3,a="Event banned successfully"),n(4,c="success"),await P()}catch(e){console.error("Failed to ban event from moderation:",e)}}onMount(()=>{setTimeout(()=>{T()},100)}),async function(){await Promise.all([R(),N(),C(),I(),B()])}();return e.$$set=e=>{"userSigner"in e&&n(35,s=e.userSigner),"userPubkey"in e&&n(36,r=e.userPubkey)},e.$$.update=()=>{1&e.$$.dirty[0]&&console.log("relayConfig changed:",S)},[S,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,[],T,P,async function(){if(u)try{await A("banpubkey",[u,d]),n(3,a="Pubkey banned successfully"),n(4,c="success"),n(6,u=""),n(7,d=""),await R()}catch(e){console.error("Failed to ban pubkey:",e)}},async function(){if(p)try{await A("allowpubkey",[p,f]),n(3,a="Pubkey allowed successfully"),n(4,c="success"),n(9,p=""),n(10,f=""),await N()}catch(e){console.error("Failed to allow pubkey:",e)}},async function(){if(y)try{await A("banevent",[y,m]),n(3,a="Event banned successfully"),n(4,c="success"),n(12,y=""),n(13,m=""),await C()}catch(e){console.error("Failed to ban event:",e)}},async function(){if(b)try{await A("allowevent",[b,v]),n(3,a="Event allowed successfully"),n(4,c="success"),n(14,b=""),n(15,v="")}catch(e){console.error("Failed to allow event:",e)}},async function(){if(_)try{await A("blockip",[_,E]),n(3,a="IP blocked successfully"),n(4,c="success"),n(17,_=""),n(18,E=""),await I()}catch(e){console.error("Failed to block IP:",e)}},async function(){if(!$)return;const e=parseInt($);if(isNaN(e))return n(3,a="Invalid kind number"),void n(4,c="error");try{await A("allowkind",[e]),n(3,a="Kind allowed successfully"),n(4,c="success"),n(20,$=""),await B()}catch(e){console.error("Failed to allow kind:",e)}},D,async function(){try{n(2,o=!0),n(3,a="");const e=[];if(S.relay_name&&e.push(A("changerelayname",[S.relay_name])),S.relay_description&&e.push(A("changerelaydescription",[S.relay_description])),S.relay_icon&&e.push(A("changerelayicon",[S.relay_icon])),0===e.length)return n(3,a="No changes to update"),void n(4,c="info");await Promise.all(e),n(3,a="Relay configuration updated successfully"),n(4,c="success"),await T()}catch(e){console.error("Failed to update relay configuration:",e),n(3,a=`Failed to update relay configuration: ${e.message}`),n(4,c="error")}finally{n(2,o=!1)}},L,F,s,r,()=>n(1,i="pubkeys"),()=>n(1,i="events"),()=>n(1,i="ips"),()=>n(1,i="kinds"),()=>{n(1,i="moderation"),x&&0!==x.length||P()},()=>n(1,i="relay"),function(){u=this.value,n(6,u)},function(){d=this.value,n(7,d)},function(){p=this.value,n(9,p)},function(){f=this.value,n(10,f)},function(){y=this.value,n(12,y)},function(){m=this.value,n(13,m)},function(){b=this.value,n(14,b)},function(){v=this.value,n(15,v)},function(){_=this.value,n(17,_)},function(){E=this.value,n(18,E)},function(){$=to_number(this.value),n(20,$)},e=>D(e),e=>L(e.id),e=>F(e.id),function(){S.relay_name=this.value,n(0,S)},function(){S.relay_description=this.value,n(0,S)},function(){S.relay_icon=this.value,n(0,S)}]}class ManagedACL extends SvelteComponent{constructor(e){super(),init(this,e,instance$1,create_fragment$1,safe_not_equal,{userSigner:35,userPubkey:36},null,[-1,-1,-1])}}const DEFAULT_RELAYS=[`wss://${window.location.host}/`];class NostrClient{constructor(){this.ndk=new NDK({explicitRelayUrls:DEFAULT_RELAYS}),this.isConnected=!1}async connect(){console.log("Starting NDK connection to",DEFAULT_RELAYS.length,"relays...");try{await this.ndk.connect(),this.isConnected=!0,console.log("✓ NDK successfully connected to relays"),await new Promise(e=>setTimeout(e,1e3))}catch(e){throw console.error("✗ NDK connection failed:",e),e}}async connectToRelay(e){console.log(`Adding relay to NDK: ${e}`);try{return DEFAULT_RELAYS.push(e),await this.connect(),console.log(`✓ Successfully added relay ${e}`),!0}catch(t){return console.error(`✗ Failed to add relay ${e}:`,t),!1}}subscribe(e,t){console.log("Creating NDK subscription with filters:",e);const n=this.ndk.subscribe(e,{closeOnEose:!0});return n.on("event",e=>{console.log("Event received via NDK:",e),t(e.rawEvent())}),n.on("eose",()=>{console.log("EOSE received via NDK"),window.dispatchEvent(new CustomEvent("nostr-eose",{detail:{subscriptionId:n.id}}))}),n.id}unsubscribe(e){console.log(`Closing NDK subscription: ${e}`)}disconnect(){console.log("Disconnecting NDK"),this.ndk&&"function"==typeof this.ndk.disconnect&&this.ndk.disconnect(),this.isConnected=!1}async publish(e){console.log("Publishing event via NDK:",e);try{const t=new NDKEvent(this.ndk,e);return await t.publish(),console.log("✓ Event published successfully via NDK"),{success:!0,okCount:1,errorCount:0}}catch(e){throw console.error("✗ Failed to publish event via NDK:",e),e}}getNDK(){return this.ndk}getSigner(){return this.ndk.signer}setSigner(e){this.ndk.signer=e}}const nostrClient=new NostrClient,DB_NAME="nostrCache",DB_VERSION=1,STORE_EVENTS="events";function openDB(){return new Promise((e,t)=>{try{const n=indexedDB.open(DB_NAME,DB_VERSION);n.onupgradeneeded=()=>{const e=n.result;if(!e.objectStoreNames.contains(STORE_EVENTS)){const t=e.createObjectStore(STORE_EVENTS,{keyPath:"id"});t.createIndex("byKindAuthor",["kind","pubkey"],{unique:!1}),t.createIndex("byKindAuthorCreated",["kind","pubkey","created_at"],{unique:!1})}},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}catch(e){t(e)}})}async function getLatestProfileEvent(e){try{const t=await openDB();return await new Promise((n,s)=>{const r=t.transaction(STORE_EVENTS,"readonly").objectStore(STORE_EVENTS).index("byKindAuthorCreated"),i=IDBKeyRange.bound([0,e,-1/0],[0,e,1/0]),o=r.openCursor(i,"prev");o.onsuccess=()=>{const e=o.result;n(e?e.value:null)},o.onerror=()=>s(o.error)})}catch(e){return console.warn("IDB getLatestProfileEvent failed",e),null}}async function putEvent(e){try{const t=await openDB();await new Promise((n,s)=>{const r=t.transaction(STORE_EVENTS,"readwrite");r.oncomplete=()=>n(),r.onerror=()=>s(r.error),r.objectStore(STORE_EVENTS).put(e)})}catch(e){console.warn("IDB putEvent failed",e)}}function parseProfileFromEvent(e){try{const t=JSON.parse(e.content||"{}");return{name:t.name||t.display_name||"",picture:t.picture||"",banner:t.banner||"",about:t.about||"",nip05:t.nip05||"",lud16:t.lud16||t.lud06||""}}catch(e){return{name:"",picture:"",banner:"",about:"",nip05:"",lud16:""}}}async function fetchUserProfile(e){console.log(`Starting profile fetch for pubkey: ${e}`);try{const t=await getLatestProfileEvent(e);if(t){console.log("Using cached profile event");return parseProfileFromEvent(t)}}catch(e){console.warn("Failed to load cached profile",e)}try{const t=nostrClient.getNDK().getUser({hexpubkey:e}),n=await t.fetchProfile();if(n){console.log("Profile fetched via NDK:",n),await putEvent(n.rawEvent());const t=parseProfileFromEvent(n.rawEvent());try{"undefined"!=typeof window&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("profile-updated",{detail:{pubkey:e,profile:t,event:n.rawEvent()}}))}catch(e){console.warn("Failed to dispatch profile-updated event",e)}return t}throw new Error("No profile found")}catch(e){throw console.error("Failed to fetch profile via NDK:",e),e}}async function fetchEvents(e,t={}){console.log("Starting event fetch with filters:",e);const{timeout:n=3e4,limit:s=null}=t;try{const t=nostrClient.getNDK(),r={...e};s&&(r.limit=s),console.log("Fetching events via NDK with filters:",r);const i=await t.fetchEvents(r,{timeout:n});console.log(`Fetched ${i.size} events via NDK`);return Array.from(i).map(e=>e.rawEvent())}catch(e){throw console.error("Failed to fetch events via NDK:",e),e}}async function fetchAllEvents(e={}){const{limit:t=100,since:n=null,until:s=null,authors:r=null}=e,i={};n&&(i.since=n),s&&(i.until=s),r&&(i.authors=r);return await fetchEvents(i,{limit:t,timeout:3e4})}async function searchEvents(e,t={}){const{limit:n=100,since:s=null,until:r=null,kinds:i=null}=t,o={search:e};s&&(o.since=s),r&&(o.until=r),i&&(o.kinds=i);return await fetchEvents(o,{limit:n,timeout:3e4})}async function fetchEventById(e,t={}){const{timeout:n=1e4,relays:s=null}=t;console.log(`Fetching event by ID: ${e}`);try{const t=nostrClient.getNDK(),s={ids:[e]};console.log("Fetching event via NDK with filters:",s);const r=await t.fetchEvents(s,{timeout:n});console.log(`Fetched ${r.size} events via NDK`);const i=Array.from(r).map(e=>e.rawEvent());return i.length>0?i[0]:null}catch(e){throw console.error("Failed to fetch event by ID via NDK:",e),e}}async function fetchDeleteEventsByTarget(e,t={}){const{timeout:n=1e4}=t;console.log(`Fetching delete events for target: ${e}`);try{const t=nostrClient.getNDK(),s={kinds:[5],"#e":[e]};console.log("Fetching delete events via NDK with filters:",s);const r=await t.fetchEvents(s,{timeout:n});console.log(`Fetched ${r.size} delete events via NDK`);return Array.from(r).map(e=>e.rawEvent())}catch(e){throw console.error("Failed to fetch delete events via NDK:",e),e}}async function initializeNostrClient(){await nostrClient.connect()}class NostrWebSocketAuth{constructor(e,t,n){this.relayUrl=e,this.userSigner=t,this.userPubkey=n,this.ws=null,this.challenge=null,this.isAuthenticated=!1,this.authPromise=null}async connect(){return new Promise((e,t)=>{this.ws=new WebSocket(this.relayUrl),this.ws.onopen=()=>{console.log("WebSocket connected to relay:",this.relayUrl),e()},this.ws.onmessage=async e=>{try{const t=JSON.parse(e.data);await this.handleMessage(t)}catch(e){console.error("Error parsing relay message:",e)}},this.ws.onerror=e=>{console.error("WebSocket error:",e),t(new Error("Failed to connect to relay"))},this.ws.onclose=()=>{console.log("WebSocket connection closed"),this.isAuthenticated=!1,this.challenge=null},setTimeout(()=>{this.ws.readyState!==WebSocket.OPEN&&t(new Error("Connection timeout"))},1e4)})}async handleMessage(e){const[t,...n]=e;switch(t){case"AUTH":this.challenge=n[0],console.log("Received AUTH challenge:",this.challenge),await this.authenticate();break;case"OK":const[e,s,r]=n;e&&s?(console.log("Authentication successful for event:",e),this.isAuthenticated=!0,this.authPromise&&(this.authPromise.resolve(),this.authPromise=null)):e&&!s&&(console.error("Authentication failed:",r),this.authPromise&&(this.authPromise.reject(new Error(r||"Authentication failed")),this.authPromise=null));break;case"NOTICE":console.log("Relay notice:",n[0]);break;default:console.log("Unhandled message type:",t,n)}}async authenticate(){if(!this.challenge)throw new Error("No challenge received from relay");if(!this.userSigner)throw new Error("No signer available for authentication");try{const e={kind:22242,created_at:Math.floor(Date.now()/1e3),tags:[["relay",this.relayUrl],["challenge",this.challenge]],content:"",pubkey:this.userPubkey},t=["AUTH",await this.userSigner.signEvent(e)];return this.ws.send(JSON.stringify(t)),console.log("Sent authentication event to relay"),new Promise((e,t)=>{this.authPromise={resolve:e,reject:t},setTimeout(()=>{this.authPromise&&(this.authPromise.reject(new Error("Authentication timeout")),this.authPromise=null)},1e4)})}catch(e){throw console.error("Authentication error:",e),e}}async publishEvent(e){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");return new Promise((t,n)=>{const s=["EVENT",e];this.ws.send(JSON.stringify(s));const r=this.ws.onmessage,i=setTimeout(()=>{this.ws.onmessage=r,n(new Error("Publish timeout"))},15e3);this.ws.onmessage=async s=>{try{const o=JSON.parse(s.data),[a,c,l,u]=o;if("OK"===a&&c===e.id)if(clearTimeout(i),this.ws.onmessage=r,l)console.log("Event published successfully:",c),t({success:!0,eventId:c,reason:u});else{if(console.error("Event publish failed:",u),u&&u.includes("auth-required")){console.log("Authentication required, attempting to authenticate...");try{await this.authenticate();const t=["EVENT",e];return void this.ws.send(JSON.stringify(t))}catch(e){return void n(new Error(`Authentication failed: ${e.message}`))}}n(new Error(`Publish failed: ${u}`))}else await this.handleMessage(o)}catch(e){clearTimeout(i),this.ws.onmessage=r,n(e)}}})}close(){this.ws&&(this.ws.close(),this.ws=null),this.isAuthenticated=!1,this.challenge=null}getAuthenticated(){return this.isAuthenticated}}async function publishEventWithAuth(e,t,n,s){const r=new NostrWebSocketAuth(e,n,s);try{await r.connect();return await r.publishEvent(t)}finally{r.close()}}function get_each_context_3(e,t,n){const s=e.slice();return s[138]=t[n],s}function get_each_context_4(e,t,n){const s=e.slice();return s[129]=t[n],s}function get_each_context_2(e,t,n){const s=e.slice();return s[135]=t[n],s}function get_each_context(e,t,n){const s=e.slice();return s[129]=t[n],s}function get_each_context_1(e,t,n){const s=e.slice();return s[132]=t[n],s}function get_each_context_5(e,t,n){const s=e.slice();return s[143]=t[n],s}function create_else_block_12(e){let t,n,s,r=e[1]&&e[4]&&create_if_block_49(e);return{c(){t=element("div"),n=element("span"),s=text("ORLY? dashboard\n "),r&&r.c(),attr(n,"class","app-title svelte-ybzzp3"),attr(t,"class","header-title svelte-ybzzp3")},m(e,i){insert(e,t,i),append(t,n),append(n,s),r&&r.m(n,null)},p(e,t){e[1]&&e[4]?r?r.p(e,t):(r=create_if_block_49(e),r.c(),r.m(n,null)):r&&(r.d(1),r=null)},d(e){e&&detach(t),r&&r.d()}}}function create_if_block_48(e){let t,n,s,r;return{c(){t=element("div"),n=element("input"),attr(n,"type","text"),attr(n,"class","search-input svelte-ybzzp3"),attr(n,"placeholder","Search..."),attr(t,"class","search-input-container svelte-ybzzp3")},m(i,o){insert(i,t,o),append(t,n),set_input_value(n,e[15]),s||(r=[listen(n,"input",e[72]),listen(n,"keydown",e[53])],s=!0)},p(e,t){32768&t[0]&&n.value!==e[15]&&set_input_value(n,e[15])},d(e){e&&detach(t),s=!1,run_all(r)}}}function create_if_block_49(e){let t,n;return{c(){t=element("span"),n=text(e[4]),attr(t,"class","permission-badge svelte-ybzzp3")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){16&t[0]&&set_data(n,e[4])},d(e){e&&detach(t)}}}function create_else_block_11(e){let t,n,s;return{c(){t=element("button"),t.textContent="Log in",attr(t,"class","login-btn svelte-ybzzp3")},m(r,i){insert(r,t,i),n||(s=listen(t,"click",e[46]),n=!0)},p:noop,d(e){e&&detach(t),n=!1,s()}}}function create_if_block_46(e){let t,n,s,r,i,o,a,c=(e[3]?.name||e[2].slice(0,8)+"...")+"";function l(e,t){return e[3]?.picture?create_if_block_47:create_else_block_10}let u=l(e),d=u(e);return{c(){t=element("div"),n=element("button"),d.c(),s=space(),r=element("span"),i=text(c),attr(r,"class","user-name svelte-ybzzp3"),attr(n,"class","user-profile-btn svelte-ybzzp3"),attr(t,"class","user-info svelte-ybzzp3")},m(c,l){insert(c,t,l),append(t,n),d.m(n,null),append(n,s),append(n,r),append(r,i),o||(a=listen(n,"click",e[50]),o=!0)},p(e,t){u===(u=l(e))&&d?d.p(e,t):(d.d(1),d=u(e),d&&(d.c(),d.m(n,s))),12&t[0]&&c!==(c=(e[3]?.name||e[2].slice(0,8)+"...")+"")&&set_data(i,c)},d(e){e&&detach(t),d.d(),o=!1,a()}}}function create_else_block_10(e){let t;return{c(){t=element("div"),t.textContent="👤",attr(t,"class","user-avatar-placeholder svelte-ybzzp3")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_47(e){let t,n;return{c(){t=element("img"),src_url_equal(t.src,n=e[3].picture)||attr(t,"src",n),attr(t,"alt","User avatar"),attr(t,"class","user-avatar svelte-ybzzp3")},m(e,n){insert(e,t,n)},p(e,s){8&s[0]&&!src_url_equal(t.src,n=e[3].picture)&&attr(t,"src",n)},d(e){e&&detach(t)}}}function create_if_block_45(e){let t,n,s;function r(){return e[73](e[143])}function i(...t){return e[74](e[143],...t)}return{c(){t=element("span"),t.textContent="✕",attr(t,"class","tab-close-icon svelte-ybzzp3"),attr(t,"role","button"),attr(t,"tabindex","0")},m(e,o){insert(e,t,o),n||(s=[listen(t,"click",stop_propagation(r)),listen(t,"keydown",i)],n=!0)},p(t,n){e=t},d(e){e&&detach(t),n=!1,run_all(s)}}}function create_each_block_5(e){let t,n,s,r,i,o,a,c,l,u,d=e[143].icon+"",h=e[143].label+"",p=e[143].isSearchTab&&create_if_block_45(e);function f(){return e[75](e[143])}return{c(){t=element("button"),n=element("span"),s=text(d),r=space(),i=element("span"),o=text(h),a=space(),p&&p.c(),c=space(),attr(n,"class","tab-icon svelte-ybzzp3"),attr(i,"class","tab-label svelte-ybzzp3"),attr(t,"class","tab svelte-ybzzp3"),toggle_class(t,"active",e[5]===e[143].id)},m(e,d){insert(e,t,d),append(t,n),append(n,s),append(t,r),append(t,i),append(i,o),append(t,a),p&&p.m(t,null),append(t,c),l||(u=listen(t,"click",f),l=!0)},p(n,r){e=n,1024&r[0]&&d!==(d=e[143].icon+"")&&set_data(s,d),1024&r[0]&&h!==(h=e[143].label+"")&&set_data(o,h),e[143].isSearchTab?p?p.p(e,r):(p=create_if_block_45(e),p.c(),p.m(t,c)):p&&(p.d(1),p=null),1056&r[0]&&toggle_class(t,"active",e[5]===e[143].id)},d(e){e&&detach(t),p&&p.d(),l=!1,u()}}}function create_else_block_8(e){let t;function n(e,t){return e[1]?create_if_block_44:create_else_block_9}let s=n(e),r=s(e);return{c(){t=element("div"),r.c(),attr(t,"class","welcome-message svelte-ybzzp3")},m(e,n){insert(e,t,n),r.m(t,null)},p(e,i){s===(s=n(e))&&r?r.p(e,i):(r.d(1),r=s(e),r&&(r.c(),r.m(t,null)))},i:noop,o:noop,d(e){e&&detach(t),r.d()}}}function create_if_block_36(e){let t,n=e[6],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_3(get_each_context_3(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(1073873012&r[0]|50331659&r[1]){let i;for(n=e[6],i=0;i<n.length;i+=1){const o=get_each_context_3(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_3(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},i:noop,o:noop,d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_29(e){let t,n,s;function r(e,t){return e[1]&&"owner"===e[4]?create_if_block_30:e[1]?create_if_block_35:create_else_block_7}let i=r(e),o=i(e);return{c(){t=element("div"),n=element("h2"),n.textContent="Sprocket Script Management",s=space(),o.c(),attr(t,"class","sprocket-view svelte-ybzzp3")},m(e,r){insert(e,t,r),append(t,n),append(t,s),o.m(t,null)},p(e,n){i===(i=r(e))&&o?o.p(e,n):(o.d(1),o=i(e),o&&(o.c(),o.m(t,null)))},i:noop,o:noop,d(e){e&&detach(t),o.d()}}}function create_if_block_26(e){let t,n,s,r;const i=[create_if_block_27,create_if_block_28,create_else_block_6],o=[];function a(e,t){return"managed"!==e[9]?0:e[1]&&"owner"===e[4]?1:2}return n=a(e),s=o[n]=i[n](e),{c(){t=element("div"),s.c(),attr(t,"class","managed-acl-view svelte-ybzzp3")},m(e,s){insert(e,t,s),o[n].m(t,null),r=!0},p(e,r){let c=n;n=a(e),n===c?o[n].p(e,r):(group_outros(),transition_out(o[c],1,1,()=>{o[c]=null}),check_outros(),s=o[n],s?s.p(e,r):(s=o[n]=i[n](e),s.c()),transition_in(s,1),s.m(t,null))},i(e){r||(transition_in(s),r=!0)},o(e){transition_out(s),r=!1},d(e){e&&detach(t),o[n].d()}}}function create_if_block_25(e){let t,n,s,r,i,o,a,c,l,u,d,h;return{c(){t=element("div"),n=element("div"),s=element("button"),s.textContent="Reformat",r=space(),i=element("button"),i.textContent="Sign",o=space(),a=element("button"),a.textContent="Publish",c=space(),l=element("div"),u=element("textarea"),attr(s,"class","compose-btn reformat-btn svelte-ybzzp3"),attr(i,"class","compose-btn sign-btn svelte-ybzzp3"),attr(a,"class","compose-btn publish-btn svelte-ybzzp3"),attr(n,"class","compose-header svelte-ybzzp3"),attr(u,"class","compose-textarea svelte-ybzzp3"),attr(u,"placeholder","Enter your Nostr event JSON here..."),attr(u,"spellcheck","false"),attr(l,"class","compose-editor svelte-ybzzp3"),attr(t,"class","compose-view svelte-ybzzp3")},m(p,f){insert(p,t,f),append(t,n),append(n,s),append(n,r),append(n,i),append(n,o),append(n,a),append(t,c),append(t,l),append(l,u),set_input_value(u,e[27]),d||(h=[listen(s,"click",e[64]),listen(i,"click",e[65]),listen(a,"click",e[66]),listen(u,"input",e[84])],d=!0)},p(e,t){134217728&t[0]&&set_input_value(u,e[27])},i:noop,o:noop,d(e){e&&detach(t),d=!1,run_all(h)}}}function create_if_block_13(e){let t,n;function s(e,t){return!e[1]||"write"!==e[4]&&"admin"!==e[4]&&"owner"!==e[4]?create_else_block_5:create_if_block_16}let r=s(e),i=r(e),o=e[1]&&("write"===e[4]||"admin"===e[4]||"owner"===e[4])&&create_if_block_14(e);return{c(){t=element("div"),i.c(),n=space(),o&&o.c(),attr(t,"class","events-view-container svelte-ybzzp3")},m(e,s){insert(e,t,s),i.m(t,null),append(t,n),o&&o.m(t,null)},p(e,a){r===(r=s(e))&&i?i.p(e,a):(i.d(1),i=r(e),i&&(i.c(),i.m(t,n))),!e[1]||"write"!==e[4]&&"admin"!==e[4]&&"owner"!==e[4]?o&&(o.d(1),o=null):o?o.p(e,a):(o=create_if_block_14(e),o.c(),o.m(t,null))},i:noop,o:noop,d(e){e&&detach(t),i.d(),o&&o.d()}}}function create_if_block_10(e){let t;function n(e,t){return!e[1]||"admin"!==e[4]&&"owner"!==e[4]?e[1]?create_if_block_12:create_else_block_2:create_if_block_11}let s=n(e),r=s(e);return{c(){t=element("div"),r.c(),attr(t,"class","import-view svelte-ybzzp3")},m(e,n){insert(e,t,n),r.m(t,null)},p(e,i){s===(s=n(e))&&r?r.p(e,i):(r.d(1),r=s(e),r&&(r.c(),r.m(t,null)))},i:noop,o:noop,d(e){e&&detach(t),r.d()}}}function create_if_block_7(e){let t;function n(e,t){return e[1]?create_if_block_8:create_else_block_1}let s=n(e),r=s(e);return{c(){r.c(),t=empty()},m(e,n){r.m(e,n),insert(e,t,n)},p(e,i){s===(s=n(e))&&r?r.p(e,i):(r.d(1),r=s(e),r&&(r.c(),r.m(t.parentNode,t)))},i:noop,o:noop,d(e){r.d(e),e&&detach(t)}}}function create_else_block_9(e){let t;return{c(){t=element("p"),t.textContent="Log in to access your user dashboard",attr(t,"class","svelte-ybzzp3")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_44(e){let t,n,s,r=(e[3]?.name||e[2].slice(0,8)+"...")+"";return{c(){t=element("p"),n=text("Welcome "),s=text(r),attr(t,"class","svelte-ybzzp3")},m(e,r){insert(e,t,r),append(t,n),append(t,s)},p(e,t){12&t[0]&&r!==(r=(e[3]?.name||e[2].slice(0,8)+"...")+"")&&set_data(s,r)},d(e){e&&detach(t)}}}function create_if_block_37(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w=e[138].query+"",_=e[30].get(e[138].id)?.isLoading,E=!e[30].get(e[138].id)?.hasMore&&e[30].get(e[138].id)?.events?.length>0;function k(){return e[88](e[138])}function $(e,t){return 64&t[0]&&(p=null),64&t[0]&&(f=null),null==p&&(p=!!(e[30].get(e[138].id)?.events?.length>0)),p?create_if_block_40:(null==f&&(f=!e[30].get(e[138].id)?.isLoading),f?create_if_block_43:void 0)}let x=$(e,[-1,-1,-1,-1,-1]),S=x&&x(e),T=_&&create_if_block_39(),A=E&&create_if_block_38();function R(...t){return e[93](e[138],...t)}return{c(){t=element("div"),n=element("div"),s=element("h2"),r=text('🔍 Search Results: "'),i=text(w),o=text('"'),a=space(),c=element("button"),l=text("🔄 Refresh"),d=space(),h=element("div"),S&&S.c(),g=space(),T&&T.c(),y=space(),A&&A.c(),m=space(),attr(s,"class","svelte-ybzzp3"),attr(c,"class","refresh-btn svelte-ybzzp3"),c.disabled=u=e[30].get(e[138].id)?.isLoading,attr(n,"class","search-results-header svelte-ybzzp3"),attr(h,"class","search-results-content svelte-ybzzp3"),attr(t,"class","search-results-view svelte-ybzzp3")},m(e,u){insert(e,t,u),append(t,n),append(n,s),append(s,r),append(s,i),append(s,o),append(n,a),append(n,c),append(c,l),append(t,d),append(t,h),S&&S.m(h,null),append(h,g),T&&T.m(h,null),append(h,y),A&&A.m(h,null),append(t,m),b||(v=[listen(c,"click",k),listen(h,"scroll",R)],b=!0)},p(t,n){e=t,64&n[0]&&w!==(w=e[138].query+"")&&set_data(i,w),64&n[0]&&u!==(u=e[30].get(e[138].id)?.isLoading)&&(c.disabled=u),x===(x=$(e,n))&&S?S.p(e,n):(S&&S.d(1),S=x&&x(e),S&&(S.c(),S.m(h,g))),64&n[0]&&(_=e[30].get(e[138].id)?.isLoading),_?T||(T=create_if_block_39(),T.c(),T.m(h,y)):T&&(T.d(1),T=null),64&n[0]&&(E=!e[30].get(e[138].id)?.hasMore&&e[30].get(e[138].id)?.events?.length>0),E?A||(A=create_if_block_38(),A.c(),A.m(h,null)):A&&(A.d(1),A=null)},d(e){e&&detach(t),S&&S.d(),T&&T.d(),A&&A.d(),b=!1,run_all(v)}}}function create_if_block_43(e){let t,n,s,r,i,o=e[138].query+"";return{c(){t=element("div"),n=element("p"),s=text('No search results found for "'),r=text(o),i=text('".'),attr(n,"class","svelte-ybzzp3"),attr(t,"class","no-search-results svelte-ybzzp3")},m(e,o){insert(e,t,o),append(t,n),append(n,s),append(n,r),append(n,i)},p(e,t){64&t[0]&&o!==(o=e[138].query+"")&&set_data(r,o)},d(e){e&&detach(t)}}}function create_if_block_40(e){let t,n=e[30].get(e[138].id).events,s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_4(get_each_context_4(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(1073872980&r[0]|11&r[1]){let i;for(n=e[30].get(e[138].id).events,i=0;i<n.length;i+=1){const o=get_each_context_4(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_4(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_if_block_42(e){let t,n,s;function r(){return e[89](e[129])}return{c(){t=element("button"),t.textContent="🗑️",attr(t,"class","delete-btn svelte-ybzzp3")},m(e,i){insert(e,t,i),n||(s=listen(t,"click",stop_propagation(r)),n=!0)},p(t,n){e=t},d(e){e&&detach(t),n=!1,s()}}}function create_if_block_41(e){let t,n,s,r,i,o,a,c,l=JSON.stringify(e[129],null,2)+"";function u(...t){return e[92](e[129],...t)}return{c(){t=element("div"),n=element("div"),s=element("pre"),r=text(l),i=space(),o=element("button"),o.textContent="📋",attr(s,"class","event-json svelte-ybzzp3"),attr(o,"class","copy-json-btn svelte-ybzzp3"),attr(o,"title","Copy minified JSON to clipboard"),attr(n,"class","json-container svelte-ybzzp3"),attr(t,"class","search-result-details svelte-ybzzp3")},m(e,l){insert(e,t,l),append(t,n),append(n,s),append(s,r),append(n,i),append(n,o),a||(c=listen(o,"click",stop_propagation(u)),a=!0)},p(t,n){e=t,64&n[0]&&l!==(l=JSON.stringify(e[129],null,2)+"")&&set_data(r,l)},d(e){e&&detach(t),a=!1,c()}}}function create_each_block_4(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,S,T=truncatePubkey(e[129].pubkey)+"",A=e[129].kind+"",R=e[31](e[129].kind)+"",N=formatTimestamp(e[129].created_at)+"",C=truncateContent(e[129].content)+"",I=e[17].has(e[129].id),B=5!==e[129].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[129].pubkey&&e[129].pubkey===e[2])&&create_if_block_42(e);function P(){return e[90](e[129])}function D(...t){return e[91](e[129],...t)}let L=I&&create_if_block_41(e);return{c(){t=element("div"),n=element("div"),s=element("div"),s.innerHTML='<div class="avatar-placeholder svelte-ybzzp3">👤</div>',r=space(),i=element("div"),o=element("div"),a=text(T),c=space(),l=element("div"),u=element("span"),d=text(A),h=space(),p=element("span"),f=text(R),g=space(),y=element("div"),m=element("div"),b=text(N),v=space(),w=element("div"),_=text(C),E=space(),B&&B.c(),k=space(),L&&L.c(),$=space(),attr(s,"class","search-result-avatar svelte-ybzzp3"),attr(o,"class","search-result-author svelte-ybzzp3"),attr(u,"class","kind-number svelte-ybzzp3"),attr(p,"class","kind-name svelte-ybzzp3"),attr(l,"class","search-result-kind svelte-ybzzp3"),attr(i,"class","search-result-info svelte-ybzzp3"),attr(m,"class","event-timestamp svelte-ybzzp3"),attr(w,"class","event-content-single-line svelte-ybzzp3"),attr(y,"class","search-result-content svelte-ybzzp3"),attr(n,"class","search-result-row svelte-ybzzp3"),attr(n,"role","button"),attr(n,"tabindex","0"),attr(t,"class","search-result-item svelte-ybzzp3"),toggle_class(t,"expanded",e[17].has(e[129].id))},m(e,T){insert(e,t,T),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(i,c),append(i,l),append(l,u),append(u,d),append(l,h),append(l,p),append(p,f),append(n,g),append(n,y),append(y,m),append(m,b),append(y,v),append(y,w),append(w,_),append(n,E),B&&B.m(n,null),append(t,k),L&&L.m(t,null),append(t,$),x||(S=[listen(n,"click",P),listen(n,"keydown",D)],x=!0)},p(s,r){e=s,64&r[0]&&T!==(T=truncatePubkey(e[129].pubkey)+"")&&set_data(a,T),64&r[0]&&A!==(A=e[129].kind+"")&&set_data(d,A),64&r[0]&&R!==(R=e[31](e[129].kind)+"")&&set_data(f,R),64&r[0]&&N!==(N=formatTimestamp(e[129].created_at)+"")&&set_data(b,N),64&r[0]&&C!==(C=truncateContent(e[129].content)+"")&&set_data(_,C),5!==e[129].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[129].pubkey&&e[129].pubkey===e[2])?B?B.p(e,r):(B=create_if_block_42(e),B.c(),B.m(n,null)):B&&(B.d(1),B=null),131136&r[0]&&(I=e[17].has(e[129].id)),I?L?L.p(e,r):(L=create_if_block_41(e),L.c(),L.m(t,$)):L&&(L.d(1),L=null),1073872960&r[0]&&toggle_class(t,"expanded",e[17].has(e[129].id))},d(e){e&&detach(t),B&&B.d(),L&&L.d(),x=!1,run_all(S)}}}function create_if_block_39(e){let t;return{c(){t=element("div"),t.innerHTML='<div class="loading-spinner svelte-ybzzp3"></div> \n <p class="svelte-ybzzp3">Searching...</p>',attr(t,"class","loading-search-results svelte-ybzzp3")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_38(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-ybzzp3">No more search results to load.</p>',attr(t,"class","end-of-search-results svelte-ybzzp3")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_each_block_3(e){let t,n=e[138].id===e[5]&&create_if_block_37(e);return{c(){n&&n.c(),t=empty()},m(e,s){n&&n.m(e,s),insert(e,t,s)},p(e,s){e[138].id===e[5]?n?n.p(e,s):(n=create_if_block_37(e),n.c(),n.m(t.parentNode,t)):n&&(n.d(1),n=null)},d(e){n&&n.d(e),e&&detach(t)}}}function create_else_block_7(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in to access sprocket management.",s=space(),r=element("button"),r.textContent="Log In",attr(n,"class","svelte-ybzzp3"),attr(r,"class","login-btn svelte-ybzzp3"),attr(t,"class","login-prompt svelte-ybzzp3")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[46]),i=!0)},p:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_35(e){let t,n,s,r,i,o,a,c,l,u=(e[4]||"none")+"";return{c(){t=element("div"),n=element("p"),n.textContent="❌ Owner permission required for sprocket\n management.",s=space(),r=element("p"),r.innerHTML="To enable sprocket functionality, set the <code>ORLY_OWNERS</code> environment variable with your npub when starting the\n relay.",i=space(),o=element("p"),a=text("Current user role: "),c=element("strong"),l=text(u),attr(n,"class","svelte-ybzzp3"),attr(r,"class","svelte-ybzzp3"),attr(o,"class","svelte-ybzzp3"),attr(t,"class","permission-denied svelte-ybzzp3")},m(e,u){insert(e,t,u),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),append(o,a),append(o,c),append(c,l)},p(e,t){16&t[0]&&u!==(u=(e[4]||"none")+"")&&set_data(l,u)},d(e){e&&detach(t)}}}function create_if_block_30(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,S,T,A,R,N,C,I,B,P,D,L,F,O,U,z,M,K,H,j,V,q,W,G,J,Z,Y,X,Q,ee,te,ne,se=e[21]?.is_running?"🟢 Running":"🔴 Stopped",re=e[21]?.script_exists?"✅ Exists":"❌ Not found",ie=e[21]?.pid&&create_if_block_34(e),oe=e[24]&&create_if_block_33(e),ae=e[22],ce=[];for(let t=0;t<ae.length;t+=1)ce[t]=create_each_block_2(get_each_context_2(e,ae,t));return{c(){t=element("div"),n=element("div"),s=element("h3"),s.textContent="Script Editor",r=space(),i=element("div"),o=element("button"),a=text("🔄 Restart"),c=space(),l=element("button"),u=text("🗑️ Delete Script"),h=space(),p=element("div"),f=element("h4"),f.textContent="Upload Script",g=space(),y=element("div"),m=element("input"),b=space(),v=element("button"),w=text("📤 Upload & Update"),E=space(),k=element("div"),$=element("div"),x=element("span"),x.textContent="Status:",S=space(),T=element("span"),A=text(se),R=space(),ie&&ie.c(),N=space(),C=element("div"),I=element("span"),I.textContent="Script:",B=space(),P=element("span"),D=text(re),L=space(),F=element("div"),O=element("textarea"),U=space(),z=element("div"),M=element("button"),K=text("💾 Save & Update"),H=space(),j=element("button"),V=text("📥 Load Current"),q=space(),oe&&oe.c(),W=space(),G=element("div"),J=element("h3"),J.textContent="Script Versions",Z=space(),Y=element("div");for(let e=0;e<ce.length;e+=1)ce[e].c();X=space(),Q=element("button"),ee=text("🔄 Refresh Versions"),attr(o,"class","sprocket-btn restart-btn svelte-ybzzp3"),o.disabled=e[23],attr(l,"class","sprocket-btn delete-btn svelte-ybzzp3"),l.disabled=d=e[23]||!e[21]?.script_exists,attr(i,"class","sprocket-controls svelte-ybzzp3"),attr(n,"class","sprocket-header svelte-ybzzp3"),attr(f,"class","svelte-ybzzp3"),attr(m,"type","file"),attr(m,"id","sprocket-upload-file"),attr(m,"accept",".sh,.bash"),m.disabled=e[23],attr(m,"class","svelte-ybzzp3"),attr(v,"class","sprocket-btn upload-btn svelte-ybzzp3"),v.disabled=_=e[23]||!e[26],attr(y,"class","upload-controls svelte-ybzzp3"),attr(p,"class","sprocket-upload-section svelte-ybzzp3"),attr(x,"class","status-label svelte-ybzzp3"),attr(T,"class","status-value svelte-ybzzp3"),toggle_class(T,"running",e[21]?.is_running),attr($,"class","status-item svelte-ybzzp3"),attr(I,"class","status-label svelte-ybzzp3"),attr(P,"class","status-value svelte-ybzzp3"),attr(C,"class","status-item svelte-ybzzp3"),attr(k,"class","sprocket-status svelte-ybzzp3"),attr(O,"class","script-editor svelte-ybzzp3"),attr(O,"placeholder","#!/bin/bash # Enter your sprocket script here..."),O.disabled=e[23],attr(F,"class","script-editor-container svelte-ybzzp3"),attr(M,"class","sprocket-btn save-btn svelte-ybzzp3"),M.disabled=e[23],attr(j,"class","sprocket-btn load-btn svelte-ybzzp3"),j.disabled=e[23],attr(z,"class","script-actions svelte-ybzzp3"),attr(t,"class","sprocket-section svelte-ybzzp3"),attr(Y,"class","versions-list svelte-ybzzp3"),attr(Q,"class","sprocket-btn refresh-btn svelte-ybzzp3"),Q.disabled=e[23],attr(G,"class","sprocket-section svelte-ybzzp3")},m(d,_){insert(d,t,_),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(i,c),append(i,l),append(l,u),append(t,h),append(t,p),append(p,f),append(p,g),append(p,y),append(y,m),append(y,b),append(y,v),append(v,w),append(t,E),append(t,k),append(k,$),append($,x),append($,S),append($,T),append(T,A),append(k,R),ie&&ie.m(k,null),append(k,N),append(k,C),append(C,I),append(C,B),append(C,P),append(P,D),append(t,L),append(t,F),append(F,O),set_input_value(O,e[20]),append(t,U),append(t,z),append(z,M),append(M,K),append(z,H),append(z,j),append(j,V),append(t,q),oe&&oe.m(t,null),insert(d,W,_),insert(d,G,_),append(G,J),append(G,Z),append(G,Y);for(let e=0;e<ce.length;e+=1)ce[e]&&ce[e].m(Y,null);append(G,X),append(G,Q),append(Q,ee),te||(ne=[listen(o,"click",e[37]),listen(l,"click",e[38]),listen(m,"change",e[42]),listen(v,"click",e[43]),listen(O,"input",e[85]),listen(M,"click",e[36]),listen(j,"click",e[35]),listen(Q,"click",e[39])],te=!0)},p(e,n){if(8388608&n[0]&&(o.disabled=e[23]),10485760&n[0]&&d!==(d=e[23]||!e[21]?.script_exists)&&(l.disabled=d),8388608&n[0]&&(m.disabled=e[23]),75497472&n[0]&&_!==(_=e[23]||!e[26])&&(v.disabled=_),2097152&n[0]&&se!==(se=e[21]?.is_running?"🟢 Running":"🔴 Stopped")&&set_data(A,se),2097152&n[0]&&toggle_class(T,"running",e[21]?.is_running),e[21]?.pid?ie?ie.p(e,n):(ie=create_if_block_34(e),ie.c(),ie.m(k,N)):ie&&(ie.d(1),ie=null),2097152&n[0]&&re!==(re=e[21]?.script_exists?"✅ Exists":"❌ Not found")&&set_data(D,re),8388608&n[0]&&(O.disabled=e[23]),1048576&n[0]&&set_input_value(O,e[20]),8388608&n[0]&&(M.disabled=e[23]),8388608&n[0]&&(j.disabled=e[23]),e[24]?oe?oe.p(e,n):(oe=create_if_block_33(e),oe.c(),oe.m(t,null)):oe&&(oe.d(1),oe=null),12582912&n[0]|1536&n[1]){let t;for(ae=e[22],t=0;t<ae.length;t+=1){const s=get_each_context_2(e,ae,t);ce[t]?ce[t].p(s,n):(ce[t]=create_each_block_2(s),ce[t].c(),ce[t].m(Y,null))}for(;t<ce.length;t+=1)ce[t].d(1);ce.length=ae.length}8388608&n[0]&&(Q.disabled=e[23])},d(e){e&&detach(t),ie&&ie.d(),oe&&oe.d(),e&&detach(W),e&&detach(G),destroy_each(ce,e),te=!1,run_all(ne)}}}function create_if_block_34(e){let t,n,s,r,i,o=e[21].pid+"";return{c(){t=element("div"),n=element("span"),n.textContent="PID:",s=space(),r=element("span"),i=text(o),attr(n,"class","status-label svelte-ybzzp3"),attr(r,"class","status-value svelte-ybzzp3"),attr(t,"class","status-item svelte-ybzzp3")},m(e,o){insert(e,t,o),append(t,n),append(t,s),append(t,r),append(r,i)},p(e,t){2097152&t[0]&&o!==(o=e[21].pid+"")&&set_data(i,o)},d(e){e&&detach(t)}}}function create_if_block_33(e){let t,n;return{c(){t=element("div"),n=text(e[24]),attr(t,"class","sprocket-message svelte-ybzzp3"),toggle_class(t,"error","error"===e[25])},m(e,s){insert(e,t,s),append(t,n)},p(e,s){16777216&s[0]&&set_data(n,e[24]),33554432&s[0]&&toggle_class(t,"error","error"===e[25])},d(e){e&&detach(t)}}}function create_if_block_32(e){let t;return{c(){t=element("span"),t.textContent="Current",attr(t,"class","current-badge svelte-ybzzp3")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_31(e){let t,n,s,r;function i(){return e[87](e[135])}return{c(){t=element("button"),n=text("🗑️ Delete"),attr(t,"class","version-btn delete-btn svelte-ybzzp3"),t.disabled=e[23]},m(e,o){insert(e,t,o),append(t,n),s||(r=listen(t,"click",i),s=!0)},p(n,s){e=n,8388608&s[0]&&(t.disabled=e[23])},d(e){e&&detach(t),s=!1,r()}}}function create_each_block_2(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m=e[135].name+"",b=new Date(e[135].modified).toLocaleString()+"",v=e[135].is_current&&create_if_block_32();function w(){return e[86](e[135])}let _=!e[135].is_current&&create_if_block_31(e);return{c(){t=element("div"),n=element("div"),s=element("div"),r=text(m),i=space(),o=element("div"),a=text(b),c=space(),v&&v.c(),l=space(),u=element("div"),d=element("button"),h=text("📥 Load"),p=space(),_&&_.c(),f=space(),attr(s,"class","version-name svelte-ybzzp3"),attr(o,"class","version-date svelte-ybzzp3"),attr(n,"class","version-info svelte-ybzzp3"),attr(d,"class","version-btn load-btn svelte-ybzzp3"),d.disabled=e[23],attr(u,"class","version-actions svelte-ybzzp3"),attr(t,"class","version-item svelte-ybzzp3"),toggle_class(t,"current",e[135].is_current)},m(e,m){insert(e,t,m),append(t,n),append(n,s),append(s,r),append(n,i),append(n,o),append(o,a),append(o,c),v&&v.m(o,null),append(t,l),append(t,u),append(u,d),append(d,h),append(u,p),_&&_.m(u,null),append(t,f),g||(y=listen(d,"click",w),g=!0)},p(n,s){e=n,4194304&s[0]&&m!==(m=e[135].name+"")&&set_data(r,m),4194304&s[0]&&b!==(b=new Date(e[135].modified).toLocaleString()+"")&&set_data(a,b),e[135].is_current?v||(v=create_if_block_32(),v.c(),v.m(o,null)):v&&(v.d(1),v=null),8388608&s[0]&&(d.disabled=e[23]),e[135].is_current?_&&(_.d(1),_=null):_?_.p(e,s):(_=create_if_block_31(e),_.c(),_.m(u,null)),4194304&s[0]&&toggle_class(t,"current",e[135].is_current)},d(e){e&&detach(t),v&&v.d(),_&&_.d(),g=!1,y()}}}function create_else_block_6(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in with owner permissions to access\n managed ACL configuration.",s=space(),r=element("button"),r.textContent="Log In",attr(r,"class","login-btn svelte-ybzzp3"),attr(t,"class","access-denied")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[46]),i=!0)},p:noop,i:noop,o:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_28(e){let t,n;return t=new ManagedACL({props:{userSigner:e[12],userPubkey:e[2]}}),{c(){create_component(t.$$.fragment)},m(e,s){mount_component(t,e,s),n=!0},p(e,n){const s={};4096&n[0]&&(s.userSigner=e[12]),4&n[0]&&(s.userPubkey=e[2]),t.$set(s)},i(e){n||(transition_in(t.$$.fragment,e),n=!0)},o(e){transition_out(t.$$.fragment,e),n=!1},d(e){destroy_component(t,e)}}}function create_if_block_27(e){let t,n,s,r,i,o,a,c,l,u,d,h=(e[9]||"unknown")+"";return{c(){t=element("div"),n=element("h3"),n.textContent="⚠️ Managed ACL Mode Not Active",s=space(),r=element("p"),r.textContent='To use the Managed ACL interface, you need to set\n the ACL mode to "managed" in your relay\n configuration.',i=space(),o=element("p"),a=text("Current ACL mode: "),c=element("strong"),l=text(h),u=space(),d=element("p"),d.innerHTML='Please set <code class="svelte-ybzzp3">ORLY_ACL_MODE=managed</code> in your\n environment variables and restart the relay.',attr(n,"class","svelte-ybzzp3"),attr(r,"class","svelte-ybzzp3"),attr(o,"class","svelte-ybzzp3"),attr(d,"class","svelte-ybzzp3"),attr(t,"class","acl-mode-warning svelte-ybzzp3")},m(e,h){insert(e,t,h),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),append(o,a),append(o,c),append(c,l),append(t,u),append(t,d)},p(e,t){512&t[0]&&h!==(h=(e[9]||"unknown")+"")&&set_data(l,h)},i:noop,o:noop,d(e){e&&detach(t)}}}function create_else_block_5(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-ybzzp3">❌ Write, admin, or owner permission required to\n view all events.</p>',attr(t,"class","permission-denied svelte-ybzzp3")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_16(e){let t,n,s,r,i;function o(e,t){return e[29].length>0?create_if_block_19:e[18]?void 0:create_if_block_24}let a=o(e),c=a&&a(e),l=e[18]&&create_if_block_18(),u=!e[19]&&e[7].length>0&&create_if_block_17();return{c(){t=element("div"),c&&c.c(),n=space(),l&&l.c(),s=space(),u&&u.c(),attr(t,"class","events-view-content svelte-ybzzp3")},m(o,a){insert(o,t,a),c&&c.m(t,null),append(t,n),l&&l.m(t,null),append(t,s),u&&u.m(t,null),r||(i=listen(t,"scroll",e[63]),r=!0)},p(e,r){a===(a=o(e))&&c?c.p(e,r):(c&&c.d(1),c=a&&a(e),c&&(c.c(),c.m(t,n))),e[18]?l||(l=create_if_block_18(),l.c(),l.m(t,s)):l&&(l.d(1),l=null),!e[19]&&e[7].length>0?u||(u=create_if_block_17(),u.c(),u.m(t,null)):u&&(u.d(1),u=null)},d(e){e&&detach(t),c&&c.d(),l&&l.d(),u&&u.d(),r=!1,i()}}}function create_if_block_24(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-ybzzp3">No events found.</p>',attr(t,"class","no-events svelte-ybzzp3")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_19(e){let t,n=e[29],s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block(get_each_context(e,n,t));return{c(){for(let e=0;e<s.length;e+=1)s[e].c();t=empty()},m(e,n){for(let t=0;t<s.length;t+=1)s[t]&&s[t].m(e,n);insert(e,t,n)},p(e,r){if(537002004&r[0]|11&r[1]){let i;for(n=e[29],i=0;i<n.length;i+=1){const o=get_each_context(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block(o),s[i].c(),s[i].m(t.parentNode,t))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){destroy_each(s,e),e&&detach(t)}}}function create_else_block_4(e){let t,n,s=truncateContent(e[129].content)+"";return{c(){t=element("div"),n=text(s),attr(t,"class","event-content-single-line svelte-ybzzp3")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){536870912&t[0]&&s!==(s=truncateContent(e[129].content)+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_if_block_22(e){let t,n,s,r=e[129].tags&&e[129].tags.length>0&&create_if_block_23(e);return{c(){t=element("div"),n=element("span"),n.textContent="🗑️ Delete Event",s=space(),r&&r.c(),attr(n,"class","delete-event-label svelte-ybzzp3"),attr(t,"class","delete-event-info svelte-ybzzp3")},m(e,i){insert(e,t,i),append(t,n),append(t,s),r&&r.m(t,null)},p(e,n){e[129].tags&&e[129].tags.length>0?r?r.p(e,n):(r=create_if_block_23(e),r.c(),r.m(t,null)):r&&(r.d(1),r=null)},d(e){e&&detach(t),r&&r.d()}}}function create_if_block_23(e){let t,n=e[129].tags.filter(func_1),s=[];for(let t=0;t<n.length;t+=1)s[t]=create_each_block_1(get_each_context_1(e,n,t));return{c(){t=element("div");for(let e=0;e<s.length;e+=1)s[e].c();attr(t,"class","delete-targets svelte-ybzzp3")},m(e,n){insert(e,t,n);for(let e=0;e<s.length;e+=1)s[e]&&s[e].m(t,null)},p(e,r){if(536870912&r[0]){let i;for(n=e[129].tags.filter(func_1),i=0;i<n.length;i+=1){const o=get_each_context_1(e,n,i);s[i]?s[i].p(o,r):(s[i]=create_each_block_1(o),s[i].c(),s[i].m(t,null))}for(;i<s.length;i+=1)s[i].d(1);s.length=n.length}},d(e){e&&detach(t),destroy_each(s,e)}}}function create_each_block_1(e){let t,n,s,r,i,o=e[132][1].slice(0,8)+"",a=e[132][1].slice(-8)+"";return{c(){t=element("span"),n=text("Target: "),s=text(o),r=text("..."),i=text(a),attr(t,"class","delete-target svelte-ybzzp3")},m(e,o){insert(e,t,o),append(t,n),append(t,s),append(t,r),append(t,i)},p(e,t){536870912&t[0]&&o!==(o=e[132][1].slice(0,8)+"")&&set_data(s,o),536870912&t[0]&&a!==(a=e[132][1].slice(-8)+"")&&set_data(i,a)},d(e){e&&detach(t)}}}function create_if_block_21(e){let t,n,s;function r(){return e[76](e[129])}return{c(){t=element("button"),t.textContent="🗑️",attr(t,"class","delete-btn svelte-ybzzp3")},m(e,i){insert(e,t,i),n||(s=listen(t,"click",stop_propagation(r)),n=!0)},p(t,n){e=t},d(e){e&&detach(t),n=!1,s()}}}function create_if_block_20(e){let t,n,s,r,i,o,a,c,l=JSON.stringify(e[129],null,2)+"";function u(...t){return e[79](e[129],...t)}return{c(){t=element("div"),n=element("div"),s=element("pre"),r=text(l),i=space(),o=element("button"),o.textContent="📋",attr(s,"class","event-json svelte-ybzzp3"),attr(o,"class","copy-json-btn svelte-ybzzp3"),attr(o,"title","Copy minified JSON to clipboard"),attr(n,"class","json-container svelte-ybzzp3"),attr(t,"class","events-view-details svelte-ybzzp3")},m(e,l){insert(e,t,l),append(t,n),append(n,s),append(s,r),append(n,i),append(n,o),a||(c=listen(o,"click",stop_propagation(u)),a=!0)},p(t,n){e=t,536870912&n[0]&&l!==(l=JSON.stringify(e[129],null,2)+"")&&set_data(r,l)},d(e){e&&detach(t),a=!1,c()}}}function create_each_block(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x=truncatePubkey(e[129].pubkey)+"",S=e[129].kind+"",T=e[31](e[129].kind)+"",A=formatTimestamp(e[129].created_at)+"",R=e[17].has(e[129].id);function N(e,t){return 5===e[129].kind?create_if_block_22:create_else_block_4}let C=N(e),I=C(e),B=5!==e[129].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[129].pubkey&&e[129].pubkey===e[2])&&create_if_block_21(e);function P(){return e[77](e[129])}function D(...t){return e[78](e[129],...t)}let L=R&&create_if_block_20(e);return{c(){t=element("div"),n=element("div"),s=element("div"),s.innerHTML='<div class="avatar-placeholder svelte-ybzzp3">👤</div>',r=space(),i=element("div"),o=element("div"),a=text(x),c=space(),l=element("div"),u=element("span"),d=text(S),h=space(),p=element("span"),f=text(T),g=space(),y=element("div"),m=element("div"),b=text(A),v=space(),I.c(),w=space(),B&&B.c(),_=space(),L&&L.c(),E=space(),attr(s,"class","events-view-avatar svelte-ybzzp3"),attr(o,"class","events-view-author svelte-ybzzp3"),attr(u,"class","kind-number svelte-ybzzp3"),toggle_class(u,"delete-event",5===e[129].kind),attr(p,"class","kind-name svelte-ybzzp3"),attr(l,"class","events-view-kind svelte-ybzzp3"),attr(i,"class","events-view-info svelte-ybzzp3"),attr(m,"class","event-timestamp svelte-ybzzp3"),attr(y,"class","events-view-content svelte-ybzzp3"),attr(n,"class","events-view-row svelte-ybzzp3"),attr(n,"role","button"),attr(n,"tabindex","0"),attr(t,"class","events-view-item svelte-ybzzp3"),toggle_class(t,"expanded",e[17].has(e[129].id))},m(e,x){insert(e,t,x),append(t,n),append(n,s),append(n,r),append(n,i),append(i,o),append(o,a),append(i,c),append(i,l),append(l,u),append(u,d),append(l,h),append(l,p),append(p,f),append(n,g),append(n,y),append(y,m),append(m,b),append(y,v),I.m(y,null),append(n,w),B&&B.m(n,null),append(t,_),L&&L.m(t,null),append(t,E),k||($=[listen(n,"click",P),listen(n,"keydown",D)],k=!0)},p(s,r){e=s,536870912&r[0]&&x!==(x=truncatePubkey(e[129].pubkey)+"")&&set_data(a,x),536870912&r[0]&&S!==(S=e[129].kind+"")&&set_data(d,S),536870912&r[0]&&toggle_class(u,"delete-event",5===e[129].kind),536870912&r[0]&&T!==(T=e[31](e[129].kind)+"")&&set_data(f,T),536870912&r[0]&&A!==(A=formatTimestamp(e[129].created_at)+"")&&set_data(b,A),C===(C=N(e))&&I?I.p(e,r):(I.d(1),I=C(e),I&&(I.c(),I.m(y,null))),5!==e[129].kind&&("admin"===e[4]||"owner"===e[4]||"write"===e[4]&&e[129].pubkey&&e[129].pubkey===e[2])?B?B.p(e,r):(B=create_if_block_21(e),B.c(),B.m(n,null)):B&&(B.d(1),B=null),537001984&r[0]&&(R=e[17].has(e[129].id)),R?L?L.p(e,r):(L=create_if_block_20(e),L.c(),L.m(t,E)):L&&(L.d(1),L=null),537001984&r[0]&&toggle_class(t,"expanded",e[17].has(e[129].id))},d(e){e&&detach(t),I.d(),B&&B.d(),L&&L.d(),k=!1,run_all($)}}}function create_if_block_18(e){let t;return{c(){t=element("div"),t.innerHTML='<div class="loading-spinner svelte-ybzzp3"></div> \n <p class="svelte-ybzzp3">Loading events...</p>',attr(t,"class","loading-events svelte-ybzzp3")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_17(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-ybzzp3">No more events to load.</p>',attr(t,"class","end-of-events svelte-ybzzp3")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_14(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y;function m(e,t){return e[18]?create_if_block_15:create_else_block_3}let b=m(e),v=b(e);return{c(){t=element("div"),n=element("div"),s=element("label"),r=element("input"),i=space(),o=element("span"),a=space(),c=element("span"),c.textContent="Only show my events",l=space(),u=element("div"),d=element("button"),h=text("🔄 Load More"),p=space(),f=element("button"),v.c(),attr(r,"type","checkbox"),attr(r,"class","svelte-ybzzp3"),attr(o,"class","toggle-slider svelte-ybzzp3"),attr(c,"class","toggle-label svelte-ybzzp3"),attr(s,"class","toggle-container svelte-ybzzp3"),attr(n,"class","events-view-toggle svelte-ybzzp3"),attr(d,"class","refresh-btn svelte-ybzzp3"),d.disabled=e[18],attr(f,"class","reload-btn svelte-ybzzp3"),f.disabled=e[18],attr(u,"class","events-view-buttons svelte-ybzzp3"),attr(t,"class","events-view-header svelte-ybzzp3")},m(m,b){insert(m,t,b),append(t,n),append(n,s),append(s,r),r.checked=e[8],append(s,i),append(s,o),append(s,a),append(s,c),append(t,l),append(t,u),append(u,d),append(d,h),append(u,p),append(u,f),v.m(f,null),g||(y=[listen(r,"change",e[80]),listen(r,"change",e[81]),listen(d,"click",e[82]),listen(f,"click",e[83])],g=!0)},p(e,t){256&t[0]&&(r.checked=e[8]),262144&t[0]&&(d.disabled=e[18]),b!==(b=m(e))&&(v.d(1),v=b(e),v&&(v.c(),v.m(f,null))),262144&t[0]&&(f.disabled=e[18])},d(e){e&&detach(t),v.d(),g=!1,run_all(y)}}}function create_else_block_3(e){let t;return{c(){t=text("🔄")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_if_block_15(e){let t;return{c(){t=element("div"),attr(t,"class","spinner svelte-ybzzp3")},m(e,n){insert(e,t,n)},d(e){e&&detach(t)}}}function create_else_block_2(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in to access import functionality.",s=space(),r=element("button"),r.textContent="Log In",attr(n,"class","svelte-ybzzp3"),attr(r,"class","login-btn svelte-ybzzp3"),attr(t,"class","login-prompt svelte-ybzzp3")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[46]),i=!0)},p:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_12(e){let t;return{c(){t=element("div"),t.innerHTML='<p class="svelte-ybzzp3">❌ Admin or owner permission required for import\n functionality.</p>',attr(t,"class","permission-denied svelte-ybzzp3")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_11(e){let t,n,s,r,i,o,a,c,l,u,d;return{c(){t=element("h2"),t.textContent="Import Events",n=space(),s=element("p"),s.textContent="Upload a JSONL file to import events into the database.",r=space(),i=element("input"),o=space(),a=element("button"),c=text("📥 Import Events"),attr(t,"class","svelte-ybzzp3"),attr(i,"type","file"),attr(i,"id","import-file"),attr(i,"accept",".jsonl,.txt"),attr(i,"class","svelte-ybzzp3"),attr(a,"class","import-btn svelte-ybzzp3"),a.disabled=l=!e[16]},m(l,h){insert(l,t,h),insert(l,n,h),insert(l,s,h),insert(l,r,h),insert(l,i,h),insert(l,o,h),insert(l,a,h),append(a,c),u||(d=[listen(i,"change",e[60]),listen(a,"click",e[61])],u=!0)},p(e,t){65536&t[0]&&l!==(l=!e[16])&&(a.disabled=l)},d(e){e&&detach(t),e&&detach(n),e&&detach(s),e&&detach(r),e&&detach(i),e&&detach(o),e&&detach(a),u=!1,run_all(d)}}}function create_else_block_1(e){let t,n,s,r,i,o;return{c(){t=element("div"),n=element("p"),n.textContent="Please log in to access export functionality.",s=space(),r=element("button"),r.textContent="Log In",attr(n,"class","svelte-ybzzp3"),attr(r,"class","login-btn svelte-ybzzp3"),attr(t,"class","login-prompt svelte-ybzzp3")},m(a,c){insert(a,t,c),append(t,n),append(t,s),append(t,r),i||(o=listen(r,"click",e[46]),i=!0)},p:noop,d(e){e&&detach(t),i=!1,o()}}}function create_if_block_8(e){let t,n,s,r,i,o,a,c,l,u,d=("admin"===e[4]||"owner"===e[4])&&create_if_block_9(e);return{c(){t=element("div"),n=element("h2"),n.textContent="Export My Events",s=space(),r=element("p"),r.textContent="Download your personal events as a JSONL file.",i=space(),o=element("button"),o.textContent="📤 Export My Events",a=space(),d&&d.c(),c=empty(),attr(r,"class","svelte-ybzzp3"),attr(o,"class","export-btn svelte-ybzzp3"),attr(t,"class","export-section svelte-ybzzp3")},m(h,p){insert(h,t,p),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),insert(h,a,p),d&&d.m(h,p),insert(h,c,p),l||(u=listen(o,"click",e[59]),l=!0)},p(e,t){"admin"===e[4]||"owner"===e[4]?d?d.p(e,t):(d=create_if_block_9(e),d.c(),d.m(c.parentNode,c)):d&&(d.d(1),d=null)},d(e){e&&detach(t),e&&detach(a),d&&d.d(e),e&&detach(c),l=!1,u()}}}function create_if_block_9(e){let t,n,s,r,i,o,a,c;return{c(){t=element("div"),n=element("h3"),n.textContent="Export All Events",s=space(),r=element("p"),r.textContent="Download the complete database as a JSONL file. This\n includes all events from all users.",i=space(),o=element("button"),o.textContent="📤 Export All Events",attr(n,"class","svelte-ybzzp3"),attr(r,"class","svelte-ybzzp3"),attr(o,"class","export-btn svelte-ybzzp3"),attr(t,"class","export-section svelte-ybzzp3")},m(l,u){insert(l,t,u),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),a||(c=listen(o,"click",e[58]),a=!0)},p:noop,d(e){e&&detach(t),a=!1,c()}}}function create_if_block(e){let t,n,s,r,i,o,a,c,l,u;function d(e,t){return e[3]?create_if_block_1:e[1]&&e[2]?create_if_block_6:void 0}let h=d(e),p=h&&h(e);return{c(){t=element("div"),n=element("div"),s=element("div"),r=element("h2"),r.textContent="Settings",i=space(),o=element("button"),o.textContent="✕",a=space(),c=element("div"),p&&p.c(),attr(r,"class","svelte-ybzzp3"),attr(o,"class","close-btn svelte-ybzzp3"),attr(s,"class","drawer-header svelte-ybzzp3"),attr(c,"class","drawer-content"),attr(n,"class","settings-drawer svelte-ybzzp3"),toggle_class(n,"dark-theme",e[0]),attr(t,"class","drawer-overlay svelte-ybzzp3"),attr(t,"role","button"),attr(t,"tabindex","0")},m(d,h){insert(d,t,h),append(t,n),append(n,s),append(s,r),append(s,i),append(s,o),append(n,a),append(n,c),p&&p.m(c,null),l||(u=[listen(o,"click",e[51]),listen(n,"click",stop_propagation(e[69])),listen(n,"keydown",stop_propagation(e[70])),listen(t,"click",e[51]),listen(t,"keydown",e[94])],l=!0)},p(e,t){h===(h=d(e))&&p?p.p(e,t):(p&&p.d(1),p=h&&h(e),p&&(p.c(),p.m(c,null))),1&t[0]&&toggle_class(n,"dark-theme",e[0])},d(e){e&&detach(t),p&&p.d(),l=!1,run_all(u)}}}function create_if_block_6(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y=e[2].slice(0,16)+"",m=e[2].slice(-8)+"";return{c(){t=element("div"),n=element("h3"),n.textContent="Profile Loading",s=space(),r=element("p"),r.textContent="Your profile metadata is being loaded...",i=space(),o=element("button"),o.textContent="Retry Loading Profile",a=space(),c=element("div"),l=element("strong"),l.textContent="Public Key:",u=space(),d=text(y),h=text("..."),p=text(m),attr(n,"class","svelte-ybzzp3"),attr(r,"class","svelte-ybzzp3"),attr(o,"class","retry-profile-btn svelte-ybzzp3"),attr(c,"class","user-pubkey-display svelte-ybzzp3"),attr(t,"class","profile-loading-section svelte-ybzzp3")},m(y,m){insert(y,t,m),append(t,n),append(t,s),append(t,r),append(t,i),append(t,o),append(t,a),append(t,c),append(c,l),append(c,u),append(c,d),append(c,h),append(c,p),f||(g=listen(o,"click",e[57]),f=!0)},p(e,t){4&t[0]&&y!==(y=e[2].slice(0,16)+"")&&set_data(d,y),4&t[0]&&m!==(m=e[2].slice(-8)+"")&&set_data(p,m)},d(e){e&&detach(t),f=!1,g()}}}function create_if_block_1(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f=(e[3].name||"Unknown User")+"",g=e[3].banner&&create_if_block_5(e);function y(e,t){return e[3].picture?create_if_block_4:create_else_block}let m=y(e),b=m(e),v=e[3].nip05&&create_if_block_3(e),w=e[3].about&&create_if_block_2(e);return{c(){t=element("div"),n=element("div"),g&&g.c(),s=space(),r=element("button"),r.textContent="Log out",i=space(),b.c(),o=space(),a=element("div"),c=element("h3"),l=text(f),u=space(),v&&v.c(),d=space(),w&&w.c(),attr(r,"class","logout-btn floating svelte-ybzzp3"),attr(c,"class","profile-username svelte-ybzzp3"),attr(a,"class","name-row svelte-ybzzp3"),attr(n,"class","profile-hero svelte-ybzzp3"),attr(t,"class","profile-section svelte-ybzzp3")},m(f,y){insert(f,t,y),append(t,n),g&&g.m(n,null),append(n,s),append(n,r),append(n,i),b.m(n,null),append(n,o),append(n,a),append(a,c),append(c,l),append(a,u),v&&v.m(a,null),append(t,d),w&&w.m(t,null),h||(p=listen(r,"click",e[48]),h=!0)},p(e,r){e[3].banner?g?g.p(e,r):(g=create_if_block_5(e),g.c(),g.m(n,s)):g&&(g.d(1),g=null),m===(m=y(e))&&b?b.p(e,r):(b.d(1),b=m(e),b&&(b.c(),b.m(n,o))),8&r[0]&&f!==(f=(e[3].name||"Unknown User")+"")&&set_data(l,f),e[3].nip05?v?v.p(e,r):(v=create_if_block_3(e),v.c(),v.m(a,null)):v&&(v.d(1),v=null),e[3].about?w?w.p(e,r):(w=create_if_block_2(e),w.c(),w.m(t,null)):w&&(w.d(1),w=null)},d(e){e&&detach(t),g&&g.d(),b.d(),v&&v.d(),w&&w.d(),h=!1,p()}}}function create_if_block_5(e){let t,n;return{c(){t=element("img"),src_url_equal(t.src,n=e[3].banner)||attr(t,"src",n),attr(t,"alt","Profile banner"),attr(t,"class","profile-banner svelte-ybzzp3")},m(e,n){insert(e,t,n)},p(e,s){8&s[0]&&!src_url_equal(t.src,n=e[3].banner)&&attr(t,"src",n)},d(e){e&&detach(t)}}}function create_else_block(e){let t;return{c(){t=element("div"),t.textContent="👤",attr(t,"class","profile-avatar-placeholder overlap svelte-ybzzp3")},m(e,n){insert(e,t,n)},p:noop,d(e){e&&detach(t)}}}function create_if_block_4(e){let t,n;return{c(){t=element("img"),src_url_equal(t.src,n=e[3].picture)||attr(t,"src",n),attr(t,"alt","User avatar"),attr(t,"class","profile-avatar overlap svelte-ybzzp3")},m(e,n){insert(e,t,n)},p(e,s){8&s[0]&&!src_url_equal(t.src,n=e[3].picture)&&attr(t,"src",n)},d(e){e&&detach(t)}}}function create_if_block_3(e){let t,n,s=e[3].nip05+"";return{c(){t=element("span"),n=text(s),attr(t,"class","profile-nip05-inline svelte-ybzzp3")},m(e,s){insert(e,t,s),append(t,n)},p(e,t){8&t[0]&&s!==(s=e[3].nip05+"")&&set_data(n,s)},d(e){e&&detach(t)}}}function create_if_block_2(e){let t,n;return{c(){t=element("div"),n=element("p"),attr(n,"class","profile-about svelte-ybzzp3"),attr(t,"class","about-card svelte-ybzzp3")},m(s,r){insert(s,t,r),append(t,n),n.innerHTML=e[28]},p(e,t){268435456&t[0]&&(n.innerHTML=e[28])},d(e){e&&detach(t)}}}function create_fragment(e){let t,n,s,r,i,o,a,c,l,u,d,h,p,f,g,y,m,b,v,w,_,E,k,$,x,S,T,A,R=e[0]?"☀️":"🌙";function N(e,t){return e[14]?create_if_block_48:create_else_block_12}let C=N(e),I=C(e);function B(e,t){return e[1]?create_if_block_46:create_else_block_11}let P=B(e),D=P(e),L=e[10],F=[];for(let t=0;t<L.length;t+=1)F[t]=create_each_block_5(get_each_context_5(e,L,t));const O=[create_if_block_7,create_if_block_10,create_if_block_13,create_if_block_25,create_if_block_26,create_if_block_29,create_if_block_36,create_else_block_8],U=[];function z(e,t){return 96&t[0]&&(v=null),"export"===e[5]?0:"import"===e[5]?1:"events"===e[5]?2:"compose"===e[5]?3:"managed-acl"===e[5]?4:"sprocket"===e[5]?5:(null==v&&(v=!!e[6].some(e[71])),v?6:7)}w=z(e,[-1,-1,-1,-1,-1]),_=U[w]=O[w](e);let M=e[13]&&create_if_block(e);function K(t){e[95](t)}let H={isDarkTheme:e[0]};return void 0!==e[11]&&(H.showModal=e[11]),$=new LoginModal({props:H}),binding_callbacks.push(()=>bind($,"showModal",K)),$.$on("login",e[47]),$.$on("close",e[49]),{c(){t=element("header"),n=element("div"),s=element("img"),i=space(),I.c(),o=space(),a=element("button"),a.textContent="🔍",c=space(),l=element("button"),u=text(R),d=space(),D.c(),h=space(),p=element("div"),f=element("aside"),g=element("div"),y=element("div");for(let e=0;e<F.length;e+=1)F[e].c();m=space(),b=element("main"),_.c(),E=space(),M&&M.c(),k=space(),create_component($.$$.fragment),src_url_equal(s.src,r="/orly.png")||attr(s,"src","/orly.png"),attr(s,"alt","ORLY Logo"),attr(s,"class","logo svelte-ybzzp3"),attr(a,"class","search-btn svelte-ybzzp3"),attr(l,"class","theme-toggle-btn svelte-ybzzp3"),attr(n,"class","header-content svelte-ybzzp3"),attr(t,"class","main-header svelte-ybzzp3"),toggle_class(t,"dark-theme",e[0]),attr(y,"class","tabs svelte-ybzzp3"),attr(g,"class","sidebar-content svelte-ybzzp3"),attr(f,"class","sidebar svelte-ybzzp3"),toggle_class(f,"dark-theme",e[0]),attr(b,"class","main-content svelte-ybzzp3"),attr(p,"class","app-container svelte-ybzzp3"),toggle_class(p,"dark-theme",e[0])},m(r,v){insert(r,t,v),append(t,n),append(n,s),append(n,i),I.m(n,null),append(n,o),append(n,a),append(n,c),append(n,l),append(l,u),append(n,d),D.m(n,null),insert(r,h,v),insert(r,p,v),append(p,f),append(f,g),append(g,y);for(let e=0;e<F.length;e+=1)F[e]&&F[e].m(y,null);append(p,m),append(p,b),U[w].m(b,null),insert(r,E,v),M&&M.m(r,v),insert(r,k,v),mount_component($,r,v),S=!0,T||(A=[listen(a,"click",e[52]),listen(l,"click",e[45])],T=!0)},p(e,s){if(C===(C=N(e))&&I?I.p(e,s):(I.d(1),I=C(e),I&&(I.c(),I.m(n,o))),(!S||1&s[0])&&R!==(R=e[0]?"☀️":"🌙")&&set_data(u,R),P===(P=B(e))&&D?D.p(e,s):(D.d(1),D=P(e),D&&(D.c(),D.m(n,null))),(!S||1&s[0])&&toggle_class(t,"dark-theme",e[0]),1056&s[0]|8396800&s[1]){let t;for(L=e[10],t=0;t<L.length;t+=1){const n=get_each_context_5(e,L,t);F[t]?F[t].p(n,s):(F[t]=create_each_block_5(n),F[t].c(),F[t].m(y,null))}for(;t<F.length;t+=1)F[t].d(1);F.length=L.length}(!S||1&s[0])&&toggle_class(f,"dark-theme",e[0]);let r=w;w=z(e,s),w===r?U[w].p(e,s):(group_outros(),transition_out(U[r],1,1,()=>{U[r]=null}),check_outros(),_=U[w],_?_.p(e,s):(_=U[w]=O[w](e),_.c()),transition_in(_,1),_.m(b,null)),(!S||1&s[0])&&toggle_class(p,"dark-theme",e[0]),e[13]?M?M.p(e,s):(M=create_if_block(e),M.c(),M.m(k.parentNode,k)):M&&(M.d(1),M=null);const i={};1&s[0]&&(i.isDarkTheme=e[0]),!x&&2048&s[0]&&(x=!0,i.showModal=e[11],add_flush_callback(()=>x=!1)),$.$set(i)},i(e){S||(transition_in(_),transition_in($.$$.fragment,e),S=!0)},o(e){transition_out(_),transition_out($.$$.fragment,e),S=!1},d(e){e&&detach(t),I.d(),D.d(),e&&detach(h),e&&detach(p),destroy_each(F,e),U[w].d(),e&&detach(E),M&&M.d(e),e&&detach(k),destroy_component($,e),T=!1,run_all(A)}}}function truncatePubkey(e){return e?e.slice(0,8)+"..."+e.slice(-8):"unknown"}function truncateContent(e,t=100){return e?e.length>t?e.slice(0,t)+"...":e:""}function formatTimestamp(e){return e?new Date(1e3*e).toLocaleString():""}async function copyEventToClipboard(e,t){try{const n=JSON.stringify(e);await navigator.clipboard.writeText(n);const s=t.target.closest(".copy-json-btn");if(s){const e=s.textContent;s.textContent="✅",s.style.backgroundColor="#4CAF50",setTimeout(()=>{s.textContent=e,s.style.backgroundColor=""},2e3)}}catch(n){console.error("Failed to copy to clipboard:",n);try{const n=document.createElement("textarea");n.value=JSON.stringify(e),document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n);const s=t.target.closest(".copy-json-btn");if(s){const e=s.textContent;s.textContent="✅",s.style.backgroundColor="#4CAF50",setTimeout(()=>{s.textContent=e,s.style.backgroundColor=""},2e3)}}catch(e){console.error("Fallback copy also failed:",e),alert("Failed to copy to clipboard. Please copy manually.")}}}function escapeHtml(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const func_1=e=>"e"===e[0];function instance(e,t,n){let s,r,i,o,a=!1,c=!1,l=!1,u="",d="",h=null,p="",f=null,g=!1,y="export",m=!1,b="",v=[],w=[],_=null,E=new Set,k=!1,$=!0,x=null,S=new Map,T=[],A=0;const R=3e5;let N=!1,C=[],I=!0,B=null,P="",D=null,L=[],F=!1,O="",U="info",z=!1,M=null,K="",H="";const j={0:"ProfileMetadata",1:"TextNote",2:"RecommendRelay",3:"FollowList",4:"EncryptedDirectMessage",5:"EventDeletion",6:"Repost",7:"Reaction",8:"BadgeAward",13:"Seal",14:"PrivateDirectMessage",15:"ReadReceipt",16:"GenericRepost",40:"ChannelCreation",41:"ChannelMetadata",42:"ChannelMessage",43:"ChannelHideMessage",44:"ChannelMuteUser",1021:"Bid",1022:"BidConfirmation",1040:"OpenTimestamps",1059:"GiftWrap",1060:"GiftWrapWithKind4",1063:"FileMetadata",1311:"LiveChatMessage",1517:"BitcoinBlock",1808:"LiveStream",1971:"ProblemTracker",1984:"Reporting",1985:"Label",4550:"CommunityPostApproval",5e3:"JobRequestStart",5999:"JobRequestEnd",6e3:"JobResultStart",6999:"JobResultEnd",7e3:"JobFeedback",9041:"ZapGoal",9734:"ZapRequest",9735:"Zap",9882:"Highlights",1e4:"BlockList",10001:"PinList",10002:"RelayListMetadata",10003:"BookmarkList",10004:"CommunitiesList",10005:"PublicChatsList",10006:"BlockedRelaysList",10007:"SearchRelaysList",10015:"InterestsList",10030:"UserEmojiList",10050:"DMRelaysList",10096:"FileStorageServerList",13004:"JWTBinding",13194:"NWCWalletServiceInfo",19999:"ReplaceableEnd",2e4:"EphemeralStart",21e3:"LightningPubRPC",22242:"ClientAuthentication",23194:"WalletRequest",23195:"WalletResponse",23196:"WalletNotificationNip4",23197:"WalletNotification",24133:"NostrConnect",27235:"HTTPAuth",29999:"EphemeralEnd",3e4:"FollowSets",30001:"GenericLists",30002:"RelaySets",30003:"BookmarkSets",30004:"CurationSets",30008:"ProfileBadges",30009:"BadgeDefinition",30015:"InterestSets",30017:"StallDefinition",30018:"ProductDefinition",30019:"MarketplaceUIUX",30020:"ProductSoldAsAuction",30023:"LongFormContent",30024:"DraftLongFormContent",30030:"EmojiSets"};function V(e){E.has(e)?E.delete(e):E.add(e),n(17,E)}async function q(){console.log("Toggle changed, showOnlyMyEvents:",N);const e=N&&l&&u?[u]:null;await de(!0,e)}async function W(e){if(!l)return void alert("Please log in first");const t=w.find(t=>t.id===e);if(!t)return void alert("Event not found");if("admin"===p||"owner"===p||"write"===p&&t.pubkey&&t.pubkey===u){if(confirm("Are you sure you want to delete this event?"))try{if(!f)throw new Error("Signer not available for signing");const s={kind:5,created_at:Math.floor(Date.now()/1e3),tags:[["e",e]],content:""};console.log("Created delete event template:",s),console.log("User pubkey:",u),console.log("Target event:",t),console.log("Target event pubkey:",t.pubkey);const r=await f.signEvent(s);console.log("Signed delete event:",r),console.log("Signed delete event pubkey:",r.pubkey),console.log("Delete event tags:",r.tags);const i=`wss://${window.location.host}`;try{const e=await publishEventWithAuth(i,r,f,u);e.success?console.log("Delete event published successfully to ORLY relay"):console.error("Failed to publish delete event:",e.reason)}catch(e){console.error("Error publishing delete event:",e)}const o=t.pubkey&&t.pubkey===u;if(o){const t=await nostrClient.publish(r);if(console.log("Delete event published:",t),!(t.success&&t.okCount>0))throw new Error("No relays accepted the delete event");{await new Promise(e=>setTimeout(e,2e3));try{const n=await fetchEventById(e,{timeout:5e3});n?(console.warn("Event still exists after deletion attempt:",n),alert(`Warning: Delete event was accepted by ${t.okCount} relay(s), but the event still exists on the relay. This may indicate the relay does not properly handle delete events.`)):console.log("Event successfully deleted and verified")}catch(e){console.log("Could not fetch event after deletion (likely deleted):",e.message)}try{const t=await fetchDeleteEventsByTarget(e,{timeout:5e3});if(t.length>0){console.log(`Delete event verification: Found ${t.length} delete event(s) targeting ${e}`);const n=t.find(e=>e.pubkey&&e.pubkey===u);n?console.log("Our delete event found in database:",n.id):console.warn("Our delete event not found in database, but other delete events exist")}else console.warn("No delete events found in database for target event:",e)}catch(e){console.log("Could not verify delete event in database:",e.message)}n(7,w=w.filter(t=>t.id!==e)),C=C.filter(t=>t.id!==e),T=T.filter(t=>t.id!==e);for(const[t,n]of S)n.events&&(n.events=n.events.filter(t=>t.id!==e),S.set(t,n));G(),console.log("Reloading events to show delete event...");const s=N&&l&&u?[u]:null;await de(!0,s),alert(`Event deleted successfully (accepted by ${t.okCount} relay(s))`)}}else{const t=`wss://${window.location.host}/`,s=new NostrClient;await s.connectToRelay(t);const i=await s.publish(r);if(console.log("Delete event published to local relay only:",i),!(i.success&&i.okCount>0))throw new Error("Local relay did not accept the delete event");{await new Promise(e=>setTimeout(e,2e3));try{const t=await fetchEventById(e,{timeout:5e3});t?(console.warn("Event still exists after deletion attempt:",t),alert(`Warning: Delete event was accepted by ${i.okCount} relay(s), but the event still exists on the relay. This may indicate the relay does not properly handle delete events.`)):console.log("Event successfully deleted and verified")}catch(e){console.log("Could not fetch event after deletion (likely deleted):",e.message)}try{const t=await fetchDeleteEventsByTarget(e,{timeout:5e3});if(t.length>0){console.log(`Delete event verification: Found ${t.length} delete event(s) targeting ${e}`);const n=t.find(e=>e.pubkey&&e.pubkey===u);n?console.log("Our delete event found in database:",n.id):console.warn("Our delete event not found in database, but other delete events exist")}else console.warn("No delete events found in database for target event:",e)}catch(e){console.log("Could not verify delete event in database:",e.message)}n(7,w=w.filter(t=>t.id!==e)),C=C.filter(t=>t.id!==e),T=T.filter(t=>t.id!==e);for(const[t,n]of S)n.events&&(n.events=n.events.filter(t=>t.id!==e),S.set(t,n));G(),console.log("Reloading events to show delete event...");const t=N&&l&&u?[u]:null;await de(!0,t),alert("Event deleted successfully (local relay only - admin/owner deleting other user's event)")}}}catch(e){console.error("Failed to delete event:",e),alert("Failed to delete event: "+e.message)}}else alert("You do not have permission to delete this event")}if("undefined"!=typeof localStorage){const e=localStorage.getItem("isDarkTheme");null!==e&&(a=JSON.parse(e));const t=localStorage.getItem("nostr_auth_method"),s=localStorage.getItem("nostr_pubkey");t&&s&&(l=!0,u=s,d=t,"extension"===t&&window.nostr&&(f=window.nostr),ce(),le()),function(){if("undefined"==typeof localStorage)return;try{const t=localStorage.getItem("app_state");if(t){const s=JSON.parse(t);s.selectedTab&&te.some(e=>e.id===s.selectedTab)&&n(5,y=s.selectedTab),s.expandedEvents&&n(17,E=new Set(s.expandedEvents)),s.globalEventsCache&&(T=s.globalEventsCache),s.globalCacheTimestamp&&(A=s.globalCacheTimestamp),void 0!==s.hasMoreEvents&&n(19,$=s.hasMoreEvents),s.oldestEventTimestamp&&(x=s.oldestEventTimestamp),void 0!==s.hasMoreMyEvents&&(I=s.hasMoreMyEvents),s.oldestMyEventTimestamp&&(B=s.oldestMyEventTimestamp),T.length>0&&((e=A)&&Date.now()-e<R)&&n(7,w=T)}}catch(e){console.error("Failed to load persistent state:",e)}var e}(),async function(){try{const e=await fetch("/api/sprocket/config",{method:"GET",headers:{"Content-Type":"application/json"}});if(e.ok){const t=await e.json();n(67,z=t.enabled)}}catch(e){console.error("Error loading sprocket config:",e)}}()}function G(){if("undefined"==typeof localStorage)return;const e={selectedTab:y,expandedEvents:Array.from(E),globalEventsCache:T,globalCacheTimestamp:A,hasMoreEvents:$,oldestEventTimestamp:x};localStorage.setItem("app_state",JSON.stringify(e))}function J(e){T=e.sort((e,t)=>t.created_at-e.created_at),A=Date.now(),G()}async function Z(){if(l&&"owner"===p&&z)try{n(23,F=!0);const e=await fetch("/api/sprocket/status",{method:"GET",headers:{Authorization:`Nostr ${await fe("GET","/api/sprocket/status")}`,"Content-Type":"application/json"}});e.ok?n(21,D=await e.json()):ee("Failed to load sprocket status","error")}catch(e){ee(`Error loading sprocket status: ${e.message}`,"error")}finally{n(23,F=!1)}}async function Y(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/versions",{method:"GET",headers:{Authorization:`Nostr ${await fe("GET","/api/sprocket/versions")}`,"Content-Type":"application/json"}});e.ok?n(22,L=await e.json()):ee("Failed to load versions","error")}catch(e){ee(`Error loading versions: ${e.message}`,"error")}finally{n(23,F=!1)}}async function X(e){l&&"owner"===p&&(n(20,P=e.content),ee(`Loaded version: ${e.name}`,"success"))}async function Q(e){if(l&&"owner"===p&&confirm(`Are you sure you want to delete version ${e}?`))try{n(23,F=!0);const t=await fetch("/api/sprocket/delete-version",{method:"POST",headers:{Authorization:`Nostr ${await fe("POST","/api/sprocket/delete-version")}`,"Content-Type":"application/json"},body:JSON.stringify({filename:e})});if(t.ok)ee(`Version ${e} deleted successfully`,"success"),await Y();else{ee(`Failed to delete version: ${await t.text()}`,"error")}}catch(e){ee(`Error deleting version: ${e.message}`,"error")}finally{n(23,F=!1)}}function ee(e,t="info"){n(24,O=e),n(25,U=t),setTimeout(()=>{n(24,O="")},5e3)}const te=[{id:"export",icon:"📤",label:"Export"},{id:"import",icon:"💾",label:"Import",requiresAdmin:!0},{id:"events",icon:"📡",label:"Events"},{id:"compose",icon:"✏️",label:"Compose"},{id:"managed-acl",icon:"🛡️",label:"Managed ACL",requiresOwner:!0},{id:"sprocket",icon:"⚙️",label:"Sprocket",requiresOwner:!0}];function ne(e){n(5,y=e),"sprocket"===e&&l&&"owner"===p&&z&&(Z(),Y()),G()}function se(){n(13,g=!1)}function re(e){n(6,v=v.filter(t=>t.id!==e)),S.delete(e),y===e&&n(5,y="export")}async function ie(e,t,n=!0){const s=S.get(e);if(s&&!s.isLoading){s.isLoading=!0,S.set(e,s);try{const r={limit:n?100:200,until:n?Math.floor(Date.now()/1e3):s.oldestTimestamp};console.log("Loading search results for query:",t,"with options:",r);const i=await searchEvents(t,r);if(console.log("Received search results:",i.length,"events"),s.events=n?i.sort((e,t)=>t.created_at-e.created_at):[...s.events,...i].sort((e,t)=>t.created_at-e.created_at),i.length>0){const e=Math.min(...i.map(e=>e.created_at));(!s.oldestTimestamp||e<s.oldestTimestamp)&&(s.oldestTimestamp=e)}s.hasMore=i.length===(n?100:200),s.isLoading=!1,S.set(e,s)}catch(t){console.error("Failed to load search results:",t),s.isLoading=!1,S.set(e,s),alert("Failed to load search results: "+t.message)}}}function oe(e,t){const{scrollTop:n,scrollHeight:s,clientHeight:r}=e.target;if(s-n-r<100){const e=S.get(t);e&&!e.isLoading&&e.hasMore&&async function(e){const t=v.find(t=>t.id===e);t&&await ie(e,t.query,!1)}(t)}}async function ae(){if(l&&u&&!h)try{console.log("Auto-fetching profile for:",u),await initializeNostrClient(),n(3,h=await fetchUserProfile(u)),console.log("Profile auto-loaded:",h)}catch(e){console.error("Failed to auto-load profile:",e)}}async function ce(){if(l&&u)try{const e=await fetch(`/api/permissions/${u}`);if(e.ok){const t=await e.json();n(4,p=t.permission||""),console.log("User role loaded:",p),console.log("Is owner?","owner"===p)}else console.error("Failed to fetch user role:",e.status),n(4,p="")}catch(e){console.error("Error fetching user role:",e),n(4,p="")}else n(4,p="")}async function le(){try{const e=await fetch("/api/acl-mode");if(e.ok){const t=await e.json();n(9,K=t.acl_mode||""),console.log("ACL mode loaded:",K)}else console.error("Failed to fetch ACL mode:",e.status),n(9,K="")}catch(e){console.error("Error fetching ACL mode:",e),n(9,K="")}}async function ue(e=[]){if(l)if(0!==e.length||"admin"===p||"owner"===p)try{const t=await pe("/api/export","POST"),n=await fetch("/api/export",{method:"POST",headers:{Authorization:t,"Content-Type":"application/json"},body:JSON.stringify({pubkeys:e})});if(!n.ok)throw new Error(`Export failed: ${n.status} ${n.statusText}`);const s=await n.blob(),r=window.URL.createObjectURL(s),i=document.createElement("a");i.href=r;const o=n.headers.get("Content-Disposition");let a="events.jsonl";if(o){const e=o.match(/filename="([^"]+)"/);e&&(a=e[1])}i.download=a,document.body.appendChild(i),i.click(),document.body.removeChild(i),window.URL.revokeObjectURL(r)}catch(e){console.error("Export failed:",e),alert("Export failed: "+e.message)}else alert("Admin or owner permission required to export all events");else alert("Please log in first")}async function de(e=!1,t=null){if(!l||"write"!==p&&"admin"!==p&&"owner"!==p)alert("Write, admin, or owner permission required");else if(!k){n(18,k=!0),e&&(x=null);try{console.log("Loading events with authors filter:",t,"including delete events");const s=await fetchAllEvents({limit:e?100:200,until:e?Math.floor(Date.now()/1e3):x,authors:t});if(console.log("Received events:",s.length,"events"),t&&s.length>0){const e=s.filter(e=>e.pubkey&&e.pubkey!==u);e.length>0&&console.warn("Server returned non-user events:",e.length,"out of",s.length)}if(e?(n(7,w=s.sort((e,t)=>t.created_at-e.created_at)),J(s)):(n(7,w=[...w,...s].sort((e,t)=>t.created_at-e.created_at)),J(w)),s.length>0){const e=Math.min(...s.map(e=>e.created_at));(!x||e<x)&&(x=e)}n(19,$=s.length===(e?1e3:200)),e&&$&&setTimeout(()=>{if("events"===y){const e=document.querySelectorAll(".events-view-content")[0];e&&e.scrollHeight<=e.clientHeight&&he()}},100)}catch(e){console.error("Failed to load events:",e),alert("Failed to load events: "+e.message)}finally{n(18,k=!1)}}}async function he(){await de(!1)}async function pe(e,t){if(!l||!u)throw new Error("Not logged in");const n={kind:27235,created_at:Math.floor(Date.now()/1e3),tags:[["u",window.location.origin+e],["method",t.toUpperCase()]],content:"",pubkey:u};let s;if(f&&"extension"===d)try{s=await f.signEvent(n)}catch(e){throw new Error("Failed to sign with extension: "+e.message)}else{if("nsec"!==d)throw new Error("No valid signer available");n.id="mock-id-"+Date.now(),n.sig="mock-signature-"+Date.now(),s=n}const r=JSON.stringify(s);return`Nostr ${btoa(r)}`}async function fe(e,t){if(!l||!u)throw new Error("Not logged in");const n={kind:27235,created_at:Math.floor(Date.now()/1e3),tags:[["u",window.location.origin+t],["method",e.toUpperCase()]],content:"",pubkey:u};let s;if(f&&"extension"===d)try{s=await f.signEvent(n)}catch(e){throw new Error("Failed to sign with extension: "+e.message)}else{if("nsec"!==d)throw new Error("No valid signer available");n.id="mock-id-"+Date.now(),n.sig="mock-signature-"+Date.now(),s=n}const r=JSON.stringify(s);return btoa(r)}return e.$$.update=()=>{if(390&e.$$.dirty[0]&&n(29,s=(N&&l&&u?w.filter(e=>e.pubkey&&e.pubkey===u):w).sort((e,t)=>t.created_at-e.created_at)),8&e.$$.dirty[0]&&n(28,r=h?.about?escapeHtml(h.about).replace(/\n{2,}/g,"<br>"):""),530&e.$$.dirty[0]|32&e.$$.dirty[2]&&n(68,i=te.filter(e=>!(e.requiresAdmin&&(!l||"admin"!==p&&"owner"!==p))&&(!(e.requiresOwner&&(!l||"owner"!==p))&&(!("sprocket"===e.id&&!z)&&(("managed-acl"!==e.id||"managed"===K)&&("managed-acl"===e.id&&console.log("Managed ACL tab check:",{isLoggedIn:l,userRole:p,requiresOwner:e.requiresOwner,aclMode:K}),!0)))))),64&e.$$.dirty[0]|64&e.$$.dirty[2]&&n(10,o=[...i,...v]),1554&e.$$.dirty[0]|64&e.$$.dirty[2]&&console.log("Tabs debug:",{isLoggedIn:l,userRole:p,aclMode:K,filteredBaseTabs:i.map(e=>e.id),allTabs:o.map(e=>e.id)}),1&e.$$.dirty[0]&&"undefined"!=typeof document&&(a?document.body.classList.add("dark-theme"):document.body.classList.remove("dark-theme")),14&e.$$.dirty[0]&&l&&u&&!h&&ae(),438&e.$$.dirty[0]&&"events"===y&&l&&("write"===p||"admin"===p||"owner"===p)&&0===w.length){de(!0,N&&u?[u]:null)}},[a,l,u,h,p,y,v,w,N,K,o,c,f,g,m,b,_,E,k,$,P,D,L,F,O,U,M,H,r,s,S,function(e){return j[e]||`Kind ${e}`},V,q,W,async function(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/status",{method:"GET",headers:{Authorization:`Nostr ${await fe("GET","/api/sprocket/status")}`,"Content-Type":"application/json"}});if(e.ok){const t=await e.json();n(20,P=t.script_content||""),n(21,D=t),ee("Script loaded successfully","success")}else ee("Failed to load script","error")}catch(e){ee(`Error loading script: ${e.message}`,"error")}finally{n(23,F=!1)}},async function(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/update",{method:"POST",headers:{Authorization:`Nostr ${await fe("POST","/api/sprocket/update")}`,"Content-Type":"text/plain"},body:P});if(e.ok)ee("Script saved and updated successfully","success"),await Z(),await Y();else{ee(`Failed to save script: ${await e.text()}`,"error")}}catch(e){ee(`Error saving script: ${e.message}`,"error")}finally{n(23,F=!1)}},async function(){if(l&&"owner"===p)try{n(23,F=!0);const e=await fetch("/api/sprocket/restart",{method:"POST",headers:{Authorization:`Nostr ${await fe("POST","/api/sprocket/restart")}`,"Content-Type":"application/json"}});if(e.ok)ee("Sprocket restarted successfully","success"),await Z();else{ee(`Failed to restart sprocket: ${await e.text()}`,"error")}}catch(e){ee(`Error restarting sprocket: ${e.message}`,"error")}finally{n(23,F=!1)}},async function(){if(l&&"owner"===p&&confirm("Are you sure you want to delete the sprocket script? This will stop the current process."))try{n(23,F=!0);const e=await fetch("/api/sprocket/update",{method:"POST",headers:{Authorization:`Nostr ${await fe("POST","/api/sprocket/update")}`,"Content-Type":"text/plain"},body:""});if(e.ok)n(20,P=""),ee("Sprocket script deleted successfully","success"),await Z(),await Y();else{ee(`Failed to delete script: ${await e.text()}`,"error")}}catch(e){ee(`Error deleting script: ${e.message}`,"error")}finally{n(23,F=!1)}},Y,X,Q,function(e){n(26,M=e.target.files[0])},async function(){if(l&&"owner"===p&&M)try{n(23,F=!0);const e=await M.text(),t=await fetch("/api/sprocket/update",{method:"POST",headers:{Authorization:`Nostr ${await fe("POST","/api/sprocket/update")}`,"Content-Type":"text/plain"},body:e});if(t.ok)n(20,P=e),ee("Script uploaded and updated successfully","success"),await Z(),await Y();else{ee(`Failed to upload script: ${await t.text()}`,"error")}}catch(e){ee(`Error uploading script: ${e.message}`,"error")}finally{n(23,F=!1),n(26,M=null);const e=document.getElementById("sprocket-upload-file");e&&(e.value="")}},ne,function(){n(0,a=!a),"undefined"!=typeof localStorage&&localStorage.setItem("isDarkTheme",JSON.stringify(a))},function(){l||n(11,c=!0)},async function(e){const{method:t,pubkey:s,privateKey:r,signer:i}=e.detail;n(1,l=!0),n(2,u=s),d=t,n(12,f=i),n(11,c=!1);try{if(await initializeNostrClient(),"extension"===t&&i)nostrClient.setSigner(i);else if("nsec"===t&&r){const e=new NDKPrivateKeySigner(r);nostrClient.setSigner(e)}n(3,h=await fetchUserProfile(s)),console.log("Profile loaded:",h)}catch(e){console.error("Failed to load profile:",e)}await ce(),await le()},function(){n(1,l=!1),n(2,u=""),d="",n(3,h=null),n(4,p=""),n(12,f=null),n(13,g=!1),C=[],n(7,w=[]),T=[],A=0,G(),"undefined"!=typeof localStorage&&(localStorage.removeItem("nostr_auth_method"),localStorage.removeItem("nostr_pubkey"),localStorage.removeItem("nostr_privkey"))},function(){n(11,c=!1)},function(){n(13,g=!0)},se,function(){n(14,m=!m),m||n(15,b="")},function(e){"Enter"===e.key&&b.trim()?(!function(e){const t=`search-${Date.now()}`,s={id:t,icon:"🔍",label:e,isSearchTab:!0,query:e};n(6,v=[...v,s]),n(5,y=t),S.set(t,{events:[],isLoading:!1,hasMore:!0,oldestTimestamp:null}),ie(t,e)}(b.trim()),n(15,b=""),n(14,m=!1)):"Escape"===e.key&&(n(14,m=!1),n(15,b=""))},re,ie,oe,ae,async function(){await ue([])},async function(){await ue([u])},function(e){n(16,_=e.target.files[0])},async function(){if(!l||"admin"!==p&&"owner"!==p)alert("Admin or owner permission required");else if(_)try{const e=await pe("/api/import","POST"),t=new FormData;t.append("file",_);const s=await fetch("/api/import",{method:"POST",headers:{Authorization:e},body:t});if(!s.ok)throw new Error(`Import failed: ${s.status} ${s.statusText}`);await s.json();alert("Import started successfully"),n(16,_=null),document.getElementById("import-file").value=""}catch(e){console.error("Import failed:",e),alert("Import failed: "+e.message)}else alert("Please select a file")},de,function(e){const{scrollTop:t,scrollHeight:n,clientHeight:s}=e.target;n-t-s<100&&he()},function(){try{if(!H.trim())return void alert("Please enter some JSON to reformat");const e=JSON.parse(H);n(27,H=JSON.stringify(e,null,2))}catch(e){alert("Invalid JSON: "+e.message)}},async function(){try{if(!H.trim())return void alert("Please enter an event to sign");if(!l||!u)return void alert("Please log in to sign events");if(!f)return void alert("No signer available. Please log in with a valid authentication method.");const e=JSON.parse(H);e.pubkey=u,e.created_at=Math.floor(Date.now()/1e3),delete e.id,delete e.sig;const t=await f.signEvent(e);n(27,H=JSON.stringify(t,null,2)),alert("Event signed successfully!")}catch(e){console.error("Error signing event:",e),alert("Error signing event: "+e.message)}},async function(){try{if(!H.trim())return void alert("Please enter an event to publish");if(!l)return void alert("Please log in to publish events");if(!f)return void alert("No signer available. Please log in with a valid authentication method.");const e=JSON.parse(H);if(!e.id||!e.sig)return void alert('Event must be signed before publishing. Please click "Sign" first.');const t=`wss://${window.location.host}`,n=await publishEventWithAuth(t,e,f,u);n.success?alert("Event published successfully to ORLY relay!"):alert(`Event publishing failed: ${n.reason||"Unknown error"}`)}catch(e){console.error("Error publishing event:",e),alert("Error publishing event: "+e.message)}},z,i,function(t){bubble.call(this,e,t)},function(t){bubble.call(this,e,t)},e=>e.id===y,function(){b=this.value,n(15,b)},e=>re(e.id),(e,t)=>"Enter"===t.key&&re(e.id),e=>ne(e.id),e=>W(e.id),e=>V(e.id),(e,t)=>"Enter"===t.key&&V(e.id),(e,t)=>copyEventToClipboard(e,t),function(){N=this.checked,n(8,N)},()=>q(),()=>{de(!1,N&&u?[u]:null)},()=>{de(!0,N&&u?[u]:null)},function(){H=this.value,n(27,H)},function(){P=this.value,n(20,P)},e=>X(e),e=>Q(e.name),e=>ie(e.id,e.query,!0),e=>W(e.id),e=>V(e.id),(e,t)=>"Enter"===t.key&&V(e.id),(e,t)=>copyEventToClipboard(e,t),(e,t)=>oe(t,e.id),e=>"Escape"===e.key&&se(),function(e){c=e,n(11,c)}]}class App extends SvelteComponent{constructor(e){super(),init(this,e,instance,create_fragment,safe_not_equal,{},null,[-1,-1,-1,-1,-1])}}const app=new App({target:document.body,props:{name:"world"}});return app}(); |