nostr-components 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/assets/{base-styles-CBypR3FR.js → base-styles-BSEzBDsk.js} +3 -3
  2. package/dist/assets/{base-styles-CBypR3FR.js.map → base-styles-BSEzBDsk.js.map} +1 -1
  3. package/dist/assets/{copy-delegation-C4uvRTVM.js → copy-delegation-B7y2q5Kn.js} +5 -5
  4. package/dist/assets/{copy-delegation-C4uvRTVM.js.map → copy-delegation-B7y2q5Kn.js.map} +1 -1
  5. package/dist/assets/{dialog-likers-BjiCHFan.js → dialog-likers-BqDn2P_3.js} +4 -4
  6. package/dist/assets/{dialog-likers-BjiCHFan.js.map → dialog-likers-BqDn2P_3.js.map} +1 -1
  7. package/dist/assets/{nostr-service-pr_crY62.js → nostr-service-CnaPxjc6.js} +2 -2
  8. package/dist/assets/{nostr-service-pr_crY62.js.map → nostr-service-CnaPxjc6.js.map} +1 -1
  9. package/dist/assets/{nostr-user-component-BOdux8_6.js → nostr-user-component-Cbs97dlK.js} +2 -2
  10. package/dist/assets/{nostr-user-component-BOdux8_6.js.map → nostr-user-component-Cbs97dlK.js.map} +1 -1
  11. package/dist/assets/{pure-jrVhRVpB.js → pure-DPo-pzxM.js} +2 -2
  12. package/dist/assets/{pure-jrVhRVpB.js.map → pure-DPo-pzxM.js.map} +1 -1
  13. package/dist/assets/{theme-C1r1Zw8r.js → theme-BN1Bvweb.js} +2 -2
  14. package/dist/assets/{theme-C1r1Zw8r.js.map → theme-BN1Bvweb.js.map} +1 -1
  15. package/dist/assets/{user-resolver-C-E6KdwY.js → user-resolver-CMmbtY9Y.js} +2 -2
  16. package/dist/assets/{user-resolver-C-E6KdwY.js.map → user-resolver-CMmbtY9Y.js.map} +1 -1
  17. package/dist/assets/{zap-utils-B1sz0Abx.js → zap-utils-KFUD_vTU.js} +2 -2
  18. package/dist/assets/{zap-utils-B1sz0Abx.js.map → zap-utils-KFUD_vTU.js.map} +1 -1
  19. package/dist/components/nostr-comment.es.js +5 -5
  20. package/dist/components/nostr-dm.es.js +2 -2
  21. package/dist/components/nostr-follow-button.es.js +2 -2
  22. package/dist/components/nostr-follow-button.es.js.map +1 -1
  23. package/dist/components/nostr-like.es.js +4 -4
  24. package/dist/components/nostr-live-chat.es.js +3 -3
  25. package/dist/components/nostr-live-chat.es.js.map +1 -1
  26. package/dist/components/nostr-post.es.js +2 -2
  27. package/dist/components/nostr-profile-badge.es.js +3 -3
  28. package/dist/components/nostr-profile.es.js +2 -2
  29. package/dist/components/nostr-zap.es.js +4 -4
  30. package/dist/components/nostr-zap.es.js.map +1 -1
  31. package/dist/index.d.ts +4 -0
  32. package/dist/nostr-components.es.js +1 -1
  33. package/dist/nostr-components.es.js.map +1 -1
  34. package/dist/nostr-components.umd.js +6 -6
  35. package/dist/nostr-components.umd.js.map +1 -1
  36. package/dist/src/index.d.ts +22 -0
  37. package/package.json +1 -1
@@ -72,8 +72,8 @@
72
72
  collection[i].apply(undefined, arguments);
73
73
  }
74
74
  });
75
- })`;{var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}}exports.bakeCollectionVariadic=bakeCollectionVariadic})(bakeCollection);var __spreadArray$1=commonjsGlobal&&commonjsGlobal.__spreadArray||function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))};Object.defineProperty(taskCollection,"__esModule",{value:!0}),taskCollection.TaskCollection=void 0;var utils_1$1=utils$3,bake_collection_1=bakeCollection;function push_norebuild(n,e){var t=this.length;if(t>1)if(e){var r;(r=this._tasks).push.apply(r,arguments),this.length+=arguments.length}else this._tasks.push(n),this.length++;else if(e){if(t===1){var s=Array(1+arguments.length);s.push(s),s.push.apply(s,arguments),this._tasks=s}else{var s=Array(arguments.length);s.push.apply(s,arguments),this._tasks=s}this.length+=arguments.length}else t===1?this._tasks=[this._tasks,n]:this._tasks=n,this.length++}function push_rebuild(n,e){var t=this.length;if(t>1)if(e){var r;(r=this._tasks).push.apply(r,arguments),this.length+=arguments.length}else this._tasks.push(n),this.length++;else if(e){if(t===1){var s=Array(1+arguments.length);s.push(s),s.push.apply(s,arguments),this._tasks=s}else{var s=Array(arguments.length);s.push.apply(s,arguments),this._tasks=s}this.length+=arguments.length}else t===1?this._tasks=[this._tasks,n]:this._tasks=n,this.length++;this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function removeLast_norebuild(n){this.length!==0&&(this.length===1?this._tasks===n&&(this.length=0):((0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(n)),this._tasks.length===1?(this._tasks=this._tasks[0],this.length=1):this.length=this._tasks.length))}function removeLast_rebuild(n){if(this.length!==0){if(this.length===1)if(this._tasks===n&&(this.length=0),this.firstEmitBuildStrategy){this.call=bake_collection_1.BAKED_EMPTY_FUNC;return}else{this.rebuild();return}else(0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(n)),this._tasks.length===1?(this._tasks=this._tasks[0],this.length=1):this.length=this._tasks.length;this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}}function insert_norebuild(n){for(var e,t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.length===0?(this._tasks=t,this.length=1):this.length===1?(t.unshift(this._tasks),this._tasks=t,this.length=this._tasks.length):((e=this._tasks).splice.apply(e,__spreadArray$1([n,0],t,!1)),this.length=this._tasks.length)}function insert_rebuild(n){for(var e,t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.length===0?(this._tasks=t,this.length=1):this.length===1?(t.unshift(this._tasks),this._tasks=t,this.length=this._tasks.length):((e=this._tasks).splice.apply(e,__spreadArray$1([n,0],t,!1)),this.length=this._tasks.length),this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function rebuild_noawait(){this.length===0?this.call=bake_collection_1.BAKED_EMPTY_FUNC:this.length===1?this.call=this._tasks:this.call=(0,bake_collection_1.bakeCollection)(this._tasks,this.argsNum)}function rebuild_await(){this.length===0?this.call=bake_collection_1.BAKED_EMPTY_FUNC:this.length===1?this.call=this._tasks:this.call=(0,bake_collection_1.bakeCollectionAwait)(this._tasks,this.argsNum)}function rebuild_on_first_call(){this.rebuild(),this.call.apply(void 0,arguments)}var TaskCollection=function(){function n(e,t,r,s){t===void 0&&(t=!0),r===void 0&&(r=null),s===void 0&&(s=!1),this.awaitTasks=s,this.call=bake_collection_1.BAKED_EMPTY_FUNC,this.argsNum=e,this.firstEmitBuildStrategy=!0,s?this.rebuild=rebuild_await.bind(this):this.rebuild=rebuild_noawait.bind(this),this.setAutoRebuild(t),r?typeof r=="function"?(this._tasks=r,this.length=1):(this._tasks=r,this.length=r.length):(this._tasks=null,this.length=0),t&&this.rebuild()}return n}();taskCollection.TaskCollection=TaskCollection;function fastClear(){this._tasks=null,this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC}function clear(){this._tasks=null,this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC}function growArgsNum(n){this.argsNum<n&&(this.argsNum=n,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}function setAutoRebuild(n){n?(this.push=push_rebuild.bind(this),this.insert=insert_rebuild.bind(this),this.removeLast=removeLast_rebuild.bind(this)):(this.push=push_norebuild.bind(this),this.insert=insert_norebuild.bind(this),this.removeLast=removeLast_norebuild.bind(this))}function tasksAsArray(){return this.length===0?[]:this.length===1?[this._tasks]:this._tasks}function setTasks(n){n.length===0?(this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC):n.length===1?(this.length=1,this.call=n[0],this._tasks=n[0]):(this.length=n.length,this._tasks=n,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}TaskCollection.prototype.fastClear=fastClear,TaskCollection.prototype.clear=clear,TaskCollection.prototype.growArgsNum=growArgsNum,TaskCollection.prototype.setAutoRebuild=setAutoRebuild,TaskCollection.prototype.tasksAsArray=tasksAsArray,TaskCollection.prototype.setTasks=setTasks,function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,u)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(taskCollection,n)}(taskCollection$1);var utils$2={};Object.defineProperty(utils$2,"__esModule",{value:!0}),utils$2.nullObj=void 0;function nullObj(){var n={};return n.__proto__=null,n}utils$2.nullObj=nullObj;var __spreadArray=commonjsGlobal&&commonjsGlobal.__spreadArray||function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))};Object.defineProperty(ee,"__esModule",{value:!0}),ee.EventEmitter=void 0;var task_collection_1=taskCollection$1,utils_1=utils$3,utils_2=utils$2;function emit(n,e,t,r,s,o){var a=this.events[n];if(a){if(a.length===0)return!1;if(a.argsNum<6)a.call(e,t,r,s,o);else{for(var u=new Array(a.argsNum),c=0,l=u.length;c<l;++c)u[c]=arguments[c+1];a.call.apply(void 0,u)}return!0}return!1}function emitHasOnce(n,e,t,r,s,o){var a=this.events[n],u;if(a!==void 0){if(a.length===0)return!1;if(a.argsNum<6)a.call(e,t,r,s,o);else{u=new Array(a.argsNum);for(var c=0,l=u.length;c<l;++c)u[c]=arguments[c+1];a.call.apply(void 0,u)}}var h=this.onceEvents[n];if(h){if(typeof h=="function")if(this.onceEvents[n]=void 0,arguments.length<6)h(e,t,r,s,o);else{if(u===void 0){u=new Array(arguments.length-1);for(var c=0,l=u.length;c<l;++c)u[c]=arguments[c+1]}h.apply(void 0,u)}else{var f=h;if(this.onceEvents[n]=void 0,arguments.length<6)for(var c=0;c<f.length;++c)f[c](e,t,r,s,o);else{if(u===void 0){u=new Array(arguments.length-1);for(var c=0,l=u.length;c<l;++c)u[c]=arguments[c+1]}for(var c=0;c<f.length;++c)f[c].apply(void 0,u)}}return!0}return a!==void 0}var EventEmitter=function(){function n(){this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set,this.maxListeners=1/0}return Object.defineProperty(n.prototype,"_eventsCount",{get:function(){return this.eventNames().length},enumerable:!1,configurable:!0}),n}();ee.EventEmitter=EventEmitter;function once(n,e){switch(this.emit===emit&&(this.emit=emitHasOnce),typeof this.onceEvents[n]){case"undefined":this.onceEvents[n]=e,typeof n=="symbol"&&this._symbolKeys.add(n);break;case"function":this.onceEvents[n]=[this.onceEvents[n],e];break;case"object":this.onceEvents[n].push(e)}return this}function addListener(n,e,t){if(t===void 0&&(t=e.length),typeof e!="function")throw new TypeError("The listener must be a function");var r=this.events[n];return r?(r.push(e),r.growArgsNum(t),this.maxListeners!==1/0&&this.maxListeners<=r.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" event!'))):(this.events[n]=new task_collection_1.TaskCollection(t,!0,e,!1),typeof n=="symbol"&&this._symbolKeys.add(n)),this}function removeListener(n,e){var t=this.events[n];t&&t.removeLast(e);var r=this.onceEvents[n];return r&&(typeof r=="function"?this.onceEvents[n]=void 0:typeof r=="object"&&(r.length===1&&r[0]===e?this.onceEvents[n]=void 0:(0,utils_1._fast_remove_single)(r,r.lastIndexOf(e)))),this}function addListenerBound(n,e,t,r){t===void 0&&(t=this),r===void 0&&(r=e.length),this.boundFuncs||(this.boundFuncs=new Map);var s=e.bind(t);return this.boundFuncs.set(e,s),this.addListener(n,s,r)}function removeListenerBound(n,e){var t,r,s=(t=this.boundFuncs)===null||t===void 0?void 0:t.get(e);return(r=this.boundFuncs)===null||r===void 0||r.delete(e),this.removeListener(n,s)}function hasListeners(n){return this.events[n]&&!!this.events[n].length}function prependListener(n,e,t){if(t===void 0&&(t=e.length),typeof e!="function")throw new TypeError("The listener must be a function");var r=this.events[n];return!r||!(r instanceof task_collection_1.TaskCollection)?(r=this.events[n]=new task_collection_1.TaskCollection(t,!0,e,!1),typeof n=="symbol"&&this._symbolKeys.add(n)):(r.insert(0,e),r.growArgsNum(t),this.maxListeners!==1/0&&this.maxListeners<=r.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" event!'))),this}function prependOnceListener(n,e){this.emit===emit&&(this.emit=emitHasOnce);var t=this.onceEvents[n];return t?typeof t!="object"?(this.onceEvents[n]=[e,t],typeof n=="symbol"&&this._symbolKeys.add(n)):(t.unshift(e),this.maxListeners!==1/0&&this.maxListeners<=t.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" once event!'))):(this.onceEvents[n]=[e],typeof n=="symbol"&&this._symbolKeys.add(n)),this}function removeAllListeners(n){return n===void 0?(this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set):(this.events[n]=void 0,this.onceEvents[n]=void 0,typeof n=="symbol"&&this._symbolKeys.delete(n)),this}function setMaxListeners(n){return this.maxListeners=n,this}function getMaxListeners(){return this.maxListeners}function listeners(n){return this.emit===emit?this.events[n]?this.events[n].tasksAsArray().slice():[]:this.events[n]&&this.onceEvents[n]?__spreadArray(__spreadArray([],this.events[n].tasksAsArray(),!0),typeof this.onceEvents[n]=="function"?[this.onceEvents[n]]:this.onceEvents[n],!0):this.events[n]?this.events[n].tasksAsArray():this.onceEvents[n]?typeof this.onceEvents[n]=="function"?[this.onceEvents[n]]:this.onceEvents[n]:[]}function eventNames(){var n=this;if(this.emit===emit){var e=Object.keys(this.events);return __spreadArray(__spreadArray([],e,!0),Array.from(this._symbolKeys),!0).filter(function(r){return r in n.events&&n.events[r]&&n.events[r].length})}else{var e=Object.keys(this.events).filter(function(s){return n.events[s]&&n.events[s].length}),t=Object.keys(this.onceEvents).filter(function(s){return n.onceEvents[s]&&n.onceEvents[s].length});return __spreadArray(__spreadArray(__spreadArray([],e,!0),t,!0),Array.from(this._symbolKeys).filter(function(s){return s in n.events&&n.events[s]&&n.events[s].length||s in n.onceEvents&&n.onceEvents[s]&&n.onceEvents[s].length}),!0)}}function listenerCount(n){return this.emit===emit?this.events[n]&&this.events[n].length||0:(this.events[n]&&this.events[n].length||0)+(this.onceEvents[n]&&this.onceEvents[n].length||0)}EventEmitter.prototype.emit=emit,EventEmitter.prototype.on=addListener,EventEmitter.prototype.once=once,EventEmitter.prototype.addListener=addListener,EventEmitter.prototype.removeListener=removeListener,EventEmitter.prototype.addListenerBound=addListenerBound,EventEmitter.prototype.removeListenerBound=removeListenerBound,EventEmitter.prototype.hasListeners=hasListeners,EventEmitter.prototype.prependListener=prependListener,EventEmitter.prototype.prependOnceListener=prependOnceListener,EventEmitter.prototype.off=removeListener,EventEmitter.prototype.removeAllListeners=removeAllListeners,EventEmitter.prototype.setMaxListeners=setMaxListeners,EventEmitter.prototype.getMaxListeners=getMaxListeners,EventEmitter.prototype.listeners=listeners,EventEmitter.prototype.eventNames=eventNames,EventEmitter.prototype.listenerCount=listenerCount,function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,u)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(types,n),t(ee,n)}(lib$1);var browser={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var n=1e3,e=n*60,t=e*60,r=t*24,s=r*7,o=r*365.25;ms=function(h,f){f=f||{};var p=typeof h;if(p==="string"&&h.length>0)return a(h);if(p==="number"&&isFinite(h))return f.long?c(h):u(h);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(h))};function a(h){if(h=String(h),!(h.length>100)){var f=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(h);if(f){var p=parseFloat(f[1]),b=(f[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return p*o;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*r;case"hours":case"hour":case"hrs":case"hr":case"h":return p*t;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function u(h){var f=Math.abs(h);return f>=r?Math.round(h/r)+"d":f>=t?Math.round(h/t)+"h":f>=e?Math.round(h/e)+"m":f>=n?Math.round(h/n)+"s":h+"ms"}function c(h){var f=Math.abs(h);return f>=r?l(h,f,r,"day"):f>=t?l(h,f,t,"hour"):f>=e?l(h,f,e,"minute"):f>=n?l(h,f,n,"second"):h+" ms"}function l(h,f,p,b){var v=f>=p*1.5;return Math.round(h/p)+" "+b+(v?"s":"")}return ms}function setup(n){t.debug=t,t.default=t,t.coerce=c,t.disable=a,t.enable=s,t.enabled=u,t.humanize=requireMs(),t.destroy=l,Object.keys(n).forEach(h=>{t[h]=n[h]}),t.names=[],t.skips=[],t.formatters={};function e(h){let f=0;for(let p=0;p<h.length;p++)f=(f<<5)-f+h.charCodeAt(p),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(h){let f,p=null,b,v;function m(...y){if(!m.enabled)return;const w=m,x=Number(new Date),k=x-(f||x);w.diff=k,w.prev=f,w.curr=x,f=x,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let C=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(R,N)=>{if(R==="%%")return"%";C++;const B=t.formatters[N];if(typeof B=="function"){const O=y[C];R=B.call(w,O),y.splice(C,1),C--}return R}),t.formatArgs.call(w,y),(w.log||t.log).apply(w,y)}return m.namespace=h,m.useColors=t.useColors(),m.color=t.selectColor(h),m.extend=r,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(b!==t.namespaces&&(b=t.namespaces,v=t.enabled(h)),v),set:y=>{p=y}}),typeof t.init=="function"&&t.init(m),m}function r(h,f){const p=t(this.namespace+(typeof f>"u"?":":f)+h);return p.log=this.log,p}function s(h){t.save(h),t.namespaces=h,t.names=[],t.skips=[];const f=(typeof h=="string"?h:"").trim().replace(" ",",").split(",").filter(Boolean);for(const p of f)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function o(h,f){let p=0,b=0,v=-1,m=0;for(;p<h.length;)if(b<f.length&&(f[b]===h[p]||f[b]==="*"))f[b]==="*"?(v=b,m=p,b++):(p++,b++);else if(v!==-1)b=v+1,m++,p=m;else return!1;for(;b<f.length&&f[b]==="*";)b++;return b===f.length}function a(){const h=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),h}function u(h){for(const f of t.skips)if(o(h,f))return!1;for(const f of t.names)if(o(h,f))return!0;return!1}function c(h){return h instanceof Error?h.stack||h.message:h}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}var common=setup;(function(n,e){e.formatArgs=r,e.save=s,e.load=o,e.useColors=t,e.storage=a(),e.destroy=(()=>{let c=!1;return()=>{c||(c=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let c;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+n.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;c.splice(1,0,l,"color: inherit");let h=0,f=0;c[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(h++,p==="%c"&&(f=h))}),c.splice(f,0,l)}e.log=console.debug||console.log||(()=>{});function s(c){try{c?e.storage.setItem("debug",c):e.storage.removeItem("debug")}catch{}}function o(){let c;try{c=e.storage.getItem("debug")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function a(){try{return localStorage}catch{}}n.exports=common(e);const{formatters:u}=n.exports;u.j=function(c){try{return JSON.stringify(c)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(browser,browser.exports);var browserExports=browser.exports;const createDebug5=getDefaultExportFromCjs(browserExports);function number$2(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bytes$2(n,...e){if(!(n instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function hash$1(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$2(n.outputLen),number$2(n.blockLen)}function exists$1(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function output$1(n,e){bytes$2(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const crypto$3=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a$2=n=>n instanceof Uint8Array,createView$2=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),rotr$2=(n,e)=>n<<32-e|n>>>e,isLE$2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$2)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$4(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function toBytes$2(n){if(typeof n=="string"&&(n=utf8ToBytes$4(n)),!u8a$2(n))throw new Error(`expected Uint8Array, got ${typeof n}`);return n}function concatBytes$4(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a$2(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}let Hash$2=class{clone(){return this._cloneInto()}};function wrapConstructor$2(n){const e=r=>n().update(toBytes$2(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes$2(n=32){if(crypto$3&&typeof crypto$3.getRandomValues=="function")return crypto$3.getRandomValues(new Uint8Array(n));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64$2(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),u=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,a,r),n.setUint32(e+l,u,r)}let SHA2$1=class extends Hash$2{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView$2(this.buffer)}update(e){exists$1(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes$2(e);const o=e.length;for(let a=0;a<o;){const u=Math.min(s-this.pos,o-a);if(u===s){const c=createView$2(e);for(;s<=o-a;a+=s)this.process(c,a);continue}r.set(e.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){exists$1(this),output$1(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let f=a;f<s;f++)t[f]=0;setBigUint64$2(r,s-8,BigInt(this.length*8),o),this.process(r,0);const u=createView$2(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)u.setUint32(4*f,h[f],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:u}=this;return e.length=s,e.pos=u,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}};const Chi$2=(n,e,t)=>n&e^~n&t,Maj$2=(n,e,t)=>n&e^n&t^e&t,SHA256_K$2=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV$1=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W$2=new Uint32Array(64);let SHA256$2=class extends SHA2$1{constructor(){super(64,32,8,!1),this.A=IV$1[0]|0,this.B=IV$1[1]|0,this.C=IV$1[2]|0,this.D=IV$1[3]|0,this.E=IV$1[4]|0,this.F=IV$1[5]|0,this.G=IV$1[6]|0,this.H=IV$1[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:u,H:c}=this;return[e,t,r,s,o,a,u,c]}set(e,t,r,s,o,a,u,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=u|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)SHA256_W$2[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){const p=SHA256_W$2[f-15],b=SHA256_W$2[f-2],v=rotr$2(p,7)^rotr$2(p,18)^p>>>3,m=rotr$2(b,17)^rotr$2(b,19)^b>>>10;SHA256_W$2[f]=m+SHA256_W$2[f-7]+v+SHA256_W$2[f-16]|0}let{A:r,B:s,C:o,D:a,E:u,F:c,G:l,H:h}=this;for(let f=0;f<64;f++){const p=rotr$2(u,6)^rotr$2(u,11)^rotr$2(u,25),b=h+p+Chi$2(u,c,l)+SHA256_K$2[f]+SHA256_W$2[f]|0,m=(rotr$2(r,2)^rotr$2(r,13)^rotr$2(r,22))+Maj$2(r,s,o)|0;h=l,l=c,c=u,u=a+b|0,a=o,o=s,s=r,r=b+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(r,s,o,a,u,c,l,h)}roundClean(){SHA256_W$2.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const sha256$2=wrapConstructor$2(()=>new SHA256$2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$9=BigInt(0),_1n$9=BigInt(1),_2n$5=BigInt(2),u8a$1=n=>n instanceof Uint8Array,hexes$3=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$3(n){if(!u8a$1(n))throw new Error("Uint8Array expected");let e="";for(let t=0;t<n.length;t++)e+=hexes$3[n[t]];return e}function numberToHexUnpadded$1(n){const e=n.toString(16);return e.length&1?`0${e}`:e}function hexToNumber$1(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return BigInt(n===""?"0":`0x${n}`)}function hexToBytes$3(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let r=0;r<t.length;r++){const s=r*2,o=n.slice(s,s+2),a=Number.parseInt(o,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[r]=a}return t}function bytesToNumberBE$1(n){return hexToNumber$1(bytesToHex$3(n))}function bytesToNumberLE$1(n){if(!u8a$1(n))throw new Error("Uint8Array expected");return hexToNumber$1(bytesToHex$3(Uint8Array.from(n).reverse()))}function numberToBytesBE$1(n,e){return hexToBytes$3(n.toString(16).padStart(e*2,"0"))}function numberToBytesLE$1(n,e){return numberToBytesBE$1(n,e).reverse()}function numberToVarBytesBE$1(n){return hexToBytes$3(numberToHexUnpadded$1(n))}function ensureBytes$1(n,e,t){let r;if(typeof e=="string")try{r=hexToBytes$3(e)}catch(o){throw new Error(`${n} must be valid hex string, got "${e}". Cause: ${o}`)}else if(u8a$1(e))r=Uint8Array.from(e);else throw new Error(`${n} must be hex string or Uint8Array`);const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(`${n} expected ${t} bytes, got ${s}`);return r}function concatBytes$3(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a$1(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}function equalBytes$2(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function utf8ToBytes$3(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function bitLen$1(n){let e;for(e=0;n>_0n$9;n>>=_1n$9,e+=1);return e}function bitGet$1(n,e){return n>>BigInt(e)&_1n$9}const bitSet$1=(n,e,t)=>n|(t?_1n$9:_0n$9)<<BigInt(e),bitMask$1=n=>(_2n$5<<BigInt(n-1))-_1n$9,u8n$1=n=>new Uint8Array(n),u8fr$1=n=>Uint8Array.from(n);function createHmacDrbg$1(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=u8n$1(n),s=u8n$1(n),o=0;const a=()=>{r.fill(1),s.fill(0),o=0},u=(...f)=>t(s,r,...f),c=(f=u8n$1())=>{s=u(u8fr$1([0]),f),r=u(),f.length!==0&&(s=u(u8fr$1([1]),f),r=u())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){r=u();const b=r.slice();p.push(b),f+=r.length}return concatBytes$3(...p)};return(f,p)=>{a(),c(f);let b;for(;!(b=p(l()));)c();return a(),b}}const validatorFns$1={bigint:n=>typeof n=="bigint",function:n=>typeof n=="function",boolean:n=>typeof n=="boolean",string:n=>typeof n=="string",stringOrUint8Array:n=>typeof n=="string"||n instanceof Uint8Array,isSafeInteger:n=>Number.isSafeInteger(n),array:n=>Array.isArray(n),field:(n,e)=>e.Fp.isValid(n),hash:n=>typeof n=="function"&&Number.isSafeInteger(n.outputLen)};function validateObject$1(n,e,t={}){const r=(s,o,a)=>{const u=validatorFns$1[o];if(typeof u!="function")throw new Error(`Invalid validator "${o}", expected function`);const c=n[s];if(!(a&&c===void 0)&&!u(c,n))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${o}`)};for(const[s,o]of Object.entries(e))r(s,o,!1);for(const[s,o]of Object.entries(t))r(s,o,!0);return n}const ut$1=Object.freeze(Object.defineProperty({__proto__:null,bitGet:bitGet$1,bitLen:bitLen$1,bitMask:bitMask$1,bitSet:bitSet$1,bytesToHex:bytesToHex$3,bytesToNumberBE:bytesToNumberBE$1,bytesToNumberLE:bytesToNumberLE$1,concatBytes:concatBytes$3,createHmacDrbg:createHmacDrbg$1,ensureBytes:ensureBytes$1,equalBytes:equalBytes$2,hexToBytes:hexToBytes$3,hexToNumber:hexToNumber$1,numberToBytesBE:numberToBytesBE$1,numberToBytesLE:numberToBytesLE$1,numberToHexUnpadded:numberToHexUnpadded$1,numberToVarBytesBE:numberToVarBytesBE$1,utf8ToBytes:utf8ToBytes$3,validateObject:validateObject$1},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$8=BigInt(0),_1n$8=BigInt(1),_2n$4=BigInt(2),_3n$3=BigInt(3),_4n$1=BigInt(4),_5n$1=BigInt(5),_8n$1=BigInt(8);BigInt(9),BigInt(16);function mod$1(n,e){const t=n%e;return t>=_0n$8?t:e+t}function pow$1(n,e,t){if(t<=_0n$8||e<_0n$8)throw new Error("Expected power/modulo > 0");if(t===_1n$8)return _0n$8;let r=_1n$8;for(;e>_0n$8;)e&_1n$8&&(r=r*n%t),n=n*n%t,e>>=_1n$8;return r}function pow2$1(n,e,t){let r=n;for(;e-- >_0n$8;)r*=r,r%=t;return r}function invert$1(n,e){if(n===_0n$8||e<=_0n$8)throw new Error(`invert: expected positive integers, got n=${n} mod=${e}`);let t=mod$1(n,e),r=e,s=_0n$8,o=_1n$8;for(;t!==_0n$8;){const u=r/t,c=r%t,l=s-o*u;r=t,t=c,s=o,o=l}if(r!==_1n$8)throw new Error("invert: does not exist");return mod$1(s,e)}function tonelliShanks$1(n){const e=(n-_1n$8)/_2n$4;let t,r,s;for(t=n-_1n$8,r=0;t%_2n$4===_0n$8;t/=_2n$4,r++);for(s=_2n$4;s<n&&pow$1(s,e,n)!==n-_1n$8;s++);if(r===1){const a=(n+_1n$8)/_4n$1;return function(c,l){const h=c.pow(l,a);if(!c.eql(c.sqr(h),l))throw new Error("Cannot find square root");return h}}const o=(t+_1n$8)/_2n$4;return function(u,c){if(u.pow(c,e)===u.neg(u.ONE))throw new Error("Cannot find square root");let l=r,h=u.pow(u.mul(u.ONE,s),t),f=u.pow(c,o),p=u.pow(c,t);for(;!u.eql(p,u.ONE);){if(u.eql(p,u.ZERO))return u.ZERO;let b=1;for(let m=u.sqr(p);b<l&&!u.eql(m,u.ONE);b++)m=u.sqr(m);const v=u.pow(h,_1n$8<<BigInt(l-b-1));h=u.sqr(v),f=u.mul(f,v),p=u.mul(p,h),l=b}return f}}function FpSqrt$1(n){if(n%_4n$1===_3n$3){const e=(n+_1n$8)/_4n$1;return function(r,s){const o=r.pow(s,e);if(!r.eql(r.sqr(o),s))throw new Error("Cannot find square root");return o}}if(n%_8n$1===_5n$1){const e=(n-_5n$1)/_8n$1;return function(r,s){const o=r.mul(s,_2n$4),a=r.pow(o,e),u=r.mul(s,a),c=r.mul(r.mul(u,_2n$4),a),l=r.mul(u,r.sub(c,r.ONE));if(!r.eql(r.sqr(l),s))throw new Error("Cannot find square root");return l}}return tonelliShanks$1(n)}const FIELD_FIELDS$1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField$1(n){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=FIELD_FIELDS$1.reduce((r,s)=>(r[s]="function",r),e);return validateObject$1(n,t)}function FpPow$1(n,e,t){if(t<_0n$8)throw new Error("Expected power > 0");if(t===_0n$8)return n.ONE;if(t===_1n$8)return e;let r=n.ONE,s=e;for(;t>_0n$8;)t&_1n$8&&(r=n.mul(r,s)),s=n.sqr(s),t>>=_1n$8;return r}function FpInvertBatch$1(n,e){const t=new Array(e.length),r=e.reduce((o,a,u)=>n.is0(a)?o:(t[u]=o,n.mul(o,a)),n.ONE),s=n.inv(r);return e.reduceRight((o,a,u)=>n.is0(a)?o:(t[u]=n.mul(o,t[u]),n.mul(o,a)),s),t}function nLength$1(n,e){const t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Field$1(n,e,t=!1,r={}){if(n<=_0n$8)throw new Error(`Expected Field ORDER > 0, got ${n}`);const{nBitLength:s,nByteLength:o}=nLength$1(n,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const a=FpSqrt$1(n),u=Object.freeze({ORDER:n,BITS:s,BYTES:o,MASK:bitMask$1(s),ZERO:_0n$8,ONE:_1n$8,create:c=>mod$1(c,n),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return _0n$8<=c&&c<n},is0:c=>c===_0n$8,isOdd:c=>(c&_1n$8)===_1n$8,neg:c=>mod$1(-c,n),eql:(c,l)=>c===l,sqr:c=>mod$1(c*c,n),add:(c,l)=>mod$1(c+l,n),sub:(c,l)=>mod$1(c-l,n),mul:(c,l)=>mod$1(c*l,n),pow:(c,l)=>FpPow$1(u,c,l),div:(c,l)=>mod$1(c*invert$1(l,n),n),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>invert$1(c,n),sqrt:r.sqrt||(c=>a(u,c)),invertBatch:c=>FpInvertBatch$1(u,c),cmov:(c,l,h)=>h?l:c,toBytes:c=>t?numberToBytesLE$1(c,o):numberToBytesBE$1(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return t?bytesToNumberLE$1(c):bytesToNumberBE$1(c)}});return Object.freeze(u)}function getFieldBytesLength$1(n){if(typeof n!="bigint")throw new Error("field order must be bigint");const e=n.toString(2).length;return Math.ceil(e/8)}function getMinHashLength$1(n){const e=getFieldBytesLength$1(n);return e+Math.ceil(e/2)}function mapHashToField$1(n,e,t=!1){const r=n.length,s=getFieldBytesLength$1(e),o=getMinHashLength$1(e);if(r<16||r<o||r>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${r}`);const a=t?bytesToNumberBE$1(n):bytesToNumberLE$1(n),u=mod$1(a,e-_1n$8)+_1n$8;return t?numberToBytesLE$1(u,s):numberToBytesBE$1(u,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$7=BigInt(0),_1n$7=BigInt(1);function wNAF$1(n,e){const t=(s,o)=>{const a=o.negate();return s?a:o},r=s=>{const o=Math.ceil(e/s)+1,a=2**(s-1);return{windows:o,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,o){let a=n.ZERO,u=s;for(;o>_0n$7;)o&_1n$7&&(a=a.add(u)),u=u.double(),o>>=_1n$7;return a},precomputeWindow(s,o){const{windows:a,windowSize:u}=r(o),c=[];let l=s,h=l;for(let f=0;f<a;f++){h=l,c.push(h);for(let p=1;p<u;p++)h=h.add(l),c.push(h);l=h.double()}return c},wNAF(s,o,a){const{windows:u,windowSize:c}=r(s);let l=n.ZERO,h=n.BASE;const f=BigInt(2**s-1),p=2**s,b=BigInt(s);for(let v=0;v<u;v++){const m=v*c;let y=Number(a&f);a>>=b,y>c&&(y-=p,a+=_1n$7);const w=m,x=m+Math.abs(y)-1,k=v%2!==0,C=y<0;y===0?h=h.add(t(k,o[w])):l=l.add(t(C,o[x]))}return{p:l,f:h}},wNAFCached(s,o,a,u){const c=s._WINDOW_SIZE||1;let l=o.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&o.set(s,u(l))),this.wNAF(c,l,a)}}}function validateBasic$1(n){return validateField$1(n.Fp),validateObject$1(n,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength$1(n.n,n.nBitLength),...n,p:n.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts$1(n){const e=validateBasic$1(n);validateObject$1(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=e;if(t){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:b2n$1,hexToBytes:h2b$1}=ut$1,DER$1={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(n){const{Err:e}=DER$1;if(n.length<2||n[0]!==2)throw new e("Invalid signature integer tag");const t=n[1],r=n.subarray(2,t+2);if(!t||r.length!==t)throw new e("Invalid signature integer: wrong length");if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:b2n$1(r),l:n.subarray(t+2)}},toSig(n){const{Err:e}=DER$1,t=typeof n=="string"?h2b$1(n):n;if(!(t instanceof Uint8Array))throw new Error("ui8a expected");let r=t.length;if(r<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:s,l:o}=DER$1._parseInt(t.subarray(2)),{d:a,l:u}=DER$1._parseInt(o);if(u.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:a}},hexFromSig(n){const e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{const h=l.toString(16);return h.length&1?`0${h}`:h},r=e(t(n.s)),s=e(t(n.r)),o=r.length/2,a=s.length/2,u=t(o),c=t(a);return`30${t(a+o+4)}02${c}${s}02${u}${r}`}},_0n$6=BigInt(0),_1n$6=BigInt(1);BigInt(2);const _3n$2=BigInt(3);BigInt(4);function weierstrassPoints$1(n){const e=validatePointOpts$1(n),{Fp:t}=e,r=e.toBytes||((v,m,y)=>{const w=m.toAffine();return concatBytes$3(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),s=e.fromBytes||(v=>{const m=v.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),w=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:w}});function o(v){const{a:m,b:y}=e,w=t.sqr(v),x=t.mul(w,v);return t.add(t.add(x,t.mul(v,m)),y)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(v){return typeof v=="bigint"&&_0n$6<v&&v<e.n}function u(v){if(!a(v))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(v){const{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:w,n:x}=e;if(m&&typeof v!="bigint"){if(v instanceof Uint8Array&&(v=bytesToHex$3(v)),typeof v!="string"||!m.includes(v.length))throw new Error("Invalid key");v=v.padStart(y*2,"0")}let k;try{k=typeof v=="bigint"?v:bytesToNumberBE$1(ensureBytes$1("private key",v,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof v}`)}return w&&(k=mod$1(k,x)),u(k),k}const l=new Map;function h(v){if(!(v instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(m,y,w){if(this.px=m,this.py=y,this.pz=w,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(m){const{x:y,y:w}=m||{};if(!m||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(m instanceof f)throw new Error("projective point not allowed");const x=k=>t.eql(k,t.ZERO);return x(y)&&x(w)?f.ZERO:new f(y,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const y=t.invertBatch(m.map(w=>w.pz));return m.map((w,x)=>w.toAffine(y[x])).map(f.fromAffine)}static fromHex(m){const y=f.fromAffine(s(ensureBytes$1("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return f.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");const w=t.sqr(y),x=o(m);if(!t.eql(w,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){h(m);const{px:y,py:w,pz:x}=this,{px:k,py:C,pz:P}=m,R=t.eql(t.mul(y,P),t.mul(k,x)),N=t.eql(t.mul(w,P),t.mul(C,x));return R&&N}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){const{a:m,b:y}=e,w=t.mul(y,_3n$2),{px:x,py:k,pz:C}=this;let P=t.ZERO,R=t.ZERO,N=t.ZERO,B=t.mul(x,x),O=t.mul(k,k),H=t.mul(C,C),S=t.mul(x,k);return S=t.add(S,S),N=t.mul(x,C),N=t.add(N,N),P=t.mul(m,N),R=t.mul(w,H),R=t.add(P,R),P=t.sub(O,R),R=t.add(O,R),R=t.mul(P,R),P=t.mul(S,P),N=t.mul(w,N),H=t.mul(m,H),S=t.sub(B,H),S=t.mul(m,S),S=t.add(S,N),N=t.add(B,B),B=t.add(N,B),B=t.add(B,H),B=t.mul(B,S),R=t.add(R,B),H=t.mul(k,C),H=t.add(H,H),B=t.mul(H,S),P=t.sub(P,B),N=t.mul(H,O),N=t.add(N,N),N=t.add(N,N),new f(P,R,N)}add(m){h(m);const{px:y,py:w,pz:x}=this,{px:k,py:C,pz:P}=m;let R=t.ZERO,N=t.ZERO,B=t.ZERO;const O=e.a,H=t.mul(e.b,_3n$2);let S=t.mul(y,k),_=t.mul(w,C),L=t.mul(x,P),I=t.add(y,w),A=t.add(k,C);I=t.mul(I,A),A=t.add(S,_),I=t.sub(I,A),A=t.add(y,x);let E=t.add(k,P);return A=t.mul(A,E),E=t.add(S,L),A=t.sub(A,E),E=t.add(w,x),R=t.add(C,P),E=t.mul(E,R),R=t.add(_,L),E=t.sub(E,R),B=t.mul(O,A),R=t.mul(H,L),B=t.add(R,B),R=t.sub(_,B),B=t.add(_,B),N=t.mul(R,B),_=t.add(S,S),_=t.add(_,S),L=t.mul(O,L),A=t.mul(H,A),_=t.add(_,L),L=t.sub(S,L),L=t.mul(O,L),A=t.add(A,L),S=t.mul(_,A),N=t.add(N,S),S=t.mul(E,A),R=t.mul(I,R),R=t.sub(R,S),S=t.mul(I,_),B=t.mul(E,B),B=t.add(B,S),new f(R,N,B)}subtract(m){return this.add(m.negate())}is0(){return this.equals(f.ZERO)}wNAF(m){return b.wNAFCached(this,l,m,y=>{const w=t.invertBatch(y.map(x=>x.pz));return y.map((x,k)=>x.toAffine(w[k])).map(f.fromAffine)})}multiplyUnsafe(m){const y=f.ZERO;if(m===_0n$6)return y;if(u(m),m===_1n$6)return this;const{endo:w}=e;if(!w)return b.unsafeLadder(this,m);let{k1neg:x,k1:k,k2neg:C,k2:P}=w.splitScalar(m),R=y,N=y,B=this;for(;k>_0n$6||P>_0n$6;)k&_1n$6&&(R=R.add(B)),P&_1n$6&&(N=N.add(B)),B=B.double(),k>>=_1n$6,P>>=_1n$6;return x&&(R=R.negate()),C&&(N=N.negate()),N=new f(t.mul(N.px,w.beta),N.py,N.pz),R.add(N)}multiply(m){u(m);let y=m,w,x;const{endo:k}=e;if(k){const{k1neg:C,k1:P,k2neg:R,k2:N}=k.splitScalar(y);let{p:B,f:O}=this.wNAF(P),{p:H,f:S}=this.wNAF(N);B=b.constTimeNegate(C,B),H=b.constTimeNegate(R,H),H=new f(t.mul(H.px,k.beta),H.py,H.pz),w=B.add(H),x=O.add(S)}else{const{p:C,f:P}=this.wNAF(y);w=C,x=P}return f.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(m,y,w){const x=f.BASE,k=(P,R)=>R===_0n$6||R===_1n$6||!P.equals(x)?P.multiplyUnsafe(R):P.multiply(R),C=k(this,y).add(k(m,w));return C.is0()?void 0:C}toAffine(m){const{px:y,py:w,pz:x}=this,k=this.is0();m==null&&(m=k?t.ONE:t.inv(x));const C=t.mul(y,m),P=t.mul(w,m),R=t.mul(x,m);if(k)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x:C,y:P}}isTorsionFree(){const{h:m,isTorsionFree:y}=e;if(m===_1n$6)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:y}=e;return m===_1n$6?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),r(f,this,m)}toHex(m=!0){return bytesToHex$3(this.toRawBytes(m))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);const p=e.nBitLength,b=wNAF$1(f,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function validateOpts$1(n){const e=validateBasic$1(n);return validateObject$1(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function weierstrass$1(n){const e=validateOpts$1(n),{Fp:t,n:r}=e,s=t.BYTES+1,o=2*t.BYTES+1;function a(A){return _0n$6<A&&A<t.ORDER}function u(A){return mod$1(A,r)}function c(A){return invert$1(A,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=weierstrassPoints$1({...e,toBytes(A,E,$){const M=E.toAffine(),U=t.toBytes(M.x),z=concatBytes$3;return $?z(Uint8Array.from([E.hasEvenY()?2:3]),U):z(Uint8Array.from([4]),U,t.toBytes(M.y))},fromBytes(A){const E=A.length,$=A[0],M=A.subarray(1);if(E===s&&($===2||$===3)){const U=bytesToNumberBE$1(M);if(!a(U))throw new Error("Point is not on curve");const z=f(U);let D=t.sqrt(z);const V=(D&_1n$6)===_1n$6;return($&1)===1!==V&&(D=t.neg(D)),{x:U,y:D}}else if(E===o&&$===4){const U=t.fromBytes(M.subarray(0,t.BYTES)),z=t.fromBytes(M.subarray(t.BYTES,2*t.BYTES));return{x:U,y:z}}else throw new Error(`Point of length ${E} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}}),b=A=>bytesToHex$3(numberToBytesBE$1(A,e.nByteLength));function v(A){const E=r>>_1n$6;return A>E}function m(A){return v(A)?u(-A):A}const y=(A,E,$)=>bytesToNumberBE$1(A.slice(E,$));class w{constructor(E,$,M){this.r=E,this.s=$,this.recovery=M,this.assertValidity()}static fromCompact(E){const $=e.nByteLength;return E=ensureBytes$1("compactSignature",E,$*2),new w(y(E,0,$),y(E,$,2*$))}static fromDER(E){const{r:$,s:M}=DER$1.toSig(ensureBytes$1("DER",E));return new w($,M)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(E){return new w(this.r,this.s,E)}recoverPublicKey(E){const{r:$,s:M,recovery:U}=this,z=N(ensureBytes$1("msgHash",E));if(U==null||![0,1,2,3].includes(U))throw new Error("recovery id invalid");const D=U===2||U===3?$+e.n:$;if(D>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const V=U&1?"03":"02",W=l.fromHex(V+b(D)),Z=c(D),G=u(-z*Z),K=u(M*Z),ne=l.BASE.multiplyAndAddUnsafe(W,G,K);if(!ne)throw new Error("point at infinify");return ne.assertValidity(),ne}hasHighS(){return v(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,u(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes$3(this.toDERHex())}toDERHex(){return DER$1.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes$3(this.toCompactHex())}toCompactHex(){return b(this.r)+b(this.s)}}const x={isValidPrivateKey(A){try{return h(A),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const A=getMinHashLength$1(e.n);return mapHashToField$1(e.randomBytes(A),e.n)},precompute(A=8,E=l.BASE){return E._setWindowSize(A),E.multiply(BigInt(3)),E}};function k(A,E=!0){return l.fromPrivateKey(A).toRawBytes(E)}function C(A){const E=A instanceof Uint8Array,$=typeof A=="string",M=(E||$)&&A.length;return E?M===s||M===o:$?M===2*s||M===2*o:A instanceof l}function P(A,E,$=!0){if(C(A))throw new Error("first arg must be private key");if(!C(E))throw new Error("second arg must be public key");return l.fromHex(E).multiply(h(A)).toRawBytes($)}const R=e.bits2int||function(A){const E=bytesToNumberBE$1(A),$=A.length*8-e.nBitLength;return $>0?E>>BigInt($):E},N=e.bits2int_modN||function(A){return u(R(A))},B=bitMask$1(e.nBitLength);function O(A){if(typeof A!="bigint")throw new Error("bigint expected");if(!(_0n$6<=A&&A<B))throw new Error(`bigint expected < 2^${e.nBitLength}`);return numberToBytesBE$1(A,e.nByteLength)}function H(A,E,$=S){if(["recovered","canonical"].some(se=>se in $))throw new Error("sign() legacy options not supported");const{hash:M,randomBytes:U}=e;let{lowS:z,prehash:D,extraEntropy:V}=$;z==null&&(z=!0),A=ensureBytes$1("msgHash",A),D&&(A=ensureBytes$1("prehashed msgHash",M(A)));const W=N(A),Z=h(E),G=[O(Z),O(W)];if(V!=null){const se=V===!0?U(t.BYTES):V;G.push(ensureBytes$1("extraEntropy",se))}const K=concatBytes$3(...G),ne=W;function ae(se){const pe=R(se);if(!p(pe))return;const ye=c(pe),J=l.BASE.multiply(pe).toAffine(),Q=u(J.x);if(Q===_0n$6)return;const te=u(ye*u(ne+Q*Z));if(te===_0n$6)return;let be=(J.x===Q?0:2)|Number(J.y&_1n$6),Be=te;return z&&v(te)&&(Be=m(te),be^=1),new w(Q,Be,be)}return{seed:K,k2sig:ae}}const S={lowS:e.lowS,prehash:!1},_={lowS:e.lowS,prehash:!1};function L(A,E,$=S){const{seed:M,k2sig:U}=H(A,E,$),z=e;return createHmacDrbg$1(z.hash.outputLen,z.nByteLength,z.hmac)(M,U)}l.BASE._setWindowSize(8);function I(A,E,$,M=_){var J;const U=A;if(E=ensureBytes$1("msgHash",E),$=ensureBytes$1("publicKey",$),"strict"in M)throw new Error("options.strict was renamed to lowS");const{lowS:z,prehash:D}=M;let V,W;try{if(typeof U=="string"||U instanceof Uint8Array)try{V=w.fromDER(U)}catch(Q){if(!(Q instanceof DER$1.Err))throw Q;V=w.fromCompact(U)}else if(typeof U=="object"&&typeof U.r=="bigint"&&typeof U.s=="bigint"){const{r:Q,s:te}=U;V=new w(Q,te)}else throw new Error("PARSE");W=l.fromHex($)}catch(Q){if(Q.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(z&&V.hasHighS())return!1;D&&(E=e.hash(E));const{r:Z,s:G}=V,K=N(E),ne=c(G),ae=u(K*ne),se=u(Z*ne),pe=(J=l.BASE.multiplyAndAddUnsafe(W,ae,se))==null?void 0:J.toAffine();return pe?u(pe.x)===Z:!1}return{CURVE:e,getPublicKey:k,getSharedSecret:P,sign:L,verify:I,ProjectivePoint:l,Signature:w,utils:x}}let HMAC$2=class extends Hash$2{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,hash$1(e);const r=toBytes$2(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return exists$1(this),this.iHash.update(e),this}digestInto(e){exists$1(this),bytes$2(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=u,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$2=(n,e,t)=>new HMAC$2(n,e).update(t).digest();hmac$2.create=(n,e)=>new HMAC$2(n,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash$1(n){return{hash:n,hmac:(e,...t)=>hmac$2(n,e,concatBytes$4(...t)),randomBytes:randomBytes$2}}function createCurve$1(n,e){const t=r=>weierstrass$1({...n,...getHash$1(r)});return Object.freeze({...t(e),create:t})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P$1=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N$1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n$5=BigInt(1),_2n$3=BigInt(2),divNearest$1=(n,e)=>(n+e/_2n$3)/e;function sqrtMod$1(n){const e=secp256k1P$1,t=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),a=BigInt(23),u=BigInt(44),c=BigInt(88),l=n*n*n%e,h=l*l*n%e,f=pow2$1(h,t,e)*h%e,p=pow2$1(f,t,e)*h%e,b=pow2$1(p,_2n$3,e)*l%e,v=pow2$1(b,s,e)*b%e,m=pow2$1(v,o,e)*v%e,y=pow2$1(m,u,e)*m%e,w=pow2$1(y,c,e)*y%e,x=pow2$1(w,u,e)*m%e,k=pow2$1(x,t,e)*h%e,C=pow2$1(k,a,e)*v%e,P=pow2$1(C,r,e)*l%e,R=pow2$1(P,_2n$3,e);if(!Fp.eql(Fp.sqr(R),n))throw new Error("Cannot find square root");return R}const Fp=Field$1(secp256k1P$1,void 0,void 0,{sqrt:sqrtMod$1}),secp256k1$1=createCurve$1({a:BigInt(0),b:BigInt(7),Fp,n:secp256k1N$1,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:n=>{const e=secp256k1N$1,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-_1n$5*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,a=BigInt("0x100000000000000000000000000000000"),u=divNearest$1(o*n,e),c=divNearest$1(-r*n,e);let l=mod$1(n-u*t-c*s,e),h=mod$1(-u*r-c*o,e);const f=l>a,p=h>a;if(f&&(l=e-l),p&&(h=e-h),l>a||h>a)throw new Error("splitScalar: Endomorphism failed, k="+n);return{k1neg:f,k1:l,k2neg:p,k2:h}}}},sha256$2),_0n$5=BigInt(0),fe=n=>typeof n=="bigint"&&_0n$5<n&&n<secp256k1P$1,ge=n=>typeof n=="bigint"&&_0n$5<n&&n<secp256k1N$1,TAGGED_HASH_PREFIXES$1={};function taggedHash$1(n,...e){let t=TAGGED_HASH_PREFIXES$1[n];if(t===void 0){const r=sha256$2(Uint8Array.from(n,s=>s.charCodeAt(0)));t=concatBytes$3(r,r),TAGGED_HASH_PREFIXES$1[n]=t}return sha256$2(concatBytes$3(t,...e))}const pointToBytes$1=n=>n.toRawBytes(!0).slice(1),numTo32b$1=n=>numberToBytesBE$1(n,32),modP$1=n=>mod$1(n,secp256k1P$1),modN$1=n=>mod$1(n,secp256k1N$1),Point$1=secp256k1$1.ProjectivePoint,GmulAdd$1=(n,e,t)=>Point$1.BASE.multiplyAndAddUnsafe(n,e,t);function schnorrGetExtPubKey$1(n){let e=secp256k1$1.utils.normPrivateKeyToScalar(n),t=Point$1.fromPrivateKey(e);return{scalar:t.hasEvenY()?e:modN$1(-e),bytes:pointToBytes$1(t)}}function lift_x$1(n){if(!fe(n))throw new Error("bad x: need 0 < x < p");const e=modP$1(n*n),t=modP$1(e*n+BigInt(7));let r=sqrtMod$1(t);r%_2n$3!==_0n$5&&(r=modP$1(-r));const s=new Point$1(n,r,_1n$5);return s.assertValidity(),s}function challenge$1(...n){return modN$1(bytesToNumberBE$1(taggedHash$1("BIP0340/challenge",...n)))}function schnorrGetPublicKey$1(n){return schnorrGetExtPubKey$1(n).bytes}function schnorrSign$1(n,e,t=randomBytes$2(32)){const r=ensureBytes$1("message",n),{bytes:s,scalar:o}=schnorrGetExtPubKey$1(e),a=ensureBytes$1("auxRand",t,32),u=numTo32b$1(o^bytesToNumberBE$1(taggedHash$1("BIP0340/aux",a))),c=taggedHash$1("BIP0340/nonce",u,s,r),l=modN$1(bytesToNumberBE$1(c));if(l===_0n$5)throw new Error("sign failed: k is zero");const{bytes:h,scalar:f}=schnorrGetExtPubKey$1(l),p=challenge$1(h,s,r),b=new Uint8Array(64);if(b.set(h,0),b.set(numTo32b$1(modN$1(f+p*o)),32),!schnorrVerify$1(b,r,s))throw new Error("sign: Invalid signature produced");return b}function schnorrVerify$1(n,e,t){const r=ensureBytes$1("signature",n,64),s=ensureBytes$1("message",e),o=ensureBytes$1("publicKey",t,32);try{const a=lift_x$1(bytesToNumberBE$1(o)),u=bytesToNumberBE$1(r.subarray(0,32));if(!fe(u))return!1;const c=bytesToNumberBE$1(r.subarray(32,64));if(!ge(c))return!1;const l=challenge$1(numTo32b$1(u),pointToBytes$1(a),s),h=GmulAdd$1(a,c,modN$1(-l));return!(!h||!h.hasEvenY()||h.toAffine().x!==u)}catch{return!1}}const schnorr$1={getPublicKey:schnorrGetPublicKey$1,sign:schnorrSign$1,verify:schnorrVerify$1,utils:{randomPrivateKey:secp256k1$1.utils.randomPrivateKey,lift_x:lift_x$1,pointToBytes:pointToBytes$1,numberToBytesBE:numberToBytesBE$1,bytesToNumberBE:bytesToNumberBE$1,taggedHash:taggedHash$1,mod:mod$1}},crypto$2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a=n=>n instanceof Uint8Array,createView$1=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),rotr$1=(n,e)=>n<<32-e|n>>>e,isLE$1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$1)throw new Error("Non little-endian hardware is not supported");const hexes$2=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$2(n){if(!u8a(n))throw new Error("Uint8Array expected");let e="";for(let t=0;t<n.length;t++)e+=hexes$2[n[t]];return e}function hexToBytes$2(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let r=0;r<t.length;r++){const s=r*2,o=n.slice(s,s+2),a=Number.parseInt(o,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[r]=a}return t}function utf8ToBytes$2(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function toBytes$1(n){if(typeof n=="string"&&(n=utf8ToBytes$2(n)),!u8a(n))throw new Error(`expected Uint8Array, got ${typeof n}`);return n}function concatBytes$2(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}let Hash$1=class{clone(){return this._cloneInto()}};function wrapConstructor$1(n){const e=r=>n().update(toBytes$1(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes$1(n=32){if(crypto$2&&typeof crypto$2.getRandomValues=="function")return crypto$2.getRandomValues(new Uint8Array(n));throw new Error("crypto.getRandomValues must be defined")}function number$1(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bool$1(n){if(typeof n!="boolean")throw new Error(`Expected boolean, not ${n}`)}function bytes$1(n,...e){if(!(n instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function hash(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$1(n.outputLen),number$1(n.blockLen)}function exists(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function output(n,e){bytes$1(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const assert={number:number$1,bool:bool$1,bytes:bytes$1,hash,exists,output};function setBigUint64$1(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),u=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,a,r),n.setUint32(e+l,u,r)}class SHA2 extends Hash$1{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView$1(this.buffer)}update(e){assert.exists(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes$1(e);const o=e.length;for(let a=0;a<o;){const u=Math.min(s-this.pos,o-a);if(u===s){const c=createView$1(e);for(;s<=o-a;a+=s)this.process(c,a);continue}r.set(e.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){assert.exists(this),assert.output(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let f=a;f<s;f++)t[f]=0;setBigUint64$1(r,s-8,BigInt(this.length*8),o),this.process(r,0);const u=createView$1(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)u.setUint32(4*f,h[f],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:u}=this;return e.length=s,e.pos=u,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}}const Chi$1=(n,e,t)=>n&e^~n&t,Maj$1=(n,e,t)=>n&e^n&t^e&t,SHA256_K$1=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W$1=new Uint32Array(64);let SHA256$1=class extends SHA2{constructor(){super(64,32,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:u,H:c}=this;return[e,t,r,s,o,a,u,c]}set(e,t,r,s,o,a,u,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=u|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)SHA256_W$1[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){const p=SHA256_W$1[f-15],b=SHA256_W$1[f-2],v=rotr$1(p,7)^rotr$1(p,18)^p>>>3,m=rotr$1(b,17)^rotr$1(b,19)^b>>>10;SHA256_W$1[f]=m+SHA256_W$1[f-7]+v+SHA256_W$1[f-16]|0}let{A:r,B:s,C:o,D:a,E:u,F:c,G:l,H:h}=this;for(let f=0;f<64;f++){const p=rotr$1(u,6)^rotr$1(u,11)^rotr$1(u,25),b=h+p+Chi$1(u,c,l)+SHA256_K$1[f]+SHA256_W$1[f]|0,m=(rotr$1(r,2)^rotr$1(r,13)^rotr$1(r,22))+Maj$1(r,s,o)|0;h=l,l=c,c=u,u=a+b|0,a=o,o=s,s=r,r=b+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(r,s,o,a,u,c,l,h)}roundClean(){SHA256_W$1.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};class SHA224 extends SHA256$1{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const sha256$1=wrapConstructor$1(()=>new SHA256$1);wrapConstructor$1(()=>new SHA224);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function assertNumber(n){if(!Number.isSafeInteger(n))throw new Error(`Wrong integer: ${n}`)}function chain(...n){const e=(s,o)=>a=>s(o(a)),t=Array.from(n).reverse().reduce((s,o)=>s?e(s,o.encode):o.encode,void 0),r=n.reduce((s,o)=>s?e(s,o.decode):o.decode,void 0);return{encode:t,decode:r}}function alphabet(n){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(t=>{if(assertNumber(t),t<0||t>=n.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${n.length})`);return n[t]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(t=>{if(typeof t!="string")throw new Error(`alphabet.decode: not string element=${t}`);const r=n.indexOf(t);if(r===-1)throw new Error(`Unknown letter: "${t}". Allowed: ${n}`);return r})}}}function join(n=""){if(typeof n!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let t of e)if(typeof t!="string")throw new Error(`join.encode: non-string input=${t}`);return e.join(n)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(n)}}}function padding(n,e="="){if(assertNumber(n),typeof e!="string")throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of t)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;t.length*n%8;)t.push(e);return t},decode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let s of t)if(typeof s!="string")throw new Error(`padding.decode: non-string input=${s}`);let r=t.length;if(r*n%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&t[r-1]===e;r--)if(!((r-1)*n%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,r)}}}function normalize$1(n){if(typeof n!="function")throw new Error("normalize fn should be function");return{encode:e=>e,decode:e=>n(e)}}function convertRadix(n,e,t){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(t<2)throw new Error(`convertRadix: wrong to=${t}, base cannot be less than 2`);if(!Array.isArray(n))throw new Error("convertRadix: data should be array");if(!n.length)return[];let r=0;const s=[],o=Array.from(n);for(o.forEach(a=>{if(assertNumber(a),a<0||a>=e)throw new Error(`Wrong integer: ${a}`)});;){let a=0,u=!0;for(let c=r;c<o.length;c++){const l=o[c],h=e*a+l;if(!Number.isSafeInteger(h)||e*a/e!==a||h-l!==e*a)throw new Error("convertRadix: carry overflow");if(a=h%t,o[c]=Math.floor(h/t),!Number.isSafeInteger(o[c])||o[c]*t+a!==h)throw new Error("convertRadix: carry overflow");if(u)o[c]?u=!1:r=c;else continue}if(s.push(a),u)break}for(let a=0;a<n.length-1&&n[a]===0;a++)s.push(0);return s.reverse()}const gcd=(n,e)=>e?gcd(e,n%e):n,radix2carry=(n,e)=>n+(e-gcd(n,e));function convertRadix2(n,e,t,r){if(!Array.isArray(n))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(radix2carry(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${radix2carry(e,t)}`);let s=0,o=0;const a=2**t-1,u=[];for(const c of n){if(assertNumber(c),c>=2**e)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(s=s<<e|c,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=t;o-=t)u.push((s>>o-t&a)>>>0);s&=2**o-1}if(s=s<<t-o&a,!r&&o>=e)throw new Error("Excess padding");if(!r&&s)throw new Error(`Non-zero padding: ${s}`);return r&&o>0&&u.push(s>>>0),u}function radix(n){return assertNumber(n),{encode:e=>{if(!(e instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(e),2**8,n)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(convertRadix(e,n,2**8))}}}function radix2(n,e=!1){if(assertNumber(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,n)>32||radix2carry(n,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 convertRadix2(Array.from(t),8,n,!e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(convertRadix2(t,n,8,e))}}}function unsafeWrapper(n){if(typeof n!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return n.apply(null,e)}catch{}}}const base16=chain(radix2(4),alphabet("0123456789ABCDEF"),join("")),base32=chain(radix2(5),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),padding(5),join(""));chain(radix2(5),alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"),padding(5),join("")),chain(radix2(5),alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),join(""),normalize$1(n=>n.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const base64=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6),join("")),base64url=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding(6),join("")),genBase58=n=>chain(radix(58),alphabet(n),join("")),base58=genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const XMR_BLOCK_LEN=[0,2,3,5,6,7,9,10,11],base58xmr={encode(n){let e="";for(let t=0;t<n.length;t+=8){const r=n.subarray(t,t+8);e+=base58.encode(r).padStart(XMR_BLOCK_LEN[r.length],"1")}return e},decode(n){let e=[];for(let t=0;t<n.length;t+=11){const r=n.slice(t,t+11),s=XMR_BLOCK_LEN.indexOf(r.length),o=base58.decode(r);for(let a=0;a<o.length-s;a++)if(o[a]!==0)throw new Error("base58xmr: wrong padding");e=e.concat(Array.from(o.slice(o.length-s)))}return Uint8Array.from(e)}},BECH_ALPHABET=chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join("")),POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(n){const e=n>>25;let t=(n&33554431)<<5;for(let r=0;r<POLYMOD_GENERATORS.length;r++)(e>>r&1)===1&&(t^=POLYMOD_GENERATORS[r]);return t}function bechChecksum(n,e,t=1){const r=n.length;let s=1;for(let o=0;o<r;o++){const a=n.charCodeAt(o);if(a<33||a>126)throw new Error(`Invalid prefix (${n})`);s=bech32Polymod(s)^a>>5}s=bech32Polymod(s);for(let o=0;o<r;o++)s=bech32Polymod(s)^n.charCodeAt(o)&31;for(let o of e)s=bech32Polymod(s)^o;for(let o=0;o<6;o++)s=bech32Polymod(s);return s^=t,BECH_ALPHABET.encode(convertRadix2([s%2**30],30,5,!1))}function genBech32(n){const e=n==="bech32"?1:734539939,t=radix2(5),r=t.decode,s=t.encode,o=unsafeWrapper(r);function a(h,f,p=90){if(typeof h!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof h}`);if(!Array.isArray(f)||f.length&&typeof f[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof f}`);const b=h.length+7+f.length;if(p!==!1&&b>p)throw new TypeError(`Length ${b} exceeds limit ${p}`);return h=h.toLowerCase(),`${h}1${BECH_ALPHABET.encode(f)}${bechChecksum(h,f,e)}`}function u(h,f=90){if(typeof h!="string")throw new Error(`bech32.decode input should be string, not ${typeof h}`);if(h.length<8||f!==!1&&h.length>f)throw new TypeError(`Wrong string length: ${h.length} (${h}). Expected (8..${f})`);const p=h.toLowerCase();if(h!==p&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");h=p;const b=h.lastIndexOf("1");if(b===0||b===-1)throw new Error('Letter "1" must be present between prefix and data only');const v=h.slice(0,b),m=h.slice(b+1);if(m.length<6)throw new Error("Data must be at least 6 characters long");const y=BECH_ALPHABET.decode(m).slice(0,-6),w=bechChecksum(v,y,e);if(!m.endsWith(w))throw new Error(`Invalid checksum in ${h}: expected "${w}"`);return{prefix:v,words:y}}const c=unsafeWrapper(u);function l(h){const{prefix:f,words:p}=u(h,!1);return{prefix:f,words:p,bytes:r(p)}}return{encode:a,decode:u,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:o,toWords:s}}const bech32$1=genBech32("bech32");genBech32("bech32m");const utf8$1={encode:n=>new TextDecoder().decode(n),decode:n=>new TextEncoder().encode(n)},hex$1=chain(radix2(4),alphabet("0123456789abcdef"),join(""),normalize$1(n=>{if(typeof n!="string"||n.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof n} with length ${n.length}`);return n.toLowerCase()})),CODERS={utf8:utf8$1,hex:hex$1,base16,base32,base64,base64url,base58,base58xmr};`${Object.keys(CODERS).join(", ")}`;function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, not ${n}`)}function bool(n){if(typeof n!="boolean")throw new Error(`boolean expected, not ${n}`)}function isBytes$2(n){return n instanceof Uint8Array||n!=null&&typeof n=="object"&&n.constructor.name==="Uint8Array"}function bytes(n,...e){if(!isBytes$2(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${n.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const u32=n=>new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)),isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function checkOpts(n,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(n,e)}function equalBytes$1(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}const wrapCipher=(n,e)=>(Object.assign(e,n),e),BLOCK_SIZE=16,POLY=283;function mul2(n){return n<<1^POLY&-(n>>7)}function mul(n,e){let t=0;for(;e>0;e>>=1)t^=n&-(e&1),n=mul2(n);return t}const sbox=(()=>{let n=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=mul2(r))n[t]=r;const e=new Uint8Array(256);e[0]=99;for(let t=0;t<255;t++){let r=n[255-t];r|=r<<8,e[n[t]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return e})(),invSbox=sbox.map((n,e)=>sbox.indexOf(e)),rotr32_8=n=>n<<24|n>>>8,rotl32_8=n=>n<<8|n>>>24;function genTtable(n,e){if(n.length!==256)throw new Error("Wrong sbox length");const t=new Uint32Array(256).map((l,h)=>e(n[h])),r=t.map(rotl32_8),s=r.map(rotl32_8),o=s.map(rotl32_8),a=new Uint32Array(256*256),u=new Uint32Array(256*256),c=new Uint16Array(256*256);for(let l=0;l<256;l++)for(let h=0;h<256;h++){const f=l*256+h;a[f]=t[l]^r[h],u[f]=s[l]^o[h],c[f]=n[l]<<8|n[h]}return{sbox:n,sbox2:c,T0:t,T1:r,T2:s,T3:o,T01:a,T23:u}}const tableEncoding=genTtable(sbox,n=>mul(n,3)<<24|n<<16|n<<8|mul(n,2)),tableDecoding=genTtable(invSbox,n=>mul(n,11)<<24|mul(n,13)<<16|mul(n,9)<<8|mul(n,14)),xPowers=(()=>{const n=new Uint8Array(16);for(let e=0,t=1;e<16;e++,t=mul2(t))n[e]=t;return n})();function expandKeyLE(n){bytes(n);const e=n.length;if(![16,24,32].includes(e))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);const{sbox2:t}=tableEncoding,r=u32(n),s=r.length,o=u=>applySbox(t,u,u,u,u),a=new Uint32Array(e+28);a.set(r);for(let u=s;u<a.length;u++){let c=a[u-1];u%s===0?c=o(rotr32_8(c))^xPowers[u/s-1]:s>6&&u%s===4&&(c=o(c)),a[u]=a[u-s]^c}return a}function expandKeyDecLE(n){const e=expandKeyLE(n),t=e.slice(),r=e.length,{sbox2:s}=tableEncoding,{T0:o,T1:a,T2:u,T3:c}=tableDecoding;for(let l=0;l<r;l+=4)for(let h=0;h<4;h++)t[l+h]=e[r-l-4+h];e.fill(0);for(let l=4;l<r-4;l++){const h=t[l],f=applySbox(s,h,h,h,h);t[l]=o[f&255]^a[f>>>8&255]^u[f>>>16&255]^c[f>>>24]}return t}function apply0123(n,e,t,r,s,o){return n[t<<8&65280|r>>>8&255]^e[s>>>8&65280|o>>>24&255]}function applySbox(n,e,t,r,s){return n[e&255|t&65280]|n[r>>>16&255|s>>>16&65280]<<16}function encrypt$2(n,e,t,r,s){const{sbox2:o,T01:a,T23:u}=tableEncoding;let c=0;e^=n[c++],t^=n[c++],r^=n[c++],s^=n[c++];const l=n.length/4-2;for(let v=0;v<l;v++){const m=n[c++]^apply0123(a,u,e,t,r,s),y=n[c++]^apply0123(a,u,t,r,s,e),w=n[c++]^apply0123(a,u,r,s,e,t),x=n[c++]^apply0123(a,u,s,e,t,r);e=m,t=y,r=w,s=x}const h=n[c++]^applySbox(o,e,t,r,s),f=n[c++]^applySbox(o,t,r,s,e),p=n[c++]^applySbox(o,r,s,e,t),b=n[c++]^applySbox(o,s,e,t,r);return{s0:h,s1:f,s2:p,s3:b}}function decrypt$2(n,e,t,r,s){const{sbox2:o,T01:a,T23:u}=tableDecoding;let c=0;e^=n[c++],t^=n[c++],r^=n[c++],s^=n[c++];const l=n.length/4-2;for(let v=0;v<l;v++){const m=n[c++]^apply0123(a,u,e,s,r,t),y=n[c++]^apply0123(a,u,t,e,s,r),w=n[c++]^apply0123(a,u,r,t,e,s),x=n[c++]^apply0123(a,u,s,r,t,e);e=m,t=y,r=w,s=x}const h=n[c++]^applySbox(o,e,s,r,t),f=n[c++]^applySbox(o,t,e,s,r),p=n[c++]^applySbox(o,r,t,e,s),b=n[c++]^applySbox(o,s,r,t,e);return{s0:h,s1:f,s2:p,s3:b}}function getDst(n,e){if(!e)return new Uint8Array(n);if(bytes(e),e.length<n)throw new Error(`aes: wrong destination length, expected at least ${n}, got: ${e.length}`);return e}function validateBlockDecrypt(n){if(bytes(n),n.length%BLOCK_SIZE!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`)}function validateBlockEncrypt(n,e,t){let r=n.length;const s=r%BLOCK_SIZE;if(!e&&s!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const o=u32(n);if(e){let c=BLOCK_SIZE-s;c||(c=BLOCK_SIZE),r=r+c}const a=getDst(r,t),u=u32(a);return{b:o,o:u,out:a}}function validatePCKS(n,e){if(!e)return n;const t=n.length;if(!t)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=n[t-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const s=n.subarray(0,-r);for(let o=0;o<r;o++)if(n[t-o-1]!==r)throw new Error("aes/pcks5: wrong padding");return s}function padPCKS(n){const e=new Uint8Array(16),t=u32(e);e.set(n);const r=BLOCK_SIZE-n.length;for(let s=BLOCK_SIZE-r;s<BLOCK_SIZE;s++)e[s]=r;return t}const cbc=wrapCipher({blockSize:16,nonceLength:16},function n(e,t,r={}){bytes(e),bytes(t,16);const s=!r.disablePadding;return{encrypt:(o,a)=>{const u=expandKeyLE(e),{b:c,o:l,out:h}=validateBlockEncrypt(o,s,a),f=u32(t);let p=f[0],b=f[1],v=f[2],m=f[3],y=0;for(;y+4<=c.length;)p^=c[y+0],b^=c[y+1],v^=c[y+2],m^=c[y+3],{s0:p,s1:b,s2:v,s3:m}=encrypt$2(u,p,b,v,m),l[y++]=p,l[y++]=b,l[y++]=v,l[y++]=m;if(s){const w=padPCKS(o.subarray(y*4));p^=w[0],b^=w[1],v^=w[2],m^=w[3],{s0:p,s1:b,s2:v,s3:m}=encrypt$2(u,p,b,v,m),l[y++]=p,l[y++]=b,l[y++]=v,l[y++]=m}return u.fill(0),h},decrypt:(o,a)=>{validateBlockDecrypt(o);const u=expandKeyDecLE(e),c=u32(t),l=getDst(o.length,a),h=u32(o),f=u32(l);let p=c[0],b=c[1],v=c[2],m=c[3];for(let y=0;y+4<=h.length;){const w=p,x=b,k=v,C=m;p=h[y+0],b=h[y+1],v=h[y+2],m=h[y+3];const{s0:P,s1:R,s2:N,s3:B}=decrypt$2(u,p,b,v,m);f[y++]=P^w,f[y++]=R^x,f[y++]=N^k,f[y++]=B^C}return u.fill(0),validatePCKS(l,s)}}}),_utf8ToBytes=n=>Uint8Array.from(n.split("").map(e=>e.charCodeAt(0))),sigma16=_utf8ToBytes("expand 16-byte k"),sigma32=_utf8ToBytes("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32);sigma32_32.slice();function rotl(n,e){return n<<e|n>>>32-e}function isAligned32(n){return n.byteOffset%4===0}const BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=2**32-1,U32_EMPTY=new Uint32Array;function runCipher(n,e,t,r,s,o,a,u){const c=s.length,l=new Uint8Array(BLOCK_LEN),h=u32(l),f=isAligned32(s)&&isAligned32(o),p=f?u32(s):U32_EMPTY,b=f?u32(o):U32_EMPTY;for(let v=0;v<c;a++){if(n(e,t,r,h,a,u),a>=MAX_COUNTER)throw new Error("arx: counter overflow");const m=Math.min(BLOCK_LEN,c-v);if(f&&m===BLOCK_LEN){const y=v/4;if(v%4!==0)throw new Error("arx: invalid block position");for(let w=0,x;w<BLOCK_LEN32;w++)x=y+w,b[x]=p[x]^h[w];v+=BLOCK_LEN;continue}for(let y=0,w;y<m;y++)w=v+y,o[w]=s[w]^l[y];v+=m}}function createCipher(n,e){const{allowShortKeys:t,extendNonceFn:r,counterLength:s,counterRight:o,rounds:a}=checkOpts({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof n!="function")throw new Error("core must be a function");return number(s),number(a),bool(o),bool(t),(u,c,l,h,f=0)=>{bytes(u),bytes(c),bytes(l);const p=l.length;if(h||(h=new Uint8Array(p)),bytes(h),number(f),f<0||f>=MAX_COUNTER)throw new Error("arx: counter overflow");if(h.length<p)throw new Error(`arx: output (${h.length}) is shorter than data (${p})`);const b=[];let v=u.length,m,y;if(v===32)m=u.slice(),b.push(m),y=sigma32_32;else if(v===16&&t)m=new Uint8Array(32),m.set(u),m.set(u,16),y=sigma16_32,b.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${v}`);isAligned32(c)||(c=c.slice(),b.push(c));const w=u32(m);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,w,u32(c.subarray(0,16)),w),c=c.subarray(16)}const x=16-s;if(x!==c.length)throw new Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){const C=new Uint8Array(12);C.set(c,o?0:12-c.length),c=C,b.push(c)}const k=u32(c);for(runCipher(n,y,w,k,l,h,f,a);b.length>0;)b.pop().fill(0);return h}}function chachaCore(n,e,t,r,s,o=20){let a=n[0],u=n[1],c=n[2],l=n[3],h=e[0],f=e[1],p=e[2],b=e[3],v=e[4],m=e[5],y=e[6],w=e[7],x=s,k=t[0],C=t[1],P=t[2],R=a,N=u,B=c,O=l,H=h,S=f,_=p,L=b,I=v,A=m,E=y,$=w,M=x,U=k,z=C,D=P;for(let W=0;W<o;W+=2)R=R+H|0,M=rotl(M^R,16),I=I+M|0,H=rotl(H^I,12),R=R+H|0,M=rotl(M^R,8),I=I+M|0,H=rotl(H^I,7),N=N+S|0,U=rotl(U^N,16),A=A+U|0,S=rotl(S^A,12),N=N+S|0,U=rotl(U^N,8),A=A+U|0,S=rotl(S^A,7),B=B+_|0,z=rotl(z^B,16),E=E+z|0,_=rotl(_^E,12),B=B+_|0,z=rotl(z^B,8),E=E+z|0,_=rotl(_^E,7),O=O+L|0,D=rotl(D^O,16),$=$+D|0,L=rotl(L^$,12),O=O+L|0,D=rotl(D^O,8),$=$+D|0,L=rotl(L^$,7),R=R+S|0,D=rotl(D^R,16),E=E+D|0,S=rotl(S^E,12),R=R+S|0,D=rotl(D^R,8),E=E+D|0,S=rotl(S^E,7),N=N+_|0,M=rotl(M^N,16),$=$+M|0,_=rotl(_^$,12),N=N+_|0,M=rotl(M^N,8),$=$+M|0,_=rotl(_^$,7),B=B+L|0,U=rotl(U^B,16),I=I+U|0,L=rotl(L^I,12),B=B+L|0,U=rotl(U^B,8),I=I+U|0,L=rotl(L^I,7),O=O+H|0,z=rotl(z^O,16),A=A+z|0,H=rotl(H^A,12),O=O+H|0,z=rotl(z^O,8),A=A+z|0,H=rotl(H^A,7);let V=0;r[V++]=a+R|0,r[V++]=u+N|0,r[V++]=c+B|0,r[V++]=l+O|0,r[V++]=h+H|0,r[V++]=f+S|0,r[V++]=p+_|0,r[V++]=b+L|0,r[V++]=v+I|0,r[V++]=m+A|0,r[V++]=y+E|0,r[V++]=w+$|0,r[V++]=x+M|0,r[V++]=k+U|0,r[V++]=C+z|0,r[V++]=P+D|0}const chacha20=createCipher(chachaCore,{counterRight:!1,counterLength:4,allowShortKeys:!1});let HMAC$1=class extends Hash$1{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,assert.hash(e);const r=toBytes$1(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return assert.exists(this),this.iHash.update(e),this}digestInto(e){assert.exists(this),assert.bytes(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=u,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$1=(n,e,t)=>new HMAC$1(n,e).update(t).digest();hmac$1.create=(n,e)=>new HMAC$1(n,e);function extract(n,e,t){return assert.hash(n),hmac$1(n,toBytes$1(t),toBytes$1(e))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(n,e,t,r=32){if(assert.hash(n),assert.number(r),r>255*n.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/n.outputLen);t===void 0&&(t=EMPTY_BUFFER);const o=new Uint8Array(s*n.outputLen),a=hmac$1.create(n,e),u=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)HKDF_COUNTER[0]=l+1,u.update(l===0?EMPTY_BUFFER:c).update(t).update(HKDF_COUNTER).digestInto(c),o.set(c,n.outputLen*l),a._cloneInto(u);return a.destroy(),u.destroy(),c.fill(0),HKDF_COUNTER.fill(0),o.slice(0,r)}var __defProp=Object.defineProperty,__export=(n,e)=>{for(var t in e)__defProp(n,t,{get:e[t],enumerable:!0})},verifiedSymbol$1=Symbol("verified"),isRecord$1=n=>n instanceof Object;function validateEvent$1(n){if(!isRecord$1(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!n.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(n.tags))return!1;for(let e=0;e<n.tags.length;e++){let t=n.tags[e];if(!Array.isArray(t))return!1;for(let r=0;r<t.length;r++)if(typeof t[r]=="object")return!1}return!0}var utils_exports={};__export(utils_exports,{Queue:()=>Queue$1,QueueNode:()=>QueueNode,binarySearch:()=>binarySearch,insertEventIntoAscendingList:()=>insertEventIntoAscendingList,insertEventIntoDescendingList:()=>insertEventIntoDescendingList,normalizeURL:()=>normalizeURL$2,utf8Decoder:()=>utf8Decoder,utf8Encoder:()=>utf8Encoder$1});var utf8Decoder=new TextDecoder("utf-8"),utf8Encoder$1=new TextEncoder;function normalizeURL$2(n){n.indexOf("://")===-1&&(n="wss://"+n);let e=new URL(n);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}function insertEventIntoDescendingList(n,e){const[t,r]=binarySearch(n,s=>e.id===s.id?0:e.created_at===s.created_at?-1:s.created_at-e.created_at);return r||n.splice(t,0,e),n}function insertEventIntoAscendingList(n,e){const[t,r]=binarySearch(n,s=>e.id===s.id?0:e.created_at===s.created_at?-1:e.created_at-s.created_at);return r||n.splice(t,0,e),n}function binarySearch(n,e){let t=0,r=n.length-1;for(;t<=r;){const s=Math.floor((t+r)/2),o=e(n[s]);if(o===0)return[s,!0];o<0?r=s-1:t=s+1}return[t,!1]}var QueueNode=class{constructor(n){g(this,"value");g(this,"next",null);g(this,"prev",null);this.value=n}},Queue$1=class{constructor(){g(this,"first");g(this,"last");this.first=null,this.last=null}enqueue(e){const t=new QueueNode(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,e.value}},JS$1=class{generateSecretKey(){return schnorr$1.utils.randomPrivateKey()}getPublicKey(e){return bytesToHex$2(schnorr$1.getPublicKey(e))}finalizeEvent(e,t){const r=e;return r.pubkey=bytesToHex$2(schnorr$1.getPublicKey(t)),r.id=getEventHash$2(r),r.sig=bytesToHex$2(schnorr$1.sign(getEventHash$2(r),t)),r[verifiedSymbol$1]=!0,r}verifyEvent(e){if(typeof e[verifiedSymbol$1]=="boolean")return e[verifiedSymbol$1];const t=getEventHash$2(e);if(t!==e.id)return e[verifiedSymbol$1]=!1,!1;try{const r=schnorr$1.verify(e.sig,t,e.pubkey);return e[verifiedSymbol$1]=r,r}catch{return e[verifiedSymbol$1]=!1,!1}}};function serializeEvent$1(n){if(!validateEvent$1(n))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])}function getEventHash$2(n){let e=sha256$1(utf8Encoder$1.encode(serializeEvent$1(n)));return bytesToHex$2(e)}var i$1=new JS$1,generateSecretKey$1=i$1.generateSecretKey,getPublicKey$1=i$1.getPublicKey,finalizeEvent$1=i$1.finalizeEvent,verifyEvent=i$1.verifyEvent,kinds_exports={};__export(kinds_exports,{Application:()=>Application,BadgeAward:()=>BadgeAward,BadgeDefinition:()=>BadgeDefinition,BlockedRelaysList:()=>BlockedRelaysList,BookmarkList:()=>BookmarkList,Bookmarksets:()=>Bookmarksets,Calendar:()=>Calendar,CalendarEventRSVP:()=>CalendarEventRSVP,ChannelCreation:()=>ChannelCreation,ChannelHideMessage:()=>ChannelHideMessage,ChannelMessage:()=>ChannelMessage,ChannelMetadata:()=>ChannelMetadata,ChannelMuteUser:()=>ChannelMuteUser,ClassifiedListing:()=>ClassifiedListing,ClientAuth:()=>ClientAuth,CommunitiesList:()=>CommunitiesList,CommunityDefinition:()=>CommunityDefinition,CommunityPostApproval:()=>CommunityPostApproval,Contacts:()=>Contacts,CreateOrUpdateProduct:()=>CreateOrUpdateProduct,CreateOrUpdateStall:()=>CreateOrUpdateStall,Curationsets:()=>Curationsets,Date:()=>Date2,DirectMessageRelaysList:()=>DirectMessageRelaysList,DraftClassifiedListing:()=>DraftClassifiedListing,DraftLong:()=>DraftLong,Emojisets:()=>Emojisets,EncryptedDirectMessage:()=>EncryptedDirectMessage,EventDeletion:()=>EventDeletion,FileMetadata:()=>FileMetadata,FileServerPreference:()=>FileServerPreference,Followsets:()=>Followsets,GenericRepost:()=>GenericRepost,Genericlists:()=>Genericlists,GiftWrap:()=>GiftWrap,HTTPAuth:()=>HTTPAuth,Handlerinformation:()=>Handlerinformation,Handlerrecommendation:()=>Handlerrecommendation,Highlights:()=>Highlights,InterestsList:()=>InterestsList,Interestsets:()=>Interestsets,JobFeedback:()=>JobFeedback,JobRequest:()=>JobRequest,JobResult:()=>JobResult,Label:()=>Label,LightningPubRPC:()=>LightningPubRPC,LiveChatMessage:()=>LiveChatMessage,LiveEvent:()=>LiveEvent,LongFormArticle:()=>LongFormArticle,Metadata:()=>Metadata,Mutelist:()=>Mutelist,NWCWalletInfo:()=>NWCWalletInfo,NWCWalletRequest:()=>NWCWalletRequest,NWCWalletResponse:()=>NWCWalletResponse,NostrConnect:()=>NostrConnect,OpenTimestamps:()=>OpenTimestamps,Pinlist:()=>Pinlist,PrivateDirectMessage:()=>PrivateDirectMessage,ProblemTracker:()=>ProblemTracker,ProfileBadges:()=>ProfileBadges,PublicChatsList:()=>PublicChatsList,Reaction:()=>Reaction,RecommendRelay:()=>RecommendRelay,RelayList:()=>RelayList,Relaysets:()=>Relaysets,Report:()=>Report,Reporting:()=>Reporting,Repost:()=>Repost,Seal:()=>Seal,SearchRelaysList:()=>SearchRelaysList,ShortTextNote:()=>ShortTextNote,Time:()=>Time,UserEmojiList:()=>UserEmojiList,UserStatuses:()=>UserStatuses,Zap:()=>Zap,ZapGoal:()=>ZapGoal,ZapRequest:()=>ZapRequest,classifyKind:()=>classifyKind,isAddressableKind:()=>isAddressableKind,isEphemeralKind:()=>isEphemeralKind,isKind:()=>isKind,isParameterizedReplaceableKind:()=>isParameterizedReplaceableKind,isRegularKind:()=>isRegularKind,isReplaceableKind:()=>isReplaceableKind});function isRegularKind(n){return 1e3<=n&&n<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(n)}function isReplaceableKind(n){return[0,3].includes(n)||1e4<=n&&n<2e4}function isEphemeralKind(n){return 2e4<=n&&n<3e4}function isAddressableKind(n){return 3e4<=n&&n<4e4}var isParameterizedReplaceableKind=isAddressableKind;function classifyKind(n){return isRegularKind(n)?"regular":isReplaceableKind(n)?"replaceable":isEphemeralKind(n)?"ephemeral":isAddressableKind(n)?"parameterized":"unknown"}function isKind(n,e){const t=e instanceof Array?e:[e];return validateEvent$1(n)&&t.includes(n.kind)||!1}var Metadata=0,ShortTextNote=1,RecommendRelay=2,Contacts=3,EncryptedDirectMessage=4,EventDeletion=5,Repost=6,Reaction=7,BadgeAward=8,Seal=13,PrivateDirectMessage=14,GenericRepost=16,ChannelCreation=40,ChannelMetadata=41,ChannelMessage=42,ChannelHideMessage=43,ChannelMuteUser=44,OpenTimestamps=1040,GiftWrap=1059,FileMetadata=1063,LiveChatMessage=1311,ProblemTracker=1971,Report=1984,Reporting=1984,Label=1985,CommunityPostApproval=4550,JobRequest=5999,JobResult=6999,JobFeedback=7e3,ZapGoal=9041,ZapRequest=9734,Zap=9735,Highlights=9802,Mutelist=1e4,Pinlist=10001,RelayList=10002,BookmarkList=10003,CommunitiesList=10004,PublicChatsList=10005,BlockedRelaysList=10006,SearchRelaysList=10007,InterestsList=10015,UserEmojiList=10030,DirectMessageRelaysList=10050,FileServerPreference=10096,NWCWalletInfo=13194,LightningPubRPC=21e3,ClientAuth=22242,NWCWalletRequest=23194,NWCWalletResponse=23195,NostrConnect=24133,HTTPAuth=27235,Followsets=3e4,Genericlists=30001,Relaysets=30002,Bookmarksets=30003,Curationsets=30004,ProfileBadges=30008,BadgeDefinition=30009,Interestsets=30015,CreateOrUpdateStall=30017,CreateOrUpdateProduct=30018,LongFormArticle=30023,DraftLong=30024,Emojisets=30030,Application=30078,LiveEvent=30311,UserStatuses=30315,ClassifiedListing=30402,DraftClassifiedListing=30403,Date2=31922,Time=31923,Calendar=31924,CalendarEventRSVP=31925,Handlerrecommendation=31989,Handlerinformation=31990,CommunityDefinition=34550;function matchFilter(n,e){if(n.ids&&n.ids.indexOf(e.id)===-1||n.kinds&&n.kinds.indexOf(e.kind)===-1||n.authors&&n.authors.indexOf(e.pubkey)===-1)return!1;for(let t in n)if(t[0]==="#"){let r=t.slice(1),s=n[`#${r}`];if(s&&!e.tags.find(([o,a])=>o===t.slice(1)&&s.indexOf(a)!==-1))return!1}return!(n.since&&e.created_at<n.since||n.until&&e.created_at>n.until)}function matchFilters(n,e){for(let t=0;t<n.length;t++)if(matchFilter(n[t],e))return!0;return!1}var fakejson_exports={};__export(fakejson_exports,{getHex64:()=>getHex64,getInt:()=>getInt,getSubscriptionId:()=>getSubscriptionId,matchEventId:()=>matchEventId,matchEventKind:()=>matchEventKind,matchEventPubkey:()=>matchEventPubkey});function getHex64(n,e){let t=e.length+3,r=n.indexOf(`"${e}":`)+t,s=n.slice(r).indexOf('"')+r+1;return n.slice(s,s+64)}function getInt(n,e){let t=e.length,r=n.indexOf(`"${e}":`)+t+3,s=n.slice(r),o=Math.min(s.indexOf(","),s.indexOf("}"));return parseInt(s.slice(0,o),10)}function getSubscriptionId(n){let e=n.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let t=n.slice(e+7+1).indexOf('"');if(t===-1)return null;let r=e+7+1+t,s=n.slice(r+1,80).indexOf('"');if(s===-1)return null;let o=r+1+s;return n.slice(r+1,o)}function matchEventId(n,e){return e===getHex64(n,"id")}function matchEventPubkey(n,e){return e===getHex64(n,"pubkey")}function matchEventKind(n,e){return e===getInt(n,"kind")}var nip42_exports={};__export(nip42_exports,{makeAuthEvent:()=>makeAuthEvent});function makeAuthEvent(n,e){return{kind:ClientAuth,created_at:Math.floor(Date.now()/1e3),tags:[["relay",n],["challenge",e]],content:""}}async function yieldThread(){return new Promise(n=>{const e=new MessageChannel,t=()=>{e.port1.removeEventListener("message",t),n()};e.port1.addEventListener("message",t),e.port2.postMessage(0),e.port1.start()})}var alwaysTrue=n=>(n[verifiedSymbol$1]=!0,!0),AbstractRelay=class{constructor(n,e){g(this,"url");g(this,"_connected",!1);g(this,"onclose",null);g(this,"onnotice",n=>console.debug(`NOTICE from ${this.url}: ${n}`));g(this,"_onauth",null);g(this,"baseEoseTimeout",4400);g(this,"connectionTimeout",4400);g(this,"publishTimeout",4400);g(this,"openSubs",new Map);g(this,"connectionTimeoutHandle");g(this,"connectionPromise");g(this,"openCountRequests",new Map);g(this,"openEventPublishes",new Map);g(this,"ws");g(this,"incomingMessageQueue",new Queue$1);g(this,"queueRunning",!1);g(this,"challenge");g(this,"authPromise");g(this,"serial",0);g(this,"verifyEvent");g(this,"_WebSocket");this.url=normalizeURL$2(n),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket}static async connect(n,e){const t=new AbstractRelay(n,e);return await t.connect(),t}closeAllSubscriptions(n){for(let[e,t]of this.openSubs)t.close(n);this.openSubs.clear();for(let[e,t]of this.openEventPublishes)t.reject(new Error(n));this.openEventPublishes.clear();for(let[e,t]of this.openCountRequests)t.reject(new Error(n));this.openCountRequests.clear()}get connected(){return this._connected}async connect(){return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.connectionPromise=new Promise((n,e)=>{this.connectionTimeoutHandle=setTimeout(()=>{var t;e("connection timed out"),this.connectionPromise=void 0,(t=this.onclose)==null||t.call(this),this.closeAllSubscriptions("relay connection timed out")},this.connectionTimeout);try{this.ws=new this._WebSocket(this.url)}catch(t){e(t);return}this.ws.onopen=()=>{clearTimeout(this.connectionTimeoutHandle),this._connected=!0,n()},this.ws.onerror=t=>{var r;e(t.message||"websocket error"),this._connected&&(this._connected=!1,this.connectionPromise=void 0,(r=this.onclose)==null||r.call(this),this.closeAllSubscriptions("relay connection errored"))},this.ws.onclose=async()=>{var t;this._connected&&(this._connected=!1,this.connectionPromise=void 0,(t=this.onclose)==null||t.call(this),this.closeAllSubscriptions("relay connection closed"))},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}async runQueue(){for(this.queueRunning=!0;this.handleNext()!==!1;)await yieldThread();this.queueRunning=!1}handleNext(){var t,r,s;const n=this.incomingMessageQueue.dequeue();if(!n)return!1;const e=getSubscriptionId(n);if(e){const o=this.openSubs.get(e);if(!o)return;const a=getHex64(n,"id"),u=(t=o.alreadyHaveEvent)==null?void 0:t.call(o,a);if((r=o.receivedEvent)==null||r.call(o,this,a),u)return}try{let o=JSON.parse(n);switch(o[0]){case"EVENT":{const a=this.openSubs.get(o[1]),u=o[2];this.verifyEvent(u)&&matchFilters(a.filters,u)&&a.onevent(u);return}case"COUNT":{const a=o[1],u=o[2],c=this.openCountRequests.get(a);c&&(c.resolve(u.count),this.openCountRequests.delete(a));return}case"EOSE":{const a=this.openSubs.get(o[1]);if(!a)return;a.receivedEose();return}case"OK":{const a=o[1],u=o[2],c=o[3],l=this.openEventPublishes.get(a);l&&(clearTimeout(l.timeout),u?l.resolve(c):l.reject(new Error(c)),this.openEventPublishes.delete(a));return}case"CLOSED":{const a=o[1],u=this.openSubs.get(a);if(!u)return;u.closed=!0,u.close(o[2]);return}case"NOTICE":this.onnotice(o[1]);return;case"AUTH":{this.challenge=o[1],this.authPromise=void 0,(s=this._onauth)==null||s.call(this,o[1]);return}}}catch{return}}async send(n){if(!this.connectionPromise)throw new Error("sending on closed connection");this.connectionPromise.then(()=>{var e;(e=this.ws)==null||e.send(n)})}async auth(n){if(!this.challenge)throw new Error("can't perform auth, no challenge was received");if(this.authPromise)return this.authPromise;const e=await n(makeAuthEvent(this.url,this.challenge));return this.authPromise=new Promise((t,r)=>{const s=setTimeout(()=>{const o=this.openEventPublishes.get(e.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:t,reject:r,timeout:s})}),this.send('["AUTH",'+JSON.stringify(e)+"]"),this.authPromise}async publish(n){const e=new Promise((t,r)=>{const s=setTimeout(()=>{const o=this.openEventPublishes.get(n.id);o&&(o.reject(new Error("publish timed out")),this.openEventPublishes.delete(n.id))},this.publishTimeout);this.openEventPublishes.set(n.id,{resolve:t,reject:r,timeout:s})});return this.send('["EVENT",'+JSON.stringify(n)+"]"),e}async count(n,e){this.serial++;const t=(e==null?void 0:e.id)||"count:"+this.serial,r=new Promise((s,o)=>{this.openCountRequests.set(t,{resolve:s,reject:o})});return this.send('["COUNT","'+t+'",'+JSON.stringify(n).substring(1)),r}subscribe(n,e){const t=this.prepareSubscription(n,e);return t.fire(),t}prepareSubscription(n,e){this.serial++;const t=e.id||(e.label?e.label+":":"sub:")+this.serial,r=new Subscription(this,t,n,e);return this.openSubs.set(t,r),r}close(){var n;this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,(n=this.ws)==null||n.close()}_onmessage(n){this.incomingMessageQueue.enqueue(n.data),this.queueRunning||this.runQueue()}},Subscription=class{constructor(n,e,t,r){g(this,"relay");g(this,"id");g(this,"closed",!1);g(this,"eosed",!1);g(this,"filters");g(this,"alreadyHaveEvent");g(this,"receivedEvent");g(this,"onevent");g(this,"oneose");g(this,"onclose");g(this,"eoseTimeout");g(this,"eoseTimeoutHandle");this.relay=n,this.filters=t,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||n.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.onevent=r.onevent||(s=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,s)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){var n;this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,(n=this.oneose)==null||n.call(this))}close(n="closed by caller"){var e;!this.closed&&this.relay.connected&&(this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]"),this.closed=!0),this.relay.openSubs.delete(this.id),(e=this.onclose)==null||e.call(this,n)}},_WebSocket;try{_WebSocket=WebSocket}catch{}var AbstractSimplePool=class{constructor(n){g(this,"relays",new Map);g(this,"seenOn",new Map);g(this,"trackRelays",!1);g(this,"verifyEvent");g(this,"trustedRelayURLs",new Set);g(this,"_WebSocket");this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation}async ensureRelay(n,e){n=normalizeURL$2(n);let t=this.relays.get(n);return t||(t=new AbstractRelay(n,{verifyEvent:this.trustedRelayURLs.has(n)?alwaysTrue:this.verifyEvent,websocketImplementation:this._WebSocket}),e!=null&&e.connectionTimeout&&(t.connectionTimeout=e.connectionTimeout),this.relays.set(n,t)),await t.connect(),t}close(n){n.map(normalizeURL$2).forEach(e=>{var t;(t=this.relays.get(e))==null||t.close()})}subscribe(n,e,t){return this.subscribeMap(n.map(r=>({url:r,filter:e})),t)}subscribeMany(n,e,t){return this.subscribeMap(n.flatMap(r=>e.map(s=>({url:r,filter:s}))),t)}subscribeMap(n,e){this.trackRelays&&(e.receivedEvent=(h,f)=>{let p=this.seenOn.get(f);p||(p=new Set,this.seenOn.set(f,p)),p.add(h)});const t=new Set,r=[],s=[];let o=h=>{var f;s[h]||(s[h]=!0,s.filter(p=>p).length===n.length&&((f=e.oneose)==null||f.call(e),o=()=>{}))};const a=[];let u=(h,f)=>{var p;a[h]||(o(h),a[h]=f,a.filter(b=>b).length===n.length&&((p=e.onclose)==null||p.call(e,a),u=()=>{}))};const c=h=>{var p;if((p=e.alreadyHaveEvent)!=null&&p.call(e,h))return!0;const f=t.has(h);return t.add(h),f},l=Promise.all(n.map(async({url:h,filter:f},p)=>{h=normalizeURL$2(h);let b;try{b=await this.ensureRelay(h,{connectionTimeout:e.maxWait?Math.max(e.maxWait*.8,e.maxWait-1e3):void 0})}catch(m){u(p,(m==null?void 0:m.message)||String(m));return}let v=b.subscribe([f],{...e,oneose:()=>o(p),onclose:m=>{m.startsWith("auth-required:")&&e.doauth?b.auth(e.doauth).then(()=>{b.subscribe([f],{...e,oneose:()=>o(p),onclose:y=>{u(p,y)},alreadyHaveEvent:c,eoseTimeout:e.maxWait})}).catch(y=>{u(p,`auth was required and attempted, but failed with: ${y}`)}):u(p,m)},alreadyHaveEvent:c,eoseTimeout:e.maxWait});r.push(v)}));return{async close(){await l,r.forEach(h=>{h.close()})}}}subscribeManyMap(n,e){this.trackRelays&&(e.receivedEvent=(f,p)=>{let b=this.seenOn.get(p);b||(b=new Set,this.seenOn.set(p,b)),b.add(f)});const t=new Set,r=[],s=Object.keys(n).length,o=[];let a=f=>{var p;o[f]||(o[f]=!0,o.filter(b=>b).length===s&&((p=e.oneose)==null||p.call(e),a=()=>{}))};const u=[];let c=(f,p)=>{var b;u[f]||(a(f),u[f]=p,u.filter(v=>v).length===s&&((b=e.onclose)==null||b.call(e,u),c=()=>{}))};const l=f=>{var b;if((b=e.alreadyHaveEvent)!=null&&b.call(e,f))return!0;const p=t.has(f);return t.add(f),p},h=Promise.all(Object.entries(n).map(async(f,p,b)=>{if(b.indexOf(f)!==p){c(p,"duplicate url");return}let[v,m]=f;v=normalizeURL$2(v);let y;try{y=await this.ensureRelay(v,{connectionTimeout:e.maxWait?Math.max(e.maxWait*.8,e.maxWait-1e3):void 0})}catch(x){c(p,(x==null?void 0:x.message)||String(x));return}let w=y.subscribe(m,{...e,oneose:()=>a(p),onclose:x=>{x.startsWith("auth-required:")&&e.doauth?y.auth(e.doauth).then(()=>{y.subscribe(m,{...e,oneose:()=>a(p),onclose:k=>{c(p,k)},alreadyHaveEvent:l,eoseTimeout:e.maxWait})}).catch(k=>{c(p,`auth was required and attempted, but failed with: ${k}`)}):c(p,x)},alreadyHaveEvent:l,eoseTimeout:e.maxWait});r.push(w)}));return{async close(){await h,r.forEach(f=>{f.close()})}}}subscribeEose(n,e,t){const r=this.subscribe(n,e,{...t,oneose(){r.close()}});return r}subscribeManyEose(n,e,t){const r=this.subscribeMany(n,e,{...t,oneose(){r.close()}});return r}async querySync(n,e,t){return new Promise(async r=>{const s=[];this.subscribeEose(n,e,{...t,onevent(o){s.push(o)},onclose(o){r(s)}})})}async get(n,e,t){e.limit=1;const r=await this.querySync(n,e,t);return r.sort((s,o)=>o.created_at-s.created_at),r[0]||null}publish(n,e){return n.map(normalizeURL$2).map(async(t,r,s)=>{if(s.indexOf(t)!==r)return Promise.reject("duplicate url");let o=await this.ensureRelay(t);return o.publish(e).then(a=>{if(this.trackRelays){let u=this.seenOn.get(e.id);u||(u=new Set,this.seenOn.set(e.id,u)),u.add(o)}return a})})}listConnectionStatus(){const n=new Map;return this.relays.forEach((e,t)=>n.set(t,e.connected)),n}destroy(){this.relays.forEach(n=>n.close()),this.relays=new Map}},_WebSocket2;try{_WebSocket2=WebSocket}catch{}var SimplePool=class extends AbstractSimplePool{constructor(){super({verifyEvent,websocketImplementation:_WebSocket2})}},nip19_exports={};__export(nip19_exports,{BECH32_REGEX:()=>BECH32_REGEX$1,Bech32MaxSize:()=>Bech32MaxSize,NostrTypeGuard:()=>NostrTypeGuard,decode:()=>decode,decodeNostrURI:()=>decodeNostrURI,encodeBytes:()=>encodeBytes,naddrEncode:()=>naddrEncode,neventEncode:()=>neventEncode,noteEncode:()=>noteEncode,nprofileEncode:()=>nprofileEncode,npubEncode:()=>npubEncode,nsecEncode:()=>nsecEncode});var NostrTypeGuard={isNProfile:n=>/^nprofile1[a-z\d]+$/.test(n||""),isNEvent:n=>/^nevent1[a-z\d]+$/.test(n||""),isNAddr:n=>/^naddr1[a-z\d]+$/.test(n||""),isNSec:n=>/^nsec1[a-z\d]{58}$/.test(n||""),isNPub:n=>/^npub1[a-z\d]{58}$/.test(n||""),isNote:n=>/^note1[a-z\d]+$/.test(n||""),isNcryptsec:n=>/^ncryptsec1[a-z\d]+$/.test(n||"")},Bech32MaxSize=5e3,BECH32_REGEX$1=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function integerToUint8Array(n){const e=new Uint8Array(4);return e[0]=n>>24&255,e[1]=n>>16&255,e[2]=n>>8&255,e[3]=n&255,e}function decodeNostrURI(n){try{return n.startsWith("nostr:")&&(n=n.substring(6)),decode(n)}catch{return{type:"invalid",data:null}}}function decode(n){var s,o,a,u,c,l,h;let{prefix:e,words:t}=bech32$1.decode(n,Bech32MaxSize),r=new Uint8Array(bech32$1.fromWords(t));switch(e){case"nprofile":{let f=parseTLV(r);if(!((s=f[0])!=null&&s[0]))throw new Error("missing TLV 0 for nprofile");if(f[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$2(f[0][0]),relays:f[1]?f[1].map(p=>utf8Decoder.decode(p)):[]}}}case"nevent":{let f=parseTLV(r);if(!((o=f[0])!=null&&o[0]))throw new Error("missing TLV 0 for nevent");if(f[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(f[2]&&f[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(f[3]&&f[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$2(f[0][0]),relays:f[1]?f[1].map(p=>utf8Decoder.decode(p)):[],author:(a=f[2])!=null&&a[0]?bytesToHex$2(f[2][0]):void 0,kind:(u=f[3])!=null&&u[0]?parseInt(bytesToHex$2(f[3][0]),16):void 0}}}case"naddr":{let f=parseTLV(r);if(!((c=f[0])!=null&&c[0]))throw new Error("missing TLV 0 for naddr");if(!((l=f[2])!=null&&l[0]))throw new Error("missing TLV 2 for naddr");if(f[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((h=f[3])!=null&&h[0]))throw new Error("missing TLV 3 for naddr");if(f[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder.decode(f[0][0]),pubkey:bytesToHex$2(f[2][0]),kind:parseInt(bytesToHex$2(f[3][0]),16),relays:f[1]?f[1].map(p=>utf8Decoder.decode(p)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:bytesToHex$2(r)};default:throw new Error(`unknown prefix ${e}`)}}function parseTLV(n){let e={},t=n;for(;t.length>0;){let r=t[0],s=t[1],o=t.slice(2,2+s);if(t=t.slice(2+s),o.length<s)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(o)}return e}function nsecEncode(n){return encodeBytes("nsec",n)}function npubEncode(n){return encodeBytes("npub",hexToBytes$2(n))}function noteEncode(n){return encodeBytes("note",hexToBytes$2(n))}function encodeBech32(n,e){let t=bech32$1.toWords(e);return bech32$1.encode(n,t,Bech32MaxSize)}function encodeBytes(n,e){return encodeBech32(n,e)}function nprofileEncode(n){let e=encodeTLV({0:[hexToBytes$2(n.pubkey)],1:(n.relays||[]).map(t=>utf8Encoder$1.encode(t))});return encodeBech32("nprofile",e)}function neventEncode(n){let e;n.kind!==void 0&&(e=integerToUint8Array(n.kind));let t=encodeTLV({0:[hexToBytes$2(n.id)],1:(n.relays||[]).map(r=>utf8Encoder$1.encode(r)),2:n.author?[hexToBytes$2(n.author)]:[],3:e?[new Uint8Array(e)]:[]});return encodeBech32("nevent",t)}function naddrEncode(n){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,n.kind,!1);let t=encodeTLV({0:[utf8Encoder$1.encode(n.identifier)],1:(n.relays||[]).map(r=>utf8Encoder$1.encode(r)),2:[hexToBytes$2(n.pubkey)],3:[new Uint8Array(e)]});return encodeBech32("naddr",t)}function encodeTLV(n){let e=[];return Object.entries(n).reverse().forEach(([t,r])=>{r.forEach(s=>{let o=new Uint8Array(s.length+2);o.set([parseInt(t)],0),o.set([s.length],1),o.set(s,2),e.push(o)})}),concatBytes$2(...e)}var nip04_exports={};__export(nip04_exports,{decrypt:()=>decrypt$1,encrypt:()=>encrypt$1});function encrypt$1(n,e,t){const r=n instanceof Uint8Array?bytesToHex$2(n):n,s=secp256k1$1.getSharedSecret(r,"02"+e),o=getNormalizedX(s);let a=Uint8Array.from(randomBytes$1(16)),u=utf8Encoder$1.encode(t),c=cbc(o,a).encrypt(u),l=base64.encode(new Uint8Array(c)),h=base64.encode(new Uint8Array(a.buffer));return`${l}?iv=${h}`}function decrypt$1(n,e,t){const r=n instanceof Uint8Array?bytesToHex$2(n):n;let[s,o]=t.split("?iv="),a=secp256k1$1.getSharedSecret(r,"02"+e),u=getNormalizedX(a),c=base64.decode(o),l=base64.decode(s),h=cbc(u,c).decrypt(l);return utf8Decoder.decode(h)}function getNormalizedX(n){return n.slice(1,33)}var nip05_exports={};__export(nip05_exports,{NIP05_REGEX:()=>NIP05_REGEX$1,isNip05:()=>isNip05,isValid:()=>isValid,queryProfile:()=>queryProfile,searchDomain:()=>searchDomain,useFetchImplementation:()=>useFetchImplementation});var NIP05_REGEX$1=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,isNip05=n=>NIP05_REGEX$1.test(n||""),_fetch;try{_fetch=fetch}catch(n){}function useFetchImplementation(n){_fetch=n}async function searchDomain(n,e=""){try{const t=`https://${n}/.well-known/nostr.json?name=${e}`,r=await _fetch(t,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function queryProfile(n){var s;const e=n.match(NIP05_REGEX$1);if(!e)return null;const[,t="_",r]=e;try{const o=`https://${r}/.well-known/nostr.json?name=${t}`,a=await _fetch(o,{redirect:"manual"});if(a.status!==200)throw Error("Wrong response code");const u=await a.json(),c=u.names[t];return c?{pubkey:c,relays:(s=u.relays)==null?void 0:s[c]}:null}catch{return null}}async function isValid(n,e){const t=await queryProfile(e);return t?t.pubkey===n:!1}var nip10_exports={};__export(nip10_exports,{parse:()=>parse});function parse(n){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let t,r;for(let s=n.tags.length-1;s>=0;s--){const o=n.tags[s];if(o[0]==="e"&&o[1]){const[a,u,c,l,h]=o,f={id:u,relays:c?[c]:[],author:h};if(l==="root"){e.root=f;continue}if(l==="reply"){e.reply=f;continue}if(l==="mention"){e.mentions.push(f);continue}t?r=f:t=f,e.mentions.push(f);continue}if(o[0]==="q"&&o[1]){const[a,u,c]=o;e.quotes.push({id:u,relays:c?[c]:[]})}if(o[0]==="p"&&o[1]){e.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]});continue}}return e.root||(e.root=r||t||e.reply),e.reply||(e.reply=t||e.root),[e.reply,e.root].forEach(s=>{if(!s)return;let o=e.mentions.indexOf(s);if(o!==-1&&e.mentions.splice(o,1),s.author){let a=e.profiles.find(u=>u.pubkey===s.author);a&&a.relays&&(s.relays||(s.relays=[]),a.relays.forEach(u=>{var c;((c=s.relays)==null?void 0:c.indexOf(u))===-1&&s.relays.push(u)}),a.relays=s.relays)}}),e.mentions.forEach(s=>{if(s.author){let o=e.profiles.find(a=>a.pubkey===s.author);o&&o.relays&&(s.relays||(s.relays=[]),o.relays.forEach(a=>{s.relays.indexOf(a)===-1&&s.relays.push(a)}),o.relays=s.relays)}}),e}var nip11_exports={};__export(nip11_exports,{fetchRelayInformation:()=>fetchRelayInformation,useFetchImplementation:()=>useFetchImplementation2});var _fetch2;try{_fetch2=fetch}catch{}function useFetchImplementation2(n){_fetch2=n}async function fetchRelayInformation(n){return await(await fetch(n.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var nip13_exports={};__export(nip13_exports,{fastEventHash:()=>fastEventHash,getPow:()=>getPow,minePow:()=>minePow});function getPow(n){let e=0;for(let t=0;t<64;t+=8){const r=parseInt(n.substring(t,t+8),16);if(r===0)e+=32;else{e+=Math.clz32(r);break}}return e}function minePow(n,e){let t=0;const r=n,s=["nonce",t.toString(),e.toString()];for(r.tags.push(s);;){const o=Math.floor(new Date().getTime()/1e3);if(o!==r.created_at&&(t=0,r.created_at=o),s[1]=(++t).toString(),r.id=fastEventHash(r),getPow(r.id)>=e)break}return r}function fastEventHash(n){return bytesToHex$2(sha256$1(utf8Encoder$1.encode(JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content]))))}var nip17_exports={};__export(nip17_exports,{unwrapEvent:()=>unwrapEvent2,unwrapManyEvents:()=>unwrapManyEvents2,wrapEvent:()=>wrapEvent2,wrapManyEvents:()=>wrapManyEvents2});var nip59_exports={};__export(nip59_exports,{createRumor:()=>createRumor,createSeal:()=>createSeal,createWrap:()=>createWrap,unwrapEvent:()=>unwrapEvent,unwrapManyEvents:()=>unwrapManyEvents,wrapEvent:()=>wrapEvent$1,wrapManyEvents:()=>wrapManyEvents});var nip44_exports={};__export(nip44_exports,{decrypt:()=>decrypt2,encrypt:()=>encrypt2,getConversationKey:()=>getConversationKey,v2:()=>v2});var minPlaintextSize=1,maxPlaintextSize=65535;function getConversationKey(n,e){const t=secp256k1$1.getSharedSecret(n,"02"+e).subarray(1,33);return extract(sha256$1,t,"nip44-v2")}function getMessageKeys(n,e){const t=expand(sha256$1,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function calcPaddedLen(n){if(!Number.isSafeInteger(n)||n<1)throw new Error("expected positive integer");if(n<=32)return 32;const e=1<<Math.floor(Math.log2(n-1))+1,t=e<=256?32:e/8;return t*(Math.floor((n-1)/t)+1)}function writeU16BE(n){if(!Number.isSafeInteger(n)||n<minPlaintextSize||n>maxPlaintextSize)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,n,!1),e}function pad(n){const e=utf8Encoder$1.encode(n),t=e.length,r=writeU16BE(t),s=new Uint8Array(calcPaddedLen(t)-t);return concatBytes$2(r,e,s)}function unpad(n){const e=new DataView(n.buffer).getUint16(0),t=n.subarray(2,2+e);if(e<minPlaintextSize||e>maxPlaintextSize||t.length!==e||n.length!==2+calcPaddedLen(e))throw new Error("invalid padding");return utf8Decoder.decode(t)}function hmacAad(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=concatBytes$2(t,e);return hmac$1(sha256$1,n,r)}function decodePayload(n){if(typeof n!="string")throw new Error("payload must be a valid string");const e=n.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if(n[0]==="#")throw new Error("unknown encryption version");let t;try{t=base64.decode(n)}catch(o){throw new Error("invalid base64: "+o.message)}const r=t.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const s=t[0];if(s!==2)throw new Error("unknown encryption version "+s);return{nonce:t.subarray(1,33),ciphertext:t.subarray(33,-32),mac:t.subarray(-32)}}function encrypt2(n,e,t=randomBytes$1(32)){const{chacha_key:r,chacha_nonce:s,hmac_key:o}=getMessageKeys(e,t),a=pad(n),u=chacha20(r,s,a),c=hmacAad(o,u,t);return base64.encode(concatBytes$2(new Uint8Array([2]),t,u,c))}function decrypt2(n,e){const{nonce:t,ciphertext:r,mac:s}=decodePayload(n),{chacha_key:o,chacha_nonce:a,hmac_key:u}=getMessageKeys(e,t),c=hmacAad(u,r,t);if(!equalBytes$1(c,s))throw new Error("invalid MAC");const l=chacha20(o,a,r);return unpad(l)}var v2={utils:{getConversationKey,calcPaddedLen},encrypt:encrypt2,decrypt:decrypt2},TWO_DAYS=2*24*60*60,now$1=()=>Math.round(Date.now()/1e3),randomNow=()=>Math.round(now$1()-Math.random()*TWO_DAYS),nip44ConversationKey=(n,e)=>getConversationKey(n,e),nip44Encrypt=(n,e,t)=>encrypt2(JSON.stringify(n),nip44ConversationKey(e,t)),nip44Decrypt=(n,e)=>JSON.parse(decrypt2(n.content,nip44ConversationKey(e,n.pubkey)));function createRumor(n,e){const t={created_at:now$1(),content:"",tags:[],...n,pubkey:getPublicKey$1(e)};return t.id=getEventHash$2(t),t}function createSeal(n,e,t){return finalizeEvent$1({kind:Seal,content:nip44Encrypt(n,e,t),created_at:randomNow(),tags:[]},e)}function createWrap(n,e){const t=generateSecretKey$1();return finalizeEvent$1({kind:GiftWrap,content:nip44Encrypt(n,t,e),created_at:randomNow(),tags:[["p",e]]},t)}function wrapEvent$1(n,e,t){const r=createRumor(n,e),s=createSeal(r,e,t);return createWrap(s,t)}function wrapManyEvents(n,e,t){if(!t||t.length===0)throw new Error("At least one recipient is required.");const r=getPublicKey$1(e),s=[wrapEvent$1(n,e,r)];return t.forEach(o=>{s.push(wrapEvent$1(n,e,o))}),s}function unwrapEvent(n,e){const t=nip44Decrypt(n,e);return nip44Decrypt(t,e)}function unwrapManyEvents(n,e){let t=[];return n.forEach(r=>{t.push(unwrapEvent(r,e))}),t.sort((r,s)=>r.created_at-s.created_at),t}function createEvent(n,e,t,r){const s={created_at:Math.ceil(Date.now()/1e3),kind:PrivateDirectMessage,tags:[],content:e};return(Array.isArray(n)?n:[n]).forEach(({publicKey:a,relayUrl:u})=>{s.tags.push(u?["p",a,u]:["p",a])}),r&&s.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),t&&s.tags.push(["subject",t]),s}function wrapEvent2(n,e,t,r,s){const o=createEvent(e,t,r,s);return wrapEvent$1(o,n,e.publicKey)}function wrapManyEvents2(n,e,t,r,s){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:getPublicKey$1(n)},...e].map(a=>wrapEvent2(n,a,t,r,s))}var unwrapEvent2=unwrapEvent,unwrapManyEvents2=unwrapManyEvents,nip18_exports={};__export(nip18_exports,{finishRepostEvent:()=>finishRepostEvent,getRepostedEvent:()=>getRepostedEvent,getRepostedEventPointer:()=>getRepostedEventPointer});function finishRepostEvent(n,e,t,r){var a;let s;const o=[...n.tags??[],["e",e.id,t],["p",e.pubkey]];return e.kind===ShortTextNote?s=Repost:(s=GenericRepost,o.push(["k",String(e.kind)])),finalizeEvent$1({kind:s,tags:o,content:n.content===""||(a=e.tags)!=null&&a.find(u=>u[0]==="-")?"":JSON.stringify(e),created_at:n.created_at},r)}function getRepostedEventPointer(n){if(![Repost,GenericRepost].includes(n.kind))return;let e,t;for(let r=n.tags.length-1;r>=0&&(e===void 0||t===void 0);r--){const s=n.tags[r];s.length>=2&&(s[0]==="e"&&e===void 0?e=s:s[0]==="p"&&t===void 0&&(t=s))}if(e!==void 0)return{id:e[1],relays:[e[2],t==null?void 0:t[2]].filter(r=>typeof r=="string"),author:t==null?void 0:t[1]}}function getRepostedEvent(n,{skipVerification:e}={}){const t=getRepostedEventPointer(n);if(t===void 0||n.content==="")return;let r;try{r=JSON.parse(n.content)}catch{return}if(r.id===t.id&&!(!e&&!verifyEvent(r)))return r}var nip21_exports={};__export(nip21_exports,{NOSTR_URI_REGEX:()=>NOSTR_URI_REGEX,parse:()=>parse2,test:()=>test});var NOSTR_URI_REGEX=new RegExp(`nostr:(${BECH32_REGEX$1.source})`);function test(n){return typeof n=="string"&&new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(n)}function parse2(n){const e=n.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${n}`);return{uri:e[0],value:e[1],decoded:decode(e[1])}}var nip25_exports={};__export(nip25_exports,{finishReactionEvent:()=>finishReactionEvent,getReactedEventPointer:()=>getReactedEventPointer});function finishReactionEvent(n,e,t){const r=e.tags.filter(s=>s.length>=2&&(s[0]==="e"||s[0]==="p"));return finalizeEvent$1({...n,kind:Reaction,tags:[...n.tags??[],...r,["e",e.id],["p",e.pubkey]],content:n.content??"+"},t)}function getReactedEventPointer(n){if(n.kind!==Reaction)return;let e,t;for(let r=n.tags.length-1;r>=0&&(e===void 0||t===void 0);r--){const s=n.tags[r];s.length>=2&&(s[0]==="e"&&e===void 0?e=s:s[0]==="p"&&t===void 0&&(t=s))}if(!(e===void 0||t===void 0))return{id:e[1],relays:[e[2],t[2]].filter(r=>r!==void 0),author:t[1]}}var nip27_exports={};__export(nip27_exports,{parse:()=>parse3});var noCharacter=/\W/m,noURLCharacter=/\W |\W$|$|,| /m;function*parse3(n){const e=n.length;let t=0,r=0;for(;r<e;){let s=n.indexOf(":",r);if(s===-1)break;if(n.substring(s-5,s)==="nostr"){const o=n.substring(s+60).match(noCharacter),a=o?s+60+o.index:e;try{let u,{data:c,type:l}=decode(n.substring(s+1,a));switch(l){case"npub":u={pubkey:c};break;case"nsec":case"note":r=a+1;continue;default:u=c}t!==s-5&&(yield{type:"text",text:n.substring(t,s-5)}),yield{type:"reference",pointer:u},r=a,t=r;continue}catch{r=s+1;continue}}else if(n.substring(s-5,s)==="https"||n.substring(s-4,s)==="http"){const o=n.substring(s+4).match(noURLCharacter),a=o?s+4+o.index:e,u=n[s-1]==="s"?5:4;try{let c=new URL(n.substring(s-u,a));if(c.hostname.indexOf(".")===-1)throw new Error("invalid url");if(t!==s-u&&(yield{type:"text",text:n.substring(t,s-u)}),c.pathname.endsWith(".png")||c.pathname.endsWith(".jpg")||c.pathname.endsWith(".jpeg")||c.pathname.endsWith(".gif")||c.pathname.endsWith(".webp")){yield{type:"image",url:c.toString()},r=a,t=r;continue}if(c.pathname.endsWith(".mp4")||c.pathname.endsWith(".avi")||c.pathname.endsWith(".webm")||c.pathname.endsWith(".mkv")){yield{type:"video",url:c.toString()},r=a,t=r;continue}if(c.pathname.endsWith(".mp3")||c.pathname.endsWith(".aac")||c.pathname.endsWith(".ogg")||c.pathname.endsWith(".opus")){yield{type:"audio",url:c.toString()},r=a,t=r;continue}yield{type:"url",url:c.toString()},r=a,t=r;continue}catch{r=a+1;continue}}else if(n.substring(s-3,s)==="wss"||n.substring(s-2,s)==="ws"){const o=n.substring(s+4).match(noURLCharacter),a=o?s+4+o.index:e,u=n[s-1]==="s"?3:2;try{let c=new URL(n.substring(s-u,a));if(c.hostname.indexOf(".")===-1)throw new Error("invalid ws url");t!==s-u&&(yield{type:"text",text:n.substring(t,s-u)}),yield{type:"relay",url:c.toString()},r=a,t=r;continue}catch{r=a+1;continue}}else{r=s+1;continue}}t!==e&&(yield{type:"text",text:n.substring(t)})}var nip28_exports={};__export(nip28_exports,{channelCreateEvent:()=>channelCreateEvent,channelHideMessageEvent:()=>channelHideMessageEvent,channelMessageEvent:()=>channelMessageEvent,channelMetadataEvent:()=>channelMetadataEvent,channelMuteUserEvent:()=>channelMuteUserEvent});var channelCreateEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelCreation,tags:[...n.tags??[]],content:t,created_at:n.created_at},e)},channelMetadataEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelMetadata,tags:[["e",n.channel_create_event_id],...n.tags??[]],content:t,created_at:n.created_at},e)},channelMessageEvent=(n,e)=>{const t=[["e",n.channel_create_event_id,n.relay_url,"root"]];return n.reply_to_channel_message_event_id&&t.push(["e",n.reply_to_channel_message_event_id,n.relay_url,"reply"]),finalizeEvent$1({kind:ChannelMessage,tags:[...t,...n.tags??[]],content:n.content,created_at:n.created_at},e)},channelHideMessageEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelHideMessage,tags:[["e",n.channel_message_event_id],...n.tags??[]],content:t,created_at:n.created_at},e)},channelMuteUserEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelMuteUser,tags:[["p",n.pubkey_to_mute],...n.tags??[]],content:t,created_at:n.created_at},e)},nip30_exports={};__export(nip30_exports,{EMOJI_SHORTCODE_REGEX:()=>EMOJI_SHORTCODE_REGEX,matchAll:()=>matchAll,regex:()=>regex$1,replaceAll:()=>replaceAll});var EMOJI_SHORTCODE_REGEX=/:(\w+):/,regex$1=()=>new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`,"g");function*matchAll(n){const e=n.matchAll(regex$1());for(const t of e)try{const[r,s]=t;yield{shortcode:r,name:s,start:t.index,end:t.index+r.length}}catch{}}function replaceAll(n,e){return n.replaceAll(regex$1(),(t,r)=>e({shortcode:t,name:r}))}var nip39_exports={};__export(nip39_exports,{useFetchImplementation:()=>useFetchImplementation3,validateGithub:()=>validateGithub});var _fetch3;try{_fetch3=fetch}catch{}function useFetchImplementation3(n){_fetch3=n}async function validateGithub(n,e,t){try{return await(await _fetch3(`https://gist.github.com/${e}/${t}/raw`)).text()===`Verifying that I control the following Nostr public key: ${n}`}catch{return!1}}var nip47_exports={};__export(nip47_exports,{makeNwcRequestEvent:()=>makeNwcRequestEvent,parseConnectionString:()=>parseConnectionString});function parseConnectionString(n){const{pathname:e,searchParams:t}=new URL(n),r=e,s=t.get("relay"),o=t.get("secret");if(!r||!s||!o)throw new Error("invalid connection string");return{pubkey:r,relay:s,secret:o}}async function makeNwcRequestEvent(n,e,t){const s=await encrypt$1(e,n,JSON.stringify({method:"pay_invoice",params:{invoice:t}})),o={kind:NWCWalletRequest,created_at:Math.round(Date.now()/1e3),content:s,tags:[["p",n]]};return finalizeEvent$1(o,e)}var nip54_exports={};__export(nip54_exports,{normalizeIdentifier:()=>normalizeIdentifier});function normalizeIdentifier(n){return n=n.trim().toLowerCase(),n=n.normalize("NFKC"),Array.from(n).map(e=>new RegExp("\\p{Letter}","u").test(e)||new RegExp("\\p{Number}","u").test(e)?e:"-").join("")}var nip57_exports={};__export(nip57_exports,{getZapEndpoint:()=>getZapEndpoint$1,makeZapReceipt:()=>makeZapReceipt,makeZapRequest:()=>makeZapRequest,useFetchImplementation:()=>useFetchImplementation4,validateZapRequest:()=>validateZapRequest});var _fetch4;try{_fetch4=fetch}catch{}function useFetchImplementation4(n){_fetch4=n}async function getZapEndpoint$1(n){try{let e="",{lud06:t,lud16:r}=JSON.parse(n.content);if(t){let{words:a}=bech32$1.decode(t,1e3),u=bech32$1.fromWords(a);e=utf8Decoder.decode(u)}else if(r){let[a,u]=r.split("@");e=new URL(`/.well-known/lnurlp/${a}`,`https://${u}`).toString()}else return null;let o=await(await _fetch4(e)).json();if(o.allowsNostr&&o.nostrPubkey)return o.callback}catch{}return null}function makeZapRequest({profile:n,event:e,amount:t,relays:r,comment:s=""}){if(!t)throw new Error("amount not given");if(!n)throw new Error("profile not given");let o={kind:9734,created_at:Math.round(Date.now()/1e3),content:s,tags:[["p",n],["amount",t.toString()],["relays",...r]]};if(e&&typeof e=="string"&&o.tags.push(["e",e]),e&&typeof e=="object"){if(isReplaceableKind(e.kind)){const a=["a",`${e.kind}:${e.pubkey}:`];o.tags.push(a)}else if(isAddressableKind(e.kind)){let a=e.tags.find(([c,l])=>c==="d"&&l);if(!a)throw new Error("d tag not found or is empty");const u=["a",`${e.kind}:${e.pubkey}:${a[1]}`];o.tags.push(u)}}return o}function validateZapRequest(n){let e;try{e=JSON.parse(n)}catch{return"Invalid zap request JSON."}if(!validateEvent$1(e))return"Zap request is not a valid Nostr event.";if(!verifyEvent(e))return"Invalid signature on zap request.";let t=e.tags.find(([o,a])=>o==="p"&&a);if(!t)return"Zap request doesn't have a 'p' tag.";if(!t[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=e.tags.find(([o,a])=>o==="e"&&a);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":e.tags.find(([o,a])=>o==="relays"&&a)?null:"Zap request doesn't have a 'relays' tag."}function makeZapReceipt({zapRequest:n,preimage:e,bolt11:t,paidAt:r}){let s=JSON.parse(n),o=s.tags.filter(([u])=>u==="e"||u==="p"||u==="a"),a={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...o,["P",s.pubkey],["bolt11",t],["description",n]]};return e&&a.tags.push(["preimage",e]),a}var nip98_exports={};__export(nip98_exports,{getToken:()=>getToken,hashPayload:()=>hashPayload,unpackEventFromToken:()=>unpackEventFromToken,validateEvent:()=>validateEvent2,validateEventKind:()=>validateEventKind,validateEventMethodTag:()=>validateEventMethodTag,validateEventPayloadTag:()=>validateEventPayloadTag,validateEventTimestamp:()=>validateEventTimestamp,validateEventUrlTag:()=>validateEventUrlTag,validateToken:()=>validateToken});var _authorizationScheme="Nostr ";async function getToken(n,e,t,r=!1,s){const o={kind:HTTPAuth,tags:[["u",n],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};s&&o.tags.push(["payload",hashPayload(s)]);const a=await t(o);return(r?_authorizationScheme:"")+base64.encode(utf8Encoder$1.encode(JSON.stringify(a)))}async function validateToken(n,e,t){const r=await unpackEventFromToken(n).catch(o=>{throw o});return await validateEvent2(r,e,t).catch(o=>{throw o})}async function unpackEventFromToken(n){if(!n)throw new Error("Missing token");n=n.replace(_authorizationScheme,"");const e=utf8Decoder.decode(base64.decode(n));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function validateEventTimestamp(n){return n.created_at?Math.round(new Date().getTime()/1e3)-n.created_at<60:!1}function validateEventKind(n){return n.kind===HTTPAuth}function validateEventUrlTag(n,e){const t=n.tags.find(r=>r[0]==="u");return t?t.length>0&&t[1]===e:!1}function validateEventMethodTag(n,e){const t=n.tags.find(r=>r[0]==="method");return t?t.length>0&&t[1].toLowerCase()===e.toLowerCase():!1}function hashPayload(n){const e=sha256$1(utf8Encoder$1.encode(JSON.stringify(n)));return bytesToHex$2(e)}function validateEventPayloadTag(n,e){const t=n.tags.find(s=>s[0]==="payload");if(!t)return!1;const r=hashPayload(e);return t.length>0&&t[1]===r}async function validateEvent2(n,e,t,r){if(!verifyEvent(n))throw new Error("Invalid nostr event, signature invalid");if(!validateEventKind(n))throw new Error("Invalid nostr event, kind invalid");if(!validateEventTimestamp(n))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!validateEventUrlTag(n,e))throw new Error("Invalid nostr event, url tag invalid");if(!validateEventMethodTag(n,t))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!validateEventPayloadTag(n,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const index$1=Object.freeze(Object.defineProperty({__proto__:null,SimplePool,finalizeEvent:finalizeEvent$1,fj:fakejson_exports,generateSecretKey:generateSecretKey$1,getEventHash:getEventHash$2,getPublicKey:getPublicKey$1,kinds:kinds_exports,matchFilter,matchFilters,nip04:nip04_exports,nip05:nip05_exports,nip10:nip10_exports,nip11:nip11_exports,nip13:nip13_exports,nip17:nip17_exports,nip18:nip18_exports,nip19:nip19_exports,nip21:nip21_exports,nip25:nip25_exports,nip27:nip27_exports,nip28:nip28_exports,nip30:nip30_exports,nip39:nip39_exports,nip42:nip42_exports,nip44:nip44_exports,nip47:nip47_exports,nip54:nip54_exports,nip57:nip57_exports,nip59:nip59_exports,nip98:nip98_exports,serializeEvent:serializeEvent$1,utils:utils_exports,validateEvent:validateEvent$1,verifiedSymbol:verifiedSymbol$1,verifyEvent},Symbol.toStringTag,{value:"Module"}));function anumber(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function isBytes$1(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function abytes$1(n,...e){if(!isBytes$1(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function ahash(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");anumber(n.outputLen),anumber(n.blockLen)}function aexists(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function aoutput(n,e){abytes$1(n);const t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const crypto$1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function createView(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function rotr(n,e){return n<<32-e|n>>>e}const hexes$1=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$1(n){abytes$1(n);let e="";for(let t=0;t<n.length;t++)e+=hexes$1[n[t]];return e}const asciis$1={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16$1(n){if(n>=asciis$1._0&&n<=asciis$1._9)return n-asciis$1._0;if(n>=asciis$1.A&&n<=asciis$1.F)return n-(asciis$1.A-10);if(n>=asciis$1.a&&n<=asciis$1.f)return n-(asciis$1.a-10)}function hexToBytes$1(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){const a=asciiToBase16$1(n.charCodeAt(o)),u=asciiToBase16$1(n.charCodeAt(o+1));if(a===void 0||u===void 0){const c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=a*16+u}return r}function utf8ToBytes$1(n){if(typeof n!="string")throw new Error("utf8ToBytes expected string, got "+typeof n);return new Uint8Array(new TextEncoder().encode(n))}function toBytes(n){return typeof n=="string"&&(n=utf8ToBytes$1(n)),abytes$1(n),n}function concatBytes$1(...n){let e=0;for(let r=0;r<n.length;r++){const s=n[r];abytes$1(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){const o=n[r];t.set(o,s),s+=o.length}return t}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(n){const e=r=>n().update(toBytes(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes(n=32){if(crypto$1&&typeof crypto$1.getRandomValues=="function")return crypto$1.getRandomValues(new Uint8Array(n));if(crypto$1&&typeof crypto$1.randomBytes=="function")return crypto$1.randomBytes(n);throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),u=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,a,r),n.setUint32(e+l,u,r)}function Chi(n,e,t){return n&e^~n&t}function Maj(n,e,t){return n&e^n&t^e&t}class HashMD extends Hash{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes(e);const o=e.length;for(let a=0;a<o;){const u=Math.min(s-this.pos,o-a);if(u===s){const c=createView(e);for(;s<=o-a;a+=s)this.process(c,a);continue}r.set(e.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){aexists(this),aoutput(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let f=a;f<s;f++)t[f]=0;setBigUint64(r,s-8,BigInt(this.length*8),o),this.process(r,0);const u=createView(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)u.setUint32(4*f,h[f],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:u}=this;return e.length=s,e.pos=u,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}}const SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),SHA256_IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(){super(64,32,8,!1),this.A=SHA256_IV[0]|0,this.B=SHA256_IV[1]|0,this.C=SHA256_IV[2]|0,this.D=SHA256_IV[3]|0,this.E=SHA256_IV[4]|0,this.F=SHA256_IV[5]|0,this.G=SHA256_IV[6]|0,this.H=SHA256_IV[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:u,H:c}=this;return[e,t,r,s,o,a,u,c]}set(e,t,r,s,o,a,u,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=u|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)SHA256_W[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){const p=SHA256_W[f-15],b=SHA256_W[f-2],v=rotr(p,7)^rotr(p,18)^p>>>3,m=rotr(b,17)^rotr(b,19)^b>>>10;SHA256_W[f]=m+SHA256_W[f-7]+v+SHA256_W[f-16]|0}let{A:r,B:s,C:o,D:a,E:u,F:c,G:l,H:h}=this;for(let f=0;f<64;f++){const p=rotr(u,6)^rotr(u,11)^rotr(u,25),b=h+p+Chi(u,c,l)+SHA256_K[f]+SHA256_W[f]|0,m=(rotr(r,2)^rotr(r,13)^rotr(r,22))+Maj(r,s,o)|0;h=l,l=c,c=u,u=a+b|0,a=o,o=s,s=r,r=b+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(r,s,o,a,u,c,l,h)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256=wrapConstructor(()=>new SHA256);class HMAC extends Hash{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ahash(e);const r=toBytes(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return aexists(this),this.iHash.update(e),this}digestInto(e){aexists(this),abytes$1(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=u,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(n,e,t)=>new HMAC(n,e).update(t).digest();hmac.create=(n,e)=>new HMAC(n,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2);function isBytes(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function abytes(n){if(!isBytes(n))throw new Error("Uint8Array expected")}function abool(n,e){if(typeof e!="boolean")throw new Error(n+" boolean expected, got "+e)}const hexes=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex(n){abytes(n);let e="";for(let t=0;t<n.length;t++)e+=hexes[n[t]];return e}function numberToHexUnpadded(n){const e=n.toString(16);return e.length&1?"0"+e:e}function hexToNumber(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?_0n$4:BigInt("0x"+n)}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(n){if(n>=asciis._0&&n<=asciis._9)return n-asciis._0;if(n>=asciis.A&&n<=asciis.F)return n-(asciis.A-10);if(n>=asciis.a&&n<=asciis.f)return n-(asciis.a-10)}function hexToBytes(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){const a=asciiToBase16(n.charCodeAt(o)),u=asciiToBase16(n.charCodeAt(o+1));if(a===void 0||u===void 0){const c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=a*16+u}return r}function bytesToNumberBE(n){return hexToNumber(bytesToHex(n))}function bytesToNumberLE(n){return abytes(n),hexToNumber(bytesToHex(Uint8Array.from(n).reverse()))}function numberToBytesBE(n,e){return hexToBytes(n.toString(16).padStart(e*2,"0"))}function numberToBytesLE(n,e){return numberToBytesBE(n,e).reverse()}function numberToVarBytesBE(n){return hexToBytes(numberToHexUnpadded(n))}function ensureBytes(n,e,t){let r;if(typeof e=="string")try{r=hexToBytes(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(isBytes(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(n+" of length "+t+" expected, got "+s);return r}function concatBytes(...n){let e=0;for(let r=0;r<n.length;r++){const s=n[r];abytes(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){const o=n[r];t.set(o,s),s+=o.length}return t}function equalBytes(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function utf8ToBytes(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}const isPosBig=n=>typeof n=="bigint"&&_0n$4<=n;function inRange(n,e,t){return isPosBig(n)&&isPosBig(e)&&isPosBig(t)&&e<=n&&n<t}function aInRange(n,e,t,r){if(!inRange(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function bitLen(n){let e;for(e=0;n>_0n$4;n>>=_1n$4,e+=1);return e}function bitGet(n,e){return n>>BigInt(e)&_1n$4}function bitSet(n,e,t){return n|(t?_1n$4:_0n$4)<<BigInt(e)}const bitMask=n=>(_2n$2<<BigInt(n-1))-_1n$4,u8n=n=>new Uint8Array(n),u8fr=n=>Uint8Array.from(n);function createHmacDrbg(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=u8n(n),s=u8n(n),o=0;const a=()=>{r.fill(1),s.fill(0),o=0},u=(...f)=>t(s,r,...f),c=(f=u8n())=>{s=u(u8fr([0]),f),r=u(),f.length!==0&&(s=u(u8fr([1]),f),r=u())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){r=u();const b=r.slice();p.push(b),f+=r.length}return concatBytes(...p)};return(f,p)=>{a(),c(f);let b;for(;!(b=p(l()));)c();return a(),b}}const validatorFns={bigint:n=>typeof n=="bigint",function:n=>typeof n=="function",boolean:n=>typeof n=="boolean",string:n=>typeof n=="string",stringOrUint8Array:n=>typeof n=="string"||isBytes(n),isSafeInteger:n=>Number.isSafeInteger(n),array:n=>Array.isArray(n),field:(n,e)=>e.Fp.isValid(n),hash:n=>typeof n=="function"&&Number.isSafeInteger(n.outputLen)};function validateObject(n,e,t={}){const r=(s,o,a)=>{const u=validatorFns[o];if(typeof u!="function")throw new Error("invalid validator function");const c=n[s];if(!(a&&c===void 0)&&!u(c,n))throw new Error("param "+String(s)+" is invalid. Expected "+o+", got "+c)};for(const[s,o]of Object.entries(e))r(s,o,!1);for(const[s,o]of Object.entries(t))r(s,o,!0);return n}const notImplemented=()=>{throw new Error("not implemented")};function memoized(n){const e=new WeakMap;return(t,...r)=>{const s=e.get(t);if(s!==void 0)return s;const o=n(t,...r);return e.set(t,o),o}}const ut=Object.freeze(Object.defineProperty({__proto__:null,aInRange,abool,abytes,bitGet,bitLen,bitMask,bitSet,bytesToHex,bytesToNumberBE,bytesToNumberLE,concatBytes,createHmacDrbg,ensureBytes,equalBytes,hexToBytes,hexToNumber,inRange,isBytes,memoized,notImplemented,numberToBytesBE,numberToBytesLE,numberToHexUnpadded,numberToVarBytesBE,utf8ToBytes,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$3=BigInt(1),_2n$1=BigInt(2),_3n$1=BigInt(3),_4n=BigInt(4),_5n=BigInt(5),_8n=BigInt(8);function mod(n,e){const t=n%e;return t>=_0n$3?t:e+t}function pow(n,e,t){if(e<_0n$3)throw new Error("invalid exponent, negatives unsupported");if(t<=_0n$3)throw new Error("invalid modulus");if(t===_1n$3)return _0n$3;let r=_1n$3;for(;e>_0n$3;)e&_1n$3&&(r=r*n%t),n=n*n%t,e>>=_1n$3;return r}function pow2(n,e,t){let r=n;for(;e-- >_0n$3;)r*=r,r%=t;return r}function invert(n,e){if(n===_0n$3)throw new Error("invert: expected non-zero number");if(e<=_0n$3)throw new Error("invert: expected positive modulus, got "+e);let t=mod(n,e),r=e,s=_0n$3,o=_1n$3;for(;t!==_0n$3;){const u=r/t,c=r%t,l=s-o*u;r=t,t=c,s=o,o=l}if(r!==_1n$3)throw new Error("invert: does not exist");return mod(s,e)}function tonelliShanks(n){const e=(n-_1n$3)/_2n$1;let t,r,s;for(t=n-_1n$3,r=0;t%_2n$1===_0n$3;t/=_2n$1,r++);for(s=_2n$1;s<n&&pow(s,e,n)!==n-_1n$3;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const a=(n+_1n$3)/_4n;return function(c,l){const h=c.pow(l,a);if(!c.eql(c.sqr(h),l))throw new Error("Cannot find square root");return h}}const o=(t+_1n$3)/_2n$1;return function(u,c){if(u.pow(c,e)===u.neg(u.ONE))throw new Error("Cannot find square root");let l=r,h=u.pow(u.mul(u.ONE,s),t),f=u.pow(c,o),p=u.pow(c,t);for(;!u.eql(p,u.ONE);){if(u.eql(p,u.ZERO))return u.ZERO;let b=1;for(let m=u.sqr(p);b<l&&!u.eql(m,u.ONE);b++)m=u.sqr(m);const v=u.pow(h,_1n$3<<BigInt(l-b-1));h=u.sqr(v),f=u.mul(f,v),p=u.mul(p,h),l=b}return f}}function FpSqrt(n){if(n%_4n===_3n$1){const e=(n+_1n$3)/_4n;return function(r,s){const o=r.pow(s,e);if(!r.eql(r.sqr(o),s))throw new Error("Cannot find square root");return o}}if(n%_8n===_5n){const e=(n-_5n)/_8n;return function(r,s){const o=r.mul(s,_2n$1),a=r.pow(o,e),u=r.mul(s,a),c=r.mul(r.mul(u,_2n$1),a),l=r.mul(u,r.sub(c,r.ONE));if(!r.eql(r.sqr(l),s))throw new Error("Cannot find square root");return l}}return tonelliShanks(n)}const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(n){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=FIELD_FIELDS.reduce((r,s)=>(r[s]="function",r),e);return validateObject(n,t)}function FpPow(n,e,t){if(t<_0n$3)throw new Error("invalid exponent, negatives unsupported");if(t===_0n$3)return n.ONE;if(t===_1n$3)return e;let r=n.ONE,s=e;for(;t>_0n$3;)t&_1n$3&&(r=n.mul(r,s)),s=n.sqr(s),t>>=_1n$3;return r}function FpInvertBatch(n,e){const t=new Array(e.length),r=e.reduce((o,a,u)=>n.is0(a)?o:(t[u]=o,n.mul(o,a)),n.ONE),s=n.inv(r);return e.reduceRight((o,a,u)=>n.is0(a)?o:(t[u]=n.mul(o,t[u]),n.mul(o,a)),s),t}function nLength(n,e){const t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Field(n,e,t=!1,r={}){if(n<=_0n$3)throw new Error("invalid field: expected ORDER > 0, got "+n);const{nBitLength:s,nByteLength:o}=nLength(n,e);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a;const u=Object.freeze({ORDER:n,isLE:t,BITS:s,BYTES:o,MASK:bitMask(s),ZERO:_0n$3,ONE:_1n$3,create:c=>mod(c,n),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return _0n$3<=c&&c<n},is0:c=>c===_0n$3,isOdd:c=>(c&_1n$3)===_1n$3,neg:c=>mod(-c,n),eql:(c,l)=>c===l,sqr:c=>mod(c*c,n),add:(c,l)=>mod(c+l,n),sub:(c,l)=>mod(c-l,n),mul:(c,l)=>mod(c*l,n),pow:(c,l)=>FpPow(u,c,l),div:(c,l)=>mod(c*invert(l,n),n),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>invert(c,n),sqrt:r.sqrt||(c=>(a||(a=FpSqrt(n)),a(u,c))),invertBatch:c=>FpInvertBatch(u,c),cmov:(c,l,h)=>h?l:c,toBytes:c=>t?numberToBytesLE(c,o):numberToBytesBE(c,o),fromBytes:c=>{if(c.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+c.length);return t?bytesToNumberLE(c):bytesToNumberBE(c)}});return Object.freeze(u)}function getFieldBytesLength(n){if(typeof n!="bigint")throw new Error("field order must be bigint");const e=n.toString(2).length;return Math.ceil(e/8)}function getMinHashLength(n){const e=getFieldBytesLength(n);return e+Math.ceil(e/2)}function mapHashToField(n,e,t=!1){const r=n.length,s=getFieldBytesLength(e),o=getMinHashLength(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const a=t?bytesToNumberLE(n):bytesToNumberBE(n),u=mod(a,e-_1n$3)+_1n$3;return t?numberToBytesLE(u,s):numberToBytesBE(u,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$2=BigInt(1);function constTimeNegate(n,e){const t=e.negate();return n?t:e}function validateW(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function calcWOpts(n,e){validateW(n,e);const t=Math.ceil(e/n)+1,r=2**(n-1);return{windows:t,windowSize:r}}function validateMSMPoints(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function validateMSMScalars(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(n){return pointWindowSizes.get(n)||1}function wNAF(n,e){return{constTimeNegate,hasPrecomputes(t){return getW(t)!==1},unsafeLadder(t,r,s=n.ZERO){let o=t;for(;r>_0n$2;)r&_1n$2&&(s=s.add(o)),o=o.double(),r>>=_1n$2;return s},precomputeWindow(t,r){const{windows:s,windowSize:o}=calcWOpts(r,e),a=[];let u=t,c=u;for(let l=0;l<s;l++){c=u,a.push(c);for(let h=1;h<o;h++)c=c.add(u),a.push(c);u=c.double()}return a},wNAF(t,r,s){const{windows:o,windowSize:a}=calcWOpts(t,e);let u=n.ZERO,c=n.BASE;const l=BigInt(2**t-1),h=2**t,f=BigInt(t);for(let p=0;p<o;p++){const b=p*a;let v=Number(s&l);s>>=f,v>a&&(v-=h,s+=_1n$2);const m=b,y=b+Math.abs(v)-1,w=p%2!==0,x=v<0;v===0?c=c.add(constTimeNegate(w,r[m])):u=u.add(constTimeNegate(x,r[y]))}return{p:u,f:c}},wNAFUnsafe(t,r,s,o=n.ZERO){const{windows:a,windowSize:u}=calcWOpts(t,e),c=BigInt(2**t-1),l=2**t,h=BigInt(t);for(let f=0;f<a;f++){const p=f*u;if(s===_0n$2)break;let b=Number(s&c);if(s>>=h,b>u&&(b-=l,s+=_1n$2),b===0)continue;let v=r[p+Math.abs(b)-1];b<0&&(v=v.negate()),o=o.add(v)}return o},getPrecomputes(t,r,s){let o=pointPrecomputes.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&pointPrecomputes.set(r,s(o))),o},wNAFCached(t,r,s){const o=getW(t);return this.wNAF(o,this.getPrecomputes(o,t,s),r)},wNAFCachedUnsafe(t,r,s,o){const a=getW(t);return a===1?this.unsafeLadder(t,r,o):this.wNAFUnsafe(a,this.getPrecomputes(a,t,s),r,o)},setWindowSize(t,r){validateW(r,e),pointWindowSizes.set(t,r),pointPrecomputes.delete(t)}}}function pippenger(n,e,t,r){if(validateMSMPoints(t,n),validateMSMScalars(r,e),t.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=n.ZERO,o=bitLen(BigInt(t.length)),a=o>12?o-3:o>4?o-2:o?2:1,u=(1<<a)-1,c=new Array(u+1).fill(s),l=Math.floor((e.BITS-1)/a)*a;let h=s;for(let f=l;f>=0;f-=a){c.fill(s);for(let b=0;b<r.length;b++){const v=r[b],m=Number(v>>BigInt(f)&BigInt(u));c[m]=c[m].add(t[b])}let p=s;for(let b=c.length-1,v=s;b>0;b--)v=v.add(c[b]),p=p.add(v);if(h=h.add(p),f!==0)for(let b=0;b<a;b++)h=h.double()}return h}function validateBasic(n){return validateField(n.Fp),validateObject(n,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength(n.n,n.nBitLength),...n,p:n.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validateSigVerOpts(n){n.lowS!==void 0&&abool("lowS",n.lowS),n.prehash!==void 0&&abool("prehash",n.prehash)}function validatePointOpts(n){const e=validateBasic(n);validateObject(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=e;if(t){if(!r.eql(s,r.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut;class DERErr extends Error{constructor(e=""){super(e)}}const DER={Err:DERErr,_tlv:{encode:(n,e)=>{const{Err:t}=DER;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const r=e.length/2,s=numberToHexUnpadded(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");const o=r>127?numberToHexUnpadded(s.length/2|128):"";return numberToHexUnpadded(n)+o+s+e},decode(n,e){const{Err:t}=DER;let r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");const s=e[r++],o=!!(s&128);let a=0;if(!o)a=s;else{const c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const h of l)a=a<<8|h;if(r+=c,a<128)throw new t("tlv.decode(long): not minimal encoding")}const u=e.subarray(r,r+a);if(u.length!==a)throw new t("tlv.decode: wrong value length");return{v:u,l:e.subarray(r+a)}}},_int:{encode(n){const{Err:e}=DER;if(n<_0n$1)throw new e("integer: negative integers are not allowed");let t=numberToHexUnpadded(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){const{Err:e}=DER;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return b2n(n)}},toSig(n){const{Err:e,_int:t,_tlv:r}=DER,s=typeof n=="string"?h2b(n):n;abytes(s);const{v:o,l:a}=r.decode(48,s);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:u,l:c}=r.decode(2,o),{v:l,l:h}=r.decode(2,c);if(h.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(u),s:t.decode(l)}},hexFromSig(n){const{_tlv:e,_int:t}=DER,r=e.encode(2,t.encode(n.r)),s=e.encode(2,t.encode(n.s)),o=r+s;return e.encode(48,o)}},_0n$1=BigInt(0),_1n$1=BigInt(1);BigInt(2);const _3n=BigInt(3);BigInt(4);function weierstrassPoints(n){const e=validatePointOpts(n),{Fp:t}=e,r=Field(e.n,e.nBitLength),s=e.toBytes||((m,y,w)=>{const x=y.toAffine();return concatBytes(Uint8Array.from([4]),t.toBytes(x.x),t.toBytes(x.y))}),o=e.fromBytes||(m=>{const y=m.subarray(1),w=t.fromBytes(y.subarray(0,t.BYTES)),x=t.fromBytes(y.subarray(t.BYTES,2*t.BYTES));return{x:w,y:x}});function a(m){const{a:y,b:w}=e,x=t.sqr(m),k=t.mul(x,m);return t.add(t.add(k,t.mul(m,y)),w)}if(!t.eql(t.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function u(m){return inRange(m,_1n$1,e.n)}function c(m){const{allowedPrivateKeyLengths:y,nByteLength:w,wrapPrivateKey:x,n:k}=e;if(y&&typeof m!="bigint"){if(isBytes(m)&&(m=bytesToHex(m)),typeof m!="string"||!y.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let C;try{C=typeof m=="bigint"?m:bytesToNumberBE(ensureBytes("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return x&&(C=mod(C,k)),aInRange("private key",C,_1n$1,k),C}function l(m){if(!(m instanceof p))throw new Error("ProjectivePoint expected")}const h=memoized((m,y)=>{const{px:w,py:x,pz:k}=m;if(t.eql(k,t.ONE))return{x:w,y:x};const C=m.is0();y==null&&(y=C?t.ONE:t.inv(k));const P=t.mul(w,y),R=t.mul(x,y),N=t.mul(k,y);if(C)return{x:t.ZERO,y:t.ZERO};if(!t.eql(N,t.ONE))throw new Error("invZ was invalid");return{x:P,y:R}}),f=memoized(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}const{x:y,y:w}=m.toAffine();if(!t.isValid(y)||!t.isValid(w))throw new Error("bad point: x or y not FE");const x=t.sqr(w),k=a(y);if(!t.eql(x,k))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(y,w,x){if(this.px=y,this.py=w,this.pz=x,y==null||!t.isValid(y))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(x==null||!t.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(y){const{x:w,y:x}=y||{};if(!y||!t.isValid(w)||!t.isValid(x))throw new Error("invalid affine point");if(y instanceof p)throw new Error("projective point not allowed");const k=C=>t.eql(C,t.ZERO);return k(w)&&k(x)?p.ZERO:new p(w,x,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){const w=t.invertBatch(y.map(x=>x.pz));return y.map((x,k)=>x.toAffine(w[k])).map(p.fromAffine)}static fromHex(y){const w=p.fromAffine(o(ensureBytes("pointHex",y)));return w.assertValidity(),w}static fromPrivateKey(y){return p.BASE.multiply(c(y))}static msm(y,w){return pippenger(p,r,y,w)}_setWindowSize(y){v.setWindowSize(this,y)}assertValidity(){f(this)}hasEvenY(){const{y}=this.toAffine();if(t.isOdd)return!t.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){l(y);const{px:w,py:x,pz:k}=this,{px:C,py:P,pz:R}=y,N=t.eql(t.mul(w,R),t.mul(C,k)),B=t.eql(t.mul(x,R),t.mul(P,k));return N&&B}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:y,b:w}=e,x=t.mul(w,_3n),{px:k,py:C,pz:P}=this;let R=t.ZERO,N=t.ZERO,B=t.ZERO,O=t.mul(k,k),H=t.mul(C,C),S=t.mul(P,P),_=t.mul(k,C);return _=t.add(_,_),B=t.mul(k,P),B=t.add(B,B),R=t.mul(y,B),N=t.mul(x,S),N=t.add(R,N),R=t.sub(H,N),N=t.add(H,N),N=t.mul(R,N),R=t.mul(_,R),B=t.mul(x,B),S=t.mul(y,S),_=t.sub(O,S),_=t.mul(y,_),_=t.add(_,B),B=t.add(O,O),O=t.add(B,O),O=t.add(O,S),O=t.mul(O,_),N=t.add(N,O),S=t.mul(C,P),S=t.add(S,S),O=t.mul(S,_),R=t.sub(R,O),B=t.mul(S,H),B=t.add(B,B),B=t.add(B,B),new p(R,N,B)}add(y){l(y);const{px:w,py:x,pz:k}=this,{px:C,py:P,pz:R}=y;let N=t.ZERO,B=t.ZERO,O=t.ZERO;const H=e.a,S=t.mul(e.b,_3n);let _=t.mul(w,C),L=t.mul(x,P),I=t.mul(k,R),A=t.add(w,x),E=t.add(C,P);A=t.mul(A,E),E=t.add(_,L),A=t.sub(A,E),E=t.add(w,k);let $=t.add(C,R);return E=t.mul(E,$),$=t.add(_,I),E=t.sub(E,$),$=t.add(x,k),N=t.add(P,R),$=t.mul($,N),N=t.add(L,I),$=t.sub($,N),O=t.mul(H,E),N=t.mul(S,I),O=t.add(N,O),N=t.sub(L,O),O=t.add(L,O),B=t.mul(N,O),L=t.add(_,_),L=t.add(L,_),I=t.mul(H,I),E=t.mul(S,E),L=t.add(L,I),I=t.sub(_,I),I=t.mul(H,I),E=t.add(E,I),_=t.mul(L,E),B=t.add(B,_),_=t.mul($,E),N=t.mul(A,N),N=t.sub(N,_),_=t.mul(A,L),O=t.mul($,O),O=t.add(O,_),new p(N,B,O)}subtract(y){return this.add(y.negate())}is0(){return this.equals(p.ZERO)}wNAF(y){return v.wNAFCached(this,y,p.normalizeZ)}multiplyUnsafe(y){const{endo:w,n:x}=e;aInRange("scalar",y,_0n$1,x);const k=p.ZERO;if(y===_0n$1)return k;if(this.is0()||y===_1n$1)return this;if(!w||v.hasPrecomputes(this))return v.wNAFCachedUnsafe(this,y,p.normalizeZ);let{k1neg:C,k1:P,k2neg:R,k2:N}=w.splitScalar(y),B=k,O=k,H=this;for(;P>_0n$1||N>_0n$1;)P&_1n$1&&(B=B.add(H)),N&_1n$1&&(O=O.add(H)),H=H.double(),P>>=_1n$1,N>>=_1n$1;return C&&(B=B.negate()),R&&(O=O.negate()),O=new p(t.mul(O.px,w.beta),O.py,O.pz),B.add(O)}multiply(y){const{endo:w,n:x}=e;aInRange("scalar",y,_1n$1,x);let k,C;if(w){const{k1neg:P,k1:R,k2neg:N,k2:B}=w.splitScalar(y);let{p:O,f:H}=this.wNAF(R),{p:S,f:_}=this.wNAF(B);O=v.constTimeNegate(P,O),S=v.constTimeNegate(N,S),S=new p(t.mul(S.px,w.beta),S.py,S.pz),k=O.add(S),C=H.add(_)}else{const{p:P,f:R}=this.wNAF(y);k=P,C=R}return p.normalizeZ([k,C])[0]}multiplyAndAddUnsafe(y,w,x){const k=p.BASE,C=(R,N)=>N===_0n$1||N===_1n$1||!R.equals(k)?R.multiplyUnsafe(N):R.multiply(N),P=C(this,w).add(C(y,x));return P.is0()?void 0:P}toAffine(y){return h(this,y)}isTorsionFree(){const{h:y,isTorsionFree:w}=e;if(y===_1n$1)return!0;if(w)return w(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:y,clearCofactor:w}=e;return y===_1n$1?this:w?w(p,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return abool("isCompressed",y),this.assertValidity(),s(p,this,y)}toHex(y=!0){return abool("isCompressed",y),bytesToHex(this.toRawBytes(y))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const b=e.nBitLength,v=wNAF(p,e.endo?Math.ceil(b/2):b);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:u}}function validateOpts(n){const e=validateBasic(n);return validateObject(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function weierstrass(n){const e=validateOpts(n),{Fp:t,n:r}=e,s=t.BYTES+1,o=2*t.BYTES+1;function a(I){return mod(I,r)}function u(I){return invert(I,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:h,isWithinCurveOrder:f}=weierstrassPoints({...e,toBytes(I,A,E){const $=A.toAffine(),M=t.toBytes($.x),U=concatBytes;return abool("isCompressed",E),E?U(Uint8Array.from([A.hasEvenY()?2:3]),M):U(Uint8Array.from([4]),M,t.toBytes($.y))},fromBytes(I){const A=I.length,E=I[0],$=I.subarray(1);if(A===s&&(E===2||E===3)){const M=bytesToNumberBE($);if(!inRange(M,_1n$1,t.ORDER))throw new Error("Point is not on curve");const U=h(M);let z;try{z=t.sqrt(U)}catch(W){const Z=W instanceof Error?": "+W.message:"";throw new Error("Point is not on curve"+Z)}const D=(z&_1n$1)===_1n$1;return(E&1)===1!==D&&(z=t.neg(z)),{x:M,y:z}}else if(A===o&&E===4){const M=t.fromBytes($.subarray(0,t.BYTES)),U=t.fromBytes($.subarray(t.BYTES,2*t.BYTES));return{x:M,y:U}}else{const M=s,U=o;throw new Error("invalid Point, expected length of "+M+", or uncompressed "+U+", got "+A)}}}),p=I=>bytesToHex(numberToBytesBE(I,e.nByteLength));function b(I){const A=r>>_1n$1;return I>A}function v(I){return b(I)?a(-I):I}const m=(I,A,E)=>bytesToNumberBE(I.slice(A,E));class y{constructor(A,E,$){this.r=A,this.s=E,this.recovery=$,this.assertValidity()}static fromCompact(A){const E=e.nByteLength;return A=ensureBytes("compactSignature",A,E*2),new y(m(A,0,E),m(A,E,2*E))}static fromDER(A){const{r:E,s:$}=DER.toSig(ensureBytes("DER",A));return new y(E,$)}assertValidity(){aInRange("r",this.r,_1n$1,r),aInRange("s",this.s,_1n$1,r)}addRecoveryBit(A){return new y(this.r,this.s,A)}recoverPublicKey(A){const{r:E,s:$,recovery:M}=this,U=R(ensureBytes("msgHash",A));if(M==null||![0,1,2,3].includes(M))throw new Error("recovery id invalid");const z=M===2||M===3?E+e.n:E;if(z>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const D=M&1?"03":"02",V=c.fromHex(D+p(z)),W=u(z),Z=a(-U*W),G=a($*W),K=c.BASE.multiplyAndAddUnsafe(V,Z,G);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return b(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const w={isValidPrivateKey(I){try{return l(I),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const I=getMinHashLength(e.n);return mapHashToField(e.randomBytes(I),e.n)},precompute(I=8,A=c.BASE){return A._setWindowSize(I),A.multiply(BigInt(3)),A}};function x(I,A=!0){return c.fromPrivateKey(I).toRawBytes(A)}function k(I){const A=isBytes(I),E=typeof I=="string",$=(A||E)&&I.length;return A?$===s||$===o:E?$===2*s||$===2*o:I instanceof c}function C(I,A,E=!0){if(k(I))throw new Error("first arg must be private key");if(!k(A))throw new Error("second arg must be public key");return c.fromHex(A).multiply(l(I)).toRawBytes(E)}const P=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const A=bytesToNumberBE(I),E=I.length*8-e.nBitLength;return E>0?A>>BigInt(E):A},R=e.bits2int_modN||function(I){return a(P(I))},N=bitMask(e.nBitLength);function B(I){return aInRange("num < 2^"+e.nBitLength,I,_0n$1,N),numberToBytesBE(I,e.nByteLength)}function O(I,A,E=H){if(["recovered","canonical"].some(ae=>ae in E))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:M}=e;let{lowS:U,prehash:z,extraEntropy:D}=E;U==null&&(U=!0),I=ensureBytes("msgHash",I),validateSigVerOpts(E),z&&(I=ensureBytes("prehashed msgHash",$(I)));const V=R(I),W=l(A),Z=[B(W),B(V)];if(D!=null&&D!==!1){const ae=D===!0?M(t.BYTES):D;Z.push(ensureBytes("extraEntropy",ae))}const G=concatBytes(...Z),K=V;function ne(ae){const se=P(ae);if(!f(se))return;const pe=u(se),ye=c.BASE.multiply(se).toAffine(),J=a(ye.x);if(J===_0n$1)return;const Q=a(pe*a(K+J*W));if(Q===_0n$1)return;let te=(ye.x===J?0:2)|Number(ye.y&_1n$1),be=Q;return U&&b(Q)&&(be=v(Q),te^=1),new y(J,be,te)}return{seed:G,k2sig:ne}}const H={lowS:e.lowS,prehash:!1},S={lowS:e.lowS,prehash:!1};function _(I,A,E=H){const{seed:$,k2sig:M}=O(I,A,E),U=e;return createHmacDrbg(U.hash.outputLen,U.nByteLength,U.hmac)($,M)}c.BASE._setWindowSize(8);function L(I,A,E,$=S){var te;const M=I;A=ensureBytes("msgHash",A),E=ensureBytes("publicKey",E);const{lowS:U,prehash:z,format:D}=$;if(validateSigVerOpts($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&D!=="compact"&&D!=="der")throw new Error("format must be compact or der");const V=typeof M=="string"||isBytes(M),W=!V&&!D&&typeof M=="object"&&M!==null&&typeof M.r=="bigint"&&typeof M.s=="bigint";if(!V&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Z,G;try{if(W&&(Z=new y(M.r,M.s)),V){try{D!=="compact"&&(Z=y.fromDER(M))}catch(be){if(!(be instanceof DER.Err))throw be}!Z&&D!=="der"&&(Z=y.fromCompact(M))}G=c.fromHex(E)}catch{return!1}if(!Z||U&&Z.hasHighS())return!1;z&&(A=e.hash(A));const{r:K,s:ne}=Z,ae=R(A),se=u(ne),pe=a(ae*se),ye=a(K*se),J=(te=c.BASE.multiplyAndAddUnsafe(G,pe,ye))==null?void 0:te.toAffine();return J?a(J.x)===K:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:C,sign:_,verify:L,ProjectivePoint:c,Signature:y,utils:w}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(n){return{hash:n,hmac:(e,...t)=>hmac(n,e,concatBytes$1(...t)),randomBytes}}function createCurve(n,e){const t=r=>weierstrass({...n,...getHash(r)});return{...t(e),create:t}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n=BigInt(1),_2n=BigInt(2),divNearest=(n,e)=>(n+e/_2n)/e;function sqrtMod(n){const e=secp256k1P,t=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),a=BigInt(23),u=BigInt(44),c=BigInt(88),l=n*n*n%e,h=l*l*n%e,f=pow2(h,t,e)*h%e,p=pow2(f,t,e)*h%e,b=pow2(p,_2n,e)*l%e,v=pow2(b,s,e)*b%e,m=pow2(v,o,e)*v%e,y=pow2(m,u,e)*m%e,w=pow2(y,c,e)*y%e,x=pow2(w,u,e)*m%e,k=pow2(x,t,e)*h%e,C=pow2(k,a,e)*v%e,P=pow2(C,r,e)*l%e,R=pow2(P,_2n,e);if(!Fpk1.eql(Fpk1.sqr(R),n))throw new Error("Cannot find square root");return R}const Fpk1=Field(secp256k1P,void 0,void 0,{sqrt:sqrtMod}),secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp:Fpk1,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:n=>{const e=secp256k1N,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,a=BigInt("0x100000000000000000000000000000000"),u=divNearest(o*n,e),c=divNearest(-r*n,e);let l=mod(n-u*t-c*s,e),h=mod(-u*r-c*o,e);const f=l>a,p=h>a;if(f&&(l=e-l),p&&(h=e-h),l>a||h>a)throw new Error("splitScalar: Endomorphism failed, k="+n);return{k1neg:f,k1:l,k2neg:p,k2:h}}}},sha256),_0n=BigInt(0),TAGGED_HASH_PREFIXES={};function taggedHash(n,...e){let t=TAGGED_HASH_PREFIXES[n];if(t===void 0){const r=sha256(Uint8Array.from(n,s=>s.charCodeAt(0)));t=concatBytes(r,r),TAGGED_HASH_PREFIXES[n]=t}return sha256(concatBytes(t,...e))}const pointToBytes=n=>n.toRawBytes(!0).slice(1),numTo32b=n=>numberToBytesBE(n,32),modP=n=>mod(n,secp256k1P),modN=n=>mod(n,secp256k1N),Point=secp256k1.ProjectivePoint,GmulAdd=(n,e,t)=>Point.BASE.multiplyAndAddUnsafe(n,e,t);function schnorrGetExtPubKey(n){let e=secp256k1.utils.normPrivateKeyToScalar(n),t=Point.fromPrivateKey(e);return{scalar:t.hasEvenY()?e:modN(-e),bytes:pointToBytes(t)}}function lift_x(n){aInRange("x",n,_1n,secp256k1P);const e=modP(n*n),t=modP(e*n+BigInt(7));let r=sqrtMod(t);r%_2n!==_0n&&(r=modP(-r));const s=new Point(n,r,_1n);return s.assertValidity(),s}const num=bytesToNumberBE;function challenge(...n){return modN(num(taggedHash("BIP0340/challenge",...n)))}function schnorrGetPublicKey(n){return schnorrGetExtPubKey(n).bytes}function schnorrSign(n,e,t=randomBytes(32)){const r=ensureBytes("message",n),{bytes:s,scalar:o}=schnorrGetExtPubKey(e),a=ensureBytes("auxRand",t,32),u=numTo32b(o^num(taggedHash("BIP0340/aux",a))),c=taggedHash("BIP0340/nonce",u,s,r),l=modN(num(c));if(l===_0n)throw new Error("sign failed: k is zero");const{bytes:h,scalar:f}=schnorrGetExtPubKey(l),p=challenge(h,s,r),b=new Uint8Array(64);if(b.set(h,0),b.set(numTo32b(modN(f+p*o)),32),!schnorrVerify(b,r,s))throw new Error("sign: Invalid signature produced");return b}function schnorrVerify(n,e,t){const r=ensureBytes("signature",n,64),s=ensureBytes("message",e),o=ensureBytes("publicKey",t,32);try{const a=lift_x(num(o)),u=num(r.subarray(0,32));if(!inRange(u,_1n,secp256k1P))return!1;const c=num(r.subarray(32,64));if(!inRange(c,_1n,secp256k1N))return!1;const l=challenge(numTo32b(u),pointToBytes(a),s),h=GmulAdd(a,c,modN(-l));return!(!h||!h.hasEvenY()||h.toAffine().x!==u)}catch{return!1}}const schnorr={getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,utils:{randomPrivateKey:secp256k1.utils.randomPrivateKey,lift_x,pointToBytes,numberToBytesBE,bytesToNumberBE,taggedHash,mod}};var dist={},LRUCache$1={},LRUCacheNode$1={};Object.defineProperty(LRUCacheNode$1,"__esModule",{value:!0}),LRUCacheNode$1.LRUCacheNode=void 0;class LRUCacheNode{constructor(e,t,r){const{entryExpirationTimeInMS:s=null,next:o=null,prev:a=null,onEntryEvicted:u,onEntryMarkedAsMostRecentlyUsed:c,clone:l,cloneFn:h}=r??{};if(typeof s=="number"&&(s<=0||Number.isNaN(s)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.clone=l??!1,this.cloneFn=h??this.defaultClone,this.key=e,this.internalValue=this.clone?this.cloneFn(t):t,this.created=Date.now(),this.entryExpirationTimeInMS=s,this.next=o,this.prev=a,this.onEntryEvicted=u,this.onEntryMarkedAsMostRecentlyUsed=c}get value(){return this.clone?this.cloneFn(this.internalValue):this.internalValue}get isExpired(){return typeof this.entryExpirationTimeInMS=="number"&&Date.now()-this.created>this.entryExpirationTimeInMS}invokeOnEvicted(){if(this.onEntryEvicted){const{key:e,value:t,isExpired:r}=this;this.onEntryEvicted({key:e,value:t,isExpired:r})}}invokeOnEntryMarkedAsMostRecentlyUsed(){if(this.onEntryMarkedAsMostRecentlyUsed){const{key:e,value:t}=this;this.onEntryMarkedAsMostRecentlyUsed({key:e,value:t})}}defaultClone(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"?e:JSON.parse(JSON.stringify(e))}}LRUCacheNode$1.LRUCacheNode=LRUCacheNode,Object.defineProperty(LRUCache$1,"__esModule",{value:!0}),LRUCache$1.LRUCache=void 0;const LRUCacheNode_1=LRUCacheNode$1;class LRUCache{constructor(e){this.lookupTable=new Map,this.head=null,this.tail=null;const{maxSize:t=25,entryExpirationTimeInMS:r=null,onEntryEvicted:s,onEntryMarkedAsMostRecentlyUsed:o,cloneFn:a,clone:u}=e??{};if(Number.isNaN(t)||t<=0)throw new Error("maxSize must be greater than 0.");if(typeof r=="number"&&(r<=0||Number.isNaN(r)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.maxSizeInternal=t,this.entryExpirationTimeInMS=r,this.onEntryEvicted=s,this.onEntryMarkedAsMostRecentlyUsed=o,this.clone=u,this.cloneFn=a}get size(){return this.cleanCache(),this.lookupTable.size}get remainingSize(){return this.maxSizeInternal-this.size}get newest(){return this.head?this.head.isExpired?(this.removeNodeFromListAndLookupTable(this.head),this.newest):this.mapNodeToEntry(this.head):null}get oldest(){return this.tail?this.tail.isExpired?(this.removeNodeFromListAndLookupTable(this.tail),this.oldest):this.mapNodeToEntry(this.tail):null}get maxSize(){return this.maxSizeInternal}set maxSize(e){if(Number.isNaN(e)||e<=0)throw new Error("maxSize must be greater than 0.");this.maxSizeInternal=e,this.enforceSizeLimit()}set(e,t,r){const s=this.lookupTable.get(e);s&&this.removeNodeFromListAndLookupTable(s);const o=new LRUCacheNode_1.LRUCacheNode(e,t,{entryExpirationTimeInMS:this.entryExpirationTimeInMS,onEntryEvicted:this.onEntryEvicted,onEntryMarkedAsMostRecentlyUsed:this.onEntryMarkedAsMostRecentlyUsed,clone:this.clone,cloneFn:this.cloneFn,...r});return this.setNodeAsHead(o),this.lookupTable.set(e,o),this.enforceSizeLimit(),this}get(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):(this.setNodeAsHead(t),t.value):null}peek(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):t.value:null}delete(e){const t=this.lookupTable.get(e);return t?this.removeNodeFromListAndLookupTable(t):!1}has(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),!1):!0:!1}clear(){this.head=null,this.tail=null,this.lookupTable.clear()}find(e){let t=this.head;for(;t;){if(t.isExpired){const s=t.next;this.removeNodeFromListAndLookupTable(t),t=s;continue}const r=this.mapNodeToEntry(t);if(e(r))return this.setNodeAsHead(t),r;t=t.next}return null}forEach(e){let t=this.head,r=0;for(;t;){if(t.isExpired){const s=t.next;this.removeNodeFromListAndLookupTable(t),t=s;continue}e(t.value,t.key,r),t=t.next,r++}}*values(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield e.value,e=e.next}}*keys(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield e.key,e=e.next}}*entries(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield this.mapNodeToEntry(e),e=e.next}}*[Symbol.iterator](){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield this.mapNodeToEntry(e),e=e.next}}enforceSizeLimit(){let e=this.tail;for(;e!==null&&this.size>this.maxSizeInternal;){const t=e.prev;this.removeNodeFromListAndLookupTable(e),e=t}}mapNodeToEntry({key:e,value:t}){return{key:e,value:t}}setNodeAsHead(e){this.removeNodeFromList(e),this.head?(e.next=this.head,this.head.prev=e,this.head=e):(this.head=e,this.tail=e),e.invokeOnEntryMarkedAsMostRecentlyUsed()}removeNodeFromList(e){e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.head===e&&(this.head=e.next),this.tail===e&&(this.tail=e.prev),e.next=null,e.prev=null}removeNodeFromListAndLookupTable(e){return e.invokeOnEvicted(),this.removeNodeFromList(e),this.lookupTable.delete(e.key)}cleanCache(){if(!this.entryExpirationTimeInMS)return;const e=[];for(const t of this.lookupTable.values())t.isExpired&&e.push(t);e.forEach(t=>this.removeNodeFromListAndLookupTable(t))}}LRUCache$1.LRUCache=LRUCache,function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,u)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(LRUCache$1,n)}(dist);var lib={};(function(n){/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(n,"__esModule",{value:!0}),n.bytes=n.stringToBytes=n.str=n.bytesToString=n.hex=n.utf8=n.bech32m=n.bech32=n.base58check=n.base58xmr=n.base58xrp=n.base58flickr=n.base58=n.base64url=n.base64=n.base32crockford=n.base32hex=n.base32=n.base16=n.utils=n.assertNumber=void 0;function e(S){if(!Number.isSafeInteger(S))throw new Error(`Wrong integer: ${S}`)}n.assertNumber=e;function t(...S){const _=(A,E)=>$=>A(E($)),L=Array.from(S).reverse().reduce((A,E)=>A?_(A,E.encode):E.encode,void 0),I=S.reduce((A,E)=>A?_(A,E.decode):E.decode,void 0);return{encode:L,decode:I}}function r(S){return{encode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return _.map(L=>{if(e(L),L<0||L>=S.length)throw new Error(`Digit index outside alphabet: ${L} (alphabet: ${S.length})`);return S[L]})},decode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="string")throw new Error("alphabet.decode input should be array of strings");return _.map(L=>{if(typeof L!="string")throw new Error(`alphabet.decode: not string element=${L}`);const I=S.indexOf(L);if(I===-1)throw new Error(`Unknown letter: "${L}". Allowed: ${S}`);return I})}}}function s(S=""){if(typeof S!="string")throw new Error("join separator should be string");return{encode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="string")throw new Error("join.encode input should be array of strings");for(let L of _)if(typeof L!="string")throw new Error(`join.encode: non-string input=${L}`);return _.join(S)},decode:_=>{if(typeof _!="string")throw new Error("join.decode input should be string");return _.split(S)}}}function o(S,_="="){if(e(S),typeof _!="string")throw new Error("padding chr should be string");return{encode(L){if(!Array.isArray(L)||L.length&&typeof L[0]!="string")throw new Error("padding.encode input should be array of strings");for(let I of L)if(typeof I!="string")throw new Error(`padding.encode: non-string input=${I}`);for(;L.length*S%8;)L.push(_);return L},decode(L){if(!Array.isArray(L)||L.length&&typeof L[0]!="string")throw new Error("padding.encode input should be array of strings");for(let A of L)if(typeof A!="string")throw new Error(`padding.decode: non-string input=${A}`);let I=L.length;if(I*S%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;I>0&&L[I-1]===_;I--)if(!((I-1)*S%8))throw new Error("Invalid padding: string has too much padding");return L.slice(0,I)}}}function a(S){if(typeof S!="function")throw new Error("normalize fn should be function");return{encode:_=>_,decode:_=>S(_)}}function u(S,_,L){if(_<2)throw new Error(`convertRadix: wrong from=${_}, base cannot be less than 2`);if(L<2)throw new Error(`convertRadix: wrong to=${L}, base cannot be less than 2`);if(!Array.isArray(S))throw new Error("convertRadix: data should be array");if(!S.length)return[];let I=0;const A=[],E=Array.from(S);for(E.forEach($=>{if(e($),$<0||$>=_)throw new Error(`Wrong integer: ${$}`)});;){let $=0,M=!0;for(let U=I;U<E.length;U++){const z=E[U],D=_*$+z;if(!Number.isSafeInteger(D)||_*$/_!==$||D-z!==_*$)throw new Error("convertRadix: carry overflow");if($=D%L,E[U]=Math.floor(D/L),!Number.isSafeInteger(E[U])||E[U]*L+$!==D)throw new Error("convertRadix: carry overflow");if(M)E[U]?M=!1:I=U;else continue}if(A.push($),M)break}for(let $=0;$<S.length-1&&S[$]===0;$++)A.push(0);return A.reverse()}const c=(S,_)=>_?c(_,S%_):S,l=(S,_)=>S+(_-c(S,_));function h(S,_,L,I){if(!Array.isArray(S))throw new Error("convertRadix2: data should be array");if(_<=0||_>32)throw new Error(`convertRadix2: wrong from=${_}`);if(L<=0||L>32)throw new Error(`convertRadix2: wrong to=${L}`);if(l(_,L)>32)throw new Error(`convertRadix2: carry overflow from=${_} to=${L} carryBits=${l(_,L)}`);let A=0,E=0;const $=2**L-1,M=[];for(const U of S){if(e(U),U>=2**_)throw new Error(`convertRadix2: invalid data word=${U} from=${_}`);if(A=A<<_|U,E+_>32)throw new Error(`convertRadix2: carry overflow pos=${E} from=${_}`);for(E+=_;E>=L;E-=L)M.push((A>>E-L&$)>>>0);A&=2**E-1}if(A=A<<L-E&$,!I&&E>=_)throw new Error("Excess padding");if(!I&&A)throw new Error(`Non-zero padding: ${A}`);return I&&E>0&&M.push(A>>>0),M}function f(S){return e(S),{encode:_=>{if(!(_ instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return u(Array.from(_),2**8,S)},decode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(u(_,S,2**8))}}}function p(S,_=!1){if(e(S),S<=0||S>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,S)>32||l(S,8)>32)throw new Error("radix2: carry overflow");return{encode:L=>{if(!(L instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(L),8,S,!_)},decode:L=>{if(!Array.isArray(L)||L.length&&typeof L[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(L,S,8,_))}}}function b(S){if(typeof S!="function")throw new Error("unsafeWrapper fn should be function");return function(..._){try{return S.apply(null,_)}catch{}}}function v(S,_){if(e(S),typeof _!="function")throw new Error("checksum fn should be function");return{encode(L){if(!(L instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const I=_(L).slice(0,S),A=new Uint8Array(L.length+S);return A.set(L),A.set(I,L.length),A},decode(L){if(!(L instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const I=L.slice(0,-S),A=_(I).slice(0,S),E=L.slice(-S);for(let $=0;$<S;$++)if(A[$]!==E[$])throw new Error("Invalid checksum");return I}}}n.utils={alphabet:r,chain:t,checksum:v,radix:f,radix2:p,join:s,padding:o},n.base16=t(p(4),r("0123456789ABCDEF"),s("")),n.base32=t(p(5),r("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),o(5),s("")),n.base32hex=t(p(5),r("0123456789ABCDEFGHIJKLMNOPQRSTUV"),o(5),s("")),n.base32crockford=t(p(5),r("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),s(""),a(S=>S.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),n.base64=t(p(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),o(6),s("")),n.base64url=t(p(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),o(6),s(""));const m=S=>t(f(58),r(S),s(""));n.base58=m("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),n.base58flickr=m("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),n.base58xrp=m("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const y=[0,2,3,5,6,7,9,10,11];n.base58xmr={encode(S){let _="";for(let L=0;L<S.length;L+=8){const I=S.subarray(L,L+8);_+=n.base58.encode(I).padStart(y[I.length],"1")}return _},decode(S){let _=[];for(let L=0;L<S.length;L+=11){const I=S.slice(L,L+11),A=y.indexOf(I.length),E=n.base58.decode(I);for(let $=0;$<E.length-A;$++)if(E[$]!==0)throw new Error("base58xmr: wrong padding");_=_.concat(Array.from(E.slice(E.length-A)))}return Uint8Array.from(_)}};const w=S=>t(v(4,_=>S(S(_))),n.base58);n.base58check=w;const x=t(r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),s("")),k=[996825010,642813549,513874426,1027748829,705979059];function C(S){const _=S>>25;let L=(S&33554431)<<5;for(let I=0;I<k.length;I++)(_>>I&1)===1&&(L^=k[I]);return L}function P(S,_,L=1){const I=S.length;let A=1;for(let E=0;E<I;E++){const $=S.charCodeAt(E);if($<33||$>126)throw new Error(`Invalid prefix (${S})`);A=C(A)^$>>5}A=C(A);for(let E=0;E<I;E++)A=C(A)^S.charCodeAt(E)&31;for(let E of _)A=C(A)^E;for(let E=0;E<6;E++)A=C(A);return A^=L,x.encode(h([A%2**30],30,5,!1))}function R(S){const _=S==="bech32"?1:734539939,L=p(5),I=L.decode,A=L.encode,E=b(I);function $(D,V,W=90){if(typeof D!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof D}`);if(!Array.isArray(V)||V.length&&typeof V[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof V}`);const Z=D.length+7+V.length;if(W!==!1&&Z>W)throw new TypeError(`Length ${Z} exceeds limit ${W}`);return D=D.toLowerCase(),`${D}1${x.encode(V)}${P(D,V,_)}`}function M(D,V=90){if(typeof D!="string")throw new Error(`bech32.decode input should be string, not ${typeof D}`);if(D.length<8||V!==!1&&D.length>V)throw new TypeError(`Wrong string length: ${D.length} (${D}). Expected (8..${V})`);const W=D.toLowerCase();if(D!==W&&D!==D.toUpperCase())throw new Error("String must be lowercase or uppercase");D=W;const Z=D.lastIndexOf("1");if(Z===0||Z===-1)throw new Error('Letter "1" must be present between prefix and data only');const G=D.slice(0,Z),K=D.slice(Z+1);if(K.length<6)throw new Error("Data must be at least 6 characters long");const ne=x.decode(K).slice(0,-6),ae=P(G,ne,_);if(!K.endsWith(ae))throw new Error(`Invalid checksum in ${D}: expected "${ae}"`);return{prefix:G,words:ne}}const U=b(M);function z(D){const{prefix:V,words:W}=M(D,!1);return{prefix:V,words:W,bytes:I(W)}}return{encode:$,decode:M,decodeToBytes:z,decodeUnsafe:U,fromWords:I,fromWordsUnsafe:E,toWords:A}}n.bech32=R("bech32"),n.bech32m=R("bech32m"),n.utf8={encode:S=>new TextDecoder().decode(S),decode:S=>new TextEncoder().encode(S)},n.hex=t(p(4),r("0123456789abcdef"),s(""),a(S=>{if(typeof S!="string"||S.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof S} with length ${S.length}`);return S.toLowerCase()}));const N={utf8:n.utf8,hex:n.hex,base16:n.base16,base32:n.base32,base64:n.base64,base64url:n.base64url,base58:n.base58,base58xmr:n.base58xmr},B=`Invalid encoding type. Available types: ${Object.keys(N).join(", ")}`,O=(S,_)=>{if(typeof S!="string"||!N.hasOwnProperty(S))throw new TypeError(B);if(!(_ instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return N[S].encode(_)};n.bytesToString=O,n.str=n.bytesToString;const H=(S,_)=>{if(!N.hasOwnProperty(S))throw new TypeError(B);if(typeof _!="string")throw new TypeError("stringToBytes() expects string");return N[S].decode(_)};n.stringToBytes=H,n.bytes=n.stringToBytes})(lib);const{bech32,hex,utf8}=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 n=0,e=Object.keys(TAGCODES);n<e.length;n++)e[n],TAGCODES[e[n]].toString();var NDKKind=(n=>(n[n.Metadata=0]="Metadata",n[n.Text=1]="Text",n[n.RecommendRelay=2]="RecommendRelay",n[n.Contacts=3]="Contacts",n[n.EncryptedDirectMessage=4]="EncryptedDirectMessage",n[n.EventDeletion=5]="EventDeletion",n[n.Repost=6]="Repost",n[n.Reaction=7]="Reaction",n[n.BadgeAward=8]="BadgeAward",n[n.GroupChat=9]="GroupChat",n[n.GroupNote=11]="GroupNote",n[n.GroupReply=12]="GroupReply",n[n.GiftWrapSeal=13]="GiftWrapSeal",n[n.PrivateDirectMessage=14]="PrivateDirectMessage",n[n.Image=20]="Image",n[n.Video=21]="Video",n[n.ShortVideo=22]="ShortVideo",n[n.Story=23]="Story",n[n.Vanish=62]="Vanish",n[n.CashuWalletBackup=375]="CashuWalletBackup",n[n.GiftWrap=1059]="GiftWrap",n[n.GenericRepost=16]="GenericRepost",n[n.ChannelCreation=40]="ChannelCreation",n[n.ChannelMetadata=41]="ChannelMetadata",n[n.ChannelMessage=42]="ChannelMessage",n[n.ChannelHideMessage=43]="ChannelHideMessage",n[n.ChannelMuteUser=44]="ChannelMuteUser",n[n.GenericReply=1111]="GenericReply",n[n.Media=1063]="Media",n[n.Report=1984]="Report",n[n.Label=1985]="Label",n[n.DVMReqTextExtraction=5e3]="DVMReqTextExtraction",n[n.DVMReqTextSummarization=5001]="DVMReqTextSummarization",n[n.DVMReqTextTranslation=5002]="DVMReqTextTranslation",n[n.DVMReqTextGeneration=5050]="DVMReqTextGeneration",n[n.DVMReqImageGeneration=5100]="DVMReqImageGeneration",n[n.DVMReqTextToSpeech=5250]="DVMReqTextToSpeech",n[n.DVMReqDiscoveryNostrContent=5300]="DVMReqDiscoveryNostrContent",n[n.DVMReqDiscoveryNostrPeople=5301]="DVMReqDiscoveryNostrPeople",n[n.DVMReqTimestamping=5900]="DVMReqTimestamping",n[n.DVMEventSchedule=5905]="DVMEventSchedule",n[n.DVMJobFeedback=7e3]="DVMJobFeedback",n[n.Subscribe=7001]="Subscribe",n[n.Unsubscribe=7002]="Unsubscribe",n[n.SubscriptionReceipt=7003]="SubscriptionReceipt",n[n.CashuReserve=7373]="CashuReserve",n[n.CashuQuote=7374]="CashuQuote",n[n.CashuToken=7375]="CashuToken",n[n.CashuWalletTx=7376]="CashuWalletTx",n[n.GroupAdminAddUser=9e3]="GroupAdminAddUser",n[n.GroupAdminRemoveUser=9001]="GroupAdminRemoveUser",n[n.GroupAdminEditMetadata=9002]="GroupAdminEditMetadata",n[n.GroupAdminEditStatus=9006]="GroupAdminEditStatus",n[n.GroupAdminCreateGroup=9007]="GroupAdminCreateGroup",n[n.GroupAdminRequestJoin=9021]="GroupAdminRequestJoin",n[n.MuteList=1e4]="MuteList",n[n.PinList=10001]="PinList",n[n.RelayList=10002]="RelayList",n[n.BookmarkList=10003]="BookmarkList",n[n.CommunityList=10004]="CommunityList",n[n.PublicChatList=10005]="PublicChatList",n[n.BlockRelayList=10006]="BlockRelayList",n[n.SearchRelayList=10007]="SearchRelayList",n[n.SimpleGroupList=10009]="SimpleGroupList",n[n.InterestList=10015]="InterestList",n[n.CashuMintList=10019]="CashuMintList",n[n.EmojiList=10030]="EmojiList",n[n.DirectMessageReceiveRelayList=10050]="DirectMessageReceiveRelayList",n[n.BlossomList=10063]="BlossomList",n[n.NostrWaletConnectInfo=13194]="NostrWaletConnectInfo",n[n.TierList=17e3]="TierList",n[n.CashuWallet=17375]="CashuWallet",n[n.FollowSet=3e4]="FollowSet",n[n.CategorizedPeopleList=3e4]="CategorizedPeopleList",n[n.CategorizedBookmarkList=30001]="CategorizedBookmarkList",n[n.RelaySet=30002]="RelaySet",n[n.CategorizedRelayList=30002]="CategorizedRelayList",n[n.BookmarkSet=30003]="BookmarkSet",n[n.CurationSet=30004]="CurationSet",n[n.ArticleCurationSet=30004]="ArticleCurationSet",n[n.VideoCurationSet=30005]="VideoCurationSet",n[n.ImageCurationSet=30006]="ImageCurationSet",n[n.InterestSet=30015]="InterestSet",n[n.InterestsList=30015]="InterestsList",n[n.EmojiSet=30030]="EmojiSet",n[n.ModularArticle=30040]="ModularArticle",n[n.ModularArticleItem=30041]="ModularArticleItem",n[n.Wiki=30818]="Wiki",n[n.Draft=31234]="Draft",n[n.SubscriptionTier=37001]="SubscriptionTier",n[n.EcashMintRecommendation=38e3]="EcashMintRecommendation",n[n.HighlightSet=39802]="HighlightSet",n[n.CategorizedHighlightList=39802]="CategorizedHighlightList",n[n.Nutzap=9321]="Nutzap",n[n.ZapRequest=9734]="ZapRequest",n[n.Zap=9735]="Zap",n[n.Highlight=9802]="Highlight",n[n.ClientAuth=22242]="ClientAuth",n[n.NostrWalletConnectReq=23194]="NostrWalletConnectReq",n[n.NostrWalletConnectRes=23195]="NostrWalletConnectRes",n[n.NostrConnect=24133]="NostrConnect",n[n.BlossomUpload=24242]="BlossomUpload",n[n.HttpAuth=27235]="HttpAuth",n[n.ProfileBadge=30008]="ProfileBadge",n[n.BadgeDefinition=30009]="BadgeDefinition",n[n.MarketStall=30017]="MarketStall",n[n.MarketProduct=30018]="MarketProduct",n[n.Article=30023]="Article",n[n.AppSpecificData=30078]="AppSpecificData",n[n.Classified=30402]="Classified",n[n.HorizontalVideo=34235]="HorizontalVideo",n[n.VerticalVideo=34236]="VerticalVideo",n[n.LegacyCashuWallet=37375]="LegacyCashuWallet",n[n.GroupMetadata=39e3]="GroupMetadata",n[n.GroupAdmins=39001]="GroupAdmins",n[n.GroupMembers=39002]="GroupMembers",n[n.AppRecommendation=31989]="AppRecommendation",n[n.AppHandler=31990]="AppHandler",n))(NDKKind||{});function getRelaysForSync(n,e,t="write"){if(!n.outboxTracker)return;const r=n.outboxTracker.data.get(e);if(r)return t==="write"?r.writeRelays:r.readRelays}async function getWriteRelaysFor(n,e,t="write"){if(n.outboxTracker)return n.outboxTracker.data.has(e)||await n.outboxTracker.trackUsers([e]),getRelaysForSync(n,e,t)}function getTopRelaysForAuthors(n,e){const t=new Map;return e.forEach(s=>{const o=getRelaysForSync(n,s);o&&o.forEach(a=>{const u=t.get(a)||0;t.set(a,u+1)})}),Array.from(t.entries()).sort((s,o)=>o[1]-s[1]).map(s=>s[0])}function getAllRelaysForAllPubkeys(n,e,t="read"){const r=new Map,s=new Set;return e.forEach(o=>{const a=getRelaysForSync(n,o,t);a&&a.size>0?(a.forEach(u=>{(r.get(u)||new Set).add(o)}),r.set(o,a)):s.add(o)}),{pubkeysToRelays:r,authorsMissingRelays:s}}function chooseRelayCombinationForPubkeys(n,e,t,{count:r,preferredRelays:s}={}){r??(r=2),s??(s=new Set);const o=n.pool,a=o.connectedRelays();a.forEach(p=>{s==null||s.add(p.url)});const u=new Map,{pubkeysToRelays:c,authorsMissingRelays:l}=getAllRelaysForAllPubkeys(n,e,t),h=getTopRelaysForAuthors(n,e),f=(p,b)=>{const v=u.get(b)||[];v.push(p),u.set(b,v)};for(const[p,b]of c.entries()){let v=r;for(const m of a)b.has(m.url)&&(f(p,m.url),v--);for(const m of b)u.has(m)&&(f(p,m),v--);if(!(v<=0))for(const m of h){if(v<=0)break;b.has(m)&&(f(p,m),v--)}}for(const p of l)o.permanentAndConnectedRelays().forEach(b=>{const v=u.get(b.url)||[];v.push(p),u.set(b.url,v)});return u}function getRelaysForFilterWithAuthors(n,e,t=2){return chooseRelayCombinationForPubkeys(n,e,"write",{count:t})}function tryNormalizeRelayUrl(n){try{return normalizeRelayUrl(n)}catch{return}}function normalizeRelayUrl(n){let e=normalizeUrl(n,{stripAuthentication:!1,stripWWW:!1,stripHash:!0});return e.endsWith("/")||(e+="/"),e}function normalize(n){const e=new Set;for(const t of n)try{e.add(normalizeRelayUrl(t))}catch{}return Array.from(e)}var DATA_URL_DEFAULT_MIME_TYPE="text/plain",DATA_URL_DEFAULT_CHARSET="us-ascii",testParameter=(n,e)=>e.some(t=>t instanceof RegExp?t.test(n):t===n),supportedProtocols=new Set(["https:","http:","file:"]),hasCustomProtocol=n=>{try{const{protocol:e}=new URL(n);return e.endsWith(":")&&!e.includes(".")&&!supportedProtocols.has(e)}catch{return!1}},normalizeDataURL=(n,{stripHash:e})=>{var f,p,b,v;const t=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(n);if(!t)throw new Error(`Invalid URL: ${n}`);const r=((f=t.groups)==null?void 0:f.type)??"",s=((p=t.groups)==null?void 0:p.data)??"";let o=((b=t.groups)==null?void 0:b.hash)??"";const a=r.split(";");o=e?"":o;let u=!1;a[a.length-1]==="base64"&&(a.pop(),u=!0);const c=((v=a.shift())==null?void 0:v.toLowerCase())??"",h=[...a.map(m=>{let[y,w=""]=m.split("=").map(x=>x.trim());return y==="charset"&&(w=w.toLowerCase(),w===DATA_URL_DEFAULT_CHARSET)?"":`${y}${w?`=${w}`:""}`}).filter(Boolean)];return u&&h.push("base64"),(h.length>0||c&&c!==DATA_URL_DEFAULT_MIME_TYPE)&&h.unshift(c),`data:${h.join(";")},${u?s.trim():s}${o?`#${o}`:""}`};function normalizeUrl(n,e={}){if(e={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,...e},typeof e.defaultProtocol=="string"&&!e.defaultProtocol.endsWith(":")&&(e.defaultProtocol=`${e.defaultProtocol}:`),n=n.trim(),/^data:/i.test(n))return normalizeDataURL(n,e);if(hasCustomProtocol(n))return n;const t=n.startsWith("//");!t&&/^\.*\//.test(n)||(n=n.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));const s=new URL(n);if(s.hostname=s.hostname.toLowerCase(),e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&s.protocol==="https:"&&(s.protocol="http:"),e.forceHttps&&s.protocol==="http:"&&(s.protocol="https:"),e.stripAuthentication&&(s.username="",s.password=""),e.stripHash?s.hash="":e.stripTextFragment&&(s.hash=s.hash.replace(/#?:~:text.*?$/i,"")),s.pathname){const a=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let u=0,c="";for(;;){const h=a.exec(s.pathname);if(!h)break;const f=h[0],p=h.index,b=s.pathname.slice(u,p);c+=b.replace(/\/{2,}/g,"/"),c+=f,u=p+f.length}const l=s.pathname.slice(u,s.pathname.length);c+=l.replace(/\/{2,}/g,"/"),s.pathname=c}if(s.pathname)try{s.pathname=decodeURI(s.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let a=s.pathname.split("/");const u=a[a.length-1];testParameter(u,e.removeDirectoryIndex)&&(a=a.slice(0,-1),s.pathname=`${a.slice(1).join("/")}/`)}if(s.hostname&&(s.hostname=s.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(s.hostname)&&(s.hostname=s.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(const a of[...s.searchParams.keys()])testParameter(a,e.removeQueryParameters)&&s.searchParams.delete(a);if(!Array.isArray(e.keepQueryParameters)&&e.removeQueryParameters===!0&&(s.search=""),Array.isArray(e.keepQueryParameters)&&e.keepQueryParameters.length>0)for(const a of[...s.searchParams.keys()])testParameter(a,e.keepQueryParameters)||s.searchParams.delete(a);if(e.sortQueryParameters){s.searchParams.sort();try{s.search=decodeURIComponent(s.search)}catch{}}e.removeTrailingSlash&&(s.pathname=s.pathname.replace(/\/$/,"")),e.removeExplicitPort&&s.port&&(s.port="");const o=n;return n=s.toString(),!e.removeSingleSlash&&s.pathname==="/"&&!o.endsWith("/")&&s.hash===""&&(n=n.replace(/\/$/,"")),(e.removeTrailingSlash||s.pathname==="/")&&s.hash===""&&e.removeSingleSlash&&(n=n.replace(/\/$/,"")),t&&!e.normalizeProtocol&&(n=n.replace(/^http:\/\//,"//")),e.stripProtocol&&(n=n.replace(/^(?:https?:)?\/\//,"")),n}var MAX_RECONNECT_ATTEMPTS=5,FLAPPING_THRESHOLD_MS=1e3,NDKRelayConnectivity=class{constructor(n,e){g(this,"ndkRelay");g(this,"ws");g(this,"_status");g(this,"timeoutMs");g(this,"connectedAt");g(this,"_connectionStats",{attempts:0,success:0,durations:[]});g(this,"debug");g(this,"netDebug");g(this,"connectTimeout");g(this,"reconnectTimeout");g(this,"ndk");g(this,"openSubs",new Map);g(this,"openCountRequests",new Map);g(this,"openEventPublishes",new Map);g(this,"serial",0);g(this,"baseEoseTimeout",4400);g(this,"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()}});this.ndkRelay=n,this._status=1;const t=Math.floor(Math.random()*1e3);this.debug=this.ndkRelay.debug.extend(`connectivity${t}`),this.ndk=e}async connect(n,e=!0){if(this._status!==2&&this._status!==1||this.reconnectTimeout){this.debug("Relay requested to be connected but was in state %s or it had a reconnect timeout",this._status);return}this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),n??(n=this.timeoutMs),!this.timeoutMs&&n&&(this.timeoutMs=n),this.timeoutMs&&(this.connectTimeout=setTimeout(()=>this.onConnectionError(e),this.timeoutMs));try{this.updateConnectionStats.attempt(),this._status===1?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(t){throw this.debug(`Failed to connect to ${this.ndkRelay.url}`,t),this._status=1,e?this.handleReconnection():this.ndkRelay.emit("delayed-connect",2*24*60*60*1e3),t}}disconnect(){var n;this._status=0;try{(n=this.ws)==null||n.close()}catch(e){this.debug("Failed to disconnect",e),this._status=1}}onConnectionError(n){this.debug(`Error connecting to ${this.ndkRelay.url}`,this.timeoutMs),n&&!this.reconnectTimeout&&this.handleReconnection()}onConnect(){var n;(n=this.netDebug)==null||n.call(this,"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.ndkRelay.emit("connect"),this.ndkRelay.emit("ready")}onDisconnect(){var n;(n=this.netDebug)==null||n.call(this,"disconnected",this.ndkRelay),this.updateConnectionStats.disconnected(),this._status===5&&this.handleReconnection(),this._status=1,this.ndkRelay.emit("disconnect")}onMessage(n){var e;(e=this.netDebug)==null||e.call(this,n.data,this.ndkRelay,"recv");try{const t=JSON.parse(n.data),[r,s,...o]=t;switch(r){case"EVENT":{const a=this.openSubs.get(s),u=t[2];if(!a){this.debug(`Received event for unknown subscription ${s}`);return}a.onevent(u);return}case"COUNT":{const a=t[2],u=this.openCountRequests.get(s);u&&(u.resolve(a.count),this.openCountRequests.delete(s));return}case"EOSE":{const a=this.openSubs.get(s);if(!a)return;a.oneose(s);return}case"OK":{const a=t[2],u=t[3],c=this.openEventPublishes.get(s),l=c==null?void 0:c.pop();if(!c||!l){this.debug("Received OK for unknown event publish",s);return}a?l.resolve(u):l.reject(new Error(u)),c.length===0?this.openEventPublishes.delete(s):this.openEventPublishes.set(s,c);return}case"CLOSED":{const a=this.openSubs.get(s);if(!a)return;a.onclosed(t[2]);return}case"NOTICE":this.onNotice(t[1]);return;case"AUTH":{this.onAuthRequested(t[1]);return}}}catch(t){this.debug(`Error parsing message from ${this.ndkRelay.url}: ${t.message}`,t==null?void 0:t.stack);return}}async onAuthRequested(n){var t,r,s;const e=this.ndkRelay.authPolicy??((t=this.ndk)==null?void 0:t.relayAuthDefaultPolicy);if(this.debug("Relay requested authentication",{havePolicy:!!e}),this._status===7){this.debug("Already authenticating, ignoring");return}if(this._status=6,e){if(this._status>=5){this._status=7;let o;try{o=await e(this.ndkRelay,n)}catch(a){this.debug("Authentication policy threw an error",a),o=!1}if(this.debug("Authentication policy returned",!!o),o instanceof NDKEvent||o===!0){o instanceof NDKEvent&&await this.auth(o);const a=async()=>{if(this._status>=5&&this._status<8){const u=new NDKEvent(this.ndk);u.kind=22242,u.tags=[["relay",this.ndkRelay.url],["challenge",n]],await u.sign(),this.auth(u).then(()=>{this._status=8,this.ndkRelay.emit("authed"),this.debug("Authentication successful")}).catch(c=>{this._status=6,this.ndkRelay.emit("auth:failed",c),this.debug("Authentication failed",c)})}else this.debug("Authentication failed, it changed status, status is %d",this._status)};o===!0&&((r=this.ndk)!=null&&r.signer?a().catch(u=>{console.error("Error authenticating",u)}):(this.debug("No signer available for authentication localhost"),(s=this.ndk)==null||s.once("signer:ready",a))),this._status=5,this.ndkRelay.emit("authed")}}}else this.ndkRelay.emit("auth",n)}onError(n){this.debug(`WebSocket error on ${this.ndkRelay.url}:`,n)}get status(){return this._status}isAvailable(){return this._status===5}isFlapping(){const n=this._connectionStats.durations;if(n.length%3!==0)return!1;const t=n.reduce((a,u)=>a+u,0)/n.length,r=n.map(a=>(a-t)**2).reduce((a,u)=>a+u,0)/n.length;return Math.sqrt(r)<FLAPPING_THRESHOLD_MS}async onNotice(n){this.ndkRelay.emit("notice",n)}handleReconnection(n=0){if(this.reconnectTimeout)return;if(this.isFlapping()){this.ndkRelay.emit("flapping",this._connectionStats),this._status=3;return}const e=this.connectedAt?Math.max(0,6e4-(Date.now()-this.connectedAt)):5e3*(this._connectionStats.attempts+1);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=void 0,this._status=2,this.connect().catch(t=>{n<MAX_RECONNECT_ATTEMPTS?setTimeout(()=>{this.handleReconnection(n+1)},1e3*(n+1)^4):this.debug("Reconnect failed")})},e),this.ndkRelay.emit("delayed-connect",e),this.debug("Reconnecting in",e),this._connectionStats.nextReconnectAt=Date.now()+e}async send(n){var e,t,r;this._status>=5&&((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN?((t=this.ws)==null||t.send(n),(r=this.netDebug)==null||r.call(this,n,this.ndkRelay,"send")):this.debug(`Not connected to ${this.ndkRelay.url} (%d), not sending message ${n}`,this._status)}async auth(n){const e=new Promise((t,r)=>{const s=this.openEventPublishes.get(n.id)??[];s.push({resolve:t,reject:r}),this.openEventPublishes.set(n.id,s)});return this.send(`["AUTH",${JSON.stringify(n.rawEvent())}]`),e}async publish(n){const e=new Promise((t,r)=>{const s=this.openEventPublishes.get(n.id)??[];s.length>0&&console.warn(`Duplicate event publishing detected, you are publishing event ${n.id} twice`),s.push({resolve:t,reject:r}),this.openEventPublishes.set(n.id,s)});return this.send(`["EVENT",${JSON.stringify(n)}]`),e}async count(n,e){this.serial++;const t=(e==null?void 0:e.id)||`count:${this.serial}`,r=new Promise((s,o)=>{this.openCountRequests.set(t,{resolve:s,reject:o})});return this.send(`["COUNT","${t}",${JSON.stringify(n).substring(1)}`),r}close(n,e){this.send(`["CLOSE","${n}"]`);const t=this.openSubs.get(n);this.openSubs.delete(n),t&&t.onclose(e)}req(n){`${this.send(`["REQ","${n.subId}",${JSON.stringify(n.executeFilters).substring(1)}`)}`,this.openSubs.set(n.subId,n)}get connectionStats(){return this._connectionStats}get url(){return this.ndkRelay.url}get connected(){var n;return this._status>=5&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN}},NDKRelayPublisher=class{constructor(n){g(this,"ndkRelay");g(this,"debug");this.ndkRelay=n,this.debug=n.debug.extend("publisher")}async publish(n,e=2500){let t;const r=()=>new Promise((h,f)=>{try{this.publishEvent(n).then(p=>{this.ndkRelay.emit("published",n),n.emit("relay:published",this.ndkRelay),h(!0)}).catch(f)}catch(p){f(p)}}),s=new Promise((h,f)=>{t=setTimeout(()=>{t=void 0,f(new Error(`Timeout: ${e}ms`))},e)}),o=()=>{r().then(h=>a(h)).catch(h=>u(h))};let a,u;const c=h=>{throw this.ndkRelay.debug("Publish failed",h,n.id),this.ndkRelay.emit("publish:failed",n,h),n.emit("relay:publish:failed",this.ndkRelay,h),h},l=()=>{t&&clearTimeout(t),this.ndkRelay.removeListener("connect",o)};return this.ndkRelay.status>=5?Promise.race([r(),s]).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((h,f)=>{a=h,u=f,this.ndkRelay.once("connect",o)}),s]).catch(c).finally(l))}async publishEvent(n){return this.ndkRelay.connectivity.publish(n.rawEvent())}};function filterFingerprint(n,e){const t=[];for(const s of n){const o=Object.entries(s||{}).map(([a,u])=>["since","until"].includes(a)?`${a}:${u}`:a).sort().join("-");t.push(o)}let r=e?"+":"";return r+=t.join("|"),r}function mergeFilters(n){const e=[],t={};return n.filter(r=>!!r.limit).forEach(r=>e.push(r)),n=n.filter(r=>!r.limit),n.length===0?e:(n.forEach(r=>{Object.entries(r).forEach(([s,o])=>{Array.isArray(o)?t[s]===void 0?t[s]=[...o]:t[s]=Array.from(new Set([...t[s],...o])):t[s]=o})}),[...e,t])}var NDKRelaySubscription=class{constructor(n,e,t){g(this,"fingerprint");g(this,"items",new Map);g(this,"topSubManager");g(this,"debug");g(this,"status",0);g(this,"onClose");g(this,"relay");g(this,"eosed",!1);g(this,"executionTimer");g(this,"fireTime");g(this,"delayType");g(this,"executeFilters");g(this,"id",Math.random().toString(36).substring(7));g(this,"_subId");g(this,"subIdParts",new Set);g(this,"executeOnRelayReady",()=>{if(this.status===2){if(this.items.size===0){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,items:this.items,itemsSize:this.items.size,id:this.id,subId:this.subId}),this.cleanup();return}this.debug("Executing on relay ready",{status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.status=1,this.execute()}});g(this,"reExecuteAfterAuth",(()=>{const n=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:n}),this._subId=void 0,this.status=1,this.execute(),this.debug("Re-executed after auth %s 👉 %s",n,this.subId)}).bind(this));this.relay=n,this.topSubManager=t,this.debug=n.debug.extend(`sub[${this.id}]`),this.fingerprint=e||Math.random().toString(36).substring(7)}get subId(){return this._subId?this._subId:(this._subId=this.fingerprint.slice(0,15),this._subId)}addSubIdPart(n){this.subIdParts.add(n)}addItem(n,e){if(this.debug("Adding item",{filters:e,internalId:n.internalId,status:this.status,fingerprint:this.fingerprint,id:this.subId,items:this.items,itemsSize:this.items.size}),!this.items.has(n.internalId))switch(n.on("close",this.removeItem.bind(this,n)),this.items.set(n.internalId,{subscription:n,filters:e}),this.status!==3&&n.subId&&(!this._subId||this._subId.length<48)&&(this.status===0||this.status===1)&&this.addSubIdPart(n.subId),this.status){case 0:this.evaluateExecutionPlan(n);break;case 3:break;case 1:this.evaluateExecutionPlan(n);break;case 4:throw this.debug("Subscription is closed, cannot add new items %o (%o)",n,e),new Error("Cannot add new items to a closed subscription")}}removeItem(n){if(this.items.delete(n.internalId),this.items.size===0){if(!this.eosed)return;this.close(),this.cleanup()}}close(){if(this.status===4)return;const n=this.status;if(this.status=4,n===3)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:n,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(n){if(!n.isGroupable()){this.status=1,this.execute();return}if(n.filters.find(r=>!!r.limit)&&(this.executeFilters=this.compileFilters(),this.executeFilters.length>=10)){this.status=1,this.execute();return}const e=n.groupableDelay,t=n.groupableDelayType;if(!e)throw new Error("Cannot group a subscription without a delay");if(this.status===0)this.schedule(e,t);else{const r=this.delayType,s=this.fireTime-Date.now();if(r==="at-least"&&t==="at-least")s<e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-least"&&t==="at-most")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-most"&&t==="at-most")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-most"&&t==="at-least")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else throw new Error(`Unknown delay type combination ${r} ${t}`)}}schedule(n,e){this.status=1;const t=Date.now();this.fireTime=t+n,this.delayType=e;const r=setTimeout(this.execute.bind(this),n);e==="at-least"&&(this.executionTimer=r)}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)}`}execute(){if(this.status===1){if(!this.relay.connected){this.status=2,this.debug("Waiting for relay to be ready",{status:this.status,id:this.subId,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.relay.once("ready",this.executeOnRelayReady);return}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(n){this.topSubManager.dispatchEvent(n,this.relay)}oneose(n){if(this.eosed=!0,n!==this.subId){this.debug("Received EOSE for an abandoned subscription",n,this.subId),this.relay.close(n);return}this.items.size===0&&this.close();for(const{subscription:e}of this.items.values())e.eoseReceived(this.relay),e.closeOnEose&&(this.debug("Removing item because of EOSE",{filters:e.filters,internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.removeItem(e))}onclose(n){this.status=4}onclosed(n){if(n)for(const{subscription:e}of this.items.values())e.closedReceived(this.relay,n)}compileFilters(){const n=[],e=Array.from(this.items.values()).map(r=>r.filters);if(!e[0])return this.debug("👀 No filters to merge",this.items),console.error("BUG: No filters to merge!",this.items),[];const t=e[0].length;for(let r=0;r<t;r++){const s=e.map(o=>o[r]);n.push(...mergeFilters(s))}return n}},NDKRelaySubscriptionManager=class{constructor(n,e){g(this,"relay");g(this,"subscriptions");g(this,"generalSubManager");this.relay=n,this.subscriptions=new Map,this.generalSubManager=e}addSubscription(n,e){let t;if(!n.isGroupable())t=this.createSubscription(n,e);else{const r=filterFingerprint(e,n.closeOnEose);r&&(t=(this.subscriptions.get(r)||[]).find(o=>o.status<3)),t??(t=this.createSubscription(n,e,r))}t.addItem(n,e)}createSubscription(n,e,t){const r=new NDKRelaySubscription(this.relay,t||null,this.generalSubManager);r.onClose=this.onRelaySubscriptionClose.bind(this);const s=this.subscriptions.get(r.fingerprint)??[];return this.subscriptions.set(r.fingerprint,[...s,r]),r}onRelaySubscriptionClose(n){let e=this.subscriptions.get(n.fingerprint)??[];e?e.length===1?this.subscriptions.delete(n.fingerprint):(e=e.filter(t=>t.id!==n.id),this.subscriptions.set(n.fingerprint,e)):console.warn("Unexpectedly did not find a subscription with fingerprint",n.fingerprint)}},NDKRelay=(oe=class extends lib$1.EventEmitter{constructor(t,r,s){super();g(this,"url");g(this,"scores");g(this,"connectivity");g(this,"subs");g(this,"publisher");g(this,"authPolicy");g(this,"lowestValidationRatio");g(this,"targetValidationRatio");g(this,"validationRatioFn");g(this,"validatedEventCount",0);g(this,"nonValidatedEventCount",0);g(this,"trusted",!1);g(this,"complaining",!1);g(this,"debug");g(this,"req");g(this,"close");this.url=normalizeRelayUrl(t),this.scores=new Map,this.debug=createDebug5(`ndk:relay:${t}`),this.connectivity=new NDKRelayConnectivity(this,s),this.connectivity.netDebug=s==null?void 0: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=r,this.targetValidationRatio=s==null?void 0:s.initialValidationRatio,this.lowestValidationRatio=s==null?void 0:s.lowestValidationRatio,this.validationRatioFn=((s==null?void 0:s.validationRatioFn)??oe.defaultValidationRatioUpdateFn).bind(this),this.updateValidationRatio(),s||console.trace("relay created without ndk")}updateValidationRatio(){setTimeout(()=>{this.updateValidationRatio()},3e4)}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(t,r=!0){return this.connectivity.connect(t,r)}disconnect(){this.status!==1&&this.connectivity.disconnect()}subscribe(t,r){this.subs.addSubscription(t,r)}async publish(t,r=2500){return this.publisher.publish(t,r)}referenceTags(){return[["r",this.url]]}addValidatedEvent(){this.validatedEventCount++}addNonValidatedEvent(){this.nonValidatedEventCount++}get validationRatio(){return this.nonValidatedEventCount===0?1:this.validatedEventCount/(this.validatedEventCount+this.nonValidatedEventCount)}shouldValidateEvent(){return this.trusted?!1:this.targetValidationRatio===void 0?!0:this.validationRatio<this.targetValidationRatio}get connected(){return this.connectivity.connected}},g(oe,"defaultValidationRatioUpdateFn",(t,r,s)=>{if(t.lowestValidationRatio===void 0||t.targetValidationRatio===void 0)return 1;let o=t.validationRatio;if(t.validationRatio>t.targetValidationRatio){const a=r/100;o=Math.max(t.lowestValidationRatio,t.validationRatio-a)}return o<t.validationRatio?o:t.validationRatio}),oe),NDKPublishError=class extends Error{constructor(e,t,r,s){super(e);g(this,"errors");g(this,"publishedToRelays");g(this,"intendedRelaySet");this.errors=t,this.publishedToRelays=r,this.intendedRelaySet=s}get relayErrors(){const e=[];for(const[t,r]of this.errors)e.push(`${t.url}: ${r}`);return e.join(`
76
- `)}},NDKRelaySet=class Tt{constructor(e,t,r){g(this,"relays");g(this,"debug");g(this,"ndk");g(this,"pool");this.relays=e,this.ndk=t,this.pool=r??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(e,t,r=!0,s){if(s=s??t.pool,!s)throw new Error("No pool provided");const o=new Set;for(const a of e){const u=s.relays.get(normalizeRelayUrl(a));if(u)u.status<5&&r&&u.connect(),o.add(u);else{const c=new NDKRelay(normalizeRelayUrl(a),t==null?void 0:t.relayAuthDefaultPolicy,t);s.useTemporaryRelay(c,void 0,`requested from fromRelayUrls ${e}`),o.add(c)}}return new Tt(new Set(o),t,s)}async publish(e,t,r=1){var c;const s=new Set,o=new Map,a=e.isEphemeral();e.publishStatus="pending";const u=l=>{s.add(l)};e.on("relay:published",u);try{const l=Array.from(this.relays).map(h=>new Promise(f=>{const p=t?setTimeout(()=>{s.has(h)||(o.set(h,new Error(`Publish timeout after ${t}ms`)),f(!1))},t):null;h.publish(e,t).then(b=>{p&&clearTimeout(p),b?(s.add(h),f(!0)):f(!1)}).catch(b=>{p&&clearTimeout(p),a||o.set(h,b),f(!1)})}));if(await Promise.all(l),s.size<r){if(!a){const h=new NDKPublishError("Not enough relays received the event",o,s,this);throw e.publishStatus="error",e.publishError=h,(c=this.ndk)==null||c.emit("event:publish-failed",e,h,this.relayUrls),h}}else e.publishStatus="success",e.emit("published",{relaySet:this,publishedToRelays:s});return s}finally{e.off("relay:published",u)}}get size(){return this.relays.size}},d=createDebug5("ndk:outbox:calculate");async function calculateRelaySetFromEvent(n,e){var a;const t=new Set,r=await getWriteRelaysFor(n,e.pubkey);r&&r.forEach(u=>{var l;const c=(l=n.pool)==null?void 0:l.getRelay(u);c&&t.add(c)});let s=e.tags.filter(u=>["a","e"].includes(u[0])).map(u=>u[2]).filter(u=>u==null?void 0:u.startsWith("wss://")).filter(u=>{try{return new URL(u),!0}catch{return!1}}).map(u=>normalizeRelayUrl(u));s=Array.from(new Set(s)).slice(0,5),s.forEach(u=>{var l;const c=(l=n.pool)==null?void 0:l.getRelay(u,!0,!0);c&&(d("Adding relay hint %s",u),t.add(c))});const o=e.getMatchingTags("p").map(u=>u[1]);return o.length<5?Array.from(chooseRelayCombinationForPubkeys(n,o,"read",{preferredRelays:new Set(r)}).keys()).forEach(c=>{var h;const l=(h=n.pool)==null?void 0:h.getRelay(c,!1,!0);l&&(d("Adding p-tagged relay %s",c),t.add(l))}):d("Too many p-tags to consider %d",o.length),(a=n.pool)==null||a.permanentAndConnectedRelays().forEach(u=>t.add(u)),new NDKRelaySet(t,n)}function calculateRelaySetsFromFilter(n,e,t){const r=new Map,s=new Set;if(e.forEach(o=>{o.authors&&o.authors.forEach(a=>s.add(a))}),s.size>0){const o=getRelaysForFilterWithAuthors(n,Array.from(s));for(const a of o.keys())r.set(a,[]);for(const a of e)if(a.authors)for(const[u,c]of o.entries()){const l=a.authors.filter(h=>c.includes(h));r.set(u,[...r.get(u),{...a,authors:l}])}else for(const u of o.keys())r.set(u,[...r.get(u),a])}else n.explicitRelayUrls&&n.explicitRelayUrls.forEach(o=>{r.set(o,e)});return r.size===0&&t.permanentAndConnectedRelays().slice(0,5).forEach(o=>{r.set(o.url,e)}),r}function calculateRelaySetsFromFilters(n,e,t){return calculateRelaySetsFromFilter(n,e,t)}function mergeTags(n,e){const t=new Map,r=a=>a.join(","),s=(a,u)=>a.every((c,l)=>c===u[l]),o=a=>{for(const[u,c]of t)if(s(c,a)||s(a,c)){a.length>=c.length&&t.set(u,a);return}t.set(r(a),a)};return n.concat(e).forEach(o),Array.from(t.values())}var hashtagRegex=new RegExp(`(?<=\\s|^)(#[^\\s!@#$%^&*()=+./,[{\\]};:'"?><]+)`,"g");function generateHashtags(n){const e=n.match(hashtagRegex),t=new Set,r=new Set;if(e)for(const s of e)t.has(s.slice(1))||(r.add(s.slice(1)),t.add(s.slice(1)));return Array.from(r)}async function generateContentTags(n,e=[]){const t=/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,r=[],s=a=>{e.find(u=>["q",a[0]].includes(u[0])&&u[1]===a[1])||e.push(a)};n=n.replace(t,a=>{try{const u=a.split(/(@|nostr:)/)[2],{type:c,data:l}=nip19_exports.decode(u);let h;switch(c){case"npub":h=["p",l];break;case"nprofile":h=["p",l.pubkey];break;case"note":r.push(new Promise(async f=>{s(["q",l,await maybeGetEventRelayUrl(u)]),f()}));break;case"nevent":r.push(new Promise(async f=>{const{id:p,author:b}=l;let{relays:v}=l;(!v||v.length===0)&&(v=[await maybeGetEventRelayUrl(u)]),s(["q",p,v[0]]),b&&s(["p",b]),f()}));break;case"naddr":r.push(new Promise(async f=>{const p=[l.kind,l.pubkey,l.identifier].join(":");let b=l.relays??[];b.length===0&&(b=[await maybeGetEventRelayUrl(u)]),s(["q",p,b[0]]),s(["p",l.pubkey]),f()}));break;default:return a}return h&&s(h),`nostr:${u}`}catch{return a}}),await Promise.all(r);const o=generateHashtags(n).map(a=>["t",a]);return e=mergeTags(e,o),{content:n,tags:e}}async function maybeGetEventRelayUrl(n){return""}async function encrypt(n,e,t="nip44"){let r;if(!this.ndk)throw new Error("No NDK instance found!");let s=e;if(s||(this.ndk.assertSigner(),s=this.ndk.signer),!s)throw new Error("no NDK signer");const o=n||(()=>{const a=this.getMatchingTags("p");if(a.length!==1)throw new Error("No recipient could be determined and no explicit recipient was provided");return this.ndk.getUser({pubkey:a[0][1]})})();if(t==="nip44"&&await isEncryptionEnabled(s,"nip44")&&(r=await s.encrypt(o,this.content,"nip44")),(!r||t==="nip04")&&await isEncryptionEnabled(s,"nip04")&&(r=await s.encrypt(o,this.content,"nip04")),!r)throw new Error("Failed to encrypt event.");this.content=r}async function decrypt(n,e,t){var u,c,l,h;if((c=(u=this.ndk)==null?void 0:u.cacheAdapter)!=null&&c.getDecryptedEvent){let f=null;if(typeof this.ndk.cacheAdapter.getDecryptedEvent=="function"&&(f=this.ndk.cacheAdapter.getDecryptedEvent(this.id)),f){this.content=f.content;return}}let r;if(!this.ndk)throw new Error("No NDK instance found!");let s=e;if(s||(this.ndk.assertSigner(),s=this.ndk.signer),!s)throw new Error("no NDK signer");const o=n||this.author;if(!o)throw new Error("No sender provided and no author available");const a=t||(this.content.match(/\\?iv=/)?"nip04":"nip44");if((a==="nip04"||this.kind===4)&&await isEncryptionEnabled(s,"nip04")&&this.content.search("\\?iv=")&&(r=await s.decrypt(o,this.content,"nip04")),!r&&a==="nip44"&&await isEncryptionEnabled(s,"nip44")&&(r=await s.decrypt(o,this.content,"nip44")),!r)throw new Error("Failed to decrypt event.");this.content=r,(h=(l=this.ndk)==null?void 0:l.cacheAdapter)!=null&&h.addDecryptedEvent&&this.ndk.cacheAdapter.addDecryptedEvent(this)}async function isEncryptionEnabled(n,e){return n.encryptionEnabled?e?!!await n.encryptionEnabled(e):!0:!1}function eventHasETagMarkers(n){for(const e of n.tags)if(e[0]==="e"&&(e[3]??"").length>0)return!0;return!1}function getRootTag(n,e){e??(e=n.tagType());const t=n.tags.find(isTagRootTag);if(!t){if(eventHasETagMarkers(n))return;const r=n.getMatchingTags(e);if(r.length<3)return r[0]}return t}var nip22RootTags=new Set(["A","E","I"]),nip22ReplyTags=new Set(["a","e","i"]);function getReplyTag(n,e){if(n.kind===1111){let s;for(const o of n.tags)if(nip22RootTags.has(o[0]))s=o;else if(nip22ReplyTags.has(o[0])){s=o;break}return s}e??(e=n.tagType());let t=!1,r;for(const s of n.tags)if(s[0]===e){if((s[3]??"").length>0&&(t=!0),t&&s[3]==="reply")return s;t&&s[3]==="root"&&(r=s),t||(r=s)}return r}function isTagRootTag(n){return n[0]==="E"||n[3]==="root"}async function fetchTaggedEvent(n,e){if(!this.ndk)throw new Error("NDK instance not found");const t=this.getMatchingTags(n,e);if(t.length===0)return;const[r,s,o]=t[0];let a=o!==""?this.ndk.pool.getRelay(o):void 0;return await this.ndk.fetchEvent(s,{},a)}async function fetchRootEvent(n){if(!this.ndk)throw new Error("NDK instance not found");const e=getRootTag(this);if(e)return this.ndk.fetchEventFromTag(e,this,n)}async function fetchReplyEvent(n){if(!this.ndk)throw new Error("NDK instance not found");const e=getReplyTag(this);if(e)return this.ndk.fetchEventFromTag(e,this,n)}function isReplaceable(){if(this.kind===void 0)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(this.kind===void 0)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function isParamReplaceable(){if(this.kind===void 0)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}var DEFAULT_RELAY_COUNT=2;function encode(n=DEFAULT_RELAY_COUNT){let e=[];return this.onRelays.length>0?e=this.onRelays.map(t=>t.url):this.relay&&(e=[this.relay.url]),e.length>n&&(e=e.slice(0,n)),this.isParamReplaceable()?nip19_exports.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:e}):e.length>0?nip19_exports.neventEncode({id:this.tagId(),relays:e,author:this.pubkey}):nip19_exports.noteEncode(this.tagId())}async function repost(n=!0,e){if(!e&&n){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),e=this.ndk.signer}const t=new NDKEvent(this.ndk,{kind:getKind(this)});return this.isProtected||(t.content=JSON.stringify(this.rawEvent())),t.tag(this),this.kind!==1&&t.tags.push(["k",`${this.kind}`]),e&&await t.sign(e),n&&await t.publish(),t}function getKind(n){return n.kind===1?6:16}function serialize(n=!1,e=!1){const t=[0,this.pubkey,this.created_at,this.kind,this.tags,this.content];return n&&t.push(this.sig),e&&t.push(this.id),JSON.stringify(t)}function deserialize(n){const e=JSON.parse(n),t={pubkey:e[1],created_at:e[2],kind:e[3],tags:e[4],content:e[5]};return e.length>=7&&(t.sig=e[6]),e.length>=8&&(t.id=e[7]),t}var worker,processingQueue={};function signatureVerificationInit(n){worker=n,worker.onmessage=e=>{const[t,r]=e.data,s=processingQueue[t];if(!s){console.error("No record found for event",t);return}delete processingQueue[t];for(const o of s.resolves)o(r)}}async function verifySignatureAsync(n,e){return new Promise(r=>{const s=n.serialize();let o=!1;processingQueue[n.id]||(processingQueue[n.id]={event:n,resolves:[]},o=!0),processingQueue[n.id].resolves.push(r),o&&(worker==null||worker.postMessage({serialized:s,id:n.id,sig:n.sig,pubkey:n.pubkey}))})}var PUBKEY_REGEX=/^[a-f0-9]{64}$/;function validate(){if(typeof this.kind!="number"||typeof this.content!="string"||typeof this.created_at!="number"||typeof this.pubkey!="string"||!this.pubkey.match(PUBKEY_REGEX)||!Array.isArray(this.tags))return!1;for(let n=0;n<this.tags.length;n++){const e=this.tags[n];if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(typeof e[t]=="object")return!1}return!0}var verifiedSignatures=new dist.LRUCache({maxSize:1e3,entryExpirationTimeInMS:6e4});function verifySignature(n){var t;if(typeof this.signatureVerified=="boolean")return this.signatureVerified;const e=verifiedSignatures.get(this.id);if(e!==null)return this.signatureVerified=!!e,this.signatureVerified;try{if((t=this.ndk)!=null&&t.asyncSigVerification)verifySignatureAsync(this,n).then(r=>{var s;n&&(this.signatureVerified=r,r&&verifiedSignatures.set(this.id,this.sig)),r||((s=this.ndk)==null||s.emit("event:invalid-sig",this),verifiedSignatures.set(this.id,!1))});else{const r=sha256(new TextEncoder().encode(this.serialize())),s=schnorr.verify(this.sig,r,this.pubkey);return s?verifiedSignatures.set(this.id,this.sig):verifiedSignatures.set(this.id,!1),this.signatureVerified=s,s}}catch{return this.signatureVerified=!1,!1}}function getEventHash$1(){return getEventHashFromSerializedEvent(this.serialize())}function getEventHashFromSerializedEvent(n){const e=sha256(new TextEncoder().encode(n));return bytesToHex$1(e)}var skipClientTagOnKinds=new Set([0,4,1059,13,3,9734,5]),NDKEvent=class Pe extends lib$1.EventEmitter{constructor(t,r){var s;super();g(this,"ndk");g(this,"created_at");g(this,"content","");g(this,"tags",[]);g(this,"kind");g(this,"id","");g(this,"sig");g(this,"pubkey","");g(this,"signatureVerified");g(this,"_author");g(this,"relay");g(this,"publishStatus","success");g(this,"publishError");g(this,"serialize",serialize.bind(this));g(this,"getEventHash",getEventHash$1.bind(this));g(this,"validate",validate.bind(this));g(this,"verifySignature",verifySignature.bind(this));g(this,"isReplaceable",isReplaceable.bind(this));g(this,"isEphemeral",isEphemeral.bind(this));g(this,"isDvm",()=>this.kind&&this.kind>=5e3&&this.kind<=7e3);g(this,"isParamReplaceable",isParamReplaceable.bind(this));g(this,"encode",encode.bind(this));g(this,"encrypt",encrypt.bind(this));g(this,"decrypt",decrypt.bind(this));g(this,"fetchTaggedEvent",fetchTaggedEvent.bind(this));g(this,"fetchRootEvent",fetchRootEvent.bind(this));g(this,"fetchReplyEvent",fetchReplyEvent.bind(this));g(this,"repost",repost.bind(this));this.ndk=t,this.created_at=r==null?void 0:r.created_at,this.content=(r==null?void 0:r.content)||"",this.tags=(r==null?void 0:r.tags)||[],this.id=(r==null?void 0:r.id)||"",this.sig=r==null?void 0:r.sig,this.pubkey=(r==null?void 0:r.pubkey)||"",this.kind=r==null?void 0:r.kind,r instanceof Pe&&(this.relay&&(this.relay=r.relay,(s=this.ndk)==null||s.subManager.seenEvent(r.id,this.relay)),this.publishStatus=r.publishStatus,this.publishError=r.publishError)}get onRelays(){let t=[];return this.ndk?t=this.ndk.subManager.seenEvents.get(this.id)||[]:this.relay&&t.push(this.relay),t}static deserialize(t,r){return new Pe(t,deserialize(r))}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(t){var r;this.pubkey=t.pubkey,this._author=t,(r=this._author).ndk??(r.ndk=this.ndk)}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const t=this.ndk.getUser({pubkey:this.pubkey});return this._author=t,t}tagExternal(t,r,s){const o=["i"],a=["k"];switch(r){case"url":{const u=new URL(t);u.hash="",o.push(u.toString()),a.push(`${u.protocol}//${u.host}`);break}case"hashtag":o.push(`#${t.toLowerCase()}`),a.push("#");break;case"geohash":o.push(`geo:${t.toLowerCase()}`),a.push("geo");break;case"isbn":o.push(`isbn:${t.replace(/-/g,"")}`),a.push("isbn");break;case"podcast:guid":o.push(`podcast:guid:${t}`),a.push("podcast:guid");break;case"podcast:item:guid":o.push(`podcast:item:guid:${t}`),a.push("podcast:item:guid");break;case"podcast:publisher:guid":o.push(`podcast:publisher:guid:${t}`),a.push("podcast:publisher:guid");break;case"isan":o.push(`isan:${t.split("-").slice(0,4).join("-")}`),a.push("isan");break;case"doi":o.push(`doi:${t.toLowerCase()}`),a.push("doi");break;default:throw new Error(`Unsupported NIP-73 entity type: ${r}`)}s&&o.push(s),this.tags.push(o),this.tags.push(a)}tag(t,r,s,o){let a=[];if(t.fetchProfile!==void 0){o??(o="p");const c=[o,t.pubkey];r&&c.push("",r),a.push(c)}else if(t instanceof Pe){const c=t;s??(s=(c==null?void 0:c.pubkey)===this.pubkey),a=c.referenceTags(r,s,o);for(const l of c.getMatchingTags("p"))l[1]!==this.pubkey&&(this.tags.find(h=>h[0]==="p"&&h[1]===l[1])||this.tags.push(["p",l[1]]))}else if(Array.isArray(t))a=[t];else throw new Error("Invalid argument",t);this.tags=mergeTags(this.tags,a)}async toNostrEvent(t){var o,a;if(!t&&this.pubkey===""){const u=await((a=(o=this.ndk)==null?void 0:o.signer)==null?void 0:a.user());this.pubkey=(u==null?void 0:u.pubkey)||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const{content:r,tags:s}=await this.generateTags();this.content=r||"",this.tags=s;try{this.id=this.getEventHash()}catch{}return this.rawEvent()}getMatchingTags(t,r){const s=this.tags.filter(o=>o[0]===t);return r===void 0?s:s.filter(o=>o[3]===r)}hasTag(t,r){return this.tags.some(s=>s[0]===t&&(!r||s[3]===r))}tagValue(t){const r=this.getMatchingTags(t);if(r.length!==0)return r[0][1]}get alt(){return this.tagValue("alt")}set alt(t){this.removeTag("alt"),t&&this.tags.push(["alt",t])}get dTag(){return this.tagValue("d")}set dTag(t){this.removeTag("d"),t&&this.tags.push(["d",t])}removeTag(t){const r=Array.isArray(t)?t:[t];this.tags=this.tags.filter(s=>!r.includes(s[0]))}replaceTag(t){this.removeTag(t[0]),this.tags.push(t)}async sign(t){var s,o;t?this.author=await t.user():((s=this.ndk)==null||s.assertSigner(),t=(o=this.ndk)==null?void 0:o.signer);const r=await this.toNostrEvent();return this.sig=await t.sign(r),this.sig}async publishReplaceable(t,r,s){return this.id="",this.created_at=Math.floor(Date.now()/1e3),this.sig="",this.publish(t,r,s)}async publish(t,r,s){var u,c,l;if(this.sig||await this.sign(),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");if((!t||t.size===0)&&(t=this.ndk.devWriteRelaySet||await calculateRelaySetFromEvent(this.ndk,this)),this.kind===5&&((u=this.ndk.cacheAdapter)!=null&&u.deleteEventIds)){const h=this.getMatchingTags("e").map(f=>f[1]);this.ndk.cacheAdapter.deleteEventIds(h)}const o=this.rawEvent();if((c=this.ndk.cacheAdapter)!=null&&c.addUnpublishedEvent&&shouldTrackUnpublishedEvent(this))try{this.ndk.cacheAdapter.addUnpublishedEvent(this,t.relayUrls)}catch(h){console.error("Error adding unpublished event to cache",h)}this.kind===5&&((l=this.ndk.cacheAdapter)!=null&&l.deleteEventIds)&&this.ndk.cacheAdapter.deleteEventIds(this.getMatchingTags("e").map(h=>h[1])),this.ndk.subManager.dispatchEvent(o,void 0,!0);const a=await t.publish(this,r,s);return a.forEach(h=>{var f;return(f=this.ndk)==null?void 0:f.subManager.seenEvent(this.id,h)}),a}async generateTags(){var o,a,u;let t=[];const r=await generateContentTags(this.content,this.tags),s=r.content;if(t=r.tags,this.kind&&this.isParamReplaceable()&&!this.getMatchingTags("d")[0]){const l=this.tagValue("title");let f=[...Array(l?6:16)].map(()=>Math.random().toString(36)[2]).join("");l&&l.length>0&&(f=`${l.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")}-${f}`),t.push(["d",f])}if(this.shouldAddClientTag){const c=["client",((o=this.ndk)==null?void 0:o.clientName)??""];(a=this.ndk)!=null&&a.clientNip89&&c.push((u=this.ndk)==null?void 0:u.clientNip89),t.push(c)}else this.shouldStripClientTag&&(t=t.filter(c=>c[0]!=="client"));return{content:s||"",tags:t}}get shouldAddClientTag(){var t,r;return!(!((t=this.ndk)!=null&&t.clientName)&&!((r=this.ndk)!=null&&r.clientNip89)||skipClientTagOnKinds.has(this.kind)||this.isEphemeral()||this.isReplaceable()&&!this.isParamReplaceable()||this.isDvm()||this.hasTag("client"))}get shouldStripClientTag(){return skipClientTagOnKinds.has(this.kind)}muted(){var o,a;const t=(o=this.ndk)==null?void 0:o.mutedIds.get(this.pubkey);if(t&&t==="p")return"author";const r=this.tagReference(),s=(a=this.ndk)==null?void 0:a.mutedIds.get(r[1]);return s&&s===r[0]?"event":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const t=this.getMatchingTags("d")[0];return t?t[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return this.kind===0||this.kind===3||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 t=this.dTag??"";return`${this.kind}:${this.pubkey}:${t}`}if(this.isReplaceable())return`${this.kind}:${this.pubkey}:`;throw new Error("Event is not a replaceable event")}tagType(){return this.isParamReplaceable()?"a":"e"}tagReference(t){let r;return this.isParamReplaceable()?r=["a",this.tagAddress()]:r=["e",this.tagId()],this.relay?r.push(this.relay.url):r.push(""),r.push(t??""),this.isParamReplaceable()||r.push(this.pubkey),r}referenceTags(t,r,s){let o=[];return this.isParamReplaceable()?o=[[s??"a",this.tagAddress()],[s??"e",this.id]]:o=[[s??"e",this.id]],o=o.map(a=>{var u,c,l;return a[0]==="e"||t?a.push(((u=this.relay)==null?void 0:u.url)??""):(c=this.relay)!=null&&c.url&&a.push((l=this.relay)==null?void 0:l.url),a}),o.forEach(a=>{a[0]==="e"?(a.push(t??""),a.push(this.pubkey)):t&&a.push(t)}),o=[...o,...this.getMatchingTags("h")],r||o.push(...this.author.referenceTags()),o}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}nip22Filter(){return this.isParamReplaceable()?{"#A":[this.tagId()]}:{"#E":[this.tagId()]}}async delete(t,r=!0){var o;if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new Pe(this.ndk,{kind:5,content:t||""});return s.tag(this,void 0,!0),s.tags.push(["k",(o=this.kind)==null?void 0:o.toString()]),r&&(this.emit("deleted"),await s.publish()),s}set isProtected(t){this.removeTag("-"),t&&this.tags.push(["-"])}get isProtected(){return this.hasTag("-")}async react(t,r=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new Pe(this.ndk,{kind:7,content:t});return s.tag(this),r&&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(t=>t.url).join(", "))}reply(){var r,s;const t=new Pe(this.ndk);if(this.kind===1)t.kind=1,this.hasTag("e")?t.tags=[...t.tags,...this.getMatchingTags("e"),...this.getMatchingTags("p"),...this.getMatchingTags("a"),...this.referenceTags("reply")]:t.tag(this,"root");else{t.kind=1111;const o=["A","E","I","P"],a=this.tags.filter(u=>o.includes(u[0]));if(a.length>0){const u=this.tagValue("K");t.tags.push(...a),u&&t.tags.push(["K",u]);const[c,l,h,...f]=this.tagReference(),p=[c,l,...f];t.tags.push(p)}else{const[u,c,l,h]=this.tagReference(),f=[u,c,h??""];u==="e"&&f.push(this.pubkey),t.tags.push(f);const p=[...f];p[0]=p[0].toUpperCase(),t.tags.push(p),t.tags.push(["K",(r=this.kind)==null?void 0:r.toString()]),t.tags.push(["P",this.pubkey])}t.tags.push(["k",(s=this.kind)==null?void 0:s.toString()]),t.tags.push(...this.getMatchingTags("p")),t.tags.push(["p",this.pubkey])}return t}},untrackedUnpublishedEvents=new Set([24133,13194,23194,23195]);function shouldTrackUnpublishedEvent(n){return!untrackedUnpublishedEvents.has(n.kind)}var NDKPool=class extends lib$1.EventEmitter{constructor(e,t,r,{debug:s,name:o}={}){super();g(this,"_relays",new Map);g(this,"status","idle");g(this,"autoConnectRelays",new Set);g(this,"poolBlacklistRelayUrls",new Set);g(this,"debug");g(this,"temporaryRelayTimers",new Map);g(this,"flappingRelays",new Set);g(this,"backoffTimes",new Map);g(this,"ndk");g(this,"_name","unnamed");this.debug=s??r.debug.extend("pool"),o&&(this._name=o),this.ndk=r,this.relayUrls=e,this.poolBlacklistRelayUrls=new Set(t),this.ndk.pools.push(this)}get blacklistRelayUrls(){const e=new Set(this.ndk.blacklistRelayUrls);return this.poolBlacklistRelayUrls.forEach(t=>e.add(t)),e}get relays(){return this._relays}set relayUrls(e){this._relays.clear();for(const t of e){const r=new NDKRelay(t,void 0,this.ndk);r.connectivity.netDebug=this.ndk.netDebug,this.addRelay(r)}}get name(){return this._name}set name(e){this._name=e,this.debug=this.debug.extend(e)}useTemporaryRelay(e,t=3e4,r){const s=this.relays.has(e.url);s||(this.addRelay(e),this.debug("Adding temporary relay %s for filters %o",e.url,r));const o=this.temporaryRelayTimers.get(e.url);if(o&&clearTimeout(o),!s||o){const a=setTimeout(()=>{var u;(u=this.ndk.explicitRelayUrls)!=null&&u.includes(e.url)||this.removeRelay(e.url)},t);this.temporaryRelayTimers.set(e.url,a)}}addRelay(e,t=!0){var m,y;const r=this.relays.has(e.url),s=(m=this.blacklistRelayUrls)==null?void 0:m.has(e.url),o=e.url.includes("/npub1");let a=!0;const u=e.url;if(r)return;if(s){this.debug(`Refusing to add relay ${u}: blacklisted`);return}if(o){this.debug(`Refusing to add relay ${u}: is a filter relay`);return}if((y=this.ndk.cacheAdapter)!=null&&y.getRelayStatus){const w=this.ndk.cacheAdapter.getRelayStatus(u);if(w!=null&&w.dontConnectBefore){if(w.dontConnectBefore>Date.now()){const x=w.dontConnectBefore-Date.now();this.debug(`Refusing to add relay ${u}: delayed connect for ${x}ms`),setTimeout(()=>{this.addRelay(e,t)},x);return}a=!1}}const c=w=>this.emit("notice",e,w),l=()=>this.handleRelayConnect(u),h=()=>this.handleRelayReady(e),f=()=>this.emit("relay:disconnect",e),p=()=>this.handleFlapping(e),b=w=>this.emit("relay:auth",e,w),v=()=>this.emit("relay:authed",e);e.off("notice",c),e.off("connect",l),e.off("ready",h),e.off("disconnect",f),e.off("flapping",p),e.off("auth",b),e.off("authed",v),e.on("notice",c),e.on("connect",l),e.on("ready",h),e.on("disconnect",f),e.on("flapping",p),e.on("auth",b),e.on("authed",v),e.on("delayed-connect",w=>{var x;(x=this.ndk.cacheAdapter)!=null&&x.updateRelayStatus&&this.ndk.cacheAdapter.updateRelayStatus(e.url,{dontConnectBefore:Date.now()+w})}),this._relays.set(u,e),t&&this.autoConnectRelays.add(u),t&&this.status==="active"&&(this.emit("relay:connecting",e),e.connect(void 0,a).catch(w=>{this.debug(`Failed to connect to relay ${u}`,w)}))}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 r=this.temporaryRelayTimers.get(e);return r&&(clearTimeout(r),this.temporaryRelayTimers.delete(e)),!1}isRelayConnected(e){const t=normalizeRelayUrl(e),r=this.relays.get(t);return r?r.status===5:!1}getRelay(e,t=!0,r=!1,s){let o=this.relays.get(normalizeRelayUrl(e));return o||(o=new NDKRelay(e,void 0,this.ndk),o.connectivity.netDebug=this.ndk.netDebug,r?this.useTemporaryRelay(o,3e4,s):this.addRelay(o,t)),o}handleRelayConnect(e){const t=this.relays.get(e);if(!t){console.error("NDK BUG: relay not found in pool",{relayUrl:e});return}this.emit("relay:connect",t),this.stats().connected===this.relays.size&&this.emit("connect")}handleRelayReady(e){this.emit("relay:ready",e)}async connect(e){const t=[];this.status="active",this.debug(`Connecting to ${this.relays.size} relays${e?`, timeout ${e}...`:""}`);const r=new Set(this.autoConnectRelays.keys());for(const o of r){const a=this.relays.get(o);if(!a)continue;const u=new Promise((c,l)=>(this.emit("relay:connecting",a),a.connect(e).then(c).catch(l)));if(e){const c=new Promise((l,h)=>{setTimeout(()=>h(`Timed out after ${e}ms`),e)});t.push(Promise.race([u,c]).catch(l=>{this.debug(`Failed to connect to relay ${a.url}: ${l??"No reason specified"}`)}))}else t.push(u)}const s=()=>{const o=this.stats().connected===this.relays.size,a=this.stats().connected>0;!o&&a&&this.emit("connect")};e&&setTimeout(s,e),await Promise.all(t),s()}checkOnFlappingRelays(){const e=this.flappingRelays.size,t=this.relays.size;if(e/t>=.8)for(const r of this.flappingRelays)this.backoffTimes.set(r,0)}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;t=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++,t.status===5?e.connected++:t.status===1?e.disconnected++:t.status===4&&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())}},NDKCashuMintList=(X=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_p2pk");this.kind??(this.kind=10019)}static from(t){return new X(t.ndk,t)}set relays(t){this.tags=this.tags.filter(r=>r[0]!=="relay");for(const r of t)this.tags.push(["relay",r])}get relays(){const t=[];for(const r of this.tags)r[0]==="relay"&&t.push(r[1]);return t}set mints(t){this.tags=this.tags.filter(r=>r[0]!=="mint");for(const r of t)this.tags.push(["mint",r])}get mints(){const t=[];for(const r of this.tags)r[0]==="mint"&&t.push(r[1]);return Array.from(new Set(t))}get p2pk(){return this._p2pk?this._p2pk:(this._p2pk=this.tagValue("pubkey")??this.pubkey,this._p2pk)}set p2pk(t){this._p2pk=t,this.removeTag("pubkey"),t&&this.tags.push(["pubkey",t])}get relaySet(){return NDKRelaySet.fromRelayUrls(this.relays,this.ndk)}},g(X,"kind",10019),g(X,"kinds",[10019]),X),NDKArticle=(he=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=30023)}static from(e){return new he(e.ndk,e)}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"),e!==void 0&&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")}},g(he,"kind",30023),g(he,"kinds",[30023]),he);function proofsTotalBalance(n){return n.reduce((e,t)=>{if(t.amount<0)throw new Error("proof amount is negative");return e+t.amount},0)}var NDKCashuToken=(Ae=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_proofs",[]);g(this,"_mint");g(this,"_deletes",[]);g(this,"original");this.kind??(this.kind=7375)}static async from(t){const r=new Ae(t.ndk,t);r.original=t;try{await r.decrypt()}catch{r.content=r.original.content}try{const s=JSON.parse(r.content);if(r.proofs=s.proofs,r.mint=s.mint??r.tagValue("mint"),r.deletedTokens=s.del??[],!Array.isArray(r.proofs))return}catch{return}return r}get proofs(){return this._proofs}set proofs(t){const r=new Set;this._proofs=t.filter(s=>r.has(s.C)?(console.warn("Passed in proofs had duplicates, ignoring",s.C),!1):s.amount<0?(console.warn("Invalid proof with negative amount",s),!1):(r.add(s.C),!0)).map(this.cleanProof)}cleanProof(t){return{id:t.id,amount:t.amount,C:t.C,secret:t.secret}}async toNostrEvent(t){if(!this.ndk)throw new Error("no ndk");if(!this.ndk.signer)throw new Error("no signer");const r={proofs:this.proofs.map(this.cleanProof),mint:this.mint,del:this.deletedTokens??[]};this.content=JSON.stringify(r);const s=await this.ndk.signer.user();return await this.encrypt(s,void 0,"nip44"),super.toNostrEvent(t)}set mint(t){this._mint=t}get mint(){return this._mint}get deletedTokens(){return this._deletes}set deletedTokens(t){this._deletes=t}get amount(){return proofsTotalBalance(this.proofs)}async publish(t,r,s){return this.original?this.original.publish(t,r,s):super.publish(t,r,s)}},g(Ae,"kind",7375),g(Ae,"kinds",[7375]),Ae),NDKHighlight=(Se=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_article");this.kind??(this.kind=9802)}static from(t){return new Se(t.ndk,t)}get url(){return this.tagValue("r")}set context(t){t===void 0?this.tags=this.tags.filter(([r,s])=>r!=="context"):(this.tags=this.tags.filter(([r,s])=>r!=="context"),this.tags.push(["context",t]))}get context(){var t;return((t=this.tags.find(([r,s])=>r==="context"))==null?void 0:t[1])??void 0}get article(){return this._article}set article(t){this._article=t,typeof t=="string"?this.tags.push(["r",t]):this.tag(t)}getArticleTag(){return this.getMatchingTags("a")[0]||this.getMatchingTags("e")[0]||this.getMatchingTags("r")[0]}async getArticle(){var s;if(this._article!==void 0)return this._article;let t;const r=this.getArticleTag();if(r){switch(r[0]){case"a":{const[o,a,u]=r[1].split(":");t=nip19_exports.naddrEncode({kind:Number.parseInt(o),pubkey:a,identifier:u});break}case"e":t=nip19_exports.noteEncode(r[1]);break;case"r":this._article=r[1];break}if(t){let o=await((s=this.ndk)==null?void 0:s.fetchEvent(t));o&&(o.kind===30023&&(o=NDKArticle.from(o)),this._article=o)}return this._article}}},g(Se,"kind",9802),g(Se,"kinds",[9802]),Se);function mapImetaTag(n){const e={};if(n.length===2){const r=n[1].split(" ");for(let s=0;s<r.length;s+=2){const o=r[s],a=r[s+1];o==="fallback"?(e.fallback||(e.fallback=[]),e.fallback.push(a)):e[o]=a}return e}const t=n.slice(1);for(const r of t){const s=r.split(" "),o=s[0],a=s.slice(1).join(" ");o==="fallback"?(e.fallback||(e.fallback=[]),e.fallback.push(a)):e[o]=a}return e}function imetaTagToTag(n){const e=["imeta"];for(const[t,r]of Object.entries(n))if(Array.isArray(r))for(const s of r)e.push(`${t} ${s}`);else r&&e.push(`${t} ${r}`);return e}var NDKImage=(Te=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_imetas");this.kind??(this.kind=20)}static from(t){return new Te(t.ndk,t.rawEvent())}get isValid(){return this.imetas.length>0}get imetas(){return this._imetas?this._imetas:(this._imetas=this.tags.filter(t=>t[0]==="imeta").map(mapImetaTag).filter(t=>!!t.url),this._imetas)}set imetas(t){this._imetas=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),this.tags.push(...t.map(imetaTagToTag))}},g(Te,"kind",20),g(Te,"kinds",[20]),Te),NDKList=($e=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_encryptedTags");g(this,"encryptedTagsLength");this.kind??(this.kind=30001)}static from(t){return new $e(t.ndk,t)}get title(){const t=this.tagValue("title")||this.tagValue("name");return t||(this.kind===3?"Contacts":this.kind===1e4?"Mute":this.kind===10001?"Pinned Notes":this.kind===10002?"Relay Metadata":this.kind===10003?"Bookmarks":this.kind===10004?"Communities":this.kind===10005?"Public Chats":this.kind===10006?"Blocked Relays":this.kind===10007?"Search Relays":this.kind===10050?"Direct Message Receive Relays":this.kind===10015?"Interests":this.kind===10030?"Emojis":this.tagValue("d"))}set title(t){this.removeTag(["title","name"]),t&&this.tags.push(["title",t])}get name(){return this.title}set name(t){this.title=t}get description(){return this.tagValue("description")}set description(t){this.removeTag("description"),t&&this.tags.push(["description",t])}get image(){return this.tagValue("image")}set image(t){this.removeTag("image"),t&&this.tags.push(["image",t])}isEncryptedTagsCacheValid(){return!!(this._encryptedTags&&this.encryptedTagsLength===this.content.length)}async encryptedTags(t=!0){if(t&&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 r=await this.ndk.signer.user();try{if(this.content.length>0)try{const s=await this.ndk.signer.decrypt(r,this.content),o=JSON.parse(s);return o!=null&&o[0]?(this.encryptedTagsLength=this.content.length,this._encryptedTags=o):(this.encryptedTagsLength=this.content.length,this._encryptedTags=[])}catch{}}catch{}return[]}validateTag(t){return!0}getItems(t){return this.tags.filter(r=>r[0]===t)}get items(){return this.tags.filter(t=>!["d","L","l","title","name","description","published_at","summary","image","thumb","alt","expiration","subject","client"].includes(t[0]))}async addItem(t,r=void 0,s=!1,o="bottom"){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");let a;if(t instanceof NDKEvent)a=[t.tagReference(r)];else if(t instanceof NDKUser)a=t.referenceTags();else if(t instanceof NDKRelay)a=t.referenceTags();else if(Array.isArray(t))a=[t];else throw new Error("Invalid object type");if(r&&a[0].push(r),s){const u=await this.ndk.signer.user(),c=await this.encryptedTags();o==="top"?c.unshift(...a):c.push(...a),this._encryptedTags=c,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(c),await this.encrypt(u)}else o==="top"?this.tags.unshift(...a):this.tags.push(...a);this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItemByValue(t,r=!0){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const s=this.tags.findIndex(c=>c[1]===t);s>=0&&this.tags.splice(s,1);const o=await this.ndk.signer.user(),a=await this.encryptedTags(),u=a.findIndex(c=>c[1]===t);if(u>=0&&(a.splice(u,1),this._encryptedTags=a,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(a),await this.encrypt(o)),r)return this.publishReplaceable();this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItem(t,r){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");if(r){const s=await this.ndk.signer.user(),o=await this.encryptedTags();o.splice(t,1),this._encryptedTags=o,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(o),await this.encrypt(s)}else this.tags.splice(t,1);return this.created_at=Math.floor(Date.now()/1e3),this.emit("change"),this}has(t){return this.items.some(r=>r[1]===t)}filterForItems(){const t=new Set,r=new Map,s=[];for(const o of this.items)if(o[0]==="e"&&o[1])t.add(o[1]);else if(o[0]==="a"&&o[1]){const[a,u,c]=o[1].split(":");if(!a||!u)continue;const l=`${a}:${u}`,h=r.get(l)||[];h.push(c||""),r.set(l,h)}if(t.size>0&&s.push({ids:Array.from(t)}),r.size>0)for(const[o,a]of r.entries()){const[u,c]=o.split(":");s.push({kinds:[Number.parseInt(u)],authors:[c],"#d":a})}return s}},g($e,"kinds",[10063,30001,10004,10050,10030,10015,10001,10002,10007,10006,10003]),$e),lists_default=NDKList,NDKNutzap=(we=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"debug");g(this,"_proofs",[]);g(this,"sender",this.author);this.kind??(this.kind=9321),this.debug=(t==null?void 0:t.debug.extend("nutzap"))??createDebug5("ndk:nutzap"),this.alt||(this.alt="This is a nutzap");try{const s=this.getMatchingTags("proof");s.length?this._proofs=s.map(o=>JSON.parse(o[1])):this._proofs=JSON.parse(this.content)}catch{return}}static from(t){const r=new we(t.ndk,t);if(!(!r._proofs||!r._proofs.length))return r}set comment(t){this.content=t??""}get comment(){const t=this.tagValue("comment");return t||this.content}set proofs(t){this._proofs=t,this.tags=this.tags.filter(r=>r[0]!=="proof");for(const r of t)this.tags.push(["proof",JSON.stringify(r)])}get proofs(){return this._proofs}get rawP2pk(){var r;const t=this.proofs[0];try{const s=JSON.parse(t.secret);let o;if(typeof s=="string"?(o=JSON.parse(s),this.debug("stringified payload",t.secret)):typeof s=="object"&&(o=s),Array.isArray(o)&&o[0]==="P2PK"&&o.length>1&&typeof o[1]=="object"&&o[1]!==null||typeof o=="object"&&o!==null&&typeof((r=o[1])==null?void 0:r.data)=="string")return o[1].data}catch(s){this.debug("error parsing p2pk pubkey",s,this.proofs[0])}}get p2pk(){const t=this.rawP2pk;if(t)return t.startsWith("02")?t.slice(2):t}get mint(){return this.tagValue("u")}set mint(t){this.replaceTag(["u",t])}get unit(){let t=this.tagValue("unit")??"sat";return t!=null&&t.startsWith("msat")&&(t="sat"),t}set unit(t){if(this.removeTag("unit"),t!=null&&t.startsWith("msat"))throw new Error("msat is not allowed, use sat denomination instead");t&&this.tag(["unit",t])}get amount(){return this.proofs.reduce((r,s)=>r+s.amount,0)}set target(t){this.tags=this.tags.filter(r=>r[0]!=="p"),t instanceof NDKEvent&&this.tags.push(t.tagReference())}set recipientPubkey(t){this.removeTag("p"),this.tag(["p",t])}get recipientPubkey(){return this.tagValue("p")}get recipient(){const t=this.recipientPubkey;return this.ndk?this.ndk.getUser({pubkey:t}):new NDKUser({pubkey:t})}async toNostrEvent(){this.unit==="msat"&&(this.unit="sat"),this.removeTag("amount"),this.tags.push(["amount",this.amount.toString()]);const t=await super.toNostrEvent();return t.content=this.comment,t}get isValid(){let t=0,r=0,s=0;for(const o of this.tags)o[0]==="e"&&t++,o[0]==="p"&&r++,o[0]==="u"&&s++;return r===1&&s===1&&t<=1&&this.proofs.length>0}},g(we,"kind",9321),g(we,"kinds",[we.kind]),we),NDKSimpleGroupMemberList=(Ce=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"relaySet");g(this,"memberSet",new Set);this.kind??(this.kind=39002),this.memberSet=new Set(this.members)}static from(t){return new Ce(t.ndk,t)}get members(){return this.getMatchingTags("p").map(t=>t[1])}hasMember(t){return this.memberSet.has(t)}async publish(t,r,s){return t??(t=this.relaySet),super.publishReplaceable(t,r,s)}},g(Ce,"kind",39002),g(Ce,"kinds",[39002]),Ce),NDKSimpleGroupMetadata=(_e=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=39e3)}static from(e){return new _e(e.ndk,e)}get name(){return this.tagValue("name")}get picture(){return this.tagValue("picture")}get about(){return this.tagValue("about")}get scope(){if(this.getMatchingTags("public").length>0)return"public";if(this.getMatchingTags("public").length>0)return"private"}set scope(e){this.removeTag("public"),this.removeTag("private"),e==="public"?this.tags.push(["public",""]):e==="private"&&this.tags.push(["private",""])}get access(){if(this.getMatchingTags("open").length>0)return"open";if(this.getMatchingTags("closed").length>0)return"closed"}set access(e){this.removeTag("open"),this.removeTag("closed"),e==="open"?this.tags.push(["open",""]):e==="closed"&&this.tags.push(["closed",""])}},g(_e,"kind",39e3),g(_e,"kinds",[39e3]),_e);function strToPosition(n){const[e,t]=n.split(",").map(Number);return{x:e,y:t}}function strToDimension(n){const[e,t]=n.split("x").map(Number);return{width:e,height:t}}var NDKStorySticker=(me=class{constructor(e){g(this,"type");g(this,"value");g(this,"position");g(this,"dimension");g(this,"properties");g(this,"hasValidDimensions",()=>typeof this.dimension.width=="number"&&typeof this.dimension.height=="number"&&!Number.isNaN(this.dimension.width)&&!Number.isNaN(this.dimension.height));g(this,"hasValidPosition",()=>typeof this.position.x=="number"&&typeof this.position.y=="number"&&!Number.isNaN(this.position.x)&&!Number.isNaN(this.position.y));if(Array.isArray(e)){const t=e;if(t[0]!=="sticker"||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 r={};for(let s=5;s<t.length;s++){const[o,...a]=t[s].split(" ");r[o]=a.join(" ")}Object.keys(r).length>0&&(this.properties=r)}else this.type=e,this.value=void 0,this.position={x:0,y:0},this.dimension={width:0,height:0}}static fromTag(e){try{return new me(e)}catch{return null}}get style(){var e;return(e=this.properties)==null?void 0:e.style}set style(e){var t;e?this.properties={...this.properties,style:e}:(t=this.properties)==null||delete t.style}get rotation(){var e;return(e=this.properties)!=null&&e.rot?Number.parseFloat(this.properties.rot):void 0}set rotation(e){var t;e!==void 0?this.properties={...this.properties,rot:e.toString()}:(t=this.properties)==null||delete t.rot}get isValid(){return this.hasValidDimensions()&&this.hasValidPosition()}toTag(){if(!this.isValid){const r=[this.hasValidDimensions()?void 0:"dimensions is invalid",this.hasValidPosition()?void 0:"position is invalid"].filter(Boolean);throw new Error(`Invalid sticker: ${r.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[r,s]of Object.entries(this.properties))t.push(`${r} ${s}`);return t}},g(me,"Text","text"),g(me,"Pubkey","pubkey"),g(me,"Event","event"),g(me,"Prompt","prompt"),g(me,"Countdown","countdown"),me),NDKStory=(Ne=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_imeta");g(this,"_dimensions");if(this.kind??(this.kind=23),r)for(const s of r.tags)switch(s[0]){case"imeta":this._imeta=mapImetaTag(s);break;case"dim":this.dimensions=strToDimension(s[1]);break}}static from(t){return new Ne(t.ndk,t)}get isValid(){return!!this.imeta}get imeta(){return this._imeta}set imeta(t){this._imeta=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),t&&this.tags.push(imetaTagToTag(t))}get dimensions(){const t=this.tagValue("dim");if(t)return strToDimension(t)}set dimensions(t){this.removeTag("dim"),t&&this.tags.push(["dim",`${t.width}x${t.height}`])}get duration(){const t=this.tagValue("dur");if(t)return Number.parseInt(t)}set duration(t){this.removeTag("dur"),t!==void 0&&this.tags.push(["dur",t.toString()])}get stickers(){const t=[];for(const r of this.tags){if(r[0]!=="sticker"||r.length<5)continue;const s=NDKStorySticker.fromTag(r);s&&t.push(s)}return t}addSticker(t){let r;if(t instanceof NDKStorySticker)r=t;else{const s=["sticker",t.type,typeof t.value=="string"?t.value:"",coordinates(t.position),dimension(t.dimension)];if(t.properties)for(const[o,a]of Object.entries(t.properties))s.push(`${o} ${a}`);r=new NDKStorySticker(s),r.value=t.value}r.type==="pubkey"?this.tag(r.value):r.type==="event"&&this.tag(r.value),this.tags.push(r.toTag())}removeSticker(t){const r=this.stickers;if(t<0||t>=r.length)return;let s=0;for(let o=0;o<this.tags.length;o++)if(this.tags[o][0]==="sticker"){if(s===t){this.tags.splice(o,1);break}s++}}},g(Ne,"kind",23),g(Ne,"kinds",[23]),Ne),coordinates=n=>`${n.x},${n.y}`,dimension=n=>`${n.width}x${n.height}`,possibleIntervalFrequencies=["daily","weekly","monthly","quarterly","yearly"];function newAmount(n,e,t){return["amount",n.toString(),e,t]}function parseTagToSubscriptionAmount(n){const e=Number.parseInt(n[1]);if(Number.isNaN(e)||e===void 0||e===null||e<=0)return;const t=n[2];if(t===void 0||t==="")return;const r=n[3];if(r!==void 0&&possibleIntervalFrequencies.includes(r))return{amount:e,currency:t,term:r}}var NDKSubscriptionTier=(Re=class extends NDKArticle{constructor(e,t){const r=(t==null?void 0:t.kind)??37001;super(e,t),this.kind=r}static from(e){return new Re(e.ndk,e)}get perks(){return this.getMatchingTags("perk").map(e=>e[1]).filter(e=>e!==void 0)}addPerk(e){this.tags.push(["perk",e])}get amounts(){return this.getMatchingTags("amount").map(e=>parseTagToSubscriptionAmount(e)).filter(e=>e!==void 0)}addAmount(e,t,r){this.tags.push(newAmount(e,t,r))}set relayUrl(e){this.tags.push(["r",e])}get relayUrls(){return this.getMatchingTags("r").map(e=>e[1]).filter(e=>e!==void 0)}get verifierPubkey(){return this.tagValue("p")}set verifierPubkey(e){this.removeTag("p"),e&&this.tags.push(["p",e])}get isValid(){return this.title!==void 0&&this.amounts.length>0}},g(Re,"kind",37001),g(Re,"kinds",[37001]),Re),NDKVideo=(Le=class extends NDKEvent{constructor(){super(...arguments);g(this,"_imetas")}static from(t){return new Le(t.ndk,t.rawEvent())}get title(){return this.tagValue("title")}set title(t){this.removeTag("title"),t&&this.tags.push(["title",t])}get thumbnail(){var r;let t;return this.imetas&&this.imetas.length>0&&(t=(r=this.imetas[0].image)==null?void 0:r[0]),t??this.tagValue("thumb")}get imetas(){return this._imetas?this._imetas:(this._imetas=this.tags.filter(t=>t[0]==="imeta").map(mapImetaTag),this._imetas)}set imetas(t){this._imetas=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),this.tags.push(...t.map(imetaTagToTag))}get url(){return this.imetas&&this.imetas.length>0?this.imetas[0].url:this.tagValue("url")}get published_at(){const t=this.tagValue("published_at");if(t)return Number.parseInt(t)}async generateTags(){var t,r;if(super.generateTags(),!this.kind&&(r=(t=this.imetas)==null?void 0:t[0])!=null&&r.dim){const[s,o]=this.imetas[0].dim.split("x"),a=s&&o&&Number.parseInt(s)<Number.parseInt(o);this.duration&&this.duration<120&&a?this.kind=22:this.kind=21}return super.generateTags()}get duration(){const t=this.tagValue("duration");if(t)return Number.parseInt(t)}set duration(t){this.removeTag("duration"),t!==void 0&&this.tags.push(["duration",Math.floor(t).toString()])}},g(Le,"kind",21),g(Le,"kinds",[34235,34236,22,21]),Le),NDKWiki=(je=class extends NDKArticle{},g(je,"kind",30818),g(je,"kinds",[30818]),je);function wrapEvent(n){const e=new Map;for(const r of[NDKImage,NDKVideo,NDKCashuMintList,NDKArticle,NDKHighlight,NDKWiki,NDKNutzap,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKSubscriptionTier,NDKCashuToken,NDKList,NDKStory])for(const s of r.kinds)e.set(s,r);const t=e.get(n.kind);return t?t.from(n):n}function queryFullyFilled(n){return!!(filterIncludesIds(n.filter)&&resultHasAllRequestedIds(n))}function filterIncludesIds(n){return!!n.ids}function resultHasAllRequestedIds(n){const e=n.filter.ids;return!!e&&e.length===n.eventFirstSeen.size}function filterFromId(n){let e;if(n.match(NIP33_A_REGEX)){const[t,r,s]=n.split(":"),o={authors:[r],kinds:[Number.parseInt(t)]};return s&&(o["#d"]=[s]),o}if(n.match(BECH32_REGEX))try{switch(e=nip19_exports.decode(n),e.type){case"nevent":{const t={ids:[e.data.id]};return e.data.author&&(t.authors=[e.data.author]),e.data.kind&&(t.kinds=[e.data.kind]),t}case"note":return{ids:[e.data]};case"naddr":{const t={authors:[e.data.pubkey],kinds:[e.data.kind]};return e.data.identifier&&(t["#d"]=[e.data.identifier]),t}}}catch(t){console.error("Error decoding",n,t)}return{ids:[n]}}function isNip33AValue(n){return n.match(NIP33_A_REGEX)!==null}var NIP33_A_REGEX=/^(\d+):([0-9A-Fa-f]+)(?::(.*))?$/,BECH32_REGEX=/^n(event|ote|profile|pub|addr)1[\d\w]+$/;function relaysFromBech32(n,e){try{const t=nip19_exports.decode(n);if(["naddr","nevent"].includes(t==null?void 0:t.type)){const r=t.data;if(r!=null&&r.relays)return r.relays.map(s=>new NDKRelay(s,e.relayAuthDefaultPolicy,e))}}catch{}return[]}var defaultOpts$1={closeOnEose:!1,cacheUsage:"CACHE_FIRST",dontSaveToCache:!1,groupable:!0,groupableDelay:100,groupableDelayType:"at-most",cacheUnconstrainFilter:["limit","since","until"]},NDKSubscription=class extends lib$1.EventEmitter{constructor(e,t,r,s){super();g(this,"subId");g(this,"filters");g(this,"opts");g(this,"pool");g(this,"skipVerification",!1);g(this,"skipValidation",!1);g(this,"relayFilters");g(this,"relaySet");g(this,"ndk");g(this,"debug");g(this,"eventFirstSeen",new Map);g(this,"eosesSeen",new Set);g(this,"lastEventReceivedAt");g(this,"mostRecentCacheEventTimestamp");g(this,"internalId");g(this,"closeOnEose");g(this,"poolMonitor");g(this,"skipOptimisticPublishEvent",!1);g(this,"cacheUnconstrainFilter");g(this,"onStopped");g(this,"eoseTimeout");g(this,"eosed",!1);this.ndk=e,this.opts={...defaultOpts$1,...r||{}},this.pool=this.opts.pool||e.pool,this.filters=Array.isArray(t)?t:[t],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}relaysMissingEose(){var t;return this.relayFilters?Array.from((t=this.relayFilters)==null?void 0:t.keys()).filter(r=>!this.eosesSeen.has(this.pool.getRelay(r,!1,!1))):[]}get filter(){return this.filters[0]}get groupableDelay(){var e;if(this.isGroupable())return(e=this.opts)==null?void 0:e.groupableDelay}get groupableDelayType(){var e;return((e=this.opts)==null?void 0:e.groupableDelayType)||"at-most"}isGroupable(){var e;return((e=this.opts)==null?void 0:e.groupable)||!1}shouldQueryCache(){var t;return this.opts.addSinceFromCache?!0:((t=this.opts)==null?void 0:t.cacheUsage)==="ONLY_RELAY"?!1:(this.filters.some(r=>{var s;return(s=r.kinds)==null?void 0:s.some(o=>kindIsEphemeral(o))}),!0)}shouldQueryRelays(){var e;return((e=this.opts)==null?void 0:e.cacheUsage)!=="ONLY_CACHE"}shouldWaitForCache(){var e;return this.opts.addSinceFromCache?!0:this.opts.closeOnEose&&!!((e=this.ndk.cacheAdapter)!=null&&e.locking)&&this.opts.cacheUsage!=="PARALLEL"}start(e=!0){let t;const r=o=>{if(e)for(const a of o)(!this.mostRecentCacheEventTimestamp||a.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=a.created_at),this.eventReceived(a,void 0,!0,!1);else{t=[];for(const a of o){(!this.mostRecentCacheEventTimestamp||a.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=a.created_at),a.ndk=this.ndk;const u=this.opts.wrap?wrapEvent(a):a;if(!u)break;if(u instanceof Promise){u.then(c=>{this.emitEvent(!1,c,void 0,!0,!1)});break}this.eventFirstSeen.set(u.id,Date.now()),t.push(u)}}},s=()=>{this.shouldQueryRelays()?(this.startWithRelays(),this.startPoolMonitor()):this.emit("eose",this)};return this.shouldQueryCache()?(t=this.startWithCache(),t instanceof Promise?this.shouldWaitForCache()?(t.then(o=>{if(r(o),queryFullyFilled(this)){this.emit("eose",this);return}s()}),null):(t.then(o=>{r(o)}),s(),null):(r(t),queryFullyFilled(this)?this.emit("eose",this):s(),t)):(s(),null)}startPoolMonitor(){this.debug.extend("pool-monitor"),this.poolMonitor=e=>{var r,s;if((r=this.relayFilters)!=null&&r.has(e.url))return;calculateRelaySetsFromFilters(this.ndk,this.filters,this.pool).get(e.url)&&((s=this.relayFilters)==null||s.set(e.url,this.filters),e.subscribe(this,this.filters))},this.pool.on("relay:connect",this.poolMonitor)}stop(){var e;this.emit("close",this),this.poolMonitor&&this.pool.off("relay:connect",this.poolMonitor),(e=this.onStopped)==null||e.call(this)}hasAuthorsFilter(){return this.filters.some(e=>{var t;return(t=e.authors)==null?void 0:t.length})}startWithCache(){var e;return(e=this.ndk.cacheAdapter)!=null&&e.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(r=>({...r,since:Math.max(r.since||0,t)}))}if(!this.relaySet||this.relaySet.relays.size===0)this.relayFilters=calculateRelaySetsFromFilters(this.ndk,e,this.pool);else{this.relayFilters=new Map;for(const t of this.relaySet.relays)this.relayFilters.set(t.url,e)}for(const[t,r]of this.relayFilters)this.pool.getRelay(t,!0,!0,r).subscribe(this,r)}eventReceived(e,t,r=!1,s=!1){var c;const o=e.id,a=this.eventFirstSeen.has(o);let u;if(e instanceof NDKEvent&&(u=e),a){const l=Date.now()-(this.eventFirstSeen.get(o)||0);if(this.emit("event:dup",e,t,l,this,r,s),t){const h=verifiedSignatures.get(o);h&&typeof h=="string"&&e.sig===h&&t.addValidatedEvent()}}else{if(u??(u=new NDKEvent(this.ndk,e)),u.ndk=this.ndk,u.relay=t,!r&&!s){if(!this.skipValidation&&!u.isValid){this.debug("Event failed validation %s from relay %s",o,t==null?void 0:t.url);return}if(t)if((t==null?void 0:t.shouldValidateEvent())!==!1){if(!this.skipVerification){if(!u.verifySignature(!0)&&!this.ndk.asyncSigVerification){this.debug("Event failed signature validation",e);return}t&&t.addValidatedEvent()}}else t.addNonValidatedEvent();this.ndk.cacheAdapter&&!this.opts.dontSaveToCache&&this.ndk.cacheAdapter.setEvent(u,this.filters,t)}(!s||this.skipOptimisticPublishEvent!==!0)&&(this.emitEvent(((c=this.opts)==null?void 0:c.wrap)??!1,u,t,r,s),this.eventFirstSeen.set(o,Date.now()))}this.lastEventReceivedAt=Date.now()}emitEvent(e,t,r,s,o){const a=e?wrapEvent(t):t;a instanceof Promise?a.then(u=>this.emitEvent(!1,u,r,s,o)):a&&this.emit("event",a,r,this,s,o)}closedReceived(e,t){this.emit("closed",e,t)}eoseReceived(e){var a;this.debug("EOSE received from %s",e.url),this.eosesSeen.add(e);let t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0;const r=this.eosesSeen.size===((a=this.relayFilters)==null?void 0:a.size),s=queryFullyFilled(this),o=u=>{var c;this.debug("Performing EOSE: %s %d",u,this.eosed),!this.eosed&&(this.eoseTimeout&&clearTimeout(this.eoseTimeout),this.emit("eose",this),this.eosed=!0,(c=this.opts)!=null&&c.closeOnEose&&this.stop())};if(s||r)o("query filled or seen all");else if(this.relayFilters){let u=1e3;const c=new Set(this.pool.connectedRelays().map(f=>f.url)),l=Array.from(this.relayFilters.keys()).filter(f=>c.has(f));if(l.length===0){this.debug("No connected relays, waiting for all relays to connect",Array.from(this.relayFilters.keys()).join(", "));return}const h=this.eosesSeen.size/l.length;if(this.debug("Percentage of relays that have sent EOSE",{subId:this.subId,percentageOfRelaysThatHaveSentEose:h,seen:this.eosesSeen.size,total:l.length}),this.eosesSeen.size>=2&&h>=.5){if(u=u*(1-h),u===0){o("time to wait was 0");return}this.eoseTimeout&&clearTimeout(this.eoseTimeout);const f=()=>{t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0,t!==void 0&&t<20?this.eoseTimeout=setTimeout(f,u):o(`send eose timeout: ${u}`)};this.eoseTimeout=setTimeout(f,u)}}}},kindIsEphemeral=n=>n>=2e4&&n<3e4;async function follows(n,e,t=3){var s,o;if(!this.ndk)throw new Error("NDK not set");const r=await this.ndk.fetchEvent({kinds:[t],authors:[this.pubkey]},n||{groupable:!1});if(r){const a=new Set;return r.tags.forEach(u=>{u[0]==="p"&&a.add(u[1])}),e&&((o=(s=this.ndk)==null?void 0:s.outboxTracker)==null||o.trackUsers(Array.from(a))),[...a].reduce((u,c)=>{const l=new NDKUser({pubkey:c});return l.ndk=this.ndk,u.add(l),u},new Set)}return new Set}var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function getNip05For(n,e,t=fetch,r={}){return await n.queuesNip05.add({id:e,func:async()=>{var c,l,h;if((c=n.cacheAdapter)!=null&&c.loadNip05){const f=await n.cacheAdapter.loadNip05(e);if(f!=="missing"){if(f){const p=new NDKUser({pubkey:f.pubkey,relayUrls:f.relays,nip46Urls:f.nip46});return p.ndk=n,p}if(r.cache!=="no-cache")return null}}const s=e.match(NIP05_REGEX);if(!s)return null;const[o,a="_",u]=s;try{const f=await t(`https://${u}/.well-known/nostr.json?name=${a}`,r),{names:p,relays:b,nip46:v}=parseNIP05Result(await f.json()),m=p[a.toLowerCase()];let y=null;return m&&(y={pubkey:m,relays:b==null?void 0:b[m],nip46:v==null?void 0:v[m]}),(l=n==null?void 0:n.cacheAdapter)!=null&&l.saveNip05&&n.cacheAdapter.saveNip05(e,y),y}catch(f){return(h=n==null?void 0:n.cacheAdapter)!=null&&h.saveNip05&&(n==null||n.cacheAdapter.saveNip05(e,null)),console.error("Failed to fetch NIP05 for",e,f),null}}})}function parseNIP05Result(n){const e={names:{}};for(const[t,r]of Object.entries(n.names))typeof t=="string"&&typeof r=="string"&&(e.names[t.toLowerCase()]=r);if(n.relays){e.relays={};for(const[t,r]of Object.entries(n.relays))typeof t=="string"&&Array.isArray(r)&&(e.relays[t]=r.filter(s=>typeof s=="string"))}if(n.nip46){e.nip46={};for(const[t,r]of Object.entries(n.nip46))typeof t=="string"&&Array.isArray(r)&&(e.nip46[t]=r.filter(s=>typeof s=="string"))}return e}function profileFromEvent(n){const e={};let t;try{t=JSON.parse(n.content)}catch(r){throw new Error(`Failed to parse profile event: ${r}`)}e.created_at=n.created_at,e.profileEvent=JSON.stringify(n.rawEvent());for(const r of Object.keys(t))switch(r){case"name":e.name=t.name;break;case"display_name":e.displayName=t.display_name;break;case"image":case"picture":e.picture=t.picture||t.image,e.image=e.picture;break;case"banner":e.banner=t.banner;break;case"bio":e.bio=t.bio;break;case"nip05":e.nip05=t.nip05;break;case"lud06":e.lud06=t.lud06;break;case"lud16":e.lud16=t.lud16;break;case"about":e.about=t.about;break;case"website":e.website=t.website;break;default:e[r]=t[r];break}return e}function serializeProfile(n){const e={};for(const[t,r]of Object.entries(n))switch(t){case"username":case"name":e.name=r;break;case"displayName":e.display_name=r;break;case"image":case"picture":e.picture=r;break;case"bio":case"about":e.about=r;break;default:e[t]=r;break}return JSON.stringify(e)}var NDKUser=class Ct{constructor(e){g(this,"ndk");g(this,"profile");g(this,"profileEvent");g(this,"_npub");g(this,"_pubkey");g(this,"relayUrls",[]);g(this,"nip46Urls",[]);g(this,"follows",follows.bind(this));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.decode(e.nprofile);t.type==="nprofile"&&(this._pubkey=t.data.pubkey,t.data.relays&&t.data.relays.length>0&&this.relayUrls.push(...t.data.relays))}catch(t){console.error("Failed to decode nprofile",t)}}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("pubkey not set");this._npub=nip19_exports.npubEncode(this.pubkey)}return this._npub}get nprofile(){var t,r;const e=(r=(t=this.profileEvent)==null?void 0:t.onRelays)==null?void 0:r.map(s=>s.url);return nip19_exports.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.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 a=>{if(!e)return a;let u;const c=new Promise((l,h)=>{u=setTimeout(()=>h(new Error("Timeout")),e)});try{const l=await Promise.race([a,c]);return u&&clearTimeout(u),l}catch(l){if(l instanceof Error&&l.message==="Timeout")try{return await a}catch{return}return}},[r,s]=await Promise.all([t(this.fetchProfile()),t(this.ndk.fetchEvent({kinds:[10019],authors:[this.pubkey]}))]),o=new Map;if(s){const a=NDKCashuMintList.from(s);a.mints.length>0&&o.set("nip61",{mints:a.mints,relays:a.relays,p2pk:a.p2pk})}if(r){const{lud06:a,lud16:u}=r;o.set("nip57",{lud06:a,lud16:u})}return o}static async fromNip05(e,t,r=!1){if(!t)throw new Error("No NDK instance found");const s={};r&&(s.cache="no-cache");const o=await getNip05For(t,e,t==null?void 0:t.httpFetch,s);if(o){const a=new Ct({pubkey:o.pubkey,relayUrls:o.relays,nip46Urls:o.nip46});return a.ndk=t,a}}async fetchProfile(e,t=!1){if(!this.ndk)throw new Error("NDK not set");let r=null;if(this.ndk.cacheAdapter&&(this.ndk.cacheAdapter.fetchProfile||this.ndk.cacheAdapter.fetchProfileSync)&&(e==null?void 0:e.cacheUsage)!=="ONLY_RELAY"){let s=null;if(this.ndk.cacheAdapter.fetchProfileSync?s=this.ndk.cacheAdapter.fetchProfileSync(this.pubkey):this.ndk.cacheAdapter.fetchProfile&&(s=await this.ndk.cacheAdapter.fetchProfile(this.pubkey)),s)return this.profile=s,s}return e??(e={}),e.cacheUsage??(e.cacheUsage="ONLY_RELAY"),e.closeOnEose??(e.closeOnEose=!0),e.groupable??(e.groupable=!0),e.groupableDelay??(e.groupableDelay=250),r||(r=await this.ndk.fetchEvent({kinds:[0],authors:[this.pubkey]},e)),r?(this.profile=profileFromEvent(r),t&&this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile):null}async followSet(e,t,r=3){const s=await this.follows(e,t,r);return new Set(Array.from(s).map(o=>o.pubkey))}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e&&t[0].push("",e),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(),await new NDKEvent(this.ndk,{kind:0,content:serializeProfile(this.profile)}).publish()}async follow(e,t,r=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,r)),t.has(e))return!1;t.add(e);const s=new NDKEvent(this.ndk,{kind:r});for(const o of t)s.tag(o);return await s.publish(),!0}async unfollow(e,t,r=3){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,r));const s=new Set;let o=!1;for(const u of t)u.pubkey!==e.pubkey?s.add(u):o=!0;if(!o)return!1;const a=new NDKEvent(this.ndk,{kind:r});for(const u of s)a.tag(u);return await a.publish()}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(this.ndk,e);return t===null?null:t.pubkey===this.pubkey}},READ_MARKER="read",WRITE_MARKER="write",NDKRelayList=class _t extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=10002)}static from(e){return new _t(e.ndk,e.rawEvent())}get readRelayUrls(){return this.tags.filter(e=>e[0]==="r"||e[0]==="relay").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=>e[0]==="r"||e[0]==="relay").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=>e[0]==="r"||e[0]==="relay").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=>e[0]==="r"||e[0]==="relay").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=>{var t;return(t=this.ndk)==null?void 0:t.pool.getRelay(e)}).filter(e=>!!e)),this.ndk)}};function relayListFromKind3(n,e){try{const t=JSON.parse(e.content),r=new NDKRelayList(n),s=new Set,o=new Set;for(let[a,u]of Object.entries(t)){try{a=normalizeRelayUrl(a)}catch{continue}if(!u)s.add(a),o.add(a);else{const c=u;c.write&&o.add(a),c.read&&s.add(a)}}return r.readRelayUrls=Array.from(s),r.writeRelayUrls=Array.from(o),r}catch{}}var NDKPrivateKeySigner=class it{constructor(e,t){g(this,"_user");g(this,"_privateKey");g(this,"_pubkey");if(typeof e=="string")if(e.startsWith("nsec1")){const{type:r,data:s}=nip19_exports.decode(e);if(r==="nsec")this._privateKey=s;else throw new Error("Invalid private key provided.")}else if(e.length===64)this._privateKey=hexToBytes$1(e);else throw new Error("Invalid private key provided.");else this._privateKey=e;this._pubkey=getPublicKey$1(this._privateKey),t&&(this._user=t.getUser({pubkey:this._pubkey})),this._user??(this._user=new NDKUser({pubkey:this._pubkey}))}get privateKey(){if(!this._privateKey)throw new Error("Not ready");return bytesToHex$1(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.nsecEncode(this._privateKey)}get npub(){if(!this._pubkey)throw new Error("Not ready");return nip19_exports.npubEncode(this._pubkey)}static generate(){const e=generateSecretKey$1();return new it(e)}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$1(e,this._privateKey).sig}async encryptionEnabled(e){const t=[];return(!e||e==="nip04")&&t.push("nip04"),(!e||e==="nip44")&&t.push("nip44"),t}async encrypt(e,t,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to encrypt without a private key");const s=e.pubkey;if(r==="nip44"){const o=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.encrypt(t,o)}return await nip04_exports.encrypt(this._privateKey,s,t)}async decrypt(e,t,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to decrypt without a private key");const s=e.pubkey;if(r==="nip44"){const o=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.decrypt(t,o)}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(e,t){const r=JSON.parse(e);if(r.type!=="private-key")throw new Error(`Invalid payload type: expected 'private-key', got ${r.type}`);if(!r.payload||typeof r.payload!="string")throw new Error("Invalid payload content for private-key signer");return new it(r.payload,t)}};function disconnect(n,e){return e??(e=createDebug5("ndk:relay:auth-policies:disconnect")),async t=>{e==null||e(`Relay ${t.url} requested authentication, disconnecting`),n.removeRelay(t.url)}}async function signAndAuth(n,e,t,r,s,o){try{await n.sign(t),s(n)}catch(a){r==null||r(`Failed to publish auth event to relay ${e.url}`,a),o(n)}}function signIn({ndk:n,signer:e,debug:t}={}){return t??(t=createDebug5("ndk:auth-policies:signIn")),async(r,s)=>{t==null||t(`Relay ${r.url} requested authentication, signing in`);const o=new NDKEvent(n);return o.kind=22242,o.tags=[["relay",r.url],["challenge",s]],e??(e=n==null?void 0:n.signer),new Promise(async(a,u)=>{e?await signAndAuth(o,r,e,t,a,u):n==null||n.once("signer:ready",async c=>{await signAndAuth(o,r,c,t,a,u)})})}}var NDKRelayAuthPolicies={disconnect,signIn},NDKNip07Signer=class Nt{constructor(e=1e3,t){g(this,"_userPromise");g(this,"encryptionQueue",[]);g(this,"encryptionProcessing",!1);g(this,"debug");g(this,"waitTimeout");g(this,"_pubkey");g(this,"ndk");g(this,"_user");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(){var r;await this.waitForExtension();const e=await((r=window.nostr)==null?void 0:r.getPublicKey());if(!e)throw new Error("User rejected access");this._pubkey=e;let t;return this.ndk?t=this.ndk.getUser({pubkey:e}):t=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){var r;await this.waitForExtension();const t=await((r=window.nostr)==null?void 0:r.signEvent(e));if(!t)throw new Error("Failed to sign event");return t.sig}async relays(e){var s,o;await this.waitForExtension();const t=await((o=(s=window.nostr)==null?void 0:s.getRelays)==null?void 0:o.call(s))||{},r=[];for(const a of Object.keys(t))t[a].read&&t[a].write&&r.push(a);return r.map(a=>new NDKRelay(a,e==null?void 0:e.relayAuthDefaultPolicy,e))}async encryptionEnabled(e){var r,s;const t=[];return(!e||e==="nip04")&&((r=window.nostr)!=null&&r.nip04)&&t.push("nip04"),(!e||e==="nip44")&&((s=window.nostr)!=null&&s.nip44)&&t.push("nip44"),t}async encrypt(e,t,r="nip04"){if(!await this.encryptionEnabled(r))throw new Error(`${r}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(r,"encrypt",s,t)}async decrypt(e,t,r="nip04"){if(!await this.encryptionEnabled(r))throw new Error(`${r}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(r,"decrypt",s,t)}async queueEncryption(e,t,r,s){return new Promise((o,a)=>{this.encryptionQueue.push({scheme:e,method:t,counterpartyHexpubkey:r,value:s,resolve:o,reject:a}),this.encryptionProcessing||this.processEncryptionQueue()})}async processEncryptionQueue(e,t=0){var h,f;if(!e&&this.encryptionQueue.length===0){this.encryptionProcessing=!1;return}this.encryptionProcessing=!0;const r=e||this.encryptionQueue.shift();if(!r){this.encryptionProcessing=!1;return}const{scheme:s,method:o,counterpartyHexpubkey:a,value:u,resolve:c,reject:l}=r;this.debug("Processing encryption queue item",{method:o,counterpartyHexpubkey:a,value:u});try{const p=await((f=(h=window.nostr)==null?void 0:h[s])==null?void 0:f[o](a,u));if(!p)throw new Error("Failed to encrypt/decrypt");c(p)}catch(p){const b=p instanceof Error?p.message:String(p);if(b.includes("call already executing")&&t<5){this.debug("Retrying encryption queue item",{method:o,counterpartyHexpubkey:a,value:u,retries:t}),setTimeout(()=>{this.processEncryptionQueue(r,t+1)},50*t);return}l(p instanceof Error?p:new Error(b))}this.processEncryptionQueue()}waitForExtension(){return new Promise((e,t)=>{if(window.nostr){e();return}let r;const s=setInterval(()=>{window.nostr&&(clearTimeout(r),clearInterval(s),e())},100);r=setTimeout(()=>{clearInterval(s),t(new Error("NIP-07 extension not available"))},this.waitTimeout)})}toPayload(){return JSON.stringify({type:"nip07",payload:""})}static async fromPayload(e,t){const r=JSON.parse(e);if(r.type!=="nip07")throw new Error(`Invalid payload type: expected 'nip07', got ${r.type}`);return new Nt(void 0,t)}},NDKNostrRpc=class extends lib$1.EventEmitter{constructor(e,t,r,s){super();g(this,"ndk");g(this,"signer");g(this,"relaySet");g(this,"debug");g(this,"encryptionType","nip04");g(this,"pool");if(this.ndk=e,this.signer=t,s){this.pool=new NDKPool(s,[],e,{debug:r.extend("rpc-pool"),name:"Nostr RPC"}),this.relaySet=new NDKRelaySet(new Set,e,this.pool);for(const o of s){const a=this.pool.getRelay(o,!1,!1);a.authPolicy=NDKRelayAuthPolicies.signIn({ndk:e,signer:t,debug:r}),this.relaySet.addRelay(a),a.connect()}}this.debug=r.extend("rpc")}subscribe(e){const t=this.ndk.subscribe(e,{closeOnEose:!1,groupable:!1,cacheUsage:"ONLY_RELAY",pool:this.pool,relaySet:this.relaySet},!1);return t.on("event",async r=>{try{const s=await this.parseEvent(r);s.method?this.emit("request",s):this.emit(`response-${s.id}`,s)}catch(s){this.debug("error parsing event",s,r.rawEvent())}}),new Promise(r=>{t.on("eose",()=>{this.debug("eosed"),r(t)}),t.start()})}async parseEvent(e){this.encryptionType==="nip44"&&e.content.includes("?iv=")?this.encryptionType="nip04":this.encryptionType==="nip04"&&!e.content.includes("?iv=")&&(this.encryptionType="nip44");const t=this.ndk.getUser({pubkey:e.pubkey});t.ndk=this.ndk;let r;try{r=await this.signer.decrypt(t,e.content,this.encryptionType)}catch{const f=this.encryptionType==="nip04"?"nip44":"nip04";r=await this.signer.decrypt(t,e.content,f),this.encryptionType=f}const s=JSON.parse(r),{id:o,method:a,params:u,result:c,error:l}=s;return a?{id:o,pubkey:e.pubkey,method:a,params:u,event:e}:{id:o,result:c,error:l,event:e}}async sendResponse(e,t,r,s=24133,o){const a={id:e,result:r};o&&(a.error=o);const u=await this.signer.user(),c=this.ndk.getUser({pubkey:t}),l=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(a),tags:[["p",t]],pubkey:u.pubkey});l.content=await this.signer.encrypt(c,l.content,this.encryptionType),await l.sign(this.signer),await l.publish(this.relaySet)}async sendRequest(e,t,r=[],s=24133,o){const a=Math.random().toString(36).substring(7),u=await this.signer.user(),c=this.ndk.getUser({pubkey:e}),l={id:a,method:t,params:r},h=new Promise(()=>{const p=b=>{b.result==="auth_url"?(this.once(`response-${a}`,p),this.emit("authUrl",b.error)):o&&o(b)};this.once(`response-${a}`,p)}),f=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(l),tags:[["p",e]],pubkey:u.pubkey});return f.content=await this.signer.encrypt(c,f.content,this.encryptionType),await f.sign(this.signer),await f.publish(this.relaySet),h}},signerRegistry=new Map;signerRegistry.set("private-key",NDKPrivateKeySigner),signerRegistry.set("nip07",NDKNip07Signer),signerRegistry.set("nip46",NDKNip46Signer);async function ndkSignerFromPayload(n,e){let t;try{t=JSON.parse(n)}catch(s){throw new Error(`Failed to parse signer payload: ${s instanceof Error?s.message:String(s)}`)}const r=signerRegistry.get(t.type);if(!r)throw new Error(`Unknown signer type: ${t.type}`);try{return await r.fromPayload(n,e)}catch(s){const o=s instanceof Error?s.message:String(s);throw new Error(`Failed to deserialize signer type ${t.type}: ${o}`)}}var NDKNip46Signer=class ot extends lib$1.EventEmitter{constructor(t,r,s){super();g(this,"ndk");g(this,"_user");g(this,"bunkerPubkey");g(this,"userPubkey");g(this,"secret");g(this,"localSigner");g(this,"nip05");g(this,"rpc");g(this,"debug");g(this,"relayUrls");g(this,"subscription");this.ndk=t,this.debug=t.debug.extend("nip46:signer"),r.startsWith("bunker://")?this.connectionTokenInit(r):this.nip05Init(r),s?this.localSigner=s:this.localSigner=NDKPrivateKeySigner.generate(),this.rpc=new NDKNostrRpc(this.ndk,this.localSigner,this.debug,this.relayUrls)}get pubkey(){if(!this.userPubkey)throw new Error("Not ready");return this.userPubkey}connectionTokenInit(t){const r=new URL(t),s=r.hostname||r.pathname.replace(/^\/\//,""),o=r.searchParams.get("pubkey"),a=r.searchParams.getAll("relay"),u=r.searchParams.get("secret");this.bunkerPubkey=s,this.userPubkey=o,this.relayUrls=a,this.secret=u}nip05Init(t){this.nip05=t}async startListening(){if(this.subscription)return;const t=await this.localSigner.user();if(!t)throw new Error("Local signer not ready");this.subscription=await this.rpc.subscribe({kinds:[24133],"#p":[t.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 blockUntilReady(){if(this.nip05&&!this.userPubkey){const t=await NDKUser.fromNip05(this.nip05,this.ndk);t&&(this._user=t,this.userPubkey=t.pubkey,this.relayUrls=t.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",(...t)=>{this.emit("authUrl",...t)}),new Promise((t,r)=>{const s=[this.userPubkey??""];if(this.secret&&s.push(this.secret),!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"connect",s,24133,o=>{o.result==="ack"?this.getPublicKey().then(a=>{this.userPubkey=a,this._user=this.ndk.getUser({pubkey:a}),t(this._user)}):r(o.error)})})}async getPublicKey(){return this.userPubkey?this.userPubkey:new Promise((t,r)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,s=>{t(s.result)})})}async encryptionEnabled(t){return t?[t]:Promise.resolve(["nip04","nip44"])}async encrypt(t,r,s="nip04"){return this.encryption(t,r,s,"encrypt")}async decrypt(t,r,s="nip04"){return this.encryption(t,r,s,"decrypt")}async encryption(t,r,s,o){return new Promise((u,c)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,`${s}_${o}`,[t.pubkey,r],24133,l=>{l.error?c(l.error):u(l.result)})})}async sign(t){return new Promise((s,o)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[JSON.stringify(t)],24133,a=>{if(a.error)o(a.error);else{const u=JSON.parse(a.result);s(u.sig)}})})}async createAccount(t,r,s){await this.startListening();const o=[];return t&&o.push(t),r&&o.push(r),s&&o.push(s),new Promise((a,u)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"create_account",o,24133,c=>{if(c.error)u(c.error);else{const l=c.result;a(l)}})})}toPayload(){if(!this.bunkerPubkey||!this.userPubkey)throw new Error("NIP-46 signer is not fully initialized for serialization");const t={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(t)}static async fromPayload(t,r){if(!r)throw new Error("NDK instance is required to deserialize NIP-46 signer");const s=JSON.parse(t);if(s.type!=="nip46")throw new Error(`Invalid payload type: expected 'nip46', got ${s.type}`);const o=s.payload;if(!o||typeof o!="object"||!o.localSignerPayload)throw new Error("Invalid payload content for nip46 signer");const a=await ndkSignerFromPayload(o.localSignerPayload,r);if(!a)throw new Error("Failed to deserialize local signer for NIP-46");let u;return o.nip05?(u=new ot(r,o.nip05,a),u.userPubkey=o.userPubkey,u.bunkerPubkey=o.bunkerPubkey,u.relayUrls=o.relayUrls,u.secret=o.secret):(u=new ot(r,o.userPubkey,a),u.bunkerPubkey=o.bunkerPubkey,u.relayUrls=o.relayUrls,u.secret=o.secret),u}};function dedup(n,e){return n.created_at>e.created_at?n:e}async function getRelayListForUser(n,e){return(await getRelayListForUsers([n],e)).get(n)}async function getRelayListForUsers(n,e,t=!1,r=1e3){var f;const s=e.outboxPool||e.pool,o=new Set;for(const p of s.relays.values())o.add(p);const a=new Map,u=new Map,c=new NDKRelaySet(o,e);if((f=e.cacheAdapter)!=null&&f.locking&&!t){const p=await e.fetchEvents({kinds:[3,10002],authors:Array.from(new Set(n))},{cacheUsage:"ONLY_CACHE",subId:"ndk-relay-list-fetch"});for(const b of p)b.kind===10002&&a.set(b.pubkey,NDKRelayList.from(b));for(const b of p)if(b.kind===3){if(a.has(b.pubkey))continue;const v=relayListFromKind3(e,b);v&&u.set(b.pubkey,v)}n=n.filter(b=>!a.has(b)&&!u.has(b))}if(n.length===0)return a;const l=new Map,h=new Map;return new Promise(p=>{(async()=>{const v={closeOnEose:!0,pool:s,groupable:!0,subId:"ndk-relay-list-fetch",addSinceFromCache:!0,relaySet:c};c&&(v.relaySet=c),e.subscribe({kinds:[3,10002],authors:n},v,{onEvent:m=>{if(m.kind===10002){const y=l.get(m.pubkey);if(y&&y.created_at>m.created_at)return;l.set(m.pubkey,m)}else if(m.kind===3){const y=h.get(m.pubkey);if(y&&y.created_at>m.created_at)return;h.set(m.pubkey,m)}},onEose:()=>{for(const m of l.values())a.set(m.pubkey,NDKRelayList.from(m));for(const m of n){if(a.has(m))continue;const y=h.get(m);if(!y)continue;const w=relayListFromKind3(e,y);w&&a.set(m,w)}p(a)}}),setTimeout(()=>{p(a)},r)})()})}var OutboxItem=class{constructor(n){g(this,"type");g(this,"relayUrlScores");g(this,"readRelays");g(this,"writeRelays");this.type=n,this.relayUrlScores=new Map,this.readRelays=new Set,this.writeRelays=new Set}},OutboxTracker=class extends lib$1.EventEmitter{constructor(e){super();g(this,"data");g(this,"ndk");g(this,"debug");this.ndk=e,this.debug=e.debug.extend("outbox-tracker"),this.data=new dist.LRUCache({maxSize:1e5,entryExpirationTimeInMS:2*60*1e3})}async trackUsers(e,t=!1){const r=[];for(let s=0;s<e.length;s+=400){const a=e.slice(s,s+400).map(u=>getKeyFromItem(u)).filter(u=>!this.data.has(u));if(a.length!==0){for(const u of a)this.data.set(u,new OutboxItem("user"));r.push(new Promise(u=>{getRelayListForUsers(a,this.ndk,t).then(c=>{for(const[l,h]of c){let f=this.data.get(l);if(f??(f=new OutboxItem("user")),h){f.readRelays=new Set(normalize(h.readRelayUrls)),f.writeRelays=new Set(normalize(h.writeRelayUrls));for(const p of f.readRelays)this.ndk.pool.blacklistRelayUrls.has(p)&&f.readRelays.delete(p);for(const p of f.writeRelays)this.ndk.pool.blacklistRelayUrls.has(p)&&f.writeRelays.delete(p);this.data.set(l,f)}}}).finally(u)}))}}return Promise.all(r)}track(e,t,r=!0){const s=getKeyFromItem(e);t??(t=getTypeFromItem(e));let o=this.data.get(s);return o||(o=new OutboxItem(t),e instanceof NDKUser&&this.trackUsers([e])),o}};function getKeyFromItem(n){return n instanceof NDKUser?n.pubkey:n}function getTypeFromItem(n){return n instanceof NDKUser?"user":"kind"}function correctRelaySet(n,e){const t=e.connectedRelays();if(!Array.from(n.relays).some(s=>t.map(o=>o.url).includes(s.url)))for(const s of t)n.addRelay(s);if(t.length===0)for(const s of e.relays.values())n.addRelay(s);return n}var NDKSubscriptionManager=class{constructor(){g(this,"subscriptions");g(this,"seenEvents",new Map);this.subscriptions=new Map}add(n){this.subscriptions.set(n.internalId,n),n.onStopped,n.onStopped=()=>{this.subscriptions.delete(n.internalId)},n.on("close",()=>{this.subscriptions.delete(n.internalId)})}seenEvent(n,e){const t=this.seenEvents.get(n)||[];t.push(e),this.seenEvents.set(n,t)}dispatchEvent(n,e,t=!1){e&&this.seenEvent(n.id,e);const r=this.subscriptions.values(),s=[];for(const o of r)matchFilters(o.filters,n)&&s.push(o);for(const o of s)o.eventReceived(n,e,!1,t)}},debug6=createDebug5("ndk:active-user");async function getUserRelayList(n){if(!this.autoConnectUserRelays)return;const e=await getRelayListForUser(n.pubkey,this);if(e){for(const t of e.relays){let r=this.pool.relays.get(t);r||(r=new NDKRelay(t,this.relayAuthDefaultPolicy,this),this.pool.addRelay(r))}return e}}async function setActiveUser(n){const e=this.outboxPool||this.pool;e.connectedRelays.length>0?setActiveUserConnected.call(this,n):e.once("connect",()=>{setActiveUserConnected.call(this,n)})}async function setActiveUserConnected(n){var o;const e=await getUserRelayList.call(this,n),t=[{kinds:[10006],authors:[n.pubkey]}];this.autoFetchUserMutelist&&((o=t[0].kinds)==null||o.push(1e4));const r=new Map,s=e?e.relaySet:void 0;this.subscribe(t,{subId:"active-user-settings",closeOnEose:!0,relaySet:s},{onEvent:a=>{const u=r.get(a.kind);u&&u.created_at>=a.created_at||r.set(a.kind,a)},onEose:()=>{for(const a of r.values())processEvent.call(this,a)}})}async function processEvent(n){n.kind===10006?processBlockRelayList.call(this,n):n.kind===1e4&&processMuteList.call(this,n)}function processBlockRelayList(n){const e=lists_default.from(n);for(const t of e.items)this.pool.blacklistRelayUrls.add(t[0]);debug6("Added %d relays to relay blacklist",e.items.length)}function processMuteList(n){const e=lists_default.from(n);for(const t of e.items)this.mutedIds.set(t[1],t[0]);debug6("Added %d users to mute list",e.items.length)}function getEntity(n){try{const e=nip19_exports.decode(n);return e.type==="npub"?npub(this,e.data):e.type==="nprofile"?nprofile(this,e.data):e}catch{return null}}function npub(n,e){return n.getUser({pubkey:e})}function nprofile(n,e){const t=n.getUser({pubkey:e.pubkey});return e.relays&&(t.relayUrls=e.relays),t}function isValidHint(n){if(!n||n==="")return!1;try{return new URL(n),!0}catch{return!1}}async function fetchEventFromTag(n,e,t,r={type:"timeout"}){const s=this.debug.extend("fetch-event-from-tag"),[o,a,u]=n;t={},s("fetching event from tag",n,t,r);const c=getRelaysForSync(this,e.pubkey);if(c&&c.size>0){s("fetching event from author relays %o",Array.from(c));const m=NDKRelaySet.fromRelayUrls(Array.from(c),this),y=await this.fetchEvent(a,t,m);if(y)return y}else s("no author relays found for %s",e.pubkey,e);const l=calculateRelaySetsFromFilters(this,[{ids:[a]}],this.pool);s("fetching event without relay hint",l);const h=await this.fetchEvent(a,t);if(h)return h;if(u&&u!==""){const m=await this.fetchEvent(a,t,this.pool.getRelay(u,!0,!0,[{ids:[a]}]));if(m)return m}let f;const p=isValidHint(u)?this.pool.getRelay(u,!1,!0,[{ids:[a]}]):void 0,b=new Promise(m=>{this.fetchEvent(a,t,p).then(m)});if(!isValidHint(u)||r.type==="none")return b;const v=new Promise(async m=>{const y=r.relaySet,w=r.timeout??1500,x=new Promise(k=>setTimeout(k,w));if(r.type==="timeout"&&await x,f)m(f);else{s("fallback fetch triggered");const k=await this.fetchEvent(a,t,y);m(k)}});switch(r.type){case"timeout":return Promise.race([b,v]);case"eose":return f=await b,f||v}}var Queue=class{constructor(n,e){g(this,"queue",[]);g(this,"maxConcurrency");g(this,"processing",new Set);g(this,"promises",new Map);this.maxConcurrency=e}add(n){if(this.promises.has(n.id))return this.promises.get(n.id);const e=new Promise((t,r)=>{this.queue.push({...n,func:()=>n.func().then(s=>(t(s),s),s=>{throw r(s),s})}),this.process()});return this.promises.set(n.id,e),e.finally(()=>{this.promises.delete(n.id),this.processing.delete(n.id),this.process()}),e}process(){if(this.processing.size>=this.maxConcurrency||this.queue.length===0)return;const n=this.queue.shift();!n||this.processing.has(n.id)||(this.processing.add(n.id),n.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/"],DEFAULT_BLACKLISTED_RELAYS=["wss://brb.io/","wss://nostr.mutinywallet.com/"],NDK=class extends lib$1.EventEmitter{constructor(e={}){super();g(this,"_explicitRelayUrls");g(this,"blacklistRelayUrls");g(this,"pool");g(this,"outboxPool");g(this,"_signer");g(this,"_activeUser");g(this,"cacheAdapter");g(this,"debug");g(this,"devWriteRelaySet");g(this,"outboxTracker");g(this,"mutedIds");g(this,"clientName");g(this,"clientNip89");g(this,"queuesZapConfig");g(this,"queuesNip05");g(this,"asyncSigVerification",!1);g(this,"initialValidationRatio",1);g(this,"lowestValidationRatio",1);g(this,"validationRatioFn");g(this,"subManager");g(this,"publishingFailureHandled",!1);g(this,"pools",[]);g(this,"relayAuthDefaultPolicy");g(this,"httpFetch");g(this,"netDebug");g(this,"autoConnectUserRelays",!0);g(this,"autoFetchUserMutelist",!0);g(this,"walletConfig");g(this,"fetchEventFromTag",fetchEventFromTag.bind(this));g(this,"getEntity",getEntity.bind(this));this.debug=e.debug||createDebug5("ndk"),this.netDebug=e.netDebug,this._explicitRelayUrls=e.explicitRelayUrls||[],this.blacklistRelayUrls=e.blacklistRelayUrls||DEFAULT_BLACKLISTED_RELAYS,this.subManager=new NDKSubscriptionManager,this.pool=new NDKPool(e.explicitRelayUrls||[],[],this),this.pool.name="Main",this.pool.on("relay:auth",async(t,r)=>{this.relayAuthDefaultPolicy&&await this.relayAuthDefaultPolicy(t,r)}),this.autoConnectUserRelays=e.autoConnectUserRelays??!0,this.autoFetchUserMutelist=e.autoFetchUserMutelist??!0,this.clientName=e.clientName,this.clientNip89=e.clientNip89,this.relayAuthDefaultPolicy=e.relayAuthDefaultPolicy,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.signer=e.signer,this.cacheAdapter=e.cacheAdapter,this.mutedIds=e.mutedIds||new Map,e.devWriteRelayUrls&&(this.devWriteRelaySet=NDKRelaySet.fromRelayUrls(e.devWriteRelayUrls,this)),this.queuesZapConfig=new Queue("zaps",3),this.queuesNip05=new Queue("nip05",10),this.signatureVerificationWorker=e.signatureVerificationWorker,this.initialValidationRatio=e.initialValidationRatio||1,this.lowestValidationRatio=e.lowestValidationRatio||1;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.asyncSigVerification=!!e,e&&signatureVerificationInit(e)}addExplicitRelay(e,t,r=!0){var o;let s;return typeof e=="string"?s=new NDKRelay(e,t,this):s=e,this.pool.addRelay(s,r),(o=this.explicitRelayUrls)==null||o.push(s.url),s}toJSON(){return{relayCount:this.pool.relays.size}.toString()}get activeUser(){return this._activeUser}set activeUser(e){var r;const t=((r=this._activeUser)==null?void 0:r.pubkey)!==(e==null?void 0:e.pubkey);this._activeUser=e,e&&t?setActiveUser.call(this,e):e||(this.mutedIds=new Map)}get signer(){return this._signer}set signer(e){this._signer=e,e&&this.emit("signer:ready",e),e==null||e.user().then(t=>{t.ndk=this,this.activeUser=t})}async connect(e){var r,s;this._signer&&this.autoConnectUserRelays&&(this.debug("Attempting to connect to user relays specified by signer %o",await((s=(r=this._signer).relays)==null?void 0:s.call(r,this))),this._signer.relays&&(await this._signer.relays(this)).forEach(a=>this.pool.addRelay(a)));const t=[this.pool.connect(e)];return this.outboxPool&&t.push(this.outboxPool.connect(e)),this.debug("Connecting to relays %o",{timeoutMs:e}),Promise.allSettled(t).then(()=>{})}getUser(e){const t=new NDKUser(e);return t.ndk=this,t}async getUserFromNip05(e,t=!1){return NDKUser.fromNip05(e,this,t)}subscribe(e,t,r=!0){var a;const s=new NDKSubscription(this,e,t);this.subManager.add(s);const o=s.pool;if(s.relaySet)for(const u of s.relaySet.relays)o.useTemporaryRelay(u,void 0,s.filters);if(this.outboxPool&&s.hasAuthorsFilter()){const u=s.filters.filter(c=>{var l;return c.authors&&((l=c.authors)==null?void 0:l.length)>0}).flatMap(c=>c.authors);(a=this.outboxTracker)==null||a.trackUsers(u)}if(r){let u;typeof r=="object"&&(r.onEvent&&s.on("event",r.onEvent),r.onEose&&s.on("eose",r.onEose),r.onEvents&&(u=r.onEvents)),setTimeout(()=>{const c=s.start(!u);c&&c.length>0&&u&&u(c)},0)}return s}async publish(e,t,r){return this.debug("Deprecated: Use `event.publish()` instead"),e.publish(t,r)}fetchEventSync(e){if(!this.cacheAdapter)throw new Error("Cache adapter not set");let t;typeof e=="string"?t=[filterFromId(e)]:t=e;const r=new NDKSubscription(this,t),s=this.cacheAdapter.query(r);if(s instanceof Promise)throw new Error("Cache adapter is async");return s.map(o=>(o.ndk=this,o))}async fetchEvent(e,t,r){let s,o;if(r instanceof NDKRelay?o=new NDKRelaySet(new Set([r]),this):r instanceof NDKRelaySet&&(o=r),!r&&typeof e=="string"&&!isNip33AValue(e)){const a=relaysFromBech32(e,this);a.length>0&&(o=new NDKRelaySet(new Set(a),this),o=correctRelaySet(o,this.pool))}if(typeof e=="string"?s=[filterFromId(e)]:Array.isArray(e)?s=e:s=[e],s.length===0)throw new Error(`Invalid filter: ${JSON.stringify(e)}`);return new Promise(a=>{let u=null;const c={...t||{},closeOnEose:!0};o&&(c.relaySet=o);const l=this.subscribe(s,c,!1),h=setTimeout(()=>{l.stop(),a(u)},1e4);l.on("event",f=>{f.ndk=this,f.isReplaceable()?(!u||u.created_at<f.created_at)&&(u=f):(clearTimeout(h),a(f))}),l.on("eose",()=>{clearTimeout(h),a(u)}),l.start()})}async fetchEvents(e,t,r){return new Promise(s=>{const o=new Map,a={...t||{},closeOnEose:!0};r&&(a.relaySet=r);const u=this.subscribe(e,a,!1),c=l=>{let h;l instanceof NDKEvent?h=l:h=new NDKEvent(void 0,l);const f=h.deduplicationKey(),p=o.get(f);p&&(h=dedup(p,h)),h.ndk=this,o.set(f,h)};u.on("event",c),u.on("eose",()=>{s(new Set(o.values()))}),u.start()})}assertSigner(){if(!this.signer)throw this.emit("signer:required"),new Error("Signer required")}set wallet(e){var t,r;if(!e){this.walletConfig=void 0;return}this.walletConfig??(this.walletConfig={}),this.walletConfig.lnPay=(t=e==null?void 0:e.lnPay)==null?void 0:t.bind(e),this.walletConfig.cashuPay=(r=e==null?void 0:e.cashuPay)==null?void 0:r.bind(e)}};createDebug5("ndk:zapper:ln"),createDebug5("ndk:zapper");const index=Object.freeze(Object.defineProperty({__proto__:null,BECH32_REGEX,NDKArticle,NDKCashuMintList,NDKCashuToken,NDKEvent,NDKHighlight,NDKImage,NDKKind,NDKList,NDKNip07Signer,NDKNip46Signer,NDKNostrRpc,NDKNutzap,NDKPool,NDKPrivateKeySigner,NDKPublishError,NDKRelay,NDKRelayAuthPolicies,NDKRelayList,NDKRelaySet,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKStory,NDKStorySticker,NDKSubscription,NDKSubscriptionTier,NDKUser,NDKVideo,NDKWiki,NIP33_A_REGEX,calculateRelaySetFromEvent,default:NDK,defaultOpts:defaultOpts$1,deserialize,eventHasETagMarkers,filterFingerprint,filterFromId,generateContentTags,generateHashtags,getRelayListForUser,getRelayListForUsers,getReplyTag,getRootTag,imetaTagToTag,isNip33AValue,mapImetaTag,mergeFilters,mergeTags,ndkSignerFromPayload,newAmount,normalize,normalizeRelayUrl,normalizeUrl,parseTagToSubscriptionAmount,possibleIntervalFrequencies,profileFromEvent,proofsTotalBalance,queryFullyFilled,relayListFromKind3,relaysFromBech32,serialize,serializeProfile,signerRegistry,strToDimension,strToPosition,tryNormalizeRelayUrl,wrapEvent},Symbol.toStringTag,{value:"Module"})),DEFAULT_RELAYS=["wss://relay.damus.io","wss://nostr.wine","wss://relay.nostr.net","wss://relay.nostr.band","wss://nos.lol","wss://nostr-pub.wellorder.net","wss://relay.getalby.com","wss://relay.primal.net"],MILLISATS_PER_SAT=1e3,DEFAULT_PROFILE_IMAGE="./assets/default_dp.png",Ie=class Ie{constructor(){g(this,"ndk");g(this,"isConnected",!1);this.ndk=new NDK}static getInstance(){return Ie.instance||(Ie.instance=new Ie),Ie.instance}async connectToNostr(e=[...DEFAULT_RELAYS]){const t=e.filter(r=>!this.getRelays().includes(r));if(this.isConnected&&t.length){t.forEach(r=>this.ndk.addExplicitRelay(r));return}this.ndk.explicitRelayUrls=e,await this.ndk.connect(),this.isConnected=!0}getRelays(){return this.ndk.explicitRelayUrls||DEFAULT_RELAYS}async resolveNDKUser(e){return e.npub?this.ndk.getUser({npub:e.npub}):e.nip05?await this.ndk.getUserFromNip05(e.nip05)??null:e.pubkey?this.ndk.getUser({pubkey:e.pubkey}):null}async resolveNDKEvent(e){return e.hex?this.ndk.fetchEvent(e.hex):null}async getZapCount(e){const t=await this.resolveNDKUser(e);return t?this.fetchZaps(t):0}async getProfile(e){if(!e)return null;await e.fetchProfile();const t=e.profile;return t&&(t.picture===void 0||t.picture===null)&&(t.picture=DEFAULT_PROFILE_IMAGE),t}async getPost(e){const t=await this.ndk.fetchEvent(e);if(!t)return null;const r=t.getMatchingTags("e");if(r.length>0){const o=r.map(a=>a[1]);await this.ndk.fetchEvents({ids:o})}const s=t.getMatchingTags("a");for(const o of s){const a=o[1],u=o[2];a!=null&&a.startsWith("video/")&&u&&(t.content=t.content+`
75
+ })`;{var funcFactory=eval(funcFactoryCode);return funcFactory(collection)}}exports.bakeCollectionVariadic=bakeCollectionVariadic})(bakeCollection);var __spreadArray$1=commonjsGlobal&&commonjsGlobal.__spreadArray||function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))};Object.defineProperty(taskCollection,"__esModule",{value:!0}),taskCollection.TaskCollection=void 0;var utils_1$1=utils$3,bake_collection_1=bakeCollection;function push_norebuild(n,e){var t=this.length;if(t>1)if(e){var r;(r=this._tasks).push.apply(r,arguments),this.length+=arguments.length}else this._tasks.push(n),this.length++;else if(e){if(t===1){var s=Array(1+arguments.length);s.push(s),s.push.apply(s,arguments),this._tasks=s}else{var s=Array(arguments.length);s.push.apply(s,arguments),this._tasks=s}this.length+=arguments.length}else t===1?this._tasks=[this._tasks,n]:this._tasks=n,this.length++}function push_rebuild(n,e){var t=this.length;if(t>1)if(e){var r;(r=this._tasks).push.apply(r,arguments),this.length+=arguments.length}else this._tasks.push(n),this.length++;else if(e){if(t===1){var s=Array(1+arguments.length);s.push(s),s.push.apply(s,arguments),this._tasks=s}else{var s=Array(arguments.length);s.push.apply(s,arguments),this._tasks=s}this.length+=arguments.length}else t===1?this._tasks=[this._tasks,n]:this._tasks=n,this.length++;this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function removeLast_norebuild(n){this.length!==0&&(this.length===1?this._tasks===n&&(this.length=0):((0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(n)),this._tasks.length===1?(this._tasks=this._tasks[0],this.length=1):this.length=this._tasks.length))}function removeLast_rebuild(n){if(this.length!==0){if(this.length===1)if(this._tasks===n&&(this.length=0),this.firstEmitBuildStrategy){this.call=bake_collection_1.BAKED_EMPTY_FUNC;return}else{this.rebuild();return}else(0,utils_1$1._fast_remove_single)(this._tasks,this._tasks.lastIndexOf(n)),this._tasks.length===1?(this._tasks=this._tasks[0],this.length=1):this.length=this._tasks.length;this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}}function insert_norebuild(n){for(var e,t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.length===0?(this._tasks=t,this.length=1):this.length===1?(t.unshift(this._tasks),this._tasks=t,this.length=this._tasks.length):((e=this._tasks).splice.apply(e,__spreadArray$1([n,0],t,!1)),this.length=this._tasks.length)}function insert_rebuild(n){for(var e,t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];this.length===0?(this._tasks=t,this.length=1):this.length===1?(t.unshift(this._tasks),this._tasks=t,this.length=this._tasks.length):((e=this._tasks).splice.apply(e,__spreadArray$1([n,0],t,!1)),this.length=this._tasks.length),this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild()}function rebuild_noawait(){this.length===0?this.call=bake_collection_1.BAKED_EMPTY_FUNC:this.length===1?this.call=this._tasks:this.call=(0,bake_collection_1.bakeCollection)(this._tasks,this.argsNum)}function rebuild_await(){this.length===0?this.call=bake_collection_1.BAKED_EMPTY_FUNC:this.length===1?this.call=this._tasks:this.call=(0,bake_collection_1.bakeCollectionAwait)(this._tasks,this.argsNum)}function rebuild_on_first_call(){this.rebuild(),this.call.apply(void 0,arguments)}var TaskCollection=function(){function n(e,t,r,s){t===void 0&&(t=!0),r===void 0&&(r=null),s===void 0&&(s=!1),this.awaitTasks=s,this.call=bake_collection_1.BAKED_EMPTY_FUNC,this.argsNum=e,this.firstEmitBuildStrategy=!0,s?this.rebuild=rebuild_await.bind(this):this.rebuild=rebuild_noawait.bind(this),this.setAutoRebuild(t),r?typeof r=="function"?(this._tasks=r,this.length=1):(this._tasks=r,this.length=r.length):(this._tasks=null,this.length=0),t&&this.rebuild()}return n}();taskCollection.TaskCollection=TaskCollection;function fastClear(){this._tasks=null,this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC}function clear(){this._tasks=null,this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC}function growArgsNum(n){this.argsNum<n&&(this.argsNum=n,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}function setAutoRebuild(n){n?(this.push=push_rebuild.bind(this),this.insert=insert_rebuild.bind(this),this.removeLast=removeLast_rebuild.bind(this)):(this.push=push_norebuild.bind(this),this.insert=insert_norebuild.bind(this),this.removeLast=removeLast_norebuild.bind(this))}function tasksAsArray(){return this.length===0?[]:this.length===1?[this._tasks]:this._tasks}function setTasks(n){n.length===0?(this.length=0,this.call=bake_collection_1.BAKED_EMPTY_FUNC):n.length===1?(this.length=1,this.call=n[0],this._tasks=n[0]):(this.length=n.length,this._tasks=n,this.firstEmitBuildStrategy?this.call=rebuild_on_first_call:this.rebuild())}TaskCollection.prototype.fastClear=fastClear,TaskCollection.prototype.clear=clear,TaskCollection.prototype.growArgsNum=growArgsNum,TaskCollection.prototype.setAutoRebuild=setAutoRebuild,TaskCollection.prototype.tasksAsArray=tasksAsArray,TaskCollection.prototype.setTasks=setTasks,function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,u)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(taskCollection,n)}(taskCollection$1);var utils$2={};Object.defineProperty(utils$2,"__esModule",{value:!0}),utils$2.nullObj=void 0;function nullObj(){var n={};return n.__proto__=null,n}utils$2.nullObj=nullObj;var __spreadArray=commonjsGlobal&&commonjsGlobal.__spreadArray||function(n,e,t){if(t||arguments.length===2)for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return n.concat(o||Array.prototype.slice.call(e))};Object.defineProperty(ee,"__esModule",{value:!0}),ee.EventEmitter=void 0;var task_collection_1=taskCollection$1,utils_1=utils$3,utils_2=utils$2;function emit(n,e,t,r,s,o){var a=this.events[n];if(a){if(a.length===0)return!1;if(a.argsNum<6)a.call(e,t,r,s,o);else{for(var u=new Array(a.argsNum),c=0,l=u.length;c<l;++c)u[c]=arguments[c+1];a.call.apply(void 0,u)}return!0}return!1}function emitHasOnce(n,e,t,r,s,o){var a=this.events[n],u;if(a!==void 0){if(a.length===0)return!1;if(a.argsNum<6)a.call(e,t,r,s,o);else{u=new Array(a.argsNum);for(var c=0,l=u.length;c<l;++c)u[c]=arguments[c+1];a.call.apply(void 0,u)}}var h=this.onceEvents[n];if(h){if(typeof h=="function")if(this.onceEvents[n]=void 0,arguments.length<6)h(e,t,r,s,o);else{if(u===void 0){u=new Array(arguments.length-1);for(var c=0,l=u.length;c<l;++c)u[c]=arguments[c+1]}h.apply(void 0,u)}else{var f=h;if(this.onceEvents[n]=void 0,arguments.length<6)for(var c=0;c<f.length;++c)f[c](e,t,r,s,o);else{if(u===void 0){u=new Array(arguments.length-1);for(var c=0,l=u.length;c<l;++c)u[c]=arguments[c+1]}for(var c=0;c<f.length;++c)f[c].apply(void 0,u)}}return!0}return a!==void 0}var EventEmitter=function(){function n(){this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set,this.maxListeners=1/0}return Object.defineProperty(n.prototype,"_eventsCount",{get:function(){return this.eventNames().length},enumerable:!1,configurable:!0}),n}();ee.EventEmitter=EventEmitter;function once(n,e){switch(this.emit===emit&&(this.emit=emitHasOnce),typeof this.onceEvents[n]){case"undefined":this.onceEvents[n]=e,typeof n=="symbol"&&this._symbolKeys.add(n);break;case"function":this.onceEvents[n]=[this.onceEvents[n],e];break;case"object":this.onceEvents[n].push(e)}return this}function addListener(n,e,t){if(t===void 0&&(t=e.length),typeof e!="function")throw new TypeError("The listener must be a function");var r=this.events[n];return r?(r.push(e),r.growArgsNum(t),this.maxListeners!==1/0&&this.maxListeners<=r.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" event!'))):(this.events[n]=new task_collection_1.TaskCollection(t,!0,e,!1),typeof n=="symbol"&&this._symbolKeys.add(n)),this}function removeListener(n,e){var t=this.events[n];t&&t.removeLast(e);var r=this.onceEvents[n];return r&&(typeof r=="function"?this.onceEvents[n]=void 0:typeof r=="object"&&(r.length===1&&r[0]===e?this.onceEvents[n]=void 0:(0,utils_1._fast_remove_single)(r,r.lastIndexOf(e)))),this}function addListenerBound(n,e,t,r){t===void 0&&(t=this),r===void 0&&(r=e.length),this.boundFuncs||(this.boundFuncs=new Map);var s=e.bind(t);return this.boundFuncs.set(e,s),this.addListener(n,s,r)}function removeListenerBound(n,e){var t,r,s=(t=this.boundFuncs)===null||t===void 0?void 0:t.get(e);return(r=this.boundFuncs)===null||r===void 0||r.delete(e),this.removeListener(n,s)}function hasListeners(n){return this.events[n]&&!!this.events[n].length}function prependListener(n,e,t){if(t===void 0&&(t=e.length),typeof e!="function")throw new TypeError("The listener must be a function");var r=this.events[n];return!r||!(r instanceof task_collection_1.TaskCollection)?(r=this.events[n]=new task_collection_1.TaskCollection(t,!0,e,!1),typeof n=="symbol"&&this._symbolKeys.add(n)):(r.insert(0,e),r.growArgsNum(t),this.maxListeners!==1/0&&this.maxListeners<=r.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" event!'))),this}function prependOnceListener(n,e){this.emit===emit&&(this.emit=emitHasOnce);var t=this.onceEvents[n];return t?typeof t!="object"?(this.onceEvents[n]=[e,t],typeof n=="symbol"&&this._symbolKeys.add(n)):(t.unshift(e),this.maxListeners!==1/0&&this.maxListeners<=t.length&&console.warn('Maximum event listeners for "'.concat(String(n),'" once event!'))):(this.onceEvents[n]=[e],typeof n=="symbol"&&this._symbolKeys.add(n)),this}function removeAllListeners(n){return n===void 0?(this.events=(0,utils_2.nullObj)(),this.onceEvents=(0,utils_2.nullObj)(),this._symbolKeys=new Set):(this.events[n]=void 0,this.onceEvents[n]=void 0,typeof n=="symbol"&&this._symbolKeys.delete(n)),this}function setMaxListeners(n){return this.maxListeners=n,this}function getMaxListeners(){return this.maxListeners}function listeners(n){return this.emit===emit?this.events[n]?this.events[n].tasksAsArray().slice():[]:this.events[n]&&this.onceEvents[n]?__spreadArray(__spreadArray([],this.events[n].tasksAsArray(),!0),typeof this.onceEvents[n]=="function"?[this.onceEvents[n]]:this.onceEvents[n],!0):this.events[n]?this.events[n].tasksAsArray():this.onceEvents[n]?typeof this.onceEvents[n]=="function"?[this.onceEvents[n]]:this.onceEvents[n]:[]}function eventNames(){var n=this;if(this.emit===emit){var e=Object.keys(this.events);return __spreadArray(__spreadArray([],e,!0),Array.from(this._symbolKeys),!0).filter(function(r){return r in n.events&&n.events[r]&&n.events[r].length})}else{var e=Object.keys(this.events).filter(function(s){return n.events[s]&&n.events[s].length}),t=Object.keys(this.onceEvents).filter(function(s){return n.onceEvents[s]&&n.onceEvents[s].length});return __spreadArray(__spreadArray(__spreadArray([],e,!0),t,!0),Array.from(this._symbolKeys).filter(function(s){return s in n.events&&n.events[s]&&n.events[s].length||s in n.onceEvents&&n.onceEvents[s]&&n.onceEvents[s].length}),!0)}}function listenerCount(n){return this.emit===emit?this.events[n]&&this.events[n].length||0:(this.events[n]&&this.events[n].length||0)+(this.onceEvents[n]&&this.onceEvents[n].length||0)}EventEmitter.prototype.emit=emit,EventEmitter.prototype.on=addListener,EventEmitter.prototype.once=once,EventEmitter.prototype.addListener=addListener,EventEmitter.prototype.removeListener=removeListener,EventEmitter.prototype.addListenerBound=addListenerBound,EventEmitter.prototype.removeListenerBound=removeListenerBound,EventEmitter.prototype.hasListeners=hasListeners,EventEmitter.prototype.prependListener=prependListener,EventEmitter.prototype.prependOnceListener=prependOnceListener,EventEmitter.prototype.off=removeListener,EventEmitter.prototype.removeAllListeners=removeAllListeners,EventEmitter.prototype.setMaxListeners=setMaxListeners,EventEmitter.prototype.getMaxListeners=getMaxListeners,EventEmitter.prototype.listeners=listeners,EventEmitter.prototype.eventNames=eventNames,EventEmitter.prototype.listenerCount=listenerCount,function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,u)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(types,n),t(ee,n)}(lib$1);var browser={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var n=1e3,e=n*60,t=e*60,r=t*24,s=r*7,o=r*365.25;ms=function(h,f){f=f||{};var p=typeof h;if(p==="string"&&h.length>0)return a(h);if(p==="number"&&isFinite(h))return f.long?c(h):u(h);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(h))};function a(h){if(h=String(h),!(h.length>100)){var f=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(h);if(f){var p=parseFloat(f[1]),b=(f[2]||"ms").toLowerCase();switch(b){case"years":case"year":case"yrs":case"yr":case"y":return p*o;case"weeks":case"week":case"w":return p*s;case"days":case"day":case"d":return p*r;case"hours":case"hour":case"hrs":case"hr":case"h":return p*t;case"minutes":case"minute":case"mins":case"min":case"m":return p*e;case"seconds":case"second":case"secs":case"sec":case"s":return p*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return p;default:return}}}}function u(h){var f=Math.abs(h);return f>=r?Math.round(h/r)+"d":f>=t?Math.round(h/t)+"h":f>=e?Math.round(h/e)+"m":f>=n?Math.round(h/n)+"s":h+"ms"}function c(h){var f=Math.abs(h);return f>=r?l(h,f,r,"day"):f>=t?l(h,f,t,"hour"):f>=e?l(h,f,e,"minute"):f>=n?l(h,f,n,"second"):h+" ms"}function l(h,f,p,b){var v=f>=p*1.5;return Math.round(h/p)+" "+b+(v?"s":"")}return ms}function setup(n){t.debug=t,t.default=t,t.coerce=c,t.disable=a,t.enable=s,t.enabled=u,t.humanize=requireMs(),t.destroy=l,Object.keys(n).forEach(h=>{t[h]=n[h]}),t.names=[],t.skips=[],t.formatters={};function e(h){let f=0;for(let p=0;p<h.length;p++)f=(f<<5)-f+h.charCodeAt(p),f|=0;return t.colors[Math.abs(f)%t.colors.length]}t.selectColor=e;function t(h){let f,p=null,b,v;function m(...y){if(!m.enabled)return;const w=m,x=Number(new Date),k=x-(f||x);w.diff=k,w.prev=f,w.curr=x,f=x,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let C=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(R,N)=>{if(R==="%%")return"%";C++;const B=t.formatters[N];if(typeof B=="function"){const O=y[C];R=B.call(w,O),y.splice(C,1),C--}return R}),t.formatArgs.call(w,y),(w.log||t.log).apply(w,y)}return m.namespace=h,m.useColors=t.useColors(),m.color=t.selectColor(h),m.extend=r,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(b!==t.namespaces&&(b=t.namespaces,v=t.enabled(h)),v),set:y=>{p=y}}),typeof t.init=="function"&&t.init(m),m}function r(h,f){const p=t(this.namespace+(typeof f>"u"?":":f)+h);return p.log=this.log,p}function s(h){t.save(h),t.namespaces=h,t.names=[],t.skips=[];const f=(typeof h=="string"?h:"").trim().replace(" ",",").split(",").filter(Boolean);for(const p of f)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function o(h,f){let p=0,b=0,v=-1,m=0;for(;p<h.length;)if(b<f.length&&(f[b]===h[p]||f[b]==="*"))f[b]==="*"?(v=b,m=p,b++):(p++,b++);else if(v!==-1)b=v+1,m++,p=m;else return!1;for(;b<f.length&&f[b]==="*";)b++;return b===f.length}function a(){const h=[...t.names,...t.skips.map(f=>"-"+f)].join(",");return t.enable(""),h}function u(h){for(const f of t.skips)if(o(h,f))return!1;for(const f of t.names)if(o(h,f))return!0;return!1}function c(h){return h instanceof Error?h.stack||h.message:h}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}var common=setup;(function(n,e){e.formatArgs=r,e.save=s,e.load=o,e.useColors=t,e.storage=a(),e.destroy=(()=>{let c=!1;return()=>{c||(c=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function t(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let c;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(c=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(c[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function r(c){if(c[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+c[0]+(this.useColors?"%c ":" ")+"+"+n.exports.humanize(this.diff),!this.useColors)return;const l="color: "+this.color;c.splice(1,0,l,"color: inherit");let h=0,f=0;c[0].replace(/%[a-zA-Z%]/g,p=>{p!=="%%"&&(h++,p==="%c"&&(f=h))}),c.splice(f,0,l)}e.log=console.debug||console.log||(()=>{});function s(c){try{c?e.storage.setItem("debug",c):e.storage.removeItem("debug")}catch{}}function o(){let c;try{c=e.storage.getItem("debug")}catch{}return!c&&typeof process<"u"&&"env"in process&&(c=process.env.DEBUG),c}function a(){try{return localStorage}catch{}}n.exports=common(e);const{formatters:u}=n.exports;u.j=function(c){try{return JSON.stringify(c)}catch(l){return"[UnexpectedJSONParseError]: "+l.message}}})(browser,browser.exports);var browserExports=browser.exports;const createDebug5=getDefaultExportFromCjs(browserExports);function number$2(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bytes$2(n,...e){if(!(n instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function hash$1(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$2(n.outputLen),number$2(n.blockLen)}function exists$1(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function output$1(n,e){bytes$2(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const crypto$3=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a$2=n=>n instanceof Uint8Array,createView$2=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),rotr$2=(n,e)=>n<<32-e|n>>>e,isLE$2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$2)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes$4(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function toBytes$2(n){if(typeof n=="string"&&(n=utf8ToBytes$4(n)),!u8a$2(n))throw new Error(`expected Uint8Array, got ${typeof n}`);return n}function concatBytes$4(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a$2(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}let Hash$2=class{clone(){return this._cloneInto()}};function wrapConstructor$2(n){const e=r=>n().update(toBytes$2(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes$2(n=32){if(crypto$3&&typeof crypto$3.getRandomValues=="function")return crypto$3.getRandomValues(new Uint8Array(n));throw new Error("crypto.getRandomValues must be defined")}function setBigUint64$2(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),u=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,a,r),n.setUint32(e+l,u,r)}let SHA2$1=class extends Hash$2{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView$2(this.buffer)}update(e){exists$1(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes$2(e);const o=e.length;for(let a=0;a<o;){const u=Math.min(s-this.pos,o-a);if(u===s){const c=createView$2(e);for(;s<=o-a;a+=s)this.process(c,a);continue}r.set(e.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){exists$1(this),output$1(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let f=a;f<s;f++)t[f]=0;setBigUint64$2(r,s-8,BigInt(this.length*8),o),this.process(r,0);const u=createView$2(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)u.setUint32(4*f,h[f],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:u}=this;return e.length=s,e.pos=u,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}};const Chi$2=(n,e,t)=>n&e^~n&t,Maj$2=(n,e,t)=>n&e^n&t^e&t,SHA256_K$2=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV$1=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W$2=new Uint32Array(64);let SHA256$2=class extends SHA2$1{constructor(){super(64,32,8,!1),this.A=IV$1[0]|0,this.B=IV$1[1]|0,this.C=IV$1[2]|0,this.D=IV$1[3]|0,this.E=IV$1[4]|0,this.F=IV$1[5]|0,this.G=IV$1[6]|0,this.H=IV$1[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:u,H:c}=this;return[e,t,r,s,o,a,u,c]}set(e,t,r,s,o,a,u,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=u|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)SHA256_W$2[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){const p=SHA256_W$2[f-15],b=SHA256_W$2[f-2],v=rotr$2(p,7)^rotr$2(p,18)^p>>>3,m=rotr$2(b,17)^rotr$2(b,19)^b>>>10;SHA256_W$2[f]=m+SHA256_W$2[f-7]+v+SHA256_W$2[f-16]|0}let{A:r,B:s,C:o,D:a,E:u,F:c,G:l,H:h}=this;for(let f=0;f<64;f++){const p=rotr$2(u,6)^rotr$2(u,11)^rotr$2(u,25),b=h+p+Chi$2(u,c,l)+SHA256_K$2[f]+SHA256_W$2[f]|0,m=(rotr$2(r,2)^rotr$2(r,13)^rotr$2(r,22))+Maj$2(r,s,o)|0;h=l,l=c,c=u,u=a+b|0,a=o,o=s,s=r,r=b+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(r,s,o,a,u,c,l,h)}roundClean(){SHA256_W$2.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};const sha256$2=wrapConstructor$2(()=>new SHA256$2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$9=BigInt(0),_1n$9=BigInt(1),_2n$5=BigInt(2),u8a$1=n=>n instanceof Uint8Array,hexes$3=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$3(n){if(!u8a$1(n))throw new Error("Uint8Array expected");let e="";for(let t=0;t<n.length;t++)e+=hexes$3[n[t]];return e}function numberToHexUnpadded$1(n){const e=n.toString(16);return e.length&1?`0${e}`:e}function hexToNumber$1(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return BigInt(n===""?"0":`0x${n}`)}function hexToBytes$3(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let r=0;r<t.length;r++){const s=r*2,o=n.slice(s,s+2),a=Number.parseInt(o,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[r]=a}return t}function bytesToNumberBE$1(n){return hexToNumber$1(bytesToHex$3(n))}function bytesToNumberLE$1(n){if(!u8a$1(n))throw new Error("Uint8Array expected");return hexToNumber$1(bytesToHex$3(Uint8Array.from(n).reverse()))}function numberToBytesBE$1(n,e){return hexToBytes$3(n.toString(16).padStart(e*2,"0"))}function numberToBytesLE$1(n,e){return numberToBytesBE$1(n,e).reverse()}function numberToVarBytesBE$1(n){return hexToBytes$3(numberToHexUnpadded$1(n))}function ensureBytes$1(n,e,t){let r;if(typeof e=="string")try{r=hexToBytes$3(e)}catch(o){throw new Error(`${n} must be valid hex string, got "${e}". Cause: ${o}`)}else if(u8a$1(e))r=Uint8Array.from(e);else throw new Error(`${n} must be hex string or Uint8Array`);const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(`${n} expected ${t} bytes, got ${s}`);return r}function concatBytes$3(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a$1(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}function equalBytes$2(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function utf8ToBytes$3(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function bitLen$1(n){let e;for(e=0;n>_0n$9;n>>=_1n$9,e+=1);return e}function bitGet$1(n,e){return n>>BigInt(e)&_1n$9}const bitSet$1=(n,e,t)=>n|(t?_1n$9:_0n$9)<<BigInt(e),bitMask$1=n=>(_2n$5<<BigInt(n-1))-_1n$9,u8n$1=n=>new Uint8Array(n),u8fr$1=n=>Uint8Array.from(n);function createHmacDrbg$1(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=u8n$1(n),s=u8n$1(n),o=0;const a=()=>{r.fill(1),s.fill(0),o=0},u=(...f)=>t(s,r,...f),c=(f=u8n$1())=>{s=u(u8fr$1([0]),f),r=u(),f.length!==0&&(s=u(u8fr$1([1]),f),r=u())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){r=u();const b=r.slice();p.push(b),f+=r.length}return concatBytes$3(...p)};return(f,p)=>{a(),c(f);let b;for(;!(b=p(l()));)c();return a(),b}}const validatorFns$1={bigint:n=>typeof n=="bigint",function:n=>typeof n=="function",boolean:n=>typeof n=="boolean",string:n=>typeof n=="string",stringOrUint8Array:n=>typeof n=="string"||n instanceof Uint8Array,isSafeInteger:n=>Number.isSafeInteger(n),array:n=>Array.isArray(n),field:(n,e)=>e.Fp.isValid(n),hash:n=>typeof n=="function"&&Number.isSafeInteger(n.outputLen)};function validateObject$1(n,e,t={}){const r=(s,o,a)=>{const u=validatorFns$1[o];if(typeof u!="function")throw new Error(`Invalid validator "${o}", expected function`);const c=n[s];if(!(a&&c===void 0)&&!u(c,n))throw new Error(`Invalid param ${String(s)}=${c} (${typeof c}), expected ${o}`)};for(const[s,o]of Object.entries(e))r(s,o,!1);for(const[s,o]of Object.entries(t))r(s,o,!0);return n}const ut$1=Object.freeze(Object.defineProperty({__proto__:null,bitGet:bitGet$1,bitLen:bitLen$1,bitMask:bitMask$1,bitSet:bitSet$1,bytesToHex:bytesToHex$3,bytesToNumberBE:bytesToNumberBE$1,bytesToNumberLE:bytesToNumberLE$1,concatBytes:concatBytes$3,createHmacDrbg:createHmacDrbg$1,ensureBytes:ensureBytes$1,equalBytes:equalBytes$2,hexToBytes:hexToBytes$3,hexToNumber:hexToNumber$1,numberToBytesBE:numberToBytesBE$1,numberToBytesLE:numberToBytesLE$1,numberToHexUnpadded:numberToHexUnpadded$1,numberToVarBytesBE:numberToVarBytesBE$1,utf8ToBytes:utf8ToBytes$3,validateObject:validateObject$1},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$8=BigInt(0),_1n$8=BigInt(1),_2n$4=BigInt(2),_3n$3=BigInt(3),_4n$1=BigInt(4),_5n$1=BigInt(5),_8n$1=BigInt(8);BigInt(9),BigInt(16);function mod$1(n,e){const t=n%e;return t>=_0n$8?t:e+t}function pow$1(n,e,t){if(t<=_0n$8||e<_0n$8)throw new Error("Expected power/modulo > 0");if(t===_1n$8)return _0n$8;let r=_1n$8;for(;e>_0n$8;)e&_1n$8&&(r=r*n%t),n=n*n%t,e>>=_1n$8;return r}function pow2$1(n,e,t){let r=n;for(;e-- >_0n$8;)r*=r,r%=t;return r}function invert$1(n,e){if(n===_0n$8||e<=_0n$8)throw new Error(`invert: expected positive integers, got n=${n} mod=${e}`);let t=mod$1(n,e),r=e,s=_0n$8,o=_1n$8;for(;t!==_0n$8;){const u=r/t,c=r%t,l=s-o*u;r=t,t=c,s=o,o=l}if(r!==_1n$8)throw new Error("invert: does not exist");return mod$1(s,e)}function tonelliShanks$1(n){const e=(n-_1n$8)/_2n$4;let t,r,s;for(t=n-_1n$8,r=0;t%_2n$4===_0n$8;t/=_2n$4,r++);for(s=_2n$4;s<n&&pow$1(s,e,n)!==n-_1n$8;s++);if(r===1){const a=(n+_1n$8)/_4n$1;return function(c,l){const h=c.pow(l,a);if(!c.eql(c.sqr(h),l))throw new Error("Cannot find square root");return h}}const o=(t+_1n$8)/_2n$4;return function(u,c){if(u.pow(c,e)===u.neg(u.ONE))throw new Error("Cannot find square root");let l=r,h=u.pow(u.mul(u.ONE,s),t),f=u.pow(c,o),p=u.pow(c,t);for(;!u.eql(p,u.ONE);){if(u.eql(p,u.ZERO))return u.ZERO;let b=1;for(let m=u.sqr(p);b<l&&!u.eql(m,u.ONE);b++)m=u.sqr(m);const v=u.pow(h,_1n$8<<BigInt(l-b-1));h=u.sqr(v),f=u.mul(f,v),p=u.mul(p,h),l=b}return f}}function FpSqrt$1(n){if(n%_4n$1===_3n$3){const e=(n+_1n$8)/_4n$1;return function(r,s){const o=r.pow(s,e);if(!r.eql(r.sqr(o),s))throw new Error("Cannot find square root");return o}}if(n%_8n$1===_5n$1){const e=(n-_5n$1)/_8n$1;return function(r,s){const o=r.mul(s,_2n$4),a=r.pow(o,e),u=r.mul(s,a),c=r.mul(r.mul(u,_2n$4),a),l=r.mul(u,r.sub(c,r.ONE));if(!r.eql(r.sqr(l),s))throw new Error("Cannot find square root");return l}}return tonelliShanks$1(n)}const FIELD_FIELDS$1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField$1(n){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=FIELD_FIELDS$1.reduce((r,s)=>(r[s]="function",r),e);return validateObject$1(n,t)}function FpPow$1(n,e,t){if(t<_0n$8)throw new Error("Expected power > 0");if(t===_0n$8)return n.ONE;if(t===_1n$8)return e;let r=n.ONE,s=e;for(;t>_0n$8;)t&_1n$8&&(r=n.mul(r,s)),s=n.sqr(s),t>>=_1n$8;return r}function FpInvertBatch$1(n,e){const t=new Array(e.length),r=e.reduce((o,a,u)=>n.is0(a)?o:(t[u]=o,n.mul(o,a)),n.ONE),s=n.inv(r);return e.reduceRight((o,a,u)=>n.is0(a)?o:(t[u]=n.mul(o,t[u]),n.mul(o,a)),s),t}function nLength$1(n,e){const t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Field$1(n,e,t=!1,r={}){if(n<=_0n$8)throw new Error(`Expected Field ORDER > 0, got ${n}`);const{nBitLength:s,nByteLength:o}=nLength$1(n,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");const a=FpSqrt$1(n),u=Object.freeze({ORDER:n,BITS:s,BYTES:o,MASK:bitMask$1(s),ZERO:_0n$8,ONE:_1n$8,create:c=>mod$1(c,n),isValid:c=>{if(typeof c!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof c}`);return _0n$8<=c&&c<n},is0:c=>c===_0n$8,isOdd:c=>(c&_1n$8)===_1n$8,neg:c=>mod$1(-c,n),eql:(c,l)=>c===l,sqr:c=>mod$1(c*c,n),add:(c,l)=>mod$1(c+l,n),sub:(c,l)=>mod$1(c-l,n),mul:(c,l)=>mod$1(c*l,n),pow:(c,l)=>FpPow$1(u,c,l),div:(c,l)=>mod$1(c*invert$1(l,n),n),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>invert$1(c,n),sqrt:r.sqrt||(c=>a(u,c)),invertBatch:c=>FpInvertBatch$1(u,c),cmov:(c,l,h)=>h?l:c,toBytes:c=>t?numberToBytesLE$1(c,o):numberToBytesBE$1(c,o),fromBytes:c=>{if(c.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${c.length}`);return t?bytesToNumberLE$1(c):bytesToNumberBE$1(c)}});return Object.freeze(u)}function getFieldBytesLength$1(n){if(typeof n!="bigint")throw new Error("field order must be bigint");const e=n.toString(2).length;return Math.ceil(e/8)}function getMinHashLength$1(n){const e=getFieldBytesLength$1(n);return e+Math.ceil(e/2)}function mapHashToField$1(n,e,t=!1){const r=n.length,s=getFieldBytesLength$1(e),o=getMinHashLength$1(e);if(r<16||r<o||r>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${r}`);const a=t?bytesToNumberBE$1(n):bytesToNumberLE$1(n),u=mod$1(a,e-_1n$8)+_1n$8;return t?numberToBytesLE$1(u,s):numberToBytesBE$1(u,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$7=BigInt(0),_1n$7=BigInt(1);function wNAF$1(n,e){const t=(s,o)=>{const a=o.negate();return s?a:o},r=s=>{const o=Math.ceil(e/s)+1,a=2**(s-1);return{windows:o,windowSize:a}};return{constTimeNegate:t,unsafeLadder(s,o){let a=n.ZERO,u=s;for(;o>_0n$7;)o&_1n$7&&(a=a.add(u)),u=u.double(),o>>=_1n$7;return a},precomputeWindow(s,o){const{windows:a,windowSize:u}=r(o),c=[];let l=s,h=l;for(let f=0;f<a;f++){h=l,c.push(h);for(let p=1;p<u;p++)h=h.add(l),c.push(h);l=h.double()}return c},wNAF(s,o,a){const{windows:u,windowSize:c}=r(s);let l=n.ZERO,h=n.BASE;const f=BigInt(2**s-1),p=2**s,b=BigInt(s);for(let v=0;v<u;v++){const m=v*c;let y=Number(a&f);a>>=b,y>c&&(y-=p,a+=_1n$7);const w=m,x=m+Math.abs(y)-1,k=v%2!==0,C=y<0;y===0?h=h.add(t(k,o[w])):l=l.add(t(C,o[x]))}return{p:l,f:h}},wNAFCached(s,o,a,u){const c=s._WINDOW_SIZE||1;let l=o.get(s);return l||(l=this.precomputeWindow(s,c),c!==1&&o.set(s,u(l))),this.wNAF(c,l,a)}}}function validateBasic$1(n){return validateField$1(n.Fp),validateObject$1(n,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength$1(n.n,n.nBitLength),...n,p:n.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validatePointOpts$1(n){const e=validateBasic$1(n);validateObject$1(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=e;if(t){if(!r.eql(s,r.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:b2n$1,hexToBytes:h2b$1}=ut$1,DER$1={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(n){const{Err:e}=DER$1;if(n.length<2||n[0]!==2)throw new e("Invalid signature integer tag");const t=n[1],r=n.subarray(2,t+2);if(!t||r.length!==t)throw new e("Invalid signature integer: wrong length");if(r[0]&128)throw new e("Invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("Invalid signature integer: unnecessary leading zero");return{d:b2n$1(r),l:n.subarray(t+2)}},toSig(n){const{Err:e}=DER$1,t=typeof n=="string"?h2b$1(n):n;if(!(t instanceof Uint8Array))throw new Error("ui8a expected");let r=t.length;if(r<2||t[0]!=48)throw new e("Invalid signature tag");if(t[1]!==r-2)throw new e("Invalid signature: incorrect length");const{d:s,l:o}=DER$1._parseInt(t.subarray(2)),{d:a,l:u}=DER$1._parseInt(o);if(u.length)throw new e("Invalid signature: left bytes after parsing");return{r:s,s:a}},hexFromSig(n){const e=l=>Number.parseInt(l[0],16)&8?"00"+l:l,t=l=>{const h=l.toString(16);return h.length&1?`0${h}`:h},r=e(t(n.s)),s=e(t(n.r)),o=r.length/2,a=s.length/2,u=t(o),c=t(a);return`30${t(a+o+4)}02${c}${s}02${u}${r}`}},_0n$6=BigInt(0),_1n$6=BigInt(1);BigInt(2);const _3n$2=BigInt(3);BigInt(4);function weierstrassPoints$1(n){const e=validatePointOpts$1(n),{Fp:t}=e,r=e.toBytes||((v,m,y)=>{const w=m.toAffine();return concatBytes$3(Uint8Array.from([4]),t.toBytes(w.x),t.toBytes(w.y))}),s=e.fromBytes||(v=>{const m=v.subarray(1),y=t.fromBytes(m.subarray(0,t.BYTES)),w=t.fromBytes(m.subarray(t.BYTES,2*t.BYTES));return{x:y,y:w}});function o(v){const{a:m,b:y}=e,w=t.sqr(v),x=t.mul(w,v);return t.add(t.add(x,t.mul(v,m)),y)}if(!t.eql(t.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(v){return typeof v=="bigint"&&_0n$6<v&&v<e.n}function u(v){if(!a(v))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function c(v){const{allowedPrivateKeyLengths:m,nByteLength:y,wrapPrivateKey:w,n:x}=e;if(m&&typeof v!="bigint"){if(v instanceof Uint8Array&&(v=bytesToHex$3(v)),typeof v!="string"||!m.includes(v.length))throw new Error("Invalid key");v=v.padStart(y*2,"0")}let k;try{k=typeof v=="bigint"?v:bytesToNumberBE$1(ensureBytes$1("private key",v,y))}catch{throw new Error(`private key must be ${y} bytes, hex or bigint, not ${typeof v}`)}return w&&(k=mod$1(k,x)),u(k),k}const l=new Map;function h(v){if(!(v instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(m,y,w){if(this.px=m,this.py=y,this.pz=w,m==null||!t.isValid(m))throw new Error("x required");if(y==null||!t.isValid(y))throw new Error("y required");if(w==null||!t.isValid(w))throw new Error("z required")}static fromAffine(m){const{x:y,y:w}=m||{};if(!m||!t.isValid(y)||!t.isValid(w))throw new Error("invalid affine point");if(m instanceof f)throw new Error("projective point not allowed");const x=k=>t.eql(k,t.ZERO);return x(y)&&x(w)?f.ZERO:new f(y,w,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const y=t.invertBatch(m.map(w=>w.pz));return m.map((w,x)=>w.toAffine(y[x])).map(f.fromAffine)}static fromHex(m){const y=f.fromAffine(s(ensureBytes$1("pointHex",m)));return y.assertValidity(),y}static fromPrivateKey(m){return f.BASE.multiply(c(m))}_setWindowSize(m){this._WINDOW_SIZE=m,l.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!t.is0(this.py))return;throw new Error("bad point: ZERO")}const{x:m,y}=this.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not FE");const w=t.sqr(y),x=o(m);if(!t.eql(w,x))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y:m}=this.toAffine();if(t.isOdd)return!t.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){h(m);const{px:y,py:w,pz:x}=this,{px:k,py:C,pz:P}=m,R=t.eql(t.mul(y,P),t.mul(k,x)),N=t.eql(t.mul(w,P),t.mul(C,x));return R&&N}negate(){return new f(this.px,t.neg(this.py),this.pz)}double(){const{a:m,b:y}=e,w=t.mul(y,_3n$2),{px:x,py:k,pz:C}=this;let P=t.ZERO,R=t.ZERO,N=t.ZERO,B=t.mul(x,x),O=t.mul(k,k),H=t.mul(C,C),S=t.mul(x,k);return S=t.add(S,S),N=t.mul(x,C),N=t.add(N,N),P=t.mul(m,N),R=t.mul(w,H),R=t.add(P,R),P=t.sub(O,R),R=t.add(O,R),R=t.mul(P,R),P=t.mul(S,P),N=t.mul(w,N),H=t.mul(m,H),S=t.sub(B,H),S=t.mul(m,S),S=t.add(S,N),N=t.add(B,B),B=t.add(N,B),B=t.add(B,H),B=t.mul(B,S),R=t.add(R,B),H=t.mul(k,C),H=t.add(H,H),B=t.mul(H,S),P=t.sub(P,B),N=t.mul(H,O),N=t.add(N,N),N=t.add(N,N),new f(P,R,N)}add(m){h(m);const{px:y,py:w,pz:x}=this,{px:k,py:C,pz:P}=m;let R=t.ZERO,N=t.ZERO,B=t.ZERO;const O=e.a,H=t.mul(e.b,_3n$2);let S=t.mul(y,k),_=t.mul(w,C),L=t.mul(x,P),I=t.add(y,w),A=t.add(k,C);I=t.mul(I,A),A=t.add(S,_),I=t.sub(I,A),A=t.add(y,x);let E=t.add(k,P);return A=t.mul(A,E),E=t.add(S,L),A=t.sub(A,E),E=t.add(w,x),R=t.add(C,P),E=t.mul(E,R),R=t.add(_,L),E=t.sub(E,R),B=t.mul(O,A),R=t.mul(H,L),B=t.add(R,B),R=t.sub(_,B),B=t.add(_,B),N=t.mul(R,B),_=t.add(S,S),_=t.add(_,S),L=t.mul(O,L),A=t.mul(H,A),_=t.add(_,L),L=t.sub(S,L),L=t.mul(O,L),A=t.add(A,L),S=t.mul(_,A),N=t.add(N,S),S=t.mul(E,A),R=t.mul(I,R),R=t.sub(R,S),S=t.mul(I,_),B=t.mul(E,B),B=t.add(B,S),new f(R,N,B)}subtract(m){return this.add(m.negate())}is0(){return this.equals(f.ZERO)}wNAF(m){return b.wNAFCached(this,l,m,y=>{const w=t.invertBatch(y.map(x=>x.pz));return y.map((x,k)=>x.toAffine(w[k])).map(f.fromAffine)})}multiplyUnsafe(m){const y=f.ZERO;if(m===_0n$6)return y;if(u(m),m===_1n$6)return this;const{endo:w}=e;if(!w)return b.unsafeLadder(this,m);let{k1neg:x,k1:k,k2neg:C,k2:P}=w.splitScalar(m),R=y,N=y,B=this;for(;k>_0n$6||P>_0n$6;)k&_1n$6&&(R=R.add(B)),P&_1n$6&&(N=N.add(B)),B=B.double(),k>>=_1n$6,P>>=_1n$6;return x&&(R=R.negate()),C&&(N=N.negate()),N=new f(t.mul(N.px,w.beta),N.py,N.pz),R.add(N)}multiply(m){u(m);let y=m,w,x;const{endo:k}=e;if(k){const{k1neg:C,k1:P,k2neg:R,k2:N}=k.splitScalar(y);let{p:B,f:O}=this.wNAF(P),{p:H,f:S}=this.wNAF(N);B=b.constTimeNegate(C,B),H=b.constTimeNegate(R,H),H=new f(t.mul(H.px,k.beta),H.py,H.pz),w=B.add(H),x=O.add(S)}else{const{p:C,f:P}=this.wNAF(y);w=C,x=P}return f.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(m,y,w){const x=f.BASE,k=(P,R)=>R===_0n$6||R===_1n$6||!P.equals(x)?P.multiplyUnsafe(R):P.multiply(R),C=k(this,y).add(k(m,w));return C.is0()?void 0:C}toAffine(m){const{px:y,py:w,pz:x}=this,k=this.is0();m==null&&(m=k?t.ONE:t.inv(x));const C=t.mul(y,m),P=t.mul(w,m),R=t.mul(x,m);if(k)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x:C,y:P}}isTorsionFree(){const{h:m,isTorsionFree:y}=e;if(m===_1n$6)return!0;if(y)return y(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:y}=e;return m===_1n$6?this:y?y(f,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return this.assertValidity(),r(f,this,m)}toHex(m=!0){return bytesToHex$3(this.toRawBytes(m))}}f.BASE=new f(e.Gx,e.Gy,t.ONE),f.ZERO=new f(t.ZERO,t.ONE,t.ZERO);const p=e.nBitLength,b=wNAF$1(f,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function validateOpts$1(n){const e=validateBasic$1(n);return validateObject$1(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function weierstrass$1(n){const e=validateOpts$1(n),{Fp:t,n:r}=e,s=t.BYTES+1,o=2*t.BYTES+1;function a(A){return _0n$6<A&&A<t.ORDER}function u(A){return mod$1(A,r)}function c(A){return invert$1(A,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=weierstrassPoints$1({...e,toBytes(A,E,$){const M=E.toAffine(),U=t.toBytes(M.x),z=concatBytes$3;return $?z(Uint8Array.from([E.hasEvenY()?2:3]),U):z(Uint8Array.from([4]),U,t.toBytes(M.y))},fromBytes(A){const E=A.length,$=A[0],M=A.subarray(1);if(E===s&&($===2||$===3)){const U=bytesToNumberBE$1(M);if(!a(U))throw new Error("Point is not on curve");const z=f(U);let D=t.sqrt(z);const V=(D&_1n$6)===_1n$6;return($&1)===1!==V&&(D=t.neg(D)),{x:U,y:D}}else if(E===o&&$===4){const U=t.fromBytes(M.subarray(0,t.BYTES)),z=t.fromBytes(M.subarray(t.BYTES,2*t.BYTES));return{x:U,y:z}}else throw new Error(`Point of length ${E} was invalid. Expected ${s} compressed bytes or ${o} uncompressed bytes`)}}),b=A=>bytesToHex$3(numberToBytesBE$1(A,e.nByteLength));function v(A){const E=r>>_1n$6;return A>E}function m(A){return v(A)?u(-A):A}const y=(A,E,$)=>bytesToNumberBE$1(A.slice(E,$));class w{constructor(E,$,M){this.r=E,this.s=$,this.recovery=M,this.assertValidity()}static fromCompact(E){const $=e.nByteLength;return E=ensureBytes$1("compactSignature",E,$*2),new w(y(E,0,$),y(E,$,2*$))}static fromDER(E){const{r:$,s:M}=DER$1.toSig(ensureBytes$1("DER",E));return new w($,M)}assertValidity(){if(!p(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!p(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(E){return new w(this.r,this.s,E)}recoverPublicKey(E){const{r:$,s:M,recovery:U}=this,z=N(ensureBytes$1("msgHash",E));if(U==null||![0,1,2,3].includes(U))throw new Error("recovery id invalid");const D=U===2||U===3?$+e.n:$;if(D>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const V=U&1?"03":"02",W=l.fromHex(V+b(D)),Z=c(D),G=u(-z*Z),K=u(M*Z),ne=l.BASE.multiplyAndAddUnsafe(W,G,K);if(!ne)throw new Error("point at infinify");return ne.assertValidity(),ne}hasHighS(){return v(this.s)}normalizeS(){return this.hasHighS()?new w(this.r,u(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes$3(this.toDERHex())}toDERHex(){return DER$1.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes$3(this.toCompactHex())}toCompactHex(){return b(this.r)+b(this.s)}}const x={isValidPrivateKey(A){try{return h(A),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const A=getMinHashLength$1(e.n);return mapHashToField$1(e.randomBytes(A),e.n)},precompute(A=8,E=l.BASE){return E._setWindowSize(A),E.multiply(BigInt(3)),E}};function k(A,E=!0){return l.fromPrivateKey(A).toRawBytes(E)}function C(A){const E=A instanceof Uint8Array,$=typeof A=="string",M=(E||$)&&A.length;return E?M===s||M===o:$?M===2*s||M===2*o:A instanceof l}function P(A,E,$=!0){if(C(A))throw new Error("first arg must be private key");if(!C(E))throw new Error("second arg must be public key");return l.fromHex(E).multiply(h(A)).toRawBytes($)}const R=e.bits2int||function(A){const E=bytesToNumberBE$1(A),$=A.length*8-e.nBitLength;return $>0?E>>BigInt($):E},N=e.bits2int_modN||function(A){return u(R(A))},B=bitMask$1(e.nBitLength);function O(A){if(typeof A!="bigint")throw new Error("bigint expected");if(!(_0n$6<=A&&A<B))throw new Error(`bigint expected < 2^${e.nBitLength}`);return numberToBytesBE$1(A,e.nByteLength)}function H(A,E,$=S){if(["recovered","canonical"].some(se=>se in $))throw new Error("sign() legacy options not supported");const{hash:M,randomBytes:U}=e;let{lowS:z,prehash:D,extraEntropy:V}=$;z==null&&(z=!0),A=ensureBytes$1("msgHash",A),D&&(A=ensureBytes$1("prehashed msgHash",M(A)));const W=N(A),Z=h(E),G=[O(Z),O(W)];if(V!=null){const se=V===!0?U(t.BYTES):V;G.push(ensureBytes$1("extraEntropy",se))}const K=concatBytes$3(...G),ne=W;function ae(se){const pe=R(se);if(!p(pe))return;const ye=c(pe),J=l.BASE.multiply(pe).toAffine(),Q=u(J.x);if(Q===_0n$6)return;const te=u(ye*u(ne+Q*Z));if(te===_0n$6)return;let be=(J.x===Q?0:2)|Number(J.y&_1n$6),Be=te;return z&&v(te)&&(Be=m(te),be^=1),new w(Q,Be,be)}return{seed:K,k2sig:ae}}const S={lowS:e.lowS,prehash:!1},_={lowS:e.lowS,prehash:!1};function L(A,E,$=S){const{seed:M,k2sig:U}=H(A,E,$),z=e;return createHmacDrbg$1(z.hash.outputLen,z.nByteLength,z.hmac)(M,U)}l.BASE._setWindowSize(8);function I(A,E,$,M=_){var J;const U=A;if(E=ensureBytes$1("msgHash",E),$=ensureBytes$1("publicKey",$),"strict"in M)throw new Error("options.strict was renamed to lowS");const{lowS:z,prehash:D}=M;let V,W;try{if(typeof U=="string"||U instanceof Uint8Array)try{V=w.fromDER(U)}catch(Q){if(!(Q instanceof DER$1.Err))throw Q;V=w.fromCompact(U)}else if(typeof U=="object"&&typeof U.r=="bigint"&&typeof U.s=="bigint"){const{r:Q,s:te}=U;V=new w(Q,te)}else throw new Error("PARSE");W=l.fromHex($)}catch(Q){if(Q.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(z&&V.hasHighS())return!1;D&&(E=e.hash(E));const{r:Z,s:G}=V,K=N(E),ne=c(G),ae=u(K*ne),se=u(Z*ne),pe=(J=l.BASE.multiplyAndAddUnsafe(W,ae,se))==null?void 0:J.toAffine();return pe?u(pe.x)===Z:!1}return{CURVE:e,getPublicKey:k,getSharedSecret:P,sign:L,verify:I,ProjectivePoint:l,Signature:w,utils:x}}let HMAC$2=class extends Hash$2{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,hash$1(e);const r=toBytes$2(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return exists$1(this),this.iHash.update(e),this}digestInto(e){exists$1(this),bytes$2(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=u,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$2=(n,e,t)=>new HMAC$2(n,e).update(t).digest();hmac$2.create=(n,e)=>new HMAC$2(n,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash$1(n){return{hash:n,hmac:(e,...t)=>hmac$2(n,e,concatBytes$4(...t)),randomBytes:randomBytes$2}}function createCurve$1(n,e){const t=r=>weierstrass$1({...n,...getHash$1(r)});return Object.freeze({...t(e),create:t})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P$1=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N$1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n$5=BigInt(1),_2n$3=BigInt(2),divNearest$1=(n,e)=>(n+e/_2n$3)/e;function sqrtMod$1(n){const e=secp256k1P$1,t=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),a=BigInt(23),u=BigInt(44),c=BigInt(88),l=n*n*n%e,h=l*l*n%e,f=pow2$1(h,t,e)*h%e,p=pow2$1(f,t,e)*h%e,b=pow2$1(p,_2n$3,e)*l%e,v=pow2$1(b,s,e)*b%e,m=pow2$1(v,o,e)*v%e,y=pow2$1(m,u,e)*m%e,w=pow2$1(y,c,e)*y%e,x=pow2$1(w,u,e)*m%e,k=pow2$1(x,t,e)*h%e,C=pow2$1(k,a,e)*v%e,P=pow2$1(C,r,e)*l%e,R=pow2$1(P,_2n$3,e);if(!Fp.eql(Fp.sqr(R),n))throw new Error("Cannot find square root");return R}const Fp=Field$1(secp256k1P$1,void 0,void 0,{sqrt:sqrtMod$1}),secp256k1$1=createCurve$1({a:BigInt(0),b:BigInt(7),Fp,n:secp256k1N$1,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:n=>{const e=secp256k1N$1,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-_1n$5*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,a=BigInt("0x100000000000000000000000000000000"),u=divNearest$1(o*n,e),c=divNearest$1(-r*n,e);let l=mod$1(n-u*t-c*s,e),h=mod$1(-u*r-c*o,e);const f=l>a,p=h>a;if(f&&(l=e-l),p&&(h=e-h),l>a||h>a)throw new Error("splitScalar: Endomorphism failed, k="+n);return{k1neg:f,k1:l,k2neg:p,k2:h}}}},sha256$2),_0n$5=BigInt(0),fe=n=>typeof n=="bigint"&&_0n$5<n&&n<secp256k1P$1,ge=n=>typeof n=="bigint"&&_0n$5<n&&n<secp256k1N$1,TAGGED_HASH_PREFIXES$1={};function taggedHash$1(n,...e){let t=TAGGED_HASH_PREFIXES$1[n];if(t===void 0){const r=sha256$2(Uint8Array.from(n,s=>s.charCodeAt(0)));t=concatBytes$3(r,r),TAGGED_HASH_PREFIXES$1[n]=t}return sha256$2(concatBytes$3(t,...e))}const pointToBytes$1=n=>n.toRawBytes(!0).slice(1),numTo32b$1=n=>numberToBytesBE$1(n,32),modP$1=n=>mod$1(n,secp256k1P$1),modN$1=n=>mod$1(n,secp256k1N$1),Point$1=secp256k1$1.ProjectivePoint,GmulAdd$1=(n,e,t)=>Point$1.BASE.multiplyAndAddUnsafe(n,e,t);function schnorrGetExtPubKey$1(n){let e=secp256k1$1.utils.normPrivateKeyToScalar(n),t=Point$1.fromPrivateKey(e);return{scalar:t.hasEvenY()?e:modN$1(-e),bytes:pointToBytes$1(t)}}function lift_x$1(n){if(!fe(n))throw new Error("bad x: need 0 < x < p");const e=modP$1(n*n),t=modP$1(e*n+BigInt(7));let r=sqrtMod$1(t);r%_2n$3!==_0n$5&&(r=modP$1(-r));const s=new Point$1(n,r,_1n$5);return s.assertValidity(),s}function challenge$1(...n){return modN$1(bytesToNumberBE$1(taggedHash$1("BIP0340/challenge",...n)))}function schnorrGetPublicKey$1(n){return schnorrGetExtPubKey$1(n).bytes}function schnorrSign$1(n,e,t=randomBytes$2(32)){const r=ensureBytes$1("message",n),{bytes:s,scalar:o}=schnorrGetExtPubKey$1(e),a=ensureBytes$1("auxRand",t,32),u=numTo32b$1(o^bytesToNumberBE$1(taggedHash$1("BIP0340/aux",a))),c=taggedHash$1("BIP0340/nonce",u,s,r),l=modN$1(bytesToNumberBE$1(c));if(l===_0n$5)throw new Error("sign failed: k is zero");const{bytes:h,scalar:f}=schnorrGetExtPubKey$1(l),p=challenge$1(h,s,r),b=new Uint8Array(64);if(b.set(h,0),b.set(numTo32b$1(modN$1(f+p*o)),32),!schnorrVerify$1(b,r,s))throw new Error("sign: Invalid signature produced");return b}function schnorrVerify$1(n,e,t){const r=ensureBytes$1("signature",n,64),s=ensureBytes$1("message",e),o=ensureBytes$1("publicKey",t,32);try{const a=lift_x$1(bytesToNumberBE$1(o)),u=bytesToNumberBE$1(r.subarray(0,32));if(!fe(u))return!1;const c=bytesToNumberBE$1(r.subarray(32,64));if(!ge(c))return!1;const l=challenge$1(numTo32b$1(u),pointToBytes$1(a),s),h=GmulAdd$1(a,c,modN$1(-l));return!(!h||!h.hasEvenY()||h.toAffine().x!==u)}catch{return!1}}const schnorr$1={getPublicKey:schnorrGetPublicKey$1,sign:schnorrSign$1,verify:schnorrVerify$1,utils:{randomPrivateKey:secp256k1$1.utils.randomPrivateKey,lift_x:lift_x$1,pointToBytes:pointToBytes$1,numberToBytesBE:numberToBytesBE$1,bytesToNumberBE:bytesToNumberBE$1,taggedHash:taggedHash$1,mod:mod$1}},crypto$2=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const u8a=n=>n instanceof Uint8Array,createView$1=n=>new DataView(n.buffer,n.byteOffset,n.byteLength),rotr$1=(n,e)=>n<<32-e|n>>>e,isLE$1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE$1)throw new Error("Non little-endian hardware is not supported");const hexes$2=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$2(n){if(!u8a(n))throw new Error("Uint8Array expected");let e="";for(let t=0;t<n.length;t++)e+=hexes$2[n[t]];return e}function hexToBytes$2(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(e/2);for(let r=0;r<t.length;r++){const s=r*2,o=n.slice(s,s+2),a=Number.parseInt(o,16);if(Number.isNaN(a)||a<0)throw new Error("Invalid byte sequence");t[r]=a}return t}function utf8ToBytes$2(n){if(typeof n!="string")throw new Error(`utf8ToBytes expected string, got ${typeof n}`);return new Uint8Array(new TextEncoder().encode(n))}function toBytes$1(n){if(typeof n=="string"&&(n=utf8ToBytes$2(n)),!u8a(n))throw new Error(`expected Uint8Array, got ${typeof n}`);return n}function concatBytes$2(...n){const e=new Uint8Array(n.reduce((r,s)=>r+s.length,0));let t=0;return n.forEach(r=>{if(!u8a(r))throw new Error("Uint8Array expected");e.set(r,t),t+=r.length}),e}let Hash$1=class{clone(){return this._cloneInto()}};function wrapConstructor$1(n){const e=r=>n().update(toBytes$1(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes$1(n=32){if(crypto$2&&typeof crypto$2.getRandomValues=="function")return crypto$2.getRandomValues(new Uint8Array(n));throw new Error("crypto.getRandomValues must be defined")}function number$1(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bool$1(n){if(typeof n!="boolean")throw new Error(`Expected boolean, not ${n}`)}function bytes$1(n,...e){if(!(n instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(n.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${n.length}`)}function hash(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number$1(n.outputLen),number$1(n.blockLen)}function exists(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function output(n,e){bytes$1(n);const t=e.outputLen;if(n.length<t)throw new Error(`digestInto() expects output buffer of length at least ${t}`)}const assert={number:number$1,bool:bool$1,bytes:bytes$1,hash,exists,output};function setBigUint64$1(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),u=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,a,r),n.setUint32(e+l,u,r)}class SHA2 extends Hash$1{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView$1(this.buffer)}update(e){assert.exists(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes$1(e);const o=e.length;for(let a=0;a<o;){const u=Math.min(s-this.pos,o-a);if(u===s){const c=createView$1(e);for(;s<=o-a;a+=s)this.process(c,a);continue}r.set(e.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){assert.exists(this),assert.output(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let f=a;f<s;f++)t[f]=0;setBigUint64$1(r,s-8,BigInt(this.length*8),o),this.process(r,0);const u=createView$1(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)u.setUint32(4*f,h[f],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:u}=this;return e.length=s,e.pos=u,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}}const Chi$1=(n,e,t)=>n&e^~n&t,Maj$1=(n,e,t)=>n&e^n&t^e&t,SHA256_K$1=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W$1=new Uint32Array(64);let SHA256$1=class extends SHA2{constructor(){super(64,32,8,!1),this.A=IV[0]|0,this.B=IV[1]|0,this.C=IV[2]|0,this.D=IV[3]|0,this.E=IV[4]|0,this.F=IV[5]|0,this.G=IV[6]|0,this.H=IV[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:u,H:c}=this;return[e,t,r,s,o,a,u,c]}set(e,t,r,s,o,a,u,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=u|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)SHA256_W$1[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){const p=SHA256_W$1[f-15],b=SHA256_W$1[f-2],v=rotr$1(p,7)^rotr$1(p,18)^p>>>3,m=rotr$1(b,17)^rotr$1(b,19)^b>>>10;SHA256_W$1[f]=m+SHA256_W$1[f-7]+v+SHA256_W$1[f-16]|0}let{A:r,B:s,C:o,D:a,E:u,F:c,G:l,H:h}=this;for(let f=0;f<64;f++){const p=rotr$1(u,6)^rotr$1(u,11)^rotr$1(u,25),b=h+p+Chi$1(u,c,l)+SHA256_K$1[f]+SHA256_W$1[f]|0,m=(rotr$1(r,2)^rotr$1(r,13)^rotr$1(r,22))+Maj$1(r,s,o)|0;h=l,l=c,c=u,u=a+b|0,a=o,o=s,s=r,r=b+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(r,s,o,a,u,c,l,h)}roundClean(){SHA256_W$1.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};class SHA224 extends SHA256$1{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const sha256$1=wrapConstructor$1(()=>new SHA256$1);wrapConstructor$1(()=>new SHA224);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function assertNumber(n){if(!Number.isSafeInteger(n))throw new Error(`Wrong integer: ${n}`)}function chain(...n){const e=(s,o)=>a=>s(o(a)),t=Array.from(n).reverse().reduce((s,o)=>s?e(s,o.encode):o.encode,void 0),r=n.reduce((s,o)=>s?e(s,o.decode):o.decode,void 0);return{encode:t,decode:r}}function alphabet(n){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(t=>{if(assertNumber(t),t<0||t>=n.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${n.length})`);return n[t]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(t=>{if(typeof t!="string")throw new Error(`alphabet.decode: not string element=${t}`);const r=n.indexOf(t);if(r===-1)throw new Error(`Unknown letter: "${t}". Allowed: ${n}`);return r})}}}function join(n=""){if(typeof n!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let t of e)if(typeof t!="string")throw new Error(`join.encode: non-string input=${t}`);return e.join(n)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(n)}}}function padding(n,e="="){if(assertNumber(n),typeof e!="string")throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let r of t)if(typeof r!="string")throw new Error(`padding.encode: non-string input=${r}`);for(;t.length*n%8;)t.push(e);return t},decode(t){if(!Array.isArray(t)||t.length&&typeof t[0]!="string")throw new Error("padding.encode input should be array of strings");for(let s of t)if(typeof s!="string")throw new Error(`padding.decode: non-string input=${s}`);let r=t.length;if(r*n%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;r>0&&t[r-1]===e;r--)if(!((r-1)*n%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,r)}}}function normalize$1(n){if(typeof n!="function")throw new Error("normalize fn should be function");return{encode:e=>e,decode:e=>n(e)}}function convertRadix(n,e,t){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(t<2)throw new Error(`convertRadix: wrong to=${t}, base cannot be less than 2`);if(!Array.isArray(n))throw new Error("convertRadix: data should be array");if(!n.length)return[];let r=0;const s=[],o=Array.from(n);for(o.forEach(a=>{if(assertNumber(a),a<0||a>=e)throw new Error(`Wrong integer: ${a}`)});;){let a=0,u=!0;for(let c=r;c<o.length;c++){const l=o[c],h=e*a+l;if(!Number.isSafeInteger(h)||e*a/e!==a||h-l!==e*a)throw new Error("convertRadix: carry overflow");if(a=h%t,o[c]=Math.floor(h/t),!Number.isSafeInteger(o[c])||o[c]*t+a!==h)throw new Error("convertRadix: carry overflow");if(u)o[c]?u=!1:r=c;else continue}if(s.push(a),u)break}for(let a=0;a<n.length-1&&n[a]===0;a++)s.push(0);return s.reverse()}const gcd=(n,e)=>e?gcd(e,n%e):n,radix2carry=(n,e)=>n+(e-gcd(n,e));function convertRadix2(n,e,t,r){if(!Array.isArray(n))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(radix2carry(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${radix2carry(e,t)}`);let s=0,o=0;const a=2**t-1,u=[];for(const c of n){if(assertNumber(c),c>=2**e)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(s=s<<e|c,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=t;o-=t)u.push((s>>o-t&a)>>>0);s&=2**o-1}if(s=s<<t-o&a,!r&&o>=e)throw new Error("Excess padding");if(!r&&s)throw new Error(`Non-zero padding: ${s}`);return r&&o>0&&u.push(s>>>0),u}function radix(n){return assertNumber(n),{encode:e=>{if(!(e instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return convertRadix(Array.from(e),2**8,n)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(convertRadix(e,n,2**8))}}}function radix2(n,e=!1){if(assertNumber(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(radix2carry(8,n)>32||radix2carry(n,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 convertRadix2(Array.from(t),8,n,!e)},decode:t=>{if(!Array.isArray(t)||t.length&&typeof t[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(convertRadix2(t,n,8,e))}}}function unsafeWrapper(n){if(typeof n!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return n.apply(null,e)}catch{}}}const base16=chain(radix2(4),alphabet("0123456789ABCDEF"),join("")),base32=chain(radix2(5),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),padding(5),join(""));chain(radix2(5),alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"),padding(5),join("")),chain(radix2(5),alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),join(""),normalize$1(n=>n.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const base64=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),padding(6),join("")),base64url=chain(radix2(6),alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),padding(6),join("")),genBase58=n=>chain(radix(58),alphabet(n),join("")),base58=genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");genBase58("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),genBase58("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const XMR_BLOCK_LEN=[0,2,3,5,6,7,9,10,11],base58xmr={encode(n){let e="";for(let t=0;t<n.length;t+=8){const r=n.subarray(t,t+8);e+=base58.encode(r).padStart(XMR_BLOCK_LEN[r.length],"1")}return e},decode(n){let e=[];for(let t=0;t<n.length;t+=11){const r=n.slice(t,t+11),s=XMR_BLOCK_LEN.indexOf(r.length),o=base58.decode(r);for(let a=0;a<o.length-s;a++)if(o[a]!==0)throw new Error("base58xmr: wrong padding");e=e.concat(Array.from(o.slice(o.length-s)))}return Uint8Array.from(e)}},BECH_ALPHABET=chain(alphabet("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),join("")),POLYMOD_GENERATORS=[996825010,642813549,513874426,1027748829,705979059];function bech32Polymod(n){const e=n>>25;let t=(n&33554431)<<5;for(let r=0;r<POLYMOD_GENERATORS.length;r++)(e>>r&1)===1&&(t^=POLYMOD_GENERATORS[r]);return t}function bechChecksum(n,e,t=1){const r=n.length;let s=1;for(let o=0;o<r;o++){const a=n.charCodeAt(o);if(a<33||a>126)throw new Error(`Invalid prefix (${n})`);s=bech32Polymod(s)^a>>5}s=bech32Polymod(s);for(let o=0;o<r;o++)s=bech32Polymod(s)^n.charCodeAt(o)&31;for(let o of e)s=bech32Polymod(s)^o;for(let o=0;o<6;o++)s=bech32Polymod(s);return s^=t,BECH_ALPHABET.encode(convertRadix2([s%2**30],30,5,!1))}function genBech32(n){const e=n==="bech32"?1:734539939,t=radix2(5),r=t.decode,s=t.encode,o=unsafeWrapper(r);function a(h,f,p=90){if(typeof h!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof h}`);if(!Array.isArray(f)||f.length&&typeof f[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof f}`);const b=h.length+7+f.length;if(p!==!1&&b>p)throw new TypeError(`Length ${b} exceeds limit ${p}`);return h=h.toLowerCase(),`${h}1${BECH_ALPHABET.encode(f)}${bechChecksum(h,f,e)}`}function u(h,f=90){if(typeof h!="string")throw new Error(`bech32.decode input should be string, not ${typeof h}`);if(h.length<8||f!==!1&&h.length>f)throw new TypeError(`Wrong string length: ${h.length} (${h}). Expected (8..${f})`);const p=h.toLowerCase();if(h!==p&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");h=p;const b=h.lastIndexOf("1");if(b===0||b===-1)throw new Error('Letter "1" must be present between prefix and data only');const v=h.slice(0,b),m=h.slice(b+1);if(m.length<6)throw new Error("Data must be at least 6 characters long");const y=BECH_ALPHABET.decode(m).slice(0,-6),w=bechChecksum(v,y,e);if(!m.endsWith(w))throw new Error(`Invalid checksum in ${h}: expected "${w}"`);return{prefix:v,words:y}}const c=unsafeWrapper(u);function l(h){const{prefix:f,words:p}=u(h,!1);return{prefix:f,words:p,bytes:r(p)}}return{encode:a,decode:u,decodeToBytes:l,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:o,toWords:s}}const bech32$1=genBech32("bech32");genBech32("bech32m");const utf8$1={encode:n=>new TextDecoder().decode(n),decode:n=>new TextEncoder().encode(n)},hex$1=chain(radix2(4),alphabet("0123456789abcdef"),join(""),normalize$1(n=>{if(typeof n!="string"||n.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof n} with length ${n.length}`);return n.toLowerCase()})),CODERS={utf8:utf8$1,hex:hex$1,base16,base32,base64,base64url,base58,base58xmr};`${Object.keys(CODERS).join(", ")}`;function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`positive integer expected, not ${n}`)}function bool(n){if(typeof n!="boolean")throw new Error(`boolean expected, not ${n}`)}function isBytes$2(n){return n instanceof Uint8Array||n!=null&&typeof n=="object"&&n.constructor.name==="Uint8Array"}function bytes(n,...e){if(!isBytes$2(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${n.length}`)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */const u32=n=>new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4)),isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function checkOpts(n,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(n,e)}function equalBytes$1(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}const wrapCipher=(n,e)=>(Object.assign(e,n),e),BLOCK_SIZE=16,POLY=283;function mul2(n){return n<<1^POLY&-(n>>7)}function mul(n,e){let t=0;for(;e>0;e>>=1)t^=n&-(e&1),n=mul2(n);return t}const sbox=(()=>{let n=new Uint8Array(256);for(let t=0,r=1;t<256;t++,r^=mul2(r))n[t]=r;const e=new Uint8Array(256);e[0]=99;for(let t=0;t<255;t++){let r=n[255-t];r|=r<<8,e[n[t]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return e})(),invSbox=sbox.map((n,e)=>sbox.indexOf(e)),rotr32_8=n=>n<<24|n>>>8,rotl32_8=n=>n<<8|n>>>24;function genTtable(n,e){if(n.length!==256)throw new Error("Wrong sbox length");const t=new Uint32Array(256).map((l,h)=>e(n[h])),r=t.map(rotl32_8),s=r.map(rotl32_8),o=s.map(rotl32_8),a=new Uint32Array(256*256),u=new Uint32Array(256*256),c=new Uint16Array(256*256);for(let l=0;l<256;l++)for(let h=0;h<256;h++){const f=l*256+h;a[f]=t[l]^r[h],u[f]=s[l]^o[h],c[f]=n[l]<<8|n[h]}return{sbox:n,sbox2:c,T0:t,T1:r,T2:s,T3:o,T01:a,T23:u}}const tableEncoding=genTtable(sbox,n=>mul(n,3)<<24|n<<16|n<<8|mul(n,2)),tableDecoding=genTtable(invSbox,n=>mul(n,11)<<24|mul(n,13)<<16|mul(n,9)<<8|mul(n,14)),xPowers=(()=>{const n=new Uint8Array(16);for(let e=0,t=1;e<16;e++,t=mul2(t))n[e]=t;return n})();function expandKeyLE(n){bytes(n);const e=n.length;if(![16,24,32].includes(e))throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${e}`);const{sbox2:t}=tableEncoding,r=u32(n),s=r.length,o=u=>applySbox(t,u,u,u,u),a=new Uint32Array(e+28);a.set(r);for(let u=s;u<a.length;u++){let c=a[u-1];u%s===0?c=o(rotr32_8(c))^xPowers[u/s-1]:s>6&&u%s===4&&(c=o(c)),a[u]=a[u-s]^c}return a}function expandKeyDecLE(n){const e=expandKeyLE(n),t=e.slice(),r=e.length,{sbox2:s}=tableEncoding,{T0:o,T1:a,T2:u,T3:c}=tableDecoding;for(let l=0;l<r;l+=4)for(let h=0;h<4;h++)t[l+h]=e[r-l-4+h];e.fill(0);for(let l=4;l<r-4;l++){const h=t[l],f=applySbox(s,h,h,h,h);t[l]=o[f&255]^a[f>>>8&255]^u[f>>>16&255]^c[f>>>24]}return t}function apply0123(n,e,t,r,s,o){return n[t<<8&65280|r>>>8&255]^e[s>>>8&65280|o>>>24&255]}function applySbox(n,e,t,r,s){return n[e&255|t&65280]|n[r>>>16&255|s>>>16&65280]<<16}function encrypt$2(n,e,t,r,s){const{sbox2:o,T01:a,T23:u}=tableEncoding;let c=0;e^=n[c++],t^=n[c++],r^=n[c++],s^=n[c++];const l=n.length/4-2;for(let v=0;v<l;v++){const m=n[c++]^apply0123(a,u,e,t,r,s),y=n[c++]^apply0123(a,u,t,r,s,e),w=n[c++]^apply0123(a,u,r,s,e,t),x=n[c++]^apply0123(a,u,s,e,t,r);e=m,t=y,r=w,s=x}const h=n[c++]^applySbox(o,e,t,r,s),f=n[c++]^applySbox(o,t,r,s,e),p=n[c++]^applySbox(o,r,s,e,t),b=n[c++]^applySbox(o,s,e,t,r);return{s0:h,s1:f,s2:p,s3:b}}function decrypt$2(n,e,t,r,s){const{sbox2:o,T01:a,T23:u}=tableDecoding;let c=0;e^=n[c++],t^=n[c++],r^=n[c++],s^=n[c++];const l=n.length/4-2;for(let v=0;v<l;v++){const m=n[c++]^apply0123(a,u,e,s,r,t),y=n[c++]^apply0123(a,u,t,e,s,r),w=n[c++]^apply0123(a,u,r,t,e,s),x=n[c++]^apply0123(a,u,s,r,t,e);e=m,t=y,r=w,s=x}const h=n[c++]^applySbox(o,e,s,r,t),f=n[c++]^applySbox(o,t,e,s,r),p=n[c++]^applySbox(o,r,t,e,s),b=n[c++]^applySbox(o,s,r,t,e);return{s0:h,s1:f,s2:p,s3:b}}function getDst(n,e){if(!e)return new Uint8Array(n);if(bytes(e),e.length<n)throw new Error(`aes: wrong destination length, expected at least ${n}, got: ${e.length}`);return e}function validateBlockDecrypt(n){if(bytes(n),n.length%BLOCK_SIZE!==0)throw new Error(`aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`)}function validateBlockEncrypt(n,e,t){let r=n.length;const s=r%BLOCK_SIZE;if(!e&&s!==0)throw new Error("aec/(cbc-ecb): unpadded plaintext with disabled padding");const o=u32(n);if(e){let c=BLOCK_SIZE-s;c||(c=BLOCK_SIZE),r=r+c}const a=getDst(r,t),u=u32(a);return{b:o,o:u,out:a}}function validatePCKS(n,e){if(!e)return n;const t=n.length;if(!t)throw new Error("aes/pcks5: empty ciphertext not allowed");const r=n[t-1];if(r<=0||r>16)throw new Error(`aes/pcks5: wrong padding byte: ${r}`);const s=n.subarray(0,-r);for(let o=0;o<r;o++)if(n[t-o-1]!==r)throw new Error("aes/pcks5: wrong padding");return s}function padPCKS(n){const e=new Uint8Array(16),t=u32(e);e.set(n);const r=BLOCK_SIZE-n.length;for(let s=BLOCK_SIZE-r;s<BLOCK_SIZE;s++)e[s]=r;return t}const cbc=wrapCipher({blockSize:16,nonceLength:16},function n(e,t,r={}){bytes(e),bytes(t,16);const s=!r.disablePadding;return{encrypt:(o,a)=>{const u=expandKeyLE(e),{b:c,o:l,out:h}=validateBlockEncrypt(o,s,a),f=u32(t);let p=f[0],b=f[1],v=f[2],m=f[3],y=0;for(;y+4<=c.length;)p^=c[y+0],b^=c[y+1],v^=c[y+2],m^=c[y+3],{s0:p,s1:b,s2:v,s3:m}=encrypt$2(u,p,b,v,m),l[y++]=p,l[y++]=b,l[y++]=v,l[y++]=m;if(s){const w=padPCKS(o.subarray(y*4));p^=w[0],b^=w[1],v^=w[2],m^=w[3],{s0:p,s1:b,s2:v,s3:m}=encrypt$2(u,p,b,v,m),l[y++]=p,l[y++]=b,l[y++]=v,l[y++]=m}return u.fill(0),h},decrypt:(o,a)=>{validateBlockDecrypt(o);const u=expandKeyDecLE(e),c=u32(t),l=getDst(o.length,a),h=u32(o),f=u32(l);let p=c[0],b=c[1],v=c[2],m=c[3];for(let y=0;y+4<=h.length;){const w=p,x=b,k=v,C=m;p=h[y+0],b=h[y+1],v=h[y+2],m=h[y+3];const{s0:P,s1:R,s2:N,s3:B}=decrypt$2(u,p,b,v,m);f[y++]=P^w,f[y++]=R^x,f[y++]=N^k,f[y++]=B^C}return u.fill(0),validatePCKS(l,s)}}}),_utf8ToBytes=n=>Uint8Array.from(n.split("").map(e=>e.charCodeAt(0))),sigma16=_utf8ToBytes("expand 16-byte k"),sigma32=_utf8ToBytes("expand 32-byte k"),sigma16_32=u32(sigma16),sigma32_32=u32(sigma32);sigma32_32.slice();function rotl(n,e){return n<<e|n>>>32-e}function isAligned32(n){return n.byteOffset%4===0}const BLOCK_LEN=64,BLOCK_LEN32=16,MAX_COUNTER=2**32-1,U32_EMPTY=new Uint32Array;function runCipher(n,e,t,r,s,o,a,u){const c=s.length,l=new Uint8Array(BLOCK_LEN),h=u32(l),f=isAligned32(s)&&isAligned32(o),p=f?u32(s):U32_EMPTY,b=f?u32(o):U32_EMPTY;for(let v=0;v<c;a++){if(n(e,t,r,h,a,u),a>=MAX_COUNTER)throw new Error("arx: counter overflow");const m=Math.min(BLOCK_LEN,c-v);if(f&&m===BLOCK_LEN){const y=v/4;if(v%4!==0)throw new Error("arx: invalid block position");for(let w=0,x;w<BLOCK_LEN32;w++)x=y+w,b[x]=p[x]^h[w];v+=BLOCK_LEN;continue}for(let y=0,w;y<m;y++)w=v+y,o[w]=s[w]^l[y];v+=m}}function createCipher(n,e){const{allowShortKeys:t,extendNonceFn:r,counterLength:s,counterRight:o,rounds:a}=checkOpts({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof n!="function")throw new Error("core must be a function");return number(s),number(a),bool(o),bool(t),(u,c,l,h,f=0)=>{bytes(u),bytes(c),bytes(l);const p=l.length;if(h||(h=new Uint8Array(p)),bytes(h),number(f),f<0||f>=MAX_COUNTER)throw new Error("arx: counter overflow");if(h.length<p)throw new Error(`arx: output (${h.length}) is shorter than data (${p})`);const b=[];let v=u.length,m,y;if(v===32)m=u.slice(),b.push(m),y=sigma32_32;else if(v===16&&t)m=new Uint8Array(32),m.set(u),m.set(u,16),y=sigma16_32,b.push(m);else throw new Error(`arx: invalid 32-byte key, got length=${v}`);isAligned32(c)||(c=c.slice(),b.push(c));const w=u32(m);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,w,u32(c.subarray(0,16)),w),c=c.subarray(16)}const x=16-s;if(x!==c.length)throw new Error(`arx: nonce must be ${x} or 16 bytes`);if(x!==12){const C=new Uint8Array(12);C.set(c,o?0:12-c.length),c=C,b.push(c)}const k=u32(c);for(runCipher(n,y,w,k,l,h,f,a);b.length>0;)b.pop().fill(0);return h}}function chachaCore(n,e,t,r,s,o=20){let a=n[0],u=n[1],c=n[2],l=n[3],h=e[0],f=e[1],p=e[2],b=e[3],v=e[4],m=e[5],y=e[6],w=e[7],x=s,k=t[0],C=t[1],P=t[2],R=a,N=u,B=c,O=l,H=h,S=f,_=p,L=b,I=v,A=m,E=y,$=w,M=x,U=k,z=C,D=P;for(let W=0;W<o;W+=2)R=R+H|0,M=rotl(M^R,16),I=I+M|0,H=rotl(H^I,12),R=R+H|0,M=rotl(M^R,8),I=I+M|0,H=rotl(H^I,7),N=N+S|0,U=rotl(U^N,16),A=A+U|0,S=rotl(S^A,12),N=N+S|0,U=rotl(U^N,8),A=A+U|0,S=rotl(S^A,7),B=B+_|0,z=rotl(z^B,16),E=E+z|0,_=rotl(_^E,12),B=B+_|0,z=rotl(z^B,8),E=E+z|0,_=rotl(_^E,7),O=O+L|0,D=rotl(D^O,16),$=$+D|0,L=rotl(L^$,12),O=O+L|0,D=rotl(D^O,8),$=$+D|0,L=rotl(L^$,7),R=R+S|0,D=rotl(D^R,16),E=E+D|0,S=rotl(S^E,12),R=R+S|0,D=rotl(D^R,8),E=E+D|0,S=rotl(S^E,7),N=N+_|0,M=rotl(M^N,16),$=$+M|0,_=rotl(_^$,12),N=N+_|0,M=rotl(M^N,8),$=$+M|0,_=rotl(_^$,7),B=B+L|0,U=rotl(U^B,16),I=I+U|0,L=rotl(L^I,12),B=B+L|0,U=rotl(U^B,8),I=I+U|0,L=rotl(L^I,7),O=O+H|0,z=rotl(z^O,16),A=A+z|0,H=rotl(H^A,12),O=O+H|0,z=rotl(z^O,8),A=A+z|0,H=rotl(H^A,7);let V=0;r[V++]=a+R|0,r[V++]=u+N|0,r[V++]=c+B|0,r[V++]=l+O|0,r[V++]=h+H|0,r[V++]=f+S|0,r[V++]=p+_|0,r[V++]=b+L|0,r[V++]=v+I|0,r[V++]=m+A|0,r[V++]=y+E|0,r[V++]=w+$|0,r[V++]=x+M|0,r[V++]=k+U|0,r[V++]=C+z|0,r[V++]=P+D|0}const chacha20=createCipher(chachaCore,{counterRight:!1,counterLength:4,allowShortKeys:!1});let HMAC$1=class extends Hash$1{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,assert.hash(e);const r=toBytes$1(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return assert.exists(this),this.iHash.update(e),this}digestInto(e){assert.exists(this),assert.bytes(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=u,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const hmac$1=(n,e,t)=>new HMAC$1(n,e).update(t).digest();hmac$1.create=(n,e)=>new HMAC$1(n,e);function extract(n,e,t){return assert.hash(n),hmac$1(n,toBytes$1(t),toBytes$1(e))}const HKDF_COUNTER=new Uint8Array([0]),EMPTY_BUFFER=new Uint8Array;function expand(n,e,t,r=32){if(assert.hash(n),assert.number(r),r>255*n.outputLen)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/n.outputLen);t===void 0&&(t=EMPTY_BUFFER);const o=new Uint8Array(s*n.outputLen),a=hmac$1.create(n,e),u=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)HKDF_COUNTER[0]=l+1,u.update(l===0?EMPTY_BUFFER:c).update(t).update(HKDF_COUNTER).digestInto(c),o.set(c,n.outputLen*l),a._cloneInto(u);return a.destroy(),u.destroy(),c.fill(0),HKDF_COUNTER.fill(0),o.slice(0,r)}var __defProp=Object.defineProperty,__export=(n,e)=>{for(var t in e)__defProp(n,t,{get:e[t],enumerable:!0})},verifiedSymbol$1=Symbol("verified"),isRecord$1=n=>n instanceof Object;function validateEvent$1(n){if(!isRecord$1(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!n.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(n.tags))return!1;for(let e=0;e<n.tags.length;e++){let t=n.tags[e];if(!Array.isArray(t))return!1;for(let r=0;r<t.length;r++)if(typeof t[r]=="object")return!1}return!0}var utils_exports={};__export(utils_exports,{Queue:()=>Queue$1,QueueNode:()=>QueueNode,binarySearch:()=>binarySearch,insertEventIntoAscendingList:()=>insertEventIntoAscendingList,insertEventIntoDescendingList:()=>insertEventIntoDescendingList,normalizeURL:()=>normalizeURL$2,utf8Decoder:()=>utf8Decoder,utf8Encoder:()=>utf8Encoder$1});var utf8Decoder=new TextDecoder("utf-8"),utf8Encoder$1=new TextEncoder;function normalizeURL$2(n){n.indexOf("://")===-1&&(n="wss://"+n);let e=new URL(n);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}function insertEventIntoDescendingList(n,e){const[t,r]=binarySearch(n,s=>e.id===s.id?0:e.created_at===s.created_at?-1:s.created_at-e.created_at);return r||n.splice(t,0,e),n}function insertEventIntoAscendingList(n,e){const[t,r]=binarySearch(n,s=>e.id===s.id?0:e.created_at===s.created_at?-1:e.created_at-s.created_at);return r||n.splice(t,0,e),n}function binarySearch(n,e){let t=0,r=n.length-1;for(;t<=r;){const s=Math.floor((t+r)/2),o=e(n[s]);if(o===0)return[s,!0];o<0?r=s-1:t=s+1}return[t,!1]}var QueueNode=class{constructor(n){g(this,"value");g(this,"next",null);g(this,"prev",null);this.value=n}},Queue$1=class{constructor(){g(this,"first");g(this,"last");this.first=null,this.last=null}enqueue(e){const t=new QueueNode(e);return this.last?this.last===this.first?(this.last=t,this.last.prev=this.first,this.first.next=t):(t.prev=this.last,this.last.next=t,this.last=t):(this.first=t,this.last=t),!0}dequeue(){if(!this.first)return null;if(this.first===this.last){const t=this.first;return this.first=null,this.last=null,t.value}const e=this.first;return this.first=e.next,e.value}},JS$1=class{generateSecretKey(){return schnorr$1.utils.randomPrivateKey()}getPublicKey(e){return bytesToHex$2(schnorr$1.getPublicKey(e))}finalizeEvent(e,t){const r=e;return r.pubkey=bytesToHex$2(schnorr$1.getPublicKey(t)),r.id=getEventHash$2(r),r.sig=bytesToHex$2(schnorr$1.sign(getEventHash$2(r),t)),r[verifiedSymbol$1]=!0,r}verifyEvent(e){if(typeof e[verifiedSymbol$1]=="boolean")return e[verifiedSymbol$1];const t=getEventHash$2(e);if(t!==e.id)return e[verifiedSymbol$1]=!1,!1;try{const r=schnorr$1.verify(e.sig,t,e.pubkey);return e[verifiedSymbol$1]=r,r}catch{return e[verifiedSymbol$1]=!1,!1}}};function serializeEvent$1(n){if(!validateEvent$1(n))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])}function getEventHash$2(n){let e=sha256$1(utf8Encoder$1.encode(serializeEvent$1(n)));return bytesToHex$2(e)}var i$1=new JS$1,generateSecretKey$1=i$1.generateSecretKey,getPublicKey$1=i$1.getPublicKey,finalizeEvent$1=i$1.finalizeEvent,verifyEvent=i$1.verifyEvent,kinds_exports={};__export(kinds_exports,{Application:()=>Application,BadgeAward:()=>BadgeAward,BadgeDefinition:()=>BadgeDefinition,BlockedRelaysList:()=>BlockedRelaysList,BookmarkList:()=>BookmarkList,Bookmarksets:()=>Bookmarksets,Calendar:()=>Calendar,CalendarEventRSVP:()=>CalendarEventRSVP,ChannelCreation:()=>ChannelCreation,ChannelHideMessage:()=>ChannelHideMessage,ChannelMessage:()=>ChannelMessage,ChannelMetadata:()=>ChannelMetadata,ChannelMuteUser:()=>ChannelMuteUser,ClassifiedListing:()=>ClassifiedListing,ClientAuth:()=>ClientAuth,CommunitiesList:()=>CommunitiesList,CommunityDefinition:()=>CommunityDefinition,CommunityPostApproval:()=>CommunityPostApproval,Contacts:()=>Contacts,CreateOrUpdateProduct:()=>CreateOrUpdateProduct,CreateOrUpdateStall:()=>CreateOrUpdateStall,Curationsets:()=>Curationsets,Date:()=>Date2,DirectMessageRelaysList:()=>DirectMessageRelaysList,DraftClassifiedListing:()=>DraftClassifiedListing,DraftLong:()=>DraftLong,Emojisets:()=>Emojisets,EncryptedDirectMessage:()=>EncryptedDirectMessage,EventDeletion:()=>EventDeletion,FileMetadata:()=>FileMetadata,FileServerPreference:()=>FileServerPreference,Followsets:()=>Followsets,GenericRepost:()=>GenericRepost,Genericlists:()=>Genericlists,GiftWrap:()=>GiftWrap,HTTPAuth:()=>HTTPAuth,Handlerinformation:()=>Handlerinformation,Handlerrecommendation:()=>Handlerrecommendation,Highlights:()=>Highlights,InterestsList:()=>InterestsList,Interestsets:()=>Interestsets,JobFeedback:()=>JobFeedback,JobRequest:()=>JobRequest,JobResult:()=>JobResult,Label:()=>Label,LightningPubRPC:()=>LightningPubRPC,LiveChatMessage:()=>LiveChatMessage,LiveEvent:()=>LiveEvent,LongFormArticle:()=>LongFormArticle,Metadata:()=>Metadata,Mutelist:()=>Mutelist,NWCWalletInfo:()=>NWCWalletInfo,NWCWalletRequest:()=>NWCWalletRequest,NWCWalletResponse:()=>NWCWalletResponse,NostrConnect:()=>NostrConnect,OpenTimestamps:()=>OpenTimestamps,Pinlist:()=>Pinlist,PrivateDirectMessage:()=>PrivateDirectMessage,ProblemTracker:()=>ProblemTracker,ProfileBadges:()=>ProfileBadges,PublicChatsList:()=>PublicChatsList,Reaction:()=>Reaction,RecommendRelay:()=>RecommendRelay,RelayList:()=>RelayList,Relaysets:()=>Relaysets,Report:()=>Report,Reporting:()=>Reporting,Repost:()=>Repost,Seal:()=>Seal,SearchRelaysList:()=>SearchRelaysList,ShortTextNote:()=>ShortTextNote,Time:()=>Time,UserEmojiList:()=>UserEmojiList,UserStatuses:()=>UserStatuses,Zap:()=>Zap,ZapGoal:()=>ZapGoal,ZapRequest:()=>ZapRequest,classifyKind:()=>classifyKind,isAddressableKind:()=>isAddressableKind,isEphemeralKind:()=>isEphemeralKind,isKind:()=>isKind,isParameterizedReplaceableKind:()=>isParameterizedReplaceableKind,isRegularKind:()=>isRegularKind,isReplaceableKind:()=>isReplaceableKind});function isRegularKind(n){return 1e3<=n&&n<1e4||[1,2,4,5,6,7,8,16,40,41,42,43,44].includes(n)}function isReplaceableKind(n){return[0,3].includes(n)||1e4<=n&&n<2e4}function isEphemeralKind(n){return 2e4<=n&&n<3e4}function isAddressableKind(n){return 3e4<=n&&n<4e4}var isParameterizedReplaceableKind=isAddressableKind;function classifyKind(n){return isRegularKind(n)?"regular":isReplaceableKind(n)?"replaceable":isEphemeralKind(n)?"ephemeral":isAddressableKind(n)?"parameterized":"unknown"}function isKind(n,e){const t=e instanceof Array?e:[e];return validateEvent$1(n)&&t.includes(n.kind)||!1}var Metadata=0,ShortTextNote=1,RecommendRelay=2,Contacts=3,EncryptedDirectMessage=4,EventDeletion=5,Repost=6,Reaction=7,BadgeAward=8,Seal=13,PrivateDirectMessage=14,GenericRepost=16,ChannelCreation=40,ChannelMetadata=41,ChannelMessage=42,ChannelHideMessage=43,ChannelMuteUser=44,OpenTimestamps=1040,GiftWrap=1059,FileMetadata=1063,LiveChatMessage=1311,ProblemTracker=1971,Report=1984,Reporting=1984,Label=1985,CommunityPostApproval=4550,JobRequest=5999,JobResult=6999,JobFeedback=7e3,ZapGoal=9041,ZapRequest=9734,Zap=9735,Highlights=9802,Mutelist=1e4,Pinlist=10001,RelayList=10002,BookmarkList=10003,CommunitiesList=10004,PublicChatsList=10005,BlockedRelaysList=10006,SearchRelaysList=10007,InterestsList=10015,UserEmojiList=10030,DirectMessageRelaysList=10050,FileServerPreference=10096,NWCWalletInfo=13194,LightningPubRPC=21e3,ClientAuth=22242,NWCWalletRequest=23194,NWCWalletResponse=23195,NostrConnect=24133,HTTPAuth=27235,Followsets=3e4,Genericlists=30001,Relaysets=30002,Bookmarksets=30003,Curationsets=30004,ProfileBadges=30008,BadgeDefinition=30009,Interestsets=30015,CreateOrUpdateStall=30017,CreateOrUpdateProduct=30018,LongFormArticle=30023,DraftLong=30024,Emojisets=30030,Application=30078,LiveEvent=30311,UserStatuses=30315,ClassifiedListing=30402,DraftClassifiedListing=30403,Date2=31922,Time=31923,Calendar=31924,CalendarEventRSVP=31925,Handlerrecommendation=31989,Handlerinformation=31990,CommunityDefinition=34550;function matchFilter(n,e){if(n.ids&&n.ids.indexOf(e.id)===-1||n.kinds&&n.kinds.indexOf(e.kind)===-1||n.authors&&n.authors.indexOf(e.pubkey)===-1)return!1;for(let t in n)if(t[0]==="#"){let r=t.slice(1),s=n[`#${r}`];if(s&&!e.tags.find(([o,a])=>o===t.slice(1)&&s.indexOf(a)!==-1))return!1}return!(n.since&&e.created_at<n.since||n.until&&e.created_at>n.until)}function matchFilters(n,e){for(let t=0;t<n.length;t++)if(matchFilter(n[t],e))return!0;return!1}var fakejson_exports={};__export(fakejson_exports,{getHex64:()=>getHex64,getInt:()=>getInt,getSubscriptionId:()=>getSubscriptionId,matchEventId:()=>matchEventId,matchEventKind:()=>matchEventKind,matchEventPubkey:()=>matchEventPubkey});function getHex64(n,e){let t=e.length+3,r=n.indexOf(`"${e}":`)+t,s=n.slice(r).indexOf('"')+r+1;return n.slice(s,s+64)}function getInt(n,e){let t=e.length,r=n.indexOf(`"${e}":`)+t+3,s=n.slice(r),o=Math.min(s.indexOf(","),s.indexOf("}"));return parseInt(s.slice(0,o),10)}function getSubscriptionId(n){let e=n.slice(0,22).indexOf('"EVENT"');if(e===-1)return null;let t=n.slice(e+7+1).indexOf('"');if(t===-1)return null;let r=e+7+1+t,s=n.slice(r+1,80).indexOf('"');if(s===-1)return null;let o=r+1+s;return n.slice(r+1,o)}function matchEventId(n,e){return e===getHex64(n,"id")}function matchEventPubkey(n,e){return e===getHex64(n,"pubkey")}function matchEventKind(n,e){return e===getInt(n,"kind")}var nip42_exports={};__export(nip42_exports,{makeAuthEvent:()=>makeAuthEvent});function makeAuthEvent(n,e){return{kind:ClientAuth,created_at:Math.floor(Date.now()/1e3),tags:[["relay",n],["challenge",e]],content:""}}async function yieldThread(){return new Promise(n=>{const e=new MessageChannel,t=()=>{e.port1.removeEventListener("message",t),n()};e.port1.addEventListener("message",t),e.port2.postMessage(0),e.port1.start()})}var alwaysTrue=n=>(n[verifiedSymbol$1]=!0,!0),AbstractRelay=class{constructor(n,e){g(this,"url");g(this,"_connected",!1);g(this,"onclose",null);g(this,"onnotice",n=>console.debug(`NOTICE from ${this.url}: ${n}`));g(this,"_onauth",null);g(this,"baseEoseTimeout",4400);g(this,"connectionTimeout",4400);g(this,"publishTimeout",4400);g(this,"openSubs",new Map);g(this,"connectionTimeoutHandle");g(this,"connectionPromise");g(this,"openCountRequests",new Map);g(this,"openEventPublishes",new Map);g(this,"ws");g(this,"incomingMessageQueue",new Queue$1);g(this,"queueRunning",!1);g(this,"challenge");g(this,"authPromise");g(this,"serial",0);g(this,"verifyEvent");g(this,"_WebSocket");this.url=normalizeURL$2(n),this.verifyEvent=e.verifyEvent,this._WebSocket=e.websocketImplementation||WebSocket}static async connect(n,e){const t=new AbstractRelay(n,e);return await t.connect(),t}closeAllSubscriptions(n){for(let[e,t]of this.openSubs)t.close(n);this.openSubs.clear();for(let[e,t]of this.openEventPublishes)t.reject(new Error(n));this.openEventPublishes.clear();for(let[e,t]of this.openCountRequests)t.reject(new Error(n));this.openCountRequests.clear()}get connected(){return this._connected}async connect(){return this.connectionPromise?this.connectionPromise:(this.challenge=void 0,this.authPromise=void 0,this.connectionPromise=new Promise((n,e)=>{this.connectionTimeoutHandle=setTimeout(()=>{var t;e("connection timed out"),this.connectionPromise=void 0,(t=this.onclose)==null||t.call(this),this.closeAllSubscriptions("relay connection timed out")},this.connectionTimeout);try{this.ws=new this._WebSocket(this.url)}catch(t){e(t);return}this.ws.onopen=()=>{clearTimeout(this.connectionTimeoutHandle),this._connected=!0,n()},this.ws.onerror=t=>{var r;e(t.message||"websocket error"),this._connected&&(this._connected=!1,this.connectionPromise=void 0,(r=this.onclose)==null||r.call(this),this.closeAllSubscriptions("relay connection errored"))},this.ws.onclose=async()=>{var t;this._connected&&(this._connected=!1,this.connectionPromise=void 0,(t=this.onclose)==null||t.call(this),this.closeAllSubscriptions("relay connection closed"))},this.ws.onmessage=this._onmessage.bind(this)}),this.connectionPromise)}async runQueue(){for(this.queueRunning=!0;this.handleNext()!==!1;)await yieldThread();this.queueRunning=!1}handleNext(){var t,r,s;const n=this.incomingMessageQueue.dequeue();if(!n)return!1;const e=getSubscriptionId(n);if(e){const o=this.openSubs.get(e);if(!o)return;const a=getHex64(n,"id"),u=(t=o.alreadyHaveEvent)==null?void 0:t.call(o,a);if((r=o.receivedEvent)==null||r.call(o,this,a),u)return}try{let o=JSON.parse(n);switch(o[0]){case"EVENT":{const a=this.openSubs.get(o[1]),u=o[2];this.verifyEvent(u)&&matchFilters(a.filters,u)&&a.onevent(u);return}case"COUNT":{const a=o[1],u=o[2],c=this.openCountRequests.get(a);c&&(c.resolve(u.count),this.openCountRequests.delete(a));return}case"EOSE":{const a=this.openSubs.get(o[1]);if(!a)return;a.receivedEose();return}case"OK":{const a=o[1],u=o[2],c=o[3],l=this.openEventPublishes.get(a);l&&(clearTimeout(l.timeout),u?l.resolve(c):l.reject(new Error(c)),this.openEventPublishes.delete(a));return}case"CLOSED":{const a=o[1],u=this.openSubs.get(a);if(!u)return;u.closed=!0,u.close(o[2]);return}case"NOTICE":this.onnotice(o[1]);return;case"AUTH":{this.challenge=o[1],this.authPromise=void 0,(s=this._onauth)==null||s.call(this,o[1]);return}}}catch{return}}async send(n){if(!this.connectionPromise)throw new Error("sending on closed connection");this.connectionPromise.then(()=>{var e;(e=this.ws)==null||e.send(n)})}async auth(n){if(!this.challenge)throw new Error("can't perform auth, no challenge was received");if(this.authPromise)return this.authPromise;const e=await n(makeAuthEvent(this.url,this.challenge));return this.authPromise=new Promise((t,r)=>{const s=setTimeout(()=>{const o=this.openEventPublishes.get(e.id);o&&(o.reject(new Error("auth timed out")),this.openEventPublishes.delete(e.id))},this.publishTimeout);this.openEventPublishes.set(e.id,{resolve:t,reject:r,timeout:s})}),this.send('["AUTH",'+JSON.stringify(e)+"]"),this.authPromise}async publish(n){const e=new Promise((t,r)=>{const s=setTimeout(()=>{const o=this.openEventPublishes.get(n.id);o&&(o.reject(new Error("publish timed out")),this.openEventPublishes.delete(n.id))},this.publishTimeout);this.openEventPublishes.set(n.id,{resolve:t,reject:r,timeout:s})});return this.send('["EVENT",'+JSON.stringify(n)+"]"),e}async count(n,e){this.serial++;const t=(e==null?void 0:e.id)||"count:"+this.serial,r=new Promise((s,o)=>{this.openCountRequests.set(t,{resolve:s,reject:o})});return this.send('["COUNT","'+t+'",'+JSON.stringify(n).substring(1)),r}subscribe(n,e){const t=this.prepareSubscription(n,e);return t.fire(),t}prepareSubscription(n,e){this.serial++;const t=e.id||(e.label?e.label+":":"sub:")+this.serial,r=new Subscription(this,t,n,e);return this.openSubs.set(t,r),r}close(){var n;this.closeAllSubscriptions("relay connection closed by us"),this._connected=!1,(n=this.ws)==null||n.close()}_onmessage(n){this.incomingMessageQueue.enqueue(n.data),this.queueRunning||this.runQueue()}},Subscription=class{constructor(n,e,t,r){g(this,"relay");g(this,"id");g(this,"closed",!1);g(this,"eosed",!1);g(this,"filters");g(this,"alreadyHaveEvent");g(this,"receivedEvent");g(this,"onevent");g(this,"oneose");g(this,"onclose");g(this,"eoseTimeout");g(this,"eoseTimeoutHandle");this.relay=n,this.filters=t,this.id=e,this.alreadyHaveEvent=r.alreadyHaveEvent,this.receivedEvent=r.receivedEvent,this.eoseTimeout=r.eoseTimeout||n.baseEoseTimeout,this.oneose=r.oneose,this.onclose=r.onclose,this.onevent=r.onevent||(s=>{console.warn(`onevent() callback not defined for subscription '${this.id}' in relay ${this.relay.url}. event received:`,s)})}fire(){this.relay.send('["REQ","'+this.id+'",'+JSON.stringify(this.filters).substring(1)),this.eoseTimeoutHandle=setTimeout(this.receivedEose.bind(this),this.eoseTimeout)}receivedEose(){var n;this.eosed||(clearTimeout(this.eoseTimeoutHandle),this.eosed=!0,(n=this.oneose)==null||n.call(this))}close(n="closed by caller"){var e;!this.closed&&this.relay.connected&&(this.relay.send('["CLOSE",'+JSON.stringify(this.id)+"]"),this.closed=!0),this.relay.openSubs.delete(this.id),(e=this.onclose)==null||e.call(this,n)}},_WebSocket;try{_WebSocket=WebSocket}catch{}var AbstractSimplePool=class{constructor(n){g(this,"relays",new Map);g(this,"seenOn",new Map);g(this,"trackRelays",!1);g(this,"verifyEvent");g(this,"trustedRelayURLs",new Set);g(this,"_WebSocket");this.verifyEvent=n.verifyEvent,this._WebSocket=n.websocketImplementation}async ensureRelay(n,e){n=normalizeURL$2(n);let t=this.relays.get(n);return t||(t=new AbstractRelay(n,{verifyEvent:this.trustedRelayURLs.has(n)?alwaysTrue:this.verifyEvent,websocketImplementation:this._WebSocket}),e!=null&&e.connectionTimeout&&(t.connectionTimeout=e.connectionTimeout),this.relays.set(n,t)),await t.connect(),t}close(n){n.map(normalizeURL$2).forEach(e=>{var t;(t=this.relays.get(e))==null||t.close()})}subscribe(n,e,t){return this.subscribeMap(n.map(r=>({url:r,filter:e})),t)}subscribeMany(n,e,t){return this.subscribeMap(n.flatMap(r=>e.map(s=>({url:r,filter:s}))),t)}subscribeMap(n,e){this.trackRelays&&(e.receivedEvent=(h,f)=>{let p=this.seenOn.get(f);p||(p=new Set,this.seenOn.set(f,p)),p.add(h)});const t=new Set,r=[],s=[];let o=h=>{var f;s[h]||(s[h]=!0,s.filter(p=>p).length===n.length&&((f=e.oneose)==null||f.call(e),o=()=>{}))};const a=[];let u=(h,f)=>{var p;a[h]||(o(h),a[h]=f,a.filter(b=>b).length===n.length&&((p=e.onclose)==null||p.call(e,a),u=()=>{}))};const c=h=>{var p;if((p=e.alreadyHaveEvent)!=null&&p.call(e,h))return!0;const f=t.has(h);return t.add(h),f},l=Promise.all(n.map(async({url:h,filter:f},p)=>{h=normalizeURL$2(h);let b;try{b=await this.ensureRelay(h,{connectionTimeout:e.maxWait?Math.max(e.maxWait*.8,e.maxWait-1e3):void 0})}catch(m){u(p,(m==null?void 0:m.message)||String(m));return}let v=b.subscribe([f],{...e,oneose:()=>o(p),onclose:m=>{m.startsWith("auth-required:")&&e.doauth?b.auth(e.doauth).then(()=>{b.subscribe([f],{...e,oneose:()=>o(p),onclose:y=>{u(p,y)},alreadyHaveEvent:c,eoseTimeout:e.maxWait})}).catch(y=>{u(p,`auth was required and attempted, but failed with: ${y}`)}):u(p,m)},alreadyHaveEvent:c,eoseTimeout:e.maxWait});r.push(v)}));return{async close(){await l,r.forEach(h=>{h.close()})}}}subscribeManyMap(n,e){this.trackRelays&&(e.receivedEvent=(f,p)=>{let b=this.seenOn.get(p);b||(b=new Set,this.seenOn.set(p,b)),b.add(f)});const t=new Set,r=[],s=Object.keys(n).length,o=[];let a=f=>{var p;o[f]||(o[f]=!0,o.filter(b=>b).length===s&&((p=e.oneose)==null||p.call(e),a=()=>{}))};const u=[];let c=(f,p)=>{var b;u[f]||(a(f),u[f]=p,u.filter(v=>v).length===s&&((b=e.onclose)==null||b.call(e,u),c=()=>{}))};const l=f=>{var b;if((b=e.alreadyHaveEvent)!=null&&b.call(e,f))return!0;const p=t.has(f);return t.add(f),p},h=Promise.all(Object.entries(n).map(async(f,p,b)=>{if(b.indexOf(f)!==p){c(p,"duplicate url");return}let[v,m]=f;v=normalizeURL$2(v);let y;try{y=await this.ensureRelay(v,{connectionTimeout:e.maxWait?Math.max(e.maxWait*.8,e.maxWait-1e3):void 0})}catch(x){c(p,(x==null?void 0:x.message)||String(x));return}let w=y.subscribe(m,{...e,oneose:()=>a(p),onclose:x=>{x.startsWith("auth-required:")&&e.doauth?y.auth(e.doauth).then(()=>{y.subscribe(m,{...e,oneose:()=>a(p),onclose:k=>{c(p,k)},alreadyHaveEvent:l,eoseTimeout:e.maxWait})}).catch(k=>{c(p,`auth was required and attempted, but failed with: ${k}`)}):c(p,x)},alreadyHaveEvent:l,eoseTimeout:e.maxWait});r.push(w)}));return{async close(){await h,r.forEach(f=>{f.close()})}}}subscribeEose(n,e,t){const r=this.subscribe(n,e,{...t,oneose(){r.close()}});return r}subscribeManyEose(n,e,t){const r=this.subscribeMany(n,e,{...t,oneose(){r.close()}});return r}async querySync(n,e,t){return new Promise(async r=>{const s=[];this.subscribeEose(n,e,{...t,onevent(o){s.push(o)},onclose(o){r(s)}})})}async get(n,e,t){e.limit=1;const r=await this.querySync(n,e,t);return r.sort((s,o)=>o.created_at-s.created_at),r[0]||null}publish(n,e){return n.map(normalizeURL$2).map(async(t,r,s)=>{if(s.indexOf(t)!==r)return Promise.reject("duplicate url");let o=await this.ensureRelay(t);return o.publish(e).then(a=>{if(this.trackRelays){let u=this.seenOn.get(e.id);u||(u=new Set,this.seenOn.set(e.id,u)),u.add(o)}return a})})}listConnectionStatus(){const n=new Map;return this.relays.forEach((e,t)=>n.set(t,e.connected)),n}destroy(){this.relays.forEach(n=>n.close()),this.relays=new Map}},_WebSocket2;try{_WebSocket2=WebSocket}catch{}var SimplePool=class extends AbstractSimplePool{constructor(){super({verifyEvent,websocketImplementation:_WebSocket2})}},nip19_exports={};__export(nip19_exports,{BECH32_REGEX:()=>BECH32_REGEX$1,Bech32MaxSize:()=>Bech32MaxSize,NostrTypeGuard:()=>NostrTypeGuard,decode:()=>decode,decodeNostrURI:()=>decodeNostrURI,encodeBytes:()=>encodeBytes,naddrEncode:()=>naddrEncode,neventEncode:()=>neventEncode,noteEncode:()=>noteEncode,nprofileEncode:()=>nprofileEncode,npubEncode:()=>npubEncode,nsecEncode:()=>nsecEncode});var NostrTypeGuard={isNProfile:n=>/^nprofile1[a-z\d]+$/.test(n||""),isNEvent:n=>/^nevent1[a-z\d]+$/.test(n||""),isNAddr:n=>/^naddr1[a-z\d]+$/.test(n||""),isNSec:n=>/^nsec1[a-z\d]{58}$/.test(n||""),isNPub:n=>/^npub1[a-z\d]{58}$/.test(n||""),isNote:n=>/^note1[a-z\d]+$/.test(n||""),isNcryptsec:n=>/^ncryptsec1[a-z\d]+$/.test(n||"")},Bech32MaxSize=5e3,BECH32_REGEX$1=/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/;function integerToUint8Array(n){const e=new Uint8Array(4);return e[0]=n>>24&255,e[1]=n>>16&255,e[2]=n>>8&255,e[3]=n&255,e}function decodeNostrURI(n){try{return n.startsWith("nostr:")&&(n=n.substring(6)),decode(n)}catch{return{type:"invalid",data:null}}}function decode(n){var s,o,a,u,c,l,h;let{prefix:e,words:t}=bech32$1.decode(n,Bech32MaxSize),r=new Uint8Array(bech32$1.fromWords(t));switch(e){case"nprofile":{let f=parseTLV(r);if(!((s=f[0])!=null&&s[0]))throw new Error("missing TLV 0 for nprofile");if(f[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:bytesToHex$2(f[0][0]),relays:f[1]?f[1].map(p=>utf8Decoder.decode(p)):[]}}}case"nevent":{let f=parseTLV(r);if(!((o=f[0])!=null&&o[0]))throw new Error("missing TLV 0 for nevent");if(f[0][0].length!==32)throw new Error("TLV 0 should be 32 bytes");if(f[2]&&f[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(f[3]&&f[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:bytesToHex$2(f[0][0]),relays:f[1]?f[1].map(p=>utf8Decoder.decode(p)):[],author:(a=f[2])!=null&&a[0]?bytesToHex$2(f[2][0]):void 0,kind:(u=f[3])!=null&&u[0]?parseInt(bytesToHex$2(f[3][0]),16):void 0}}}case"naddr":{let f=parseTLV(r);if(!((c=f[0])!=null&&c[0]))throw new Error("missing TLV 0 for naddr");if(!((l=f[2])!=null&&l[0]))throw new Error("missing TLV 2 for naddr");if(f[2][0].length!==32)throw new Error("TLV 2 should be 32 bytes");if(!((h=f[3])!=null&&h[0]))throw new Error("missing TLV 3 for naddr");if(f[3][0].length!==4)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:utf8Decoder.decode(f[0][0]),pubkey:bytesToHex$2(f[2][0]),kind:parseInt(bytesToHex$2(f[3][0]),16),relays:f[1]?f[1].map(p=>utf8Decoder.decode(p)):[]}}}case"nsec":return{type:e,data:r};case"npub":case"note":return{type:e,data:bytesToHex$2(r)};default:throw new Error(`unknown prefix ${e}`)}}function parseTLV(n){let e={},t=n;for(;t.length>0;){let r=t[0],s=t[1],o=t.slice(2,2+s);if(t=t.slice(2+s),o.length<s)throw new Error(`not enough data to read on TLV ${r}`);e[r]=e[r]||[],e[r].push(o)}return e}function nsecEncode(n){return encodeBytes("nsec",n)}function npubEncode(n){return encodeBytes("npub",hexToBytes$2(n))}function noteEncode(n){return encodeBytes("note",hexToBytes$2(n))}function encodeBech32(n,e){let t=bech32$1.toWords(e);return bech32$1.encode(n,t,Bech32MaxSize)}function encodeBytes(n,e){return encodeBech32(n,e)}function nprofileEncode(n){let e=encodeTLV({0:[hexToBytes$2(n.pubkey)],1:(n.relays||[]).map(t=>utf8Encoder$1.encode(t))});return encodeBech32("nprofile",e)}function neventEncode(n){let e;n.kind!==void 0&&(e=integerToUint8Array(n.kind));let t=encodeTLV({0:[hexToBytes$2(n.id)],1:(n.relays||[]).map(r=>utf8Encoder$1.encode(r)),2:n.author?[hexToBytes$2(n.author)]:[],3:e?[new Uint8Array(e)]:[]});return encodeBech32("nevent",t)}function naddrEncode(n){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,n.kind,!1);let t=encodeTLV({0:[utf8Encoder$1.encode(n.identifier)],1:(n.relays||[]).map(r=>utf8Encoder$1.encode(r)),2:[hexToBytes$2(n.pubkey)],3:[new Uint8Array(e)]});return encodeBech32("naddr",t)}function encodeTLV(n){let e=[];return Object.entries(n).reverse().forEach(([t,r])=>{r.forEach(s=>{let o=new Uint8Array(s.length+2);o.set([parseInt(t)],0),o.set([s.length],1),o.set(s,2),e.push(o)})}),concatBytes$2(...e)}var nip04_exports={};__export(nip04_exports,{decrypt:()=>decrypt$1,encrypt:()=>encrypt$1});function encrypt$1(n,e,t){const r=n instanceof Uint8Array?bytesToHex$2(n):n,s=secp256k1$1.getSharedSecret(r,"02"+e),o=getNormalizedX(s);let a=Uint8Array.from(randomBytes$1(16)),u=utf8Encoder$1.encode(t),c=cbc(o,a).encrypt(u),l=base64.encode(new Uint8Array(c)),h=base64.encode(new Uint8Array(a.buffer));return`${l}?iv=${h}`}function decrypt$1(n,e,t){const r=n instanceof Uint8Array?bytesToHex$2(n):n;let[s,o]=t.split("?iv="),a=secp256k1$1.getSharedSecret(r,"02"+e),u=getNormalizedX(a),c=base64.decode(o),l=base64.decode(s),h=cbc(u,c).decrypt(l);return utf8Decoder.decode(h)}function getNormalizedX(n){return n.slice(1,33)}var nip05_exports={};__export(nip05_exports,{NIP05_REGEX:()=>NIP05_REGEX$1,isNip05:()=>isNip05,isValid:()=>isValid,queryProfile:()=>queryProfile,searchDomain:()=>searchDomain,useFetchImplementation:()=>useFetchImplementation});var NIP05_REGEX$1=/^(?:([\w.+-]+)@)?([\w_-]+(\.[\w_-]+)+)$/,isNip05=n=>NIP05_REGEX$1.test(n||""),_fetch;try{_fetch=fetch}catch(n){}function useFetchImplementation(n){_fetch=n}async function searchDomain(n,e=""){try{const t=`https://${n}/.well-known/nostr.json?name=${e}`,r=await _fetch(t,{redirect:"manual"});if(r.status!==200)throw Error("Wrong response code");return(await r.json()).names}catch{return{}}}async function queryProfile(n){var s;const e=n.match(NIP05_REGEX$1);if(!e)return null;const[,t="_",r]=e;try{const o=`https://${r}/.well-known/nostr.json?name=${t}`,a=await _fetch(o,{redirect:"manual"});if(a.status!==200)throw Error("Wrong response code");const u=await a.json(),c=u.names[t];return c?{pubkey:c,relays:(s=u.relays)==null?void 0:s[c]}:null}catch{return null}}async function isValid(n,e){const t=await queryProfile(e);return t?t.pubkey===n:!1}var nip10_exports={};__export(nip10_exports,{parse:()=>parse});function parse(n){const e={reply:void 0,root:void 0,mentions:[],profiles:[],quotes:[]};let t,r;for(let s=n.tags.length-1;s>=0;s--){const o=n.tags[s];if(o[0]==="e"&&o[1]){const[a,u,c,l,h]=o,f={id:u,relays:c?[c]:[],author:h};if(l==="root"){e.root=f;continue}if(l==="reply"){e.reply=f;continue}if(l==="mention"){e.mentions.push(f);continue}t?r=f:t=f,e.mentions.push(f);continue}if(o[0]==="q"&&o[1]){const[a,u,c]=o;e.quotes.push({id:u,relays:c?[c]:[]})}if(o[0]==="p"&&o[1]){e.profiles.push({pubkey:o[1],relays:o[2]?[o[2]]:[]});continue}}return e.root||(e.root=r||t||e.reply),e.reply||(e.reply=t||e.root),[e.reply,e.root].forEach(s=>{if(!s)return;let o=e.mentions.indexOf(s);if(o!==-1&&e.mentions.splice(o,1),s.author){let a=e.profiles.find(u=>u.pubkey===s.author);a&&a.relays&&(s.relays||(s.relays=[]),a.relays.forEach(u=>{var c;((c=s.relays)==null?void 0:c.indexOf(u))===-1&&s.relays.push(u)}),a.relays=s.relays)}}),e.mentions.forEach(s=>{if(s.author){let o=e.profiles.find(a=>a.pubkey===s.author);o&&o.relays&&(s.relays||(s.relays=[]),o.relays.forEach(a=>{s.relays.indexOf(a)===-1&&s.relays.push(a)}),o.relays=s.relays)}}),e}var nip11_exports={};__export(nip11_exports,{fetchRelayInformation:()=>fetchRelayInformation,useFetchImplementation:()=>useFetchImplementation2});var _fetch2;try{_fetch2=fetch}catch{}function useFetchImplementation2(n){_fetch2=n}async function fetchRelayInformation(n){return await(await fetch(n.replace("ws://","http://").replace("wss://","https://"),{headers:{Accept:"application/nostr+json"}})).json()}var nip13_exports={};__export(nip13_exports,{fastEventHash:()=>fastEventHash,getPow:()=>getPow,minePow:()=>minePow});function getPow(n){let e=0;for(let t=0;t<64;t+=8){const r=parseInt(n.substring(t,t+8),16);if(r===0)e+=32;else{e+=Math.clz32(r);break}}return e}function minePow(n,e){let t=0;const r=n,s=["nonce",t.toString(),e.toString()];for(r.tags.push(s);;){const o=Math.floor(new Date().getTime()/1e3);if(o!==r.created_at&&(t=0,r.created_at=o),s[1]=(++t).toString(),r.id=fastEventHash(r),getPow(r.id)>=e)break}return r}function fastEventHash(n){return bytesToHex$2(sha256$1(utf8Encoder$1.encode(JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content]))))}var nip17_exports={};__export(nip17_exports,{unwrapEvent:()=>unwrapEvent2,unwrapManyEvents:()=>unwrapManyEvents2,wrapEvent:()=>wrapEvent2,wrapManyEvents:()=>wrapManyEvents2});var nip59_exports={};__export(nip59_exports,{createRumor:()=>createRumor,createSeal:()=>createSeal,createWrap:()=>createWrap,unwrapEvent:()=>unwrapEvent,unwrapManyEvents:()=>unwrapManyEvents,wrapEvent:()=>wrapEvent$1,wrapManyEvents:()=>wrapManyEvents});var nip44_exports={};__export(nip44_exports,{decrypt:()=>decrypt2,encrypt:()=>encrypt2,getConversationKey:()=>getConversationKey,v2:()=>v2});var minPlaintextSize=1,maxPlaintextSize=65535;function getConversationKey(n,e){const t=secp256k1$1.getSharedSecret(n,"02"+e).subarray(1,33);return extract(sha256$1,t,"nip44-v2")}function getMessageKeys(n,e){const t=expand(sha256$1,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function calcPaddedLen(n){if(!Number.isSafeInteger(n)||n<1)throw new Error("expected positive integer");if(n<=32)return 32;const e=1<<Math.floor(Math.log2(n-1))+1,t=e<=256?32:e/8;return t*(Math.floor((n-1)/t)+1)}function writeU16BE(n){if(!Number.isSafeInteger(n)||n<minPlaintextSize||n>maxPlaintextSize)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");const e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,n,!1),e}function pad(n){const e=utf8Encoder$1.encode(n),t=e.length,r=writeU16BE(t),s=new Uint8Array(calcPaddedLen(t)-t);return concatBytes$2(r,e,s)}function unpad(n){const e=new DataView(n.buffer).getUint16(0),t=n.subarray(2,2+e);if(e<minPlaintextSize||e>maxPlaintextSize||t.length!==e||n.length!==2+calcPaddedLen(e))throw new Error("invalid padding");return utf8Decoder.decode(t)}function hmacAad(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");const r=concatBytes$2(t,e);return hmac$1(sha256$1,n,r)}function decodePayload(n){if(typeof n!="string")throw new Error("payload must be a valid string");const e=n.length;if(e<132||e>87472)throw new Error("invalid payload length: "+e);if(n[0]==="#")throw new Error("unknown encryption version");let t;try{t=base64.decode(n)}catch(o){throw new Error("invalid base64: "+o.message)}const r=t.length;if(r<99||r>65603)throw new Error("invalid data length: "+r);const s=t[0];if(s!==2)throw new Error("unknown encryption version "+s);return{nonce:t.subarray(1,33),ciphertext:t.subarray(33,-32),mac:t.subarray(-32)}}function encrypt2(n,e,t=randomBytes$1(32)){const{chacha_key:r,chacha_nonce:s,hmac_key:o}=getMessageKeys(e,t),a=pad(n),u=chacha20(r,s,a),c=hmacAad(o,u,t);return base64.encode(concatBytes$2(new Uint8Array([2]),t,u,c))}function decrypt2(n,e){const{nonce:t,ciphertext:r,mac:s}=decodePayload(n),{chacha_key:o,chacha_nonce:a,hmac_key:u}=getMessageKeys(e,t),c=hmacAad(u,r,t);if(!equalBytes$1(c,s))throw new Error("invalid MAC");const l=chacha20(o,a,r);return unpad(l)}var v2={utils:{getConversationKey,calcPaddedLen},encrypt:encrypt2,decrypt:decrypt2},TWO_DAYS=2*24*60*60,now$1=()=>Math.round(Date.now()/1e3),randomNow=()=>Math.round(now$1()-Math.random()*TWO_DAYS),nip44ConversationKey=(n,e)=>getConversationKey(n,e),nip44Encrypt=(n,e,t)=>encrypt2(JSON.stringify(n),nip44ConversationKey(e,t)),nip44Decrypt=(n,e)=>JSON.parse(decrypt2(n.content,nip44ConversationKey(e,n.pubkey)));function createRumor(n,e){const t={created_at:now$1(),content:"",tags:[],...n,pubkey:getPublicKey$1(e)};return t.id=getEventHash$2(t),t}function createSeal(n,e,t){return finalizeEvent$1({kind:Seal,content:nip44Encrypt(n,e,t),created_at:randomNow(),tags:[]},e)}function createWrap(n,e){const t=generateSecretKey$1();return finalizeEvent$1({kind:GiftWrap,content:nip44Encrypt(n,t,e),created_at:randomNow(),tags:[["p",e]]},t)}function wrapEvent$1(n,e,t){const r=createRumor(n,e),s=createSeal(r,e,t);return createWrap(s,t)}function wrapManyEvents(n,e,t){if(!t||t.length===0)throw new Error("At least one recipient is required.");const r=getPublicKey$1(e),s=[wrapEvent$1(n,e,r)];return t.forEach(o=>{s.push(wrapEvent$1(n,e,o))}),s}function unwrapEvent(n,e){const t=nip44Decrypt(n,e);return nip44Decrypt(t,e)}function unwrapManyEvents(n,e){let t=[];return n.forEach(r=>{t.push(unwrapEvent(r,e))}),t.sort((r,s)=>r.created_at-s.created_at),t}function createEvent(n,e,t,r){const s={created_at:Math.ceil(Date.now()/1e3),kind:PrivateDirectMessage,tags:[],content:e};return(Array.isArray(n)?n:[n]).forEach(({publicKey:a,relayUrl:u})=>{s.tags.push(u?["p",a,u]:["p",a])}),r&&s.tags.push(["e",r.eventId,r.relayUrl||"","reply"]),t&&s.tags.push(["subject",t]),s}function wrapEvent2(n,e,t,r,s){const o=createEvent(e,t,r,s);return wrapEvent$1(o,n,e.publicKey)}function wrapManyEvents2(n,e,t,r,s){if(!e||e.length===0)throw new Error("At least one recipient is required.");return[{publicKey:getPublicKey$1(n)},...e].map(a=>wrapEvent2(n,a,t,r,s))}var unwrapEvent2=unwrapEvent,unwrapManyEvents2=unwrapManyEvents,nip18_exports={};__export(nip18_exports,{finishRepostEvent:()=>finishRepostEvent,getRepostedEvent:()=>getRepostedEvent,getRepostedEventPointer:()=>getRepostedEventPointer});function finishRepostEvent(n,e,t,r){var a;let s;const o=[...n.tags??[],["e",e.id,t],["p",e.pubkey]];return e.kind===ShortTextNote?s=Repost:(s=GenericRepost,o.push(["k",String(e.kind)])),finalizeEvent$1({kind:s,tags:o,content:n.content===""||(a=e.tags)!=null&&a.find(u=>u[0]==="-")?"":JSON.stringify(e),created_at:n.created_at},r)}function getRepostedEventPointer(n){if(![Repost,GenericRepost].includes(n.kind))return;let e,t;for(let r=n.tags.length-1;r>=0&&(e===void 0||t===void 0);r--){const s=n.tags[r];s.length>=2&&(s[0]==="e"&&e===void 0?e=s:s[0]==="p"&&t===void 0&&(t=s))}if(e!==void 0)return{id:e[1],relays:[e[2],t==null?void 0:t[2]].filter(r=>typeof r=="string"),author:t==null?void 0:t[1]}}function getRepostedEvent(n,{skipVerification:e}={}){const t=getRepostedEventPointer(n);if(t===void 0||n.content==="")return;let r;try{r=JSON.parse(n.content)}catch{return}if(r.id===t.id&&!(!e&&!verifyEvent(r)))return r}var nip21_exports={};__export(nip21_exports,{NOSTR_URI_REGEX:()=>NOSTR_URI_REGEX,parse:()=>parse2,test:()=>test});var NOSTR_URI_REGEX=new RegExp(`nostr:(${BECH32_REGEX$1.source})`);function test(n){return typeof n=="string"&&new RegExp(`^${NOSTR_URI_REGEX.source}$`).test(n)}function parse2(n){const e=n.match(new RegExp(`^${NOSTR_URI_REGEX.source}$`));if(!e)throw new Error(`Invalid Nostr URI: ${n}`);return{uri:e[0],value:e[1],decoded:decode(e[1])}}var nip25_exports={};__export(nip25_exports,{finishReactionEvent:()=>finishReactionEvent,getReactedEventPointer:()=>getReactedEventPointer});function finishReactionEvent(n,e,t){const r=e.tags.filter(s=>s.length>=2&&(s[0]==="e"||s[0]==="p"));return finalizeEvent$1({...n,kind:Reaction,tags:[...n.tags??[],...r,["e",e.id],["p",e.pubkey]],content:n.content??"+"},t)}function getReactedEventPointer(n){if(n.kind!==Reaction)return;let e,t;for(let r=n.tags.length-1;r>=0&&(e===void 0||t===void 0);r--){const s=n.tags[r];s.length>=2&&(s[0]==="e"&&e===void 0?e=s:s[0]==="p"&&t===void 0&&(t=s))}if(!(e===void 0||t===void 0))return{id:e[1],relays:[e[2],t[2]].filter(r=>r!==void 0),author:t[1]}}var nip27_exports={};__export(nip27_exports,{parse:()=>parse3});var noCharacter=/\W/m,noURLCharacter=/\W |\W$|$|,| /m;function*parse3(n){const e=n.length;let t=0,r=0;for(;r<e;){let s=n.indexOf(":",r);if(s===-1)break;if(n.substring(s-5,s)==="nostr"){const o=n.substring(s+60).match(noCharacter),a=o?s+60+o.index:e;try{let u,{data:c,type:l}=decode(n.substring(s+1,a));switch(l){case"npub":u={pubkey:c};break;case"nsec":case"note":r=a+1;continue;default:u=c}t!==s-5&&(yield{type:"text",text:n.substring(t,s-5)}),yield{type:"reference",pointer:u},r=a,t=r;continue}catch{r=s+1;continue}}else if(n.substring(s-5,s)==="https"||n.substring(s-4,s)==="http"){const o=n.substring(s+4).match(noURLCharacter),a=o?s+4+o.index:e,u=n[s-1]==="s"?5:4;try{let c=new URL(n.substring(s-u,a));if(c.hostname.indexOf(".")===-1)throw new Error("invalid url");if(t!==s-u&&(yield{type:"text",text:n.substring(t,s-u)}),c.pathname.endsWith(".png")||c.pathname.endsWith(".jpg")||c.pathname.endsWith(".jpeg")||c.pathname.endsWith(".gif")||c.pathname.endsWith(".webp")){yield{type:"image",url:c.toString()},r=a,t=r;continue}if(c.pathname.endsWith(".mp4")||c.pathname.endsWith(".avi")||c.pathname.endsWith(".webm")||c.pathname.endsWith(".mkv")){yield{type:"video",url:c.toString()},r=a,t=r;continue}if(c.pathname.endsWith(".mp3")||c.pathname.endsWith(".aac")||c.pathname.endsWith(".ogg")||c.pathname.endsWith(".opus")){yield{type:"audio",url:c.toString()},r=a,t=r;continue}yield{type:"url",url:c.toString()},r=a,t=r;continue}catch{r=a+1;continue}}else if(n.substring(s-3,s)==="wss"||n.substring(s-2,s)==="ws"){const o=n.substring(s+4).match(noURLCharacter),a=o?s+4+o.index:e,u=n[s-1]==="s"?3:2;try{let c=new URL(n.substring(s-u,a));if(c.hostname.indexOf(".")===-1)throw new Error("invalid ws url");t!==s-u&&(yield{type:"text",text:n.substring(t,s-u)}),yield{type:"relay",url:c.toString()},r=a,t=r;continue}catch{r=a+1;continue}}else{r=s+1;continue}}t!==e&&(yield{type:"text",text:n.substring(t)})}var nip28_exports={};__export(nip28_exports,{channelCreateEvent:()=>channelCreateEvent,channelHideMessageEvent:()=>channelHideMessageEvent,channelMessageEvent:()=>channelMessageEvent,channelMetadataEvent:()=>channelMetadataEvent,channelMuteUserEvent:()=>channelMuteUserEvent});var channelCreateEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelCreation,tags:[...n.tags??[]],content:t,created_at:n.created_at},e)},channelMetadataEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelMetadata,tags:[["e",n.channel_create_event_id],...n.tags??[]],content:t,created_at:n.created_at},e)},channelMessageEvent=(n,e)=>{const t=[["e",n.channel_create_event_id,n.relay_url,"root"]];return n.reply_to_channel_message_event_id&&t.push(["e",n.reply_to_channel_message_event_id,n.relay_url,"reply"]),finalizeEvent$1({kind:ChannelMessage,tags:[...t,...n.tags??[]],content:n.content,created_at:n.created_at},e)},channelHideMessageEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelHideMessage,tags:[["e",n.channel_message_event_id],...n.tags??[]],content:t,created_at:n.created_at},e)},channelMuteUserEvent=(n,e)=>{let t;if(typeof n.content=="object")t=JSON.stringify(n.content);else if(typeof n.content=="string")t=n.content;else return;return finalizeEvent$1({kind:ChannelMuteUser,tags:[["p",n.pubkey_to_mute],...n.tags??[]],content:t,created_at:n.created_at},e)},nip30_exports={};__export(nip30_exports,{EMOJI_SHORTCODE_REGEX:()=>EMOJI_SHORTCODE_REGEX,matchAll:()=>matchAll,regex:()=>regex$1,replaceAll:()=>replaceAll});var EMOJI_SHORTCODE_REGEX=/:(\w+):/,regex$1=()=>new RegExp(`\\B${EMOJI_SHORTCODE_REGEX.source}\\B`,"g");function*matchAll(n){const e=n.matchAll(regex$1());for(const t of e)try{const[r,s]=t;yield{shortcode:r,name:s,start:t.index,end:t.index+r.length}}catch{}}function replaceAll(n,e){return n.replaceAll(regex$1(),(t,r)=>e({shortcode:t,name:r}))}var nip39_exports={};__export(nip39_exports,{useFetchImplementation:()=>useFetchImplementation3,validateGithub:()=>validateGithub});var _fetch3;try{_fetch3=fetch}catch{}function useFetchImplementation3(n){_fetch3=n}async function validateGithub(n,e,t){try{return await(await _fetch3(`https://gist.github.com/${e}/${t}/raw`)).text()===`Verifying that I control the following Nostr public key: ${n}`}catch{return!1}}var nip47_exports={};__export(nip47_exports,{makeNwcRequestEvent:()=>makeNwcRequestEvent,parseConnectionString:()=>parseConnectionString});function parseConnectionString(n){const{pathname:e,searchParams:t}=new URL(n),r=e,s=t.get("relay"),o=t.get("secret");if(!r||!s||!o)throw new Error("invalid connection string");return{pubkey:r,relay:s,secret:o}}async function makeNwcRequestEvent(n,e,t){const s=await encrypt$1(e,n,JSON.stringify({method:"pay_invoice",params:{invoice:t}})),o={kind:NWCWalletRequest,created_at:Math.round(Date.now()/1e3),content:s,tags:[["p",n]]};return finalizeEvent$1(o,e)}var nip54_exports={};__export(nip54_exports,{normalizeIdentifier:()=>normalizeIdentifier});function normalizeIdentifier(n){return n=n.trim().toLowerCase(),n=n.normalize("NFKC"),Array.from(n).map(e=>new RegExp("\\p{Letter}","u").test(e)||new RegExp("\\p{Number}","u").test(e)?e:"-").join("")}var nip57_exports={};__export(nip57_exports,{getZapEndpoint:()=>getZapEndpoint$1,makeZapReceipt:()=>makeZapReceipt,makeZapRequest:()=>makeZapRequest,useFetchImplementation:()=>useFetchImplementation4,validateZapRequest:()=>validateZapRequest});var _fetch4;try{_fetch4=fetch}catch{}function useFetchImplementation4(n){_fetch4=n}async function getZapEndpoint$1(n){try{let e="",{lud06:t,lud16:r}=JSON.parse(n.content);if(t){let{words:a}=bech32$1.decode(t,1e3),u=bech32$1.fromWords(a);e=utf8Decoder.decode(u)}else if(r){let[a,u]=r.split("@");e=new URL(`/.well-known/lnurlp/${a}`,`https://${u}`).toString()}else return null;let o=await(await _fetch4(e)).json();if(o.allowsNostr&&o.nostrPubkey)return o.callback}catch{}return null}function makeZapRequest({profile:n,event:e,amount:t,relays:r,comment:s=""}){if(!t)throw new Error("amount not given");if(!n)throw new Error("profile not given");let o={kind:9734,created_at:Math.round(Date.now()/1e3),content:s,tags:[["p",n],["amount",t.toString()],["relays",...r]]};if(e&&typeof e=="string"&&o.tags.push(["e",e]),e&&typeof e=="object"){if(isReplaceableKind(e.kind)){const a=["a",`${e.kind}:${e.pubkey}:`];o.tags.push(a)}else if(isAddressableKind(e.kind)){let a=e.tags.find(([c,l])=>c==="d"&&l);if(!a)throw new Error("d tag not found or is empty");const u=["a",`${e.kind}:${e.pubkey}:${a[1]}`];o.tags.push(u)}}return o}function validateZapRequest(n){let e;try{e=JSON.parse(n)}catch{return"Invalid zap request JSON."}if(!validateEvent$1(e))return"Zap request is not a valid Nostr event.";if(!verifyEvent(e))return"Invalid signature on zap request.";let t=e.tags.find(([o,a])=>o==="p"&&a);if(!t)return"Zap request doesn't have a 'p' tag.";if(!t[1].match(/^[a-f0-9]{64}$/))return"Zap request 'p' tag is not valid hex.";let r=e.tags.find(([o,a])=>o==="e"&&a);return r&&!r[1].match(/^[a-f0-9]{64}$/)?"Zap request 'e' tag is not valid hex.":e.tags.find(([o,a])=>o==="relays"&&a)?null:"Zap request doesn't have a 'relays' tag."}function makeZapReceipt({zapRequest:n,preimage:e,bolt11:t,paidAt:r}){let s=JSON.parse(n),o=s.tags.filter(([u])=>u==="e"||u==="p"||u==="a"),a={kind:9735,created_at:Math.round(r.getTime()/1e3),content:"",tags:[...o,["P",s.pubkey],["bolt11",t],["description",n]]};return e&&a.tags.push(["preimage",e]),a}var nip98_exports={};__export(nip98_exports,{getToken:()=>getToken,hashPayload:()=>hashPayload,unpackEventFromToken:()=>unpackEventFromToken,validateEvent:()=>validateEvent2,validateEventKind:()=>validateEventKind,validateEventMethodTag:()=>validateEventMethodTag,validateEventPayloadTag:()=>validateEventPayloadTag,validateEventTimestamp:()=>validateEventTimestamp,validateEventUrlTag:()=>validateEventUrlTag,validateToken:()=>validateToken});var _authorizationScheme="Nostr ";async function getToken(n,e,t,r=!1,s){const o={kind:HTTPAuth,tags:[["u",n],["method",e]],created_at:Math.round(new Date().getTime()/1e3),content:""};s&&o.tags.push(["payload",hashPayload(s)]);const a=await t(o);return(r?_authorizationScheme:"")+base64.encode(utf8Encoder$1.encode(JSON.stringify(a)))}async function validateToken(n,e,t){const r=await unpackEventFromToken(n).catch(o=>{throw o});return await validateEvent2(r,e,t).catch(o=>{throw o})}async function unpackEventFromToken(n){if(!n)throw new Error("Missing token");n=n.replace(_authorizationScheme,"");const e=utf8Decoder.decode(base64.decode(n));if(!e||e.length===0||!e.startsWith("{"))throw new Error("Invalid token");return JSON.parse(e)}function validateEventTimestamp(n){return n.created_at?Math.round(new Date().getTime()/1e3)-n.created_at<60:!1}function validateEventKind(n){return n.kind===HTTPAuth}function validateEventUrlTag(n,e){const t=n.tags.find(r=>r[0]==="u");return t?t.length>0&&t[1]===e:!1}function validateEventMethodTag(n,e){const t=n.tags.find(r=>r[0]==="method");return t?t.length>0&&t[1].toLowerCase()===e.toLowerCase():!1}function hashPayload(n){const e=sha256$1(utf8Encoder$1.encode(JSON.stringify(n)));return bytesToHex$2(e)}function validateEventPayloadTag(n,e){const t=n.tags.find(s=>s[0]==="payload");if(!t)return!1;const r=hashPayload(e);return t.length>0&&t[1]===r}async function validateEvent2(n,e,t,r){if(!verifyEvent(n))throw new Error("Invalid nostr event, signature invalid");if(!validateEventKind(n))throw new Error("Invalid nostr event, kind invalid");if(!validateEventTimestamp(n))throw new Error("Invalid nostr event, created_at timestamp invalid");if(!validateEventUrlTag(n,e))throw new Error("Invalid nostr event, url tag invalid");if(!validateEventMethodTag(n,t))throw new Error("Invalid nostr event, method tag invalid");if(r&&typeof r=="object"&&Object.keys(r).length>0&&!validateEventPayloadTag(n,r))throw new Error("Invalid nostr event, payload tag does not match request body hash");return!0}const index$2=Object.freeze(Object.defineProperty({__proto__:null,SimplePool,finalizeEvent:finalizeEvent$1,fj:fakejson_exports,generateSecretKey:generateSecretKey$1,getEventHash:getEventHash$2,getPublicKey:getPublicKey$1,kinds:kinds_exports,matchFilter,matchFilters,nip04:nip04_exports,nip05:nip05_exports,nip10:nip10_exports,nip11:nip11_exports,nip13:nip13_exports,nip17:nip17_exports,nip18:nip18_exports,nip19:nip19_exports,nip21:nip21_exports,nip25:nip25_exports,nip27:nip27_exports,nip28:nip28_exports,nip30:nip30_exports,nip39:nip39_exports,nip42:nip42_exports,nip44:nip44_exports,nip47:nip47_exports,nip54:nip54_exports,nip57:nip57_exports,nip59:nip59_exports,nip98:nip98_exports,serializeEvent:serializeEvent$1,utils:utils_exports,validateEvent:validateEvent$1,verifiedSymbol:verifiedSymbol$1,verifyEvent},Symbol.toStringTag,{value:"Module"}));function anumber(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function isBytes$1(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function abytes$1(n,...e){if(!isBytes$1(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function ahash(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");anumber(n.outputLen),anumber(n.blockLen)}function aexists(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function aoutput(n,e){abytes$1(n);const t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}const crypto$1=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function createView(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function rotr(n,e){return n<<32-e|n>>>e}const hexes$1=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex$1(n){abytes$1(n);let e="";for(let t=0;t<n.length;t++)e+=hexes$1[n[t]];return e}const asciis$1={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16$1(n){if(n>=asciis$1._0&&n<=asciis$1._9)return n-asciis$1._0;if(n>=asciis$1.A&&n<=asciis$1.F)return n-(asciis$1.A-10);if(n>=asciis$1.a&&n<=asciis$1.f)return n-(asciis$1.a-10)}function hexToBytes$1(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){const a=asciiToBase16$1(n.charCodeAt(o)),u=asciiToBase16$1(n.charCodeAt(o+1));if(a===void 0||u===void 0){const c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=a*16+u}return r}function utf8ToBytes$1(n){if(typeof n!="string")throw new Error("utf8ToBytes expected string, got "+typeof n);return new Uint8Array(new TextEncoder().encode(n))}function toBytes(n){return typeof n=="string"&&(n=utf8ToBytes$1(n)),abytes$1(n),n}function concatBytes$1(...n){let e=0;for(let r=0;r<n.length;r++){const s=n[r];abytes$1(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){const o=n[r];t.set(o,s),s+=o.length}return t}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(n){const e=r=>n().update(toBytes(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function randomBytes(n=32){if(crypto$1&&typeof crypto$1.getRandomValues=="function")return crypto$1.getRandomValues(new Uint8Array(n));if(crypto$1&&typeof crypto$1.randomBytes=="function")return crypto$1.randomBytes(n);throw new Error("crypto.getRandomValues must be defined")}function setBigUint64(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);const s=BigInt(32),o=BigInt(4294967295),a=Number(t>>s&o),u=Number(t&o),c=r?4:0,l=r?0:4;n.setUint32(e+c,a,r),n.setUint32(e+l,u,r)}function Chi(n,e,t){return n&e^~n&t}function Maj(n,e,t){return n&e^n&t^e&t}class HashMD extends Hash{constructor(e,t,r,s){super(),this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=createView(this.buffer)}update(e){aexists(this);const{view:t,buffer:r,blockLen:s}=this;e=toBytes(e);const o=e.length;for(let a=0;a<o;){const u=Math.min(s-this.pos,o-a);if(u===s){const c=createView(e);for(;s<=o-a;a+=s)this.process(c,a);continue}r.set(e.subarray(a,a+u),this.pos),this.pos+=u,a+=u,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){aexists(this),aoutput(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:s,isLE:o}=this;let{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>s-a&&(this.process(r,0),a=0);for(let f=a;f<s;f++)t[f]=0;setBigUint64(r,s-8,BigInt(this.length*8),o),this.process(r,0);const u=createView(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,h=this.get();if(l>h.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)u.setUint32(4*f,h[f],o)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:s,finished:o,destroyed:a,pos:u}=this;return e.length=s,e.pos=u,e.finished=o,e.destroyed=a,s%t&&e.buffer.set(r),e}}const SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),SHA256_IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),SHA256_W=new Uint32Array(64);class SHA256 extends HashMD{constructor(){super(64,32,8,!1),this.A=SHA256_IV[0]|0,this.B=SHA256_IV[1]|0,this.C=SHA256_IV[2]|0,this.D=SHA256_IV[3]|0,this.E=SHA256_IV[4]|0,this.F=SHA256_IV[5]|0,this.G=SHA256_IV[6]|0,this.H=SHA256_IV[7]|0}get(){const{A:e,B:t,C:r,D:s,E:o,F:a,G:u,H:c}=this;return[e,t,r,s,o,a,u,c]}set(e,t,r,s,o,a,u,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=s|0,this.E=o|0,this.F=a|0,this.G=u|0,this.H=c|0}process(e,t){for(let f=0;f<16;f++,t+=4)SHA256_W[f]=e.getUint32(t,!1);for(let f=16;f<64;f++){const p=SHA256_W[f-15],b=SHA256_W[f-2],v=rotr(p,7)^rotr(p,18)^p>>>3,m=rotr(b,17)^rotr(b,19)^b>>>10;SHA256_W[f]=m+SHA256_W[f-7]+v+SHA256_W[f-16]|0}let{A:r,B:s,C:o,D:a,E:u,F:c,G:l,H:h}=this;for(let f=0;f<64;f++){const p=rotr(u,6)^rotr(u,11)^rotr(u,25),b=h+p+Chi(u,c,l)+SHA256_K[f]+SHA256_W[f]|0,m=(rotr(r,2)^rotr(r,13)^rotr(r,22))+Maj(r,s,o)|0;h=l,l=c,c=u,u=a+b|0,a=o,o=s,s=r,r=b+m|0}r=r+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,u=u+this.E|0,c=c+this.F|0,l=l+this.G|0,h=h+this.H|0,this.set(r,s,o,a,u,c,l,h)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const sha256=wrapConstructor(()=>new SHA256);class HMAC extends Hash{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,ahash(e);const r=toBytes(t);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,o=new Uint8Array(s);o.set(r.length>s?e.create().update(r).digest():r);for(let a=0;a<o.length;a++)o[a]^=54;this.iHash.update(o),this.oHash=e.create();for(let a=0;a<o.length;a++)o[a]^=106;this.oHash.update(o),o.fill(0)}update(e){return aexists(this),this.iHash.update(e),this}digestInto(e){aexists(this),abytes$1(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:t,iHash:r,finished:s,destroyed:o,blockLen:a,outputLen:u}=this;return e=e,e.finished=s,e.destroyed=o,e.blockLen=a,e.outputLen=u,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hmac=(n,e,t)=>new HMAC(n,e).update(t).digest();hmac.create=(n,e)=>new HMAC(n,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$4=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2);function isBytes(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function abytes(n){if(!isBytes(n))throw new Error("Uint8Array expected")}function abool(n,e){if(typeof e!="boolean")throw new Error(n+" boolean expected, got "+e)}const hexes=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function bytesToHex(n){abytes(n);let e="";for(let t=0;t<n.length;t++)e+=hexes[n[t]];return e}function numberToHexUnpadded(n){const e=n.toString(16);return e.length&1?"0"+e:e}function hexToNumber(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?_0n$4:BigInt("0x"+n)}const asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};function asciiToBase16(n){if(n>=asciis._0&&n<=asciis._9)return n-asciis._0;if(n>=asciis.A&&n<=asciis.F)return n-(asciis.A-10);if(n>=asciis.a&&n<=asciis.f)return n-(asciis.a-10)}function hexToBytes(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);const e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let s=0,o=0;s<t;s++,o+=2){const a=asciiToBase16(n.charCodeAt(o)),u=asciiToBase16(n.charCodeAt(o+1));if(a===void 0||u===void 0){const c=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}r[s]=a*16+u}return r}function bytesToNumberBE(n){return hexToNumber(bytesToHex(n))}function bytesToNumberLE(n){return abytes(n),hexToNumber(bytesToHex(Uint8Array.from(n).reverse()))}function numberToBytesBE(n,e){return hexToBytes(n.toString(16).padStart(e*2,"0"))}function numberToBytesLE(n,e){return numberToBytesBE(n,e).reverse()}function numberToVarBytesBE(n){return hexToBytes(numberToHexUnpadded(n))}function ensureBytes(n,e,t){let r;if(typeof e=="string")try{r=hexToBytes(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(isBytes(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");const s=r.length;if(typeof t=="number"&&s!==t)throw new Error(n+" of length "+t+" expected, got "+s);return r}function concatBytes(...n){let e=0;for(let r=0;r<n.length;r++){const s=n[r];abytes(s),e+=s.length}const t=new Uint8Array(e);for(let r=0,s=0;r<n.length;r++){const o=n[r];t.set(o,s),s+=o.length}return t}function equalBytes(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function utf8ToBytes(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}const isPosBig=n=>typeof n=="bigint"&&_0n$4<=n;function inRange(n,e,t){return isPosBig(n)&&isPosBig(e)&&isPosBig(t)&&e<=n&&n<t}function aInRange(n,e,t,r){if(!inRange(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function bitLen(n){let e;for(e=0;n>_0n$4;n>>=_1n$4,e+=1);return e}function bitGet(n,e){return n>>BigInt(e)&_1n$4}function bitSet(n,e,t){return n|(t?_1n$4:_0n$4)<<BigInt(e)}const bitMask=n=>(_2n$2<<BigInt(n-1))-_1n$4,u8n=n=>new Uint8Array(n),u8fr=n=>Uint8Array.from(n);function createHmacDrbg(n,e,t){if(typeof n!="number"||n<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof t!="function")throw new Error("hmacFn must be a function");let r=u8n(n),s=u8n(n),o=0;const a=()=>{r.fill(1),s.fill(0),o=0},u=(...f)=>t(s,r,...f),c=(f=u8n())=>{s=u(u8fr([0]),f),r=u(),f.length!==0&&(s=u(u8fr([1]),f),r=u())},l=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){r=u();const b=r.slice();p.push(b),f+=r.length}return concatBytes(...p)};return(f,p)=>{a(),c(f);let b;for(;!(b=p(l()));)c();return a(),b}}const validatorFns={bigint:n=>typeof n=="bigint",function:n=>typeof n=="function",boolean:n=>typeof n=="boolean",string:n=>typeof n=="string",stringOrUint8Array:n=>typeof n=="string"||isBytes(n),isSafeInteger:n=>Number.isSafeInteger(n),array:n=>Array.isArray(n),field:(n,e)=>e.Fp.isValid(n),hash:n=>typeof n=="function"&&Number.isSafeInteger(n.outputLen)};function validateObject(n,e,t={}){const r=(s,o,a)=>{const u=validatorFns[o];if(typeof u!="function")throw new Error("invalid validator function");const c=n[s];if(!(a&&c===void 0)&&!u(c,n))throw new Error("param "+String(s)+" is invalid. Expected "+o+", got "+c)};for(const[s,o]of Object.entries(e))r(s,o,!1);for(const[s,o]of Object.entries(t))r(s,o,!0);return n}const notImplemented=()=>{throw new Error("not implemented")};function memoized(n){const e=new WeakMap;return(t,...r)=>{const s=e.get(t);if(s!==void 0)return s;const o=n(t,...r);return e.set(t,o),o}}const ut=Object.freeze(Object.defineProperty({__proto__:null,aInRange,abool,abytes,bitGet,bitLen,bitMask,bitSet,bytesToHex,bytesToNumberBE,bytesToNumberLE,concatBytes,createHmacDrbg,ensureBytes,equalBytes,hexToBytes,hexToNumber,inRange,isBytes,memoized,notImplemented,numberToBytesBE,numberToBytesLE,numberToHexUnpadded,numberToVarBytesBE,utf8ToBytes,validateObject},Symbol.toStringTag,{value:"Module"}));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$3=BigInt(0),_1n$3=BigInt(1),_2n$1=BigInt(2),_3n$1=BigInt(3),_4n=BigInt(4),_5n=BigInt(5),_8n=BigInt(8);function mod(n,e){const t=n%e;return t>=_0n$3?t:e+t}function pow(n,e,t){if(e<_0n$3)throw new Error("invalid exponent, negatives unsupported");if(t<=_0n$3)throw new Error("invalid modulus");if(t===_1n$3)return _0n$3;let r=_1n$3;for(;e>_0n$3;)e&_1n$3&&(r=r*n%t),n=n*n%t,e>>=_1n$3;return r}function pow2(n,e,t){let r=n;for(;e-- >_0n$3;)r*=r,r%=t;return r}function invert(n,e){if(n===_0n$3)throw new Error("invert: expected non-zero number");if(e<=_0n$3)throw new Error("invert: expected positive modulus, got "+e);let t=mod(n,e),r=e,s=_0n$3,o=_1n$3;for(;t!==_0n$3;){const u=r/t,c=r%t,l=s-o*u;r=t,t=c,s=o,o=l}if(r!==_1n$3)throw new Error("invert: does not exist");return mod(s,e)}function tonelliShanks(n){const e=(n-_1n$3)/_2n$1;let t,r,s;for(t=n-_1n$3,r=0;t%_2n$1===_0n$3;t/=_2n$1,r++);for(s=_2n$1;s<n&&pow(s,e,n)!==n-_1n$3;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const a=(n+_1n$3)/_4n;return function(c,l){const h=c.pow(l,a);if(!c.eql(c.sqr(h),l))throw new Error("Cannot find square root");return h}}const o=(t+_1n$3)/_2n$1;return function(u,c){if(u.pow(c,e)===u.neg(u.ONE))throw new Error("Cannot find square root");let l=r,h=u.pow(u.mul(u.ONE,s),t),f=u.pow(c,o),p=u.pow(c,t);for(;!u.eql(p,u.ONE);){if(u.eql(p,u.ZERO))return u.ZERO;let b=1;for(let m=u.sqr(p);b<l&&!u.eql(m,u.ONE);b++)m=u.sqr(m);const v=u.pow(h,_1n$3<<BigInt(l-b-1));h=u.sqr(v),f=u.mul(f,v),p=u.mul(p,h),l=b}return f}}function FpSqrt(n){if(n%_4n===_3n$1){const e=(n+_1n$3)/_4n;return function(r,s){const o=r.pow(s,e);if(!r.eql(r.sqr(o),s))throw new Error("Cannot find square root");return o}}if(n%_8n===_5n){const e=(n-_5n)/_8n;return function(r,s){const o=r.mul(s,_2n$1),a=r.pow(o,e),u=r.mul(s,a),c=r.mul(r.mul(u,_2n$1),a),l=r.mul(u,r.sub(c,r.ONE));if(!r.eql(r.sqr(l),s))throw new Error("Cannot find square root");return l}}return tonelliShanks(n)}const FIELD_FIELDS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function validateField(n){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},t=FIELD_FIELDS.reduce((r,s)=>(r[s]="function",r),e);return validateObject(n,t)}function FpPow(n,e,t){if(t<_0n$3)throw new Error("invalid exponent, negatives unsupported");if(t===_0n$3)return n.ONE;if(t===_1n$3)return e;let r=n.ONE,s=e;for(;t>_0n$3;)t&_1n$3&&(r=n.mul(r,s)),s=n.sqr(s),t>>=_1n$3;return r}function FpInvertBatch(n,e){const t=new Array(e.length),r=e.reduce((o,a,u)=>n.is0(a)?o:(t[u]=o,n.mul(o,a)),n.ONE),s=n.inv(r);return e.reduceRight((o,a,u)=>n.is0(a)?o:(t[u]=n.mul(o,t[u]),n.mul(o,a)),s),t}function nLength(n,e){const t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function Field(n,e,t=!1,r={}){if(n<=_0n$3)throw new Error("invalid field: expected ORDER > 0, got "+n);const{nBitLength:s,nByteLength:o}=nLength(n,e);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let a;const u=Object.freeze({ORDER:n,isLE:t,BITS:s,BYTES:o,MASK:bitMask(s),ZERO:_0n$3,ONE:_1n$3,create:c=>mod(c,n),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return _0n$3<=c&&c<n},is0:c=>c===_0n$3,isOdd:c=>(c&_1n$3)===_1n$3,neg:c=>mod(-c,n),eql:(c,l)=>c===l,sqr:c=>mod(c*c,n),add:(c,l)=>mod(c+l,n),sub:(c,l)=>mod(c-l,n),mul:(c,l)=>mod(c*l,n),pow:(c,l)=>FpPow(u,c,l),div:(c,l)=>mod(c*invert(l,n),n),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>invert(c,n),sqrt:r.sqrt||(c=>(a||(a=FpSqrt(n)),a(u,c))),invertBatch:c=>FpInvertBatch(u,c),cmov:(c,l,h)=>h?l:c,toBytes:c=>t?numberToBytesLE(c,o):numberToBytesBE(c,o),fromBytes:c=>{if(c.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+c.length);return t?bytesToNumberLE(c):bytesToNumberBE(c)}});return Object.freeze(u)}function getFieldBytesLength(n){if(typeof n!="bigint")throw new Error("field order must be bigint");const e=n.toString(2).length;return Math.ceil(e/8)}function getMinHashLength(n){const e=getFieldBytesLength(n);return e+Math.ceil(e/2)}function mapHashToField(n,e,t=!1){const r=n.length,s=getFieldBytesLength(e),o=getMinHashLength(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);const a=t?bytesToNumberLE(n):bytesToNumberBE(n),u=mod(a,e-_1n$3)+_1n$3;return t?numberToBytesLE(u,s):numberToBytesBE(u,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _0n$2=BigInt(0),_1n$2=BigInt(1);function constTimeNegate(n,e){const t=e.negate();return n?t:e}function validateW(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function calcWOpts(n,e){validateW(n,e);const t=Math.ceil(e/n)+1,r=2**(n-1);return{windows:t,windowSize:r}}function validateMSMPoints(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function validateMSMScalars(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}const pointPrecomputes=new WeakMap,pointWindowSizes=new WeakMap;function getW(n){return pointWindowSizes.get(n)||1}function wNAF(n,e){return{constTimeNegate,hasPrecomputes(t){return getW(t)!==1},unsafeLadder(t,r,s=n.ZERO){let o=t;for(;r>_0n$2;)r&_1n$2&&(s=s.add(o)),o=o.double(),r>>=_1n$2;return s},precomputeWindow(t,r){const{windows:s,windowSize:o}=calcWOpts(r,e),a=[];let u=t,c=u;for(let l=0;l<s;l++){c=u,a.push(c);for(let h=1;h<o;h++)c=c.add(u),a.push(c);u=c.double()}return a},wNAF(t,r,s){const{windows:o,windowSize:a}=calcWOpts(t,e);let u=n.ZERO,c=n.BASE;const l=BigInt(2**t-1),h=2**t,f=BigInt(t);for(let p=0;p<o;p++){const b=p*a;let v=Number(s&l);s>>=f,v>a&&(v-=h,s+=_1n$2);const m=b,y=b+Math.abs(v)-1,w=p%2!==0,x=v<0;v===0?c=c.add(constTimeNegate(w,r[m])):u=u.add(constTimeNegate(x,r[y]))}return{p:u,f:c}},wNAFUnsafe(t,r,s,o=n.ZERO){const{windows:a,windowSize:u}=calcWOpts(t,e),c=BigInt(2**t-1),l=2**t,h=BigInt(t);for(let f=0;f<a;f++){const p=f*u;if(s===_0n$2)break;let b=Number(s&c);if(s>>=h,b>u&&(b-=l,s+=_1n$2),b===0)continue;let v=r[p+Math.abs(b)-1];b<0&&(v=v.negate()),o=o.add(v)}return o},getPrecomputes(t,r,s){let o=pointPrecomputes.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&pointPrecomputes.set(r,s(o))),o},wNAFCached(t,r,s){const o=getW(t);return this.wNAF(o,this.getPrecomputes(o,t,s),r)},wNAFCachedUnsafe(t,r,s,o){const a=getW(t);return a===1?this.unsafeLadder(t,r,o):this.wNAFUnsafe(a,this.getPrecomputes(a,t,s),r,o)},setWindowSize(t,r){validateW(r,e),pointWindowSizes.set(t,r),pointPrecomputes.delete(t)}}}function pippenger(n,e,t,r){if(validateMSMPoints(t,n),validateMSMScalars(r,e),t.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=n.ZERO,o=bitLen(BigInt(t.length)),a=o>12?o-3:o>4?o-2:o?2:1,u=(1<<a)-1,c=new Array(u+1).fill(s),l=Math.floor((e.BITS-1)/a)*a;let h=s;for(let f=l;f>=0;f-=a){c.fill(s);for(let b=0;b<r.length;b++){const v=r[b],m=Number(v>>BigInt(f)&BigInt(u));c[m]=c[m].add(t[b])}let p=s;for(let b=c.length-1,v=s;b>0;b--)v=v.add(c[b]),p=p.add(v);if(h=h.add(p),f!==0)for(let b=0;b<a;b++)h=h.double()}return h}function validateBasic(n){return validateField(n.Fp),validateObject(n,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nLength(n.n,n.nBitLength),...n,p:n.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function validateSigVerOpts(n){n.lowS!==void 0&&abool("lowS",n.lowS),n.prehash!==void 0&&abool("prehash",n.prehash)}function validatePointOpts(n){const e=validateBasic(n);validateObject(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:t,Fp:r,a:s}=e;if(t){if(!r.eql(s,r.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof t!="object"||typeof t.beta!="bigint"||typeof t.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut;class DERErr extends Error{constructor(e=""){super(e)}}const DER={Err:DERErr,_tlv:{encode:(n,e)=>{const{Err:t}=DER;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const r=e.length/2,s=numberToHexUnpadded(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");const o=r>127?numberToHexUnpadded(s.length/2|128):"";return numberToHexUnpadded(n)+o+s+e},decode(n,e){const{Err:t}=DER;let r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");const s=e[r++],o=!!(s&128);let a=0;if(!o)a=s;else{const c=s&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new t("tlv.decode: length bytes not complete");if(l[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const h of l)a=a<<8|h;if(r+=c,a<128)throw new t("tlv.decode(long): not minimal encoding")}const u=e.subarray(r,r+a);if(u.length!==a)throw new t("tlv.decode: wrong value length");return{v:u,l:e.subarray(r+a)}}},_int:{encode(n){const{Err:e}=DER;if(n<_0n$1)throw new e("integer: negative integers are not allowed");let t=numberToHexUnpadded(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){const{Err:e}=DER;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return b2n(n)}},toSig(n){const{Err:e,_int:t,_tlv:r}=DER,s=typeof n=="string"?h2b(n):n;abytes(s);const{v:o,l:a}=r.decode(48,s);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:u,l:c}=r.decode(2,o),{v:l,l:h}=r.decode(2,c);if(h.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(u),s:t.decode(l)}},hexFromSig(n){const{_tlv:e,_int:t}=DER,r=e.encode(2,t.encode(n.r)),s=e.encode(2,t.encode(n.s)),o=r+s;return e.encode(48,o)}},_0n$1=BigInt(0),_1n$1=BigInt(1);BigInt(2);const _3n=BigInt(3);BigInt(4);function weierstrassPoints(n){const e=validatePointOpts(n),{Fp:t}=e,r=Field(e.n,e.nBitLength),s=e.toBytes||((m,y,w)=>{const x=y.toAffine();return concatBytes(Uint8Array.from([4]),t.toBytes(x.x),t.toBytes(x.y))}),o=e.fromBytes||(m=>{const y=m.subarray(1),w=t.fromBytes(y.subarray(0,t.BYTES)),x=t.fromBytes(y.subarray(t.BYTES,2*t.BYTES));return{x:w,y:x}});function a(m){const{a:y,b:w}=e,x=t.sqr(m),k=t.mul(x,m);return t.add(t.add(k,t.mul(m,y)),w)}if(!t.eql(t.sqr(e.Gy),a(e.Gx)))throw new Error("bad generator point: equation left != right");function u(m){return inRange(m,_1n$1,e.n)}function c(m){const{allowedPrivateKeyLengths:y,nByteLength:w,wrapPrivateKey:x,n:k}=e;if(y&&typeof m!="bigint"){if(isBytes(m)&&(m=bytesToHex(m)),typeof m!="string"||!y.includes(m.length))throw new Error("invalid private key");m=m.padStart(w*2,"0")}let C;try{C=typeof m=="bigint"?m:bytesToNumberBE(ensureBytes("private key",m,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof m)}return x&&(C=mod(C,k)),aInRange("private key",C,_1n$1,k),C}function l(m){if(!(m instanceof p))throw new Error("ProjectivePoint expected")}const h=memoized((m,y)=>{const{px:w,py:x,pz:k}=m;if(t.eql(k,t.ONE))return{x:w,y:x};const C=m.is0();y==null&&(y=C?t.ONE:t.inv(k));const P=t.mul(w,y),R=t.mul(x,y),N=t.mul(k,y);if(C)return{x:t.ZERO,y:t.ZERO};if(!t.eql(N,t.ONE))throw new Error("invZ was invalid");return{x:P,y:R}}),f=memoized(m=>{if(m.is0()){if(e.allowInfinityPoint&&!t.is0(m.py))return;throw new Error("bad point: ZERO")}const{x:y,y:w}=m.toAffine();if(!t.isValid(y)||!t.isValid(w))throw new Error("bad point: x or y not FE");const x=t.sqr(w),k=a(y);if(!t.eql(x,k))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class p{constructor(y,w,x){if(this.px=y,this.py=w,this.pz=x,y==null||!t.isValid(y))throw new Error("x required");if(w==null||!t.isValid(w))throw new Error("y required");if(x==null||!t.isValid(x))throw new Error("z required");Object.freeze(this)}static fromAffine(y){const{x:w,y:x}=y||{};if(!y||!t.isValid(w)||!t.isValid(x))throw new Error("invalid affine point");if(y instanceof p)throw new Error("projective point not allowed");const k=C=>t.eql(C,t.ZERO);return k(w)&&k(x)?p.ZERO:new p(w,x,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){const w=t.invertBatch(y.map(x=>x.pz));return y.map((x,k)=>x.toAffine(w[k])).map(p.fromAffine)}static fromHex(y){const w=p.fromAffine(o(ensureBytes("pointHex",y)));return w.assertValidity(),w}static fromPrivateKey(y){return p.BASE.multiply(c(y))}static msm(y,w){return pippenger(p,r,y,w)}_setWindowSize(y){v.setWindowSize(this,y)}assertValidity(){f(this)}hasEvenY(){const{y}=this.toAffine();if(t.isOdd)return!t.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){l(y);const{px:w,py:x,pz:k}=this,{px:C,py:P,pz:R}=y,N=t.eql(t.mul(w,R),t.mul(C,k)),B=t.eql(t.mul(x,R),t.mul(P,k));return N&&B}negate(){return new p(this.px,t.neg(this.py),this.pz)}double(){const{a:y,b:w}=e,x=t.mul(w,_3n),{px:k,py:C,pz:P}=this;let R=t.ZERO,N=t.ZERO,B=t.ZERO,O=t.mul(k,k),H=t.mul(C,C),S=t.mul(P,P),_=t.mul(k,C);return _=t.add(_,_),B=t.mul(k,P),B=t.add(B,B),R=t.mul(y,B),N=t.mul(x,S),N=t.add(R,N),R=t.sub(H,N),N=t.add(H,N),N=t.mul(R,N),R=t.mul(_,R),B=t.mul(x,B),S=t.mul(y,S),_=t.sub(O,S),_=t.mul(y,_),_=t.add(_,B),B=t.add(O,O),O=t.add(B,O),O=t.add(O,S),O=t.mul(O,_),N=t.add(N,O),S=t.mul(C,P),S=t.add(S,S),O=t.mul(S,_),R=t.sub(R,O),B=t.mul(S,H),B=t.add(B,B),B=t.add(B,B),new p(R,N,B)}add(y){l(y);const{px:w,py:x,pz:k}=this,{px:C,py:P,pz:R}=y;let N=t.ZERO,B=t.ZERO,O=t.ZERO;const H=e.a,S=t.mul(e.b,_3n);let _=t.mul(w,C),L=t.mul(x,P),I=t.mul(k,R),A=t.add(w,x),E=t.add(C,P);A=t.mul(A,E),E=t.add(_,L),A=t.sub(A,E),E=t.add(w,k);let $=t.add(C,R);return E=t.mul(E,$),$=t.add(_,I),E=t.sub(E,$),$=t.add(x,k),N=t.add(P,R),$=t.mul($,N),N=t.add(L,I),$=t.sub($,N),O=t.mul(H,E),N=t.mul(S,I),O=t.add(N,O),N=t.sub(L,O),O=t.add(L,O),B=t.mul(N,O),L=t.add(_,_),L=t.add(L,_),I=t.mul(H,I),E=t.mul(S,E),L=t.add(L,I),I=t.sub(_,I),I=t.mul(H,I),E=t.add(E,I),_=t.mul(L,E),B=t.add(B,_),_=t.mul($,E),N=t.mul(A,N),N=t.sub(N,_),_=t.mul(A,L),O=t.mul($,O),O=t.add(O,_),new p(N,B,O)}subtract(y){return this.add(y.negate())}is0(){return this.equals(p.ZERO)}wNAF(y){return v.wNAFCached(this,y,p.normalizeZ)}multiplyUnsafe(y){const{endo:w,n:x}=e;aInRange("scalar",y,_0n$1,x);const k=p.ZERO;if(y===_0n$1)return k;if(this.is0()||y===_1n$1)return this;if(!w||v.hasPrecomputes(this))return v.wNAFCachedUnsafe(this,y,p.normalizeZ);let{k1neg:C,k1:P,k2neg:R,k2:N}=w.splitScalar(y),B=k,O=k,H=this;for(;P>_0n$1||N>_0n$1;)P&_1n$1&&(B=B.add(H)),N&_1n$1&&(O=O.add(H)),H=H.double(),P>>=_1n$1,N>>=_1n$1;return C&&(B=B.negate()),R&&(O=O.negate()),O=new p(t.mul(O.px,w.beta),O.py,O.pz),B.add(O)}multiply(y){const{endo:w,n:x}=e;aInRange("scalar",y,_1n$1,x);let k,C;if(w){const{k1neg:P,k1:R,k2neg:N,k2:B}=w.splitScalar(y);let{p:O,f:H}=this.wNAF(R),{p:S,f:_}=this.wNAF(B);O=v.constTimeNegate(P,O),S=v.constTimeNegate(N,S),S=new p(t.mul(S.px,w.beta),S.py,S.pz),k=O.add(S),C=H.add(_)}else{const{p:P,f:R}=this.wNAF(y);k=P,C=R}return p.normalizeZ([k,C])[0]}multiplyAndAddUnsafe(y,w,x){const k=p.BASE,C=(R,N)=>N===_0n$1||N===_1n$1||!R.equals(k)?R.multiplyUnsafe(N):R.multiply(N),P=C(this,w).add(C(y,x));return P.is0()?void 0:P}toAffine(y){return h(this,y)}isTorsionFree(){const{h:y,isTorsionFree:w}=e;if(y===_1n$1)return!0;if(w)return w(p,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:y,clearCofactor:w}=e;return y===_1n$1?this:w?w(p,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return abool("isCompressed",y),this.assertValidity(),s(p,this,y)}toHex(y=!0){return abool("isCompressed",y),bytesToHex(this.toRawBytes(y))}}p.BASE=new p(e.Gx,e.Gy,t.ONE),p.ZERO=new p(t.ZERO,t.ONE,t.ZERO);const b=e.nBitLength,v=wNAF(p,e.endo?Math.ceil(b/2):b);return{CURVE:e,ProjectivePoint:p,normPrivateKeyToScalar:c,weierstrassEquation:a,isWithinCurveOrder:u}}function validateOpts(n){const e=validateBasic(n);return validateObject(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function weierstrass(n){const e=validateOpts(n),{Fp:t,n:r}=e,s=t.BYTES+1,o=2*t.BYTES+1;function a(I){return mod(I,r)}function u(I){return invert(I,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:h,isWithinCurveOrder:f}=weierstrassPoints({...e,toBytes(I,A,E){const $=A.toAffine(),M=t.toBytes($.x),U=concatBytes;return abool("isCompressed",E),E?U(Uint8Array.from([A.hasEvenY()?2:3]),M):U(Uint8Array.from([4]),M,t.toBytes($.y))},fromBytes(I){const A=I.length,E=I[0],$=I.subarray(1);if(A===s&&(E===2||E===3)){const M=bytesToNumberBE($);if(!inRange(M,_1n$1,t.ORDER))throw new Error("Point is not on curve");const U=h(M);let z;try{z=t.sqrt(U)}catch(W){const Z=W instanceof Error?": "+W.message:"";throw new Error("Point is not on curve"+Z)}const D=(z&_1n$1)===_1n$1;return(E&1)===1!==D&&(z=t.neg(z)),{x:M,y:z}}else if(A===o&&E===4){const M=t.fromBytes($.subarray(0,t.BYTES)),U=t.fromBytes($.subarray(t.BYTES,2*t.BYTES));return{x:M,y:U}}else{const M=s,U=o;throw new Error("invalid Point, expected length of "+M+", or uncompressed "+U+", got "+A)}}}),p=I=>bytesToHex(numberToBytesBE(I,e.nByteLength));function b(I){const A=r>>_1n$1;return I>A}function v(I){return b(I)?a(-I):I}const m=(I,A,E)=>bytesToNumberBE(I.slice(A,E));class y{constructor(A,E,$){this.r=A,this.s=E,this.recovery=$,this.assertValidity()}static fromCompact(A){const E=e.nByteLength;return A=ensureBytes("compactSignature",A,E*2),new y(m(A,0,E),m(A,E,2*E))}static fromDER(A){const{r:E,s:$}=DER.toSig(ensureBytes("DER",A));return new y(E,$)}assertValidity(){aInRange("r",this.r,_1n$1,r),aInRange("s",this.s,_1n$1,r)}addRecoveryBit(A){return new y(this.r,this.s,A)}recoverPublicKey(A){const{r:E,s:$,recovery:M}=this,U=R(ensureBytes("msgHash",A));if(M==null||![0,1,2,3].includes(M))throw new Error("recovery id invalid");const z=M===2||M===3?E+e.n:E;if(z>=t.ORDER)throw new Error("recovery id 2 or 3 invalid");const D=M&1?"03":"02",V=c.fromHex(D+p(z)),W=u(z),Z=a(-U*W),G=a($*W),K=c.BASE.multiplyAndAddUnsafe(V,Z,G);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return b(this.s)}normalizeS(){return this.hasHighS()?new y(this.r,a(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}const w={isValidPrivateKey(I){try{return l(I),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const I=getMinHashLength(e.n);return mapHashToField(e.randomBytes(I),e.n)},precompute(I=8,A=c.BASE){return A._setWindowSize(I),A.multiply(BigInt(3)),A}};function x(I,A=!0){return c.fromPrivateKey(I).toRawBytes(A)}function k(I){const A=isBytes(I),E=typeof I=="string",$=(A||E)&&I.length;return A?$===s||$===o:E?$===2*s||$===2*o:I instanceof c}function C(I,A,E=!0){if(k(I))throw new Error("first arg must be private key");if(!k(A))throw new Error("second arg must be public key");return c.fromHex(A).multiply(l(I)).toRawBytes(E)}const P=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const A=bytesToNumberBE(I),E=I.length*8-e.nBitLength;return E>0?A>>BigInt(E):A},R=e.bits2int_modN||function(I){return a(P(I))},N=bitMask(e.nBitLength);function B(I){return aInRange("num < 2^"+e.nBitLength,I,_0n$1,N),numberToBytesBE(I,e.nByteLength)}function O(I,A,E=H){if(["recovered","canonical"].some(ae=>ae in E))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:M}=e;let{lowS:U,prehash:z,extraEntropy:D}=E;U==null&&(U=!0),I=ensureBytes("msgHash",I),validateSigVerOpts(E),z&&(I=ensureBytes("prehashed msgHash",$(I)));const V=R(I),W=l(A),Z=[B(W),B(V)];if(D!=null&&D!==!1){const ae=D===!0?M(t.BYTES):D;Z.push(ensureBytes("extraEntropy",ae))}const G=concatBytes(...Z),K=V;function ne(ae){const se=P(ae);if(!f(se))return;const pe=u(se),ye=c.BASE.multiply(se).toAffine(),J=a(ye.x);if(J===_0n$1)return;const Q=a(pe*a(K+J*W));if(Q===_0n$1)return;let te=(ye.x===J?0:2)|Number(ye.y&_1n$1),be=Q;return U&&b(Q)&&(be=v(Q),te^=1),new y(J,be,te)}return{seed:G,k2sig:ne}}const H={lowS:e.lowS,prehash:!1},S={lowS:e.lowS,prehash:!1};function _(I,A,E=H){const{seed:$,k2sig:M}=O(I,A,E),U=e;return createHmacDrbg(U.hash.outputLen,U.nByteLength,U.hmac)($,M)}c.BASE._setWindowSize(8);function L(I,A,E,$=S){var te;const M=I;A=ensureBytes("msgHash",A),E=ensureBytes("publicKey",E);const{lowS:U,prehash:z,format:D}=$;if(validateSigVerOpts($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(D!==void 0&&D!=="compact"&&D!=="der")throw new Error("format must be compact or der");const V=typeof M=="string"||isBytes(M),W=!V&&!D&&typeof M=="object"&&M!==null&&typeof M.r=="bigint"&&typeof M.s=="bigint";if(!V&&!W)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Z,G;try{if(W&&(Z=new y(M.r,M.s)),V){try{D!=="compact"&&(Z=y.fromDER(M))}catch(be){if(!(be instanceof DER.Err))throw be}!Z&&D!=="der"&&(Z=y.fromCompact(M))}G=c.fromHex(E)}catch{return!1}if(!Z||U&&Z.hasHighS())return!1;z&&(A=e.hash(A));const{r:K,s:ne}=Z,ae=R(A),se=u(ne),pe=a(ae*se),ye=a(K*se),J=(te=c.BASE.multiplyAndAddUnsafe(G,pe,ye))==null?void 0:te.toAffine();return J?a(J.x)===K:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:C,sign:_,verify:L,ProjectivePoint:c,Signature:y,utils:w}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function getHash(n){return{hash:n,hmac:(e,...t)=>hmac(n,e,concatBytes$1(...t)),randomBytes}}function createCurve(n,e){const t=r=>weierstrass({...n,...getHash(r)});return{...t(e),create:t}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),_1n=BigInt(1),_2n=BigInt(2),divNearest=(n,e)=>(n+e/_2n)/e;function sqrtMod(n){const e=secp256k1P,t=BigInt(3),r=BigInt(6),s=BigInt(11),o=BigInt(22),a=BigInt(23),u=BigInt(44),c=BigInt(88),l=n*n*n%e,h=l*l*n%e,f=pow2(h,t,e)*h%e,p=pow2(f,t,e)*h%e,b=pow2(p,_2n,e)*l%e,v=pow2(b,s,e)*b%e,m=pow2(v,o,e)*v%e,y=pow2(m,u,e)*m%e,w=pow2(y,c,e)*y%e,x=pow2(w,u,e)*m%e,k=pow2(x,t,e)*h%e,C=pow2(k,a,e)*v%e,P=pow2(C,r,e)*l%e,R=pow2(P,_2n,e);if(!Fpk1.eql(Fpk1.sqr(R),n))throw new Error("Cannot find square root");return R}const Fpk1=Field(secp256k1P,void 0,void 0,{sqrt:sqrtMod}),secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp:Fpk1,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:n=>{const e=secp256k1N,t=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=t,a=BigInt("0x100000000000000000000000000000000"),u=divNearest(o*n,e),c=divNearest(-r*n,e);let l=mod(n-u*t-c*s,e),h=mod(-u*r-c*o,e);const f=l>a,p=h>a;if(f&&(l=e-l),p&&(h=e-h),l>a||h>a)throw new Error("splitScalar: Endomorphism failed, k="+n);return{k1neg:f,k1:l,k2neg:p,k2:h}}}},sha256),_0n=BigInt(0),TAGGED_HASH_PREFIXES={};function taggedHash(n,...e){let t=TAGGED_HASH_PREFIXES[n];if(t===void 0){const r=sha256(Uint8Array.from(n,s=>s.charCodeAt(0)));t=concatBytes(r,r),TAGGED_HASH_PREFIXES[n]=t}return sha256(concatBytes(t,...e))}const pointToBytes=n=>n.toRawBytes(!0).slice(1),numTo32b=n=>numberToBytesBE(n,32),modP=n=>mod(n,secp256k1P),modN=n=>mod(n,secp256k1N),Point=secp256k1.ProjectivePoint,GmulAdd=(n,e,t)=>Point.BASE.multiplyAndAddUnsafe(n,e,t);function schnorrGetExtPubKey(n){let e=secp256k1.utils.normPrivateKeyToScalar(n),t=Point.fromPrivateKey(e);return{scalar:t.hasEvenY()?e:modN(-e),bytes:pointToBytes(t)}}function lift_x(n){aInRange("x",n,_1n,secp256k1P);const e=modP(n*n),t=modP(e*n+BigInt(7));let r=sqrtMod(t);r%_2n!==_0n&&(r=modP(-r));const s=new Point(n,r,_1n);return s.assertValidity(),s}const num=bytesToNumberBE;function challenge(...n){return modN(num(taggedHash("BIP0340/challenge",...n)))}function schnorrGetPublicKey(n){return schnorrGetExtPubKey(n).bytes}function schnorrSign(n,e,t=randomBytes(32)){const r=ensureBytes("message",n),{bytes:s,scalar:o}=schnorrGetExtPubKey(e),a=ensureBytes("auxRand",t,32),u=numTo32b(o^num(taggedHash("BIP0340/aux",a))),c=taggedHash("BIP0340/nonce",u,s,r),l=modN(num(c));if(l===_0n)throw new Error("sign failed: k is zero");const{bytes:h,scalar:f}=schnorrGetExtPubKey(l),p=challenge(h,s,r),b=new Uint8Array(64);if(b.set(h,0),b.set(numTo32b(modN(f+p*o)),32),!schnorrVerify(b,r,s))throw new Error("sign: Invalid signature produced");return b}function schnorrVerify(n,e,t){const r=ensureBytes("signature",n,64),s=ensureBytes("message",e),o=ensureBytes("publicKey",t,32);try{const a=lift_x(num(o)),u=num(r.subarray(0,32));if(!inRange(u,_1n,secp256k1P))return!1;const c=num(r.subarray(32,64));if(!inRange(c,_1n,secp256k1N))return!1;const l=challenge(numTo32b(u),pointToBytes(a),s),h=GmulAdd(a,c,modN(-l));return!(!h||!h.hasEvenY()||h.toAffine().x!==u)}catch{return!1}}const schnorr={getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,utils:{randomPrivateKey:secp256k1.utils.randomPrivateKey,lift_x,pointToBytes,numberToBytesBE,bytesToNumberBE,taggedHash,mod}};var dist={},LRUCache$1={},LRUCacheNode$1={};Object.defineProperty(LRUCacheNode$1,"__esModule",{value:!0}),LRUCacheNode$1.LRUCacheNode=void 0;class LRUCacheNode{constructor(e,t,r){const{entryExpirationTimeInMS:s=null,next:o=null,prev:a=null,onEntryEvicted:u,onEntryMarkedAsMostRecentlyUsed:c,clone:l,cloneFn:h}=r??{};if(typeof s=="number"&&(s<=0||Number.isNaN(s)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.clone=l??!1,this.cloneFn=h??this.defaultClone,this.key=e,this.internalValue=this.clone?this.cloneFn(t):t,this.created=Date.now(),this.entryExpirationTimeInMS=s,this.next=o,this.prev=a,this.onEntryEvicted=u,this.onEntryMarkedAsMostRecentlyUsed=c}get value(){return this.clone?this.cloneFn(this.internalValue):this.internalValue}get isExpired(){return typeof this.entryExpirationTimeInMS=="number"&&Date.now()-this.created>this.entryExpirationTimeInMS}invokeOnEvicted(){if(this.onEntryEvicted){const{key:e,value:t,isExpired:r}=this;this.onEntryEvicted({key:e,value:t,isExpired:r})}}invokeOnEntryMarkedAsMostRecentlyUsed(){if(this.onEntryMarkedAsMostRecentlyUsed){const{key:e,value:t}=this;this.onEntryMarkedAsMostRecentlyUsed({key:e,value:t})}}defaultClone(e){return typeof e=="boolean"||typeof e=="string"||typeof e=="number"?e:JSON.parse(JSON.stringify(e))}}LRUCacheNode$1.LRUCacheNode=LRUCacheNode,Object.defineProperty(LRUCache$1,"__esModule",{value:!0}),LRUCache$1.LRUCache=void 0;const LRUCacheNode_1=LRUCacheNode$1;class LRUCache{constructor(e){this.lookupTable=new Map,this.head=null,this.tail=null;const{maxSize:t=25,entryExpirationTimeInMS:r=null,onEntryEvicted:s,onEntryMarkedAsMostRecentlyUsed:o,cloneFn:a,clone:u}=e??{};if(Number.isNaN(t)||t<=0)throw new Error("maxSize must be greater than 0.");if(typeof r=="number"&&(r<=0||Number.isNaN(r)))throw new Error("entryExpirationTimeInMS must either be null (no expiry) or greater than 0");this.maxSizeInternal=t,this.entryExpirationTimeInMS=r,this.onEntryEvicted=s,this.onEntryMarkedAsMostRecentlyUsed=o,this.clone=u,this.cloneFn=a}get size(){return this.cleanCache(),this.lookupTable.size}get remainingSize(){return this.maxSizeInternal-this.size}get newest(){return this.head?this.head.isExpired?(this.removeNodeFromListAndLookupTable(this.head),this.newest):this.mapNodeToEntry(this.head):null}get oldest(){return this.tail?this.tail.isExpired?(this.removeNodeFromListAndLookupTable(this.tail),this.oldest):this.mapNodeToEntry(this.tail):null}get maxSize(){return this.maxSizeInternal}set maxSize(e){if(Number.isNaN(e)||e<=0)throw new Error("maxSize must be greater than 0.");this.maxSizeInternal=e,this.enforceSizeLimit()}set(e,t,r){const s=this.lookupTable.get(e);s&&this.removeNodeFromListAndLookupTable(s);const o=new LRUCacheNode_1.LRUCacheNode(e,t,{entryExpirationTimeInMS:this.entryExpirationTimeInMS,onEntryEvicted:this.onEntryEvicted,onEntryMarkedAsMostRecentlyUsed:this.onEntryMarkedAsMostRecentlyUsed,clone:this.clone,cloneFn:this.cloneFn,...r});return this.setNodeAsHead(o),this.lookupTable.set(e,o),this.enforceSizeLimit(),this}get(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):(this.setNodeAsHead(t),t.value):null}peek(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),null):t.value:null}delete(e){const t=this.lookupTable.get(e);return t?this.removeNodeFromListAndLookupTable(t):!1}has(e){const t=this.lookupTable.get(e);return t?t.isExpired?(this.removeNodeFromListAndLookupTable(t),!1):!0:!1}clear(){this.head=null,this.tail=null,this.lookupTable.clear()}find(e){let t=this.head;for(;t;){if(t.isExpired){const s=t.next;this.removeNodeFromListAndLookupTable(t),t=s;continue}const r=this.mapNodeToEntry(t);if(e(r))return this.setNodeAsHead(t),r;t=t.next}return null}forEach(e){let t=this.head,r=0;for(;t;){if(t.isExpired){const s=t.next;this.removeNodeFromListAndLookupTable(t),t=s;continue}e(t.value,t.key,r),t=t.next,r++}}*values(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield e.value,e=e.next}}*keys(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield e.key,e=e.next}}*entries(){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield this.mapNodeToEntry(e),e=e.next}}*[Symbol.iterator](){let e=this.head;for(;e;){if(e.isExpired){const t=e.next;this.removeNodeFromListAndLookupTable(e),e=t;continue}yield this.mapNodeToEntry(e),e=e.next}}enforceSizeLimit(){let e=this.tail;for(;e!==null&&this.size>this.maxSizeInternal;){const t=e.prev;this.removeNodeFromListAndLookupTable(e),e=t}}mapNodeToEntry({key:e,value:t}){return{key:e,value:t}}setNodeAsHead(e){this.removeNodeFromList(e),this.head?(e.next=this.head,this.head.prev=e,this.head=e):(this.head=e,this.tail=e),e.invokeOnEntryMarkedAsMostRecentlyUsed()}removeNodeFromList(e){e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.head===e&&(this.head=e.next),this.tail===e&&(this.tail=e.prev),e.next=null,e.prev=null}removeNodeFromListAndLookupTable(e){return e.invokeOnEvicted(),this.removeNodeFromList(e),this.lookupTable.delete(e.key)}cleanCache(){if(!this.entryExpirationTimeInMS)return;const e=[];for(const t of this.lookupTable.values())t.isExpired&&e.push(t);e.forEach(t=>this.removeNodeFromListAndLookupTable(t))}}LRUCache$1.LRUCache=LRUCache,function(n){var e=commonjsGlobal&&commonjsGlobal.__createBinding||(Object.create?function(r,s,o,a){a===void 0&&(a=o);var u=Object.getOwnPropertyDescriptor(s,o);(!u||("get"in u?!s.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,a,u)}:function(r,s,o,a){a===void 0&&(a=o),r[a]=s[o]}),t=commonjsGlobal&&commonjsGlobal.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&e(s,r,o)};Object.defineProperty(n,"__esModule",{value:!0}),t(LRUCache$1,n)}(dist);var lib={};(function(n){/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(n,"__esModule",{value:!0}),n.bytes=n.stringToBytes=n.str=n.bytesToString=n.hex=n.utf8=n.bech32m=n.bech32=n.base58check=n.base58xmr=n.base58xrp=n.base58flickr=n.base58=n.base64url=n.base64=n.base32crockford=n.base32hex=n.base32=n.base16=n.utils=n.assertNumber=void 0;function e(S){if(!Number.isSafeInteger(S))throw new Error(`Wrong integer: ${S}`)}n.assertNumber=e;function t(...S){const _=(A,E)=>$=>A(E($)),L=Array.from(S).reverse().reduce((A,E)=>A?_(A,E.encode):E.encode,void 0),I=S.reduce((A,E)=>A?_(A,E.decode):E.decode,void 0);return{encode:L,decode:I}}function r(S){return{encode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return _.map(L=>{if(e(L),L<0||L>=S.length)throw new Error(`Digit index outside alphabet: ${L} (alphabet: ${S.length})`);return S[L]})},decode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="string")throw new Error("alphabet.decode input should be array of strings");return _.map(L=>{if(typeof L!="string")throw new Error(`alphabet.decode: not string element=${L}`);const I=S.indexOf(L);if(I===-1)throw new Error(`Unknown letter: "${L}". Allowed: ${S}`);return I})}}}function s(S=""){if(typeof S!="string")throw new Error("join separator should be string");return{encode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="string")throw new Error("join.encode input should be array of strings");for(let L of _)if(typeof L!="string")throw new Error(`join.encode: non-string input=${L}`);return _.join(S)},decode:_=>{if(typeof _!="string")throw new Error("join.decode input should be string");return _.split(S)}}}function o(S,_="="){if(e(S),typeof _!="string")throw new Error("padding chr should be string");return{encode(L){if(!Array.isArray(L)||L.length&&typeof L[0]!="string")throw new Error("padding.encode input should be array of strings");for(let I of L)if(typeof I!="string")throw new Error(`padding.encode: non-string input=${I}`);for(;L.length*S%8;)L.push(_);return L},decode(L){if(!Array.isArray(L)||L.length&&typeof L[0]!="string")throw new Error("padding.encode input should be array of strings");for(let A of L)if(typeof A!="string")throw new Error(`padding.decode: non-string input=${A}`);let I=L.length;if(I*S%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;I>0&&L[I-1]===_;I--)if(!((I-1)*S%8))throw new Error("Invalid padding: string has too much padding");return L.slice(0,I)}}}function a(S){if(typeof S!="function")throw new Error("normalize fn should be function");return{encode:_=>_,decode:_=>S(_)}}function u(S,_,L){if(_<2)throw new Error(`convertRadix: wrong from=${_}, base cannot be less than 2`);if(L<2)throw new Error(`convertRadix: wrong to=${L}, base cannot be less than 2`);if(!Array.isArray(S))throw new Error("convertRadix: data should be array");if(!S.length)return[];let I=0;const A=[],E=Array.from(S);for(E.forEach($=>{if(e($),$<0||$>=_)throw new Error(`Wrong integer: ${$}`)});;){let $=0,M=!0;for(let U=I;U<E.length;U++){const z=E[U],D=_*$+z;if(!Number.isSafeInteger(D)||_*$/_!==$||D-z!==_*$)throw new Error("convertRadix: carry overflow");if($=D%L,E[U]=Math.floor(D/L),!Number.isSafeInteger(E[U])||E[U]*L+$!==D)throw new Error("convertRadix: carry overflow");if(M)E[U]?M=!1:I=U;else continue}if(A.push($),M)break}for(let $=0;$<S.length-1&&S[$]===0;$++)A.push(0);return A.reverse()}const c=(S,_)=>_?c(_,S%_):S,l=(S,_)=>S+(_-c(S,_));function h(S,_,L,I){if(!Array.isArray(S))throw new Error("convertRadix2: data should be array");if(_<=0||_>32)throw new Error(`convertRadix2: wrong from=${_}`);if(L<=0||L>32)throw new Error(`convertRadix2: wrong to=${L}`);if(l(_,L)>32)throw new Error(`convertRadix2: carry overflow from=${_} to=${L} carryBits=${l(_,L)}`);let A=0,E=0;const $=2**L-1,M=[];for(const U of S){if(e(U),U>=2**_)throw new Error(`convertRadix2: invalid data word=${U} from=${_}`);if(A=A<<_|U,E+_>32)throw new Error(`convertRadix2: carry overflow pos=${E} from=${_}`);for(E+=_;E>=L;E-=L)M.push((A>>E-L&$)>>>0);A&=2**E-1}if(A=A<<L-E&$,!I&&E>=_)throw new Error("Excess padding");if(!I&&A)throw new Error(`Non-zero padding: ${A}`);return I&&E>0&&M.push(A>>>0),M}function f(S){return e(S),{encode:_=>{if(!(_ instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return u(Array.from(_),2**8,S)},decode:_=>{if(!Array.isArray(_)||_.length&&typeof _[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(u(_,S,2**8))}}}function p(S,_=!1){if(e(S),S<=0||S>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,S)>32||l(S,8)>32)throw new Error("radix2: carry overflow");return{encode:L=>{if(!(L instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(L),8,S,!_)},decode:L=>{if(!Array.isArray(L)||L.length&&typeof L[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(L,S,8,_))}}}function b(S){if(typeof S!="function")throw new Error("unsafeWrapper fn should be function");return function(..._){try{return S.apply(null,_)}catch{}}}function v(S,_){if(e(S),typeof _!="function")throw new Error("checksum fn should be function");return{encode(L){if(!(L instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const I=_(L).slice(0,S),A=new Uint8Array(L.length+S);return A.set(L),A.set(I,L.length),A},decode(L){if(!(L instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const I=L.slice(0,-S),A=_(I).slice(0,S),E=L.slice(-S);for(let $=0;$<S;$++)if(A[$]!==E[$])throw new Error("Invalid checksum");return I}}}n.utils={alphabet:r,chain:t,checksum:v,radix:f,radix2:p,join:s,padding:o},n.base16=t(p(4),r("0123456789ABCDEF"),s("")),n.base32=t(p(5),r("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),o(5),s("")),n.base32hex=t(p(5),r("0123456789ABCDEFGHIJKLMNOPQRSTUV"),o(5),s("")),n.base32crockford=t(p(5),r("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),s(""),a(S=>S.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),n.base64=t(p(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),o(6),s("")),n.base64url=t(p(6),r("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),o(6),s(""));const m=S=>t(f(58),r(S),s(""));n.base58=m("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),n.base58flickr=m("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),n.base58xrp=m("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const y=[0,2,3,5,6,7,9,10,11];n.base58xmr={encode(S){let _="";for(let L=0;L<S.length;L+=8){const I=S.subarray(L,L+8);_+=n.base58.encode(I).padStart(y[I.length],"1")}return _},decode(S){let _=[];for(let L=0;L<S.length;L+=11){const I=S.slice(L,L+11),A=y.indexOf(I.length),E=n.base58.decode(I);for(let $=0;$<E.length-A;$++)if(E[$]!==0)throw new Error("base58xmr: wrong padding");_=_.concat(Array.from(E.slice(E.length-A)))}return Uint8Array.from(_)}};const w=S=>t(v(4,_=>S(S(_))),n.base58);n.base58check=w;const x=t(r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),s("")),k=[996825010,642813549,513874426,1027748829,705979059];function C(S){const _=S>>25;let L=(S&33554431)<<5;for(let I=0;I<k.length;I++)(_>>I&1)===1&&(L^=k[I]);return L}function P(S,_,L=1){const I=S.length;let A=1;for(let E=0;E<I;E++){const $=S.charCodeAt(E);if($<33||$>126)throw new Error(`Invalid prefix (${S})`);A=C(A)^$>>5}A=C(A);for(let E=0;E<I;E++)A=C(A)^S.charCodeAt(E)&31;for(let E of _)A=C(A)^E;for(let E=0;E<6;E++)A=C(A);return A^=L,x.encode(h([A%2**30],30,5,!1))}function R(S){const _=S==="bech32"?1:734539939,L=p(5),I=L.decode,A=L.encode,E=b(I);function $(D,V,W=90){if(typeof D!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof D}`);if(!Array.isArray(V)||V.length&&typeof V[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof V}`);const Z=D.length+7+V.length;if(W!==!1&&Z>W)throw new TypeError(`Length ${Z} exceeds limit ${W}`);return D=D.toLowerCase(),`${D}1${x.encode(V)}${P(D,V,_)}`}function M(D,V=90){if(typeof D!="string")throw new Error(`bech32.decode input should be string, not ${typeof D}`);if(D.length<8||V!==!1&&D.length>V)throw new TypeError(`Wrong string length: ${D.length} (${D}). Expected (8..${V})`);const W=D.toLowerCase();if(D!==W&&D!==D.toUpperCase())throw new Error("String must be lowercase or uppercase");D=W;const Z=D.lastIndexOf("1");if(Z===0||Z===-1)throw new Error('Letter "1" must be present between prefix and data only');const G=D.slice(0,Z),K=D.slice(Z+1);if(K.length<6)throw new Error("Data must be at least 6 characters long");const ne=x.decode(K).slice(0,-6),ae=P(G,ne,_);if(!K.endsWith(ae))throw new Error(`Invalid checksum in ${D}: expected "${ae}"`);return{prefix:G,words:ne}}const U=b(M);function z(D){const{prefix:V,words:W}=M(D,!1);return{prefix:V,words:W,bytes:I(W)}}return{encode:$,decode:M,decodeToBytes:z,decodeUnsafe:U,fromWords:I,fromWordsUnsafe:E,toWords:A}}n.bech32=R("bech32"),n.bech32m=R("bech32m"),n.utf8={encode:S=>new TextDecoder().decode(S),decode:S=>new TextEncoder().encode(S)},n.hex=t(p(4),r("0123456789abcdef"),s(""),a(S=>{if(typeof S!="string"||S.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof S} with length ${S.length}`);return S.toLowerCase()}));const N={utf8:n.utf8,hex:n.hex,base16:n.base16,base32:n.base32,base64:n.base64,base64url:n.base64url,base58:n.base58,base58xmr:n.base58xmr},B=`Invalid encoding type. Available types: ${Object.keys(N).join(", ")}`,O=(S,_)=>{if(typeof S!="string"||!N.hasOwnProperty(S))throw new TypeError(B);if(!(_ instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return N[S].encode(_)};n.bytesToString=O,n.str=n.bytesToString;const H=(S,_)=>{if(!N.hasOwnProperty(S))throw new TypeError(B);if(typeof _!="string")throw new TypeError("stringToBytes() expects string");return N[S].decode(_)};n.stringToBytes=H,n.bytes=n.stringToBytes})(lib);const{bech32,hex,utf8}=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 n=0,e=Object.keys(TAGCODES);n<e.length;n++)e[n],TAGCODES[e[n]].toString();var NDKKind=(n=>(n[n.Metadata=0]="Metadata",n[n.Text=1]="Text",n[n.RecommendRelay=2]="RecommendRelay",n[n.Contacts=3]="Contacts",n[n.EncryptedDirectMessage=4]="EncryptedDirectMessage",n[n.EventDeletion=5]="EventDeletion",n[n.Repost=6]="Repost",n[n.Reaction=7]="Reaction",n[n.BadgeAward=8]="BadgeAward",n[n.GroupChat=9]="GroupChat",n[n.GroupNote=11]="GroupNote",n[n.GroupReply=12]="GroupReply",n[n.GiftWrapSeal=13]="GiftWrapSeal",n[n.PrivateDirectMessage=14]="PrivateDirectMessage",n[n.Image=20]="Image",n[n.Video=21]="Video",n[n.ShortVideo=22]="ShortVideo",n[n.Story=23]="Story",n[n.Vanish=62]="Vanish",n[n.CashuWalletBackup=375]="CashuWalletBackup",n[n.GiftWrap=1059]="GiftWrap",n[n.GenericRepost=16]="GenericRepost",n[n.ChannelCreation=40]="ChannelCreation",n[n.ChannelMetadata=41]="ChannelMetadata",n[n.ChannelMessage=42]="ChannelMessage",n[n.ChannelHideMessage=43]="ChannelHideMessage",n[n.ChannelMuteUser=44]="ChannelMuteUser",n[n.GenericReply=1111]="GenericReply",n[n.Media=1063]="Media",n[n.Report=1984]="Report",n[n.Label=1985]="Label",n[n.DVMReqTextExtraction=5e3]="DVMReqTextExtraction",n[n.DVMReqTextSummarization=5001]="DVMReqTextSummarization",n[n.DVMReqTextTranslation=5002]="DVMReqTextTranslation",n[n.DVMReqTextGeneration=5050]="DVMReqTextGeneration",n[n.DVMReqImageGeneration=5100]="DVMReqImageGeneration",n[n.DVMReqTextToSpeech=5250]="DVMReqTextToSpeech",n[n.DVMReqDiscoveryNostrContent=5300]="DVMReqDiscoveryNostrContent",n[n.DVMReqDiscoveryNostrPeople=5301]="DVMReqDiscoveryNostrPeople",n[n.DVMReqTimestamping=5900]="DVMReqTimestamping",n[n.DVMEventSchedule=5905]="DVMEventSchedule",n[n.DVMJobFeedback=7e3]="DVMJobFeedback",n[n.Subscribe=7001]="Subscribe",n[n.Unsubscribe=7002]="Unsubscribe",n[n.SubscriptionReceipt=7003]="SubscriptionReceipt",n[n.CashuReserve=7373]="CashuReserve",n[n.CashuQuote=7374]="CashuQuote",n[n.CashuToken=7375]="CashuToken",n[n.CashuWalletTx=7376]="CashuWalletTx",n[n.GroupAdminAddUser=9e3]="GroupAdminAddUser",n[n.GroupAdminRemoveUser=9001]="GroupAdminRemoveUser",n[n.GroupAdminEditMetadata=9002]="GroupAdminEditMetadata",n[n.GroupAdminEditStatus=9006]="GroupAdminEditStatus",n[n.GroupAdminCreateGroup=9007]="GroupAdminCreateGroup",n[n.GroupAdminRequestJoin=9021]="GroupAdminRequestJoin",n[n.MuteList=1e4]="MuteList",n[n.PinList=10001]="PinList",n[n.RelayList=10002]="RelayList",n[n.BookmarkList=10003]="BookmarkList",n[n.CommunityList=10004]="CommunityList",n[n.PublicChatList=10005]="PublicChatList",n[n.BlockRelayList=10006]="BlockRelayList",n[n.SearchRelayList=10007]="SearchRelayList",n[n.SimpleGroupList=10009]="SimpleGroupList",n[n.InterestList=10015]="InterestList",n[n.CashuMintList=10019]="CashuMintList",n[n.EmojiList=10030]="EmojiList",n[n.DirectMessageReceiveRelayList=10050]="DirectMessageReceiveRelayList",n[n.BlossomList=10063]="BlossomList",n[n.NostrWaletConnectInfo=13194]="NostrWaletConnectInfo",n[n.TierList=17e3]="TierList",n[n.CashuWallet=17375]="CashuWallet",n[n.FollowSet=3e4]="FollowSet",n[n.CategorizedPeopleList=3e4]="CategorizedPeopleList",n[n.CategorizedBookmarkList=30001]="CategorizedBookmarkList",n[n.RelaySet=30002]="RelaySet",n[n.CategorizedRelayList=30002]="CategorizedRelayList",n[n.BookmarkSet=30003]="BookmarkSet",n[n.CurationSet=30004]="CurationSet",n[n.ArticleCurationSet=30004]="ArticleCurationSet",n[n.VideoCurationSet=30005]="VideoCurationSet",n[n.ImageCurationSet=30006]="ImageCurationSet",n[n.InterestSet=30015]="InterestSet",n[n.InterestsList=30015]="InterestsList",n[n.EmojiSet=30030]="EmojiSet",n[n.ModularArticle=30040]="ModularArticle",n[n.ModularArticleItem=30041]="ModularArticleItem",n[n.Wiki=30818]="Wiki",n[n.Draft=31234]="Draft",n[n.SubscriptionTier=37001]="SubscriptionTier",n[n.EcashMintRecommendation=38e3]="EcashMintRecommendation",n[n.HighlightSet=39802]="HighlightSet",n[n.CategorizedHighlightList=39802]="CategorizedHighlightList",n[n.Nutzap=9321]="Nutzap",n[n.ZapRequest=9734]="ZapRequest",n[n.Zap=9735]="Zap",n[n.Highlight=9802]="Highlight",n[n.ClientAuth=22242]="ClientAuth",n[n.NostrWalletConnectReq=23194]="NostrWalletConnectReq",n[n.NostrWalletConnectRes=23195]="NostrWalletConnectRes",n[n.NostrConnect=24133]="NostrConnect",n[n.BlossomUpload=24242]="BlossomUpload",n[n.HttpAuth=27235]="HttpAuth",n[n.ProfileBadge=30008]="ProfileBadge",n[n.BadgeDefinition=30009]="BadgeDefinition",n[n.MarketStall=30017]="MarketStall",n[n.MarketProduct=30018]="MarketProduct",n[n.Article=30023]="Article",n[n.AppSpecificData=30078]="AppSpecificData",n[n.Classified=30402]="Classified",n[n.HorizontalVideo=34235]="HorizontalVideo",n[n.VerticalVideo=34236]="VerticalVideo",n[n.LegacyCashuWallet=37375]="LegacyCashuWallet",n[n.GroupMetadata=39e3]="GroupMetadata",n[n.GroupAdmins=39001]="GroupAdmins",n[n.GroupMembers=39002]="GroupMembers",n[n.AppRecommendation=31989]="AppRecommendation",n[n.AppHandler=31990]="AppHandler",n))(NDKKind||{});function getRelaysForSync(n,e,t="write"){if(!n.outboxTracker)return;const r=n.outboxTracker.data.get(e);if(r)return t==="write"?r.writeRelays:r.readRelays}async function getWriteRelaysFor(n,e,t="write"){if(n.outboxTracker)return n.outboxTracker.data.has(e)||await n.outboxTracker.trackUsers([e]),getRelaysForSync(n,e,t)}function getTopRelaysForAuthors(n,e){const t=new Map;return e.forEach(s=>{const o=getRelaysForSync(n,s);o&&o.forEach(a=>{const u=t.get(a)||0;t.set(a,u+1)})}),Array.from(t.entries()).sort((s,o)=>o[1]-s[1]).map(s=>s[0])}function getAllRelaysForAllPubkeys(n,e,t="read"){const r=new Map,s=new Set;return e.forEach(o=>{const a=getRelaysForSync(n,o,t);a&&a.size>0?(a.forEach(u=>{(r.get(u)||new Set).add(o)}),r.set(o,a)):s.add(o)}),{pubkeysToRelays:r,authorsMissingRelays:s}}function chooseRelayCombinationForPubkeys(n,e,t,{count:r,preferredRelays:s}={}){r??(r=2),s??(s=new Set);const o=n.pool,a=o.connectedRelays();a.forEach(p=>{s==null||s.add(p.url)});const u=new Map,{pubkeysToRelays:c,authorsMissingRelays:l}=getAllRelaysForAllPubkeys(n,e,t),h=getTopRelaysForAuthors(n,e),f=(p,b)=>{const v=u.get(b)||[];v.push(p),u.set(b,v)};for(const[p,b]of c.entries()){let v=r;for(const m of a)b.has(m.url)&&(f(p,m.url),v--);for(const m of b)u.has(m)&&(f(p,m),v--);if(!(v<=0))for(const m of h){if(v<=0)break;b.has(m)&&(f(p,m),v--)}}for(const p of l)o.permanentAndConnectedRelays().forEach(b=>{const v=u.get(b.url)||[];v.push(p),u.set(b.url,v)});return u}function getRelaysForFilterWithAuthors(n,e,t=2){return chooseRelayCombinationForPubkeys(n,e,"write",{count:t})}function tryNormalizeRelayUrl(n){try{return normalizeRelayUrl(n)}catch{return}}function normalizeRelayUrl(n){let e=normalizeUrl(n,{stripAuthentication:!1,stripWWW:!1,stripHash:!0});return e.endsWith("/")||(e+="/"),e}function normalize(n){const e=new Set;for(const t of n)try{e.add(normalizeRelayUrl(t))}catch{}return Array.from(e)}var DATA_URL_DEFAULT_MIME_TYPE="text/plain",DATA_URL_DEFAULT_CHARSET="us-ascii",testParameter=(n,e)=>e.some(t=>t instanceof RegExp?t.test(n):t===n),supportedProtocols=new Set(["https:","http:","file:"]),hasCustomProtocol=n=>{try{const{protocol:e}=new URL(n);return e.endsWith(":")&&!e.includes(".")&&!supportedProtocols.has(e)}catch{return!1}},normalizeDataURL=(n,{stripHash:e})=>{var f,p,b,v;const t=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(n);if(!t)throw new Error(`Invalid URL: ${n}`);const r=((f=t.groups)==null?void 0:f.type)??"",s=((p=t.groups)==null?void 0:p.data)??"";let o=((b=t.groups)==null?void 0:b.hash)??"";const a=r.split(";");o=e?"":o;let u=!1;a[a.length-1]==="base64"&&(a.pop(),u=!0);const c=((v=a.shift())==null?void 0:v.toLowerCase())??"",h=[...a.map(m=>{let[y,w=""]=m.split("=").map(x=>x.trim());return y==="charset"&&(w=w.toLowerCase(),w===DATA_URL_DEFAULT_CHARSET)?"":`${y}${w?`=${w}`:""}`}).filter(Boolean)];return u&&h.push("base64"),(h.length>0||c&&c!==DATA_URL_DEFAULT_MIME_TYPE)&&h.unshift(c),`data:${h.join(";")},${u?s.trim():s}${o?`#${o}`:""}`};function normalizeUrl(n,e={}){if(e={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,...e},typeof e.defaultProtocol=="string"&&!e.defaultProtocol.endsWith(":")&&(e.defaultProtocol=`${e.defaultProtocol}:`),n=n.trim(),/^data:/i.test(n))return normalizeDataURL(n,e);if(hasCustomProtocol(n))return n;const t=n.startsWith("//");!t&&/^\.*\//.test(n)||(n=n.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,e.defaultProtocol));const s=new URL(n);if(s.hostname=s.hostname.toLowerCase(),e.forceHttp&&e.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");if(e.forceHttp&&s.protocol==="https:"&&(s.protocol="http:"),e.forceHttps&&s.protocol==="http:"&&(s.protocol="https:"),e.stripAuthentication&&(s.username="",s.password=""),e.stripHash?s.hash="":e.stripTextFragment&&(s.hash=s.hash.replace(/#?:~:text.*?$/i,"")),s.pathname){const a=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let u=0,c="";for(;;){const h=a.exec(s.pathname);if(!h)break;const f=h[0],p=h.index,b=s.pathname.slice(u,p);c+=b.replace(/\/{2,}/g,"/"),c+=f,u=p+f.length}const l=s.pathname.slice(u,s.pathname.length);c+=l.replace(/\/{2,}/g,"/"),s.pathname=c}if(s.pathname)try{s.pathname=decodeURI(s.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let a=s.pathname.split("/");const u=a[a.length-1];testParameter(u,e.removeDirectoryIndex)&&(a=a.slice(0,-1),s.pathname=`${a.slice(1).join("/")}/`)}if(s.hostname&&(s.hostname=s.hostname.replace(/\.$/,""),e.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(s.hostname)&&(s.hostname=s.hostname.replace(/^www\./,""))),Array.isArray(e.removeQueryParameters))for(const a of[...s.searchParams.keys()])testParameter(a,e.removeQueryParameters)&&s.searchParams.delete(a);if(!Array.isArray(e.keepQueryParameters)&&e.removeQueryParameters===!0&&(s.search=""),Array.isArray(e.keepQueryParameters)&&e.keepQueryParameters.length>0)for(const a of[...s.searchParams.keys()])testParameter(a,e.keepQueryParameters)||s.searchParams.delete(a);if(e.sortQueryParameters){s.searchParams.sort();try{s.search=decodeURIComponent(s.search)}catch{}}e.removeTrailingSlash&&(s.pathname=s.pathname.replace(/\/$/,"")),e.removeExplicitPort&&s.port&&(s.port="");const o=n;return n=s.toString(),!e.removeSingleSlash&&s.pathname==="/"&&!o.endsWith("/")&&s.hash===""&&(n=n.replace(/\/$/,"")),(e.removeTrailingSlash||s.pathname==="/")&&s.hash===""&&e.removeSingleSlash&&(n=n.replace(/\/$/,"")),t&&!e.normalizeProtocol&&(n=n.replace(/^http:\/\//,"//")),e.stripProtocol&&(n=n.replace(/^(?:https?:)?\/\//,"")),n}var MAX_RECONNECT_ATTEMPTS=5,FLAPPING_THRESHOLD_MS=1e3,NDKRelayConnectivity=class{constructor(n,e){g(this,"ndkRelay");g(this,"ws");g(this,"_status");g(this,"timeoutMs");g(this,"connectedAt");g(this,"_connectionStats",{attempts:0,success:0,durations:[]});g(this,"debug");g(this,"netDebug");g(this,"connectTimeout");g(this,"reconnectTimeout");g(this,"ndk");g(this,"openSubs",new Map);g(this,"openCountRequests",new Map);g(this,"openEventPublishes",new Map);g(this,"serial",0);g(this,"baseEoseTimeout",4400);g(this,"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()}});this.ndkRelay=n,this._status=1;const t=Math.floor(Math.random()*1e3);this.debug=this.ndkRelay.debug.extend(`connectivity${t}`),this.ndk=e}async connect(n,e=!0){if(this._status!==2&&this._status!==1||this.reconnectTimeout){this.debug("Relay requested to be connected but was in state %s or it had a reconnect timeout",this._status);return}this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),n??(n=this.timeoutMs),!this.timeoutMs&&n&&(this.timeoutMs=n),this.timeoutMs&&(this.connectTimeout=setTimeout(()=>this.onConnectionError(e),this.timeoutMs));try{this.updateConnectionStats.attempt(),this._status===1?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(t){throw this.debug(`Failed to connect to ${this.ndkRelay.url}`,t),this._status=1,e?this.handleReconnection():this.ndkRelay.emit("delayed-connect",2*24*60*60*1e3),t}}disconnect(){var n;this._status=0;try{(n=this.ws)==null||n.close()}catch(e){this.debug("Failed to disconnect",e),this._status=1}}onConnectionError(n){this.debug(`Error connecting to ${this.ndkRelay.url}`,this.timeoutMs),n&&!this.reconnectTimeout&&this.handleReconnection()}onConnect(){var n;(n=this.netDebug)==null||n.call(this,"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.ndkRelay.emit("connect"),this.ndkRelay.emit("ready")}onDisconnect(){var n;(n=this.netDebug)==null||n.call(this,"disconnected",this.ndkRelay),this.updateConnectionStats.disconnected(),this._status===5&&this.handleReconnection(),this._status=1,this.ndkRelay.emit("disconnect")}onMessage(n){var e;(e=this.netDebug)==null||e.call(this,n.data,this.ndkRelay,"recv");try{const t=JSON.parse(n.data),[r,s,...o]=t;switch(r){case"EVENT":{const a=this.openSubs.get(s),u=t[2];if(!a){this.debug(`Received event for unknown subscription ${s}`);return}a.onevent(u);return}case"COUNT":{const a=t[2],u=this.openCountRequests.get(s);u&&(u.resolve(a.count),this.openCountRequests.delete(s));return}case"EOSE":{const a=this.openSubs.get(s);if(!a)return;a.oneose(s);return}case"OK":{const a=t[2],u=t[3],c=this.openEventPublishes.get(s),l=c==null?void 0:c.pop();if(!c||!l){this.debug("Received OK for unknown event publish",s);return}a?l.resolve(u):l.reject(new Error(u)),c.length===0?this.openEventPublishes.delete(s):this.openEventPublishes.set(s,c);return}case"CLOSED":{const a=this.openSubs.get(s);if(!a)return;a.onclosed(t[2]);return}case"NOTICE":this.onNotice(t[1]);return;case"AUTH":{this.onAuthRequested(t[1]);return}}}catch(t){this.debug(`Error parsing message from ${this.ndkRelay.url}: ${t.message}`,t==null?void 0:t.stack);return}}async onAuthRequested(n){var t,r,s;const e=this.ndkRelay.authPolicy??((t=this.ndk)==null?void 0:t.relayAuthDefaultPolicy);if(this.debug("Relay requested authentication",{havePolicy:!!e}),this._status===7){this.debug("Already authenticating, ignoring");return}if(this._status=6,e){if(this._status>=5){this._status=7;let o;try{o=await e(this.ndkRelay,n)}catch(a){this.debug("Authentication policy threw an error",a),o=!1}if(this.debug("Authentication policy returned",!!o),o instanceof NDKEvent||o===!0){o instanceof NDKEvent&&await this.auth(o);const a=async()=>{if(this._status>=5&&this._status<8){const u=new NDKEvent(this.ndk);u.kind=22242,u.tags=[["relay",this.ndkRelay.url],["challenge",n]],await u.sign(),this.auth(u).then(()=>{this._status=8,this.ndkRelay.emit("authed"),this.debug("Authentication successful")}).catch(c=>{this._status=6,this.ndkRelay.emit("auth:failed",c),this.debug("Authentication failed",c)})}else this.debug("Authentication failed, it changed status, status is %d",this._status)};o===!0&&((r=this.ndk)!=null&&r.signer?a().catch(u=>{console.error("Error authenticating",u)}):(this.debug("No signer available for authentication localhost"),(s=this.ndk)==null||s.once("signer:ready",a))),this._status=5,this.ndkRelay.emit("authed")}}}else this.ndkRelay.emit("auth",n)}onError(n){this.debug(`WebSocket error on ${this.ndkRelay.url}:`,n)}get status(){return this._status}isAvailable(){return this._status===5}isFlapping(){const n=this._connectionStats.durations;if(n.length%3!==0)return!1;const t=n.reduce((a,u)=>a+u,0)/n.length,r=n.map(a=>(a-t)**2).reduce((a,u)=>a+u,0)/n.length;return Math.sqrt(r)<FLAPPING_THRESHOLD_MS}async onNotice(n){this.ndkRelay.emit("notice",n)}handleReconnection(n=0){if(this.reconnectTimeout)return;if(this.isFlapping()){this.ndkRelay.emit("flapping",this._connectionStats),this._status=3;return}const e=this.connectedAt?Math.max(0,6e4-(Date.now()-this.connectedAt)):5e3*(this._connectionStats.attempts+1);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=void 0,this._status=2,this.connect().catch(t=>{n<MAX_RECONNECT_ATTEMPTS?setTimeout(()=>{this.handleReconnection(n+1)},1e3*(n+1)^4):this.debug("Reconnect failed")})},e),this.ndkRelay.emit("delayed-connect",e),this.debug("Reconnecting in",e),this._connectionStats.nextReconnectAt=Date.now()+e}async send(n){var e,t,r;this._status>=5&&((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN?((t=this.ws)==null||t.send(n),(r=this.netDebug)==null||r.call(this,n,this.ndkRelay,"send")):this.debug(`Not connected to ${this.ndkRelay.url} (%d), not sending message ${n}`,this._status)}async auth(n){const e=new Promise((t,r)=>{const s=this.openEventPublishes.get(n.id)??[];s.push({resolve:t,reject:r}),this.openEventPublishes.set(n.id,s)});return this.send(`["AUTH",${JSON.stringify(n.rawEvent())}]`),e}async publish(n){const e=new Promise((t,r)=>{const s=this.openEventPublishes.get(n.id)??[];s.length>0&&console.warn(`Duplicate event publishing detected, you are publishing event ${n.id} twice`),s.push({resolve:t,reject:r}),this.openEventPublishes.set(n.id,s)});return this.send(`["EVENT",${JSON.stringify(n)}]`),e}async count(n,e){this.serial++;const t=(e==null?void 0:e.id)||`count:${this.serial}`,r=new Promise((s,o)=>{this.openCountRequests.set(t,{resolve:s,reject:o})});return this.send(`["COUNT","${t}",${JSON.stringify(n).substring(1)}`),r}close(n,e){this.send(`["CLOSE","${n}"]`);const t=this.openSubs.get(n);this.openSubs.delete(n),t&&t.onclose(e)}req(n){`${this.send(`["REQ","${n.subId}",${JSON.stringify(n.executeFilters).substring(1)}`)}`,this.openSubs.set(n.subId,n)}get connectionStats(){return this._connectionStats}get url(){return this.ndkRelay.url}get connected(){var n;return this._status>=5&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN}},NDKRelayPublisher=class{constructor(n){g(this,"ndkRelay");g(this,"debug");this.ndkRelay=n,this.debug=n.debug.extend("publisher")}async publish(n,e=2500){let t;const r=()=>new Promise((h,f)=>{try{this.publishEvent(n).then(p=>{this.ndkRelay.emit("published",n),n.emit("relay:published",this.ndkRelay),h(!0)}).catch(f)}catch(p){f(p)}}),s=new Promise((h,f)=>{t=setTimeout(()=>{t=void 0,f(new Error(`Timeout: ${e}ms`))},e)}),o=()=>{r().then(h=>a(h)).catch(h=>u(h))};let a,u;const c=h=>{throw this.ndkRelay.debug("Publish failed",h,n.id),this.ndkRelay.emit("publish:failed",n,h),n.emit("relay:publish:failed",this.ndkRelay,h),h},l=()=>{t&&clearTimeout(t),this.ndkRelay.removeListener("connect",o)};return this.ndkRelay.status>=5?Promise.race([r(),s]).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((h,f)=>{a=h,u=f,this.ndkRelay.once("connect",o)}),s]).catch(c).finally(l))}async publishEvent(n){return this.ndkRelay.connectivity.publish(n.rawEvent())}};function filterFingerprint(n,e){const t=[];for(const s of n){const o=Object.entries(s||{}).map(([a,u])=>["since","until"].includes(a)?`${a}:${u}`:a).sort().join("-");t.push(o)}let r=e?"+":"";return r+=t.join("|"),r}function mergeFilters(n){const e=[],t={};return n.filter(r=>!!r.limit).forEach(r=>e.push(r)),n=n.filter(r=>!r.limit),n.length===0?e:(n.forEach(r=>{Object.entries(r).forEach(([s,o])=>{Array.isArray(o)?t[s]===void 0?t[s]=[...o]:t[s]=Array.from(new Set([...t[s],...o])):t[s]=o})}),[...e,t])}var NDKRelaySubscription=class{constructor(n,e,t){g(this,"fingerprint");g(this,"items",new Map);g(this,"topSubManager");g(this,"debug");g(this,"status",0);g(this,"onClose");g(this,"relay");g(this,"eosed",!1);g(this,"executionTimer");g(this,"fireTime");g(this,"delayType");g(this,"executeFilters");g(this,"id",Math.random().toString(36).substring(7));g(this,"_subId");g(this,"subIdParts",new Set);g(this,"executeOnRelayReady",()=>{if(this.status===2){if(this.items.size===0){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,items:this.items,itemsSize:this.items.size,id:this.id,subId:this.subId}),this.cleanup();return}this.debug("Executing on relay ready",{status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.status=1,this.execute()}});g(this,"reExecuteAfterAuth",(()=>{const n=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:n}),this._subId=void 0,this.status=1,this.execute(),this.debug("Re-executed after auth %s 👉 %s",n,this.subId)}).bind(this));this.relay=n,this.topSubManager=t,this.debug=n.debug.extend(`sub[${this.id}]`),this.fingerprint=e||Math.random().toString(36).substring(7)}get subId(){return this._subId?this._subId:(this._subId=this.fingerprint.slice(0,15),this._subId)}addSubIdPart(n){this.subIdParts.add(n)}addItem(n,e){if(this.debug("Adding item",{filters:e,internalId:n.internalId,status:this.status,fingerprint:this.fingerprint,id:this.subId,items:this.items,itemsSize:this.items.size}),!this.items.has(n.internalId))switch(n.on("close",this.removeItem.bind(this,n)),this.items.set(n.internalId,{subscription:n,filters:e}),this.status!==3&&n.subId&&(!this._subId||this._subId.length<48)&&(this.status===0||this.status===1)&&this.addSubIdPart(n.subId),this.status){case 0:this.evaluateExecutionPlan(n);break;case 3:break;case 1:this.evaluateExecutionPlan(n);break;case 4:throw this.debug("Subscription is closed, cannot add new items %o (%o)",n,e),new Error("Cannot add new items to a closed subscription")}}removeItem(n){if(this.items.delete(n.internalId),this.items.size===0){if(!this.eosed)return;this.close(),this.cleanup()}}close(){if(this.status===4)return;const n=this.status;if(this.status=4,n===3)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:n,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(n){if(!n.isGroupable()){this.status=1,this.execute();return}if(n.filters.find(r=>!!r.limit)&&(this.executeFilters=this.compileFilters(),this.executeFilters.length>=10)){this.status=1,this.execute();return}const e=n.groupableDelay,t=n.groupableDelayType;if(!e)throw new Error("Cannot group a subscription without a delay");if(this.status===0)this.schedule(e,t);else{const r=this.delayType,s=this.fireTime-Date.now();if(r==="at-least"&&t==="at-least")s<e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-least"&&t==="at-most")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-most"&&t==="at-most")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else if(r==="at-most"&&t==="at-least")s>e&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(e,t));else throw new Error(`Unknown delay type combination ${r} ${t}`)}}schedule(n,e){this.status=1;const t=Date.now();this.fireTime=t+n,this.delayType=e;const r=setTimeout(this.execute.bind(this),n);e==="at-least"&&(this.executionTimer=r)}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)}`}execute(){if(this.status===1){if(!this.relay.connected){this.status=2,this.debug("Waiting for relay to be ready",{status:this.status,id:this.subId,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.relay.once("ready",this.executeOnRelayReady);return}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(n){this.topSubManager.dispatchEvent(n,this.relay)}oneose(n){if(this.eosed=!0,n!==this.subId){this.debug("Received EOSE for an abandoned subscription",n,this.subId),this.relay.close(n);return}this.items.size===0&&this.close();for(const{subscription:e}of this.items.values())e.eoseReceived(this.relay),e.closeOnEose&&(this.debug("Removing item because of EOSE",{filters:e.filters,internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.removeItem(e))}onclose(n){this.status=4}onclosed(n){if(n)for(const{subscription:e}of this.items.values())e.closedReceived(this.relay,n)}compileFilters(){const n=[],e=Array.from(this.items.values()).map(r=>r.filters);if(!e[0])return this.debug("👀 No filters to merge",this.items),console.error("BUG: No filters to merge!",this.items),[];const t=e[0].length;for(let r=0;r<t;r++){const s=e.map(o=>o[r]);n.push(...mergeFilters(s))}return n}},NDKRelaySubscriptionManager=class{constructor(n,e){g(this,"relay");g(this,"subscriptions");g(this,"generalSubManager");this.relay=n,this.subscriptions=new Map,this.generalSubManager=e}addSubscription(n,e){let t;if(!n.isGroupable())t=this.createSubscription(n,e);else{const r=filterFingerprint(e,n.closeOnEose);r&&(t=(this.subscriptions.get(r)||[]).find(o=>o.status<3)),t??(t=this.createSubscription(n,e,r))}t.addItem(n,e)}createSubscription(n,e,t){const r=new NDKRelaySubscription(this.relay,t||null,this.generalSubManager);r.onClose=this.onRelaySubscriptionClose.bind(this);const s=this.subscriptions.get(r.fingerprint)??[];return this.subscriptions.set(r.fingerprint,[...s,r]),r}onRelaySubscriptionClose(n){let e=this.subscriptions.get(n.fingerprint)??[];e?e.length===1?this.subscriptions.delete(n.fingerprint):(e=e.filter(t=>t.id!==n.id),this.subscriptions.set(n.fingerprint,e)):console.warn("Unexpectedly did not find a subscription with fingerprint",n.fingerprint)}},NDKRelay=(oe=class extends lib$1.EventEmitter{constructor(t,r,s){super();g(this,"url");g(this,"scores");g(this,"connectivity");g(this,"subs");g(this,"publisher");g(this,"authPolicy");g(this,"lowestValidationRatio");g(this,"targetValidationRatio");g(this,"validationRatioFn");g(this,"validatedEventCount",0);g(this,"nonValidatedEventCount",0);g(this,"trusted",!1);g(this,"complaining",!1);g(this,"debug");g(this,"req");g(this,"close");this.url=normalizeRelayUrl(t),this.scores=new Map,this.debug=createDebug5(`ndk:relay:${t}`),this.connectivity=new NDKRelayConnectivity(this,s),this.connectivity.netDebug=s==null?void 0: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=r,this.targetValidationRatio=s==null?void 0:s.initialValidationRatio,this.lowestValidationRatio=s==null?void 0:s.lowestValidationRatio,this.validationRatioFn=((s==null?void 0:s.validationRatioFn)??oe.defaultValidationRatioUpdateFn).bind(this),this.updateValidationRatio(),s||console.trace("relay created without ndk")}updateValidationRatio(){setTimeout(()=>{this.updateValidationRatio()},3e4)}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(t,r=!0){return this.connectivity.connect(t,r)}disconnect(){this.status!==1&&this.connectivity.disconnect()}subscribe(t,r){this.subs.addSubscription(t,r)}async publish(t,r=2500){return this.publisher.publish(t,r)}referenceTags(){return[["r",this.url]]}addValidatedEvent(){this.validatedEventCount++}addNonValidatedEvent(){this.nonValidatedEventCount++}get validationRatio(){return this.nonValidatedEventCount===0?1:this.validatedEventCount/(this.validatedEventCount+this.nonValidatedEventCount)}shouldValidateEvent(){return this.trusted?!1:this.targetValidationRatio===void 0?!0:this.validationRatio<this.targetValidationRatio}get connected(){return this.connectivity.connected}},g(oe,"defaultValidationRatioUpdateFn",(t,r,s)=>{if(t.lowestValidationRatio===void 0||t.targetValidationRatio===void 0)return 1;let o=t.validationRatio;if(t.validationRatio>t.targetValidationRatio){const a=r/100;o=Math.max(t.lowestValidationRatio,t.validationRatio-a)}return o<t.validationRatio?o:t.validationRatio}),oe),NDKPublishError=class extends Error{constructor(e,t,r,s){super(e);g(this,"errors");g(this,"publishedToRelays");g(this,"intendedRelaySet");this.errors=t,this.publishedToRelays=r,this.intendedRelaySet=s}get relayErrors(){const e=[];for(const[t,r]of this.errors)e.push(`${t.url}: ${r}`);return e.join(`
76
+ `)}},NDKRelaySet=class Tt{constructor(e,t,r){g(this,"relays");g(this,"debug");g(this,"ndk");g(this,"pool");this.relays=e,this.ndk=t,this.pool=r??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(e,t,r=!0,s){if(s=s??t.pool,!s)throw new Error("No pool provided");const o=new Set;for(const a of e){const u=s.relays.get(normalizeRelayUrl(a));if(u)u.status<5&&r&&u.connect(),o.add(u);else{const c=new NDKRelay(normalizeRelayUrl(a),t==null?void 0:t.relayAuthDefaultPolicy,t);s.useTemporaryRelay(c,void 0,`requested from fromRelayUrls ${e}`),o.add(c)}}return new Tt(new Set(o),t,s)}async publish(e,t,r=1){var c;const s=new Set,o=new Map,a=e.isEphemeral();e.publishStatus="pending";const u=l=>{s.add(l)};e.on("relay:published",u);try{const l=Array.from(this.relays).map(h=>new Promise(f=>{const p=t?setTimeout(()=>{s.has(h)||(o.set(h,new Error(`Publish timeout after ${t}ms`)),f(!1))},t):null;h.publish(e,t).then(b=>{p&&clearTimeout(p),b?(s.add(h),f(!0)):f(!1)}).catch(b=>{p&&clearTimeout(p),a||o.set(h,b),f(!1)})}));if(await Promise.all(l),s.size<r){if(!a){const h=new NDKPublishError("Not enough relays received the event",o,s,this);throw e.publishStatus="error",e.publishError=h,(c=this.ndk)==null||c.emit("event:publish-failed",e,h,this.relayUrls),h}}else e.publishStatus="success",e.emit("published",{relaySet:this,publishedToRelays:s});return s}finally{e.off("relay:published",u)}}get size(){return this.relays.size}},d=createDebug5("ndk:outbox:calculate");async function calculateRelaySetFromEvent(n,e){var a;const t=new Set,r=await getWriteRelaysFor(n,e.pubkey);r&&r.forEach(u=>{var l;const c=(l=n.pool)==null?void 0:l.getRelay(u);c&&t.add(c)});let s=e.tags.filter(u=>["a","e"].includes(u[0])).map(u=>u[2]).filter(u=>u==null?void 0:u.startsWith("wss://")).filter(u=>{try{return new URL(u),!0}catch{return!1}}).map(u=>normalizeRelayUrl(u));s=Array.from(new Set(s)).slice(0,5),s.forEach(u=>{var l;const c=(l=n.pool)==null?void 0:l.getRelay(u,!0,!0);c&&(d("Adding relay hint %s",u),t.add(c))});const o=e.getMatchingTags("p").map(u=>u[1]);return o.length<5?Array.from(chooseRelayCombinationForPubkeys(n,o,"read",{preferredRelays:new Set(r)}).keys()).forEach(c=>{var h;const l=(h=n.pool)==null?void 0:h.getRelay(c,!1,!0);l&&(d("Adding p-tagged relay %s",c),t.add(l))}):d("Too many p-tags to consider %d",o.length),(a=n.pool)==null||a.permanentAndConnectedRelays().forEach(u=>t.add(u)),new NDKRelaySet(t,n)}function calculateRelaySetsFromFilter(n,e,t){const r=new Map,s=new Set;if(e.forEach(o=>{o.authors&&o.authors.forEach(a=>s.add(a))}),s.size>0){const o=getRelaysForFilterWithAuthors(n,Array.from(s));for(const a of o.keys())r.set(a,[]);for(const a of e)if(a.authors)for(const[u,c]of o.entries()){const l=a.authors.filter(h=>c.includes(h));r.set(u,[...r.get(u),{...a,authors:l}])}else for(const u of o.keys())r.set(u,[...r.get(u),a])}else n.explicitRelayUrls&&n.explicitRelayUrls.forEach(o=>{r.set(o,e)});return r.size===0&&t.permanentAndConnectedRelays().slice(0,5).forEach(o=>{r.set(o.url,e)}),r}function calculateRelaySetsFromFilters(n,e,t){return calculateRelaySetsFromFilter(n,e,t)}function mergeTags(n,e){const t=new Map,r=a=>a.join(","),s=(a,u)=>a.every((c,l)=>c===u[l]),o=a=>{for(const[u,c]of t)if(s(c,a)||s(a,c)){a.length>=c.length&&t.set(u,a);return}t.set(r(a),a)};return n.concat(e).forEach(o),Array.from(t.values())}var hashtagRegex=new RegExp(`(?<=\\s|^)(#[^\\s!@#$%^&*()=+./,[{\\]};:'"?><]+)`,"g");function generateHashtags(n){const e=n.match(hashtagRegex),t=new Set,r=new Set;if(e)for(const s of e)t.has(s.slice(1))||(r.add(s.slice(1)),t.add(s.slice(1)));return Array.from(r)}async function generateContentTags(n,e=[]){const t=/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,r=[],s=a=>{e.find(u=>["q",a[0]].includes(u[0])&&u[1]===a[1])||e.push(a)};n=n.replace(t,a=>{try{const u=a.split(/(@|nostr:)/)[2],{type:c,data:l}=nip19_exports.decode(u);let h;switch(c){case"npub":h=["p",l];break;case"nprofile":h=["p",l.pubkey];break;case"note":r.push(new Promise(async f=>{s(["q",l,await maybeGetEventRelayUrl(u)]),f()}));break;case"nevent":r.push(new Promise(async f=>{const{id:p,author:b}=l;let{relays:v}=l;(!v||v.length===0)&&(v=[await maybeGetEventRelayUrl(u)]),s(["q",p,v[0]]),b&&s(["p",b]),f()}));break;case"naddr":r.push(new Promise(async f=>{const p=[l.kind,l.pubkey,l.identifier].join(":");let b=l.relays??[];b.length===0&&(b=[await maybeGetEventRelayUrl(u)]),s(["q",p,b[0]]),s(["p",l.pubkey]),f()}));break;default:return a}return h&&s(h),`nostr:${u}`}catch{return a}}),await Promise.all(r);const o=generateHashtags(n).map(a=>["t",a]);return e=mergeTags(e,o),{content:n,tags:e}}async function maybeGetEventRelayUrl(n){return""}async function encrypt(n,e,t="nip44"){let r;if(!this.ndk)throw new Error("No NDK instance found!");let s=e;if(s||(this.ndk.assertSigner(),s=this.ndk.signer),!s)throw new Error("no NDK signer");const o=n||(()=>{const a=this.getMatchingTags("p");if(a.length!==1)throw new Error("No recipient could be determined and no explicit recipient was provided");return this.ndk.getUser({pubkey:a[0][1]})})();if(t==="nip44"&&await isEncryptionEnabled(s,"nip44")&&(r=await s.encrypt(o,this.content,"nip44")),(!r||t==="nip04")&&await isEncryptionEnabled(s,"nip04")&&(r=await s.encrypt(o,this.content,"nip04")),!r)throw new Error("Failed to encrypt event.");this.content=r}async function decrypt(n,e,t){var u,c,l,h;if((c=(u=this.ndk)==null?void 0:u.cacheAdapter)!=null&&c.getDecryptedEvent){let f=null;if(typeof this.ndk.cacheAdapter.getDecryptedEvent=="function"&&(f=this.ndk.cacheAdapter.getDecryptedEvent(this.id)),f){this.content=f.content;return}}let r;if(!this.ndk)throw new Error("No NDK instance found!");let s=e;if(s||(this.ndk.assertSigner(),s=this.ndk.signer),!s)throw new Error("no NDK signer");const o=n||this.author;if(!o)throw new Error("No sender provided and no author available");const a=t||(this.content.match(/\\?iv=/)?"nip04":"nip44");if((a==="nip04"||this.kind===4)&&await isEncryptionEnabled(s,"nip04")&&this.content.search("\\?iv=")&&(r=await s.decrypt(o,this.content,"nip04")),!r&&a==="nip44"&&await isEncryptionEnabled(s,"nip44")&&(r=await s.decrypt(o,this.content,"nip44")),!r)throw new Error("Failed to decrypt event.");this.content=r,(h=(l=this.ndk)==null?void 0:l.cacheAdapter)!=null&&h.addDecryptedEvent&&this.ndk.cacheAdapter.addDecryptedEvent(this)}async function isEncryptionEnabled(n,e){return n.encryptionEnabled?e?!!await n.encryptionEnabled(e):!0:!1}function eventHasETagMarkers(n){for(const e of n.tags)if(e[0]==="e"&&(e[3]??"").length>0)return!0;return!1}function getRootTag(n,e){e??(e=n.tagType());const t=n.tags.find(isTagRootTag);if(!t){if(eventHasETagMarkers(n))return;const r=n.getMatchingTags(e);if(r.length<3)return r[0]}return t}var nip22RootTags=new Set(["A","E","I"]),nip22ReplyTags=new Set(["a","e","i"]);function getReplyTag(n,e){if(n.kind===1111){let s;for(const o of n.tags)if(nip22RootTags.has(o[0]))s=o;else if(nip22ReplyTags.has(o[0])){s=o;break}return s}e??(e=n.tagType());let t=!1,r;for(const s of n.tags)if(s[0]===e){if((s[3]??"").length>0&&(t=!0),t&&s[3]==="reply")return s;t&&s[3]==="root"&&(r=s),t||(r=s)}return r}function isTagRootTag(n){return n[0]==="E"||n[3]==="root"}async function fetchTaggedEvent(n,e){if(!this.ndk)throw new Error("NDK instance not found");const t=this.getMatchingTags(n,e);if(t.length===0)return;const[r,s,o]=t[0];let a=o!==""?this.ndk.pool.getRelay(o):void 0;return await this.ndk.fetchEvent(s,{},a)}async function fetchRootEvent(n){if(!this.ndk)throw new Error("NDK instance not found");const e=getRootTag(this);if(e)return this.ndk.fetchEventFromTag(e,this,n)}async function fetchReplyEvent(n){if(!this.ndk)throw new Error("NDK instance not found");const e=getReplyTag(this);if(e)return this.ndk.fetchEventFromTag(e,this,n)}function isReplaceable(){if(this.kind===void 0)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(this.kind===void 0)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function isParamReplaceable(){if(this.kind===void 0)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}var DEFAULT_RELAY_COUNT=2;function encode(n=DEFAULT_RELAY_COUNT){let e=[];return this.onRelays.length>0?e=this.onRelays.map(t=>t.url):this.relay&&(e=[this.relay.url]),e.length>n&&(e=e.slice(0,n)),this.isParamReplaceable()?nip19_exports.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:e}):e.length>0?nip19_exports.neventEncode({id:this.tagId(),relays:e,author:this.pubkey}):nip19_exports.noteEncode(this.tagId())}async function repost(n=!0,e){if(!e&&n){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),e=this.ndk.signer}const t=new NDKEvent(this.ndk,{kind:getKind(this)});return this.isProtected||(t.content=JSON.stringify(this.rawEvent())),t.tag(this),this.kind!==1&&t.tags.push(["k",`${this.kind}`]),e&&await t.sign(e),n&&await t.publish(),t}function getKind(n){return n.kind===1?6:16}function serialize(n=!1,e=!1){const t=[0,this.pubkey,this.created_at,this.kind,this.tags,this.content];return n&&t.push(this.sig),e&&t.push(this.id),JSON.stringify(t)}function deserialize(n){const e=JSON.parse(n),t={pubkey:e[1],created_at:e[2],kind:e[3],tags:e[4],content:e[5]};return e.length>=7&&(t.sig=e[6]),e.length>=8&&(t.id=e[7]),t}var worker,processingQueue={};function signatureVerificationInit(n){worker=n,worker.onmessage=e=>{const[t,r]=e.data,s=processingQueue[t];if(!s){console.error("No record found for event",t);return}delete processingQueue[t];for(const o of s.resolves)o(r)}}async function verifySignatureAsync(n,e){return new Promise(r=>{const s=n.serialize();let o=!1;processingQueue[n.id]||(processingQueue[n.id]={event:n,resolves:[]},o=!0),processingQueue[n.id].resolves.push(r),o&&(worker==null||worker.postMessage({serialized:s,id:n.id,sig:n.sig,pubkey:n.pubkey}))})}var PUBKEY_REGEX=/^[a-f0-9]{64}$/;function validate(){if(typeof this.kind!="number"||typeof this.content!="string"||typeof this.created_at!="number"||typeof this.pubkey!="string"||!this.pubkey.match(PUBKEY_REGEX)||!Array.isArray(this.tags))return!1;for(let n=0;n<this.tags.length;n++){const e=this.tags[n];if(!Array.isArray(e))return!1;for(let t=0;t<e.length;t++)if(typeof e[t]=="object")return!1}return!0}var verifiedSignatures=new dist.LRUCache({maxSize:1e3,entryExpirationTimeInMS:6e4});function verifySignature(n){var t;if(typeof this.signatureVerified=="boolean")return this.signatureVerified;const e=verifiedSignatures.get(this.id);if(e!==null)return this.signatureVerified=!!e,this.signatureVerified;try{if((t=this.ndk)!=null&&t.asyncSigVerification)verifySignatureAsync(this,n).then(r=>{var s;n&&(this.signatureVerified=r,r&&verifiedSignatures.set(this.id,this.sig)),r||((s=this.ndk)==null||s.emit("event:invalid-sig",this),verifiedSignatures.set(this.id,!1))});else{const r=sha256(new TextEncoder().encode(this.serialize())),s=schnorr.verify(this.sig,r,this.pubkey);return s?verifiedSignatures.set(this.id,this.sig):verifiedSignatures.set(this.id,!1),this.signatureVerified=s,s}}catch{return this.signatureVerified=!1,!1}}function getEventHash$1(){return getEventHashFromSerializedEvent(this.serialize())}function getEventHashFromSerializedEvent(n){const e=sha256(new TextEncoder().encode(n));return bytesToHex$1(e)}var skipClientTagOnKinds=new Set([0,4,1059,13,3,9734,5]),NDKEvent=class Pe extends lib$1.EventEmitter{constructor(t,r){var s;super();g(this,"ndk");g(this,"created_at");g(this,"content","");g(this,"tags",[]);g(this,"kind");g(this,"id","");g(this,"sig");g(this,"pubkey","");g(this,"signatureVerified");g(this,"_author");g(this,"relay");g(this,"publishStatus","success");g(this,"publishError");g(this,"serialize",serialize.bind(this));g(this,"getEventHash",getEventHash$1.bind(this));g(this,"validate",validate.bind(this));g(this,"verifySignature",verifySignature.bind(this));g(this,"isReplaceable",isReplaceable.bind(this));g(this,"isEphemeral",isEphemeral.bind(this));g(this,"isDvm",()=>this.kind&&this.kind>=5e3&&this.kind<=7e3);g(this,"isParamReplaceable",isParamReplaceable.bind(this));g(this,"encode",encode.bind(this));g(this,"encrypt",encrypt.bind(this));g(this,"decrypt",decrypt.bind(this));g(this,"fetchTaggedEvent",fetchTaggedEvent.bind(this));g(this,"fetchRootEvent",fetchRootEvent.bind(this));g(this,"fetchReplyEvent",fetchReplyEvent.bind(this));g(this,"repost",repost.bind(this));this.ndk=t,this.created_at=r==null?void 0:r.created_at,this.content=(r==null?void 0:r.content)||"",this.tags=(r==null?void 0:r.tags)||[],this.id=(r==null?void 0:r.id)||"",this.sig=r==null?void 0:r.sig,this.pubkey=(r==null?void 0:r.pubkey)||"",this.kind=r==null?void 0:r.kind,r instanceof Pe&&(this.relay&&(this.relay=r.relay,(s=this.ndk)==null||s.subManager.seenEvent(r.id,this.relay)),this.publishStatus=r.publishStatus,this.publishError=r.publishError)}get onRelays(){let t=[];return this.ndk?t=this.ndk.subManager.seenEvents.get(this.id)||[]:this.relay&&t.push(this.relay),t}static deserialize(t,r){return new Pe(t,deserialize(r))}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(t){var r;this.pubkey=t.pubkey,this._author=t,(r=this._author).ndk??(r.ndk=this.ndk)}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const t=this.ndk.getUser({pubkey:this.pubkey});return this._author=t,t}tagExternal(t,r,s){const o=["i"],a=["k"];switch(r){case"url":{const u=new URL(t);u.hash="",o.push(u.toString()),a.push(`${u.protocol}//${u.host}`);break}case"hashtag":o.push(`#${t.toLowerCase()}`),a.push("#");break;case"geohash":o.push(`geo:${t.toLowerCase()}`),a.push("geo");break;case"isbn":o.push(`isbn:${t.replace(/-/g,"")}`),a.push("isbn");break;case"podcast:guid":o.push(`podcast:guid:${t}`),a.push("podcast:guid");break;case"podcast:item:guid":o.push(`podcast:item:guid:${t}`),a.push("podcast:item:guid");break;case"podcast:publisher:guid":o.push(`podcast:publisher:guid:${t}`),a.push("podcast:publisher:guid");break;case"isan":o.push(`isan:${t.split("-").slice(0,4).join("-")}`),a.push("isan");break;case"doi":o.push(`doi:${t.toLowerCase()}`),a.push("doi");break;default:throw new Error(`Unsupported NIP-73 entity type: ${r}`)}s&&o.push(s),this.tags.push(o),this.tags.push(a)}tag(t,r,s,o){let a=[];if(t.fetchProfile!==void 0){o??(o="p");const c=[o,t.pubkey];r&&c.push("",r),a.push(c)}else if(t instanceof Pe){const c=t;s??(s=(c==null?void 0:c.pubkey)===this.pubkey),a=c.referenceTags(r,s,o);for(const l of c.getMatchingTags("p"))l[1]!==this.pubkey&&(this.tags.find(h=>h[0]==="p"&&h[1]===l[1])||this.tags.push(["p",l[1]]))}else if(Array.isArray(t))a=[t];else throw new Error("Invalid argument",t);this.tags=mergeTags(this.tags,a)}async toNostrEvent(t){var o,a;if(!t&&this.pubkey===""){const u=await((a=(o=this.ndk)==null?void 0:o.signer)==null?void 0:a.user());this.pubkey=(u==null?void 0:u.pubkey)||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const{content:r,tags:s}=await this.generateTags();this.content=r||"",this.tags=s;try{this.id=this.getEventHash()}catch{}return this.rawEvent()}getMatchingTags(t,r){const s=this.tags.filter(o=>o[0]===t);return r===void 0?s:s.filter(o=>o[3]===r)}hasTag(t,r){return this.tags.some(s=>s[0]===t&&(!r||s[3]===r))}tagValue(t){const r=this.getMatchingTags(t);if(r.length!==0)return r[0][1]}get alt(){return this.tagValue("alt")}set alt(t){this.removeTag("alt"),t&&this.tags.push(["alt",t])}get dTag(){return this.tagValue("d")}set dTag(t){this.removeTag("d"),t&&this.tags.push(["d",t])}removeTag(t){const r=Array.isArray(t)?t:[t];this.tags=this.tags.filter(s=>!r.includes(s[0]))}replaceTag(t){this.removeTag(t[0]),this.tags.push(t)}async sign(t){var s,o;t?this.author=await t.user():((s=this.ndk)==null||s.assertSigner(),t=(o=this.ndk)==null?void 0:o.signer);const r=await this.toNostrEvent();return this.sig=await t.sign(r),this.sig}async publishReplaceable(t,r,s){return this.id="",this.created_at=Math.floor(Date.now()/1e3),this.sig="",this.publish(t,r,s)}async publish(t,r,s){var u,c,l;if(this.sig||await this.sign(),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");if((!t||t.size===0)&&(t=this.ndk.devWriteRelaySet||await calculateRelaySetFromEvent(this.ndk,this)),this.kind===5&&((u=this.ndk.cacheAdapter)!=null&&u.deleteEventIds)){const h=this.getMatchingTags("e").map(f=>f[1]);this.ndk.cacheAdapter.deleteEventIds(h)}const o=this.rawEvent();if((c=this.ndk.cacheAdapter)!=null&&c.addUnpublishedEvent&&shouldTrackUnpublishedEvent(this))try{this.ndk.cacheAdapter.addUnpublishedEvent(this,t.relayUrls)}catch(h){console.error("Error adding unpublished event to cache",h)}this.kind===5&&((l=this.ndk.cacheAdapter)!=null&&l.deleteEventIds)&&this.ndk.cacheAdapter.deleteEventIds(this.getMatchingTags("e").map(h=>h[1])),this.ndk.subManager.dispatchEvent(o,void 0,!0);const a=await t.publish(this,r,s);return a.forEach(h=>{var f;return(f=this.ndk)==null?void 0:f.subManager.seenEvent(this.id,h)}),a}async generateTags(){var o,a,u;let t=[];const r=await generateContentTags(this.content,this.tags),s=r.content;if(t=r.tags,this.kind&&this.isParamReplaceable()&&!this.getMatchingTags("d")[0]){const l=this.tagValue("title");let f=[...Array(l?6:16)].map(()=>Math.random().toString(36)[2]).join("");l&&l.length>0&&(f=`${l.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")}-${f}`),t.push(["d",f])}if(this.shouldAddClientTag){const c=["client",((o=this.ndk)==null?void 0:o.clientName)??""];(a=this.ndk)!=null&&a.clientNip89&&c.push((u=this.ndk)==null?void 0:u.clientNip89),t.push(c)}else this.shouldStripClientTag&&(t=t.filter(c=>c[0]!=="client"));return{content:s||"",tags:t}}get shouldAddClientTag(){var t,r;return!(!((t=this.ndk)!=null&&t.clientName)&&!((r=this.ndk)!=null&&r.clientNip89)||skipClientTagOnKinds.has(this.kind)||this.isEphemeral()||this.isReplaceable()&&!this.isParamReplaceable()||this.isDvm()||this.hasTag("client"))}get shouldStripClientTag(){return skipClientTagOnKinds.has(this.kind)}muted(){var o,a;const t=(o=this.ndk)==null?void 0:o.mutedIds.get(this.pubkey);if(t&&t==="p")return"author";const r=this.tagReference(),s=(a=this.ndk)==null?void 0:a.mutedIds.get(r[1]);return s&&s===r[0]?"event":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const t=this.getMatchingTags("d")[0];return t?t[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return this.kind===0||this.kind===3||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 t=this.dTag??"";return`${this.kind}:${this.pubkey}:${t}`}if(this.isReplaceable())return`${this.kind}:${this.pubkey}:`;throw new Error("Event is not a replaceable event")}tagType(){return this.isParamReplaceable()?"a":"e"}tagReference(t){let r;return this.isParamReplaceable()?r=["a",this.tagAddress()]:r=["e",this.tagId()],this.relay?r.push(this.relay.url):r.push(""),r.push(t??""),this.isParamReplaceable()||r.push(this.pubkey),r}referenceTags(t,r,s){let o=[];return this.isParamReplaceable()?o=[[s??"a",this.tagAddress()],[s??"e",this.id]]:o=[[s??"e",this.id]],o=o.map(a=>{var u,c,l;return a[0]==="e"||t?a.push(((u=this.relay)==null?void 0:u.url)??""):(c=this.relay)!=null&&c.url&&a.push((l=this.relay)==null?void 0:l.url),a}),o.forEach(a=>{a[0]==="e"?(a.push(t??""),a.push(this.pubkey)):t&&a.push(t)}),o=[...o,...this.getMatchingTags("h")],r||o.push(...this.author.referenceTags()),o}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}nip22Filter(){return this.isParamReplaceable()?{"#A":[this.tagId()]}:{"#E":[this.tagId()]}}async delete(t,r=!0){var o;if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new Pe(this.ndk,{kind:5,content:t||""});return s.tag(this,void 0,!0),s.tags.push(["k",(o=this.kind)==null?void 0:o.toString()]),r&&(this.emit("deleted"),await s.publish()),s}set isProtected(t){this.removeTag("-"),t&&this.tags.push(["-"])}get isProtected(){return this.hasTag("-")}async react(t,r=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const s=new Pe(this.ndk,{kind:7,content:t});return s.tag(this),r&&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(t=>t.url).join(", "))}reply(){var r,s;const t=new Pe(this.ndk);if(this.kind===1)t.kind=1,this.hasTag("e")?t.tags=[...t.tags,...this.getMatchingTags("e"),...this.getMatchingTags("p"),...this.getMatchingTags("a"),...this.referenceTags("reply")]:t.tag(this,"root");else{t.kind=1111;const o=["A","E","I","P"],a=this.tags.filter(u=>o.includes(u[0]));if(a.length>0){const u=this.tagValue("K");t.tags.push(...a),u&&t.tags.push(["K",u]);const[c,l,h,...f]=this.tagReference(),p=[c,l,...f];t.tags.push(p)}else{const[u,c,l,h]=this.tagReference(),f=[u,c,h??""];u==="e"&&f.push(this.pubkey),t.tags.push(f);const p=[...f];p[0]=p[0].toUpperCase(),t.tags.push(p),t.tags.push(["K",(r=this.kind)==null?void 0:r.toString()]),t.tags.push(["P",this.pubkey])}t.tags.push(["k",(s=this.kind)==null?void 0:s.toString()]),t.tags.push(...this.getMatchingTags("p")),t.tags.push(["p",this.pubkey])}return t}},untrackedUnpublishedEvents=new Set([24133,13194,23194,23195]);function shouldTrackUnpublishedEvent(n){return!untrackedUnpublishedEvents.has(n.kind)}var NDKPool=class extends lib$1.EventEmitter{constructor(e,t,r,{debug:s,name:o}={}){super();g(this,"_relays",new Map);g(this,"status","idle");g(this,"autoConnectRelays",new Set);g(this,"poolBlacklistRelayUrls",new Set);g(this,"debug");g(this,"temporaryRelayTimers",new Map);g(this,"flappingRelays",new Set);g(this,"backoffTimes",new Map);g(this,"ndk");g(this,"_name","unnamed");this.debug=s??r.debug.extend("pool"),o&&(this._name=o),this.ndk=r,this.relayUrls=e,this.poolBlacklistRelayUrls=new Set(t),this.ndk.pools.push(this)}get blacklistRelayUrls(){const e=new Set(this.ndk.blacklistRelayUrls);return this.poolBlacklistRelayUrls.forEach(t=>e.add(t)),e}get relays(){return this._relays}set relayUrls(e){this._relays.clear();for(const t of e){const r=new NDKRelay(t,void 0,this.ndk);r.connectivity.netDebug=this.ndk.netDebug,this.addRelay(r)}}get name(){return this._name}set name(e){this._name=e,this.debug=this.debug.extend(e)}useTemporaryRelay(e,t=3e4,r){const s=this.relays.has(e.url);s||(this.addRelay(e),this.debug("Adding temporary relay %s for filters %o",e.url,r));const o=this.temporaryRelayTimers.get(e.url);if(o&&clearTimeout(o),!s||o){const a=setTimeout(()=>{var u;(u=this.ndk.explicitRelayUrls)!=null&&u.includes(e.url)||this.removeRelay(e.url)},t);this.temporaryRelayTimers.set(e.url,a)}}addRelay(e,t=!0){var m,y;const r=this.relays.has(e.url),s=(m=this.blacklistRelayUrls)==null?void 0:m.has(e.url),o=e.url.includes("/npub1");let a=!0;const u=e.url;if(r)return;if(s){this.debug(`Refusing to add relay ${u}: blacklisted`);return}if(o){this.debug(`Refusing to add relay ${u}: is a filter relay`);return}if((y=this.ndk.cacheAdapter)!=null&&y.getRelayStatus){const w=this.ndk.cacheAdapter.getRelayStatus(u);if(w!=null&&w.dontConnectBefore){if(w.dontConnectBefore>Date.now()){const x=w.dontConnectBefore-Date.now();this.debug(`Refusing to add relay ${u}: delayed connect for ${x}ms`),setTimeout(()=>{this.addRelay(e,t)},x);return}a=!1}}const c=w=>this.emit("notice",e,w),l=()=>this.handleRelayConnect(u),h=()=>this.handleRelayReady(e),f=()=>this.emit("relay:disconnect",e),p=()=>this.handleFlapping(e),b=w=>this.emit("relay:auth",e,w),v=()=>this.emit("relay:authed",e);e.off("notice",c),e.off("connect",l),e.off("ready",h),e.off("disconnect",f),e.off("flapping",p),e.off("auth",b),e.off("authed",v),e.on("notice",c),e.on("connect",l),e.on("ready",h),e.on("disconnect",f),e.on("flapping",p),e.on("auth",b),e.on("authed",v),e.on("delayed-connect",w=>{var x;(x=this.ndk.cacheAdapter)!=null&&x.updateRelayStatus&&this.ndk.cacheAdapter.updateRelayStatus(e.url,{dontConnectBefore:Date.now()+w})}),this._relays.set(u,e),t&&this.autoConnectRelays.add(u),t&&this.status==="active"&&(this.emit("relay:connecting",e),e.connect(void 0,a).catch(w=>{this.debug(`Failed to connect to relay ${u}`,w)}))}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 r=this.temporaryRelayTimers.get(e);return r&&(clearTimeout(r),this.temporaryRelayTimers.delete(e)),!1}isRelayConnected(e){const t=normalizeRelayUrl(e),r=this.relays.get(t);return r?r.status===5:!1}getRelay(e,t=!0,r=!1,s){let o=this.relays.get(normalizeRelayUrl(e));return o||(o=new NDKRelay(e,void 0,this.ndk),o.connectivity.netDebug=this.ndk.netDebug,r?this.useTemporaryRelay(o,3e4,s):this.addRelay(o,t)),o}handleRelayConnect(e){const t=this.relays.get(e);if(!t){console.error("NDK BUG: relay not found in pool",{relayUrl:e});return}this.emit("relay:connect",t),this.stats().connected===this.relays.size&&this.emit("connect")}handleRelayReady(e){this.emit("relay:ready",e)}async connect(e){const t=[];this.status="active",this.debug(`Connecting to ${this.relays.size} relays${e?`, timeout ${e}...`:""}`);const r=new Set(this.autoConnectRelays.keys());for(const o of r){const a=this.relays.get(o);if(!a)continue;const u=new Promise((c,l)=>(this.emit("relay:connecting",a),a.connect(e).then(c).catch(l)));if(e){const c=new Promise((l,h)=>{setTimeout(()=>h(`Timed out after ${e}ms`),e)});t.push(Promise.race([u,c]).catch(l=>{this.debug(`Failed to connect to relay ${a.url}: ${l??"No reason specified"}`)}))}else t.push(u)}const s=()=>{const o=this.stats().connected===this.relays.size,a=this.stats().connected>0;!o&&a&&this.emit("connect")};e&&setTimeout(s,e),await Promise.all(t),s()}checkOnFlappingRelays(){const e=this.flappingRelays.size,t=this.relays.size;if(e/t>=.8)for(const r of this.flappingRelays)this.backoffTimes.set(r,0)}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;t=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++,t.status===5?e.connected++:t.status===1?e.disconnected++:t.status===4&&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())}},NDKCashuMintList=(X=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_p2pk");this.kind??(this.kind=10019)}static from(t){return new X(t.ndk,t)}set relays(t){this.tags=this.tags.filter(r=>r[0]!=="relay");for(const r of t)this.tags.push(["relay",r])}get relays(){const t=[];for(const r of this.tags)r[0]==="relay"&&t.push(r[1]);return t}set mints(t){this.tags=this.tags.filter(r=>r[0]!=="mint");for(const r of t)this.tags.push(["mint",r])}get mints(){const t=[];for(const r of this.tags)r[0]==="mint"&&t.push(r[1]);return Array.from(new Set(t))}get p2pk(){return this._p2pk?this._p2pk:(this._p2pk=this.tagValue("pubkey")??this.pubkey,this._p2pk)}set p2pk(t){this._p2pk=t,this.removeTag("pubkey"),t&&this.tags.push(["pubkey",t])}get relaySet(){return NDKRelaySet.fromRelayUrls(this.relays,this.ndk)}},g(X,"kind",10019),g(X,"kinds",[10019]),X),NDKArticle=(he=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=30023)}static from(e){return new he(e.ndk,e)}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"),e!==void 0&&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")}},g(he,"kind",30023),g(he,"kinds",[30023]),he);function proofsTotalBalance(n){return n.reduce((e,t)=>{if(t.amount<0)throw new Error("proof amount is negative");return e+t.amount},0)}var NDKCashuToken=(Ae=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_proofs",[]);g(this,"_mint");g(this,"_deletes",[]);g(this,"original");this.kind??(this.kind=7375)}static async from(t){const r=new Ae(t.ndk,t);r.original=t;try{await r.decrypt()}catch{r.content=r.original.content}try{const s=JSON.parse(r.content);if(r.proofs=s.proofs,r.mint=s.mint??r.tagValue("mint"),r.deletedTokens=s.del??[],!Array.isArray(r.proofs))return}catch{return}return r}get proofs(){return this._proofs}set proofs(t){const r=new Set;this._proofs=t.filter(s=>r.has(s.C)?(console.warn("Passed in proofs had duplicates, ignoring",s.C),!1):s.amount<0?(console.warn("Invalid proof with negative amount",s),!1):(r.add(s.C),!0)).map(this.cleanProof)}cleanProof(t){return{id:t.id,amount:t.amount,C:t.C,secret:t.secret}}async toNostrEvent(t){if(!this.ndk)throw new Error("no ndk");if(!this.ndk.signer)throw new Error("no signer");const r={proofs:this.proofs.map(this.cleanProof),mint:this.mint,del:this.deletedTokens??[]};this.content=JSON.stringify(r);const s=await this.ndk.signer.user();return await this.encrypt(s,void 0,"nip44"),super.toNostrEvent(t)}set mint(t){this._mint=t}get mint(){return this._mint}get deletedTokens(){return this._deletes}set deletedTokens(t){this._deletes=t}get amount(){return proofsTotalBalance(this.proofs)}async publish(t,r,s){return this.original?this.original.publish(t,r,s):super.publish(t,r,s)}},g(Ae,"kind",7375),g(Ae,"kinds",[7375]),Ae),NDKHighlight=(Se=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_article");this.kind??(this.kind=9802)}static from(t){return new Se(t.ndk,t)}get url(){return this.tagValue("r")}set context(t){t===void 0?this.tags=this.tags.filter(([r,s])=>r!=="context"):(this.tags=this.tags.filter(([r,s])=>r!=="context"),this.tags.push(["context",t]))}get context(){var t;return((t=this.tags.find(([r,s])=>r==="context"))==null?void 0:t[1])??void 0}get article(){return this._article}set article(t){this._article=t,typeof t=="string"?this.tags.push(["r",t]):this.tag(t)}getArticleTag(){return this.getMatchingTags("a")[0]||this.getMatchingTags("e")[0]||this.getMatchingTags("r")[0]}async getArticle(){var s;if(this._article!==void 0)return this._article;let t;const r=this.getArticleTag();if(r){switch(r[0]){case"a":{const[o,a,u]=r[1].split(":");t=nip19_exports.naddrEncode({kind:Number.parseInt(o),pubkey:a,identifier:u});break}case"e":t=nip19_exports.noteEncode(r[1]);break;case"r":this._article=r[1];break}if(t){let o=await((s=this.ndk)==null?void 0:s.fetchEvent(t));o&&(o.kind===30023&&(o=NDKArticle.from(o)),this._article=o)}return this._article}}},g(Se,"kind",9802),g(Se,"kinds",[9802]),Se);function mapImetaTag(n){const e={};if(n.length===2){const r=n[1].split(" ");for(let s=0;s<r.length;s+=2){const o=r[s],a=r[s+1];o==="fallback"?(e.fallback||(e.fallback=[]),e.fallback.push(a)):e[o]=a}return e}const t=n.slice(1);for(const r of t){const s=r.split(" "),o=s[0],a=s.slice(1).join(" ");o==="fallback"?(e.fallback||(e.fallback=[]),e.fallback.push(a)):e[o]=a}return e}function imetaTagToTag(n){const e=["imeta"];for(const[t,r]of Object.entries(n))if(Array.isArray(r))for(const s of r)e.push(`${t} ${s}`);else r&&e.push(`${t} ${r}`);return e}var NDKImage=(Te=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_imetas");this.kind??(this.kind=20)}static from(t){return new Te(t.ndk,t.rawEvent())}get isValid(){return this.imetas.length>0}get imetas(){return this._imetas?this._imetas:(this._imetas=this.tags.filter(t=>t[0]==="imeta").map(mapImetaTag).filter(t=>!!t.url),this._imetas)}set imetas(t){this._imetas=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),this.tags.push(...t.map(imetaTagToTag))}},g(Te,"kind",20),g(Te,"kinds",[20]),Te),NDKList=($e=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_encryptedTags");g(this,"encryptedTagsLength");this.kind??(this.kind=30001)}static from(t){return new $e(t.ndk,t)}get title(){const t=this.tagValue("title")||this.tagValue("name");return t||(this.kind===3?"Contacts":this.kind===1e4?"Mute":this.kind===10001?"Pinned Notes":this.kind===10002?"Relay Metadata":this.kind===10003?"Bookmarks":this.kind===10004?"Communities":this.kind===10005?"Public Chats":this.kind===10006?"Blocked Relays":this.kind===10007?"Search Relays":this.kind===10050?"Direct Message Receive Relays":this.kind===10015?"Interests":this.kind===10030?"Emojis":this.tagValue("d"))}set title(t){this.removeTag(["title","name"]),t&&this.tags.push(["title",t])}get name(){return this.title}set name(t){this.title=t}get description(){return this.tagValue("description")}set description(t){this.removeTag("description"),t&&this.tags.push(["description",t])}get image(){return this.tagValue("image")}set image(t){this.removeTag("image"),t&&this.tags.push(["image",t])}isEncryptedTagsCacheValid(){return!!(this._encryptedTags&&this.encryptedTagsLength===this.content.length)}async encryptedTags(t=!0){if(t&&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 r=await this.ndk.signer.user();try{if(this.content.length>0)try{const s=await this.ndk.signer.decrypt(r,this.content),o=JSON.parse(s);return o!=null&&o[0]?(this.encryptedTagsLength=this.content.length,this._encryptedTags=o):(this.encryptedTagsLength=this.content.length,this._encryptedTags=[])}catch{}}catch{}return[]}validateTag(t){return!0}getItems(t){return this.tags.filter(r=>r[0]===t)}get items(){return this.tags.filter(t=>!["d","L","l","title","name","description","published_at","summary","image","thumb","alt","expiration","subject","client"].includes(t[0]))}async addItem(t,r=void 0,s=!1,o="bottom"){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");let a;if(t instanceof NDKEvent)a=[t.tagReference(r)];else if(t instanceof NDKUser)a=t.referenceTags();else if(t instanceof NDKRelay)a=t.referenceTags();else if(Array.isArray(t))a=[t];else throw new Error("Invalid object type");if(r&&a[0].push(r),s){const u=await this.ndk.signer.user(),c=await this.encryptedTags();o==="top"?c.unshift(...a):c.push(...a),this._encryptedTags=c,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(c),await this.encrypt(u)}else o==="top"?this.tags.unshift(...a):this.tags.push(...a);this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItemByValue(t,r=!0){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");const s=this.tags.findIndex(c=>c[1]===t);s>=0&&this.tags.splice(s,1);const o=await this.ndk.signer.user(),a=await this.encryptedTags(),u=a.findIndex(c=>c[1]===t);if(u>=0&&(a.splice(u,1),this._encryptedTags=a,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(a),await this.encrypt(o)),r)return this.publishReplaceable();this.created_at=Math.floor(Date.now()/1e3),this.emit("change")}async removeItem(t,r){if(!this.ndk)throw new Error("NDK instance not set");if(!this.ndk.signer)throw new Error("NDK signer not set");if(r){const s=await this.ndk.signer.user(),o=await this.encryptedTags();o.splice(t,1),this._encryptedTags=o,this.encryptedTagsLength=this.content.length,this.content=JSON.stringify(o),await this.encrypt(s)}else this.tags.splice(t,1);return this.created_at=Math.floor(Date.now()/1e3),this.emit("change"),this}has(t){return this.items.some(r=>r[1]===t)}filterForItems(){const t=new Set,r=new Map,s=[];for(const o of this.items)if(o[0]==="e"&&o[1])t.add(o[1]);else if(o[0]==="a"&&o[1]){const[a,u,c]=o[1].split(":");if(!a||!u)continue;const l=`${a}:${u}`,h=r.get(l)||[];h.push(c||""),r.set(l,h)}if(t.size>0&&s.push({ids:Array.from(t)}),r.size>0)for(const[o,a]of r.entries()){const[u,c]=o.split(":");s.push({kinds:[Number.parseInt(u)],authors:[c],"#d":a})}return s}},g($e,"kinds",[10063,30001,10004,10050,10030,10015,10001,10002,10007,10006,10003]),$e),lists_default=NDKList,NDKNutzap=(we=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"debug");g(this,"_proofs",[]);g(this,"sender",this.author);this.kind??(this.kind=9321),this.debug=(t==null?void 0:t.debug.extend("nutzap"))??createDebug5("ndk:nutzap"),this.alt||(this.alt="This is a nutzap");try{const s=this.getMatchingTags("proof");s.length?this._proofs=s.map(o=>JSON.parse(o[1])):this._proofs=JSON.parse(this.content)}catch{return}}static from(t){const r=new we(t.ndk,t);if(!(!r._proofs||!r._proofs.length))return r}set comment(t){this.content=t??""}get comment(){const t=this.tagValue("comment");return t||this.content}set proofs(t){this._proofs=t,this.tags=this.tags.filter(r=>r[0]!=="proof");for(const r of t)this.tags.push(["proof",JSON.stringify(r)])}get proofs(){return this._proofs}get rawP2pk(){var r;const t=this.proofs[0];try{const s=JSON.parse(t.secret);let o;if(typeof s=="string"?(o=JSON.parse(s),this.debug("stringified payload",t.secret)):typeof s=="object"&&(o=s),Array.isArray(o)&&o[0]==="P2PK"&&o.length>1&&typeof o[1]=="object"&&o[1]!==null||typeof o=="object"&&o!==null&&typeof((r=o[1])==null?void 0:r.data)=="string")return o[1].data}catch(s){this.debug("error parsing p2pk pubkey",s,this.proofs[0])}}get p2pk(){const t=this.rawP2pk;if(t)return t.startsWith("02")?t.slice(2):t}get mint(){return this.tagValue("u")}set mint(t){this.replaceTag(["u",t])}get unit(){let t=this.tagValue("unit")??"sat";return t!=null&&t.startsWith("msat")&&(t="sat"),t}set unit(t){if(this.removeTag("unit"),t!=null&&t.startsWith("msat"))throw new Error("msat is not allowed, use sat denomination instead");t&&this.tag(["unit",t])}get amount(){return this.proofs.reduce((r,s)=>r+s.amount,0)}set target(t){this.tags=this.tags.filter(r=>r[0]!=="p"),t instanceof NDKEvent&&this.tags.push(t.tagReference())}set recipientPubkey(t){this.removeTag("p"),this.tag(["p",t])}get recipientPubkey(){return this.tagValue("p")}get recipient(){const t=this.recipientPubkey;return this.ndk?this.ndk.getUser({pubkey:t}):new NDKUser({pubkey:t})}async toNostrEvent(){this.unit==="msat"&&(this.unit="sat"),this.removeTag("amount"),this.tags.push(["amount",this.amount.toString()]);const t=await super.toNostrEvent();return t.content=this.comment,t}get isValid(){let t=0,r=0,s=0;for(const o of this.tags)o[0]==="e"&&t++,o[0]==="p"&&r++,o[0]==="u"&&s++;return r===1&&s===1&&t<=1&&this.proofs.length>0}},g(we,"kind",9321),g(we,"kinds",[we.kind]),we),NDKSimpleGroupMemberList=(Ce=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"relaySet");g(this,"memberSet",new Set);this.kind??(this.kind=39002),this.memberSet=new Set(this.members)}static from(t){return new Ce(t.ndk,t)}get members(){return this.getMatchingTags("p").map(t=>t[1])}hasMember(t){return this.memberSet.has(t)}async publish(t,r,s){return t??(t=this.relaySet),super.publishReplaceable(t,r,s)}},g(Ce,"kind",39002),g(Ce,"kinds",[39002]),Ce),NDKSimpleGroupMetadata=(_e=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=39e3)}static from(e){return new _e(e.ndk,e)}get name(){return this.tagValue("name")}get picture(){return this.tagValue("picture")}get about(){return this.tagValue("about")}get scope(){if(this.getMatchingTags("public").length>0)return"public";if(this.getMatchingTags("public").length>0)return"private"}set scope(e){this.removeTag("public"),this.removeTag("private"),e==="public"?this.tags.push(["public",""]):e==="private"&&this.tags.push(["private",""])}get access(){if(this.getMatchingTags("open").length>0)return"open";if(this.getMatchingTags("closed").length>0)return"closed"}set access(e){this.removeTag("open"),this.removeTag("closed"),e==="open"?this.tags.push(["open",""]):e==="closed"&&this.tags.push(["closed",""])}},g(_e,"kind",39e3),g(_e,"kinds",[39e3]),_e);function strToPosition(n){const[e,t]=n.split(",").map(Number);return{x:e,y:t}}function strToDimension(n){const[e,t]=n.split("x").map(Number);return{width:e,height:t}}var NDKStorySticker=(me=class{constructor(e){g(this,"type");g(this,"value");g(this,"position");g(this,"dimension");g(this,"properties");g(this,"hasValidDimensions",()=>typeof this.dimension.width=="number"&&typeof this.dimension.height=="number"&&!Number.isNaN(this.dimension.width)&&!Number.isNaN(this.dimension.height));g(this,"hasValidPosition",()=>typeof this.position.x=="number"&&typeof this.position.y=="number"&&!Number.isNaN(this.position.x)&&!Number.isNaN(this.position.y));if(Array.isArray(e)){const t=e;if(t[0]!=="sticker"||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 r={};for(let s=5;s<t.length;s++){const[o,...a]=t[s].split(" ");r[o]=a.join(" ")}Object.keys(r).length>0&&(this.properties=r)}else this.type=e,this.value=void 0,this.position={x:0,y:0},this.dimension={width:0,height:0}}static fromTag(e){try{return new me(e)}catch{return null}}get style(){var e;return(e=this.properties)==null?void 0:e.style}set style(e){var t;e?this.properties={...this.properties,style:e}:(t=this.properties)==null||delete t.style}get rotation(){var e;return(e=this.properties)!=null&&e.rot?Number.parseFloat(this.properties.rot):void 0}set rotation(e){var t;e!==void 0?this.properties={...this.properties,rot:e.toString()}:(t=this.properties)==null||delete t.rot}get isValid(){return this.hasValidDimensions()&&this.hasValidPosition()}toTag(){if(!this.isValid){const r=[this.hasValidDimensions()?void 0:"dimensions is invalid",this.hasValidPosition()?void 0:"position is invalid"].filter(Boolean);throw new Error(`Invalid sticker: ${r.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[r,s]of Object.entries(this.properties))t.push(`${r} ${s}`);return t}},g(me,"Text","text"),g(me,"Pubkey","pubkey"),g(me,"Event","event"),g(me,"Prompt","prompt"),g(me,"Countdown","countdown"),me),NDKStory=(Ne=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_imeta");g(this,"_dimensions");if(this.kind??(this.kind=23),r)for(const s of r.tags)switch(s[0]){case"imeta":this._imeta=mapImetaTag(s);break;case"dim":this.dimensions=strToDimension(s[1]);break}}static from(t){return new Ne(t.ndk,t)}get isValid(){return!!this.imeta}get imeta(){return this._imeta}set imeta(t){this._imeta=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),t&&this.tags.push(imetaTagToTag(t))}get dimensions(){const t=this.tagValue("dim");if(t)return strToDimension(t)}set dimensions(t){this.removeTag("dim"),t&&this.tags.push(["dim",`${t.width}x${t.height}`])}get duration(){const t=this.tagValue("dur");if(t)return Number.parseInt(t)}set duration(t){this.removeTag("dur"),t!==void 0&&this.tags.push(["dur",t.toString()])}get stickers(){const t=[];for(const r of this.tags){if(r[0]!=="sticker"||r.length<5)continue;const s=NDKStorySticker.fromTag(r);s&&t.push(s)}return t}addSticker(t){let r;if(t instanceof NDKStorySticker)r=t;else{const s=["sticker",t.type,typeof t.value=="string"?t.value:"",coordinates(t.position),dimension(t.dimension)];if(t.properties)for(const[o,a]of Object.entries(t.properties))s.push(`${o} ${a}`);r=new NDKStorySticker(s),r.value=t.value}r.type==="pubkey"?this.tag(r.value):r.type==="event"&&this.tag(r.value),this.tags.push(r.toTag())}removeSticker(t){const r=this.stickers;if(t<0||t>=r.length)return;let s=0;for(let o=0;o<this.tags.length;o++)if(this.tags[o][0]==="sticker"){if(s===t){this.tags.splice(o,1);break}s++}}},g(Ne,"kind",23),g(Ne,"kinds",[23]),Ne),coordinates=n=>`${n.x},${n.y}`,dimension=n=>`${n.width}x${n.height}`,possibleIntervalFrequencies=["daily","weekly","monthly","quarterly","yearly"];function newAmount(n,e,t){return["amount",n.toString(),e,t]}function parseTagToSubscriptionAmount(n){const e=Number.parseInt(n[1]);if(Number.isNaN(e)||e===void 0||e===null||e<=0)return;const t=n[2];if(t===void 0||t==="")return;const r=n[3];if(r!==void 0&&possibleIntervalFrequencies.includes(r))return{amount:e,currency:t,term:r}}var NDKSubscriptionTier=(Re=class extends NDKArticle{constructor(e,t){const r=(t==null?void 0:t.kind)??37001;super(e,t),this.kind=r}static from(e){return new Re(e.ndk,e)}get perks(){return this.getMatchingTags("perk").map(e=>e[1]).filter(e=>e!==void 0)}addPerk(e){this.tags.push(["perk",e])}get amounts(){return this.getMatchingTags("amount").map(e=>parseTagToSubscriptionAmount(e)).filter(e=>e!==void 0)}addAmount(e,t,r){this.tags.push(newAmount(e,t,r))}set relayUrl(e){this.tags.push(["r",e])}get relayUrls(){return this.getMatchingTags("r").map(e=>e[1]).filter(e=>e!==void 0)}get verifierPubkey(){return this.tagValue("p")}set verifierPubkey(e){this.removeTag("p"),e&&this.tags.push(["p",e])}get isValid(){return this.title!==void 0&&this.amounts.length>0}},g(Re,"kind",37001),g(Re,"kinds",[37001]),Re),NDKVideo=(Le=class extends NDKEvent{constructor(){super(...arguments);g(this,"_imetas")}static from(t){return new Le(t.ndk,t.rawEvent())}get title(){return this.tagValue("title")}set title(t){this.removeTag("title"),t&&this.tags.push(["title",t])}get thumbnail(){var r;let t;return this.imetas&&this.imetas.length>0&&(t=(r=this.imetas[0].image)==null?void 0:r[0]),t??this.tagValue("thumb")}get imetas(){return this._imetas?this._imetas:(this._imetas=this.tags.filter(t=>t[0]==="imeta").map(mapImetaTag),this._imetas)}set imetas(t){this._imetas=t,this.tags=this.tags.filter(r=>r[0]!=="imeta"),this.tags.push(...t.map(imetaTagToTag))}get url(){return this.imetas&&this.imetas.length>0?this.imetas[0].url:this.tagValue("url")}get published_at(){const t=this.tagValue("published_at");if(t)return Number.parseInt(t)}async generateTags(){var t,r;if(super.generateTags(),!this.kind&&(r=(t=this.imetas)==null?void 0:t[0])!=null&&r.dim){const[s,o]=this.imetas[0].dim.split("x"),a=s&&o&&Number.parseInt(s)<Number.parseInt(o);this.duration&&this.duration<120&&a?this.kind=22:this.kind=21}return super.generateTags()}get duration(){const t=this.tagValue("duration");if(t)return Number.parseInt(t)}set duration(t){this.removeTag("duration"),t!==void 0&&this.tags.push(["duration",Math.floor(t).toString()])}},g(Le,"kind",21),g(Le,"kinds",[34235,34236,22,21]),Le),NDKWiki=(je=class extends NDKArticle{},g(je,"kind",30818),g(je,"kinds",[30818]),je);function wrapEvent(n){const e=new Map;for(const r of[NDKImage,NDKVideo,NDKCashuMintList,NDKArticle,NDKHighlight,NDKWiki,NDKNutzap,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKSubscriptionTier,NDKCashuToken,NDKList,NDKStory])for(const s of r.kinds)e.set(s,r);const t=e.get(n.kind);return t?t.from(n):n}function queryFullyFilled(n){return!!(filterIncludesIds(n.filter)&&resultHasAllRequestedIds(n))}function filterIncludesIds(n){return!!n.ids}function resultHasAllRequestedIds(n){const e=n.filter.ids;return!!e&&e.length===n.eventFirstSeen.size}function filterFromId(n){let e;if(n.match(NIP33_A_REGEX)){const[t,r,s]=n.split(":"),o={authors:[r],kinds:[Number.parseInt(t)]};return s&&(o["#d"]=[s]),o}if(n.match(BECH32_REGEX))try{switch(e=nip19_exports.decode(n),e.type){case"nevent":{const t={ids:[e.data.id]};return e.data.author&&(t.authors=[e.data.author]),e.data.kind&&(t.kinds=[e.data.kind]),t}case"note":return{ids:[e.data]};case"naddr":{const t={authors:[e.data.pubkey],kinds:[e.data.kind]};return e.data.identifier&&(t["#d"]=[e.data.identifier]),t}}}catch(t){console.error("Error decoding",n,t)}return{ids:[n]}}function isNip33AValue(n){return n.match(NIP33_A_REGEX)!==null}var NIP33_A_REGEX=/^(\d+):([0-9A-Fa-f]+)(?::(.*))?$/,BECH32_REGEX=/^n(event|ote|profile|pub|addr)1[\d\w]+$/;function relaysFromBech32(n,e){try{const t=nip19_exports.decode(n);if(["naddr","nevent"].includes(t==null?void 0:t.type)){const r=t.data;if(r!=null&&r.relays)return r.relays.map(s=>new NDKRelay(s,e.relayAuthDefaultPolicy,e))}}catch{}return[]}var defaultOpts$1={closeOnEose:!1,cacheUsage:"CACHE_FIRST",dontSaveToCache:!1,groupable:!0,groupableDelay:100,groupableDelayType:"at-most",cacheUnconstrainFilter:["limit","since","until"]},NDKSubscription=class extends lib$1.EventEmitter{constructor(e,t,r,s){super();g(this,"subId");g(this,"filters");g(this,"opts");g(this,"pool");g(this,"skipVerification",!1);g(this,"skipValidation",!1);g(this,"relayFilters");g(this,"relaySet");g(this,"ndk");g(this,"debug");g(this,"eventFirstSeen",new Map);g(this,"eosesSeen",new Set);g(this,"lastEventReceivedAt");g(this,"mostRecentCacheEventTimestamp");g(this,"internalId");g(this,"closeOnEose");g(this,"poolMonitor");g(this,"skipOptimisticPublishEvent",!1);g(this,"cacheUnconstrainFilter");g(this,"onStopped");g(this,"eoseTimeout");g(this,"eosed",!1);this.ndk=e,this.opts={...defaultOpts$1,...r||{}},this.pool=this.opts.pool||e.pool,this.filters=Array.isArray(t)?t:[t],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}relaysMissingEose(){var t;return this.relayFilters?Array.from((t=this.relayFilters)==null?void 0:t.keys()).filter(r=>!this.eosesSeen.has(this.pool.getRelay(r,!1,!1))):[]}get filter(){return this.filters[0]}get groupableDelay(){var e;if(this.isGroupable())return(e=this.opts)==null?void 0:e.groupableDelay}get groupableDelayType(){var e;return((e=this.opts)==null?void 0:e.groupableDelayType)||"at-most"}isGroupable(){var e;return((e=this.opts)==null?void 0:e.groupable)||!1}shouldQueryCache(){var t;return this.opts.addSinceFromCache?!0:((t=this.opts)==null?void 0:t.cacheUsage)==="ONLY_RELAY"?!1:(this.filters.some(r=>{var s;return(s=r.kinds)==null?void 0:s.some(o=>kindIsEphemeral(o))}),!0)}shouldQueryRelays(){var e;return((e=this.opts)==null?void 0:e.cacheUsage)!=="ONLY_CACHE"}shouldWaitForCache(){var e;return this.opts.addSinceFromCache?!0:this.opts.closeOnEose&&!!((e=this.ndk.cacheAdapter)!=null&&e.locking)&&this.opts.cacheUsage!=="PARALLEL"}start(e=!0){let t;const r=o=>{if(e)for(const a of o)(!this.mostRecentCacheEventTimestamp||a.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=a.created_at),this.eventReceived(a,void 0,!0,!1);else{t=[];for(const a of o){(!this.mostRecentCacheEventTimestamp||a.created_at>this.mostRecentCacheEventTimestamp)&&(this.mostRecentCacheEventTimestamp=a.created_at),a.ndk=this.ndk;const u=this.opts.wrap?wrapEvent(a):a;if(!u)break;if(u instanceof Promise){u.then(c=>{this.emitEvent(!1,c,void 0,!0,!1)});break}this.eventFirstSeen.set(u.id,Date.now()),t.push(u)}}},s=()=>{this.shouldQueryRelays()?(this.startWithRelays(),this.startPoolMonitor()):this.emit("eose",this)};return this.shouldQueryCache()?(t=this.startWithCache(),t instanceof Promise?this.shouldWaitForCache()?(t.then(o=>{if(r(o),queryFullyFilled(this)){this.emit("eose",this);return}s()}),null):(t.then(o=>{r(o)}),s(),null):(r(t),queryFullyFilled(this)?this.emit("eose",this):s(),t)):(s(),null)}startPoolMonitor(){this.debug.extend("pool-monitor"),this.poolMonitor=e=>{var r,s;if((r=this.relayFilters)!=null&&r.has(e.url))return;calculateRelaySetsFromFilters(this.ndk,this.filters,this.pool).get(e.url)&&((s=this.relayFilters)==null||s.set(e.url,this.filters),e.subscribe(this,this.filters))},this.pool.on("relay:connect",this.poolMonitor)}stop(){var e;this.emit("close",this),this.poolMonitor&&this.pool.off("relay:connect",this.poolMonitor),(e=this.onStopped)==null||e.call(this)}hasAuthorsFilter(){return this.filters.some(e=>{var t;return(t=e.authors)==null?void 0:t.length})}startWithCache(){var e;return(e=this.ndk.cacheAdapter)!=null&&e.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(r=>({...r,since:Math.max(r.since||0,t)}))}if(!this.relaySet||this.relaySet.relays.size===0)this.relayFilters=calculateRelaySetsFromFilters(this.ndk,e,this.pool);else{this.relayFilters=new Map;for(const t of this.relaySet.relays)this.relayFilters.set(t.url,e)}for(const[t,r]of this.relayFilters)this.pool.getRelay(t,!0,!0,r).subscribe(this,r)}eventReceived(e,t,r=!1,s=!1){var c;const o=e.id,a=this.eventFirstSeen.has(o);let u;if(e instanceof NDKEvent&&(u=e),a){const l=Date.now()-(this.eventFirstSeen.get(o)||0);if(this.emit("event:dup",e,t,l,this,r,s),t){const h=verifiedSignatures.get(o);h&&typeof h=="string"&&e.sig===h&&t.addValidatedEvent()}}else{if(u??(u=new NDKEvent(this.ndk,e)),u.ndk=this.ndk,u.relay=t,!r&&!s){if(!this.skipValidation&&!u.isValid){this.debug("Event failed validation %s from relay %s",o,t==null?void 0:t.url);return}if(t)if((t==null?void 0:t.shouldValidateEvent())!==!1){if(!this.skipVerification){if(!u.verifySignature(!0)&&!this.ndk.asyncSigVerification){this.debug("Event failed signature validation",e);return}t&&t.addValidatedEvent()}}else t.addNonValidatedEvent();this.ndk.cacheAdapter&&!this.opts.dontSaveToCache&&this.ndk.cacheAdapter.setEvent(u,this.filters,t)}(!s||this.skipOptimisticPublishEvent!==!0)&&(this.emitEvent(((c=this.opts)==null?void 0:c.wrap)??!1,u,t,r,s),this.eventFirstSeen.set(o,Date.now()))}this.lastEventReceivedAt=Date.now()}emitEvent(e,t,r,s,o){const a=e?wrapEvent(t):t;a instanceof Promise?a.then(u=>this.emitEvent(!1,u,r,s,o)):a&&this.emit("event",a,r,this,s,o)}closedReceived(e,t){this.emit("closed",e,t)}eoseReceived(e){var a;this.debug("EOSE received from %s",e.url),this.eosesSeen.add(e);let t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0;const r=this.eosesSeen.size===((a=this.relayFilters)==null?void 0:a.size),s=queryFullyFilled(this),o=u=>{var c;this.debug("Performing EOSE: %s %d",u,this.eosed),!this.eosed&&(this.eoseTimeout&&clearTimeout(this.eoseTimeout),this.emit("eose",this),this.eosed=!0,(c=this.opts)!=null&&c.closeOnEose&&this.stop())};if(s||r)o("query filled or seen all");else if(this.relayFilters){let u=1e3;const c=new Set(this.pool.connectedRelays().map(f=>f.url)),l=Array.from(this.relayFilters.keys()).filter(f=>c.has(f));if(l.length===0){this.debug("No connected relays, waiting for all relays to connect",Array.from(this.relayFilters.keys()).join(", "));return}const h=this.eosesSeen.size/l.length;if(this.debug("Percentage of relays that have sent EOSE",{subId:this.subId,percentageOfRelaysThatHaveSentEose:h,seen:this.eosesSeen.size,total:l.length}),this.eosesSeen.size>=2&&h>=.5){if(u=u*(1-h),u===0){o("time to wait was 0");return}this.eoseTimeout&&clearTimeout(this.eoseTimeout);const f=()=>{t=this.lastEventReceivedAt?Date.now()-this.lastEventReceivedAt:void 0,t!==void 0&&t<20?this.eoseTimeout=setTimeout(f,u):o(`send eose timeout: ${u}`)};this.eoseTimeout=setTimeout(f,u)}}}},kindIsEphemeral=n=>n>=2e4&&n<3e4;async function follows(n,e,t=3){var s,o;if(!this.ndk)throw new Error("NDK not set");const r=await this.ndk.fetchEvent({kinds:[t],authors:[this.pubkey]},n||{groupable:!1});if(r){const a=new Set;return r.tags.forEach(u=>{u[0]==="p"&&a.add(u[1])}),e&&((o=(s=this.ndk)==null?void 0:s.outboxTracker)==null||o.trackUsers(Array.from(a))),[...a].reduce((u,c)=>{const l=new NDKUser({pubkey:c});return l.ndk=this.ndk,u.add(l),u},new Set)}return new Set}var NIP05_REGEX=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function getNip05For(n,e,t=fetch,r={}){return await n.queuesNip05.add({id:e,func:async()=>{var c,l,h;if((c=n.cacheAdapter)!=null&&c.loadNip05){const f=await n.cacheAdapter.loadNip05(e);if(f!=="missing"){if(f){const p=new NDKUser({pubkey:f.pubkey,relayUrls:f.relays,nip46Urls:f.nip46});return p.ndk=n,p}if(r.cache!=="no-cache")return null}}const s=e.match(NIP05_REGEX);if(!s)return null;const[o,a="_",u]=s;try{const f=await t(`https://${u}/.well-known/nostr.json?name=${a}`,r),{names:p,relays:b,nip46:v}=parseNIP05Result(await f.json()),m=p[a.toLowerCase()];let y=null;return m&&(y={pubkey:m,relays:b==null?void 0:b[m],nip46:v==null?void 0:v[m]}),(l=n==null?void 0:n.cacheAdapter)!=null&&l.saveNip05&&n.cacheAdapter.saveNip05(e,y),y}catch(f){return(h=n==null?void 0:n.cacheAdapter)!=null&&h.saveNip05&&(n==null||n.cacheAdapter.saveNip05(e,null)),console.error("Failed to fetch NIP05 for",e,f),null}}})}function parseNIP05Result(n){const e={names:{}};for(const[t,r]of Object.entries(n.names))typeof t=="string"&&typeof r=="string"&&(e.names[t.toLowerCase()]=r);if(n.relays){e.relays={};for(const[t,r]of Object.entries(n.relays))typeof t=="string"&&Array.isArray(r)&&(e.relays[t]=r.filter(s=>typeof s=="string"))}if(n.nip46){e.nip46={};for(const[t,r]of Object.entries(n.nip46))typeof t=="string"&&Array.isArray(r)&&(e.nip46[t]=r.filter(s=>typeof s=="string"))}return e}function profileFromEvent(n){const e={};let t;try{t=JSON.parse(n.content)}catch(r){throw new Error(`Failed to parse profile event: ${r}`)}e.created_at=n.created_at,e.profileEvent=JSON.stringify(n.rawEvent());for(const r of Object.keys(t))switch(r){case"name":e.name=t.name;break;case"display_name":e.displayName=t.display_name;break;case"image":case"picture":e.picture=t.picture||t.image,e.image=e.picture;break;case"banner":e.banner=t.banner;break;case"bio":e.bio=t.bio;break;case"nip05":e.nip05=t.nip05;break;case"lud06":e.lud06=t.lud06;break;case"lud16":e.lud16=t.lud16;break;case"about":e.about=t.about;break;case"website":e.website=t.website;break;default:e[r]=t[r];break}return e}function serializeProfile(n){const e={};for(const[t,r]of Object.entries(n))switch(t){case"username":case"name":e.name=r;break;case"displayName":e.display_name=r;break;case"image":case"picture":e.picture=r;break;case"bio":case"about":e.about=r;break;default:e[t]=r;break}return JSON.stringify(e)}var NDKUser=class Ct{constructor(e){g(this,"ndk");g(this,"profile");g(this,"profileEvent");g(this,"_npub");g(this,"_pubkey");g(this,"relayUrls",[]);g(this,"nip46Urls",[]);g(this,"follows",follows.bind(this));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.decode(e.nprofile);t.type==="nprofile"&&(this._pubkey=t.data.pubkey,t.data.relays&&t.data.relays.length>0&&this.relayUrls.push(...t.data.relays))}catch(t){console.error("Failed to decode nprofile",t)}}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("pubkey not set");this._npub=nip19_exports.npubEncode(this.pubkey)}return this._npub}get nprofile(){var t,r;const e=(r=(t=this.profileEvent)==null?void 0:t.onRelays)==null?void 0:r.map(s=>s.url);return nip19_exports.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.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 a=>{if(!e)return a;let u;const c=new Promise((l,h)=>{u=setTimeout(()=>h(new Error("Timeout")),e)});try{const l=await Promise.race([a,c]);return u&&clearTimeout(u),l}catch(l){if(l instanceof Error&&l.message==="Timeout")try{return await a}catch{return}return}},[r,s]=await Promise.all([t(this.fetchProfile()),t(this.ndk.fetchEvent({kinds:[10019],authors:[this.pubkey]}))]),o=new Map;if(s){const a=NDKCashuMintList.from(s);a.mints.length>0&&o.set("nip61",{mints:a.mints,relays:a.relays,p2pk:a.p2pk})}if(r){const{lud06:a,lud16:u}=r;o.set("nip57",{lud06:a,lud16:u})}return o}static async fromNip05(e,t,r=!1){if(!t)throw new Error("No NDK instance found");const s={};r&&(s.cache="no-cache");const o=await getNip05For(t,e,t==null?void 0:t.httpFetch,s);if(o){const a=new Ct({pubkey:o.pubkey,relayUrls:o.relays,nip46Urls:o.nip46});return a.ndk=t,a}}async fetchProfile(e,t=!1){if(!this.ndk)throw new Error("NDK not set");let r=null;if(this.ndk.cacheAdapter&&(this.ndk.cacheAdapter.fetchProfile||this.ndk.cacheAdapter.fetchProfileSync)&&(e==null?void 0:e.cacheUsage)!=="ONLY_RELAY"){let s=null;if(this.ndk.cacheAdapter.fetchProfileSync?s=this.ndk.cacheAdapter.fetchProfileSync(this.pubkey):this.ndk.cacheAdapter.fetchProfile&&(s=await this.ndk.cacheAdapter.fetchProfile(this.pubkey)),s)return this.profile=s,s}return e??(e={}),e.cacheUsage??(e.cacheUsage="ONLY_RELAY"),e.closeOnEose??(e.closeOnEose=!0),e.groupable??(e.groupable=!0),e.groupableDelay??(e.groupableDelay=250),r||(r=await this.ndk.fetchEvent({kinds:[0],authors:[this.pubkey]},e)),r?(this.profile=profileFromEvent(r),t&&this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile):null}async followSet(e,t,r=3){const s=await this.follows(e,t,r);return new Set(Array.from(s).map(o=>o.pubkey))}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e&&t[0].push("",e),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(),await new NDKEvent(this.ndk,{kind:0,content:serializeProfile(this.profile)}).publish()}async follow(e,t,r=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,r)),t.has(e))return!1;t.add(e);const s=new NDKEvent(this.ndk,{kind:r});for(const o of t)s.tag(o);return await s.publish(),!0}async unfollow(e,t,r=3){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,r));const s=new Set;let o=!1;for(const u of t)u.pubkey!==e.pubkey?s.add(u):o=!0;if(!o)return!1;const a=new NDKEvent(this.ndk,{kind:r});for(const u of s)a.tag(u);return await a.publish()}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await getNip05For(this.ndk,e);return t===null?null:t.pubkey===this.pubkey}},READ_MARKER="read",WRITE_MARKER="write",NDKRelayList=class _t extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=10002)}static from(e){return new _t(e.ndk,e.rawEvent())}get readRelayUrls(){return this.tags.filter(e=>e[0]==="r"||e[0]==="relay").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=>e[0]==="r"||e[0]==="relay").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=>e[0]==="r"||e[0]==="relay").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=>e[0]==="r"||e[0]==="relay").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=>{var t;return(t=this.ndk)==null?void 0:t.pool.getRelay(e)}).filter(e=>!!e)),this.ndk)}};function relayListFromKind3(n,e){try{const t=JSON.parse(e.content),r=new NDKRelayList(n),s=new Set,o=new Set;for(let[a,u]of Object.entries(t)){try{a=normalizeRelayUrl(a)}catch{continue}if(!u)s.add(a),o.add(a);else{const c=u;c.write&&o.add(a),c.read&&s.add(a)}}return r.readRelayUrls=Array.from(s),r.writeRelayUrls=Array.from(o),r}catch{}}var NDKPrivateKeySigner=class it{constructor(e,t){g(this,"_user");g(this,"_privateKey");g(this,"_pubkey");if(typeof e=="string")if(e.startsWith("nsec1")){const{type:r,data:s}=nip19_exports.decode(e);if(r==="nsec")this._privateKey=s;else throw new Error("Invalid private key provided.")}else if(e.length===64)this._privateKey=hexToBytes$1(e);else throw new Error("Invalid private key provided.");else this._privateKey=e;this._pubkey=getPublicKey$1(this._privateKey),t&&(this._user=t.getUser({pubkey:this._pubkey})),this._user??(this._user=new NDKUser({pubkey:this._pubkey}))}get privateKey(){if(!this._privateKey)throw new Error("Not ready");return bytesToHex$1(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.nsecEncode(this._privateKey)}get npub(){if(!this._pubkey)throw new Error("Not ready");return nip19_exports.npubEncode(this._pubkey)}static generate(){const e=generateSecretKey$1();return new it(e)}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$1(e,this._privateKey).sig}async encryptionEnabled(e){const t=[];return(!e||e==="nip04")&&t.push("nip04"),(!e||e==="nip44")&&t.push("nip44"),t}async encrypt(e,t,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to encrypt without a private key");const s=e.pubkey;if(r==="nip44"){const o=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.encrypt(t,o)}return await nip04_exports.encrypt(this._privateKey,s,t)}async decrypt(e,t,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to decrypt without a private key");const s=e.pubkey;if(r==="nip44"){const o=nip44_exports.v2.utils.getConversationKey(this._privateKey,s);return await nip44_exports.v2.decrypt(t,o)}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(e,t){const r=JSON.parse(e);if(r.type!=="private-key")throw new Error(`Invalid payload type: expected 'private-key', got ${r.type}`);if(!r.payload||typeof r.payload!="string")throw new Error("Invalid payload content for private-key signer");return new it(r.payload,t)}};function disconnect(n,e){return e??(e=createDebug5("ndk:relay:auth-policies:disconnect")),async t=>{e==null||e(`Relay ${t.url} requested authentication, disconnecting`),n.removeRelay(t.url)}}async function signAndAuth(n,e,t,r,s,o){try{await n.sign(t),s(n)}catch(a){r==null||r(`Failed to publish auth event to relay ${e.url}`,a),o(n)}}function signIn({ndk:n,signer:e,debug:t}={}){return t??(t=createDebug5("ndk:auth-policies:signIn")),async(r,s)=>{t==null||t(`Relay ${r.url} requested authentication, signing in`);const o=new NDKEvent(n);return o.kind=22242,o.tags=[["relay",r.url],["challenge",s]],e??(e=n==null?void 0:n.signer),new Promise(async(a,u)=>{e?await signAndAuth(o,r,e,t,a,u):n==null||n.once("signer:ready",async c=>{await signAndAuth(o,r,c,t,a,u)})})}}var NDKRelayAuthPolicies={disconnect,signIn},NDKNip07Signer=class Nt{constructor(e=1e3,t){g(this,"_userPromise");g(this,"encryptionQueue",[]);g(this,"encryptionProcessing",!1);g(this,"debug");g(this,"waitTimeout");g(this,"_pubkey");g(this,"ndk");g(this,"_user");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(){var r;await this.waitForExtension();const e=await((r=window.nostr)==null?void 0:r.getPublicKey());if(!e)throw new Error("User rejected access");this._pubkey=e;let t;return this.ndk?t=this.ndk.getUser({pubkey:e}):t=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){var r;await this.waitForExtension();const t=await((r=window.nostr)==null?void 0:r.signEvent(e));if(!t)throw new Error("Failed to sign event");return t.sig}async relays(e){var s,o;await this.waitForExtension();const t=await((o=(s=window.nostr)==null?void 0:s.getRelays)==null?void 0:o.call(s))||{},r=[];for(const a of Object.keys(t))t[a].read&&t[a].write&&r.push(a);return r.map(a=>new NDKRelay(a,e==null?void 0:e.relayAuthDefaultPolicy,e))}async encryptionEnabled(e){var r,s;const t=[];return(!e||e==="nip04")&&((r=window.nostr)!=null&&r.nip04)&&t.push("nip04"),(!e||e==="nip44")&&((s=window.nostr)!=null&&s.nip44)&&t.push("nip44"),t}async encrypt(e,t,r="nip04"){if(!await this.encryptionEnabled(r))throw new Error(`${r}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(r,"encrypt",s,t)}async decrypt(e,t,r="nip04"){if(!await this.encryptionEnabled(r))throw new Error(`${r}encryption is not available from your browser extension`);await this.waitForExtension();const s=e.pubkey;return this.queueEncryption(r,"decrypt",s,t)}async queueEncryption(e,t,r,s){return new Promise((o,a)=>{this.encryptionQueue.push({scheme:e,method:t,counterpartyHexpubkey:r,value:s,resolve:o,reject:a}),this.encryptionProcessing||this.processEncryptionQueue()})}async processEncryptionQueue(e,t=0){var h,f;if(!e&&this.encryptionQueue.length===0){this.encryptionProcessing=!1;return}this.encryptionProcessing=!0;const r=e||this.encryptionQueue.shift();if(!r){this.encryptionProcessing=!1;return}const{scheme:s,method:o,counterpartyHexpubkey:a,value:u,resolve:c,reject:l}=r;this.debug("Processing encryption queue item",{method:o,counterpartyHexpubkey:a,value:u});try{const p=await((f=(h=window.nostr)==null?void 0:h[s])==null?void 0:f[o](a,u));if(!p)throw new Error("Failed to encrypt/decrypt");c(p)}catch(p){const b=p instanceof Error?p.message:String(p);if(b.includes("call already executing")&&t<5){this.debug("Retrying encryption queue item",{method:o,counterpartyHexpubkey:a,value:u,retries:t}),setTimeout(()=>{this.processEncryptionQueue(r,t+1)},50*t);return}l(p instanceof Error?p:new Error(b))}this.processEncryptionQueue()}waitForExtension(){return new Promise((e,t)=>{if(window.nostr){e();return}let r;const s=setInterval(()=>{window.nostr&&(clearTimeout(r),clearInterval(s),e())},100);r=setTimeout(()=>{clearInterval(s),t(new Error("NIP-07 extension not available"))},this.waitTimeout)})}toPayload(){return JSON.stringify({type:"nip07",payload:""})}static async fromPayload(e,t){const r=JSON.parse(e);if(r.type!=="nip07")throw new Error(`Invalid payload type: expected 'nip07', got ${r.type}`);return new Nt(void 0,t)}},NDKNostrRpc=class extends lib$1.EventEmitter{constructor(e,t,r,s){super();g(this,"ndk");g(this,"signer");g(this,"relaySet");g(this,"debug");g(this,"encryptionType","nip04");g(this,"pool");if(this.ndk=e,this.signer=t,s){this.pool=new NDKPool(s,[],e,{debug:r.extend("rpc-pool"),name:"Nostr RPC"}),this.relaySet=new NDKRelaySet(new Set,e,this.pool);for(const o of s){const a=this.pool.getRelay(o,!1,!1);a.authPolicy=NDKRelayAuthPolicies.signIn({ndk:e,signer:t,debug:r}),this.relaySet.addRelay(a),a.connect()}}this.debug=r.extend("rpc")}subscribe(e){const t=this.ndk.subscribe(e,{closeOnEose:!1,groupable:!1,cacheUsage:"ONLY_RELAY",pool:this.pool,relaySet:this.relaySet},!1);return t.on("event",async r=>{try{const s=await this.parseEvent(r);s.method?this.emit("request",s):this.emit(`response-${s.id}`,s)}catch(s){this.debug("error parsing event",s,r.rawEvent())}}),new Promise(r=>{t.on("eose",()=>{this.debug("eosed"),r(t)}),t.start()})}async parseEvent(e){this.encryptionType==="nip44"&&e.content.includes("?iv=")?this.encryptionType="nip04":this.encryptionType==="nip04"&&!e.content.includes("?iv=")&&(this.encryptionType="nip44");const t=this.ndk.getUser({pubkey:e.pubkey});t.ndk=this.ndk;let r;try{r=await this.signer.decrypt(t,e.content,this.encryptionType)}catch{const f=this.encryptionType==="nip04"?"nip44":"nip04";r=await this.signer.decrypt(t,e.content,f),this.encryptionType=f}const s=JSON.parse(r),{id:o,method:a,params:u,result:c,error:l}=s;return a?{id:o,pubkey:e.pubkey,method:a,params:u,event:e}:{id:o,result:c,error:l,event:e}}async sendResponse(e,t,r,s=24133,o){const a={id:e,result:r};o&&(a.error=o);const u=await this.signer.user(),c=this.ndk.getUser({pubkey:t}),l=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(a),tags:[["p",t]],pubkey:u.pubkey});l.content=await this.signer.encrypt(c,l.content,this.encryptionType),await l.sign(this.signer),await l.publish(this.relaySet)}async sendRequest(e,t,r=[],s=24133,o){const a=Math.random().toString(36).substring(7),u=await this.signer.user(),c=this.ndk.getUser({pubkey:e}),l={id:a,method:t,params:r},h=new Promise(()=>{const p=b=>{b.result==="auth_url"?(this.once(`response-${a}`,p),this.emit("authUrl",b.error)):o&&o(b)};this.once(`response-${a}`,p)}),f=new NDKEvent(this.ndk,{kind:s,content:JSON.stringify(l),tags:[["p",e]],pubkey:u.pubkey});return f.content=await this.signer.encrypt(c,f.content,this.encryptionType),await f.sign(this.signer),await f.publish(this.relaySet),h}},signerRegistry=new Map;signerRegistry.set("private-key",NDKPrivateKeySigner),signerRegistry.set("nip07",NDKNip07Signer),signerRegistry.set("nip46",NDKNip46Signer);async function ndkSignerFromPayload(n,e){let t;try{t=JSON.parse(n)}catch(s){throw new Error(`Failed to parse signer payload: ${s instanceof Error?s.message:String(s)}`)}const r=signerRegistry.get(t.type);if(!r)throw new Error(`Unknown signer type: ${t.type}`);try{return await r.fromPayload(n,e)}catch(s){const o=s instanceof Error?s.message:String(s);throw new Error(`Failed to deserialize signer type ${t.type}: ${o}`)}}var NDKNip46Signer=class ot extends lib$1.EventEmitter{constructor(t,r,s){super();g(this,"ndk");g(this,"_user");g(this,"bunkerPubkey");g(this,"userPubkey");g(this,"secret");g(this,"localSigner");g(this,"nip05");g(this,"rpc");g(this,"debug");g(this,"relayUrls");g(this,"subscription");this.ndk=t,this.debug=t.debug.extend("nip46:signer"),r.startsWith("bunker://")?this.connectionTokenInit(r):this.nip05Init(r),s?this.localSigner=s:this.localSigner=NDKPrivateKeySigner.generate(),this.rpc=new NDKNostrRpc(this.ndk,this.localSigner,this.debug,this.relayUrls)}get pubkey(){if(!this.userPubkey)throw new Error("Not ready");return this.userPubkey}connectionTokenInit(t){const r=new URL(t),s=r.hostname||r.pathname.replace(/^\/\//,""),o=r.searchParams.get("pubkey"),a=r.searchParams.getAll("relay"),u=r.searchParams.get("secret");this.bunkerPubkey=s,this.userPubkey=o,this.relayUrls=a,this.secret=u}nip05Init(t){this.nip05=t}async startListening(){if(this.subscription)return;const t=await this.localSigner.user();if(!t)throw new Error("Local signer not ready");this.subscription=await this.rpc.subscribe({kinds:[24133],"#p":[t.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 blockUntilReady(){if(this.nip05&&!this.userPubkey){const t=await NDKUser.fromNip05(this.nip05,this.ndk);t&&(this._user=t,this.userPubkey=t.pubkey,this.relayUrls=t.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",(...t)=>{this.emit("authUrl",...t)}),new Promise((t,r)=>{const s=[this.userPubkey??""];if(this.secret&&s.push(this.secret),!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"connect",s,24133,o=>{o.result==="ack"?this.getPublicKey().then(a=>{this.userPubkey=a,this._user=this.ndk.getUser({pubkey:a}),t(this._user)}):r(o.error)})})}async getPublicKey(){return this.userPubkey?this.userPubkey:new Promise((t,r)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,s=>{t(s.result)})})}async encryptionEnabled(t){return t?[t]:Promise.resolve(["nip04","nip44"])}async encrypt(t,r,s="nip04"){return this.encryption(t,r,s,"encrypt")}async decrypt(t,r,s="nip04"){return this.encryption(t,r,s,"decrypt")}async encryption(t,r,s,o){return new Promise((u,c)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,`${s}_${o}`,[t.pubkey,r],24133,l=>{l.error?c(l.error):u(l.result)})})}async sign(t){return new Promise((s,o)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[JSON.stringify(t)],24133,a=>{if(a.error)o(a.error);else{const u=JSON.parse(a.result);s(u.sig)}})})}async createAccount(t,r,s){await this.startListening();const o=[];return t&&o.push(t),r&&o.push(r),s&&o.push(s),new Promise((a,u)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"create_account",o,24133,c=>{if(c.error)u(c.error);else{const l=c.result;a(l)}})})}toPayload(){if(!this.bunkerPubkey||!this.userPubkey)throw new Error("NIP-46 signer is not fully initialized for serialization");const t={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(t)}static async fromPayload(t,r){if(!r)throw new Error("NDK instance is required to deserialize NIP-46 signer");const s=JSON.parse(t);if(s.type!=="nip46")throw new Error(`Invalid payload type: expected 'nip46', got ${s.type}`);const o=s.payload;if(!o||typeof o!="object"||!o.localSignerPayload)throw new Error("Invalid payload content for nip46 signer");const a=await ndkSignerFromPayload(o.localSignerPayload,r);if(!a)throw new Error("Failed to deserialize local signer for NIP-46");let u;return o.nip05?(u=new ot(r,o.nip05,a),u.userPubkey=o.userPubkey,u.bunkerPubkey=o.bunkerPubkey,u.relayUrls=o.relayUrls,u.secret=o.secret):(u=new ot(r,o.userPubkey,a),u.bunkerPubkey=o.bunkerPubkey,u.relayUrls=o.relayUrls,u.secret=o.secret),u}};function dedup(n,e){return n.created_at>e.created_at?n:e}async function getRelayListForUser(n,e){return(await getRelayListForUsers([n],e)).get(n)}async function getRelayListForUsers(n,e,t=!1,r=1e3){var f;const s=e.outboxPool||e.pool,o=new Set;for(const p of s.relays.values())o.add(p);const a=new Map,u=new Map,c=new NDKRelaySet(o,e);if((f=e.cacheAdapter)!=null&&f.locking&&!t){const p=await e.fetchEvents({kinds:[3,10002],authors:Array.from(new Set(n))},{cacheUsage:"ONLY_CACHE",subId:"ndk-relay-list-fetch"});for(const b of p)b.kind===10002&&a.set(b.pubkey,NDKRelayList.from(b));for(const b of p)if(b.kind===3){if(a.has(b.pubkey))continue;const v=relayListFromKind3(e,b);v&&u.set(b.pubkey,v)}n=n.filter(b=>!a.has(b)&&!u.has(b))}if(n.length===0)return a;const l=new Map,h=new Map;return new Promise(p=>{(async()=>{const v={closeOnEose:!0,pool:s,groupable:!0,subId:"ndk-relay-list-fetch",addSinceFromCache:!0,relaySet:c};c&&(v.relaySet=c),e.subscribe({kinds:[3,10002],authors:n},v,{onEvent:m=>{if(m.kind===10002){const y=l.get(m.pubkey);if(y&&y.created_at>m.created_at)return;l.set(m.pubkey,m)}else if(m.kind===3){const y=h.get(m.pubkey);if(y&&y.created_at>m.created_at)return;h.set(m.pubkey,m)}},onEose:()=>{for(const m of l.values())a.set(m.pubkey,NDKRelayList.from(m));for(const m of n){if(a.has(m))continue;const y=h.get(m);if(!y)continue;const w=relayListFromKind3(e,y);w&&a.set(m,w)}p(a)}}),setTimeout(()=>{p(a)},r)})()})}var OutboxItem=class{constructor(n){g(this,"type");g(this,"relayUrlScores");g(this,"readRelays");g(this,"writeRelays");this.type=n,this.relayUrlScores=new Map,this.readRelays=new Set,this.writeRelays=new Set}},OutboxTracker=class extends lib$1.EventEmitter{constructor(e){super();g(this,"data");g(this,"ndk");g(this,"debug");this.ndk=e,this.debug=e.debug.extend("outbox-tracker"),this.data=new dist.LRUCache({maxSize:1e5,entryExpirationTimeInMS:2*60*1e3})}async trackUsers(e,t=!1){const r=[];for(let s=0;s<e.length;s+=400){const a=e.slice(s,s+400).map(u=>getKeyFromItem(u)).filter(u=>!this.data.has(u));if(a.length!==0){for(const u of a)this.data.set(u,new OutboxItem("user"));r.push(new Promise(u=>{getRelayListForUsers(a,this.ndk,t).then(c=>{for(const[l,h]of c){let f=this.data.get(l);if(f??(f=new OutboxItem("user")),h){f.readRelays=new Set(normalize(h.readRelayUrls)),f.writeRelays=new Set(normalize(h.writeRelayUrls));for(const p of f.readRelays)this.ndk.pool.blacklistRelayUrls.has(p)&&f.readRelays.delete(p);for(const p of f.writeRelays)this.ndk.pool.blacklistRelayUrls.has(p)&&f.writeRelays.delete(p);this.data.set(l,f)}}}).finally(u)}))}}return Promise.all(r)}track(e,t,r=!0){const s=getKeyFromItem(e);t??(t=getTypeFromItem(e));let o=this.data.get(s);return o||(o=new OutboxItem(t),e instanceof NDKUser&&this.trackUsers([e])),o}};function getKeyFromItem(n){return n instanceof NDKUser?n.pubkey:n}function getTypeFromItem(n){return n instanceof NDKUser?"user":"kind"}function correctRelaySet(n,e){const t=e.connectedRelays();if(!Array.from(n.relays).some(s=>t.map(o=>o.url).includes(s.url)))for(const s of t)n.addRelay(s);if(t.length===0)for(const s of e.relays.values())n.addRelay(s);return n}var NDKSubscriptionManager=class{constructor(){g(this,"subscriptions");g(this,"seenEvents",new Map);this.subscriptions=new Map}add(n){this.subscriptions.set(n.internalId,n),n.onStopped,n.onStopped=()=>{this.subscriptions.delete(n.internalId)},n.on("close",()=>{this.subscriptions.delete(n.internalId)})}seenEvent(n,e){const t=this.seenEvents.get(n)||[];t.push(e),this.seenEvents.set(n,t)}dispatchEvent(n,e,t=!1){e&&this.seenEvent(n.id,e);const r=this.subscriptions.values(),s=[];for(const o of r)matchFilters(o.filters,n)&&s.push(o);for(const o of s)o.eventReceived(n,e,!1,t)}},debug6=createDebug5("ndk:active-user");async function getUserRelayList(n){if(!this.autoConnectUserRelays)return;const e=await getRelayListForUser(n.pubkey,this);if(e){for(const t of e.relays){let r=this.pool.relays.get(t);r||(r=new NDKRelay(t,this.relayAuthDefaultPolicy,this),this.pool.addRelay(r))}return e}}async function setActiveUser(n){const e=this.outboxPool||this.pool;e.connectedRelays.length>0?setActiveUserConnected.call(this,n):e.once("connect",()=>{setActiveUserConnected.call(this,n)})}async function setActiveUserConnected(n){var o;const e=await getUserRelayList.call(this,n),t=[{kinds:[10006],authors:[n.pubkey]}];this.autoFetchUserMutelist&&((o=t[0].kinds)==null||o.push(1e4));const r=new Map,s=e?e.relaySet:void 0;this.subscribe(t,{subId:"active-user-settings",closeOnEose:!0,relaySet:s},{onEvent:a=>{const u=r.get(a.kind);u&&u.created_at>=a.created_at||r.set(a.kind,a)},onEose:()=>{for(const a of r.values())processEvent.call(this,a)}})}async function processEvent(n){n.kind===10006?processBlockRelayList.call(this,n):n.kind===1e4&&processMuteList.call(this,n)}function processBlockRelayList(n){const e=lists_default.from(n);for(const t of e.items)this.pool.blacklistRelayUrls.add(t[0]);debug6("Added %d relays to relay blacklist",e.items.length)}function processMuteList(n){const e=lists_default.from(n);for(const t of e.items)this.mutedIds.set(t[1],t[0]);debug6("Added %d users to mute list",e.items.length)}function getEntity(n){try{const e=nip19_exports.decode(n);return e.type==="npub"?npub(this,e.data):e.type==="nprofile"?nprofile(this,e.data):e}catch{return null}}function npub(n,e){return n.getUser({pubkey:e})}function nprofile(n,e){const t=n.getUser({pubkey:e.pubkey});return e.relays&&(t.relayUrls=e.relays),t}function isValidHint(n){if(!n||n==="")return!1;try{return new URL(n),!0}catch{return!1}}async function fetchEventFromTag(n,e,t,r={type:"timeout"}){const s=this.debug.extend("fetch-event-from-tag"),[o,a,u]=n;t={},s("fetching event from tag",n,t,r);const c=getRelaysForSync(this,e.pubkey);if(c&&c.size>0){s("fetching event from author relays %o",Array.from(c));const m=NDKRelaySet.fromRelayUrls(Array.from(c),this),y=await this.fetchEvent(a,t,m);if(y)return y}else s("no author relays found for %s",e.pubkey,e);const l=calculateRelaySetsFromFilters(this,[{ids:[a]}],this.pool);s("fetching event without relay hint",l);const h=await this.fetchEvent(a,t);if(h)return h;if(u&&u!==""){const m=await this.fetchEvent(a,t,this.pool.getRelay(u,!0,!0,[{ids:[a]}]));if(m)return m}let f;const p=isValidHint(u)?this.pool.getRelay(u,!1,!0,[{ids:[a]}]):void 0,b=new Promise(m=>{this.fetchEvent(a,t,p).then(m)});if(!isValidHint(u)||r.type==="none")return b;const v=new Promise(async m=>{const y=r.relaySet,w=r.timeout??1500,x=new Promise(k=>setTimeout(k,w));if(r.type==="timeout"&&await x,f)m(f);else{s("fallback fetch triggered");const k=await this.fetchEvent(a,t,y);m(k)}});switch(r.type){case"timeout":return Promise.race([b,v]);case"eose":return f=await b,f||v}}var Queue=class{constructor(n,e){g(this,"queue",[]);g(this,"maxConcurrency");g(this,"processing",new Set);g(this,"promises",new Map);this.maxConcurrency=e}add(n){if(this.promises.has(n.id))return this.promises.get(n.id);const e=new Promise((t,r)=>{this.queue.push({...n,func:()=>n.func().then(s=>(t(s),s),s=>{throw r(s),s})}),this.process()});return this.promises.set(n.id,e),e.finally(()=>{this.promises.delete(n.id),this.processing.delete(n.id),this.process()}),e}process(){if(this.processing.size>=this.maxConcurrency||this.queue.length===0)return;const n=this.queue.shift();!n||this.processing.has(n.id)||(this.processing.add(n.id),n.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/"],DEFAULT_BLACKLISTED_RELAYS=["wss://brb.io/","wss://nostr.mutinywallet.com/"],NDK=class extends lib$1.EventEmitter{constructor(e={}){super();g(this,"_explicitRelayUrls");g(this,"blacklistRelayUrls");g(this,"pool");g(this,"outboxPool");g(this,"_signer");g(this,"_activeUser");g(this,"cacheAdapter");g(this,"debug");g(this,"devWriteRelaySet");g(this,"outboxTracker");g(this,"mutedIds");g(this,"clientName");g(this,"clientNip89");g(this,"queuesZapConfig");g(this,"queuesNip05");g(this,"asyncSigVerification",!1);g(this,"initialValidationRatio",1);g(this,"lowestValidationRatio",1);g(this,"validationRatioFn");g(this,"subManager");g(this,"publishingFailureHandled",!1);g(this,"pools",[]);g(this,"relayAuthDefaultPolicy");g(this,"httpFetch");g(this,"netDebug");g(this,"autoConnectUserRelays",!0);g(this,"autoFetchUserMutelist",!0);g(this,"walletConfig");g(this,"fetchEventFromTag",fetchEventFromTag.bind(this));g(this,"getEntity",getEntity.bind(this));this.debug=e.debug||createDebug5("ndk"),this.netDebug=e.netDebug,this._explicitRelayUrls=e.explicitRelayUrls||[],this.blacklistRelayUrls=e.blacklistRelayUrls||DEFAULT_BLACKLISTED_RELAYS,this.subManager=new NDKSubscriptionManager,this.pool=new NDKPool(e.explicitRelayUrls||[],[],this),this.pool.name="Main",this.pool.on("relay:auth",async(t,r)=>{this.relayAuthDefaultPolicy&&await this.relayAuthDefaultPolicy(t,r)}),this.autoConnectUserRelays=e.autoConnectUserRelays??!0,this.autoFetchUserMutelist=e.autoFetchUserMutelist??!0,this.clientName=e.clientName,this.clientNip89=e.clientNip89,this.relayAuthDefaultPolicy=e.relayAuthDefaultPolicy,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.signer=e.signer,this.cacheAdapter=e.cacheAdapter,this.mutedIds=e.mutedIds||new Map,e.devWriteRelayUrls&&(this.devWriteRelaySet=NDKRelaySet.fromRelayUrls(e.devWriteRelayUrls,this)),this.queuesZapConfig=new Queue("zaps",3),this.queuesNip05=new Queue("nip05",10),this.signatureVerificationWorker=e.signatureVerificationWorker,this.initialValidationRatio=e.initialValidationRatio||1,this.lowestValidationRatio=e.lowestValidationRatio||1;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.asyncSigVerification=!!e,e&&signatureVerificationInit(e)}addExplicitRelay(e,t,r=!0){var o;let s;return typeof e=="string"?s=new NDKRelay(e,t,this):s=e,this.pool.addRelay(s,r),(o=this.explicitRelayUrls)==null||o.push(s.url),s}toJSON(){return{relayCount:this.pool.relays.size}.toString()}get activeUser(){return this._activeUser}set activeUser(e){var r;const t=((r=this._activeUser)==null?void 0:r.pubkey)!==(e==null?void 0:e.pubkey);this._activeUser=e,e&&t?setActiveUser.call(this,e):e||(this.mutedIds=new Map)}get signer(){return this._signer}set signer(e){this._signer=e,e&&this.emit("signer:ready",e),e==null||e.user().then(t=>{t.ndk=this,this.activeUser=t})}async connect(e){var r,s;this._signer&&this.autoConnectUserRelays&&(this.debug("Attempting to connect to user relays specified by signer %o",await((s=(r=this._signer).relays)==null?void 0:s.call(r,this))),this._signer.relays&&(await this._signer.relays(this)).forEach(a=>this.pool.addRelay(a)));const t=[this.pool.connect(e)];return this.outboxPool&&t.push(this.outboxPool.connect(e)),this.debug("Connecting to relays %o",{timeoutMs:e}),Promise.allSettled(t).then(()=>{})}getUser(e){const t=new NDKUser(e);return t.ndk=this,t}async getUserFromNip05(e,t=!1){return NDKUser.fromNip05(e,this,t)}subscribe(e,t,r=!0){var a;const s=new NDKSubscription(this,e,t);this.subManager.add(s);const o=s.pool;if(s.relaySet)for(const u of s.relaySet.relays)o.useTemporaryRelay(u,void 0,s.filters);if(this.outboxPool&&s.hasAuthorsFilter()){const u=s.filters.filter(c=>{var l;return c.authors&&((l=c.authors)==null?void 0:l.length)>0}).flatMap(c=>c.authors);(a=this.outboxTracker)==null||a.trackUsers(u)}if(r){let u;typeof r=="object"&&(r.onEvent&&s.on("event",r.onEvent),r.onEose&&s.on("eose",r.onEose),r.onEvents&&(u=r.onEvents)),setTimeout(()=>{const c=s.start(!u);c&&c.length>0&&u&&u(c)},0)}return s}async publish(e,t,r){return this.debug("Deprecated: Use `event.publish()` instead"),e.publish(t,r)}fetchEventSync(e){if(!this.cacheAdapter)throw new Error("Cache adapter not set");let t;typeof e=="string"?t=[filterFromId(e)]:t=e;const r=new NDKSubscription(this,t),s=this.cacheAdapter.query(r);if(s instanceof Promise)throw new Error("Cache adapter is async");return s.map(o=>(o.ndk=this,o))}async fetchEvent(e,t,r){let s,o;if(r instanceof NDKRelay?o=new NDKRelaySet(new Set([r]),this):r instanceof NDKRelaySet&&(o=r),!r&&typeof e=="string"&&!isNip33AValue(e)){const a=relaysFromBech32(e,this);a.length>0&&(o=new NDKRelaySet(new Set(a),this),o=correctRelaySet(o,this.pool))}if(typeof e=="string"?s=[filterFromId(e)]:Array.isArray(e)?s=e:s=[e],s.length===0)throw new Error(`Invalid filter: ${JSON.stringify(e)}`);return new Promise(a=>{let u=null;const c={...t||{},closeOnEose:!0};o&&(c.relaySet=o);const l=this.subscribe(s,c,!1),h=setTimeout(()=>{l.stop(),a(u)},1e4);l.on("event",f=>{f.ndk=this,f.isReplaceable()?(!u||u.created_at<f.created_at)&&(u=f):(clearTimeout(h),a(f))}),l.on("eose",()=>{clearTimeout(h),a(u)}),l.start()})}async fetchEvents(e,t,r){return new Promise(s=>{const o=new Map,a={...t||{},closeOnEose:!0};r&&(a.relaySet=r);const u=this.subscribe(e,a,!1),c=l=>{let h;l instanceof NDKEvent?h=l:h=new NDKEvent(void 0,l);const f=h.deduplicationKey(),p=o.get(f);p&&(h=dedup(p,h)),h.ndk=this,o.set(f,h)};u.on("event",c),u.on("eose",()=>{s(new Set(o.values()))}),u.start()})}assertSigner(){if(!this.signer)throw this.emit("signer:required"),new Error("Signer required")}set wallet(e){var t,r;if(!e){this.walletConfig=void 0;return}this.walletConfig??(this.walletConfig={}),this.walletConfig.lnPay=(t=e==null?void 0:e.lnPay)==null?void 0:t.bind(e),this.walletConfig.cashuPay=(r=e==null?void 0:e.cashuPay)==null?void 0:r.bind(e)}};createDebug5("ndk:zapper:ln"),createDebug5("ndk:zapper");const index$1=Object.freeze(Object.defineProperty({__proto__:null,BECH32_REGEX,NDKArticle,NDKCashuMintList,NDKCashuToken,NDKEvent,NDKHighlight,NDKImage,NDKKind,NDKList,NDKNip07Signer,NDKNip46Signer,NDKNostrRpc,NDKNutzap,NDKPool,NDKPrivateKeySigner,NDKPublishError,NDKRelay,NDKRelayAuthPolicies,NDKRelayList,NDKRelaySet,NDKSimpleGroupMemberList,NDKSimpleGroupMetadata,NDKStory,NDKStorySticker,NDKSubscription,NDKSubscriptionTier,NDKUser,NDKVideo,NDKWiki,NIP33_A_REGEX,calculateRelaySetFromEvent,default:NDK,defaultOpts:defaultOpts$1,deserialize,eventHasETagMarkers,filterFingerprint,filterFromId,generateContentTags,generateHashtags,getRelayListForUser,getRelayListForUsers,getReplyTag,getRootTag,imetaTagToTag,isNip33AValue,mapImetaTag,mergeFilters,mergeTags,ndkSignerFromPayload,newAmount,normalize,normalizeRelayUrl,normalizeUrl,parseTagToSubscriptionAmount,possibleIntervalFrequencies,profileFromEvent,proofsTotalBalance,queryFullyFilled,relayListFromKind3,relaysFromBech32,serialize,serializeProfile,signerRegistry,strToDimension,strToPosition,tryNormalizeRelayUrl,wrapEvent},Symbol.toStringTag,{value:"Module"})),DEFAULT_RELAYS=["wss://relay.damus.io","wss://nostr.wine","wss://relay.nostr.net","wss://relay.nostr.band","wss://nos.lol","wss://nostr-pub.wellorder.net","wss://relay.getalby.com","wss://relay.primal.net"],MILLISATS_PER_SAT=1e3,DEFAULT_PROFILE_IMAGE="./assets/default_dp.png",Ie=class Ie{constructor(){g(this,"ndk");g(this,"isConnected",!1);this.ndk=new NDK}static getInstance(){return Ie.instance||(Ie.instance=new Ie),Ie.instance}async connectToNostr(e=[...DEFAULT_RELAYS]){const t=e.filter(r=>!this.getRelays().includes(r));if(this.isConnected&&t.length){t.forEach(r=>this.ndk.addExplicitRelay(r));return}this.ndk.explicitRelayUrls=e,await this.ndk.connect(),this.isConnected=!0}getRelays(){return this.ndk.explicitRelayUrls||DEFAULT_RELAYS}async resolveNDKUser(e){return e.npub?this.ndk.getUser({npub:e.npub}):e.nip05?await this.ndk.getUserFromNip05(e.nip05)??null:e.pubkey?this.ndk.getUser({pubkey:e.pubkey}):null}async resolveNDKEvent(e){return e.hex?this.ndk.fetchEvent(e.hex):null}async getZapCount(e){const t=await this.resolveNDKUser(e);return t?this.fetchZaps(t):0}async getProfile(e){if(!e)return null;await e.fetchProfile();const t=e.profile;return t&&(t.picture===void 0||t.picture===null)&&(t.picture=DEFAULT_PROFILE_IMAGE),t}async getPost(e){const t=await this.ndk.fetchEvent(e);if(!t)return null;const r=t.getMatchingTags("e");if(r.length>0){const o=r.map(a=>a[1]);await this.ndk.fetchEvents({ids:o})}const s=t.getMatchingTags("a");for(const o of s){const a=o[1],u=o[2];a!=null&&a.startsWith("video/")&&u&&(t.content=t.content+`
77
77
  ${u}`)}return t}async fetchFollows(e){try{return(await e.followSet()).size}catch{return 0}}async fetchFollowers(e){try{const t=await this.ndk.fetchEvents({kinds:[NDKKind.Contacts],"#p":[e.pubkey]}),r=new Set;return t.forEach(o=>r.add(o.pubkey)),r.size}catch{return 0}}async fetchNotesAndReplies(e){try{const t=await this.ndk.fetchEvents({kinds:[NDKKind.Text],authors:[e.pubkey],limit:1e3});let r=0,s=0;t.forEach(u=>{u&&(u.tags.some(l=>l[0]==="e"&&l[3]!=="mention")&&r++,s++)});const o=r;return[Math.max(0,s-r),o]}catch{return[0,0]}}async fetchZaps(e){try{return(await this.ndk.fetchEvents({kinds:[9735],"#p":[e.pubkey],limit:1e3})).size}catch{return 0}}getNDK(){return this.ndk}hasSigner(){return typeof window<"u"&&window.nostr||typeof window<"u"&&typeof localStorage<"u"&&localStorage.getItem("nostr_nsec")?!0:!!this.ndk.signer}};g(Ie,"instance");let NostrService=Ie;const decodeNpub=n=>{if(typeof n!="string"||!n.startsWith("npub1"))return"";try{const e=nip19_exports.decode(n);if(e&&typeof e.data=="string")return e.data}catch(e){console.error("Failed to decode npub:",e)}return""};function hexToNpub(n){if(!n||!isValidHex(n))return"";try{return nip19_exports.npubEncode(n.toLowerCase())}catch(e){return console.error("Failed to encode hex to npub:",e),""}}function maskNPub(n="",e=3){const t=n.length;if(!n.startsWith("npub1"))return"Invalid nPub: expected npub1...";if(!validateNpub(n))return"Invalid nPub";let r="npub1";for(let o=5;o<e+5;o++)r+=n[o];r+="...";let s="";for(let o=t-1;o>=t-e;o--)s=n[o]+s;return r+=s,r}async function getPostStats(n,e){const t=await n.fetchEvents({kinds:[NDKKind.Repost],"#e":[e||""]}),r=h=>h.tags.filter(p=>p[0]==="p").length===1,s=h=>h.tags.filter(p=>p[0]==="e").length===1,o=Array.from(t).filter(r).length,a=await n.fetchEvents({kinds:[NDKKind.Reaction],"#e":[e||""]}),u=0,c=await n.fetchEvents({kinds:[NDKKind.Text],"#e":[e||""]}),l=Array.from(c).filter(s).length;return{likes:a.size,reposts:o,zaps:u/MILLISATS_PER_SAT,replies:l}}function parseRelays(n){if(n){const e=n.split(",").map(t=>t.trim()).filter(Boolean).filter(isValidRelayUrl);return e.length?Array.from(new Set(e)):[...DEFAULT_RELAYS]}return[...DEFAULT_RELAYS]}function parseTheme(n){const e=n==null?void 0:n.trim().toLowerCase();return e==="light"||e==="dark"?e:"light"}function parseBooleanAttribute(n){return n===null?!1:n===""||n.toLowerCase()==="true"}function escapeHtml$1(n){const e=document.createElement("div");return e.textContent=n,e.innerHTML}function isValidUrl(n){try{const e=new URL(n);return["http:","https:"].includes(e.protocol)}catch{return!1}}function isValidRelayUrl(n){try{const e=new URL(n);return e.protocol==="wss:"||e.protocol==="ws:"}catch{return!1}}function isValidHex(n){return/^[0-9a-fA-F]+$/.test(n)&&n.length===64}function validateNpub(n){try{const{type:e}=nip19_exports.decode(n);return e==="npub"}catch{return!1}}function validateNip05(n){return/^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9_\-\.]+\.[a-zA-Z]{2,}$/.test(n)}function validateBech32OfType(n,e){try{const{type:t}=nip19_exports.decode(n);return t===e}catch{return!1}}function validateNoteId(n){return validateBech32OfType(n,"note")}function validateEventId(n){return validateBech32OfType(n,"nevent")}function copyToClipboard(n){return navigator.clipboard.writeText(n)}function formatRelativeTime$1(n){try{const e=Date.now(),t=n*1e3,r=e-t,s=Math.floor(r/1e3);if(s<60)return"just now";if(s<3600){const a=Math.floor(s/60);return`${a} ${a===1?"min":"mins"} ago`}if(s<86400){const a=Math.floor(s/3600);return`${a} ${a===1?"hour":"hours"} ago`}if(s<2592e3){const a=Math.floor(s/86400);return`${a} ${a===1?"day":"days"} ago`}if(s<31536e3){const a=Math.floor(s/2592e3);return`${a} ${a===1?"month":"months"} ago`}const o=Math.floor(s/31536e3);return`${o} ${o===1?"year":"years"} ago`}catch(e){return console.error("Error formatting relative time:",e),"unknown"}}var NCStatus=(n=>(n[n.Idle=0]="Idle",n[n.Loading=1]="Loading",n[n.Ready=2]="Ready",n[n.Error=3]="Error",n))(NCStatus||{});const EVT_STATUS="nc:status";class NostrBaseComponent extends HTMLElement{constructor(t=!0){super();g(this,"nostrService",NostrService.getInstance());g(this,"theme","light");g(this,"errorMessage","");g(this,"nostrReady");g(this,"nostrReadyResolve");g(this,"nostrReadyReject");g(this,"conn",this.channel("connection"));g(this,"_statuses",new Map);g(this,"_overall",0);g(this,"connectSeq",0);t&&this.attachShadow({mode:"open"}),this.resetNostrReadyBarrier()}static get observedAttributes(){return["data-theme","relays"]}connectedCallback(){this.validateInputs()&&(this.getTheme(),this.conn.get()===0&&this.connectToNostr())}disconnectedCallback(){this.shadowRoot&&this._delegated&&this._delegated.clear()}attributeChangedCallback(t,r,s){r!==s&&(t==="data-theme"||t==="relays")&&this.validateInputs()&&(t==="relays"&&(this.resetNostrReadyBarrier(),this.connectToNostr()),t==="data-theme"&&(this.getTheme(),this.render()))}setStatusFor(t,r,s){const o=this._statuses.get(t);if(!(o!==r||r===3&&!!s))return;this._statuses.set(t,r),r===3&&s?this.errorMessage=s:o===3&&r!==3&&(this.errorMessage="");const u=`${t}-status`,c=NCStatus[r].toLowerCase();this.getAttribute(u)!==c&&this.setAttribute(u,c);const l=this.computeOverall(),h=NCStatus[l].toLowerCase();this._overall!==l?(this._overall=l,this.setAttribute("status",h),this.onStatusChange(l)):l===3&&s&&this.onStatusChange(l),this.dispatchEvent(new CustomEvent(EVT_STATUS,{detail:{key:t,status:r,all:this.snapshotStatuses(),overall:this._overall,errorMessage:this.errorMessage||void 0},bubbles:!0,composed:!0}))}getStatusFor(t){return this._statuses.get(t)??0}snapshotStatuses(){return Object.fromEntries(this._statuses.entries())}onStatusChange(t){}onNostrRelaysConnected(){}computeOverall(){const t=[...this._statuses.values()];return t.includes(3)?3:t.includes(1)?1:t.includes(2)?2:0}initChannelStatus(t,r,s={reflectOverall:!1}){if(this._statuses.set(t,r),this.setAttribute(`${t}-status`,NCStatus[r].toLowerCase()),s.reflectOverall){const o=this.computeOverall();this._overall=o,this.setAttribute("status",NCStatus[o].toLowerCase())}}channel(t){return{set:(r,s)=>this.setStatusFor(t,r,s),get:()=>this.getStatusFor(t)}}validateInputs(){const t=this.getAttribute("data-theme")||"light",r=this.getAttribute("relays"),s=this.tagName.toLowerCase();if(t==="light"||t==="dark"){if(r&&typeof r!="string")return this.conn.set(3,"Invalid relays list"),console.error(`Nostr-Components: ${s}: ${this.errorMessage}`),!1;if(r){const a=r.split(",").map(u=>u.trim()).filter(Boolean).filter(u=>!isValidRelayUrl(u));if(a.length>0){const u=a.join(", ");return this.conn.set(3,`Invalid relay URLs: ${u}. Relay URLs must start with 'wss://' or 'ws://'`),console.error(`Nostr-Components: ${s}: ${this.errorMessage}`),!1}}}else return this.conn.set(3,`Invalid theme '${t}'. Accepted values are 'light', 'dark'`),console.error(`Nostr-Components: ${s}: ${this.errorMessage}`),!1;return this.errorMessage="",!0}async connectToNostr(){var r,s;const t=++this.connectSeq;this.conn.set(1);try{if(await this.nostrService.connectToNostr(this.getRelays()),t!==this.connectSeq)return;this.conn.set(2),(r=this.nostrReadyResolve)==null||r.call(this);try{this.onNostrRelaysConnected()}catch(o){console.error("Error in onNostrRelaysConnected hook:",o)}}catch(o){if(t!==this.connectSeq)return;console.error("Failed to connect to Nostr relays:",o),this.conn.set(3,"Failed to connect to relays"),(s=this.nostrReadyReject)==null||s.call(this,o)}}ensureNostrConnected(){return this.nostrReady}getRelays(){return parseRelays(this.getAttribute("relays"))}getTheme(){this.theme=parseTheme(this.getAttribute("data-theme"))}delegateEvent(t,r,s){var u;const o=this.shadowRoot;if(!o)return;const a=`${t}:${r}`;(u=this._delegated)!=null&&u.has(a)||(this._delegated||(this._delegated=new Set),this._delegated.add(a),o.addEventListener(t,c=>{c.target.closest(r)&&s(c)}))}addDelegatedListener(t,r,s){this.delegateEvent(t,r,s)}renderError(t){return`Error: ${t}`}updateHostClasses(){const t=this.computeOverall()===1,r=this.computeOverall()===3,s=this.computeOverall()===2;this.classList.remove("is-clickable","is-disabled","is-error"),t?this.classList.add("is-disabled"):r?this.classList.add("is-error"):s&&this.classList.add("is-clickable")}render(){this.updateHostClasses(),this.renderContent()}handleNjumpClick(t,r,s){if(this.computeOverall()!==2)return;const o=new CustomEvent(t,{detail:r,bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(o)&&window.open(`https://njump.me/${s}`,"_blank","noopener,noreferrer")}resetNostrReadyBarrier(){this.connectSeq++,this.nostrReady=new Promise((t,r)=>{this.nostrReadyResolve=t,this.nostrReadyReject=r})}}class UserResolver{constructor(e){this.nostrService=e}validateInputs({npub:e,pubkey:t,nip05:r}){return!e&&!t&&!r?"Provide npub, nip05 or pubkey attribute":t&&!isValidHex(t)?`Invalid Pubkey: ${t}`:r&&!validateNip05(r)?`Invalid Nip05: ${r}`:e&&!validateNpub(e)?`Invalid Npub: ${e}`:null}async resolveUser({npub:e,pubkey:t,nip05:r}){const s=await this.nostrService.resolveNDKUser({npub:e,pubkey:t,nip05:r});if(!s)throw new Error("Unable to resolve user from provided identifier");const o=await this.nostrService.getProfile(s);return{user:s,profile:o??null}}}const EVT_USER="nc:user";class NostrUserComponent extends NostrBaseComponent{constructor(t=!0){super(t);g(this,"user",null);g(this,"profile",null);g(this,"userStatus",this.channel("user"));g(this,"loadSeq",0);g(this,"resolver",new UserResolver(this.nostrService))}static get observedAttributes(){return[...super.observedAttributes,"npub","pubkey","nip05"]}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),this.userStatus.get()==NCStatus.Idle&&this.initChannelStatus("user",NCStatus.Loading,{reflectOverall:!1}),this.validateInputs()&&this.resolveUserAndProfile().catch(r=>{console.error("[NostrUserComponent] init failed:",r)})}attributeChangedCallback(t,r,s){var o;r!==s&&((o=super.attributeChangedCallback)==null||o.call(this,t,r,s),(t==="npub"||t==="nip05"||t==="pubkey")&&this.validateInputs()&&this.resolveUserAndProfile())}validateInputs(){if(!super.validateInputs())return this.userStatus.set(NCStatus.Idle),!1;const t=this.getAttribute("npub"),r=this.getAttribute("pubkey"),s=this.getAttribute("nip05"),o=this.tagName.toLowerCase(),a=this.resolver.validateInputs({npub:t,pubkey:r,nip05:s});return a?(this.userStatus.set(NCStatus.Error,a),console.error(`Nostr-Components: ${o}: ${a}`),!1):(this.errorMessage="",!0)}async resolveUserAndProfile(){const t=++this.loadSeq;try{await this.ensureNostrConnected()}catch(r){if(t!==this.loadSeq)return;console.error("[NostrUserComponent] Relay connect failed before user/profile load:",r);return}this.userStatus.set(NCStatus.Loading);try{const{user:r,profile:s}=await this.resolver.resolveUser({npub:this.getAttribute("npub"),pubkey:this.getAttribute("pubkey"),nip05:this.getAttribute("nip05")});if(t!==this.loadSeq)return;if(s==null){this.userStatus.set(NCStatus.Error,"Profile not found");return}this.user=r,this.profile=s,this.userStatus.set(NCStatus.Ready),this.dispatchEvent(new CustomEvent(EVT_USER,{detail:{user:this.user,profile:this.profile},bubbles:!0,composed:!0})),this.onUserReady(this.user,this.profile)}catch(r){if(t!==this.loadSeq)return;const s=r instanceof Error?r.message:"Failed to load user/profile";console.error("[NostrUserComponent] "+s,r),this.userStatus.set(NCStatus.Error,s)}}renderContent(){}onUserReady(t,r){}}function renderTextRow(n){const{value:e,display:t=e,className:r="",monospace:s=!1,title:o=t,showCopyButton:a=!1}=n,u=r.replace(/[^\w\- ]/g,""),c=escapeHtml$1(t),l=escapeHtml$1(o),h="&#x2398;";if(a){const p=escapeHtml$1(e);return`
78
78
  <div class="${`text-row nc-copy ${s?"mono":""} ${u}`.trim()}" data-copy="${p}" title="${l}">
79
79
  <span class="nc-copy-text">${c}</span>
@@ -3152,7 +3152,7 @@ Minimum version required to store current data is: `+o+`.
3152
3152
  padding: 0 16px 16px;
3153
3153
  }
3154
3154
  </style>
3155
- `}async function resolveNip05(n,e=5e3){var c;if(!/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(n))throw new Error("Invalid NIP-05 format");const[r,s]=n.split("@");if(!r||!s)throw new Error("Invalid NIP-05: missing name or domain");const o=`https://${s}/.well-known/nostr.json?name=${encodeURIComponent(r)}`,a=new AbortController,u=setTimeout(()=>a.abort(),e);try{const l=await fetch(o,{headers:{accept:"application/json"},signal:a.signal});if(!l.ok)throw new Error("Unable to resolve NIP-05");const f=(c=(await l.json()).names)==null?void 0:c[r];if(!f)throw new Error("NIP-05 not found");return f}catch(l){throw l instanceof Error&&l.name==="AbortError"?new Error("NIP-05 resolution timed out"):l}finally{clearTimeout(u)}}function debug(n,e,t){const r=process.env.NODE_ENV==="development",s=n.getAttribute("debug")==="true";(r||s)&&(t?console.log(`[NostrDm] ${e}`,t):console.log(`[NostrDm] ${e}`))}class NostrDm extends HTMLElement{constructor(){super();g(this,"rendered",!1);g(this,"nostrService",NostrService.getInstance());g(this,"theme","light");g(this,"recipientNpub",null);g(this,"recipientNip05",null);g(this,"recipientName",null);g(this,"recipientPicture",null);g(this,"recipientPubkey",null);g(this,"message","");g(this,"isLoading",!1);g(this,"isFinding",!1);g(this,"isError",!1);g(this,"errorMessage","");g(this,"isSent",!1);g(this,"boundHandleFind",null);g(this,"boundHandleSend",null);g(this,"boundHandleTextareaChange",null);g(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(","):DEFAULT_RELAYS});g(this,"getTheme",async()=>{this.theme="light";const t=this.getAttribute("theme");if(t){if(!["light","dark"].includes(t))throw new Error(`Invalid theme '${t}'. Accepted values are 'light', 'dark'`);this.theme=t}});g(this,"getRecipient",()=>{const t=this.getAttribute("nip05");if(t){this.recipientNip05=t,this.lookupRecipientByNip05();return}const r=this.getAttribute("recipient-npub");r&&(this.recipientNpub=r,this.lookupRecipient())});this.attachShadow({mode:"open"})}connectedCallback(){this.rendered||(this.rendered=!0,this.getTheme(),this.getRecipient(),this.nostrService.connectToNostr(this.getRelays()),this.render())}static get observedAttributes(){return["relays","recipient-npub","nip05","theme","debug"]}attributeChangedCallback(t,r,s){t==="relays"&&this.nostrService.connectToNostr(this.getRelays()),t==="theme"&&this.getTheme(),t==="nip05"&&s&&(this.recipientNip05=s,this.lookupRecipientByNip05()),t==="recipient-npub"&&s&&(this.recipientNpub=s,this.lookupRecipient()),this.render()}async lookupRecipient(t){const r=t||this.recipientNpub;if(r){this.isFinding=!0,this.render();try{const o=this.nostrService.getNDK().getUser({npub:r});await o.fetchProfile(),o.profile?(this.recipientName=o.profile.displayName||o.profile.name||"Unknown",this.recipientPicture=o.profile.image||null,this.recipientPubkey=o.pubkey,this.recipientNpub=r):(this.recipientName="Unknown",this.recipientPicture=null,this.recipientPubkey=o.pubkey,this.recipientNpub=r)}catch(s){this.isError=!0,this.errorMessage=`Failed to find recipient: ${s.message}`}finally{this.isFinding=!1,this.render()}}}async lookupRecipientByNip05(t){const r=t||this.recipientNip05;if(r){this.isFinding=!0,this.render();try{const s=await resolveNip05(r);if(!s)throw new Error("Failed to resolve nip05");const o=nip19_exports.npubEncode(s);await this.lookupRecipient(o)}catch(s){this.isError=!0,this.errorMessage=`Failed to resolve nip05: ${s.message}`}finally{this.isFinding=!1,this.render()}}}async handleFindClick(){const t=this.shadowRoot.querySelector(".nostr-dm-npub-input");if(!t||!t.value){this.isError=!0,this.errorMessage="Please enter a valid npub",this.render();return}const r=t.value.trim();r.includes("@")?await this.lookupRecipientByNip05(r):await this.lookupRecipient(r)}async handleSendClick(){if(debug(this,"Send button clicked!"),!this.recipientPubkey||!this.message.trim()){this.isError=!0,this.errorMessage=this.recipientPubkey?"Please enter a message":"Recipient not found",this.render();return}if(this.isError=!1,this.isSent=!1,this.isLoading=!0,this.render(),!this.nostrService.hasSigner()){this.isError=!0,this.errorMessage="No Nostr signer available. Please ensure your Nostr extension is installed or provide a private key.",this.isLoading=!1,this.render();return}let t=null;if(typeof window<"u"&&window.nostr)t=new NDKNip07Signer;else if(typeof localStorage<"u"){const r=localStorage.getItem("nostr_nsec");if(r){const{NDKPrivateKeySigner:s}=await Promise.resolve().then(()=>index);t=new s(r)}}if(!t){this.isError=!0,this.errorMessage="Failed to create signer. Please ensure your Nostr signer (extension or private key) is configured.",this.render();return}this.render();try{const r=this.nostrService.getNDK();r.signer=t;const{nip04:s}=await Promise.resolve().then(()=>index$1),o=new NDKEvent(r,{kind:NDKKind.EncryptedDirectMessage,tags:[["p",this.recipientPubkey]],created_at:Math.floor(Date.now()/1e3)});if(typeof window<"u"&&window.nostr){const u=await window.nostr.nip04.encrypt(this.recipientPubkey,this.message.trim());o.content=u}else if(typeof localStorage<"u"){const u=localStorage.getItem("nostr_nsec");if(!u)throw new Error("No private key available");const{nip19:c}=await Promise.resolve().then(()=>index$1);let l=u;if(u.startsWith("nsec"))try{l=c.decode(u).data}catch(h){throw console.error("Failed to decode nsec:",h),new Error("Invalid private key format")}try{o.content=await s.encrypt(l,this.recipientPubkey,this.message.trim())}catch(h){throw console.error("Encryption error:",h),new Error(`Encryption failed: ${h.message}`)}}debug(this,"Sending encrypted DM:",{to:this.recipientPubkey,encryptedContent:o.content}),await o.publish(),debug(this,"DM sent with encrypted content:",o),this.isSent=!0,this.message="";const a=this.shadowRoot.querySelector(".nostr-dm-textarea");a&&(a.value="")}catch(r){this.isError=!0,this.errorMessage=`Failed to send message: ${r.message}`,this.isSent=!1}finally{this.isLoading=!1,this.isFinding=!1,this.render()}}handleTextareaChange(t){const r=t.target;this.message=r.value}attachEventListeners(){const t=this.shadowRoot.querySelector(".nostr-dm-find-btn");t?(this.boundHandleFind&&t.removeEventListener("click",this.boundHandleFind),this.boundHandleFind=this.handleFindClick.bind(this),t.addEventListener("click",this.boundHandleFind),debug(this,"Find button event listener attached")):debug(this,"Find button not found in DOM");const r=this.shadowRoot.querySelector(".nostr-dm-send-btn");r?(debug(this,"Send button found, disabled:",r.hasAttribute("disabled")),this.boundHandleSend&&r.removeEventListener("click",this.boundHandleSend),this.boundHandleSend=this.handleSendClick.bind(this),r.addEventListener("click",this.boundHandleSend),this.recipientPubkey&&!this.isLoading&&r.removeAttribute("disabled"),debug(this,"Send button event listener attached")):debug(this,"Send button not found in DOM");const s=this.shadowRoot.querySelector(".nostr-dm-textarea");s&&(this.boundHandleTextareaChange&&s.removeEventListener("input",this.boundHandleTextareaChange),this.boundHandleTextareaChange=this.handleTextareaChange.bind(this),s.addEventListener("input",this.boundHandleTextareaChange));const o=this.shadowRoot.querySelector(".nostr-dm-npub-input");o&&o.addEventListener("keydown",a=>{a.key==="Enter"&&this.handleFindClick()})}disconnectedCallback(){var o,a,u;const t=(o=this.shadowRoot)==null?void 0:o.querySelector(".nostr-dm-find-btn");t&&this.boundHandleFind&&t.removeEventListener("click",this.boundHandleFind);const r=(a=this.shadowRoot)==null?void 0:a.querySelector(".nostr-dm-send-btn");r&&this.boundHandleSend&&r.removeEventListener("click",this.boundHandleSend);const s=(u=this.shadowRoot)==null?void 0:u.querySelector(".nostr-dm-textarea");s&&this.boundHandleTextareaChange&&s.removeEventListener("input",this.boundHandleTextareaChange)}render(){debug(this,"Rendering with state:",{recipientNpub:this.recipientNpub,recipientPubkey:this.recipientPubkey,message:this.message?"[message content]":"[empty]",isLoading:this.isLoading,isFinding:this.isFinding,isError:this.isError,isSent:this.isSent});const t={theme:this.theme,recipientNpub:this.recipientNpub,recipientName:this.recipientName,recipientPicture:this.recipientPicture,message:this.message,isLoading:this.isLoading,isFinding:this.isFinding,isError:this.isError,errorMessage:this.errorMessage,isSent:this.isSent};this.shadowRoot.innerHTML=renderDm(t),this.attachEventListeners()}}customElements.define("nostr-dm",NostrDm);function formatTimestamp(n){try{return new Date(n*1e3).toLocaleString()}catch{return""}}function formatRelativeTime(n){try{const e=Date.now(),t=n*1e3,r=e-t,s=Math.floor(r/1e3);if(s<60)return"just now";if(s<3600){const a=Math.floor(s/60);return`${a} ${a===1?"min":"mins"} ago`}if(s<86400){const a=Math.floor(s/3600);return`${a} ${a===1?"hour":"hours"} ago`}if(s<2592e3){const a=Math.floor(s/86400);return`${a} ${a===1?"day":"days"} ago`}if(s<31536e3){const a=Math.floor(s/2592e3);return`${a} ${a===1?"month":"months"} ago`}const o=Math.floor(s/31536e3);return`${o} ${o===1?"year":"years"} ago`}catch{return""}}function safeSenderClass(n){return n==="me"||n==="them"?n:"them"}function sanitizeHtml(n){return n==null?"":String(n).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function renderLiveChatInner({theme:n,recipientNpub:e,recipientName:t,recipientPicture:r,message:s,messages:o,isLoading:a,isFinding:u,isError:c,errorMessage:l,currentUserName:h,currentUserPicture:f,showWelcome:p,welcomeText:b,startChatText:v,maxMessageLength:m}){const w=typeof m=="number"?m:1e3,x=(s||"").length,k=Math.max(0,w-x),C=k<=10?"nostr-chat-char-counter warn":"nostr-chat-char-counter";return`
3155
+ `}async function resolveNip05(n,e=5e3){var c;if(!/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(n))throw new Error("Invalid NIP-05 format");const[r,s]=n.split("@");if(!r||!s)throw new Error("Invalid NIP-05: missing name or domain");const o=`https://${s}/.well-known/nostr.json?name=${encodeURIComponent(r)}`,a=new AbortController,u=setTimeout(()=>a.abort(),e);try{const l=await fetch(o,{headers:{accept:"application/json"},signal:a.signal});if(!l.ok)throw new Error("Unable to resolve NIP-05");const f=(c=(await l.json()).names)==null?void 0:c[r];if(!f)throw new Error("NIP-05 not found");return f}catch(l){throw l instanceof Error&&l.name==="AbortError"?new Error("NIP-05 resolution timed out"):l}finally{clearTimeout(u)}}function debug(n,e,t){const r=process.env.NODE_ENV==="development",s=n.getAttribute("debug")==="true";(r||s)&&(t?console.log(`[NostrDm] ${e}`,t):console.log(`[NostrDm] ${e}`))}class NostrDm extends HTMLElement{constructor(){super();g(this,"rendered",!1);g(this,"nostrService",NostrService.getInstance());g(this,"theme","light");g(this,"recipientNpub",null);g(this,"recipientNip05",null);g(this,"recipientName",null);g(this,"recipientPicture",null);g(this,"recipientPubkey",null);g(this,"message","");g(this,"isLoading",!1);g(this,"isFinding",!1);g(this,"isError",!1);g(this,"errorMessage","");g(this,"isSent",!1);g(this,"boundHandleFind",null);g(this,"boundHandleSend",null);g(this,"boundHandleTextareaChange",null);g(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(","):DEFAULT_RELAYS});g(this,"getTheme",async()=>{this.theme="light";const t=this.getAttribute("theme");if(t){if(!["light","dark"].includes(t))throw new Error(`Invalid theme '${t}'. Accepted values are 'light', 'dark'`);this.theme=t}});g(this,"getRecipient",()=>{const t=this.getAttribute("nip05");if(t){this.recipientNip05=t,this.lookupRecipientByNip05();return}const r=this.getAttribute("recipient-npub");r&&(this.recipientNpub=r,this.lookupRecipient())});this.attachShadow({mode:"open"})}connectedCallback(){this.rendered||(this.rendered=!0,this.getTheme(),this.getRecipient(),this.nostrService.connectToNostr(this.getRelays()),this.render())}static get observedAttributes(){return["relays","recipient-npub","nip05","theme","debug"]}attributeChangedCallback(t,r,s){t==="relays"&&this.nostrService.connectToNostr(this.getRelays()),t==="theme"&&this.getTheme(),t==="nip05"&&s&&(this.recipientNip05=s,this.lookupRecipientByNip05()),t==="recipient-npub"&&s&&(this.recipientNpub=s,this.lookupRecipient()),this.render()}async lookupRecipient(t){const r=t||this.recipientNpub;if(r){this.isFinding=!0,this.render();try{const o=this.nostrService.getNDK().getUser({npub:r});await o.fetchProfile(),o.profile?(this.recipientName=o.profile.displayName||o.profile.name||"Unknown",this.recipientPicture=o.profile.image||null,this.recipientPubkey=o.pubkey,this.recipientNpub=r):(this.recipientName="Unknown",this.recipientPicture=null,this.recipientPubkey=o.pubkey,this.recipientNpub=r)}catch(s){this.isError=!0,this.errorMessage=`Failed to find recipient: ${s.message}`}finally{this.isFinding=!1,this.render()}}}async lookupRecipientByNip05(t){const r=t||this.recipientNip05;if(r){this.isFinding=!0,this.render();try{const s=await resolveNip05(r);if(!s)throw new Error("Failed to resolve nip05");const o=nip19_exports.npubEncode(s);await this.lookupRecipient(o)}catch(s){this.isError=!0,this.errorMessage=`Failed to resolve nip05: ${s.message}`}finally{this.isFinding=!1,this.render()}}}async handleFindClick(){const t=this.shadowRoot.querySelector(".nostr-dm-npub-input");if(!t||!t.value){this.isError=!0,this.errorMessage="Please enter a valid npub",this.render();return}const r=t.value.trim();r.includes("@")?await this.lookupRecipientByNip05(r):await this.lookupRecipient(r)}async handleSendClick(){if(debug(this,"Send button clicked!"),!this.recipientPubkey||!this.message.trim()){this.isError=!0,this.errorMessage=this.recipientPubkey?"Please enter a message":"Recipient not found",this.render();return}if(this.isError=!1,this.isSent=!1,this.isLoading=!0,this.render(),!this.nostrService.hasSigner()){this.isError=!0,this.errorMessage="No Nostr signer available. Please ensure your Nostr extension is installed or provide a private key.",this.isLoading=!1,this.render();return}let t=null;if(typeof window<"u"&&window.nostr)t=new NDKNip07Signer;else if(typeof localStorage<"u"){const r=localStorage.getItem("nostr_nsec");if(r){const{NDKPrivateKeySigner:s}=await Promise.resolve().then(()=>index$1);t=new s(r)}}if(!t){this.isError=!0,this.errorMessage="Failed to create signer. Please ensure your Nostr signer (extension or private key) is configured.",this.render();return}this.render();try{const r=this.nostrService.getNDK();r.signer=t;const{nip04:s}=await Promise.resolve().then(()=>index$2),o=new NDKEvent(r,{kind:NDKKind.EncryptedDirectMessage,tags:[["p",this.recipientPubkey]],created_at:Math.floor(Date.now()/1e3)});if(typeof window<"u"&&window.nostr){const u=await window.nostr.nip04.encrypt(this.recipientPubkey,this.message.trim());o.content=u}else if(typeof localStorage<"u"){const u=localStorage.getItem("nostr_nsec");if(!u)throw new Error("No private key available");const{nip19:c}=await Promise.resolve().then(()=>index$2);let l=u;if(u.startsWith("nsec"))try{l=c.decode(u).data}catch(h){throw console.error("Failed to decode nsec:",h),new Error("Invalid private key format")}try{o.content=await s.encrypt(l,this.recipientPubkey,this.message.trim())}catch(h){throw console.error("Encryption error:",h),new Error(`Encryption failed: ${h.message}`)}}debug(this,"Sending encrypted DM:",{to:this.recipientPubkey,encryptedContent:o.content}),await o.publish(),debug(this,"DM sent with encrypted content:",o),this.isSent=!0,this.message="";const a=this.shadowRoot.querySelector(".nostr-dm-textarea");a&&(a.value="")}catch(r){this.isError=!0,this.errorMessage=`Failed to send message: ${r.message}`,this.isSent=!1}finally{this.isLoading=!1,this.isFinding=!1,this.render()}}handleTextareaChange(t){const r=t.target;this.message=r.value}attachEventListeners(){const t=this.shadowRoot.querySelector(".nostr-dm-find-btn");t?(this.boundHandleFind&&t.removeEventListener("click",this.boundHandleFind),this.boundHandleFind=this.handleFindClick.bind(this),t.addEventListener("click",this.boundHandleFind),debug(this,"Find button event listener attached")):debug(this,"Find button not found in DOM");const r=this.shadowRoot.querySelector(".nostr-dm-send-btn");r?(debug(this,"Send button found, disabled:",r.hasAttribute("disabled")),this.boundHandleSend&&r.removeEventListener("click",this.boundHandleSend),this.boundHandleSend=this.handleSendClick.bind(this),r.addEventListener("click",this.boundHandleSend),this.recipientPubkey&&!this.isLoading&&r.removeAttribute("disabled"),debug(this,"Send button event listener attached")):debug(this,"Send button not found in DOM");const s=this.shadowRoot.querySelector(".nostr-dm-textarea");s&&(this.boundHandleTextareaChange&&s.removeEventListener("input",this.boundHandleTextareaChange),this.boundHandleTextareaChange=this.handleTextareaChange.bind(this),s.addEventListener("input",this.boundHandleTextareaChange));const o=this.shadowRoot.querySelector(".nostr-dm-npub-input");o&&o.addEventListener("keydown",a=>{a.key==="Enter"&&this.handleFindClick()})}disconnectedCallback(){var o,a,u;const t=(o=this.shadowRoot)==null?void 0:o.querySelector(".nostr-dm-find-btn");t&&this.boundHandleFind&&t.removeEventListener("click",this.boundHandleFind);const r=(a=this.shadowRoot)==null?void 0:a.querySelector(".nostr-dm-send-btn");r&&this.boundHandleSend&&r.removeEventListener("click",this.boundHandleSend);const s=(u=this.shadowRoot)==null?void 0:u.querySelector(".nostr-dm-textarea");s&&this.boundHandleTextareaChange&&s.removeEventListener("input",this.boundHandleTextareaChange)}render(){debug(this,"Rendering with state:",{recipientNpub:this.recipientNpub,recipientPubkey:this.recipientPubkey,message:this.message?"[message content]":"[empty]",isLoading:this.isLoading,isFinding:this.isFinding,isError:this.isError,isSent:this.isSent});const t={theme:this.theme,recipientNpub:this.recipientNpub,recipientName:this.recipientName,recipientPicture:this.recipientPicture,message:this.message,isLoading:this.isLoading,isFinding:this.isFinding,isError:this.isError,errorMessage:this.errorMessage,isSent:this.isSent};this.shadowRoot.innerHTML=renderDm(t),this.attachEventListeners()}}customElements.define("nostr-dm",NostrDm);function formatTimestamp(n){try{return new Date(n*1e3).toLocaleString()}catch{return""}}function formatRelativeTime(n){try{const e=Date.now(),t=n*1e3,r=e-t,s=Math.floor(r/1e3);if(s<60)return"just now";if(s<3600){const a=Math.floor(s/60);return`${a} ${a===1?"min":"mins"} ago`}if(s<86400){const a=Math.floor(s/3600);return`${a} ${a===1?"hour":"hours"} ago`}if(s<2592e3){const a=Math.floor(s/86400);return`${a} ${a===1?"day":"days"} ago`}if(s<31536e3){const a=Math.floor(s/2592e3);return`${a} ${a===1?"month":"months"} ago`}const o=Math.floor(s/31536e3);return`${o} ${o===1?"year":"years"} ago`}catch{return""}}function safeSenderClass(n){return n==="me"||n==="them"?n:"them"}function sanitizeHtml(n){return n==null?"":String(n).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function renderLiveChatInner({theme:n,recipientNpub:e,recipientName:t,recipientPicture:r,message:s,messages:o,isLoading:a,isFinding:u,isError:c,errorMessage:l,currentUserName:h,currentUserPicture:f,showWelcome:p,welcomeText:b,startChatText:v,maxMessageLength:m}){const w=typeof m=="number"?m:1e3,x=(s||"").length,k=Math.max(0,w-x),C=k<=10?"nostr-chat-char-counter warn":"nostr-chat-char-counter";return`
3156
3156
  <div class="nostr-chat-container ${c?"nostr-chat-error":""}">
3157
3157
  <div class="nostr-chat-header">
3158
3158
  <div class="nostr-chat-header-left">
@@ -3649,7 +3649,7 @@ Minimum version required to store current data is: `+o+`.
3649
3649
  text-align: center;
3650
3650
  }
3651
3651
  </style>
3652
- `}const le=class le extends HTMLElement{constructor(){super();g(this,"rendered",!1);g(this,"nostrService",NostrService.getInstance());g(this,"dmSubscription",null);g(this,"theme","light");g(this,"recipientNpub",null);g(this,"recipientNip05",null);g(this,"recipientName",null);g(this,"recipientPicture",null);g(this,"recipientPubkey",null);g(this,"message","");g(this,"messages",[]);g(this,"currentUserPubkey",null);g(this,"currentUserNpub",null);g(this,"currentUserName",null);g(this,"currentUserPicture",null);g(this,"displayType","embed");g(this,"isOpen",!1);g(this,"showWelcome",!1);g(this,"welcomeText",le.DEFAULT_WELCOME_TEXT);g(this,"startChatText",le.DEFAULT_START_CHAT_TEXT);g(this,"onlineText",le.DEFAULT_ONLINE_TEXT);g(this,"helpText",le.DEFAULT_HELP_TEXT);g(this,"MESSAGE_MAX_LENGTH",1e3);g(this,"isLoading",!1);g(this,"isFinding",!1);g(this,"isError",!1);g(this,"errorMessage","");g(this,"keySupplier",null);g(this,"boundHandleFind",null);g(this,"boundHandleSend",null);g(this,"boundHandleTextareaChange",null);g(this,"boundHandleLauncherClick",null);g(this,"boundHandleCloseClick",null);g(this,"boundHandleStartChat",null);g(this,"boundHandleNpubKeydown",null);g(this,"resubscribeTimer",null);g(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(",").map(r=>r.trim()).filter(r=>r.length>0).filter((r,s,o)=>o.indexOf(r)===s):DEFAULT_RELAYS});g(this,"getTheme",()=>{const t=this.getAttribute("theme"),r=(t||"").toLowerCase();r==="light"||r==="dark"?this.theme=r:(t&&console.warn(`Invalid theme '${t}'. Accepted values are 'light', 'dark'. Falling back to 'light'.`),this.theme="light")});g(this,"getRecipient",()=>{const t=this.getAttribute("pubkey");if(t)try{this.recipientPubkey=t,this.recipientNpub=nip19_exports.npubEncode(t),this.lookupRecipient(this.recipientNpub);return}catch(o){const a=`Invalid recipient pubkey "${t}": ${o instanceof Error?o.message:String(o)}`;this.isError=!0,this.errorMessage=a,console.error("nostr-live-chat:",a,o),this.render();return}const r=this.getAttribute("nip05");if(r){this.recipientNip05=r,this.lookupRecipientByNip05();return}const s=this.getAttribute("npub");s&&(this.recipientNpub=s,this.lookupRecipient())});this.attachShadow({mode:"open"})}async getCurrentUserInfo(){var t,r,s,o,a,u,c,l,h,f;try{const p=this.nostrService.getNDK();let b=null;if(typeof window<"u"&&window.nostr){const v=window.nostr;console.log("Nostr extension found, checking for public key...");try{const m=!!(v.enable&&typeof v.enable=="function"&&v.getPublicKey&&typeof v.getPublicKey=="function");if(console.log("Is this nos2x extension?",m),m){console.log("Using nos2x specific flow");try{await v.enable(),console.log("nos2x extension enabled"),await new Promise(w=>setTimeout(w,100));const y=await v.getPublicKey();console.log("nos2x returned pubkey:",y),y&&typeof y=="string"&&y.length===64&&(b=y,console.log("Successfully got pubkey from nos2x:",b))}catch(y){console.error("Error with nos2x extension:",y)}}else{if(typeof v.enable=="function"){console.log("Attempting to enable generic extension...");try{await v.enable(),console.log("Extension enabled successfully")}catch(y){console.warn("Extension enable failed, continuing anyway:",y)}}if(typeof v.getPublicKey=="function"){console.log("Calling getPublicKey()...");try{b=await v.getPublicKey(),console.log("Got pubkey from extension:",b)}catch(y){console.error("Error getting public key:",y)}}else if(v.getPublicKey){console.log("Found getPublicKey property, resolving...");try{b=await Promise.resolve(v.getPublicKey),console.log("Got pubkey from extension (property):",b)}catch(y){console.error("Error resolving public key:",y)}}}}catch(m){console.error("Error in extension interaction:",m)}}if(!b){let v=null;if(this.keySupplier)try{v=await this.keySupplier()}catch{}if(v)try{const{NDKPrivateKeySigner:m}=await Promise.resolve().then(()=>index);let y=v;v.startsWith("nsec")&&(y=nip19_exports.decode(v).data),b=(await new m(y).user()).pubkey}catch{}}if(b){this.currentUserPubkey=b,this.currentUserNpub=nip19_exports.npubEncode(b),console.log("Got pubkey from extension and will use it:",b);try{const v=p.getUser({pubkey:b});console.log("Fetching profile for user:",b),await v.fetchProfile(),console.log("Fetched profile:",v.profile),this.currentUserName=((t=v.profile)==null?void 0:t.displayName)||((r=v.profile)==null?void 0:r.name)||((s=this.currentUserNpub)==null?void 0:s.substring(0,10))||null,this.currentUserPicture=((o=v.profile)==null?void 0:o.image)||null,this.currentUserName||console.warn("No username found in profile"),this.currentUserPicture||console.warn("No profile picture found"),console.log("Profile info set:",{name:this.currentUserName,picture:this.currentUserPicture,npub:this.currentUserNpub})}catch(v){console.error("Error fetching profile:",v),this.currentUserName=((a=this.currentUserNpub)==null?void 0:a.substring(0,10))||null}this.render()}else{console.log("Checking for direct nos2x logs in console...");try{if(await new Promise(v=>setTimeout(v,500)),typeof window<"u"&&window.nostr){console.log("Trying direct call to extension again...");try{const v=await window.nostr.getPublicKey();if(v&&typeof v=="string"){console.log("Got pubkey on second try:",v),this.currentUserPubkey=v,this.currentUserNpub=nip19_exports.npubEncode(v);try{const m=p.getUser({pubkey:v});console.log("Fetching profile for user on second try:",v),await m.fetchProfile(),console.log("Fetched profile on second try:",m.profile),this.currentUserName=((u=m.profile)==null?void 0:u.displayName)||((c=m.profile)==null?void 0:c.name)||((l=this.currentUserNpub)==null?void 0:l.substring(0,10))||null,this.currentUserPicture=((h=m.profile)==null?void 0:h.image)||null,this.render();return}catch(m){console.error("Error fetching profile on second try:",m),this.currentUserName=((f=this.currentUserNpub)==null?void 0:f.substring(0,10))||null,this.render();return}}}catch(v){console.error("Error getting pubkey on direct second try:",v)}}}catch(v){console.error("Error in fallback pubkey detection:",v)}console.warn("No pubkey available from extension - trying fallback method")}}catch{}}getDisplayType(){const t=this.getAttribute("display-type"),r=["fab","bottom-bar","full","embed"],o=(t?String(t):"").toLowerCase(),a=r.includes(o)?o:"embed";this.displayType=a,this.displayType==="full"?this.isOpen=!0:this.displayType==="fab"||this.displayType==="bottom-bar"?(this.isOpen===void 0||this.isOpen===null)&&(this.isOpen=!1):this.isOpen=!1,this.getAttribute("display-type")!==a&&this.setAttribute("display-type",a)}connectedCallback(){if(!this.rendered){this.getTheme(),this.getDisplayType();const t=this.getAttribute("welcome-text");t&&(this.welcomeText=t);const r=this.getAttribute("start-chat-text");r&&(this.startChatText=r);const s=this.getAttribute("online-text");s&&(this.onlineText=s);const o=this.getAttribute("help-text");o&&(this.helpText=o),this.getRecipient(),this.nostrService.connectToNostr(this.getRelays()),this.getCurrentUserInfo(),this.render(),this.rendered=!0}}static get observedAttributes(){return["npub","pubkey","nip05","relays","theme","display-type","welcome-text","start-chat-text","online-text","help-text","history-days"]}unsubscribeFromDms(){if(this.dmSubscription){try{this.dmSubscription.stop()}catch{}this.dmSubscription=null}this.resubscribeTimer&&(clearTimeout(this.resubscribeTimer),this.resubscribeTimer=null)}clearRecipientAndChatState(){this.recipientPubkey=null,this.recipientNpub=null,this.recipientNip05=null,this.recipientName=null,this.recipientPicture=null,this.messages=[],this.message="",this.showWelcome=!1,this.isLoading=!1,this.isFinding=!1,this.isError=!1,this.errorMessage=""}attributeChangedCallback(t,r,s){if(this.rendered)if(t==="npub"){if(s===null){this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.render();return}s!==r&&(this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.recipientNpub=s,this.lookupRecipient());return}else if(t==="pubkey"){if(s===null){this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.render();return}if(s!==r){this.unsubscribeFromDms(),this.clearRecipientAndChatState();try{this.recipientPubkey=s,this.recipientNpub=nip19_exports.npubEncode(s),this.lookupRecipient(this.recipientNpub)}catch{}}return}else if(t==="nip05"){if(s===null){this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.render();return}s!==r&&(this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.recipientNip05=s,this.lookupRecipientByNip05());return}else if(t==="relays"){if(s!==r){const o=this.getRelays();this.recipientPubkey&&!this.showWelcome?(this.resubscribeTimer&&clearTimeout(this.resubscribeTimer),this.resubscribeTimer=window.setTimeout(()=>{this.unsubscribeFromDms(),this.nostrService.connectToNostr(o),this.subscribeToDms()},300)):this.nostrService.connectToNostr(o)}}else t==="theme"?(this.getTheme(),this.render()):t==="display-type"?(this.getDisplayType(),this.render()):t==="welcome-text"?(this.welcomeText=s!==null?s:le.DEFAULT_WELCOME_TEXT,this.render()):t==="start-chat-text"?(this.startChatText=s!==null?s:le.DEFAULT_START_CHAT_TEXT,this.render()):t==="online-text"?(this.onlineText=s!==null?s:le.DEFAULT_ONLINE_TEXT,this.render()):t==="help-text"?(this.helpText=s!==null?s:le.DEFAULT_HELP_TEXT,this.render()):t==="history-days"&&s!==r&&this.recipientPubkey&&!this.showWelcome&&(this.resubscribeTimer&&clearTimeout(this.resubscribeTimer),this.resubscribeTimer=window.setTimeout(()=>{this.subscribeToDms()},250))}async lookupRecipient(t){var r,s,o;this.unsubscribeFromDms(),this.messages=[],this.showWelcome=!1,this.isFinding=!0,this.render();try{const a=t||this.recipientNpub;if(!a)return;const{type:u,data:c}=nip19_exports.decode(a);if(u!=="npub")throw new Error("Invalid npub");this.recipientPubkey=c;const l=this.nostrService.getNDK().getUser({pubkey:this.recipientPubkey});await l.fetchProfile(),this.recipientName=((r=l.profile)==null?void 0:r.displayName)||((s=l.profile)==null?void 0:s.name)||a.substring(0,10),this.recipientPicture=((o=l.profile)==null?void 0:o.image)||null,this.showWelcome=!0,this.messages=[],this.isError=!1,this.errorMessage="",this.render()}catch(a){this.isError=!0,this.errorMessage=a.message}finally{this.isFinding=!1,this.render()}}async lookupRecipientByNip05(t){this.isFinding=!0,this.render();try{const r=t||this.recipientNip05;if(!r)return;const s=await resolveNip05(r),o=nip19_exports.npubEncode(s);this.recipientNpub=o,this.isError=!1,this.errorMessage="",await this.lookupRecipient(o)}catch(r){this.isError=!0,this.errorMessage=r.message}finally{this.isFinding=!1,this.render()}}handleFindClick(){const r=this.shadowRoot.querySelector(".nostr-chat-npub-input").value.trim();this.isError=!1,this.errorMessage="",this.render(),r&&(r.startsWith("npub")?(this.recipientNpub=r,this.lookupRecipient()):r.includes("@")?(this.recipientNip05=r,this.lookupRecipientByNip05()):(this.isError=!0,this.errorMessage="Invalid input. Please provide an npub or nip05 address.",this.render()))}async handleSendClick(){var r,s;if(!this.message.trim()||!this.recipientPubkey)return;if(this.message.length>this.MESSAGE_MAX_LENGTH){this.isError=!0,this.errorMessage=`Message is too long (max ${this.MESSAGE_MAX_LENGTH} characters).`,this.render();return}this.isLoading=!0,this.render();let t=null;try{const o=this.nostrService.getNDK();let a;if(typeof window<"u"&&window.nostr&&window.nostr.getPublicKey&&window.nostr.signEvent)try{a=new NDKNip07Signer}catch(h){console.error("Error creating NIP-07 signer:",h),this.isError=!0,this.errorMessage=`Error connecting to Nostr extension: ${h.message}`,this.isLoading=!1,this.render();return}if(!a)throw new Error("No signer available. Please install a NIP-07 extension or set a private key.");o.signer=a;const u=new NDKEvent(o,{kind:NDKKind.EncryptedDirectMessage,tags:[["p",this.recipientPubkey]],created_at:Math.floor(Date.now()/1e3)});let c=!1;if(typeof((s=(r=window.nostr)==null?void 0:r.nip04)==null?void 0:s.encrypt)=="function")try{u.content=await window.nostr.nip04.encrypt(this.recipientPubkey,this.message.trim()),c=!0}catch(h){console.error("NIP-07 encryption failed, falling back to local encryption:",h)}if(!c)throw new Error("No private key available for encryption. Please use a NIP-07 extension.");t=`temp_${Date.now()}`,this.messages.push({id:t,text:this.message,sender:"me",timestamp:u.created_at,status:"sending"}),this.message="",this.render(),await u.publish();const l=this.messages.find(h=>h.id===t);l&&(this.messages.find(f=>f.id===u.id&&f.id!==t)?this.messages=this.messages.filter(f=>f.id!==t):(l.id=u.id,l.status="sent"),this.render())}catch(o){if(this.isError=!0,this.errorMessage=o.message,t){const a=this.messages.find(u=>u.id===t);a&&(a.status="failed"),this.render()}}finally{this.isLoading=!1,this.render()}}handleTextareaChange(t){var a;const r=t.target;this.message=r.value;const s=Math.max(0,this.MESSAGE_MAX_LENGTH-this.message.length),o=(a=this.shadowRoot)==null?void 0:a.querySelector(".nostr-chat-char-counter");o&&(o.textContent=`${s} chars left`,o.classList.toggle("warn",s<=10))}handleStartChat(){this.showWelcome=!1,this.subscribeToDms(),this.render()}async subscribeToDms(){if(this.dmSubscription&&this.dmSubscription.stop(),!this.recipientPubkey)return;let t=null;try{if(typeof window<"u"&&window.nostr&&window.nostr.getPublicKey)t={pubkey:await window.nostr.getPublicKey()};else{let l=null;if(this.keySupplier)try{l=await this.keySupplier()}catch{}if(l){const{NDKPrivateKeySigner:h}=await Promise.resolve().then(()=>index);let f=l;l.startsWith("nsec")&&(f=nip19_exports.decode(l).data),t=await new h(f).user()}}}catch(l){console.error("Failed to determine current user for subscription",l)}if(!t){this.isError=!0,this.errorMessage="No signer available. Please install a NIP-07 extension or set a private key to start the chat.",this.render();return}this.messages=[];const r=this.getAttribute("history-days");let s;if(!r)s=void 0;else if(r.toLowerCase()==="all"||parseInt(r,10)<=0)s=void 0;else{const l=Math.max(1,parseInt(r,10)||30);s=Math.floor((Date.now()-l*24*60*60*1e3)/1e3)}const o={kinds:[NDKKind.EncryptedDirectMessage],"#p":[t.pubkey],authors:[this.recipientPubkey]},a={kinds:[NDKKind.EncryptedDirectMessage],"#p":[this.recipientPubkey],authors:[t.pubkey]},u=s!==void 0?{...o,since:s}:o,c=s!==void 0?{...a,since:s}:a;this.dmSubscription=this.nostrService.getNDK().subscribe([u,c],{closeOnEose:!1,groupable:!1}),this.dmSubscription.on("event",async l=>{var h;try{!this.currentUserPubkey&&t&&(this.currentUserPubkey=t.pubkey,this.currentUserNpub=nip19_exports.npubEncode(t.pubkey));const f=l.pubkey===t.pubkey,p=f?(h=l.tags.find(y=>y[0]==="p"))==null?void 0:h[1]:l.pubkey;if(!p){try{console.debug("nostr-live-chat: skipping event with missing peer",l.id)}catch{}return}if(p!==this.recipientPubkey)return;if(f){const y=this.messages.find(w=>w.id===l.id);if(y){y.status==="sending"&&(y.status="sent",this.render());return}}let b="";if(!p){try{console.debug("nostr-live-chat: missing peer prior to decrypt, skipping",l.id)}catch{}return}if(!l.content||l.content.trim()===""){try{console.debug("nostr-live-chat: missing or empty content prior to decrypt, skipping",l.id)}catch{}return}if(window.nostr&&window.nostr.nip04&&typeof window.nostr.nip04.decrypt=="function")try{b=await window.nostr.nip04.decrypt(p,l.content)}catch(y){console.error("Failed to decrypt DM content:",y);return}else throw new Error("No private key available for decryption. Please use a NIP-07 extension.");if(f){const y=this.messages.find(w=>w.status==="sending"&&w.sender==="me"&&w.text===b&&Math.abs(w.timestamp-l.created_at)<2);if(y){y.id=l.id,y.status="sent",this.render();return}}const v={id:l.id,text:b,sender:f?"me":"them",timestamp:l.created_at,status:"sent"};this.messages.find(y=>y.id===v.id)||(this.messages.push(v),this.messages.sort((y,w)=>y.timestamp-w.timestamp),this.render())}catch(f){console.error("Failed to decrypt DM content:",f)}})}attachEventListeners(){const t=this.shadowRoot.querySelector(".nostr-chat-launcher");t&&(this.boundHandleLauncherClick&&t.removeEventListener("click",this.boundHandleLauncherClick),this.boundHandleLauncherClick=()=>{this.isOpen=!0,this.render()},t.addEventListener("click",this.boundHandleLauncherClick));const r=this.shadowRoot.querySelector(".nostr-chat-close-btn");r&&(this.boundHandleCloseClick&&r.removeEventListener("click",this.boundHandleCloseClick),this.boundHandleCloseClick=l=>{l==null||l.stopPropagation(),(this.displayType==="fab"||this.displayType==="bottom-bar")&&(this.isOpen=!1),this.render()},r.addEventListener("click",this.boundHandleCloseClick));const s=this.shadowRoot.querySelector(".nostr-chat-find-btn");s&&(this.boundHandleFind&&s.removeEventListener("click",this.boundHandleFind),this.boundHandleFind=this.handleFindClick.bind(this),s.addEventListener("click",this.boundHandleFind));const o=this.shadowRoot.querySelector(".nostr-chat-send-btn");o&&(this.boundHandleSend&&o.removeEventListener("click",this.boundHandleSend),this.boundHandleSend=this.handleSendClick.bind(this),o.addEventListener("click",this.boundHandleSend));const a=this.shadowRoot.querySelector(".nostr-chat-start-btn");a&&(this.boundHandleStartChat&&a.removeEventListener("click",this.boundHandleStartChat),this.boundHandleStartChat=this.handleStartChat.bind(this),a.addEventListener("click",this.boundHandleStartChat));const u=this.shadowRoot.querySelector(".nostr-chat-textarea");u&&(this.boundHandleTextareaChange&&u.removeEventListener("input",this.boundHandleTextareaChange),this.boundHandleTextareaChange=this.handleTextareaChange.bind(this),u.addEventListener("input",this.boundHandleTextareaChange));const c=this.shadowRoot.querySelector(".nostr-chat-npub-input");c&&(this.boundHandleNpubKeydown&&c.removeEventListener("keydown",this.boundHandleNpubKeydown),this.boundHandleNpubKeydown=l=>{l.key==="Enter"&&this.handleFindClick()},c.addEventListener("keydown",this.boundHandleNpubKeydown))}disconnectedCallback(){var l,h,f,p,b,v,m;this.dmSubscription&&this.dmSubscription.stop();const t=(l=this.shadowRoot)==null?void 0:l.querySelector(".nostr-chat-launcher");t&&this.boundHandleLauncherClick&&t.removeEventListener("click",this.boundHandleLauncherClick);const r=(h=this.shadowRoot)==null?void 0:h.querySelector(".nostr-chat-close-btn");r&&this.boundHandleCloseClick&&r.removeEventListener("click",this.boundHandleCloseClick);const s=(f=this.shadowRoot)==null?void 0:f.querySelector(".nostr-chat-find-btn");s&&this.boundHandleFind&&s.removeEventListener("click",this.boundHandleFind);const o=(p=this.shadowRoot)==null?void 0:p.querySelector(".nostr-chat-send-btn");o&&this.boundHandleSend&&o.removeEventListener("click",this.boundHandleSend);const a=(b=this.shadowRoot)==null?void 0:b.querySelector(".nostr-chat-start-btn");a&&this.boundHandleStartChat&&a.removeEventListener("click",this.boundHandleStartChat);const u=(v=this.shadowRoot)==null?void 0:v.querySelector(".nostr-chat-textarea");u&&this.boundHandleTextareaChange&&u.removeEventListener("input",this.boundHandleTextareaChange);const c=(m=this.shadowRoot)==null?void 0:m.querySelector(".nostr-chat-npub-input");c&&this.boundHandleNpubKeydown&&c.removeEventListener("keydown",this.boundHandleNpubKeydown),this.resubscribeTimer&&(clearTimeout(this.resubscribeTimer),this.resubscribeTimer=null)}setKeySupplier(t){this.keySupplier=t}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}render(){const t={theme:this.theme,recipientNpub:this.recipientNpub,recipientName:this.recipientName,recipientPicture:this.recipientPicture,message:this.message,messages:this.messages,isLoading:this.isLoading,isFinding:this.isFinding,isError:this.isError,errorMessage:this.errorMessage,currentUserName:this.currentUserName,currentUserPicture:this.currentUserPicture,showWelcome:this.showWelcome,welcomeText:this.welcomeText,startChatText:this.startChatText,onlineText:this.onlineText,helpText:this.helpText,maxMessageLength:this.MESSAGE_MAX_LENGTH},r=getLiveChatStyles(this.theme),{onlineText:s,helpText:o,...a}=t,u=renderLiveChatInner(a);let c=r;this.displayType==="embed"?c+=u:this.displayType==="full"?c+=`
3652
+ `}const le=class le extends HTMLElement{constructor(){super();g(this,"rendered",!1);g(this,"nostrService",NostrService.getInstance());g(this,"dmSubscription",null);g(this,"theme","light");g(this,"recipientNpub",null);g(this,"recipientNip05",null);g(this,"recipientName",null);g(this,"recipientPicture",null);g(this,"recipientPubkey",null);g(this,"message","");g(this,"messages",[]);g(this,"currentUserPubkey",null);g(this,"currentUserNpub",null);g(this,"currentUserName",null);g(this,"currentUserPicture",null);g(this,"displayType","embed");g(this,"isOpen",!1);g(this,"showWelcome",!1);g(this,"welcomeText",le.DEFAULT_WELCOME_TEXT);g(this,"startChatText",le.DEFAULT_START_CHAT_TEXT);g(this,"onlineText",le.DEFAULT_ONLINE_TEXT);g(this,"helpText",le.DEFAULT_HELP_TEXT);g(this,"MESSAGE_MAX_LENGTH",1e3);g(this,"isLoading",!1);g(this,"isFinding",!1);g(this,"isError",!1);g(this,"errorMessage","");g(this,"keySupplier",null);g(this,"boundHandleFind",null);g(this,"boundHandleSend",null);g(this,"boundHandleTextareaChange",null);g(this,"boundHandleLauncherClick",null);g(this,"boundHandleCloseClick",null);g(this,"boundHandleStartChat",null);g(this,"boundHandleNpubKeydown",null);g(this,"resubscribeTimer",null);g(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(",").map(r=>r.trim()).filter(r=>r.length>0).filter((r,s,o)=>o.indexOf(r)===s):DEFAULT_RELAYS});g(this,"getTheme",()=>{const t=this.getAttribute("theme"),r=(t||"").toLowerCase();r==="light"||r==="dark"?this.theme=r:(t&&console.warn(`Invalid theme '${t}'. Accepted values are 'light', 'dark'. Falling back to 'light'.`),this.theme="light")});g(this,"getRecipient",()=>{const t=this.getAttribute("pubkey");if(t)try{this.recipientPubkey=t,this.recipientNpub=nip19_exports.npubEncode(t),this.lookupRecipient(this.recipientNpub);return}catch(o){const a=`Invalid recipient pubkey "${t}": ${o instanceof Error?o.message:String(o)}`;this.isError=!0,this.errorMessage=a,console.error("nostr-live-chat:",a,o),this.render();return}const r=this.getAttribute("nip05");if(r){this.recipientNip05=r,this.lookupRecipientByNip05();return}const s=this.getAttribute("npub");s&&(this.recipientNpub=s,this.lookupRecipient())});this.attachShadow({mode:"open"})}async getCurrentUserInfo(){var t,r,s,o,a,u,c,l,h,f;try{const p=this.nostrService.getNDK();let b=null;if(typeof window<"u"&&window.nostr){const v=window.nostr;console.log("Nostr extension found, checking for public key...");try{const m=!!(v.enable&&typeof v.enable=="function"&&v.getPublicKey&&typeof v.getPublicKey=="function");if(console.log("Is this nos2x extension?",m),m){console.log("Using nos2x specific flow");try{await v.enable(),console.log("nos2x extension enabled"),await new Promise(w=>setTimeout(w,100));const y=await v.getPublicKey();console.log("nos2x returned pubkey:",y),y&&typeof y=="string"&&y.length===64&&(b=y,console.log("Successfully got pubkey from nos2x:",b))}catch(y){console.error("Error with nos2x extension:",y)}}else{if(typeof v.enable=="function"){console.log("Attempting to enable generic extension...");try{await v.enable(),console.log("Extension enabled successfully")}catch(y){console.warn("Extension enable failed, continuing anyway:",y)}}if(typeof v.getPublicKey=="function"){console.log("Calling getPublicKey()...");try{b=await v.getPublicKey(),console.log("Got pubkey from extension:",b)}catch(y){console.error("Error getting public key:",y)}}else if(v.getPublicKey){console.log("Found getPublicKey property, resolving...");try{b=await Promise.resolve(v.getPublicKey),console.log("Got pubkey from extension (property):",b)}catch(y){console.error("Error resolving public key:",y)}}}}catch(m){console.error("Error in extension interaction:",m)}}if(!b){let v=null;if(this.keySupplier)try{v=await this.keySupplier()}catch{}if(v)try{const{NDKPrivateKeySigner:m}=await Promise.resolve().then(()=>index$1);let y=v;v.startsWith("nsec")&&(y=nip19_exports.decode(v).data),b=(await new m(y).user()).pubkey}catch{}}if(b){this.currentUserPubkey=b,this.currentUserNpub=nip19_exports.npubEncode(b),console.log("Got pubkey from extension and will use it:",b);try{const v=p.getUser({pubkey:b});console.log("Fetching profile for user:",b),await v.fetchProfile(),console.log("Fetched profile:",v.profile),this.currentUserName=((t=v.profile)==null?void 0:t.displayName)||((r=v.profile)==null?void 0:r.name)||((s=this.currentUserNpub)==null?void 0:s.substring(0,10))||null,this.currentUserPicture=((o=v.profile)==null?void 0:o.image)||null,this.currentUserName||console.warn("No username found in profile"),this.currentUserPicture||console.warn("No profile picture found"),console.log("Profile info set:",{name:this.currentUserName,picture:this.currentUserPicture,npub:this.currentUserNpub})}catch(v){console.error("Error fetching profile:",v),this.currentUserName=((a=this.currentUserNpub)==null?void 0:a.substring(0,10))||null}this.render()}else{console.log("Checking for direct nos2x logs in console...");try{if(await new Promise(v=>setTimeout(v,500)),typeof window<"u"&&window.nostr){console.log("Trying direct call to extension again...");try{const v=await window.nostr.getPublicKey();if(v&&typeof v=="string"){console.log("Got pubkey on second try:",v),this.currentUserPubkey=v,this.currentUserNpub=nip19_exports.npubEncode(v);try{const m=p.getUser({pubkey:v});console.log("Fetching profile for user on second try:",v),await m.fetchProfile(),console.log("Fetched profile on second try:",m.profile),this.currentUserName=((u=m.profile)==null?void 0:u.displayName)||((c=m.profile)==null?void 0:c.name)||((l=this.currentUserNpub)==null?void 0:l.substring(0,10))||null,this.currentUserPicture=((h=m.profile)==null?void 0:h.image)||null,this.render();return}catch(m){console.error("Error fetching profile on second try:",m),this.currentUserName=((f=this.currentUserNpub)==null?void 0:f.substring(0,10))||null,this.render();return}}}catch(v){console.error("Error getting pubkey on direct second try:",v)}}}catch(v){console.error("Error in fallback pubkey detection:",v)}console.warn("No pubkey available from extension - trying fallback method")}}catch{}}getDisplayType(){const t=this.getAttribute("display-type"),r=["fab","bottom-bar","full","embed"],o=(t?String(t):"").toLowerCase(),a=r.includes(o)?o:"embed";this.displayType=a,this.displayType==="full"?this.isOpen=!0:this.displayType==="fab"||this.displayType==="bottom-bar"?(this.isOpen===void 0||this.isOpen===null)&&(this.isOpen=!1):this.isOpen=!1,this.getAttribute("display-type")!==a&&this.setAttribute("display-type",a)}connectedCallback(){if(!this.rendered){this.getTheme(),this.getDisplayType();const t=this.getAttribute("welcome-text");t&&(this.welcomeText=t);const r=this.getAttribute("start-chat-text");r&&(this.startChatText=r);const s=this.getAttribute("online-text");s&&(this.onlineText=s);const o=this.getAttribute("help-text");o&&(this.helpText=o),this.getRecipient(),this.nostrService.connectToNostr(this.getRelays()),this.getCurrentUserInfo(),this.render(),this.rendered=!0}}static get observedAttributes(){return["npub","pubkey","nip05","relays","theme","display-type","welcome-text","start-chat-text","online-text","help-text","history-days"]}unsubscribeFromDms(){if(this.dmSubscription){try{this.dmSubscription.stop()}catch{}this.dmSubscription=null}this.resubscribeTimer&&(clearTimeout(this.resubscribeTimer),this.resubscribeTimer=null)}clearRecipientAndChatState(){this.recipientPubkey=null,this.recipientNpub=null,this.recipientNip05=null,this.recipientName=null,this.recipientPicture=null,this.messages=[],this.message="",this.showWelcome=!1,this.isLoading=!1,this.isFinding=!1,this.isError=!1,this.errorMessage=""}attributeChangedCallback(t,r,s){if(this.rendered)if(t==="npub"){if(s===null){this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.render();return}s!==r&&(this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.recipientNpub=s,this.lookupRecipient());return}else if(t==="pubkey"){if(s===null){this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.render();return}if(s!==r){this.unsubscribeFromDms(),this.clearRecipientAndChatState();try{this.recipientPubkey=s,this.recipientNpub=nip19_exports.npubEncode(s),this.lookupRecipient(this.recipientNpub)}catch{}}return}else if(t==="nip05"){if(s===null){this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.render();return}s!==r&&(this.unsubscribeFromDms(),this.clearRecipientAndChatState(),this.recipientNip05=s,this.lookupRecipientByNip05());return}else if(t==="relays"){if(s!==r){const o=this.getRelays();this.recipientPubkey&&!this.showWelcome?(this.resubscribeTimer&&clearTimeout(this.resubscribeTimer),this.resubscribeTimer=window.setTimeout(()=>{this.unsubscribeFromDms(),this.nostrService.connectToNostr(o),this.subscribeToDms()},300)):this.nostrService.connectToNostr(o)}}else t==="theme"?(this.getTheme(),this.render()):t==="display-type"?(this.getDisplayType(),this.render()):t==="welcome-text"?(this.welcomeText=s!==null?s:le.DEFAULT_WELCOME_TEXT,this.render()):t==="start-chat-text"?(this.startChatText=s!==null?s:le.DEFAULT_START_CHAT_TEXT,this.render()):t==="online-text"?(this.onlineText=s!==null?s:le.DEFAULT_ONLINE_TEXT,this.render()):t==="help-text"?(this.helpText=s!==null?s:le.DEFAULT_HELP_TEXT,this.render()):t==="history-days"&&s!==r&&this.recipientPubkey&&!this.showWelcome&&(this.resubscribeTimer&&clearTimeout(this.resubscribeTimer),this.resubscribeTimer=window.setTimeout(()=>{this.subscribeToDms()},250))}async lookupRecipient(t){var r,s,o;this.unsubscribeFromDms(),this.messages=[],this.showWelcome=!1,this.isFinding=!0,this.render();try{const a=t||this.recipientNpub;if(!a)return;const{type:u,data:c}=nip19_exports.decode(a);if(u!=="npub")throw new Error("Invalid npub");this.recipientPubkey=c;const l=this.nostrService.getNDK().getUser({pubkey:this.recipientPubkey});await l.fetchProfile(),this.recipientName=((r=l.profile)==null?void 0:r.displayName)||((s=l.profile)==null?void 0:s.name)||a.substring(0,10),this.recipientPicture=((o=l.profile)==null?void 0:o.image)||null,this.showWelcome=!0,this.messages=[],this.isError=!1,this.errorMessage="",this.render()}catch(a){this.isError=!0,this.errorMessage=a.message}finally{this.isFinding=!1,this.render()}}async lookupRecipientByNip05(t){this.isFinding=!0,this.render();try{const r=t||this.recipientNip05;if(!r)return;const s=await resolveNip05(r),o=nip19_exports.npubEncode(s);this.recipientNpub=o,this.isError=!1,this.errorMessage="",await this.lookupRecipient(o)}catch(r){this.isError=!0,this.errorMessage=r.message}finally{this.isFinding=!1,this.render()}}handleFindClick(){const r=this.shadowRoot.querySelector(".nostr-chat-npub-input").value.trim();this.isError=!1,this.errorMessage="",this.render(),r&&(r.startsWith("npub")?(this.recipientNpub=r,this.lookupRecipient()):r.includes("@")?(this.recipientNip05=r,this.lookupRecipientByNip05()):(this.isError=!0,this.errorMessage="Invalid input. Please provide an npub or nip05 address.",this.render()))}async handleSendClick(){var r,s;if(!this.message.trim()||!this.recipientPubkey)return;if(this.message.length>this.MESSAGE_MAX_LENGTH){this.isError=!0,this.errorMessage=`Message is too long (max ${this.MESSAGE_MAX_LENGTH} characters).`,this.render();return}this.isLoading=!0,this.render();let t=null;try{const o=this.nostrService.getNDK();let a;if(typeof window<"u"&&window.nostr&&window.nostr.getPublicKey&&window.nostr.signEvent)try{a=new NDKNip07Signer}catch(h){console.error("Error creating NIP-07 signer:",h),this.isError=!0,this.errorMessage=`Error connecting to Nostr extension: ${h.message}`,this.isLoading=!1,this.render();return}if(!a)throw new Error("No signer available. Please install a NIP-07 extension or set a private key.");o.signer=a;const u=new NDKEvent(o,{kind:NDKKind.EncryptedDirectMessage,tags:[["p",this.recipientPubkey]],created_at:Math.floor(Date.now()/1e3)});let c=!1;if(typeof((s=(r=window.nostr)==null?void 0:r.nip04)==null?void 0:s.encrypt)=="function")try{u.content=await window.nostr.nip04.encrypt(this.recipientPubkey,this.message.trim()),c=!0}catch(h){console.error("NIP-07 encryption failed, falling back to local encryption:",h)}if(!c)throw new Error("No private key available for encryption. Please use a NIP-07 extension.");t=`temp_${Date.now()}`,this.messages.push({id:t,text:this.message,sender:"me",timestamp:u.created_at,status:"sending"}),this.message="",this.render(),await u.publish();const l=this.messages.find(h=>h.id===t);l&&(this.messages.find(f=>f.id===u.id&&f.id!==t)?this.messages=this.messages.filter(f=>f.id!==t):(l.id=u.id,l.status="sent"),this.render())}catch(o){if(this.isError=!0,this.errorMessage=o.message,t){const a=this.messages.find(u=>u.id===t);a&&(a.status="failed"),this.render()}}finally{this.isLoading=!1,this.render()}}handleTextareaChange(t){var a;const r=t.target;this.message=r.value;const s=Math.max(0,this.MESSAGE_MAX_LENGTH-this.message.length),o=(a=this.shadowRoot)==null?void 0:a.querySelector(".nostr-chat-char-counter");o&&(o.textContent=`${s} chars left`,o.classList.toggle("warn",s<=10))}handleStartChat(){this.showWelcome=!1,this.subscribeToDms(),this.render()}async subscribeToDms(){if(this.dmSubscription&&this.dmSubscription.stop(),!this.recipientPubkey)return;let t=null;try{if(typeof window<"u"&&window.nostr&&window.nostr.getPublicKey)t={pubkey:await window.nostr.getPublicKey()};else{let l=null;if(this.keySupplier)try{l=await this.keySupplier()}catch{}if(l){const{NDKPrivateKeySigner:h}=await Promise.resolve().then(()=>index$1);let f=l;l.startsWith("nsec")&&(f=nip19_exports.decode(l).data),t=await new h(f).user()}}}catch(l){console.error("Failed to determine current user for subscription",l)}if(!t){this.isError=!0,this.errorMessage="No signer available. Please install a NIP-07 extension or set a private key to start the chat.",this.render();return}this.messages=[];const r=this.getAttribute("history-days");let s;if(!r)s=void 0;else if(r.toLowerCase()==="all"||parseInt(r,10)<=0)s=void 0;else{const l=Math.max(1,parseInt(r,10)||30);s=Math.floor((Date.now()-l*24*60*60*1e3)/1e3)}const o={kinds:[NDKKind.EncryptedDirectMessage],"#p":[t.pubkey],authors:[this.recipientPubkey]},a={kinds:[NDKKind.EncryptedDirectMessage],"#p":[this.recipientPubkey],authors:[t.pubkey]},u=s!==void 0?{...o,since:s}:o,c=s!==void 0?{...a,since:s}:a;this.dmSubscription=this.nostrService.getNDK().subscribe([u,c],{closeOnEose:!1,groupable:!1}),this.dmSubscription.on("event",async l=>{var h;try{!this.currentUserPubkey&&t&&(this.currentUserPubkey=t.pubkey,this.currentUserNpub=nip19_exports.npubEncode(t.pubkey));const f=l.pubkey===t.pubkey,p=f?(h=l.tags.find(y=>y[0]==="p"))==null?void 0:h[1]:l.pubkey;if(!p){try{console.debug("nostr-live-chat: skipping event with missing peer",l.id)}catch{}return}if(p!==this.recipientPubkey)return;if(f){const y=this.messages.find(w=>w.id===l.id);if(y){y.status==="sending"&&(y.status="sent",this.render());return}}let b="";if(!p){try{console.debug("nostr-live-chat: missing peer prior to decrypt, skipping",l.id)}catch{}return}if(!l.content||l.content.trim()===""){try{console.debug("nostr-live-chat: missing or empty content prior to decrypt, skipping",l.id)}catch{}return}if(window.nostr&&window.nostr.nip04&&typeof window.nostr.nip04.decrypt=="function")try{b=await window.nostr.nip04.decrypt(p,l.content)}catch(y){console.error("Failed to decrypt DM content:",y);return}else throw new Error("No private key available for decryption. Please use a NIP-07 extension.");if(f){const y=this.messages.find(w=>w.status==="sending"&&w.sender==="me"&&w.text===b&&Math.abs(w.timestamp-l.created_at)<2);if(y){y.id=l.id,y.status="sent",this.render();return}}const v={id:l.id,text:b,sender:f?"me":"them",timestamp:l.created_at,status:"sent"};this.messages.find(y=>y.id===v.id)||(this.messages.push(v),this.messages.sort((y,w)=>y.timestamp-w.timestamp),this.render())}catch(f){console.error("Failed to decrypt DM content:",f)}})}attachEventListeners(){const t=this.shadowRoot.querySelector(".nostr-chat-launcher");t&&(this.boundHandleLauncherClick&&t.removeEventListener("click",this.boundHandleLauncherClick),this.boundHandleLauncherClick=()=>{this.isOpen=!0,this.render()},t.addEventListener("click",this.boundHandleLauncherClick));const r=this.shadowRoot.querySelector(".nostr-chat-close-btn");r&&(this.boundHandleCloseClick&&r.removeEventListener("click",this.boundHandleCloseClick),this.boundHandleCloseClick=l=>{l==null||l.stopPropagation(),(this.displayType==="fab"||this.displayType==="bottom-bar")&&(this.isOpen=!1),this.render()},r.addEventListener("click",this.boundHandleCloseClick));const s=this.shadowRoot.querySelector(".nostr-chat-find-btn");s&&(this.boundHandleFind&&s.removeEventListener("click",this.boundHandleFind),this.boundHandleFind=this.handleFindClick.bind(this),s.addEventListener("click",this.boundHandleFind));const o=this.shadowRoot.querySelector(".nostr-chat-send-btn");o&&(this.boundHandleSend&&o.removeEventListener("click",this.boundHandleSend),this.boundHandleSend=this.handleSendClick.bind(this),o.addEventListener("click",this.boundHandleSend));const a=this.shadowRoot.querySelector(".nostr-chat-start-btn");a&&(this.boundHandleStartChat&&a.removeEventListener("click",this.boundHandleStartChat),this.boundHandleStartChat=this.handleStartChat.bind(this),a.addEventListener("click",this.boundHandleStartChat));const u=this.shadowRoot.querySelector(".nostr-chat-textarea");u&&(this.boundHandleTextareaChange&&u.removeEventListener("input",this.boundHandleTextareaChange),this.boundHandleTextareaChange=this.handleTextareaChange.bind(this),u.addEventListener("input",this.boundHandleTextareaChange));const c=this.shadowRoot.querySelector(".nostr-chat-npub-input");c&&(this.boundHandleNpubKeydown&&c.removeEventListener("keydown",this.boundHandleNpubKeydown),this.boundHandleNpubKeydown=l=>{l.key==="Enter"&&this.handleFindClick()},c.addEventListener("keydown",this.boundHandleNpubKeydown))}disconnectedCallback(){var l,h,f,p,b,v,m;this.dmSubscription&&this.dmSubscription.stop();const t=(l=this.shadowRoot)==null?void 0:l.querySelector(".nostr-chat-launcher");t&&this.boundHandleLauncherClick&&t.removeEventListener("click",this.boundHandleLauncherClick);const r=(h=this.shadowRoot)==null?void 0:h.querySelector(".nostr-chat-close-btn");r&&this.boundHandleCloseClick&&r.removeEventListener("click",this.boundHandleCloseClick);const s=(f=this.shadowRoot)==null?void 0:f.querySelector(".nostr-chat-find-btn");s&&this.boundHandleFind&&s.removeEventListener("click",this.boundHandleFind);const o=(p=this.shadowRoot)==null?void 0:p.querySelector(".nostr-chat-send-btn");o&&this.boundHandleSend&&o.removeEventListener("click",this.boundHandleSend);const a=(b=this.shadowRoot)==null?void 0:b.querySelector(".nostr-chat-start-btn");a&&this.boundHandleStartChat&&a.removeEventListener("click",this.boundHandleStartChat);const u=(v=this.shadowRoot)==null?void 0:v.querySelector(".nostr-chat-textarea");u&&this.boundHandleTextareaChange&&u.removeEventListener("input",this.boundHandleTextareaChange);const c=(m=this.shadowRoot)==null?void 0:m.querySelector(".nostr-chat-npub-input");c&&this.boundHandleNpubKeydown&&c.removeEventListener("keydown",this.boundHandleNpubKeydown),this.resubscribeTimer&&(clearTimeout(this.resubscribeTimer),this.resubscribeTimer=null)}setKeySupplier(t){this.keySupplier=t}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}render(){const t={theme:this.theme,recipientNpub:this.recipientNpub,recipientName:this.recipientName,recipientPicture:this.recipientPicture,message:this.message,messages:this.messages,isLoading:this.isLoading,isFinding:this.isFinding,isError:this.isError,errorMessage:this.errorMessage,currentUserName:this.currentUserName,currentUserPicture:this.currentUserPicture,showWelcome:this.showWelcome,welcomeText:this.welcomeText,startChatText:this.startChatText,onlineText:this.onlineText,helpText:this.helpText,maxMessageLength:this.MESSAGE_MAX_LENGTH},r=getLiveChatStyles(this.theme),{onlineText:s,helpText:o,...a}=t,u=renderLiveChatInner(a);let c=r;this.displayType==="embed"?c+=u:this.displayType==="full"?c+=`
3653
3653
  <div class="nostr-chat-float-panel open">${u}</div>
3654
3654
  `:this.displayType==="fab"?c+=`
3655
3655
  ${this.isOpen?"":`
@@ -3966,7 +3966,7 @@ Minimum version required to store current data is: `+o+`.
3966
3966
  `,e.showModal()};new TextDecoder("utf-8"),new TextEncoder;function normalizeURL(n){n.indexOf("://")===-1&&(n="wss://"+n);let e=new URL(n);return e.pathname=e.pathname.replace(/\/+/g,"/"),e.pathname.endsWith("/")&&(e.pathname=e.pathname.slice(0,-1)),(e.port==="80"&&e.protocol==="ws:"||e.port==="443"&&e.protocol==="wss:")&&(e.port=""),e.searchParams.sort(),e.hash="",e.toString()}async function fetchLikesForUrl(n,e){const t=normalizeURL(n),r=new SimplePool;try{const s=await r.querySync(e,{kinds:[17],"#k":["web"],"#i":[t],limit:1e3}),o=[];let a=0,u=0;for(const l of s)o.push({authorPubkey:l.pubkey,date:new Date(l.created_at*1e3),content:l.content}),l.content==="-"?u++:a++;return o.sort((l,h)=>h.date.getTime()-l.date.getTime()),{totalCount:a-u,likeDetails:o,likedCount:a,dislikedCount:u}}catch(s){throw s instanceof Error?s:new Error(String(s))}finally{r.close(e)}}function createReactionEvent(n,e){return{kind:17,content:e,tags:[["k","web"],["i",n]],created_at:Math.floor(Date.now()/1e3)}}function createLikeEvent(n){return createReactionEvent(n,"+")}function createUnlikeEvent(n){return createReactionEvent(n,"-")}async function hasUserLiked(n,e,t){const r=new SimplePool,s=n;try{const o=await r.querySync(t,{kinds:[17],authors:[e],"#k":["web"],"#i":[s],limit:1});if(o.length===0)return!1;const a=o[0];return a.content==="+"||a.content===""}catch(o){return console.error("Nostr-Components: Like button: Error checking user like status",o),!1}finally{r.close(t)}}async function getUserPubkey(){try{if(typeof window<"u"&&window.nostr)return await window.nostr.getPublicKey()}catch(n){console.error("Nostr-Components: Like button: Error getting user pubkey",n)}return null}async function signEvent(n){try{if(typeof window<"u"&&window.nostr)return await window.nostr.signEvent(n);throw new Error("NIP-07 extension not available")}catch(e){throw console.error("Nostr-Components: Like button: Error signing event",e),e}}function isNip07Available(){return typeof window<"u"&&!!window.nostr}class NostrLike extends NostrBaseComponent{constructor(){super();g(this,"likeActionStatus",this.channel("likeAction"));g(this,"likeListStatus",this.channel("likeList"));g(this,"currentUrl","");g(this,"isLiked",!1);g(this,"likeCount",0);g(this,"cachedLikeDetails",null);g(this,"loadSeq",0)}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),this.likeListStatus.get()===NCStatus.Idle&&this.initChannelStatus("likeList",NCStatus.Loading,{reflectOverall:!1}),this.attachDelegatedListeners(),this.render()}static get observedAttributes(){return[...super.observedAttributes,"url","text"]}attributeChangedCallback(t,r,s){r!==s&&(super.attributeChangedCallback(t,r,s),(t==="url"||t==="text")&&(this.likeActionStatus.set(NCStatus.Ready),this.likeListStatus.set(NCStatus.Loading),this.isLiked=!1,this.errorMessage="",this.updateLikeCount(),this.render()))}validateInputs(){if(!super.validateInputs())return this.likeActionStatus.set(NCStatus.Idle),this.likeListStatus.set(NCStatus.Idle),!1;const t=this.getAttribute("url"),r=this.getAttribute("text"),s=this.tagName.toLowerCase();let o=null;return t&&(isValidUrl(t)||(o="Invalid URL format")),r&&r.length>32&&(o="Max text length: 32 characters"),o?(this.likeActionStatus.set(NCStatus.Error,o),this.likeListStatus.set(NCStatus.Error,o),console.error(`Nostr-Components: ${s}: ${o}`),!1):!0}onStatusChange(t){this.render()}onNostrRelaysConnected(){this.updateLikeCount(),this.render()}ensureCurrentUrl(){this.currentUrl||(this.currentUrl=normalizeURL(this.getAttribute("url")||window.location.href))}async updateLikeCount(){const t=++this.loadSeq;try{await this.ensureNostrConnected(),this.currentUrl=normalizeURL(this.getAttribute("url")||window.location.href),this.likeListStatus.set(NCStatus.Loading),this.render();const r=await fetchLikesForUrl(this.currentUrl,this.getRelays());if(t!==this.loadSeq)return;this.likeCount=r.totalCount,this.cachedLikeDetails=r,this.likeListStatus.set(NCStatus.Ready)}catch(r){console.error("[NostrLike] Failed to fetch like count:",r),this.likeListStatus.set(NCStatus.Error,"Failed to load likes")}finally{this.render()}}async handleLikeClick(){if(this.ensureCurrentUrl(),!this.currentUrl){this.likeActionStatus.set(NCStatus.Error,"Invalid URL"),this.render();return}if(this.likeActionStatus.set(NCStatus.Loading),!isNip07Available()){this.likeActionStatus.set(NCStatus.Error,"Please install a Nostr browser extension (Alby, nos2x, etc.)"),this.render();return}try{const t=await getUserPubkey();t&&(this.isLiked=await hasUserLiked(this.currentUrl,t,this.getRelays()))}catch(t){console.error("[NostrLike] Failed to check user like status:",t),this.likeActionStatus.set(NCStatus.Error,"Failed to check user like status")}finally{this.render()}if(this.isLiked){if(!window.confirm("You have already liked this. Do you want to unlike it?")){this.likeActionStatus.set(NCStatus.Ready),this.render();return}await this.handleUnlike()}else await this.handleLike()}async handleLike(){if(this.ensureCurrentUrl(),!this.currentUrl){this.likeActionStatus.set(NCStatus.Error,"Invalid URL"),this.render();return}this.likeActionStatus.set(NCStatus.Loading),this.render();try{const t=createLikeEvent(this.currentUrl),r=await signEvent(t);await new NDKEvent(this.nostrService.getNDK(),r).publish(),this.isLiked=!0,this.likeCount++,this.likeActionStatus.set(NCStatus.Ready),await this.updateLikeCount()}catch(t){console.error("[NostrLike] Failed to like:",t),this.isLiked=!1,this.likeCount--;const r=t instanceof Error?t.message:"Failed to like";this.likeActionStatus.set(NCStatus.Error,r)}finally{this.render()}}async handleUnlike(){if(this.ensureCurrentUrl(),!this.currentUrl){this.likeActionStatus.set(NCStatus.Error,"Invalid URL"),this.render();return}this.likeActionStatus.set(NCStatus.Loading),this.render();try{const t=createUnlikeEvent(this.currentUrl),r=await signEvent(t);await new NDKEvent(this.nostrService.getNDK(),r).publish(),this.isLiked=!1,this.likeCount>0&&this.likeCount--,this.likeActionStatus.set(NCStatus.Ready),await this.updateLikeCount()}catch(t){console.error("[NostrLike] Failed to unlike:",t),this.isLiked=!0,this.likeCount++;const r=t instanceof Error?t.message:"Failed to unlike";this.likeActionStatus.set(NCStatus.Error,r)}finally{this.render()}}async handleCountClick(){if(!(this.likeCount===0||!this.cachedLikeDetails))try{const{openLikersDialog:t}=await Promise.resolve().then(()=>dialogLikers);await t({likeDetails:this.cachedLikeDetails.likeDetails,theme:this.theme==="dark"?"dark":"light"})}catch(t){console.error("[NostrLike] Error opening likers dialog:",t)}}async handleHelpClick(){try{await showHelpDialog(this.theme==="dark"?"dark":"light")}catch(t){console.error("[NostrLike] Error showing help dialog:",t)}}attachDelegatedListeners(){this.delegateEvent("click",".nostr-like-button",t=>{var r,s;(r=t.preventDefault)==null||r.call(t),(s=t.stopPropagation)==null||s.call(t),this.handleLikeClick()}),this.delegateEvent("click",".like-count",t=>{var r,s;(r=t.preventDefault)==null||r.call(t),(s=t.stopPropagation)==null||s.call(t),this.handleCountClick()}),this.delegateEvent("click",".help-icon",t=>{var r,s;(r=t.preventDefault)==null||r.call(t),(s=t.stopPropagation)==null||s.call(t),this.handleHelpClick()})}renderContent(){const t=this.likeActionStatus.get()===NCStatus.Loading||this.conn.get()===NCStatus.Loading,r=this.likeListStatus.get()===NCStatus.Loading,s=this.computeOverall()===NCStatus.Error,o=this.errorMessage,a=this.getAttribute("text")||"Like",u={isLoading:t,isError:s,errorMessage:o,buttonText:a,isLiked:this.isLiked,likeCount:this.likeCount,hasLikes:this.likeCount>0,isCountLoading:r,theme:this.theme};this.shadowRoot.innerHTML=`
3967
3967
  ${getLikeButtonStyles()}
3968
3968
  ${renderLikeButton(u)}
3969
- `}}customElements.define("nostr-like",NostrLike);function init(){typeof window<"u"&&console.log("Nostr Components initialized")}var verifiedSymbol=Symbol("verified"),isRecord=n=>n instanceof Object;function validateEvent(n){if(!isRecord(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!n.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(n.tags))return!1;for(let e=0;e<n.tags.length;e++){let t=n.tags[e];if(!Array.isArray(t))return!1;for(let r=0;r<t.length;r++)if(typeof t[r]=="object")return!1}return!0}new TextDecoder("utf-8");var utf8Encoder=new TextEncoder,JS=class{generateSecretKey(){return schnorr$1.utils.randomPrivateKey()}getPublicKey(n){return bytesToHex$2(schnorr$1.getPublicKey(n))}finalizeEvent(n,e){const t=n;return t.pubkey=bytesToHex$2(schnorr$1.getPublicKey(e)),t.id=getEventHash(t),t.sig=bytesToHex$2(schnorr$1.sign(getEventHash(t),e)),t[verifiedSymbol]=!0,t}verifyEvent(n){if(typeof n[verifiedSymbol]=="boolean")return n[verifiedSymbol];const e=getEventHash(n);if(e!==n.id)return n[verifiedSymbol]=!1,!1;try{const t=schnorr$1.verify(n.sig,e,n.pubkey);return n[verifiedSymbol]=t,t}catch{return n[verifiedSymbol]=!1,!1}}};function serializeEvent(n){if(!validateEvent(n))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])}function getEventHash(n){let e=sha256$1(utf8Encoder.encode(serializeEvent(n)));return bytesToHex$2(e)}var i=new JS,generateSecretKey=i.generateSecretKey,getPublicKey=i.getPublicKey,finalizeEvent=i.finalizeEvent;i.verifyEvent;const pure=Object.freeze(Object.defineProperty({__proto__:null,finalizeEvent,generateSecretKey,getEventHash,getPublicKey,serializeEvent,validateEvent,verifiedSymbol},Symbol.toStringTag,{value:"Module"}));function getLikersDialogStyles(n="light"){const e=n==="dark";return`
3969
+ `}}customElements.define("nostr-like",NostrLike);function init(){typeof window<"u"&&console.log("Nostr Components initialized")}const index={init,NostrProfileBadge,NostrPost,NostrProfile,NostrFollowButton,NostrZap,NostrComment,NostrDm,NostrLiveChat,NostrLike};var verifiedSymbol=Symbol("verified"),isRecord=n=>n instanceof Object;function validateEvent(n){if(!isRecord(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!n.pubkey.match(/^[a-f0-9]{64}$/)||!Array.isArray(n.tags))return!1;for(let e=0;e<n.tags.length;e++){let t=n.tags[e];if(!Array.isArray(t))return!1;for(let r=0;r<t.length;r++)if(typeof t[r]=="object")return!1}return!0}new TextDecoder("utf-8");var utf8Encoder=new TextEncoder,JS=class{generateSecretKey(){return schnorr$1.utils.randomPrivateKey()}getPublicKey(n){return bytesToHex$2(schnorr$1.getPublicKey(n))}finalizeEvent(n,e){const t=n;return t.pubkey=bytesToHex$2(schnorr$1.getPublicKey(e)),t.id=getEventHash(t),t.sig=bytesToHex$2(schnorr$1.sign(getEventHash(t),e)),t[verifiedSymbol]=!0,t}verifyEvent(n){if(typeof n[verifiedSymbol]=="boolean")return n[verifiedSymbol];const e=getEventHash(n);if(e!==n.id)return n[verifiedSymbol]=!1,!1;try{const t=schnorr$1.verify(n.sig,e,n.pubkey);return n[verifiedSymbol]=t,t}catch{return n[verifiedSymbol]=!1,!1}}};function serializeEvent(n){if(!validateEvent(n))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,n.pubkey,n.created_at,n.kind,n.tags,n.content])}function getEventHash(n){let e=sha256$1(utf8Encoder.encode(serializeEvent(n)));return bytesToHex$2(e)}var i=new JS,generateSecretKey=i.generateSecretKey,getPublicKey=i.getPublicKey,finalizeEvent=i.finalizeEvent;i.verifyEvent;const pure=Object.freeze(Object.defineProperty({__proto__:null,finalizeEvent,generateSecretKey,getEventHash,getPublicKey,serializeEvent,validateEvent,verifiedSymbol},Symbol.toStringTag,{value:"Module"}));function getLikersDialogStyles(n="light"){const e=n==="dark";return`
3970
3970
  .likers-dialog-content {
3971
3971
  padding: 0;
3972
3972
  max-height: 60vh;
@@ -4201,5 +4201,5 @@ Minimum version required to store current data is: `+o+`.
4201
4201
  ${n.map((r,s)=>renderSkeletonLikeEntry(r,e[s],s)).join("")}
4202
4202
  </div>
4203
4203
  </div>
4204
- `}async function enhanceLikeDetailsProgressively(n,e){const t=n.querySelector(".likers-list");if(!t)return;const r=[...new Set(e.map(s=>s.authorPubkey))];console.log("Nostr-Components: Likers dialog: Fetching profiles for",r.length,"unique authors");try{const s=await getBatchedProfileMetadata(r),o=new Map;s.forEach(u=>{o.set(u.id,u.profile)});const a=new Map;r.forEach(u=>{a.set(u,hexToNpub(u))});for(let u=0;u<e.length;u++){const c=e[u],l=o.get(c.authorPubkey),h=a.get(c.authorPubkey)||c.authorPubkey;let f;if(l){const b=extractProfileMetadataContent(l);f={...c,authorName:b.display_name||b.name||h,authorPicture:b.picture,authorNpub:h}}else f={...c,authorName:h,authorNpub:h};const p=t.querySelector(`[data-like-index="${u}"]`);if(p){const b=renderLikeEntry(f,u);p.outerHTML=b}}console.log("Nostr-Components: Likers dialog: Progressive enhancement completed for",e.length,"like entries")}catch(s){console.error("Nostr-Components: Likers dialog: Error in batched profile enhancement",s),console.log("Nostr-Components: Likers dialog: Falling back to individual profile fetching"),await enhanceLikeDetailsIndividually(n,e)}}async function enhanceLikeDetailsIndividually(n,e){const t=n.querySelector(".likers-list");if(!t)return;const r=new Map,s=e.map(async(o,a)=>{if(r.has(o.authorPubkey)){const u=r.get(o.authorPubkey);return{index:a,enhanced:{...o,authorName:u.authorName,authorPicture:u.authorPicture,authorNpub:u.authorNpub}}}try{const{getProfileMetadata:u}=await Promise.resolve().then(()=>zapUtils),c=await u(o.authorPubkey),l=extractProfileMetadataContent(c),h=hexToNpub(o.authorPubkey),f={...o,authorName:l.display_name||l.name||h,authorPicture:l.picture,authorNpub:h};return r.set(o.authorPubkey,f),{index:a,enhanced:f}}catch(u){console.error("Nostr-Components: Likers dialog: Error fetching profile for",o.authorPubkey,u);const c=hexToNpub(o.authorPubkey),l={...o,authorName:c,authorNpub:c};return r.set(o.authorPubkey,l),{index:a,enhanced:l}}});for(const o of s)try{const{index:a,enhanced:u}=await o,c=t.querySelector(`[data-like-index="${a}"]`);if(c){const l=renderLikeEntry(u,a);c.outerHTML=l}}catch(a){console.error("Nostr-Components: Likers dialog: Error processing profile enhancement",a)}}const dialogLikers=Object.freeze(Object.defineProperty({__proto__:null,injectLikersDialogStyles,openLikersDialog},Symbol.toStringTag,{value:"Module"}));exports.NostrComment=NostrComment,exports.NostrDm=NostrDm,exports.NostrFollowButton=NostrFollowButton,exports.NostrLike=NostrLike,exports.NostrLiveChat=NostrLiveChat,exports.NostrPost=NostrPost,exports.NostrProfile=NostrProfile,exports.NostrProfileBadge=NostrProfileBadge,exports.NostrZap=NostrZap,exports.init=init,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
4204
+ `}async function enhanceLikeDetailsProgressively(n,e){const t=n.querySelector(".likers-list");if(!t)return;const r=[...new Set(e.map(s=>s.authorPubkey))];console.log("Nostr-Components: Likers dialog: Fetching profiles for",r.length,"unique authors");try{const s=await getBatchedProfileMetadata(r),o=new Map;s.forEach(u=>{o.set(u.id,u.profile)});const a=new Map;r.forEach(u=>{a.set(u,hexToNpub(u))});for(let u=0;u<e.length;u++){const c=e[u],l=o.get(c.authorPubkey),h=a.get(c.authorPubkey)||c.authorPubkey;let f;if(l){const b=extractProfileMetadataContent(l);f={...c,authorName:b.display_name||b.name||h,authorPicture:b.picture,authorNpub:h}}else f={...c,authorName:h,authorNpub:h};const p=t.querySelector(`[data-like-index="${u}"]`);if(p){const b=renderLikeEntry(f,u);p.outerHTML=b}}console.log("Nostr-Components: Likers dialog: Progressive enhancement completed for",e.length,"like entries")}catch(s){console.error("Nostr-Components: Likers dialog: Error in batched profile enhancement",s),console.log("Nostr-Components: Likers dialog: Falling back to individual profile fetching"),await enhanceLikeDetailsIndividually(n,e)}}async function enhanceLikeDetailsIndividually(n,e){const t=n.querySelector(".likers-list");if(!t)return;const r=new Map,s=e.map(async(o,a)=>{if(r.has(o.authorPubkey)){const u=r.get(o.authorPubkey);return{index:a,enhanced:{...o,authorName:u.authorName,authorPicture:u.authorPicture,authorNpub:u.authorNpub}}}try{const{getProfileMetadata:u}=await Promise.resolve().then(()=>zapUtils),c=await u(o.authorPubkey),l=extractProfileMetadataContent(c),h=hexToNpub(o.authorPubkey),f={...o,authorName:l.display_name||l.name||h,authorPicture:l.picture,authorNpub:h};return r.set(o.authorPubkey,f),{index:a,enhanced:f}}catch(u){console.error("Nostr-Components: Likers dialog: Error fetching profile for",o.authorPubkey,u);const c=hexToNpub(o.authorPubkey),l={...o,authorName:c,authorNpub:c};return r.set(o.authorPubkey,l),{index:a,enhanced:l}}});for(const o of s)try{const{index:a,enhanced:u}=await o,c=t.querySelector(`[data-like-index="${a}"]`);if(c){const l=renderLikeEntry(u,a);c.outerHTML=l}}catch(a){console.error("Nostr-Components: Likers dialog: Error processing profile enhancement",a)}}const dialogLikers=Object.freeze(Object.defineProperty({__proto__:null,injectLikersDialogStyles,openLikersDialog},Symbol.toStringTag,{value:"Module"}));exports.NostrComment=NostrComment,exports.NostrDm=NostrDm,exports.NostrFollowButton=NostrFollowButton,exports.NostrLike=NostrLike,exports.NostrLiveChat=NostrLiveChat,exports.NostrPost=NostrPost,exports.NostrProfile=NostrProfile,exports.NostrProfileBadge=NostrProfileBadge,exports.NostrZap=NostrZap,exports.default=index,exports.init=init,Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
4205
4205
  //# sourceMappingURL=nostr-components.umd.js.map