nostr-components 0.2.0 → 0.2.1

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.
@@ -1,4 +1,4 @@
1
- (function(oe,Q){typeof exports=="object"&&typeof module<"u"?Q(exports):typeof define=="function"&&define.amd?define(["exports"],Q):(oe=typeof globalThis<"u"?globalThis:oe||self,Q(oe.NostrComponents={}))})(this,function(exports){"use strict";var Ut=Object.defineProperty;var Ot=(oe,Q,he)=>Q in oe?Ut(oe,Q,{enumerable:!0,configurable:!0,writable:!0,value:he}):oe[Q]=he;var g=(oe,Q,he)=>Ot(oe,typeof Q!="symbol"?Q+"":Q,he);var oe,Q,he,Se,Te,_e,Le,we,Ce,Ae,me,$e,Re,Ne,je;var _documentCurrentScript=typeof document<"u"?document.currentScript:null,commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var lib$1={},types={};Object.defineProperty(types,"__esModule",{value:!0});var ee={},taskCollection$1={},taskCollection={},utils$3={};Object.defineProperty(utils$3,"__esModule",{value:!0}),utils$3._fast_remove_single=void 0;function _fast_remove_single(n,e){e!==-1&&(e===0?n.shift():e===n.length-1?n.length=n.length-1:n.splice(e,1))}utils$3._fast_remove_single=_fast_remove_single;var bakeCollection={};(function(exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.bakeCollectionVariadic=exports.bakeCollectionAwait=exports.bakeCollection=exports.BAKED_EMPTY_FUNC=void 0,exports.BAKED_EMPTY_FUNC=function(){};var FORLOOP_FALLBACK=1500;function generateArgsDefCode(n){var e="";if(n===0)return e;for(var t=0;t<n-1;++t)e+="arg"+String(t)+", ";return e+="arg"+String(n-1),e}function generateBodyPartsCode(n,e){for(var t="",r="",s=0;s<e;++s)t+="var f".concat(s," = collection[").concat(s,`];
1
+ (function(oe,X){typeof exports=="object"&&typeof module<"u"?X(exports):typeof define=="function"&&define.amd?define(["exports"],X):(oe=typeof globalThis<"u"?globalThis:oe||self,X(oe.NostrComponents={}))})(this,function(exports){"use strict";var Ut=Object.defineProperty;var Ot=(oe,X,he)=>X in oe?Ut(oe,X,{enumerable:!0,configurable:!0,writable:!0,value:he}):oe[X]=he;var g=(oe,X,he)=>Ot(oe,typeof X!="symbol"?X+"":X,he);var oe,X,he,Ae,Se,Te,$e,we,Ce,_e,me,Ne,Re,Le,je;var _documentCurrentScript=typeof document<"u"?document.currentScript:null,commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var lib$1={},types={};Object.defineProperty(types,"__esModule",{value:!0});var ee={},taskCollection$1={},taskCollection={},utils$3={};Object.defineProperty(utils$3,"__esModule",{value:!0}),utils$3._fast_remove_single=void 0;function _fast_remove_single(n,e){e!==-1&&(e===0?n.shift():e===n.length-1?n.length=n.length-1:n.splice(e,1))}utils$3._fast_remove_single=_fast_remove_single;var bakeCollection={};(function(exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.bakeCollectionVariadic=exports.bakeCollectionAwait=exports.bakeCollection=exports.BAKED_EMPTY_FUNC=void 0,exports.BAKED_EMPTY_FUNC=function(){};var FORLOOP_FALLBACK=1500;function generateArgsDefCode(n){var e="";if(n===0)return e;for(var t=0;t<n-1;++t)e+="arg"+String(t)+", ";return e+="arg"+String(n-1),e}function generateBodyPartsCode(n,e){for(var t="",r="",s=0;s<e;++s)t+="var f".concat(s," = collection[").concat(s,`];
2
2
  `),r+="f".concat(s,"(").concat(n,`)
3
3
  `);return{funcDefCode:t,funcCallCode:r}}function generateBodyPartsVariadicCode(n){for(var e="",t="",r=0;r<n;++r)e+="var f".concat(r," = collection[").concat(r,`];
4
4
  `),t+="f".concat(r,`.apply(undefined, arguments)
@@ -72,9 +72,9 @@
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,$)=>{if(R==="%%")return"%";C++;const B=t.formatters[$];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:I}=m,R=t.eql(t.mul(y,I),t.mul(k,x)),$=t.eql(t.mul(w,I),t.mul(C,x));return R&&$}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 I=t.ZERO,R=t.ZERO,$=t.ZERO,B=t.mul(x,x),O=t.mul(k,k),H=t.mul(C,C),T=t.mul(x,k);return T=t.add(T,T),$=t.mul(x,C),$=t.add($,$),I=t.mul(m,$),R=t.mul(w,H),R=t.add(I,R),I=t.sub(O,R),R=t.add(O,R),R=t.mul(I,R),I=t.mul(T,I),$=t.mul(w,$),H=t.mul(m,H),T=t.sub(B,H),T=t.mul(m,T),T=t.add(T,$),$=t.add(B,B),B=t.add($,B),B=t.add(B,H),B=t.mul(B,T),R=t.add(R,B),H=t.mul(k,C),H=t.add(H,H),B=t.mul(H,T),I=t.sub(I,B),$=t.mul(H,O),$=t.add($,$),$=t.add($,$),new f(I,R,$)}add(m){h(m);const{px:y,py:w,pz:x}=this,{px:k,py:C,pz:I}=m;let R=t.ZERO,$=t.ZERO,B=t.ZERO;const O=e.a,H=t.mul(e.b,_3n$2);let T=t.mul(y,k),A=t.mul(w,C),N=t.mul(x,I),P=t.add(y,w),S=t.add(k,C);P=t.mul(P,S),S=t.add(T,A),P=t.sub(P,S),S=t.add(y,x);let E=t.add(k,I);return S=t.mul(S,E),E=t.add(T,N),S=t.sub(S,E),E=t.add(w,x),R=t.add(C,I),E=t.mul(E,R),R=t.add(A,N),E=t.sub(E,R),B=t.mul(O,S),R=t.mul(H,N),B=t.add(R,B),R=t.sub(A,B),B=t.add(A,B),$=t.mul(R,B),A=t.add(T,T),A=t.add(A,T),N=t.mul(O,N),S=t.mul(H,S),A=t.add(A,N),N=t.sub(T,N),N=t.mul(O,N),S=t.add(S,N),T=t.mul(A,S),$=t.add($,T),T=t.mul(E,S),R=t.mul(P,R),R=t.sub(R,T),T=t.mul(P,A),B=t.mul(E,B),B=t.add(B,T),new f(R,$,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:I}=w.splitScalar(m),R=y,$=y,B=this;for(;k>_0n$6||I>_0n$6;)k&_1n$6&&(R=R.add(B)),I&_1n$6&&($=$.add(B)),B=B.double(),k>>=_1n$6,I>>=_1n$6;return x&&(R=R.negate()),C&&($=$.negate()),$=new f(t.mul($.px,w.beta),$.py,$.pz),R.add($)}multiply(m){u(m);let y=m,w,x;const{endo:k}=e;if(k){const{k1neg:C,k1:I,k2neg:R,k2:$}=k.splitScalar(y);let{p:B,f:O}=this.wNAF(I),{p:H,f:T}=this.wNAF($);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(T)}else{const{p:C,f:I}=this.wNAF(y);w=C,x=I}return f.normalizeZ([w,x])[0]}multiplyAndAddUnsafe(m,y,w){const x=f.BASE,k=(I,R)=>R===_0n$6||R===_1n$6||!I.equals(x)?I.multiplyUnsafe(R):I.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),I=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:I}}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(S){return _0n$6<S&&S<t.ORDER}function u(S){return mod$1(S,r)}function c(S){return invert$1(S,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=weierstrassPoints$1({...e,toBytes(S,E,L){const M=E.toAffine(),U=t.toBytes(M.x),z=concatBytes$3;return L?z(Uint8Array.from([E.hasEvenY()?2:3]),U):z(Uint8Array.from([4]),U,t.toBytes(M.y))},fromBytes(S){const E=S.length,L=S[0],M=S.subarray(1);if(E===s&&(L===2||L===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(L&1)===1!==V&&(D=t.neg(D)),{x:U,y:D}}else if(E===o&&L===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=S=>bytesToHex$3(numberToBytesBE$1(S,e.nByteLength));function v(S){const E=r>>_1n$6;return S>E}function m(S){return v(S)?u(-S):S}const y=(S,E,L)=>bytesToNumberBE$1(S.slice(E,L));class w{constructor(E,L,M){this.r=E,this.s=L,this.recovery=M,this.assertValidity()}static fromCompact(E){const L=e.nByteLength;return E=ensureBytes$1("compactSignature",E,L*2),new w(y(E,0,L),y(E,L,2*L))}static fromDER(E){const{r:L,s:M}=DER$1.toSig(ensureBytes$1("DER",E));return new w(L,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:L,s:M,recovery:U}=this,z=$(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?L+e.n:L;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(S){try{return h(S),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const S=getMinHashLength$1(e.n);return mapHashToField$1(e.randomBytes(S),e.n)},precompute(S=8,E=l.BASE){return E._setWindowSize(S),E.multiply(BigInt(3)),E}};function k(S,E=!0){return l.fromPrivateKey(S).toRawBytes(E)}function C(S){const E=S instanceof Uint8Array,L=typeof S=="string",M=(E||L)&&S.length;return E?M===s||M===o:L?M===2*s||M===2*o:S instanceof l}function I(S,E,L=!0){if(C(S))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(S)).toRawBytes(L)}const R=e.bits2int||function(S){const E=bytesToNumberBE$1(S),L=S.length*8-e.nBitLength;return L>0?E>>BigInt(L):E},$=e.bits2int_modN||function(S){return u(R(S))},B=bitMask$1(e.nBitLength);function O(S){if(typeof S!="bigint")throw new Error("bigint expected");if(!(_0n$6<=S&&S<B))throw new Error(`bigint expected < 2^${e.nBitLength}`);return numberToBytesBE$1(S,e.nByteLength)}function H(S,E,L=T){if(["recovered","canonical"].some(se=>se in L))throw new Error("sign() legacy options not supported");const{hash:M,randomBytes:U}=e;let{lowS:z,prehash:D,extraEntropy:V}=L;z==null&&(z=!0),S=ensureBytes$1("msgHash",S),D&&(S=ensureBytes$1("prehashed msgHash",M(S)));const W=$(S),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(),X=u(J.x);if(X===_0n$6)return;const te=u(ye*u(ne+X*Z));if(te===_0n$6)return;let be=(J.x===X?0:2)|Number(J.y&_1n$6),Be=te;return z&&v(te)&&(Be=m(te),be^=1),new w(X,Be,be)}return{seed:K,k2sig:ae}}const T={lowS:e.lowS,prehash:!1},A={lowS:e.lowS,prehash:!1};function N(S,E,L=T){const{seed:M,k2sig:U}=H(S,E,L),z=e;return createHmacDrbg$1(z.hash.outputLen,z.nByteLength,z.hmac)(M,U)}l.BASE._setWindowSize(8);function P(S,E,L,M=A){var J;const U=S;if(E=ensureBytes$1("msgHash",E),L=ensureBytes$1("publicKey",L),"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(X){if(!(X instanceof DER$1.Err))throw X;V=w.fromCompact(U)}else if(typeof U=="object"&&typeof U.r=="bigint"&&typeof U.s=="bigint"){const{r:X,s:te}=U;V=new w(X,te)}else throw new Error("PARSE");W=l.fromHex(L)}catch(X){if(X.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=$(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:I,sign:N,verify:P,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,I=pow2$1(C,r,e)*l%e,R=pow2$1(I,_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:I,s1:R,s2:$,s3:B}=decrypt$2(u,p,b,v,m);f[y++]=I^w,f[y++]=R^x,f[y++]=$^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],I=t[2],R=a,$=u,B=c,O=l,H=h,T=f,A=p,N=b,P=v,S=m,E=y,L=w,M=x,U=k,z=C,D=I;for(let W=0;W<o;W+=2)R=R+H|0,M=rotl(M^R,16),P=P+M|0,H=rotl(H^P,12),R=R+H|0,M=rotl(M^R,8),P=P+M|0,H=rotl(H^P,7),$=$+T|0,U=rotl(U^$,16),S=S+U|0,T=rotl(T^S,12),$=$+T|0,U=rotl(U^$,8),S=S+U|0,T=rotl(T^S,7),B=B+A|0,z=rotl(z^B,16),E=E+z|0,A=rotl(A^E,12),B=B+A|0,z=rotl(z^B,8),E=E+z|0,A=rotl(A^E,7),O=O+N|0,D=rotl(D^O,16),L=L+D|0,N=rotl(N^L,12),O=O+N|0,D=rotl(D^O,8),L=L+D|0,N=rotl(N^L,7),R=R+T|0,D=rotl(D^R,16),E=E+D|0,T=rotl(T^E,12),R=R+T|0,D=rotl(D^R,8),E=E+D|0,T=rotl(T^E,7),$=$+A|0,M=rotl(M^$,16),L=L+M|0,A=rotl(A^L,12),$=$+A|0,M=rotl(M^$,8),L=L+M|0,A=rotl(A^L,7),B=B+N|0,U=rotl(U^B,16),P=P+U|0,N=rotl(N^P,12),B=B+N|0,U=rotl(U^B,8),P=P+U|0,N=rotl(N^P,7),O=O+H|0,z=rotl(z^O,16),S=S+z|0,H=rotl(H^S,12),O=O+H|0,z=rotl(z^O,8),S=S+z|0,H=rotl(H^S,7);let V=0;r[V++]=a+R|0,r[V++]=u+$|0,r[V++]=c+B|0,r[V++]=l+O|0,r[V++]=h+H|0,r[V++]=f+T|0,r[V++]=p+A|0,r[V++]=b+N|0,r[V++]=v+P|0,r[V++]=m+S|0,r[V++]=y+E|0,r[V++]=w+L|0,r[V++]=x+M|0,r[V++]=k+U|0,r[V++]=C+z|0,r[V++]=I+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 I=t.mul(w,y),R=t.mul(x,y),$=t.mul(k,y);if(C)return{x:t.ZERO,y:t.ZERO};if(!t.eql($,t.ONE))throw new Error("invZ was invalid");return{x:I,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:I,pz:R}=y,$=t.eql(t.mul(w,R),t.mul(C,k)),B=t.eql(t.mul(x,R),t.mul(I,k));return $&&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:I}=this;let R=t.ZERO,$=t.ZERO,B=t.ZERO,O=t.mul(k,k),H=t.mul(C,C),T=t.mul(I,I),A=t.mul(k,C);return A=t.add(A,A),B=t.mul(k,I),B=t.add(B,B),R=t.mul(y,B),$=t.mul(x,T),$=t.add(R,$),R=t.sub(H,$),$=t.add(H,$),$=t.mul(R,$),R=t.mul(A,R),B=t.mul(x,B),T=t.mul(y,T),A=t.sub(O,T),A=t.mul(y,A),A=t.add(A,B),B=t.add(O,O),O=t.add(B,O),O=t.add(O,T),O=t.mul(O,A),$=t.add($,O),T=t.mul(C,I),T=t.add(T,T),O=t.mul(T,A),R=t.sub(R,O),B=t.mul(T,H),B=t.add(B,B),B=t.add(B,B),new p(R,$,B)}add(y){l(y);const{px:w,py:x,pz:k}=this,{px:C,py:I,pz:R}=y;let $=t.ZERO,B=t.ZERO,O=t.ZERO;const H=e.a,T=t.mul(e.b,_3n);let A=t.mul(w,C),N=t.mul(x,I),P=t.mul(k,R),S=t.add(w,x),E=t.add(C,I);S=t.mul(S,E),E=t.add(A,N),S=t.sub(S,E),E=t.add(w,k);let L=t.add(C,R);return E=t.mul(E,L),L=t.add(A,P),E=t.sub(E,L),L=t.add(x,k),$=t.add(I,R),L=t.mul(L,$),$=t.add(N,P),L=t.sub(L,$),O=t.mul(H,E),$=t.mul(T,P),O=t.add($,O),$=t.sub(N,O),O=t.add(N,O),B=t.mul($,O),N=t.add(A,A),N=t.add(N,A),P=t.mul(H,P),E=t.mul(T,E),N=t.add(N,P),P=t.sub(A,P),P=t.mul(H,P),E=t.add(E,P),A=t.mul(N,E),B=t.add(B,A),A=t.mul(L,E),$=t.mul(S,$),$=t.sub($,A),A=t.mul(S,N),O=t.mul(L,O),O=t.add(O,A),new p($,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:I,k2neg:R,k2:$}=w.splitScalar(y),B=k,O=k,H=this;for(;I>_0n$1||$>_0n$1;)I&_1n$1&&(B=B.add(H)),$&_1n$1&&(O=O.add(H)),H=H.double(),I>>=_1n$1,$>>=_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:I,k1:R,k2neg:$,k2:B}=w.splitScalar(y);let{p:O,f:H}=this.wNAF(R),{p:T,f:A}=this.wNAF(B);O=v.constTimeNegate(I,O),T=v.constTimeNegate($,T),T=new p(t.mul(T.px,w.beta),T.py,T.pz),k=O.add(T),C=H.add(A)}else{const{p:I,f:R}=this.wNAF(y);k=I,C=R}return p.normalizeZ([k,C])[0]}multiplyAndAddUnsafe(y,w,x){const k=p.BASE,C=(R,$)=>$===_0n$1||$===_1n$1||!R.equals(k)?R.multiplyUnsafe($):R.multiply($),I=C(this,w).add(C(y,x));return I.is0()?void 0:I}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(P){return mod(P,r)}function u(P){return invert(P,r)}const{ProjectivePoint:c,normPrivateKeyToScalar:l,weierstrassEquation:h,isWithinCurveOrder:f}=weierstrassPoints({...e,toBytes(P,S,E){const L=S.toAffine(),M=t.toBytes(L.x),U=concatBytes;return abool("isCompressed",E),E?U(Uint8Array.from([S.hasEvenY()?2:3]),M):U(Uint8Array.from([4]),M,t.toBytes(L.y))},fromBytes(P){const S=P.length,E=P[0],L=P.subarray(1);if(S===s&&(E===2||E===3)){const M=bytesToNumberBE(L);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(S===o&&E===4){const M=t.fromBytes(L.subarray(0,t.BYTES)),U=t.fromBytes(L.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 "+S)}}}),p=P=>bytesToHex(numberToBytesBE(P,e.nByteLength));function b(P){const S=r>>_1n$1;return P>S}function v(P){return b(P)?a(-P):P}const m=(P,S,E)=>bytesToNumberBE(P.slice(S,E));class y{constructor(S,E,L){this.r=S,this.s=E,this.recovery=L,this.assertValidity()}static fromCompact(S){const E=e.nByteLength;return S=ensureBytes("compactSignature",S,E*2),new y(m(S,0,E),m(S,E,2*E))}static fromDER(S){const{r:E,s:L}=DER.toSig(ensureBytes("DER",S));return new y(E,L)}assertValidity(){aInRange("r",this.r,_1n$1,r),aInRange("s",this.s,_1n$1,r)}addRecoveryBit(S){return new y(this.r,this.s,S)}recoverPublicKey(S){const{r:E,s:L,recovery:M}=this,U=R(ensureBytes("msgHash",S));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(L*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(P){try{return l(P),!0}catch{return!1}},normPrivateKeyToScalar:l,randomPrivateKey:()=>{const P=getMinHashLength(e.n);return mapHashToField(e.randomBytes(P),e.n)},precompute(P=8,S=c.BASE){return S._setWindowSize(P),S.multiply(BigInt(3)),S}};function x(P,S=!0){return c.fromPrivateKey(P).toRawBytes(S)}function k(P){const S=isBytes(P),E=typeof P=="string",L=(S||E)&&P.length;return S?L===s||L===o:E?L===2*s||L===2*o:P instanceof c}function C(P,S,E=!0){if(k(P))throw new Error("first arg must be private key");if(!k(S))throw new Error("second arg must be public key");return c.fromHex(S).multiply(l(P)).toRawBytes(E)}const I=e.bits2int||function(P){if(P.length>8192)throw new Error("input is too large");const S=bytesToNumberBE(P),E=P.length*8-e.nBitLength;return E>0?S>>BigInt(E):S},R=e.bits2int_modN||function(P){return a(I(P))},$=bitMask(e.nBitLength);function B(P){return aInRange("num < 2^"+e.nBitLength,P,_0n$1,$),numberToBytesBE(P,e.nByteLength)}function O(P,S,E=H){if(["recovered","canonical"].some(ae=>ae in E))throw new Error("sign() legacy options not supported");const{hash:L,randomBytes:M}=e;let{lowS:U,prehash:z,extraEntropy:D}=E;U==null&&(U=!0),P=ensureBytes("msgHash",P),validateSigVerOpts(E),z&&(P=ensureBytes("prehashed msgHash",L(P)));const V=R(P),W=l(S),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=I(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 X=a(pe*a(K+J*W));if(X===_0n$1)return;let te=(ye.x===J?0:2)|Number(ye.y&_1n$1),be=X;return U&&b(X)&&(be=v(X),te^=1),new y(J,be,te)}return{seed:G,k2sig:ne}}const H={lowS:e.lowS,prehash:!1},T={lowS:e.lowS,prehash:!1};function A(P,S,E=H){const{seed:L,k2sig:M}=O(P,S,E),U=e;return createHmacDrbg(U.hash.outputLen,U.nByteLength,U.hmac)(L,M)}c.BASE._setWindowSize(8);function N(P,S,E,L=T){var te;const M=P;S=ensureBytes("msgHash",S),E=ensureBytes("publicKey",E);const{lowS:U,prehash:z,format:D}=L;if(validateSigVerOpts(L),"strict"in L)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&&(S=e.hash(S));const{r:K,s:ne}=Z,ae=R(S),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:A,verify:N,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,I=pow2(C,r,e)*l%e,R=pow2(I,_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(T){if(!Number.isSafeInteger(T))throw new Error(`Wrong integer: ${T}`)}n.assertNumber=e;function t(...T){const A=(S,E)=>L=>S(E(L)),N=Array.from(T).reverse().reduce((S,E)=>S?A(S,E.encode):E.encode,void 0),P=T.reduce((S,E)=>S?A(S,E.decode):E.decode,void 0);return{encode:N,decode:P}}function r(T){return{encode:A=>{if(!Array.isArray(A)||A.length&&typeof A[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return A.map(N=>{if(e(N),N<0||N>=T.length)throw new Error(`Digit index outside alphabet: ${N} (alphabet: ${T.length})`);return T[N]})},decode:A=>{if(!Array.isArray(A)||A.length&&typeof A[0]!="string")throw new Error("alphabet.decode input should be array of strings");return A.map(N=>{if(typeof N!="string")throw new Error(`alphabet.decode: not string element=${N}`);const P=T.indexOf(N);if(P===-1)throw new Error(`Unknown letter: "${N}". Allowed: ${T}`);return P})}}}function s(T=""){if(typeof T!="string")throw new Error("join separator should be string");return{encode:A=>{if(!Array.isArray(A)||A.length&&typeof A[0]!="string")throw new Error("join.encode input should be array of strings");for(let N of A)if(typeof N!="string")throw new Error(`join.encode: non-string input=${N}`);return A.join(T)},decode:A=>{if(typeof A!="string")throw new Error("join.decode input should be string");return A.split(T)}}}function o(T,A="="){if(e(T),typeof A!="string")throw new Error("padding chr should be string");return{encode(N){if(!Array.isArray(N)||N.length&&typeof N[0]!="string")throw new Error("padding.encode input should be array of strings");for(let P of N)if(typeof P!="string")throw new Error(`padding.encode: non-string input=${P}`);for(;N.length*T%8;)N.push(A);return N},decode(N){if(!Array.isArray(N)||N.length&&typeof N[0]!="string")throw new Error("padding.encode input should be array of strings");for(let S of N)if(typeof S!="string")throw new Error(`padding.decode: non-string input=${S}`);let P=N.length;if(P*T%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;P>0&&N[P-1]===A;P--)if(!((P-1)*T%8))throw new Error("Invalid padding: string has too much padding");return N.slice(0,P)}}}function a(T){if(typeof T!="function")throw new Error("normalize fn should be function");return{encode:A=>A,decode:A=>T(A)}}function u(T,A,N){if(A<2)throw new Error(`convertRadix: wrong from=${A}, base cannot be less than 2`);if(N<2)throw new Error(`convertRadix: wrong to=${N}, base cannot be less than 2`);if(!Array.isArray(T))throw new Error("convertRadix: data should be array");if(!T.length)return[];let P=0;const S=[],E=Array.from(T);for(E.forEach(L=>{if(e(L),L<0||L>=A)throw new Error(`Wrong integer: ${L}`)});;){let L=0,M=!0;for(let U=P;U<E.length;U++){const z=E[U],D=A*L+z;if(!Number.isSafeInteger(D)||A*L/A!==L||D-z!==A*L)throw new Error("convertRadix: carry overflow");if(L=D%N,E[U]=Math.floor(D/N),!Number.isSafeInteger(E[U])||E[U]*N+L!==D)throw new Error("convertRadix: carry overflow");if(M)E[U]?M=!1:P=U;else continue}if(S.push(L),M)break}for(let L=0;L<T.length-1&&T[L]===0;L++)S.push(0);return S.reverse()}const c=(T,A)=>A?c(A,T%A):T,l=(T,A)=>T+(A-c(T,A));function h(T,A,N,P){if(!Array.isArray(T))throw new Error("convertRadix2: data should be array");if(A<=0||A>32)throw new Error(`convertRadix2: wrong from=${A}`);if(N<=0||N>32)throw new Error(`convertRadix2: wrong to=${N}`);if(l(A,N)>32)throw new Error(`convertRadix2: carry overflow from=${A} to=${N} carryBits=${l(A,N)}`);let S=0,E=0;const L=2**N-1,M=[];for(const U of T){if(e(U),U>=2**A)throw new Error(`convertRadix2: invalid data word=${U} from=${A}`);if(S=S<<A|U,E+A>32)throw new Error(`convertRadix2: carry overflow pos=${E} from=${A}`);for(E+=A;E>=N;E-=N)M.push((S>>E-N&L)>>>0);S&=2**E-1}if(S=S<<N-E&L,!P&&E>=A)throw new Error("Excess padding");if(!P&&S)throw new Error(`Non-zero padding: ${S}`);return P&&E>0&&M.push(S>>>0),M}function f(T){return e(T),{encode:A=>{if(!(A instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return u(Array.from(A),2**8,T)},decode:A=>{if(!Array.isArray(A)||A.length&&typeof A[0]!="number")throw new Error("radix.decode input should be array of strings");return Uint8Array.from(u(A,T,2**8))}}}function p(T,A=!1){if(e(T),T<=0||T>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,T)>32||l(T,8)>32)throw new Error("radix2: carry overflow");return{encode:N=>{if(!(N instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(N),8,T,!A)},decode:N=>{if(!Array.isArray(N)||N.length&&typeof N[0]!="number")throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(N,T,8,A))}}}function b(T){if(typeof T!="function")throw new Error("unsafeWrapper fn should be function");return function(...A){try{return T.apply(null,A)}catch{}}}function v(T,A){if(e(T),typeof A!="function")throw new Error("checksum fn should be function");return{encode(N){if(!(N instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const P=A(N).slice(0,T),S=new Uint8Array(N.length+T);return S.set(N),S.set(P,N.length),S},decode(N){if(!(N instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const P=N.slice(0,-T),S=A(P).slice(0,T),E=N.slice(-T);for(let L=0;L<T;L++)if(S[L]!==E[L])throw new Error("Invalid checksum");return P}}}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(T=>T.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=T=>t(f(58),r(T),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(T){let A="";for(let N=0;N<T.length;N+=8){const P=T.subarray(N,N+8);A+=n.base58.encode(P).padStart(y[P.length],"1")}return A},decode(T){let A=[];for(let N=0;N<T.length;N+=11){const P=T.slice(N,N+11),S=y.indexOf(P.length),E=n.base58.decode(P);for(let L=0;L<E.length-S;L++)if(E[L]!==0)throw new Error("base58xmr: wrong padding");A=A.concat(Array.from(E.slice(E.length-S)))}return Uint8Array.from(A)}};const w=T=>t(v(4,A=>T(T(A))),n.base58);n.base58check=w;const x=t(r("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),s("")),k=[996825010,642813549,513874426,1027748829,705979059];function C(T){const A=T>>25;let N=(T&33554431)<<5;for(let P=0;P<k.length;P++)(A>>P&1)===1&&(N^=k[P]);return N}function I(T,A,N=1){const P=T.length;let S=1;for(let E=0;E<P;E++){const L=T.charCodeAt(E);if(L<33||L>126)throw new Error(`Invalid prefix (${T})`);S=C(S)^L>>5}S=C(S);for(let E=0;E<P;E++)S=C(S)^T.charCodeAt(E)&31;for(let E of A)S=C(S)^E;for(let E=0;E<6;E++)S=C(S);return S^=N,x.encode(h([S%2**30],30,5,!1))}function R(T){const A=T==="bech32"?1:734539939,N=p(5),P=N.decode,S=N.encode,E=b(P);function L(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)}${I(D,V,A)}`}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=I(G,ne,A);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:P(W)}}return{encode:L,decode:M,decodeToBytes:z,decodeUnsafe:U,fromWords:P,fromWordsUnsafe:E,toWords:S}}n.bech32=R("bech32"),n.bech32m=R("bech32m"),n.utf8={encode:T=>new TextDecoder().decode(T),decode:T=>new TextEncoder().encode(T)},n.hex=t(p(4),r("0123456789abcdef"),s(""),a(T=>{if(typeof T!="string"||T.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof T} with length ${T.length}`);return T.toLowerCase()}));const $={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($).join(", ")}`,O=(T,A)=>{if(typeof T!="string"||!$.hasOwnProperty(T))throw new TypeError(B);if(!(A instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return $[T].encode(A)};n.bytesToString=O,n.str=n.bytesToString;const H=(T,A)=>{if(!$.hasOwnProperty(T))throw new TypeError(B);if(typeof A!="string")throw new TypeError("stringToBytes() expects string");return $[T].decode(A)};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 _t{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 _t(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 Ie 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 Ie&&(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 Ie(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 Ie){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 Ie(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 Ie(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 Ie(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=(Q=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_p2pk");this.kind??(this.kind=10019)}static from(t){return new Q(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(Q,"kind",10019),g(Q,"kinds",[10019]),Q),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=(Se=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 Se(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(Se,"kind",7375),g(Se,"kinds",[7375]),Se),NDKHighlight=(Te=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_article");this.kind??(this.kind=9802)}static from(t){return new Te(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(Te,"kind",9802),g(Te,"kinds",[9802]),Te);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=(_e=class extends NDKEvent{constructor(t,r){super(t,r);g(this,"_imetas");this.kind??(this.kind=20)}static from(t){return new _e(t.ndk,t.rawEvent())}get isValid(){return this.imetas.length>0}get imetas(){return this._imetas?this._imetas:(this._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(_e,"kind",20),g(_e,"kinds",[20]),_e),NDKList=(Le=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 Le(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(Le,"kinds",[10063,30001,10004,10050,10030,10015,10001,10002,10007,10006,10003]),Le),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=(Ae=class extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=39e3)}static from(e){return new Ae(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(Ae,"kind",39e3),g(Ae,"kinds",[39e3]),Ae);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=($e=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 $e(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($e,"kind",23),g($e,"kinds",[23]),$e),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=(Ne=class extends NDKEvent{constructor(){super(...arguments);g(this,"_imetas")}static from(t){return new Ne(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(Ne,"kind",21),g(Ne,"kinds",[34235,34236,22,21]),Ne),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 At extends NDKEvent{constructor(e,t){super(e,t),this.kind??(this.kind=10002)}static from(e){return new At(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 $t{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 $t(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",Pe=class Pe{constructor(){g(this,"ndk");g(this,"isConnected",!1);this.ndk=new NDK}static getInstance(){return Pe.instance||(Pe.instance=new Pe),Pe.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
- ${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(Pe,"instance");let NostrService=Pe;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));this.initChannelStatus("user",NCStatus.Loading,{reflectOverall:!1})}static get observedAttributes(){return[...super.observedAttributes,"npub","pubkey","nip05"]}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),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`
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+`
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));this.initChannelStatus("user",NCStatus.Loading,{reflectOverall:!1})}static get observedAttributes(){return[...super.observedAttributes,"npub","pubkey","nip05"]}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),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>
80
80
  <button type="button"
@@ -332,7 +332,7 @@ ${u}`)}return t}async fetchFollows(e){try{return(await e.followSet()).size}catch
332
332
  * Glide.js v3.7.1
333
333
  * (c) 2013-2024 Jędrzej Chałubek (https://github.com/jedrzejchalubek/)
334
334
  * Released under the MIT License.
335
- */function ownKeys(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),t.push.apply(t,r)}return t}function _objectSpread2(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}function _typeof(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?_typeof=function(e){return typeof e}:_typeof=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(n)}function _classCallCheck(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function _defineProperties(n,e){for(var t=0;t<e.length;t++){var r=e[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(n,r.key,r)}}function _createClass(n,e,t){return e&&_defineProperties(n.prototype,e),n}function _defineProperty(n,e,t){return e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function _inherits(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(e&&e.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),e&&_setPrototypeOf(n,e)}function _getPrototypeOf(n){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(n)}function _setPrototypeOf(n,e){return _setPrototypeOf=Object.setPrototypeOf||function(r,s){return r.__proto__=s,r},_setPrototypeOf(n,e)}function _isNativeReflectConstruct(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function _assertThisInitialized(n){if(n===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}function _possibleConstructorReturn(n,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(n)}function _createSuper(n){var e=_isNativeReflectConstruct();return function(){var r=_getPrototypeOf(n),s;if(e){var o=_getPrototypeOf(this).constructor;s=Reflect.construct(r,arguments,o)}else s=r.apply(this,arguments);return _possibleConstructorReturn(this,s)}}function _superPropBase(n,e){for(;!Object.prototype.hasOwnProperty.call(n,e)&&(n=_getPrototypeOf(n),n!==null););return n}function _get(){return typeof Reflect<"u"&&Reflect.get?_get=Reflect.get:_get=function(e,t,r){var s=_superPropBase(e,t);if(s){var o=Object.getOwnPropertyDescriptor(s,t);return o.get?o.get.call(arguments.length<3?e:r):o.value}},_get.apply(this,arguments)}var defaults={type:"slider",startAt:0,perView:1,focusAt:0,gap:10,autoplay:!1,hoverpause:!0,keyboard:!0,bound:!1,swipeThreshold:80,dragThreshold:120,perSwipe:"",touchRatio:.5,touchAngle:45,animationDuration:400,rewind:!0,rewindDuration:800,animationTimingFunc:"cubic-bezier(.165, .840, .440, 1)",waitForTransition:!0,throttle:10,direction:"ltr",peek:0,cloningRatio:1,breakpoints:{},classes:{swipeable:"glide--swipeable",dragging:"glide--dragging",direction:{ltr:"glide--ltr",rtl:"glide--rtl"},type:{slider:"glide--slider",carousel:"glide--carousel"},slide:{clone:"glide__slide--clone",active:"glide__slide--active"},arrow:{disabled:"glide__arrow--disabled"},nav:{active:"glide__bullet--active"}}};function warn(n){console.error("[Glide warn]: ".concat(n))}function toInt(n){return parseInt(n)}function toFloat(n){return parseFloat(n)}function isString(n){return typeof n=="string"}function isObject(n){var e=_typeof(n);return e==="function"||e==="object"&&!!n}function isFunction(n){return typeof n=="function"}function isUndefined(n){return typeof n>"u"}function isArray(n){return n.constructor===Array}function mount(n,e,t){var r={};for(var s in e)isFunction(e[s])?r[s]=e[s](n,r,t):warn("Extension must be a function");for(var o in r)isFunction(r[o].mount)&&r[o].mount();return r}function define(n,e,t){Object.defineProperty(n,e,t)}function sortKeys(n){return Object.keys(n).sort().reduce(function(e,t){return e[t]=n[t],e[t],e},{})}function mergeOptions(n,e){var t=Object.assign({},n,e);if(e.hasOwnProperty("classes")){t.classes=Object.assign({},n.classes,e.classes);var r=["direction","type","slide","arrow","nav"];r.forEach(function(s){e.classes.hasOwnProperty(s)&&(t.classes[s]=_objectSpread2(_objectSpread2({},n.classes[s]),e.classes[s]))})}return e.hasOwnProperty("breakpoints")&&(t.breakpoints=Object.assign({},n.breakpoints,e.breakpoints)),t}var EventsBus=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_classCallCheck(this,n),this.events=e,this.hop=e.hasOwnProperty}return _createClass(n,[{key:"on",value:function(t,r){if(isArray(t)){for(var s=0;s<t.length;s++)this.on(t[s],r);return}this.hop.call(this.events,t)||(this.events[t]=[]);var o=this.events[t].push(r)-1;return{remove:function(){delete this.events[t][o]}}}},{key:"emit",value:function(t,r){if(isArray(t)){for(var s=0;s<t.length;s++)this.emit(t[s],r);return}this.hop.call(this.events,t)&&this.events[t].forEach(function(o){o(r||{})})}}]),n}(),Glide$1=function(){function n(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};_classCallCheck(this,n),this._c={},this._t=[],this._e=new EventsBus,this.disabled=!1,this.selector=e,this.settings=mergeOptions(defaults,t),this.index=this.settings.startAt}return _createClass(n,[{key:"mount",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._e.emit("mount.before"),isObject(t)?this._c=mount(this,t,this._e):warn("You need to provide a object on `mount()`"),this._e.emit("mount.after"),this}},{key:"mutate",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return isArray(t)?this._t=t:warn("You need to provide a array on `mutate()`"),this}},{key:"update",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.settings=mergeOptions(this.settings,t),t.hasOwnProperty("startAt")&&(this.index=t.startAt),this._e.emit("update"),this}},{key:"go",value:function(t){return this._c.Run.make(t),this}},{key:"move",value:function(t){return this._c.Transition.disable(),this._c.Move.make(t),this}},{key:"destroy",value:function(){return this._e.emit("destroy"),this}},{key:"play",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return t&&(this.settings.autoplay=t),this._e.emit("play"),this}},{key:"pause",value:function(){return this._e.emit("pause"),this}},{key:"disable",value:function(){return this.disabled=!0,this}},{key:"enable",value:function(){return this.disabled=!1,this}},{key:"on",value:function(t,r){return this._e.on(t,r),this}},{key:"isType",value:function(t){return this.settings.type===t}},{key:"settings",get:function(){return this._o},set:function(t){isObject(t)?this._o=t:warn("Options must be an `object` instance.")}},{key:"index",get:function(){return this._i},set:function(t){this._i=toInt(t)}},{key:"type",get:function(){return this.settings.type}},{key:"disabled",get:function(){return this._d},set:function(t){this._d=!!t}}]),n}();function Run(n,e,t){var r={mount:function(){this._o=!1},make:function(l){var h=this;n.disabled||(!n.settings.waitForTransition||n.disable(),this.move=l,t.emit("run.before",this.move),this.calculate(),t.emit("run",this.move),e.Transition.after(function(){h.isStart()&&t.emit("run.start",h.move),h.isEnd()&&t.emit("run.end",h.move),h.isOffset()&&(h._o=!1,t.emit("run.offset",h.move)),t.emit("run.after",h.move),n.enable()}))},calculate:function(){var l=this.move,h=this.length,f=l.steps,p=l.direction,b=1;if(p==="="){if(n.settings.bound&&toInt(f)>h){n.index=h;return}n.index=f;return}if(p===">"&&f===">"){n.index=h;return}if(p==="<"&&f==="<"){n.index=0;return}if(p==="|"&&(b=n.settings.perView||1),p===">"||p==="|"&&f===">"){var v=s(b);v>h&&(this._o=!0),n.index=o(v,b);return}if(p==="<"||p==="|"&&f==="<"){var m=a(b);m<0&&(this._o=!0),n.index=u(m,b);return}warn("Invalid direction pattern [".concat(p).concat(f,"] has been used"))},isStart:function(){return n.index<=0},isEnd:function(){return n.index>=this.length},isOffset:function(){var l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;return l?this._o?l==="|>"?this.move.direction==="|"&&this.move.steps===">":l==="|<"?this.move.direction==="|"&&this.move.steps==="<":this.move.direction===l:!1:this._o},isBound:function(){return n.isType("slider")&&n.settings.focusAt!=="center"&&n.settings.bound}};function s(c){var l=n.index;return n.isType("carousel")?l+c:l+(c-l%c)}function o(c,l){var h=r.length;return c<=h?c:n.isType("carousel")?c-(h+1):n.settings.rewind?r.isBound()&&!r.isEnd()?h:0:r.isBound()?h:Math.floor(h/l)*l}function a(c){var l=n.index;if(n.isType("carousel"))return l-c;var h=Math.ceil(l/c);return(h-1)*c}function u(c,l){var h=r.length;return c>=0?c:n.isType("carousel")?c+(h+1):n.settings.rewind?r.isBound()&&r.isStart()?h:Math.floor(h/l)*l:0}return define(r,"move",{get:function(){return this._m},set:function(l){var h=l.substr(1);this._m={direction:l.substr(0,1),steps:h?toInt(h)?toInt(h):h:0}}}),define(r,"length",{get:function(){var l=n.settings,h=e.Html.slides.length;return this.isBound()?h-1-(toInt(l.perView)-1)+toInt(l.focusAt):h-1}}),define(r,"offset",{get:function(){return this._o}}),r}function now(){return new Date().getTime()}function throttle(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,s,o,a,u=0,c=function(){u=t.leading===!1?0:now(),r=null,a=n.apply(s,o),r||(s=o=null)},l=function(){var f=now();!u&&t.leading===!1&&(u=f);var p=e-(f-u);return s=this,o=arguments,p<=0||p>e?(r&&(clearTimeout(r),r=null),u=f,a=n.apply(s,o),r||(s=o=null)):!r&&t.trailing!==!1&&(r=setTimeout(c,p)),a};return l.cancel=function(){clearTimeout(r),u=0,r=s=o=null},l}var MARGIN_TYPE={ltr:["marginLeft","marginRight"],rtl:["marginRight","marginLeft"]};function Gaps(n,e,t){var r={apply:function(o){for(var a=0,u=o.length;a<u;a++){var c=o[a].style,l=e.Direction.value;a!==0?c[MARGIN_TYPE[l][0]]="".concat(this.value/2,"px"):c[MARGIN_TYPE[l][0]]="",a!==o.length-1?c[MARGIN_TYPE[l][1]]="".concat(this.value/2,"px"):c[MARGIN_TYPE[l][1]]=""}},remove:function(o){for(var a=0,u=o.length;a<u;a++){var c=o[a].style;c.marginLeft="",c.marginRight=""}}};return define(r,"value",{get:function(){return toInt(n.settings.gap)}}),define(r,"grow",{get:function(){return r.value*e.Sizes.length}}),define(r,"reductor",{get:function(){var o=n.settings.perView;return r.value*(o-1)/o}}),t.on(["build.after","update"],throttle(function(){r.apply(e.Html.wrapper.children)},30)),t.on("destroy",function(){r.remove(e.Html.wrapper.children)}),r}function siblings(n){if(n&&n.parentNode){for(var e=n.parentNode.firstChild,t=[];e;e=e.nextSibling)e.nodeType===1&&e!==n&&t.push(e);return t}return[]}function toArray(n){return Array.prototype.slice.call(n)}var TRACK_SELECTOR='[data-glide-el="track"]';function Html(n,e,t){var r={mount:function(){this.root=n.selector,this.track=this.root.querySelector(TRACK_SELECTOR),this.collectSlides()},collectSlides:function(){this.slides=toArray(this.wrapper.children).filter(function(o){return!o.classList.contains(n.settings.classes.slide.clone)})}};return define(r,"root",{get:function(){return r._r},set:function(o){isString(o)&&(o=document.querySelector(o)),o!==null?r._r=o:warn("Root element must be a existing Html node")}}),define(r,"track",{get:function(){return r._t},set:function(o){r._t=o}}),define(r,"wrapper",{get:function(){return r.track.children[0]}}),t.on("update",function(){r.collectSlides()}),r}function Peek(n,e,t){var r={mount:function(){this.value=n.settings.peek}};return define(r,"value",{get:function(){return r._v},set:function(o){isObject(o)?(o.before=toInt(o.before),o.after=toInt(o.after)):o=toInt(o),r._v=o}}),define(r,"reductor",{get:function(){var o=r.value,a=n.settings.perView;return isObject(o)?o.before/a+o.after/a:o*2/a}}),t.on(["resize","update"],function(){r.mount()}),r}function Move(n,e,t){var r={mount:function(){this._o=0},make:function(){var o=this,a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.offset=a,t.emit("move",{movement:this.value}),e.Transition.after(function(){t.emit("move.after",{movement:o.value})})}};return define(r,"offset",{get:function(){return r._o},set:function(o){r._o=isUndefined(o)?0:toInt(o)}}),define(r,"translate",{get:function(){return e.Sizes.slideWidth*n.index}}),define(r,"value",{get:function(){var o=this.offset,a=this.translate;return e.Direction.is("rtl")?a+o:a-o}}),t.on(["build.before","run"],function(){r.make()}),r}function Sizes(n,e,t){var r={setupSlides:function(){for(var o="".concat(this.slideWidth,"px"),a=e.Html.slides,u=0;u<a.length;u++)a[u].style.width=o},setupWrapper:function(){e.Html.wrapper.style.width="".concat(this.wrapperSize,"px")},remove:function(){for(var o=e.Html.slides,a=0;a<o.length;a++)o[a].style.width="";e.Html.wrapper.style.width=""}};return define(r,"length",{get:function(){return e.Html.slides.length}}),define(r,"width",{get:function(){return e.Html.track.offsetWidth}}),define(r,"wrapperSize",{get:function(){return r.slideWidth*r.length+e.Gaps.grow+e.Clones.grow}}),define(r,"slideWidth",{get:function(){return r.width/n.settings.perView-e.Peek.reductor-e.Gaps.reductor}}),t.on(["build.before","resize","update"],function(){r.setupSlides(),r.setupWrapper()}),t.on("destroy",function(){r.remove()}),r}function Build(n,e,t){var r={mount:function(){t.emit("build.before"),this.typeClass(),this.activeClass(),t.emit("build.after")},typeClass:function(){e.Html.root.classList.add(n.settings.classes.type[n.settings.type])},activeClass:function(){var o=n.settings.classes,a=e.Html.slides[n.index];a&&(a.classList.add(o.slide.active),siblings(a).forEach(function(u){u.classList.remove(o.slide.active)}))},removeClasses:function(){var o=n.settings.classes,a=o.type,u=o.slide;e.Html.root.classList.remove(a[n.settings.type]),e.Html.slides.forEach(function(c){c.classList.remove(u.active)})}};return t.on(["destroy","update"],function(){r.removeClasses()}),t.on(["resize","update"],function(){r.mount()}),t.on("move.after",function(){r.activeClass()}),r}function Clones(n,e,t){var r={mount:function(){this.items=[],n.isType("carousel")&&(this.items=this.collect())},collect:function(){var o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],a=e.Html.slides,u=n.settings,c=u.perView,l=u.classes,h=u.cloningRatio;if(a.length>0)for(var f=+!!n.settings.peek,p=c+f+Math.round(c/2),b=a.slice(0,p).reverse(),v=a.slice(p*-1),m=0;m<Math.max(h,Math.floor(c/a.length));m++){for(var y=0;y<b.length;y++){var w=b[y].cloneNode(!0);w.classList.add(l.slide.clone),o.push(w)}for(var x=0;x<v.length;x++){var k=v[x].cloneNode(!0);k.classList.add(l.slide.clone),o.unshift(k)}}return o},append:function(){for(var o=this.items,a=e.Html,u=a.wrapper,c=a.slides,l=Math.floor(o.length/2),h=o.slice(0,l).reverse(),f=o.slice(l*-1).reverse(),p="".concat(e.Sizes.slideWidth,"px"),b=0;b<f.length;b++)u.appendChild(f[b]);for(var v=0;v<h.length;v++)u.insertBefore(h[v],c[0]);for(var m=0;m<o.length;m++)o[m].style.width=p},remove:function(){for(var o=this.items,a=0;a<o.length;a++)e.Html.wrapper.removeChild(o[a])}};return define(r,"grow",{get:function(){return(e.Sizes.slideWidth+e.Gaps.value)*r.items.length}}),t.on("update",function(){r.remove(),r.mount(),r.append()}),t.on("build.before",function(){n.isType("carousel")&&r.append()}),t.on("destroy",function(){r.remove()}),r}var EventsBinder=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_classCallCheck(this,n),this.listeners=e}return _createClass(n,[{key:"on",value:function(t,r,s){var o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;isString(t)&&(t=[t]);for(var a=0;a<t.length;a++)this.listeners[t[a]]=s,r.addEventListener(t[a],this.listeners[t[a]],o)}},{key:"off",value:function(t,r){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;isString(t)&&(t=[t]);for(var o=0;o<t.length;o++)r.removeEventListener(t[o],this.listeners[t[o]],s)}},{key:"destroy",value:function(){delete this.listeners}}]),n}();function Resize(n,e,t){var r=new EventsBinder,s={mount:function(){this.bind()},bind:function(){r.on("resize",window,throttle(function(){t.emit("resize")},n.settings.throttle))},unbind:function(){r.off("resize",window)}};return t.on("destroy",function(){s.unbind(),r.destroy()}),s}var VALID_DIRECTIONS=["ltr","rtl"],FLIPED_MOVEMENTS={">":"<","<":">","=":"="};function Direction(n,e,t){var r={mount:function(){this.value=n.settings.direction},resolve:function(o){var a=o.slice(0,1);return this.is("rtl")?o.split(a).join(FLIPED_MOVEMENTS[a]):o},is:function(o){return this.value===o},addClass:function(){e.Html.root.classList.add(n.settings.classes.direction[this.value])},removeClass:function(){e.Html.root.classList.remove(n.settings.classes.direction[this.value])}};return define(r,"value",{get:function(){return r._v},set:function(o){VALID_DIRECTIONS.indexOf(o)>-1?r._v=o:warn("Direction value must be `ltr` or `rtl`")}}),t.on(["destroy","update"],function(){r.removeClass()}),t.on("update",function(){r.mount()}),t.on(["build.before","update"],function(){r.addClass()}),r}function Rtl(n,e){return{modify:function(r){return e.Direction.is("rtl")?-r:r}}}function Gap(n,e){return{modify:function(r){var s=Math.floor(r/e.Sizes.slideWidth);return r+e.Gaps.value*s}}}function Grow(n,e){return{modify:function(r){return r+e.Clones.grow/2}}}function Peeking(n,e){return{modify:function(r){if(n.settings.focusAt>=0){var s=e.Peek.value;return isObject(s)?r-s.before:r-s}return r}}}function Focusing(n,e){return{modify:function(r){var s=e.Gaps.value,o=e.Sizes.width,a=n.settings.focusAt,u=e.Sizes.slideWidth;return a==="center"?r-(o/2-u/2):r-u*a-s*a}}}function mutator(n,e,t){var r=[Gap,Grow,Peeking,Focusing].concat(n._t,[Rtl]);return{mutate:function(o){for(var a=0;a<r.length;a++){var u=r[a];isFunction(u)&&isFunction(u().modify)?o=u(n,e,t).modify(o):warn("Transformer should be a function that returns an object with `modify()` method")}return o}}}function Translate(n,e,t){var r={set:function(o){var a=mutator(n,e).mutate(o),u="translate3d(".concat(-1*a,"px, 0px, 0px)");e.Html.wrapper.style.mozTransform=u,e.Html.wrapper.style.webkitTransform=u,e.Html.wrapper.style.transform=u},remove:function(){e.Html.wrapper.style.transform=""},getStartIndex:function(){var o=e.Sizes.length,a=n.index,u=n.settings.perView;return e.Run.isOffset(">")||e.Run.isOffset("|>")?o+(a-u):(a+u)%o},getTravelDistance:function(){var o=e.Sizes.slideWidth*n.settings.perView;return e.Run.isOffset(">")||e.Run.isOffset("|>")?o*-1:o}};return t.on("move",function(s){if(!n.isType("carousel")||!e.Run.isOffset())return r.set(s.movement);e.Transition.after(function(){t.emit("translate.jump"),r.set(e.Sizes.slideWidth*n.index)});var o=e.Sizes.slideWidth*e.Translate.getStartIndex();return r.set(o-e.Translate.getTravelDistance())}),t.on("destroy",function(){r.remove()}),r}function Transition(n,e,t){var r=!1,s={compose:function(a){var u=n.settings;return r?"".concat(a," 0ms ").concat(u.animationTimingFunc):"".concat(a," ").concat(this.duration,"ms ").concat(u.animationTimingFunc)},set:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"transform";e.Html.wrapper.style.transition=this.compose(a)},remove:function(){e.Html.wrapper.style.transition=""},after:function(a){setTimeout(function(){a()},this.duration)},enable:function(){r=!1,this.set()},disable:function(){r=!0,this.set()}};return define(s,"duration",{get:function(){var a=n.settings;return n.isType("slider")&&e.Run.offset?a.rewindDuration:a.animationDuration}}),t.on("move",function(){s.set()}),t.on(["build.before","resize","translate.jump"],function(){s.disable()}),t.on("run",function(){s.enable()}),t.on("destroy",function(){s.remove()}),s}var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});window.addEventListener("testPassive",null,opts),window.removeEventListener("testPassive",null,opts)}catch(n){}var supportsPassive$1=supportsPassive,START_EVENTS=["touchstart","mousedown"],MOVE_EVENTS=["touchmove","mousemove"],END_EVENTS=["touchend","touchcancel","mouseup","mouseleave"],MOUSE_EVENTS=["mousedown","mousemove","mouseup","mouseleave"];function Swipe(n,e,t){var r=new EventsBinder,s=0,o=0,a=0,u=!1,c=supportsPassive$1?{passive:!0}:!1,l={mount:function(){this.bindSwipeStart()},start:function(f){if(!u&&!n.disabled){this.disable();var p=this.touches(f);s=null,o=toInt(p.pageX),a=toInt(p.pageY),this.bindSwipeMove(),this.bindSwipeEnd(),t.emit("swipe.start")}},move:function(f){if(!n.disabled){var p=n.settings,b=p.touchAngle,v=p.touchRatio,m=p.classes,y=this.touches(f),w=toInt(y.pageX)-o,x=toInt(y.pageY)-a,k=Math.abs(w<<2),C=Math.abs(x<<2),I=Math.sqrt(k+C),R=Math.sqrt(C);if(s=Math.asin(R/I),s*180/Math.PI<b)f.stopPropagation(),e.Move.make(w*toFloat(v)),e.Html.root.classList.add(m.dragging),t.emit("swipe.move");else return!1}},end:function(f){if(!n.disabled){var p=n.settings,b=p.perSwipe,v=p.touchAngle,m=p.classes,y=this.touches(f),w=this.threshold(f),x=y.pageX-o,k=s*180/Math.PI;this.enable(),x>w&&k<v?e.Run.make(e.Direction.resolve("".concat(b,"<"))):x<-w&&k<v?e.Run.make(e.Direction.resolve("".concat(b,">"))):e.Move.make(),e.Html.root.classList.remove(m.dragging),this.unbindSwipeMove(),this.unbindSwipeEnd(),t.emit("swipe.end")}},bindSwipeStart:function(){var f=this,p=n.settings,b=p.swipeThreshold,v=p.dragThreshold;b&&r.on(START_EVENTS[0],e.Html.wrapper,function(m){f.start(m)},c),v&&r.on(START_EVENTS[1],e.Html.wrapper,function(m){f.start(m)},c)},unbindSwipeStart:function(){r.off(START_EVENTS[0],e.Html.wrapper,c),r.off(START_EVENTS[1],e.Html.wrapper,c)},bindSwipeMove:function(){var f=this;r.on(MOVE_EVENTS,e.Html.wrapper,throttle(function(p){f.move(p)},n.settings.throttle),c)},unbindSwipeMove:function(){r.off(MOVE_EVENTS,e.Html.wrapper,c)},bindSwipeEnd:function(){var f=this;r.on(END_EVENTS,e.Html.wrapper,function(p){f.end(p)})},unbindSwipeEnd:function(){r.off(END_EVENTS,e.Html.wrapper)},touches:function(f){return MOUSE_EVENTS.indexOf(f.type)>-1?f:f.touches[0]||f.changedTouches[0]},threshold:function(f){var p=n.settings;return MOUSE_EVENTS.indexOf(f.type)>-1?p.dragThreshold:p.swipeThreshold},enable:function(){return u=!1,e.Transition.enable(),this},disable:function(){return u=!0,e.Transition.disable(),this}};return t.on("build.after",function(){e.Html.root.classList.add(n.settings.classes.swipeable)}),t.on("destroy",function(){l.unbindSwipeStart(),l.unbindSwipeMove(),l.unbindSwipeEnd(),r.destroy()}),l}function Images(n,e,t){var r=new EventsBinder,s={mount:function(){this.bind()},bind:function(){r.on("dragstart",e.Html.wrapper,this.dragstart)},unbind:function(){r.off("dragstart",e.Html.wrapper)},dragstart:function(a){a.preventDefault()}};return t.on("destroy",function(){s.unbind(),r.destroy()}),s}function Anchors(n,e,t){var r=new EventsBinder,s=!1,o=!1,a={mount:function(){this._a=e.Html.wrapper.querySelectorAll("a"),this.bind()},bind:function(){r.on("click",e.Html.wrapper,this.click)},unbind:function(){r.off("click",e.Html.wrapper)},click:function(c){o&&(c.stopPropagation(),c.preventDefault())},detach:function(){if(o=!0,!s){for(var c=0;c<this.items.length;c++)this.items[c].draggable=!1;s=!0}return this},attach:function(){if(o=!1,s){for(var c=0;c<this.items.length;c++)this.items[c].draggable=!0;s=!1}return this}};return define(a,"items",{get:function(){return a._a}}),t.on("swipe.move",function(){a.detach()}),t.on("swipe.end",function(){e.Transition.after(function(){a.attach()})}),t.on("destroy",function(){a.attach(),a.unbind(),r.destroy()}),a}var NAV_SELECTOR='[data-glide-el="controls[nav]"]',CONTROLS_SELECTOR='[data-glide-el^="controls"]',PREVIOUS_CONTROLS_SELECTOR="".concat(CONTROLS_SELECTOR,' [data-glide-dir*="<"]'),NEXT_CONTROLS_SELECTOR="".concat(CONTROLS_SELECTOR,' [data-glide-dir*=">"]');function Controls(n,e,t){var r=new EventsBinder,s=supportsPassive$1?{passive:!0}:!1,o={mount:function(){this._n=e.Html.root.querySelectorAll(NAV_SELECTOR),this._c=e.Html.root.querySelectorAll(CONTROLS_SELECTOR),this._arrowControls={previous:e.Html.root.querySelectorAll(PREVIOUS_CONTROLS_SELECTOR),next:e.Html.root.querySelectorAll(NEXT_CONTROLS_SELECTOR)},this.addBindings()},setActive:function(){for(var u=0;u<this._n.length;u++)this.addClass(this._n[u].children)},removeActive:function(){for(var u=0;u<this._n.length;u++)this.removeClass(this._n[u].children)},addClass:function(u){var c=n.settings,l=u[n.index];l&&(l.classList.add(c.classes.nav.active),siblings(l).forEach(function(h){h.classList.remove(c.classes.nav.active)}))},removeClass:function(u){var c=u[n.index];c==null||c.classList.remove(n.settings.classes.nav.active)},setArrowState:function(){if(!n.settings.rewind){var u=o._arrowControls.next,c=o._arrowControls.previous;this.resetArrowState(u,c),n.index===0&&this.disableArrow(c),n.index===e.Run.length&&this.disableArrow(u)}},resetArrowState:function(){for(var u=n.settings,c=arguments.length,l=new Array(c),h=0;h<c;h++)l[h]=arguments[h];l.forEach(function(f){toArray(f).forEach(function(p){p.classList.remove(u.classes.arrow.disabled)})})},disableArrow:function(){for(var u=n.settings,c=arguments.length,l=new Array(c),h=0;h<c;h++)l[h]=arguments[h];l.forEach(function(f){toArray(f).forEach(function(p){p.classList.add(u.classes.arrow.disabled)})})},addBindings:function(){for(var u=0;u<this._c.length;u++)this.bind(this._c[u].children)},removeBindings:function(){for(var u=0;u<this._c.length;u++)this.unbind(this._c[u].children)},bind:function(u){for(var c=0;c<u.length;c++)r.on("click",u[c],this.click),r.on("touchstart",u[c],this.click,s)},unbind:function(u){for(var c=0;c<u.length;c++)r.off(["click","touchstart"],u[c])},click:function(u){!supportsPassive$1&&u.type==="touchstart"&&u.preventDefault();var c=u.currentTarget.getAttribute("data-glide-dir");e.Run.make(e.Direction.resolve(c))}};return define(o,"items",{get:function(){return o._c}}),t.on(["mount.after","move.after"],function(){o.setActive()}),t.on(["mount.after","run"],function(){o.setArrowState()}),t.on("destroy",function(){o.removeBindings(),o.removeActive(),r.destroy()}),o}function Keyboard(n,e,t){var r=new EventsBinder,s={mount:function(){n.settings.keyboard&&this.bind()},bind:function(){r.on("keyup",document,this.press)},unbind:function(){r.off("keyup",document)},press:function(a){var u=n.settings.perSwipe,c={ArrowRight:">",ArrowLeft:"<"};["ArrowRight","ArrowLeft"].includes(a.code)&&e.Run.make(e.Direction.resolve("".concat(u).concat(c[a.code])))}};return t.on(["destroy","update"],function(){s.unbind()}),t.on("update",function(){s.mount()}),t.on("destroy",function(){r.destroy()}),s}function Autoplay(n,e,t){var r=new EventsBinder,s={mount:function(){this.enable(),this.start(),n.settings.hoverpause&&this.bind()},enable:function(){this._e=!0},disable:function(){this._e=!1},start:function(){var a=this;this._e&&(this.enable(),n.settings.autoplay&&isUndefined(this._i)&&(this._i=setInterval(function(){a.stop(),e.Run.make(">"),a.start(),t.emit("autoplay")},this.time)))},stop:function(){this._i=clearInterval(this._i)},bind:function(){var a=this;r.on("mouseover",e.Html.root,function(){a._e&&a.stop()}),r.on("mouseout",e.Html.root,function(){a._e&&a.start()})},unbind:function(){r.off(["mouseover","mouseout"],e.Html.root)}};return define(s,"time",{get:function(){var a=e.Html.slides[n.index].getAttribute("data-glide-autoplay");return toInt(a||n.settings.autoplay)}}),t.on(["destroy","update"],function(){s.unbind()}),t.on(["run.before","swipe.start","update"],function(){s.stop()}),t.on(["pause","destroy"],function(){s.disable(),s.stop()}),t.on(["run.after","swipe.end"],function(){s.start()}),t.on(["play"],function(){s.enable(),s.start()}),t.on("update",function(){s.mount()}),t.on("destroy",function(){r.destroy()}),s}function sortBreakpoints(n){return isObject(n)?sortKeys(n):(warn("Breakpoints option must be an object"),{})}function Breakpoints(n,e,t){var r=new EventsBinder,s=n.settings,o=sortBreakpoints(s.breakpoints),a=Object.assign({},s),u={match:function(l){if(typeof window.matchMedia<"u"){for(var h in l)if(l.hasOwnProperty(h)&&window.matchMedia("(max-width: ".concat(h,"px)")).matches)return l[h]}return a}};return Object.assign(s,u.match(o)),r.on("resize",window,throttle(function(){n.settings=mergeOptions(s,u.match(o))},n.settings.throttle)),t.on("update",function(){o=sortBreakpoints(o),a=Object.assign({},s)}),t.on("destroy",function(){r.off("resize",window)}),u}var COMPONENTS={Html,Translate,Transition,Direction,Peek,Sizes,Gaps,Move,Clones,Resize,Build,Run,Swipe,Images,Anchors,Controls,Keyboard,Autoplay,Breakpoints},Glide=function(n){_inherits(t,n);var e=_createSuper(t);function t(){return _classCallCheck(this,t),e.apply(this,arguments)}return _createClass(t,[{key:"mount",value:function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return _get(_getPrototypeOf(t.prototype),"mount",this).call(this,Object.assign({},COMPONENTS,s))}}]),t}(Glide$1);const htmlDecodeTree=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(n=>n.charCodeAt(0))),xmlDecodeTree=new Uint16Array("Ȁaglq \x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(n=>n.charCodeAt(0)));var _a;const decodeMap=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),fromCodePoint=(_a=String.fromCodePoint)!==null&&_a!==void 0?_a:function(n){let e="";return n>65535&&(n-=65536,e+=String.fromCharCode(n>>>10&1023|55296),n=56320|n&1023),e+=String.fromCharCode(n),e};function replaceCodePoint(n){var e;return n>=55296&&n<=57343||n>1114111?65533:(e=decodeMap.get(n))!==null&&e!==void 0?e:n}var CharCodes$1;(function(n){n[n.NUM=35]="NUM",n[n.SEMI=59]="SEMI",n[n.EQUALS=61]="EQUALS",n[n.ZERO=48]="ZERO",n[n.NINE=57]="NINE",n[n.LOWER_A=97]="LOWER_A",n[n.LOWER_F=102]="LOWER_F",n[n.LOWER_X=120]="LOWER_X",n[n.LOWER_Z=122]="LOWER_Z",n[n.UPPER_A=65]="UPPER_A",n[n.UPPER_F=70]="UPPER_F",n[n.UPPER_Z=90]="UPPER_Z"})(CharCodes$1||(CharCodes$1={}));const TO_LOWER_BIT=32;var BinTrieFlags;(function(n){n[n.VALUE_LENGTH=49152]="VALUE_LENGTH",n[n.BRANCH_LENGTH=16256]="BRANCH_LENGTH",n[n.JUMP_TABLE=127]="JUMP_TABLE"})(BinTrieFlags||(BinTrieFlags={}));function isNumber(n){return n>=CharCodes$1.ZERO&&n<=CharCodes$1.NINE}function isHexadecimalCharacter(n){return n>=CharCodes$1.UPPER_A&&n<=CharCodes$1.UPPER_F||n>=CharCodes$1.LOWER_A&&n<=CharCodes$1.LOWER_F}function isAsciiAlphaNumeric(n){return n>=CharCodes$1.UPPER_A&&n<=CharCodes$1.UPPER_Z||n>=CharCodes$1.LOWER_A&&n<=CharCodes$1.LOWER_Z||isNumber(n)}function isEntityInAttributeInvalidEnd(n){return n===CharCodes$1.EQUALS||isAsciiAlphaNumeric(n)}var EntityDecoderState;(function(n){n[n.EntityStart=0]="EntityStart",n[n.NumericStart=1]="NumericStart",n[n.NumericDecimal=2]="NumericDecimal",n[n.NumericHex=3]="NumericHex",n[n.NamedEntity=4]="NamedEntity"})(EntityDecoderState||(EntityDecoderState={}));var DecodingMode;(function(n){n[n.Legacy=0]="Legacy",n[n.Strict=1]="Strict",n[n.Attribute=2]="Attribute"})(DecodingMode||(DecodingMode={}));class EntityDecoder{constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r,this.state=EntityDecoderState.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=DecodingMode.Strict}startEntity(e){this.decodeMode=e,this.state=EntityDecoderState.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case EntityDecoderState.EntityStart:return e.charCodeAt(t)===CharCodes$1.NUM?(this.state=EntityDecoderState.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=EntityDecoderState.NamedEntity,this.stateNamedEntity(e,t));case EntityDecoderState.NumericStart:return this.stateNumericStart(e,t);case EntityDecoderState.NumericDecimal:return this.stateNumericDecimal(e,t);case EntityDecoderState.NumericHex:return this.stateNumericHex(e,t);case EntityDecoderState.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(e.charCodeAt(t)|TO_LOWER_BIT)===CharCodes$1.LOWER_X?(this.state=EntityDecoderState.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=EntityDecoderState.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,r,s){if(t!==r){const o=r-t;this.result=this.result*Math.pow(s,o)+Number.parseInt(e.substr(t,o),s),this.consumed+=o}}stateNumericHex(e,t){const r=t;for(;t<e.length;){const s=e.charCodeAt(t);if(isNumber(s)||isHexadecimalCharacter(s))t+=1;else return this.addToNumericResult(e,r,t,16),this.emitNumericEntity(s,3)}return this.addToNumericResult(e,r,t,16),-1}stateNumericDecimal(e,t){const r=t;for(;t<e.length;){const s=e.charCodeAt(t);if(isNumber(s))t+=1;else return this.addToNumericResult(e,r,t,10),this.emitNumericEntity(s,2)}return this.addToNumericResult(e,r,t,10),-1}emitNumericEntity(e,t){var r;if(this.consumed<=t)return(r=this.errors)===null||r===void 0||r.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===CharCodes$1.SEMI)this.consumed+=1;else if(this.decodeMode===DecodingMode.Strict)return 0;return this.emitCodePoint(replaceCodePoint(this.result),this.consumed),this.errors&&(e!==CharCodes$1.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:r}=this;let s=r[this.treeIndex],o=(s&BinTrieFlags.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const a=e.charCodeAt(t);if(this.treeIndex=determineBranch(r,s,this.treeIndex+Math.max(1,o),a),this.treeIndex<0)return this.result===0||this.decodeMode===DecodingMode.Attribute&&(o===0||isEntityInAttributeInvalidEnd(a))?0:this.emitNotTerminatedNamedEntity();if(s=r[this.treeIndex],o=(s&BinTrieFlags.VALUE_LENGTH)>>14,o!==0){if(a===CharCodes$1.SEMI)return this.emitNamedEntityData(this.treeIndex,o,this.consumed+this.excess);this.decodeMode!==DecodingMode.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:r}=this,s=(r[t]&BinTrieFlags.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,s,this.consumed),(e=this.errors)===null||e===void 0||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){const{decodeTree:s}=this;return this.emitCodePoint(t===1?s[e]&~BinTrieFlags.VALUE_LENGTH:s[e+1],r),t===3&&this.emitCodePoint(s[e+2],r),r}end(){var e;switch(this.state){case EntityDecoderState.NamedEntity:return this.result!==0&&(this.decodeMode!==DecodingMode.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case EntityDecoderState.NumericDecimal:return this.emitNumericEntity(0,2);case EntityDecoderState.NumericHex:return this.emitNumericEntity(0,3);case EntityDecoderState.NumericStart:return(e=this.errors)===null||e===void 0||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case EntityDecoderState.EntityStart:return 0}}}function determineBranch(n,e,t,r){const s=(e&BinTrieFlags.BRANCH_LENGTH)>>7,o=e&BinTrieFlags.JUMP_TABLE;if(s===0)return o!==0&&r===o?t:-1;if(o){const c=r-o;return c<0||c>=s?-1:n[t+c]-1}let a=t,u=a+s-1;for(;a<=u;){const c=a+u>>>1,l=n[c];if(l<r)a=c+1;else if(l>r)u=c-1;else return n[c+s]}return-1}var CharCodes;(function(n){n[n.Tab=9]="Tab",n[n.NewLine=10]="NewLine",n[n.FormFeed=12]="FormFeed",n[n.CarriageReturn=13]="CarriageReturn",n[n.Space=32]="Space",n[n.ExclamationMark=33]="ExclamationMark",n[n.Number=35]="Number",n[n.Amp=38]="Amp",n[n.SingleQuote=39]="SingleQuote",n[n.DoubleQuote=34]="DoubleQuote",n[n.Dash=45]="Dash",n[n.Slash=47]="Slash",n[n.Zero=48]="Zero",n[n.Nine=57]="Nine",n[n.Semi=59]="Semi",n[n.Lt=60]="Lt",n[n.Eq=61]="Eq",n[n.Gt=62]="Gt",n[n.Questionmark=63]="Questionmark",n[n.UpperA=65]="UpperA",n[n.LowerA=97]="LowerA",n[n.UpperF=70]="UpperF",n[n.LowerF=102]="LowerF",n[n.UpperZ=90]="UpperZ",n[n.LowerZ=122]="LowerZ",n[n.LowerX=120]="LowerX",n[n.OpeningSquareBracket=91]="OpeningSquareBracket"})(CharCodes||(CharCodes={}));var State;(function(n){n[n.Text=1]="Text",n[n.BeforeTagName=2]="BeforeTagName",n[n.InTagName=3]="InTagName",n[n.InSelfClosingTag=4]="InSelfClosingTag",n[n.BeforeClosingTagName=5]="BeforeClosingTagName",n[n.InClosingTagName=6]="InClosingTagName",n[n.AfterClosingTagName=7]="AfterClosingTagName",n[n.BeforeAttributeName=8]="BeforeAttributeName",n[n.InAttributeName=9]="InAttributeName",n[n.AfterAttributeName=10]="AfterAttributeName",n[n.BeforeAttributeValue=11]="BeforeAttributeValue",n[n.InAttributeValueDq=12]="InAttributeValueDq",n[n.InAttributeValueSq=13]="InAttributeValueSq",n[n.InAttributeValueNq=14]="InAttributeValueNq",n[n.BeforeDeclaration=15]="BeforeDeclaration",n[n.InDeclaration=16]="InDeclaration",n[n.InProcessingInstruction=17]="InProcessingInstruction",n[n.BeforeComment=18]="BeforeComment",n[n.CDATASequence=19]="CDATASequence",n[n.InSpecialComment=20]="InSpecialComment",n[n.InCommentLike=21]="InCommentLike",n[n.BeforeSpecialS=22]="BeforeSpecialS",n[n.BeforeSpecialT=23]="BeforeSpecialT",n[n.SpecialStartSequence=24]="SpecialStartSequence",n[n.InSpecialTag=25]="InSpecialTag",n[n.InEntity=26]="InEntity"})(State||(State={}));function isWhitespace(n){return n===CharCodes.Space||n===CharCodes.NewLine||n===CharCodes.Tab||n===CharCodes.FormFeed||n===CharCodes.CarriageReturn}function isEndOfTagSection(n){return n===CharCodes.Slash||n===CharCodes.Gt||isWhitespace(n)}function isASCIIAlpha(n){return n>=CharCodes.LowerA&&n<=CharCodes.LowerZ||n>=CharCodes.UpperA&&n<=CharCodes.UpperZ}var QuoteType;(function(n){n[n.NoValue=0]="NoValue",n[n.Unquoted=1]="Unquoted",n[n.Single=2]="Single",n[n.Double=3]="Double"})(QuoteType||(QuoteType={}));const Sequences={Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,62]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])};class Tokenizer{constructor({xmlMode:e=!1,decodeEntities:t=!0},r){this.cbs=r,this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.entityStart=0,this.baseState=State.Text,this.isSpecial=!1,this.running=!0,this.offset=0,this.currentSequence=void 0,this.sequenceIndex=0,this.xmlMode=e,this.decodeEntities=t,this.entityDecoder=new EntityDecoder(e?xmlDecodeTree:htmlDecodeTree,(s,o)=>this.emitCodePoint(s,o))}reset(){this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=State.Text,this.currentSequence=void 0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){this.running&&this.finish()}pause(){this.running=!1}resume(){this.running=!0,this.index<this.buffer.length+this.offset&&this.parse()}stateText(e){e===CharCodes.Lt||!this.decodeEntities&&this.fastForwardTo(CharCodes.Lt)?(this.index>this.sectionStart&&this.cbs.ontext(this.sectionStart,this.index),this.state=State.BeforeTagName,this.sectionStart=this.index):this.decodeEntities&&e===CharCodes.Amp&&this.startEntity()}stateSpecialStartSequence(e){const t=this.sequenceIndex===this.currentSequence.length;if(!(t?isEndOfTagSection(e):(e|32)===this.currentSequence[this.sequenceIndex]))this.isSpecial=!1;else if(!t){this.sequenceIndex++;return}this.sequenceIndex=0,this.state=State.InTagName,this.stateInTagName(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(e===CharCodes.Gt||isWhitespace(e)){const t=this.index-this.currentSequence.length;if(this.sectionStart<t){const r=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=r}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}(e|32)===this.currentSequence[this.sequenceIndex]?this.sequenceIndex+=1:this.sequenceIndex===0?this.currentSequence===Sequences.TitleEnd?this.decodeEntities&&e===CharCodes.Amp&&this.startEntity():this.fastForwardTo(CharCodes.Lt)&&(this.sequenceIndex=1):this.sequenceIndex=+(e===CharCodes.Lt)}stateCDATASequence(e){e===Sequences.Cdata[this.sequenceIndex]?++this.sequenceIndex===Sequences.Cdata.length&&(this.state=State.InCommentLike,this.currentSequence=Sequences.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1):(this.sequenceIndex=0,this.state=State.InDeclaration,this.stateInDeclaration(e))}fastForwardTo(e){for(;++this.index<this.buffer.length+this.offset;)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}stateInCommentLike(e){e===this.currentSequence[this.sequenceIndex]?++this.sequenceIndex===this.currentSequence.length&&(this.currentSequence===Sequences.CdataEnd?this.cbs.oncdata(this.sectionStart,this.index,2):this.cbs.oncomment(this.sectionStart,this.index,2),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text):this.sequenceIndex===0?this.fastForwardTo(this.currentSequence[0])&&(this.sequenceIndex=1):e!==this.currentSequence[this.sequenceIndex-1]&&(this.sequenceIndex=0)}isTagStartChar(e){return this.xmlMode?!isEndOfTagSection(e):isASCIIAlpha(e)}startSpecial(e,t){this.isSpecial=!0,this.currentSequence=e,this.sequenceIndex=t,this.state=State.SpecialStartSequence}stateBeforeTagName(e){if(e===CharCodes.ExclamationMark)this.state=State.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===CharCodes.Questionmark)this.state=State.InProcessingInstruction,this.sectionStart=this.index+1;else if(this.isTagStartChar(e)){const t=e|32;this.sectionStart=this.index,this.xmlMode?this.state=State.InTagName:t===Sequences.ScriptEnd[2]?this.state=State.BeforeSpecialS:t===Sequences.TitleEnd[2]||t===Sequences.XmpEnd[2]?this.state=State.BeforeSpecialT:this.state=State.InTagName}else e===CharCodes.Slash?this.state=State.BeforeClosingTagName:(this.state=State.Text,this.stateText(e))}stateInTagName(e){isEndOfTagSection(e)&&(this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e))}stateBeforeClosingTagName(e){isWhitespace(e)||(e===CharCodes.Gt?this.state=State.Text:(this.state=this.isTagStartChar(e)?State.InClosingTagName:State.InSpecialComment,this.sectionStart=this.index))}stateInClosingTagName(e){(e===CharCodes.Gt||isWhitespace(e))&&(this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.AfterClosingTagName,this.stateAfterClosingTagName(e))}stateAfterClosingTagName(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeAttributeName(e){e===CharCodes.Gt?(this.cbs.onopentagend(this.index),this.isSpecial?(this.state=State.InSpecialTag,this.sequenceIndex=0):this.state=State.Text,this.sectionStart=this.index+1):e===CharCodes.Slash?this.state=State.InSelfClosingTag:isWhitespace(e)||(this.state=State.InAttributeName,this.sectionStart=this.index)}stateInSelfClosingTag(e){e===CharCodes.Gt?(this.cbs.onselfclosingtag(this.index),this.state=State.Text,this.sectionStart=this.index+1,this.isSpecial=!1):isWhitespace(e)||(this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e))}stateInAttributeName(e){(e===CharCodes.Eq||isEndOfTagSection(e))&&(this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=State.AfterAttributeName,this.stateAfterAttributeName(e))}stateAfterAttributeName(e){e===CharCodes.Eq?this.state=State.BeforeAttributeValue:e===CharCodes.Slash||e===CharCodes.Gt?(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e)):isWhitespace(e)||(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.state=State.InAttributeName,this.sectionStart=this.index)}stateBeforeAttributeValue(e){e===CharCodes.DoubleQuote?(this.state=State.InAttributeValueDq,this.sectionStart=this.index+1):e===CharCodes.SingleQuote?(this.state=State.InAttributeValueSq,this.sectionStart=this.index+1):isWhitespace(e)||(this.sectionStart=this.index,this.state=State.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e))}handleInAttributeValue(e,t){e===t||!this.decodeEntities&&this.fastForwardTo(t)?(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===CharCodes.DoubleQuote?QuoteType.Double:QuoteType.Single,this.index+1),this.state=State.BeforeAttributeName):this.decodeEntities&&e===CharCodes.Amp&&this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,CharCodes.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,CharCodes.SingleQuote)}stateInAttributeValueNoQuotes(e){isWhitespace(e)||e===CharCodes.Gt?(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(QuoteType.Unquoted,this.index),this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e)):this.decodeEntities&&e===CharCodes.Amp&&this.startEntity()}stateBeforeDeclaration(e){e===CharCodes.OpeningSquareBracket?(this.state=State.CDATASequence,this.sequenceIndex=0):this.state=e===CharCodes.Dash?State.BeforeComment:State.InDeclaration}stateInDeclaration(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.cbs.ondeclaration(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1)}stateInProcessingInstruction(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.cbs.onprocessinginstruction(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeComment(e){e===CharCodes.Dash?(this.state=State.InCommentLike,this.currentSequence=Sequences.CommentEnd,this.sequenceIndex=2,this.sectionStart=this.index+1):this.state=State.InDeclaration}stateInSpecialComment(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeSpecialS(e){const t=e|32;t===Sequences.ScriptEnd[3]?this.startSpecial(Sequences.ScriptEnd,4):t===Sequences.StyleEnd[3]?this.startSpecial(Sequences.StyleEnd,4):(this.state=State.InTagName,this.stateInTagName(e))}stateBeforeSpecialT(e){switch(e|32){case Sequences.TitleEnd[3]:{this.startSpecial(Sequences.TitleEnd,4);break}case Sequences.TextareaEnd[3]:{this.startSpecial(Sequences.TextareaEnd,4);break}case Sequences.XmpEnd[3]:{this.startSpecial(Sequences.XmpEnd,4);break}default:this.state=State.InTagName,this.stateInTagName(e)}}startEntity(){this.baseState=this.state,this.state=State.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?DecodingMode.Strict:this.baseState===State.Text||this.baseState===State.InSpecialTag?DecodingMode.Legacy:DecodingMode.Attribute)}stateInEntity(){const e=this.entityDecoder.write(this.buffer,this.index-this.offset);e>=0?(this.state=this.baseState,e===0&&(this.index=this.entityStart)):this.index=this.offset+this.buffer.length-1}cleanup(){this.running&&this.sectionStart!==this.index&&(this.state===State.Text||this.state===State.InSpecialTag&&this.sequenceIndex===0?(this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index):(this.state===State.InAttributeValueDq||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueNq)&&(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index))}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){for(;this.shouldContinue();){const e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case State.Text:{this.stateText(e);break}case State.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case State.InSpecialTag:{this.stateInSpecialTag(e);break}case State.CDATASequence:{this.stateCDATASequence(e);break}case State.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case State.InAttributeName:{this.stateInAttributeName(e);break}case State.InCommentLike:{this.stateInCommentLike(e);break}case State.InSpecialComment:{this.stateInSpecialComment(e);break}case State.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case State.InTagName:{this.stateInTagName(e);break}case State.InClosingTagName:{this.stateInClosingTagName(e);break}case State.BeforeTagName:{this.stateBeforeTagName(e);break}case State.AfterAttributeName:{this.stateAfterAttributeName(e);break}case State.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case State.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case State.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case State.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case State.BeforeSpecialS:{this.stateBeforeSpecialS(e);break}case State.BeforeSpecialT:{this.stateBeforeSpecialT(e);break}case State.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case State.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case State.InDeclaration:{this.stateInDeclaration(e);break}case State.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case State.BeforeComment:{this.stateBeforeComment(e);break}case State.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case State.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){this.state===State.InEntity&&(this.entityDecoder.end(),this.state=this.baseState),this.handleTrailingData(),this.cbs.onend()}handleTrailingData(){const e=this.buffer.length+this.offset;this.sectionStart>=e||(this.state===State.InCommentLike?this.currentSequence===Sequences.CdataEnd?this.cbs.oncdata(this.sectionStart,e,0):this.cbs.oncomment(this.sectionStart,e,0):this.state===State.InTagName||this.state===State.BeforeAttributeName||this.state===State.BeforeAttributeValue||this.state===State.AfterAttributeName||this.state===State.InAttributeName||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueDq||this.state===State.InAttributeValueNq||this.state===State.InClosingTagName||this.cbs.ontext(this.sectionStart,e))}emitCodePoint(e,t){this.baseState!==State.Text&&this.baseState!==State.InSpecialTag?(this.sectionStart<this.entityStart&&this.cbs.onattribdata(this.sectionStart,this.entityStart),this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)):(this.sectionStart<this.entityStart&&this.cbs.ontext(this.sectionStart,this.entityStart),this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart))}}const formTags=new Set(["input","option","optgroup","select","button","datalist","textarea"]),pTag=new Set(["p"]),tableSectionTags=new Set(["thead","tbody"]),ddtTags=new Set(["dd","dt"]),rtpTags=new Set(["rt","rp"]),openImpliesClose=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["li",new Set(["li"])],["p",pTag],["h1",pTag],["h2",pTag],["h3",pTag],["h4",pTag],["h5",pTag],["h6",pTag],["select",formTags],["input",formTags],["output",formTags],["button",formTags],["datalist",formTags],["textarea",formTags],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",ddtTags],["dt",ddtTags],["address",pTag],["article",pTag],["aside",pTag],["blockquote",pTag],["details",pTag],["div",pTag],["dl",pTag],["fieldset",pTag],["figcaption",pTag],["figure",pTag],["footer",pTag],["form",pTag],["header",pTag],["hr",pTag],["main",pTag],["nav",pTag],["ol",pTag],["pre",pTag],["section",pTag],["table",pTag],["ul",pTag],["rt",rtpTags],["rp",rtpTags],["tbody",tableSectionTags],["tfoot",tableSectionTags]]),voidElements=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),foreignContextElements=new Set(["math","svg"]),htmlIntegrationElements=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignobject","desc","title"]),reNameEnd=/\s|\//;class Parser{constructor(e,t={}){var r,s,o,a,u,c;this.options=t,this.startIndex=0,this.endIndex=0,this.openTagStart=0,this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack=[],this.buffers=[],this.bufferOffset=0,this.writeIndex=0,this.ended=!1,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=(r=t.lowerCaseTags)!==null&&r!==void 0?r:this.htmlMode,this.lowerCaseAttributeNames=(s=t.lowerCaseAttributeNames)!==null&&s!==void 0?s:this.htmlMode,this.recognizeSelfClosing=(o=t.recognizeSelfClosing)!==null&&o!==void 0?o:!this.htmlMode,this.tokenizer=new((a=t.Tokenizer)!==null&&a!==void 0?a:Tokenizer)(this.options,this),this.foreignContext=[!this.htmlMode],(c=(u=this.cbs).onparserinit)===null||c===void 0||c.call(u,this)}ontext(e,t){var r,s;const o=this.getSlice(e,t);this.endIndex=t-1,(s=(r=this.cbs).ontext)===null||s===void 0||s.call(r,o),this.startIndex=t}ontextentity(e,t){var r,s;this.endIndex=t-1,(s=(r=this.cbs).ontext)===null||s===void 0||s.call(r,fromCodePoint(e)),this.startIndex=t}isVoidElement(e){return this.htmlMode&&voidElements.has(e)}onopentagname(e,t){this.endIndex=t;let r=this.getSlice(e,t);this.lowerCaseTagNames&&(r=r.toLowerCase()),this.emitOpenTag(r)}emitOpenTag(e){var t,r,s,o;this.openTagStart=this.startIndex,this.tagname=e;const a=this.htmlMode&&openImpliesClose.get(e);if(a)for(;this.stack.length>0&&a.has(this.stack[0]);){const u=this.stack.shift();(r=(t=this.cbs).onclosetag)===null||r===void 0||r.call(t,u,!0)}this.isVoidElement(e)||(this.stack.unshift(e),this.htmlMode&&(foreignContextElements.has(e)?this.foreignContext.unshift(!0):htmlIntegrationElements.has(e)&&this.foreignContext.unshift(!1))),(o=(s=this.cbs).onopentagname)===null||o===void 0||o.call(s,e),this.cbs.onopentag&&(this.attribs={})}endOpenTag(e){var t,r;this.startIndex=this.openTagStart,this.attribs&&((r=(t=this.cbs).onopentag)===null||r===void 0||r.call(t,this.tagname,this.attribs,e),this.attribs=null),this.cbs.onclosetag&&this.isVoidElement(this.tagname)&&this.cbs.onclosetag(this.tagname,!0),this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){var r,s,o,a,u,c,l,h;this.endIndex=t;let f=this.getSlice(e,t);if(this.lowerCaseTagNames&&(f=f.toLowerCase()),this.htmlMode&&(foreignContextElements.has(f)||htmlIntegrationElements.has(f))&&this.foreignContext.shift(),this.isVoidElement(f))this.htmlMode&&f==="br"&&((a=(o=this.cbs).onopentagname)===null||a===void 0||a.call(o,"br"),(c=(u=this.cbs).onopentag)===null||c===void 0||c.call(u,"br",{},!0),(h=(l=this.cbs).onclosetag)===null||h===void 0||h.call(l,"br",!1));else{const p=this.stack.indexOf(f);if(p!==-1)for(let b=0;b<=p;b++){const v=this.stack.shift();(s=(r=this.cbs).onclosetag)===null||s===void 0||s.call(r,v,b!==p)}else this.htmlMode&&f==="p"&&(this.emitOpenTag("p"),this.closeCurrentTag(!0))}this.startIndex=t+1}onselfclosingtag(e){this.endIndex=e,this.recognizeSelfClosing||this.foreignContext[0]?(this.closeCurrentTag(!1),this.startIndex=e+1):this.onopentagend(e)}closeCurrentTag(e){var t,r;const s=this.tagname;this.endOpenTag(e),this.stack[0]===s&&((r=(t=this.cbs).onclosetag)===null||r===void 0||r.call(t,s,!e),this.stack.shift())}onattribname(e,t){this.startIndex=e;const r=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?r.toLowerCase():r}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=fromCodePoint(e)}onattribend(e,t){var r,s;this.endIndex=t,(s=(r=this.cbs).onattribute)===null||s===void 0||s.call(r,this.attribname,this.attribvalue,e===QuoteType.Double?'"':e===QuoteType.Single?"'":e===QuoteType.NoValue?void 0:null),this.attribs&&!Object.prototype.hasOwnProperty.call(this.attribs,this.attribname)&&(this.attribs[this.attribname]=this.attribvalue),this.attribvalue=""}getInstructionName(e){const t=e.search(reNameEnd);let r=t<0?e:e.substr(0,t);return this.lowerCaseTagNames&&(r=r.toLowerCase()),r}ondeclaration(e,t){this.endIndex=t;const r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){const s=this.getInstructionName(r);this.cbs.onprocessinginstruction(`!${s}`,`!${r}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;const r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){const s=this.getInstructionName(r);this.cbs.onprocessinginstruction(`?${s}`,`?${r}`)}this.startIndex=t+1}oncomment(e,t,r){var s,o,a,u;this.endIndex=t,(o=(s=this.cbs).oncomment)===null||o===void 0||o.call(s,this.getSlice(e,t-r)),(u=(a=this.cbs).oncommentend)===null||u===void 0||u.call(a),this.startIndex=t+1}oncdata(e,t,r){var s,o,a,u,c,l,h,f,p,b;this.endIndex=t;const v=this.getSlice(e,t-r);!this.htmlMode||this.options.recognizeCDATA?((o=(s=this.cbs).oncdatastart)===null||o===void 0||o.call(s),(u=(a=this.cbs).ontext)===null||u===void 0||u.call(a,v),(l=(c=this.cbs).oncdataend)===null||l===void 0||l.call(c)):((f=(h=this.cbs).oncomment)===null||f===void 0||f.call(h,`[CDATA[${v}]]`),(b=(p=this.cbs).oncommentend)===null||b===void 0||b.call(p)),this.startIndex=t+1}onend(){var e,t;if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let r=0;r<this.stack.length;r++)this.cbs.onclosetag(this.stack[r],!0)}(t=(e=this.cbs).onend)===null||t===void 0||t.call(e)}reset(){var e,t,r,s;(t=(e=this.cbs).onreset)===null||t===void 0||t.call(e),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,(s=(r=this.cbs).onparserinit)===null||s===void 0||s.call(r,this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(!this.htmlMode),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){for(;e-this.bufferOffset>=this.buffers[0].length;)this.shiftBuffer();let r=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);for(;t-this.bufferOffset>this.buffers[0].length;)this.shiftBuffer(),r+=this.buffers[0].slice(0,t-this.bufferOffset);return r}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){var t,r;if(this.ended){(r=(t=this.cbs).onerror)===null||r===void 0||r.call(t,new Error(".write() after done!"));return}this.buffers.push(e),this.tokenizer.running&&(this.tokenizer.write(e),this.writeIndex++)}end(e){var t,r;if(this.ended){(r=(t=this.cbs).onerror)===null||r===void 0||r.call(t,new Error(".end() after done!"));return}e&&this.write(e),this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){for(this.tokenizer.resume();this.tokenizer.running&&this.writeIndex<this.buffers.length;)this.tokenizer.write(this.buffers[this.writeIndex++]);this.ended&&this.tokenizer.end()}parseChunk(e){this.write(e)}done(e){this.end(e)}}var ElementType$2;(function(n){n.Root="root",n.Text="text",n.Directive="directive",n.Comment="comment",n.Script="script",n.Style="style",n.Tag="tag",n.CDATA="cdata",n.Doctype="doctype"})(ElementType$2||(ElementType$2={}));function isTag$1(n){return n.type===ElementType$2.Tag||n.type===ElementType$2.Script||n.type===ElementType$2.Style}ElementType$2.Root,ElementType$2.Text,ElementType$2.Directive,ElementType$2.Comment,ElementType$2.Script,ElementType$2.Style,ElementType$2.Tag,ElementType$2.CDATA,ElementType$2.Doctype;function isTag(n){return isTag$1(n)}function hasChildren(n){return Object.prototype.hasOwnProperty.call(n,"children")}var ElementType$1;(function(n){n.Root="root",n.Text="text",n.Directive="directive",n.Comment="comment",n.Script="script",n.Style="style",n.Tag="tag",n.CDATA="cdata",n.Doctype="doctype"})(ElementType$1||(ElementType$1={}));const Root=ElementType$1.Root,Text=ElementType$1.Text,Directive=ElementType$1.Directive,Comment=ElementType$1.Comment,Script=ElementType$1.Script,Style=ElementType$1.Style,Tag=ElementType$1.Tag,CDATA=ElementType$1.CDATA,Doctype=ElementType$1.Doctype,xmlReplacer=/["&'<>$\x80-\uFFFF]/g,xmlCodeMap=new Map([[34,"&quot;"],[38,"&amp;"],[39,"&apos;"],[60,"&lt;"],[62,"&gt;"]]),getCodePoint=String.prototype.codePointAt!=null?(n,e)=>n.codePointAt(e):(n,e)=>(n.charCodeAt(e)&64512)===55296?(n.charCodeAt(e)-55296)*1024+n.charCodeAt(e+1)-56320+65536:n.charCodeAt(e);function encodeXML(n){let e="",t=0,r;for(;(r=xmlReplacer.exec(n))!==null;){const s=r.index,o=n.charCodeAt(s),a=xmlCodeMap.get(o);a!==void 0?(e+=n.substring(t,s)+a,t=s+1):(e+=`${n.substring(t,s)}&#x${getCodePoint(n,s).toString(16)};`,t=xmlReplacer.lastIndex+=+((o&64512)===55296))}return e+n.substr(t)}function getEscaper(n,e){return function(r){let s,o=0,a="";for(;s=n.exec(r);)o!==s.index&&(a+=r.substring(o,s.index)),a+=e.get(s[0].charCodeAt(0)),o=s.index+1;return a+r.substring(o)}}const escapeAttribute=getEscaper(/["&\u00A0]/g,new Map([[34,"&quot;"],[38,"&amp;"],[160,"&nbsp;"]])),escapeText=getEscaper(/[&<>\u00A0]/g,new Map([[38,"&amp;"],[60,"&lt;"],[62,"&gt;"],[160,"&nbsp;"]])),elementNames=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(n=>[n.toLowerCase(),n])),attributeNames=new Map(["definitionURL","attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(n=>[n.toLowerCase(),n])),unencodedElements=new Set(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]);function replaceQuotes(n){return n.replace(/"/g,"&quot;")}function formatAttributes(n,e){var t;if(!n)return;const r=((t=e.encodeEntities)!==null&&t!==void 0?t:e.decodeEntities)===!1?replaceQuotes:e.xmlMode||e.encodeEntities!=="utf8"?encodeXML:escapeAttribute;return Object.keys(n).map(s=>{var o,a;const u=(o=n[s])!==null&&o!==void 0?o:"";return e.xmlMode==="foreign"&&(s=(a=attributeNames.get(s))!==null&&a!==void 0?a:s),!e.emptyAttrs&&!e.xmlMode&&u===""?s:`${s}="${r(u)}"`}).join(" ")}const singleTag=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]);function render(n,e={}){const t="length"in n?n:[n];let r="";for(let s=0;s<t.length;s++)r+=renderNode(t[s],e);return r}function renderNode(n,e){switch(n.type){case Root:return render(n.children,e);case Doctype:case Directive:return renderDirective(n);case Comment:return renderComment$1(n);case CDATA:return renderCdata(n);case Script:case Style:case Tag:return renderTag(n,e);case Text:return renderText(n,e)}}const foreignModeIntegrationPoints=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),foreignElements=new Set(["svg","math"]);function renderTag(n,e){var t;e.xmlMode==="foreign"&&(n.name=(t=elementNames.get(n.name))!==null&&t!==void 0?t:n.name,n.parent&&foreignModeIntegrationPoints.has(n.parent.name)&&(e={...e,xmlMode:!1})),!e.xmlMode&&foreignElements.has(n.name)&&(e={...e,xmlMode:"foreign"});let r=`<${n.name}`;const s=formatAttributes(n.attribs,e);return s&&(r+=` ${s}`),n.children.length===0&&(e.xmlMode?e.selfClosingTags!==!1:e.selfClosingTags&&singleTag.has(n.name))?(e.xmlMode||(r+=" "),r+="/>"):(r+=">",n.children.length>0&&(r+=render(n.children,e)),(e.xmlMode||!singleTag.has(n.name))&&(r+=`</${n.name}>`)),r}function renderDirective(n){return`<${n.data}>`}function renderText(n,e){var t;let r=n.data||"";return((t=e.encodeEntities)!==null&&t!==void 0?t:e.decodeEntities)!==!1&&!(!e.xmlMode&&n.parent&&unencodedElements.has(n.parent.name))&&(r=e.xmlMode||e.encodeEntities!=="utf8"?encodeXML(r):escapeText(r)),r}function renderCdata(n){return`<![CDATA[${n.children[0].data}]]>`}function renderComment$1(n){return`<!--${n.data}-->`}function getOuterHTML(n,e){return render(n,e)}function findAll(n,e){const t=[],r=[Array.isArray(e)?e:[e]],s=[0];for(;;){if(s[0]>=r[0].length){if(r.length===1)return t;r.shift(),s.shift();continue}const o=r[0][s[0]++];isTag(o)&&n(o)&&t.push(o),hasChildren(o)&&o.children.length>0&&(s.unshift(0),r.unshift(o.children))}}var domelementtype={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag",CDATA:"cdata"},node={exports:{}};node.exports={get firstChild(){var n=this.children;return n&&n[0]||null},get lastChild(){var n=this.children;return n&&n[n.length-1]||null},get nodeType(){return nodeTypes[this.type]||nodeTypes.element}};var domLvl1$1={tagName:"name",childNodes:"children",parentNode:"parent",previousSibling:"prev",nextSibling:"next",nodeValue:"data"},nodeTypes={element:1,text:3,cdata:4,comment:8};Object.keys(domLvl1$1).forEach(function(n){});var nodeExports=node.exports,element={exports:{}},NodePrototype$1=nodeExports,ElementPrototype$1=element.exports=Object.create(NodePrototype$1),domLvl1={tagName:"name"};Object.keys(domLvl1).forEach(function(n){var e=domLvl1[n];Object.defineProperty(ElementPrototype$1,n,{get:function(){return this[e]||null},set:function(t){return this[e]=t,t}})});var elementExports=element.exports,ElementType=domelementtype,re_whitespace=/\s+/g,NodePrototype=nodeExports,ElementPrototype=elementExports;function DomHandler(n,e,t){typeof n=="object"?(t=e,e=n,n=null):typeof e=="function"&&(t=e,e=defaultOpts),this._callback=n,this._options=e||defaultOpts,this._elementCB=t,this.dom=[],this._done=!1,this._tagStack=[],this._parser=this._parser||null}var defaultOpts={normalizeWhitespace:!1,withStartIndices:!1,withEndIndices:!1};DomHandler.prototype.onparserinit=function(n){this._parser=n},DomHandler.prototype.onreset=function(){DomHandler.call(this,this._callback,this._options,this._elementCB)},DomHandler.prototype.onend=function(){this._done||(this._done=!0,this._parser=null,this._handleCallback(null))},DomHandler.prototype._handleCallback=DomHandler.prototype.onerror=function(n){if(typeof this._callback=="function")this._callback(n,this.dom);else if(n)throw n},DomHandler.prototype.onclosetag=function(){var n=this._tagStack.pop();this._options.withEndIndices&&n&&(n.endIndex=this._parser.endIndex),this._elementCB&&this._elementCB(n)},DomHandler.prototype._createDomElement=function(n){if(!this._options.withDomLvl1)return n;var e;n.type==="tag"?e=Object.create(ElementPrototype):e=Object.create(NodePrototype);for(var t in n)n.hasOwnProperty(t)&&(e[t]=n[t]);return e},DomHandler.prototype._addDomElement=function(n){var e=this._tagStack[this._tagStack.length-1],t=e?e.children:this.dom,r=t[t.length-1];n.next=null,this._options.withStartIndices&&(n.startIndex=this._parser.startIndex),this._options.withEndIndices&&(n.endIndex=this._parser.endIndex),r?(n.prev=r,r.next=n):n.prev=null,t.push(n),n.parent=e||null},DomHandler.prototype.onopentag=function(n,e){var t={type:n==="script"?ElementType.Script:n==="style"?ElementType.Style:ElementType.Tag,name:n,attribs:e,children:[]},r=this._createDomElement(t);this._addDomElement(r),this._tagStack.push(r)},DomHandler.prototype.ontext=function(n){var e=this._options.normalizeWhitespace||this._options.ignoreWhitespace,t;if(!this._tagStack.length&&this.dom.length&&(t=this.dom[this.dom.length-1]).type===ElementType.Text)e?t.data=(t.data+n).replace(re_whitespace," "):t.data+=n;else if(this._tagStack.length&&(t=this._tagStack[this._tagStack.length-1])&&(t=t.children[t.children.length-1])&&t.type===ElementType.Text)e?t.data=(t.data+n).replace(re_whitespace," "):t.data+=n;else{e&&(n=n.replace(re_whitespace," "));var r=this._createDomElement({data:n,type:ElementType.Text});this._addDomElement(r)}},DomHandler.prototype.oncomment=function(n){var e=this._tagStack[this._tagStack.length-1];if(e&&e.type===ElementType.Comment){e.data+=n;return}var t={data:n,type:ElementType.Comment},r=this._createDomElement(t);this._addDomElement(r),this._tagStack.push(r)},DomHandler.prototype.oncdatastart=function(){var n={children:[{data:"",type:ElementType.Text}],type:ElementType.CDATA},e=this._createDomElement(n);this._addDomElement(e),this._tagStack.push(e)},DomHandler.prototype.oncommentend=DomHandler.prototype.oncdataend=function(){this._tagStack.pop()},DomHandler.prototype.onprocessinginstruction=function(n,e){var t=this._createDomElement({name:n,data:e,type:ElementType.Directive});this._addDomElement(t)};var domhandler=DomHandler;const replyIcon=`
335
+ */function ownKeys(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(n,s).enumerable})),t.push.apply(t,r)}return t}function _objectSpread2(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}function _typeof(n){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?_typeof=function(e){return typeof e}:_typeof=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_typeof(n)}function _classCallCheck(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function _defineProperties(n,e){for(var t=0;t<e.length;t++){var r=e[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(n,r.key,r)}}function _createClass(n,e,t){return e&&_defineProperties(n.prototype,e),n}function _defineProperty(n,e,t){return e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function _inherits(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(e&&e.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),e&&_setPrototypeOf(n,e)}function _getPrototypeOf(n){return _getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)},_getPrototypeOf(n)}function _setPrototypeOf(n,e){return _setPrototypeOf=Object.setPrototypeOf||function(r,s){return r.__proto__=s,r},_setPrototypeOf(n,e)}function _isNativeReflectConstruct(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function _assertThisInitialized(n){if(n===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return n}function _possibleConstructorReturn(n,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return _assertThisInitialized(n)}function _createSuper(n){var e=_isNativeReflectConstruct();return function(){var r=_getPrototypeOf(n),s;if(e){var o=_getPrototypeOf(this).constructor;s=Reflect.construct(r,arguments,o)}else s=r.apply(this,arguments);return _possibleConstructorReturn(this,s)}}function _superPropBase(n,e){for(;!Object.prototype.hasOwnProperty.call(n,e)&&(n=_getPrototypeOf(n),n!==null););return n}function _get(){return typeof Reflect<"u"&&Reflect.get?_get=Reflect.get:_get=function(e,t,r){var s=_superPropBase(e,t);if(s){var o=Object.getOwnPropertyDescriptor(s,t);return o.get?o.get.call(arguments.length<3?e:r):o.value}},_get.apply(this,arguments)}var defaults={type:"slider",startAt:0,perView:1,focusAt:0,gap:10,autoplay:!1,hoverpause:!0,keyboard:!0,bound:!1,swipeThreshold:80,dragThreshold:120,perSwipe:"",touchRatio:.5,touchAngle:45,animationDuration:400,rewind:!0,rewindDuration:800,animationTimingFunc:"cubic-bezier(.165, .840, .440, 1)",waitForTransition:!0,throttle:10,direction:"ltr",peek:0,cloningRatio:1,breakpoints:{},classes:{swipeable:"glide--swipeable",dragging:"glide--dragging",direction:{ltr:"glide--ltr",rtl:"glide--rtl"},type:{slider:"glide--slider",carousel:"glide--carousel"},slide:{clone:"glide__slide--clone",active:"glide__slide--active"},arrow:{disabled:"glide__arrow--disabled"},nav:{active:"glide__bullet--active"}}};function warn(n){console.error("[Glide warn]: ".concat(n))}function toInt(n){return parseInt(n)}function toFloat(n){return parseFloat(n)}function isString(n){return typeof n=="string"}function isObject(n){var e=_typeof(n);return e==="function"||e==="object"&&!!n}function isFunction(n){return typeof n=="function"}function isUndefined(n){return typeof n>"u"}function isArray(n){return n.constructor===Array}function mount(n,e,t){var r={};for(var s in e)isFunction(e[s])?r[s]=e[s](n,r,t):warn("Extension must be a function");for(var o in r)isFunction(r[o].mount)&&r[o].mount();return r}function define(n,e,t){Object.defineProperty(n,e,t)}function sortKeys(n){return Object.keys(n).sort().reduce(function(e,t){return e[t]=n[t],e[t],e},{})}function mergeOptions(n,e){var t=Object.assign({},n,e);if(e.hasOwnProperty("classes")){t.classes=Object.assign({},n.classes,e.classes);var r=["direction","type","slide","arrow","nav"];r.forEach(function(s){e.classes.hasOwnProperty(s)&&(t.classes[s]=_objectSpread2(_objectSpread2({},n.classes[s]),e.classes[s]))})}return e.hasOwnProperty("breakpoints")&&(t.breakpoints=Object.assign({},n.breakpoints,e.breakpoints)),t}var EventsBus=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_classCallCheck(this,n),this.events=e,this.hop=e.hasOwnProperty}return _createClass(n,[{key:"on",value:function(t,r){if(isArray(t)){for(var s=0;s<t.length;s++)this.on(t[s],r);return}this.hop.call(this.events,t)||(this.events[t]=[]);var o=this.events[t].push(r)-1;return{remove:function(){delete this.events[t][o]}}}},{key:"emit",value:function(t,r){if(isArray(t)){for(var s=0;s<t.length;s++)this.emit(t[s],r);return}this.hop.call(this.events,t)&&this.events[t].forEach(function(o){o(r||{})})}}]),n}(),Glide$1=function(){function n(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};_classCallCheck(this,n),this._c={},this._t=[],this._e=new EventsBus,this.disabled=!1,this.selector=e,this.settings=mergeOptions(defaults,t),this.index=this.settings.startAt}return _createClass(n,[{key:"mount",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this._e.emit("mount.before"),isObject(t)?this._c=mount(this,t,this._e):warn("You need to provide a object on `mount()`"),this._e.emit("mount.after"),this}},{key:"mutate",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return isArray(t)?this._t=t:warn("You need to provide a array on `mutate()`"),this}},{key:"update",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return this.settings=mergeOptions(this.settings,t),t.hasOwnProperty("startAt")&&(this.index=t.startAt),this._e.emit("update"),this}},{key:"go",value:function(t){return this._c.Run.make(t),this}},{key:"move",value:function(t){return this._c.Transition.disable(),this._c.Move.make(t),this}},{key:"destroy",value:function(){return this._e.emit("destroy"),this}},{key:"play",value:function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1;return t&&(this.settings.autoplay=t),this._e.emit("play"),this}},{key:"pause",value:function(){return this._e.emit("pause"),this}},{key:"disable",value:function(){return this.disabled=!0,this}},{key:"enable",value:function(){return this.disabled=!1,this}},{key:"on",value:function(t,r){return this._e.on(t,r),this}},{key:"isType",value:function(t){return this.settings.type===t}},{key:"settings",get:function(){return this._o},set:function(t){isObject(t)?this._o=t:warn("Options must be an `object` instance.")}},{key:"index",get:function(){return this._i},set:function(t){this._i=toInt(t)}},{key:"type",get:function(){return this.settings.type}},{key:"disabled",get:function(){return this._d},set:function(t){this._d=!!t}}]),n}();function Run(n,e,t){var r={mount:function(){this._o=!1},make:function(l){var h=this;n.disabled||(!n.settings.waitForTransition||n.disable(),this.move=l,t.emit("run.before",this.move),this.calculate(),t.emit("run",this.move),e.Transition.after(function(){h.isStart()&&t.emit("run.start",h.move),h.isEnd()&&t.emit("run.end",h.move),h.isOffset()&&(h._o=!1,t.emit("run.offset",h.move)),t.emit("run.after",h.move),n.enable()}))},calculate:function(){var l=this.move,h=this.length,f=l.steps,p=l.direction,b=1;if(p==="="){if(n.settings.bound&&toInt(f)>h){n.index=h;return}n.index=f;return}if(p===">"&&f===">"){n.index=h;return}if(p==="<"&&f==="<"){n.index=0;return}if(p==="|"&&(b=n.settings.perView||1),p===">"||p==="|"&&f===">"){var v=s(b);v>h&&(this._o=!0),n.index=o(v,b);return}if(p==="<"||p==="|"&&f==="<"){var m=a(b);m<0&&(this._o=!0),n.index=u(m,b);return}warn("Invalid direction pattern [".concat(p).concat(f,"] has been used"))},isStart:function(){return n.index<=0},isEnd:function(){return n.index>=this.length},isOffset:function(){var l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0;return l?this._o?l==="|>"?this.move.direction==="|"&&this.move.steps===">":l==="|<"?this.move.direction==="|"&&this.move.steps==="<":this.move.direction===l:!1:this._o},isBound:function(){return n.isType("slider")&&n.settings.focusAt!=="center"&&n.settings.bound}};function s(c){var l=n.index;return n.isType("carousel")?l+c:l+(c-l%c)}function o(c,l){var h=r.length;return c<=h?c:n.isType("carousel")?c-(h+1):n.settings.rewind?r.isBound()&&!r.isEnd()?h:0:r.isBound()?h:Math.floor(h/l)*l}function a(c){var l=n.index;if(n.isType("carousel"))return l-c;var h=Math.ceil(l/c);return(h-1)*c}function u(c,l){var h=r.length;return c>=0?c:n.isType("carousel")?c+(h+1):n.settings.rewind?r.isBound()&&r.isStart()?h:Math.floor(h/l)*l:0}return define(r,"move",{get:function(){return this._m},set:function(l){var h=l.substr(1);this._m={direction:l.substr(0,1),steps:h?toInt(h)?toInt(h):h:0}}}),define(r,"length",{get:function(){var l=n.settings,h=e.Html.slides.length;return this.isBound()?h-1-(toInt(l.perView)-1)+toInt(l.focusAt):h-1}}),define(r,"offset",{get:function(){return this._o}}),r}function now(){return new Date().getTime()}function throttle(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,s,o,a,u=0,c=function(){u=t.leading===!1?0:now(),r=null,a=n.apply(s,o),r||(s=o=null)},l=function(){var f=now();!u&&t.leading===!1&&(u=f);var p=e-(f-u);return s=this,o=arguments,p<=0||p>e?(r&&(clearTimeout(r),r=null),u=f,a=n.apply(s,o),r||(s=o=null)):!r&&t.trailing!==!1&&(r=setTimeout(c,p)),a};return l.cancel=function(){clearTimeout(r),u=0,r=s=o=null},l}var MARGIN_TYPE={ltr:["marginLeft","marginRight"],rtl:["marginRight","marginLeft"]};function Gaps(n,e,t){var r={apply:function(o){for(var a=0,u=o.length;a<u;a++){var c=o[a].style,l=e.Direction.value;a!==0?c[MARGIN_TYPE[l][0]]="".concat(this.value/2,"px"):c[MARGIN_TYPE[l][0]]="",a!==o.length-1?c[MARGIN_TYPE[l][1]]="".concat(this.value/2,"px"):c[MARGIN_TYPE[l][1]]=""}},remove:function(o){for(var a=0,u=o.length;a<u;a++){var c=o[a].style;c.marginLeft="",c.marginRight=""}}};return define(r,"value",{get:function(){return toInt(n.settings.gap)}}),define(r,"grow",{get:function(){return r.value*e.Sizes.length}}),define(r,"reductor",{get:function(){var o=n.settings.perView;return r.value*(o-1)/o}}),t.on(["build.after","update"],throttle(function(){r.apply(e.Html.wrapper.children)},30)),t.on("destroy",function(){r.remove(e.Html.wrapper.children)}),r}function siblings(n){if(n&&n.parentNode){for(var e=n.parentNode.firstChild,t=[];e;e=e.nextSibling)e.nodeType===1&&e!==n&&t.push(e);return t}return[]}function toArray(n){return Array.prototype.slice.call(n)}var TRACK_SELECTOR='[data-glide-el="track"]';function Html(n,e,t){var r={mount:function(){this.root=n.selector,this.track=this.root.querySelector(TRACK_SELECTOR),this.collectSlides()},collectSlides:function(){this.slides=toArray(this.wrapper.children).filter(function(o){return!o.classList.contains(n.settings.classes.slide.clone)})}};return define(r,"root",{get:function(){return r._r},set:function(o){isString(o)&&(o=document.querySelector(o)),o!==null?r._r=o:warn("Root element must be a existing Html node")}}),define(r,"track",{get:function(){return r._t},set:function(o){r._t=o}}),define(r,"wrapper",{get:function(){return r.track.children[0]}}),t.on("update",function(){r.collectSlides()}),r}function Peek(n,e,t){var r={mount:function(){this.value=n.settings.peek}};return define(r,"value",{get:function(){return r._v},set:function(o){isObject(o)?(o.before=toInt(o.before),o.after=toInt(o.after)):o=toInt(o),r._v=o}}),define(r,"reductor",{get:function(){var o=r.value,a=n.settings.perView;return isObject(o)?o.before/a+o.after/a:o*2/a}}),t.on(["resize","update"],function(){r.mount()}),r}function Move(n,e,t){var r={mount:function(){this._o=0},make:function(){var o=this,a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.offset=a,t.emit("move",{movement:this.value}),e.Transition.after(function(){t.emit("move.after",{movement:o.value})})}};return define(r,"offset",{get:function(){return r._o},set:function(o){r._o=isUndefined(o)?0:toInt(o)}}),define(r,"translate",{get:function(){return e.Sizes.slideWidth*n.index}}),define(r,"value",{get:function(){var o=this.offset,a=this.translate;return e.Direction.is("rtl")?a+o:a-o}}),t.on(["build.before","run"],function(){r.make()}),r}function Sizes(n,e,t){var r={setupSlides:function(){for(var o="".concat(this.slideWidth,"px"),a=e.Html.slides,u=0;u<a.length;u++)a[u].style.width=o},setupWrapper:function(){e.Html.wrapper.style.width="".concat(this.wrapperSize,"px")},remove:function(){for(var o=e.Html.slides,a=0;a<o.length;a++)o[a].style.width="";e.Html.wrapper.style.width=""}};return define(r,"length",{get:function(){return e.Html.slides.length}}),define(r,"width",{get:function(){return e.Html.track.offsetWidth}}),define(r,"wrapperSize",{get:function(){return r.slideWidth*r.length+e.Gaps.grow+e.Clones.grow}}),define(r,"slideWidth",{get:function(){return r.width/n.settings.perView-e.Peek.reductor-e.Gaps.reductor}}),t.on(["build.before","resize","update"],function(){r.setupSlides(),r.setupWrapper()}),t.on("destroy",function(){r.remove()}),r}function Build(n,e,t){var r={mount:function(){t.emit("build.before"),this.typeClass(),this.activeClass(),t.emit("build.after")},typeClass:function(){e.Html.root.classList.add(n.settings.classes.type[n.settings.type])},activeClass:function(){var o=n.settings.classes,a=e.Html.slides[n.index];a&&(a.classList.add(o.slide.active),siblings(a).forEach(function(u){u.classList.remove(o.slide.active)}))},removeClasses:function(){var o=n.settings.classes,a=o.type,u=o.slide;e.Html.root.classList.remove(a[n.settings.type]),e.Html.slides.forEach(function(c){c.classList.remove(u.active)})}};return t.on(["destroy","update"],function(){r.removeClasses()}),t.on(["resize","update"],function(){r.mount()}),t.on("move.after",function(){r.activeClass()}),r}function Clones(n,e,t){var r={mount:function(){this.items=[],n.isType("carousel")&&(this.items=this.collect())},collect:function(){var o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],a=e.Html.slides,u=n.settings,c=u.perView,l=u.classes,h=u.cloningRatio;if(a.length>0)for(var f=+!!n.settings.peek,p=c+f+Math.round(c/2),b=a.slice(0,p).reverse(),v=a.slice(p*-1),m=0;m<Math.max(h,Math.floor(c/a.length));m++){for(var y=0;y<b.length;y++){var w=b[y].cloneNode(!0);w.classList.add(l.slide.clone),o.push(w)}for(var x=0;x<v.length;x++){var k=v[x].cloneNode(!0);k.classList.add(l.slide.clone),o.unshift(k)}}return o},append:function(){for(var o=this.items,a=e.Html,u=a.wrapper,c=a.slides,l=Math.floor(o.length/2),h=o.slice(0,l).reverse(),f=o.slice(l*-1).reverse(),p="".concat(e.Sizes.slideWidth,"px"),b=0;b<f.length;b++)u.appendChild(f[b]);for(var v=0;v<h.length;v++)u.insertBefore(h[v],c[0]);for(var m=0;m<o.length;m++)o[m].style.width=p},remove:function(){for(var o=this.items,a=0;a<o.length;a++)e.Html.wrapper.removeChild(o[a])}};return define(r,"grow",{get:function(){return(e.Sizes.slideWidth+e.Gaps.value)*r.items.length}}),t.on("update",function(){r.remove(),r.mount(),r.append()}),t.on("build.before",function(){n.isType("carousel")&&r.append()}),t.on("destroy",function(){r.remove()}),r}var EventsBinder=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_classCallCheck(this,n),this.listeners=e}return _createClass(n,[{key:"on",value:function(t,r,s){var o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;isString(t)&&(t=[t]);for(var a=0;a<t.length;a++)this.listeners[t[a]]=s,r.addEventListener(t[a],this.listeners[t[a]],o)}},{key:"off",value:function(t,r){var s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;isString(t)&&(t=[t]);for(var o=0;o<t.length;o++)r.removeEventListener(t[o],this.listeners[t[o]],s)}},{key:"destroy",value:function(){delete this.listeners}}]),n}();function Resize(n,e,t){var r=new EventsBinder,s={mount:function(){this.bind()},bind:function(){r.on("resize",window,throttle(function(){t.emit("resize")},n.settings.throttle))},unbind:function(){r.off("resize",window)}};return t.on("destroy",function(){s.unbind(),r.destroy()}),s}var VALID_DIRECTIONS=["ltr","rtl"],FLIPED_MOVEMENTS={">":"<","<":">","=":"="};function Direction(n,e,t){var r={mount:function(){this.value=n.settings.direction},resolve:function(o){var a=o.slice(0,1);return this.is("rtl")?o.split(a).join(FLIPED_MOVEMENTS[a]):o},is:function(o){return this.value===o},addClass:function(){e.Html.root.classList.add(n.settings.classes.direction[this.value])},removeClass:function(){e.Html.root.classList.remove(n.settings.classes.direction[this.value])}};return define(r,"value",{get:function(){return r._v},set:function(o){VALID_DIRECTIONS.indexOf(o)>-1?r._v=o:warn("Direction value must be `ltr` or `rtl`")}}),t.on(["destroy","update"],function(){r.removeClass()}),t.on("update",function(){r.mount()}),t.on(["build.before","update"],function(){r.addClass()}),r}function Rtl(n,e){return{modify:function(r){return e.Direction.is("rtl")?-r:r}}}function Gap(n,e){return{modify:function(r){var s=Math.floor(r/e.Sizes.slideWidth);return r+e.Gaps.value*s}}}function Grow(n,e){return{modify:function(r){return r+e.Clones.grow/2}}}function Peeking(n,e){return{modify:function(r){if(n.settings.focusAt>=0){var s=e.Peek.value;return isObject(s)?r-s.before:r-s}return r}}}function Focusing(n,e){return{modify:function(r){var s=e.Gaps.value,o=e.Sizes.width,a=n.settings.focusAt,u=e.Sizes.slideWidth;return a==="center"?r-(o/2-u/2):r-u*a-s*a}}}function mutator(n,e,t){var r=[Gap,Grow,Peeking,Focusing].concat(n._t,[Rtl]);return{mutate:function(o){for(var a=0;a<r.length;a++){var u=r[a];isFunction(u)&&isFunction(u().modify)?o=u(n,e,t).modify(o):warn("Transformer should be a function that returns an object with `modify()` method")}return o}}}function Translate(n,e,t){var r={set:function(o){var a=mutator(n,e).mutate(o),u="translate3d(".concat(-1*a,"px, 0px, 0px)");e.Html.wrapper.style.mozTransform=u,e.Html.wrapper.style.webkitTransform=u,e.Html.wrapper.style.transform=u},remove:function(){e.Html.wrapper.style.transform=""},getStartIndex:function(){var o=e.Sizes.length,a=n.index,u=n.settings.perView;return e.Run.isOffset(">")||e.Run.isOffset("|>")?o+(a-u):(a+u)%o},getTravelDistance:function(){var o=e.Sizes.slideWidth*n.settings.perView;return e.Run.isOffset(">")||e.Run.isOffset("|>")?o*-1:o}};return t.on("move",function(s){if(!n.isType("carousel")||!e.Run.isOffset())return r.set(s.movement);e.Transition.after(function(){t.emit("translate.jump"),r.set(e.Sizes.slideWidth*n.index)});var o=e.Sizes.slideWidth*e.Translate.getStartIndex();return r.set(o-e.Translate.getTravelDistance())}),t.on("destroy",function(){r.remove()}),r}function Transition(n,e,t){var r=!1,s={compose:function(a){var u=n.settings;return r?"".concat(a," 0ms ").concat(u.animationTimingFunc):"".concat(a," ").concat(this.duration,"ms ").concat(u.animationTimingFunc)},set:function(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"transform";e.Html.wrapper.style.transition=this.compose(a)},remove:function(){e.Html.wrapper.style.transition=""},after:function(a){setTimeout(function(){a()},this.duration)},enable:function(){r=!1,this.set()},disable:function(){r=!0,this.set()}};return define(s,"duration",{get:function(){var a=n.settings;return n.isType("slider")&&e.Run.offset?a.rewindDuration:a.animationDuration}}),t.on("move",function(){s.set()}),t.on(["build.before","resize","translate.jump"],function(){s.disable()}),t.on("run",function(){s.enable()}),t.on("destroy",function(){s.remove()}),s}var supportsPassive=!1;try{var opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=!0}});window.addEventListener("testPassive",null,opts),window.removeEventListener("testPassive",null,opts)}catch(n){}var supportsPassive$1=supportsPassive,START_EVENTS=["touchstart","mousedown"],MOVE_EVENTS=["touchmove","mousemove"],END_EVENTS=["touchend","touchcancel","mouseup","mouseleave"],MOUSE_EVENTS=["mousedown","mousemove","mouseup","mouseleave"];function Swipe(n,e,t){var r=new EventsBinder,s=0,o=0,a=0,u=!1,c=supportsPassive$1?{passive:!0}:!1,l={mount:function(){this.bindSwipeStart()},start:function(f){if(!u&&!n.disabled){this.disable();var p=this.touches(f);s=null,o=toInt(p.pageX),a=toInt(p.pageY),this.bindSwipeMove(),this.bindSwipeEnd(),t.emit("swipe.start")}},move:function(f){if(!n.disabled){var p=n.settings,b=p.touchAngle,v=p.touchRatio,m=p.classes,y=this.touches(f),w=toInt(y.pageX)-o,x=toInt(y.pageY)-a,k=Math.abs(w<<2),C=Math.abs(x<<2),P=Math.sqrt(k+C),R=Math.sqrt(C);if(s=Math.asin(R/P),s*180/Math.PI<b)f.stopPropagation(),e.Move.make(w*toFloat(v)),e.Html.root.classList.add(m.dragging),t.emit("swipe.move");else return!1}},end:function(f){if(!n.disabled){var p=n.settings,b=p.perSwipe,v=p.touchAngle,m=p.classes,y=this.touches(f),w=this.threshold(f),x=y.pageX-o,k=s*180/Math.PI;this.enable(),x>w&&k<v?e.Run.make(e.Direction.resolve("".concat(b,"<"))):x<-w&&k<v?e.Run.make(e.Direction.resolve("".concat(b,">"))):e.Move.make(),e.Html.root.classList.remove(m.dragging),this.unbindSwipeMove(),this.unbindSwipeEnd(),t.emit("swipe.end")}},bindSwipeStart:function(){var f=this,p=n.settings,b=p.swipeThreshold,v=p.dragThreshold;b&&r.on(START_EVENTS[0],e.Html.wrapper,function(m){f.start(m)},c),v&&r.on(START_EVENTS[1],e.Html.wrapper,function(m){f.start(m)},c)},unbindSwipeStart:function(){r.off(START_EVENTS[0],e.Html.wrapper,c),r.off(START_EVENTS[1],e.Html.wrapper,c)},bindSwipeMove:function(){var f=this;r.on(MOVE_EVENTS,e.Html.wrapper,throttle(function(p){f.move(p)},n.settings.throttle),c)},unbindSwipeMove:function(){r.off(MOVE_EVENTS,e.Html.wrapper,c)},bindSwipeEnd:function(){var f=this;r.on(END_EVENTS,e.Html.wrapper,function(p){f.end(p)})},unbindSwipeEnd:function(){r.off(END_EVENTS,e.Html.wrapper)},touches:function(f){return MOUSE_EVENTS.indexOf(f.type)>-1?f:f.touches[0]||f.changedTouches[0]},threshold:function(f){var p=n.settings;return MOUSE_EVENTS.indexOf(f.type)>-1?p.dragThreshold:p.swipeThreshold},enable:function(){return u=!1,e.Transition.enable(),this},disable:function(){return u=!0,e.Transition.disable(),this}};return t.on("build.after",function(){e.Html.root.classList.add(n.settings.classes.swipeable)}),t.on("destroy",function(){l.unbindSwipeStart(),l.unbindSwipeMove(),l.unbindSwipeEnd(),r.destroy()}),l}function Images(n,e,t){var r=new EventsBinder,s={mount:function(){this.bind()},bind:function(){r.on("dragstart",e.Html.wrapper,this.dragstart)},unbind:function(){r.off("dragstart",e.Html.wrapper)},dragstart:function(a){a.preventDefault()}};return t.on("destroy",function(){s.unbind(),r.destroy()}),s}function Anchors(n,e,t){var r=new EventsBinder,s=!1,o=!1,a={mount:function(){this._a=e.Html.wrapper.querySelectorAll("a"),this.bind()},bind:function(){r.on("click",e.Html.wrapper,this.click)},unbind:function(){r.off("click",e.Html.wrapper)},click:function(c){o&&(c.stopPropagation(),c.preventDefault())},detach:function(){if(o=!0,!s){for(var c=0;c<this.items.length;c++)this.items[c].draggable=!1;s=!0}return this},attach:function(){if(o=!1,s){for(var c=0;c<this.items.length;c++)this.items[c].draggable=!0;s=!1}return this}};return define(a,"items",{get:function(){return a._a}}),t.on("swipe.move",function(){a.detach()}),t.on("swipe.end",function(){e.Transition.after(function(){a.attach()})}),t.on("destroy",function(){a.attach(),a.unbind(),r.destroy()}),a}var NAV_SELECTOR='[data-glide-el="controls[nav]"]',CONTROLS_SELECTOR='[data-glide-el^="controls"]',PREVIOUS_CONTROLS_SELECTOR="".concat(CONTROLS_SELECTOR,' [data-glide-dir*="<"]'),NEXT_CONTROLS_SELECTOR="".concat(CONTROLS_SELECTOR,' [data-glide-dir*=">"]');function Controls(n,e,t){var r=new EventsBinder,s=supportsPassive$1?{passive:!0}:!1,o={mount:function(){this._n=e.Html.root.querySelectorAll(NAV_SELECTOR),this._c=e.Html.root.querySelectorAll(CONTROLS_SELECTOR),this._arrowControls={previous:e.Html.root.querySelectorAll(PREVIOUS_CONTROLS_SELECTOR),next:e.Html.root.querySelectorAll(NEXT_CONTROLS_SELECTOR)},this.addBindings()},setActive:function(){for(var u=0;u<this._n.length;u++)this.addClass(this._n[u].children)},removeActive:function(){for(var u=0;u<this._n.length;u++)this.removeClass(this._n[u].children)},addClass:function(u){var c=n.settings,l=u[n.index];l&&(l.classList.add(c.classes.nav.active),siblings(l).forEach(function(h){h.classList.remove(c.classes.nav.active)}))},removeClass:function(u){var c=u[n.index];c==null||c.classList.remove(n.settings.classes.nav.active)},setArrowState:function(){if(!n.settings.rewind){var u=o._arrowControls.next,c=o._arrowControls.previous;this.resetArrowState(u,c),n.index===0&&this.disableArrow(c),n.index===e.Run.length&&this.disableArrow(u)}},resetArrowState:function(){for(var u=n.settings,c=arguments.length,l=new Array(c),h=0;h<c;h++)l[h]=arguments[h];l.forEach(function(f){toArray(f).forEach(function(p){p.classList.remove(u.classes.arrow.disabled)})})},disableArrow:function(){for(var u=n.settings,c=arguments.length,l=new Array(c),h=0;h<c;h++)l[h]=arguments[h];l.forEach(function(f){toArray(f).forEach(function(p){p.classList.add(u.classes.arrow.disabled)})})},addBindings:function(){for(var u=0;u<this._c.length;u++)this.bind(this._c[u].children)},removeBindings:function(){for(var u=0;u<this._c.length;u++)this.unbind(this._c[u].children)},bind:function(u){for(var c=0;c<u.length;c++)r.on("click",u[c],this.click),r.on("touchstart",u[c],this.click,s)},unbind:function(u){for(var c=0;c<u.length;c++)r.off(["click","touchstart"],u[c])},click:function(u){!supportsPassive$1&&u.type==="touchstart"&&u.preventDefault();var c=u.currentTarget.getAttribute("data-glide-dir");e.Run.make(e.Direction.resolve(c))}};return define(o,"items",{get:function(){return o._c}}),t.on(["mount.after","move.after"],function(){o.setActive()}),t.on(["mount.after","run"],function(){o.setArrowState()}),t.on("destroy",function(){o.removeBindings(),o.removeActive(),r.destroy()}),o}function Keyboard(n,e,t){var r=new EventsBinder,s={mount:function(){n.settings.keyboard&&this.bind()},bind:function(){r.on("keyup",document,this.press)},unbind:function(){r.off("keyup",document)},press:function(a){var u=n.settings.perSwipe,c={ArrowRight:">",ArrowLeft:"<"};["ArrowRight","ArrowLeft"].includes(a.code)&&e.Run.make(e.Direction.resolve("".concat(u).concat(c[a.code])))}};return t.on(["destroy","update"],function(){s.unbind()}),t.on("update",function(){s.mount()}),t.on("destroy",function(){r.destroy()}),s}function Autoplay(n,e,t){var r=new EventsBinder,s={mount:function(){this.enable(),this.start(),n.settings.hoverpause&&this.bind()},enable:function(){this._e=!0},disable:function(){this._e=!1},start:function(){var a=this;this._e&&(this.enable(),n.settings.autoplay&&isUndefined(this._i)&&(this._i=setInterval(function(){a.stop(),e.Run.make(">"),a.start(),t.emit("autoplay")},this.time)))},stop:function(){this._i=clearInterval(this._i)},bind:function(){var a=this;r.on("mouseover",e.Html.root,function(){a._e&&a.stop()}),r.on("mouseout",e.Html.root,function(){a._e&&a.start()})},unbind:function(){r.off(["mouseover","mouseout"],e.Html.root)}};return define(s,"time",{get:function(){var a=e.Html.slides[n.index].getAttribute("data-glide-autoplay");return toInt(a||n.settings.autoplay)}}),t.on(["destroy","update"],function(){s.unbind()}),t.on(["run.before","swipe.start","update"],function(){s.stop()}),t.on(["pause","destroy"],function(){s.disable(),s.stop()}),t.on(["run.after","swipe.end"],function(){s.start()}),t.on(["play"],function(){s.enable(),s.start()}),t.on("update",function(){s.mount()}),t.on("destroy",function(){r.destroy()}),s}function sortBreakpoints(n){return isObject(n)?sortKeys(n):(warn("Breakpoints option must be an object"),{})}function Breakpoints(n,e,t){var r=new EventsBinder,s=n.settings,o=sortBreakpoints(s.breakpoints),a=Object.assign({},s),u={match:function(l){if(typeof window.matchMedia<"u"){for(var h in l)if(l.hasOwnProperty(h)&&window.matchMedia("(max-width: ".concat(h,"px)")).matches)return l[h]}return a}};return Object.assign(s,u.match(o)),r.on("resize",window,throttle(function(){n.settings=mergeOptions(s,u.match(o))},n.settings.throttle)),t.on("update",function(){o=sortBreakpoints(o),a=Object.assign({},s)}),t.on("destroy",function(){r.off("resize",window)}),u}var COMPONENTS={Html,Translate,Transition,Direction,Peek,Sizes,Gaps,Move,Clones,Resize,Build,Run,Swipe,Images,Anchors,Controls,Keyboard,Autoplay,Breakpoints},Glide=function(n){_inherits(t,n);var e=_createSuper(t);function t(){return _classCallCheck(this,t),e.apply(this,arguments)}return _createClass(t,[{key:"mount",value:function(){var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return _get(_getPrototypeOf(t.prototype),"mount",this).call(this,Object.assign({},COMPONENTS,s))}}]),t}(Glide$1);const htmlDecodeTree=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(n=>n.charCodeAt(0))),xmlDecodeTree=new Uint16Array("Ȁaglq \x1Bɭ\0\0p;䀦os;䀧t;䀾t;䀼uot;䀢".split("").map(n=>n.charCodeAt(0)));var _a;const decodeMap=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),fromCodePoint=(_a=String.fromCodePoint)!==null&&_a!==void 0?_a:function(n){let e="";return n>65535&&(n-=65536,e+=String.fromCharCode(n>>>10&1023|55296),n=56320|n&1023),e+=String.fromCharCode(n),e};function replaceCodePoint(n){var e;return n>=55296&&n<=57343||n>1114111?65533:(e=decodeMap.get(n))!==null&&e!==void 0?e:n}var CharCodes$1;(function(n){n[n.NUM=35]="NUM",n[n.SEMI=59]="SEMI",n[n.EQUALS=61]="EQUALS",n[n.ZERO=48]="ZERO",n[n.NINE=57]="NINE",n[n.LOWER_A=97]="LOWER_A",n[n.LOWER_F=102]="LOWER_F",n[n.LOWER_X=120]="LOWER_X",n[n.LOWER_Z=122]="LOWER_Z",n[n.UPPER_A=65]="UPPER_A",n[n.UPPER_F=70]="UPPER_F",n[n.UPPER_Z=90]="UPPER_Z"})(CharCodes$1||(CharCodes$1={}));const TO_LOWER_BIT=32;var BinTrieFlags;(function(n){n[n.VALUE_LENGTH=49152]="VALUE_LENGTH",n[n.BRANCH_LENGTH=16256]="BRANCH_LENGTH",n[n.JUMP_TABLE=127]="JUMP_TABLE"})(BinTrieFlags||(BinTrieFlags={}));function isNumber(n){return n>=CharCodes$1.ZERO&&n<=CharCodes$1.NINE}function isHexadecimalCharacter(n){return n>=CharCodes$1.UPPER_A&&n<=CharCodes$1.UPPER_F||n>=CharCodes$1.LOWER_A&&n<=CharCodes$1.LOWER_F}function isAsciiAlphaNumeric(n){return n>=CharCodes$1.UPPER_A&&n<=CharCodes$1.UPPER_Z||n>=CharCodes$1.LOWER_A&&n<=CharCodes$1.LOWER_Z||isNumber(n)}function isEntityInAttributeInvalidEnd(n){return n===CharCodes$1.EQUALS||isAsciiAlphaNumeric(n)}var EntityDecoderState;(function(n){n[n.EntityStart=0]="EntityStart",n[n.NumericStart=1]="NumericStart",n[n.NumericDecimal=2]="NumericDecimal",n[n.NumericHex=3]="NumericHex",n[n.NamedEntity=4]="NamedEntity"})(EntityDecoderState||(EntityDecoderState={}));var DecodingMode;(function(n){n[n.Legacy=0]="Legacy",n[n.Strict=1]="Strict",n[n.Attribute=2]="Attribute"})(DecodingMode||(DecodingMode={}));class EntityDecoder{constructor(e,t,r){this.decodeTree=e,this.emitCodePoint=t,this.errors=r,this.state=EntityDecoderState.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=DecodingMode.Strict}startEntity(e){this.decodeMode=e,this.state=EntityDecoderState.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(e,t){switch(this.state){case EntityDecoderState.EntityStart:return e.charCodeAt(t)===CharCodes$1.NUM?(this.state=EntityDecoderState.NumericStart,this.consumed+=1,this.stateNumericStart(e,t+1)):(this.state=EntityDecoderState.NamedEntity,this.stateNamedEntity(e,t));case EntityDecoderState.NumericStart:return this.stateNumericStart(e,t);case EntityDecoderState.NumericDecimal:return this.stateNumericDecimal(e,t);case EntityDecoderState.NumericHex:return this.stateNumericHex(e,t);case EntityDecoderState.NamedEntity:return this.stateNamedEntity(e,t)}}stateNumericStart(e,t){return t>=e.length?-1:(e.charCodeAt(t)|TO_LOWER_BIT)===CharCodes$1.LOWER_X?(this.state=EntityDecoderState.NumericHex,this.consumed+=1,this.stateNumericHex(e,t+1)):(this.state=EntityDecoderState.NumericDecimal,this.stateNumericDecimal(e,t))}addToNumericResult(e,t,r,s){if(t!==r){const o=r-t;this.result=this.result*Math.pow(s,o)+Number.parseInt(e.substr(t,o),s),this.consumed+=o}}stateNumericHex(e,t){const r=t;for(;t<e.length;){const s=e.charCodeAt(t);if(isNumber(s)||isHexadecimalCharacter(s))t+=1;else return this.addToNumericResult(e,r,t,16),this.emitNumericEntity(s,3)}return this.addToNumericResult(e,r,t,16),-1}stateNumericDecimal(e,t){const r=t;for(;t<e.length;){const s=e.charCodeAt(t);if(isNumber(s))t+=1;else return this.addToNumericResult(e,r,t,10),this.emitNumericEntity(s,2)}return this.addToNumericResult(e,r,t,10),-1}emitNumericEntity(e,t){var r;if(this.consumed<=t)return(r=this.errors)===null||r===void 0||r.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(e===CharCodes$1.SEMI)this.consumed+=1;else if(this.decodeMode===DecodingMode.Strict)return 0;return this.emitCodePoint(replaceCodePoint(this.result),this.consumed),this.errors&&(e!==CharCodes$1.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(e,t){const{decodeTree:r}=this;let s=r[this.treeIndex],o=(s&BinTrieFlags.VALUE_LENGTH)>>14;for(;t<e.length;t++,this.excess++){const a=e.charCodeAt(t);if(this.treeIndex=determineBranch(r,s,this.treeIndex+Math.max(1,o),a),this.treeIndex<0)return this.result===0||this.decodeMode===DecodingMode.Attribute&&(o===0||isEntityInAttributeInvalidEnd(a))?0:this.emitNotTerminatedNamedEntity();if(s=r[this.treeIndex],o=(s&BinTrieFlags.VALUE_LENGTH)>>14,o!==0){if(a===CharCodes$1.SEMI)return this.emitNamedEntityData(this.treeIndex,o,this.consumed+this.excess);this.decodeMode!==DecodingMode.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var e;const{result:t,decodeTree:r}=this,s=(r[t]&BinTrieFlags.VALUE_LENGTH)>>14;return this.emitNamedEntityData(t,s,this.consumed),(e=this.errors)===null||e===void 0||e.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(e,t,r){const{decodeTree:s}=this;return this.emitCodePoint(t===1?s[e]&~BinTrieFlags.VALUE_LENGTH:s[e+1],r),t===3&&this.emitCodePoint(s[e+2],r),r}end(){var e;switch(this.state){case EntityDecoderState.NamedEntity:return this.result!==0&&(this.decodeMode!==DecodingMode.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case EntityDecoderState.NumericDecimal:return this.emitNumericEntity(0,2);case EntityDecoderState.NumericHex:return this.emitNumericEntity(0,3);case EntityDecoderState.NumericStart:return(e=this.errors)===null||e===void 0||e.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case EntityDecoderState.EntityStart:return 0}}}function determineBranch(n,e,t,r){const s=(e&BinTrieFlags.BRANCH_LENGTH)>>7,o=e&BinTrieFlags.JUMP_TABLE;if(s===0)return o!==0&&r===o?t:-1;if(o){const c=r-o;return c<0||c>=s?-1:n[t+c]-1}let a=t,u=a+s-1;for(;a<=u;){const c=a+u>>>1,l=n[c];if(l<r)a=c+1;else if(l>r)u=c-1;else return n[c+s]}return-1}var CharCodes;(function(n){n[n.Tab=9]="Tab",n[n.NewLine=10]="NewLine",n[n.FormFeed=12]="FormFeed",n[n.CarriageReturn=13]="CarriageReturn",n[n.Space=32]="Space",n[n.ExclamationMark=33]="ExclamationMark",n[n.Number=35]="Number",n[n.Amp=38]="Amp",n[n.SingleQuote=39]="SingleQuote",n[n.DoubleQuote=34]="DoubleQuote",n[n.Dash=45]="Dash",n[n.Slash=47]="Slash",n[n.Zero=48]="Zero",n[n.Nine=57]="Nine",n[n.Semi=59]="Semi",n[n.Lt=60]="Lt",n[n.Eq=61]="Eq",n[n.Gt=62]="Gt",n[n.Questionmark=63]="Questionmark",n[n.UpperA=65]="UpperA",n[n.LowerA=97]="LowerA",n[n.UpperF=70]="UpperF",n[n.LowerF=102]="LowerF",n[n.UpperZ=90]="UpperZ",n[n.LowerZ=122]="LowerZ",n[n.LowerX=120]="LowerX",n[n.OpeningSquareBracket=91]="OpeningSquareBracket"})(CharCodes||(CharCodes={}));var State;(function(n){n[n.Text=1]="Text",n[n.BeforeTagName=2]="BeforeTagName",n[n.InTagName=3]="InTagName",n[n.InSelfClosingTag=4]="InSelfClosingTag",n[n.BeforeClosingTagName=5]="BeforeClosingTagName",n[n.InClosingTagName=6]="InClosingTagName",n[n.AfterClosingTagName=7]="AfterClosingTagName",n[n.BeforeAttributeName=8]="BeforeAttributeName",n[n.InAttributeName=9]="InAttributeName",n[n.AfterAttributeName=10]="AfterAttributeName",n[n.BeforeAttributeValue=11]="BeforeAttributeValue",n[n.InAttributeValueDq=12]="InAttributeValueDq",n[n.InAttributeValueSq=13]="InAttributeValueSq",n[n.InAttributeValueNq=14]="InAttributeValueNq",n[n.BeforeDeclaration=15]="BeforeDeclaration",n[n.InDeclaration=16]="InDeclaration",n[n.InProcessingInstruction=17]="InProcessingInstruction",n[n.BeforeComment=18]="BeforeComment",n[n.CDATASequence=19]="CDATASequence",n[n.InSpecialComment=20]="InSpecialComment",n[n.InCommentLike=21]="InCommentLike",n[n.BeforeSpecialS=22]="BeforeSpecialS",n[n.BeforeSpecialT=23]="BeforeSpecialT",n[n.SpecialStartSequence=24]="SpecialStartSequence",n[n.InSpecialTag=25]="InSpecialTag",n[n.InEntity=26]="InEntity"})(State||(State={}));function isWhitespace(n){return n===CharCodes.Space||n===CharCodes.NewLine||n===CharCodes.Tab||n===CharCodes.FormFeed||n===CharCodes.CarriageReturn}function isEndOfTagSection(n){return n===CharCodes.Slash||n===CharCodes.Gt||isWhitespace(n)}function isASCIIAlpha(n){return n>=CharCodes.LowerA&&n<=CharCodes.LowerZ||n>=CharCodes.UpperA&&n<=CharCodes.UpperZ}var QuoteType;(function(n){n[n.NoValue=0]="NoValue",n[n.Unquoted=1]="Unquoted",n[n.Single=2]="Single",n[n.Double=3]="Double"})(QuoteType||(QuoteType={}));const Sequences={Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,62]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])};class Tokenizer{constructor({xmlMode:e=!1,decodeEntities:t=!0},r){this.cbs=r,this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.entityStart=0,this.baseState=State.Text,this.isSpecial=!1,this.running=!0,this.offset=0,this.currentSequence=void 0,this.sequenceIndex=0,this.xmlMode=e,this.decodeEntities=t,this.entityDecoder=new EntityDecoder(e?xmlDecodeTree:htmlDecodeTree,(s,o)=>this.emitCodePoint(s,o))}reset(){this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=State.Text,this.currentSequence=void 0,this.running=!0,this.offset=0}write(e){this.offset+=this.buffer.length,this.buffer=e,this.parse()}end(){this.running&&this.finish()}pause(){this.running=!1}resume(){this.running=!0,this.index<this.buffer.length+this.offset&&this.parse()}stateText(e){e===CharCodes.Lt||!this.decodeEntities&&this.fastForwardTo(CharCodes.Lt)?(this.index>this.sectionStart&&this.cbs.ontext(this.sectionStart,this.index),this.state=State.BeforeTagName,this.sectionStart=this.index):this.decodeEntities&&e===CharCodes.Amp&&this.startEntity()}stateSpecialStartSequence(e){const t=this.sequenceIndex===this.currentSequence.length;if(!(t?isEndOfTagSection(e):(e|32)===this.currentSequence[this.sequenceIndex]))this.isSpecial=!1;else if(!t){this.sequenceIndex++;return}this.sequenceIndex=0,this.state=State.InTagName,this.stateInTagName(e)}stateInSpecialTag(e){if(this.sequenceIndex===this.currentSequence.length){if(e===CharCodes.Gt||isWhitespace(e)){const t=this.index-this.currentSequence.length;if(this.sectionStart<t){const r=this.index;this.index=t,this.cbs.ontext(this.sectionStart,t),this.index=r}this.isSpecial=!1,this.sectionStart=t+2,this.stateInClosingTagName(e);return}this.sequenceIndex=0}(e|32)===this.currentSequence[this.sequenceIndex]?this.sequenceIndex+=1:this.sequenceIndex===0?this.currentSequence===Sequences.TitleEnd?this.decodeEntities&&e===CharCodes.Amp&&this.startEntity():this.fastForwardTo(CharCodes.Lt)&&(this.sequenceIndex=1):this.sequenceIndex=+(e===CharCodes.Lt)}stateCDATASequence(e){e===Sequences.Cdata[this.sequenceIndex]?++this.sequenceIndex===Sequences.Cdata.length&&(this.state=State.InCommentLike,this.currentSequence=Sequences.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1):(this.sequenceIndex=0,this.state=State.InDeclaration,this.stateInDeclaration(e))}fastForwardTo(e){for(;++this.index<this.buffer.length+this.offset;)if(this.buffer.charCodeAt(this.index-this.offset)===e)return!0;return this.index=this.buffer.length+this.offset-1,!1}stateInCommentLike(e){e===this.currentSequence[this.sequenceIndex]?++this.sequenceIndex===this.currentSequence.length&&(this.currentSequence===Sequences.CdataEnd?this.cbs.oncdata(this.sectionStart,this.index,2):this.cbs.oncomment(this.sectionStart,this.index,2),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text):this.sequenceIndex===0?this.fastForwardTo(this.currentSequence[0])&&(this.sequenceIndex=1):e!==this.currentSequence[this.sequenceIndex-1]&&(this.sequenceIndex=0)}isTagStartChar(e){return this.xmlMode?!isEndOfTagSection(e):isASCIIAlpha(e)}startSpecial(e,t){this.isSpecial=!0,this.currentSequence=e,this.sequenceIndex=t,this.state=State.SpecialStartSequence}stateBeforeTagName(e){if(e===CharCodes.ExclamationMark)this.state=State.BeforeDeclaration,this.sectionStart=this.index+1;else if(e===CharCodes.Questionmark)this.state=State.InProcessingInstruction,this.sectionStart=this.index+1;else if(this.isTagStartChar(e)){const t=e|32;this.sectionStart=this.index,this.xmlMode?this.state=State.InTagName:t===Sequences.ScriptEnd[2]?this.state=State.BeforeSpecialS:t===Sequences.TitleEnd[2]||t===Sequences.XmpEnd[2]?this.state=State.BeforeSpecialT:this.state=State.InTagName}else e===CharCodes.Slash?this.state=State.BeforeClosingTagName:(this.state=State.Text,this.stateText(e))}stateInTagName(e){isEndOfTagSection(e)&&(this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e))}stateBeforeClosingTagName(e){isWhitespace(e)||(e===CharCodes.Gt?this.state=State.Text:(this.state=this.isTagStartChar(e)?State.InClosingTagName:State.InSpecialComment,this.sectionStart=this.index))}stateInClosingTagName(e){(e===CharCodes.Gt||isWhitespace(e))&&(this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.AfterClosingTagName,this.stateAfterClosingTagName(e))}stateAfterClosingTagName(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeAttributeName(e){e===CharCodes.Gt?(this.cbs.onopentagend(this.index),this.isSpecial?(this.state=State.InSpecialTag,this.sequenceIndex=0):this.state=State.Text,this.sectionStart=this.index+1):e===CharCodes.Slash?this.state=State.InSelfClosingTag:isWhitespace(e)||(this.state=State.InAttributeName,this.sectionStart=this.index)}stateInSelfClosingTag(e){e===CharCodes.Gt?(this.cbs.onselfclosingtag(this.index),this.state=State.Text,this.sectionStart=this.index+1,this.isSpecial=!1):isWhitespace(e)||(this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e))}stateInAttributeName(e){(e===CharCodes.Eq||isEndOfTagSection(e))&&(this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=State.AfterAttributeName,this.stateAfterAttributeName(e))}stateAfterAttributeName(e){e===CharCodes.Eq?this.state=State.BeforeAttributeValue:e===CharCodes.Slash||e===CharCodes.Gt?(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e)):isWhitespace(e)||(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.state=State.InAttributeName,this.sectionStart=this.index)}stateBeforeAttributeValue(e){e===CharCodes.DoubleQuote?(this.state=State.InAttributeValueDq,this.sectionStart=this.index+1):e===CharCodes.SingleQuote?(this.state=State.InAttributeValueSq,this.sectionStart=this.index+1):isWhitespace(e)||(this.sectionStart=this.index,this.state=State.InAttributeValueNq,this.stateInAttributeValueNoQuotes(e))}handleInAttributeValue(e,t){e===t||!this.decodeEntities&&this.fastForwardTo(t)?(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(t===CharCodes.DoubleQuote?QuoteType.Double:QuoteType.Single,this.index+1),this.state=State.BeforeAttributeName):this.decodeEntities&&e===CharCodes.Amp&&this.startEntity()}stateInAttributeValueDoubleQuotes(e){this.handleInAttributeValue(e,CharCodes.DoubleQuote)}stateInAttributeValueSingleQuotes(e){this.handleInAttributeValue(e,CharCodes.SingleQuote)}stateInAttributeValueNoQuotes(e){isWhitespace(e)||e===CharCodes.Gt?(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(QuoteType.Unquoted,this.index),this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(e)):this.decodeEntities&&e===CharCodes.Amp&&this.startEntity()}stateBeforeDeclaration(e){e===CharCodes.OpeningSquareBracket?(this.state=State.CDATASequence,this.sequenceIndex=0):this.state=e===CharCodes.Dash?State.BeforeComment:State.InDeclaration}stateInDeclaration(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.cbs.ondeclaration(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1)}stateInProcessingInstruction(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.cbs.onprocessinginstruction(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeComment(e){e===CharCodes.Dash?(this.state=State.InCommentLike,this.currentSequence=Sequences.CommentEnd,this.sequenceIndex=2,this.sectionStart=this.index+1):this.state=State.InDeclaration}stateInSpecialComment(e){(e===CharCodes.Gt||this.fastForwardTo(CharCodes.Gt))&&(this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeSpecialS(e){const t=e|32;t===Sequences.ScriptEnd[3]?this.startSpecial(Sequences.ScriptEnd,4):t===Sequences.StyleEnd[3]?this.startSpecial(Sequences.StyleEnd,4):(this.state=State.InTagName,this.stateInTagName(e))}stateBeforeSpecialT(e){switch(e|32){case Sequences.TitleEnd[3]:{this.startSpecial(Sequences.TitleEnd,4);break}case Sequences.TextareaEnd[3]:{this.startSpecial(Sequences.TextareaEnd,4);break}case Sequences.XmpEnd[3]:{this.startSpecial(Sequences.XmpEnd,4);break}default:this.state=State.InTagName,this.stateInTagName(e)}}startEntity(){this.baseState=this.state,this.state=State.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?DecodingMode.Strict:this.baseState===State.Text||this.baseState===State.InSpecialTag?DecodingMode.Legacy:DecodingMode.Attribute)}stateInEntity(){const e=this.entityDecoder.write(this.buffer,this.index-this.offset);e>=0?(this.state=this.baseState,e===0&&(this.index=this.entityStart)):this.index=this.offset+this.buffer.length-1}cleanup(){this.running&&this.sectionStart!==this.index&&(this.state===State.Text||this.state===State.InSpecialTag&&this.sequenceIndex===0?(this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index):(this.state===State.InAttributeValueDq||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueNq)&&(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index))}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){for(;this.shouldContinue();){const e=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case State.Text:{this.stateText(e);break}case State.SpecialStartSequence:{this.stateSpecialStartSequence(e);break}case State.InSpecialTag:{this.stateInSpecialTag(e);break}case State.CDATASequence:{this.stateCDATASequence(e);break}case State.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(e);break}case State.InAttributeName:{this.stateInAttributeName(e);break}case State.InCommentLike:{this.stateInCommentLike(e);break}case State.InSpecialComment:{this.stateInSpecialComment(e);break}case State.BeforeAttributeName:{this.stateBeforeAttributeName(e);break}case State.InTagName:{this.stateInTagName(e);break}case State.InClosingTagName:{this.stateInClosingTagName(e);break}case State.BeforeTagName:{this.stateBeforeTagName(e);break}case State.AfterAttributeName:{this.stateAfterAttributeName(e);break}case State.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(e);break}case State.BeforeAttributeValue:{this.stateBeforeAttributeValue(e);break}case State.BeforeClosingTagName:{this.stateBeforeClosingTagName(e);break}case State.AfterClosingTagName:{this.stateAfterClosingTagName(e);break}case State.BeforeSpecialS:{this.stateBeforeSpecialS(e);break}case State.BeforeSpecialT:{this.stateBeforeSpecialT(e);break}case State.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(e);break}case State.InSelfClosingTag:{this.stateInSelfClosingTag(e);break}case State.InDeclaration:{this.stateInDeclaration(e);break}case State.BeforeDeclaration:{this.stateBeforeDeclaration(e);break}case State.BeforeComment:{this.stateBeforeComment(e);break}case State.InProcessingInstruction:{this.stateInProcessingInstruction(e);break}case State.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){this.state===State.InEntity&&(this.entityDecoder.end(),this.state=this.baseState),this.handleTrailingData(),this.cbs.onend()}handleTrailingData(){const e=this.buffer.length+this.offset;this.sectionStart>=e||(this.state===State.InCommentLike?this.currentSequence===Sequences.CdataEnd?this.cbs.oncdata(this.sectionStart,e,0):this.cbs.oncomment(this.sectionStart,e,0):this.state===State.InTagName||this.state===State.BeforeAttributeName||this.state===State.BeforeAttributeValue||this.state===State.AfterAttributeName||this.state===State.InAttributeName||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueDq||this.state===State.InAttributeValueNq||this.state===State.InClosingTagName||this.cbs.ontext(this.sectionStart,e))}emitCodePoint(e,t){this.baseState!==State.Text&&this.baseState!==State.InSpecialTag?(this.sectionStart<this.entityStart&&this.cbs.onattribdata(this.sectionStart,this.entityStart),this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.onattribentity(e)):(this.sectionStart<this.entityStart&&this.cbs.ontext(this.sectionStart,this.entityStart),this.sectionStart=this.entityStart+t,this.index=this.sectionStart-1,this.cbs.ontextentity(e,this.sectionStart))}}const formTags=new Set(["input","option","optgroup","select","button","datalist","textarea"]),pTag=new Set(["p"]),tableSectionTags=new Set(["thead","tbody"]),ddtTags=new Set(["dd","dt"]),rtpTags=new Set(["rt","rp"]),openImpliesClose=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["li",new Set(["li"])],["p",pTag],["h1",pTag],["h2",pTag],["h3",pTag],["h4",pTag],["h5",pTag],["h6",pTag],["select",formTags],["input",formTags],["output",formTags],["button",formTags],["datalist",formTags],["textarea",formTags],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",ddtTags],["dt",ddtTags],["address",pTag],["article",pTag],["aside",pTag],["blockquote",pTag],["details",pTag],["div",pTag],["dl",pTag],["fieldset",pTag],["figcaption",pTag],["figure",pTag],["footer",pTag],["form",pTag],["header",pTag],["hr",pTag],["main",pTag],["nav",pTag],["ol",pTag],["pre",pTag],["section",pTag],["table",pTag],["ul",pTag],["rt",rtpTags],["rp",rtpTags],["tbody",tableSectionTags],["tfoot",tableSectionTags]]),voidElements=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),foreignContextElements=new Set(["math","svg"]),htmlIntegrationElements=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignobject","desc","title"]),reNameEnd=/\s|\//;class Parser{constructor(e,t={}){var r,s,o,a,u,c;this.options=t,this.startIndex=0,this.endIndex=0,this.openTagStart=0,this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack=[],this.buffers=[],this.bufferOffset=0,this.writeIndex=0,this.ended=!1,this.cbs=e??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=(r=t.lowerCaseTags)!==null&&r!==void 0?r:this.htmlMode,this.lowerCaseAttributeNames=(s=t.lowerCaseAttributeNames)!==null&&s!==void 0?s:this.htmlMode,this.recognizeSelfClosing=(o=t.recognizeSelfClosing)!==null&&o!==void 0?o:!this.htmlMode,this.tokenizer=new((a=t.Tokenizer)!==null&&a!==void 0?a:Tokenizer)(this.options,this),this.foreignContext=[!this.htmlMode],(c=(u=this.cbs).onparserinit)===null||c===void 0||c.call(u,this)}ontext(e,t){var r,s;const o=this.getSlice(e,t);this.endIndex=t-1,(s=(r=this.cbs).ontext)===null||s===void 0||s.call(r,o),this.startIndex=t}ontextentity(e,t){var r,s;this.endIndex=t-1,(s=(r=this.cbs).ontext)===null||s===void 0||s.call(r,fromCodePoint(e)),this.startIndex=t}isVoidElement(e){return this.htmlMode&&voidElements.has(e)}onopentagname(e,t){this.endIndex=t;let r=this.getSlice(e,t);this.lowerCaseTagNames&&(r=r.toLowerCase()),this.emitOpenTag(r)}emitOpenTag(e){var t,r,s,o;this.openTagStart=this.startIndex,this.tagname=e;const a=this.htmlMode&&openImpliesClose.get(e);if(a)for(;this.stack.length>0&&a.has(this.stack[0]);){const u=this.stack.shift();(r=(t=this.cbs).onclosetag)===null||r===void 0||r.call(t,u,!0)}this.isVoidElement(e)||(this.stack.unshift(e),this.htmlMode&&(foreignContextElements.has(e)?this.foreignContext.unshift(!0):htmlIntegrationElements.has(e)&&this.foreignContext.unshift(!1))),(o=(s=this.cbs).onopentagname)===null||o===void 0||o.call(s,e),this.cbs.onopentag&&(this.attribs={})}endOpenTag(e){var t,r;this.startIndex=this.openTagStart,this.attribs&&((r=(t=this.cbs).onopentag)===null||r===void 0||r.call(t,this.tagname,this.attribs,e),this.attribs=null),this.cbs.onclosetag&&this.isVoidElement(this.tagname)&&this.cbs.onclosetag(this.tagname,!0),this.tagname=""}onopentagend(e){this.endIndex=e,this.endOpenTag(!1),this.startIndex=e+1}onclosetag(e,t){var r,s,o,a,u,c,l,h;this.endIndex=t;let f=this.getSlice(e,t);if(this.lowerCaseTagNames&&(f=f.toLowerCase()),this.htmlMode&&(foreignContextElements.has(f)||htmlIntegrationElements.has(f))&&this.foreignContext.shift(),this.isVoidElement(f))this.htmlMode&&f==="br"&&((a=(o=this.cbs).onopentagname)===null||a===void 0||a.call(o,"br"),(c=(u=this.cbs).onopentag)===null||c===void 0||c.call(u,"br",{},!0),(h=(l=this.cbs).onclosetag)===null||h===void 0||h.call(l,"br",!1));else{const p=this.stack.indexOf(f);if(p!==-1)for(let b=0;b<=p;b++){const v=this.stack.shift();(s=(r=this.cbs).onclosetag)===null||s===void 0||s.call(r,v,b!==p)}else this.htmlMode&&f==="p"&&(this.emitOpenTag("p"),this.closeCurrentTag(!0))}this.startIndex=t+1}onselfclosingtag(e){this.endIndex=e,this.recognizeSelfClosing||this.foreignContext[0]?(this.closeCurrentTag(!1),this.startIndex=e+1):this.onopentagend(e)}closeCurrentTag(e){var t,r;const s=this.tagname;this.endOpenTag(e),this.stack[0]===s&&((r=(t=this.cbs).onclosetag)===null||r===void 0||r.call(t,s,!e),this.stack.shift())}onattribname(e,t){this.startIndex=e;const r=this.getSlice(e,t);this.attribname=this.lowerCaseAttributeNames?r.toLowerCase():r}onattribdata(e,t){this.attribvalue+=this.getSlice(e,t)}onattribentity(e){this.attribvalue+=fromCodePoint(e)}onattribend(e,t){var r,s;this.endIndex=t,(s=(r=this.cbs).onattribute)===null||s===void 0||s.call(r,this.attribname,this.attribvalue,e===QuoteType.Double?'"':e===QuoteType.Single?"'":e===QuoteType.NoValue?void 0:null),this.attribs&&!Object.prototype.hasOwnProperty.call(this.attribs,this.attribname)&&(this.attribs[this.attribname]=this.attribvalue),this.attribvalue=""}getInstructionName(e){const t=e.search(reNameEnd);let r=t<0?e:e.substr(0,t);return this.lowerCaseTagNames&&(r=r.toLowerCase()),r}ondeclaration(e,t){this.endIndex=t;const r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){const s=this.getInstructionName(r);this.cbs.onprocessinginstruction(`!${s}`,`!${r}`)}this.startIndex=t+1}onprocessinginstruction(e,t){this.endIndex=t;const r=this.getSlice(e,t);if(this.cbs.onprocessinginstruction){const s=this.getInstructionName(r);this.cbs.onprocessinginstruction(`?${s}`,`?${r}`)}this.startIndex=t+1}oncomment(e,t,r){var s,o,a,u;this.endIndex=t,(o=(s=this.cbs).oncomment)===null||o===void 0||o.call(s,this.getSlice(e,t-r)),(u=(a=this.cbs).oncommentend)===null||u===void 0||u.call(a),this.startIndex=t+1}oncdata(e,t,r){var s,o,a,u,c,l,h,f,p,b;this.endIndex=t;const v=this.getSlice(e,t-r);!this.htmlMode||this.options.recognizeCDATA?((o=(s=this.cbs).oncdatastart)===null||o===void 0||o.call(s),(u=(a=this.cbs).ontext)===null||u===void 0||u.call(a,v),(l=(c=this.cbs).oncdataend)===null||l===void 0||l.call(c)):((f=(h=this.cbs).oncomment)===null||f===void 0||f.call(h,`[CDATA[${v}]]`),(b=(p=this.cbs).oncommentend)===null||b===void 0||b.call(p)),this.startIndex=t+1}onend(){var e,t;if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let r=0;r<this.stack.length;r++)this.cbs.onclosetag(this.stack[r],!0)}(t=(e=this.cbs).onend)===null||t===void 0||t.call(e)}reset(){var e,t,r,s;(t=(e=this.cbs).onreset)===null||t===void 0||t.call(e),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,(s=(r=this.cbs).onparserinit)===null||s===void 0||s.call(r,this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(!this.htmlMode),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(e){this.reset(),this.end(e)}getSlice(e,t){for(;e-this.bufferOffset>=this.buffers[0].length;)this.shiftBuffer();let r=this.buffers[0].slice(e-this.bufferOffset,t-this.bufferOffset);for(;t-this.bufferOffset>this.buffers[0].length;)this.shiftBuffer(),r+=this.buffers[0].slice(0,t-this.bufferOffset);return r}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(e){var t,r;if(this.ended){(r=(t=this.cbs).onerror)===null||r===void 0||r.call(t,new Error(".write() after done!"));return}this.buffers.push(e),this.tokenizer.running&&(this.tokenizer.write(e),this.writeIndex++)}end(e){var t,r;if(this.ended){(r=(t=this.cbs).onerror)===null||r===void 0||r.call(t,new Error(".end() after done!"));return}e&&this.write(e),this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){for(this.tokenizer.resume();this.tokenizer.running&&this.writeIndex<this.buffers.length;)this.tokenizer.write(this.buffers[this.writeIndex++]);this.ended&&this.tokenizer.end()}parseChunk(e){this.write(e)}done(e){this.end(e)}}var ElementType$2;(function(n){n.Root="root",n.Text="text",n.Directive="directive",n.Comment="comment",n.Script="script",n.Style="style",n.Tag="tag",n.CDATA="cdata",n.Doctype="doctype"})(ElementType$2||(ElementType$2={}));function isTag$1(n){return n.type===ElementType$2.Tag||n.type===ElementType$2.Script||n.type===ElementType$2.Style}ElementType$2.Root,ElementType$2.Text,ElementType$2.Directive,ElementType$2.Comment,ElementType$2.Script,ElementType$2.Style,ElementType$2.Tag,ElementType$2.CDATA,ElementType$2.Doctype;function isTag(n){return isTag$1(n)}function hasChildren(n){return Object.prototype.hasOwnProperty.call(n,"children")}var ElementType$1;(function(n){n.Root="root",n.Text="text",n.Directive="directive",n.Comment="comment",n.Script="script",n.Style="style",n.Tag="tag",n.CDATA="cdata",n.Doctype="doctype"})(ElementType$1||(ElementType$1={}));const Root=ElementType$1.Root,Text=ElementType$1.Text,Directive=ElementType$1.Directive,Comment=ElementType$1.Comment,Script=ElementType$1.Script,Style=ElementType$1.Style,Tag=ElementType$1.Tag,CDATA=ElementType$1.CDATA,Doctype=ElementType$1.Doctype,xmlReplacer=/["&'<>$\x80-\uFFFF]/g,xmlCodeMap=new Map([[34,"&quot;"],[38,"&amp;"],[39,"&apos;"],[60,"&lt;"],[62,"&gt;"]]),getCodePoint=String.prototype.codePointAt!=null?(n,e)=>n.codePointAt(e):(n,e)=>(n.charCodeAt(e)&64512)===55296?(n.charCodeAt(e)-55296)*1024+n.charCodeAt(e+1)-56320+65536:n.charCodeAt(e);function encodeXML(n){let e="",t=0,r;for(;(r=xmlReplacer.exec(n))!==null;){const s=r.index,o=n.charCodeAt(s),a=xmlCodeMap.get(o);a!==void 0?(e+=n.substring(t,s)+a,t=s+1):(e+=`${n.substring(t,s)}&#x${getCodePoint(n,s).toString(16)};`,t=xmlReplacer.lastIndex+=+((o&64512)===55296))}return e+n.substr(t)}function getEscaper(n,e){return function(r){let s,o=0,a="";for(;s=n.exec(r);)o!==s.index&&(a+=r.substring(o,s.index)),a+=e.get(s[0].charCodeAt(0)),o=s.index+1;return a+r.substring(o)}}const escapeAttribute=getEscaper(/["&\u00A0]/g,new Map([[34,"&quot;"],[38,"&amp;"],[160,"&nbsp;"]])),escapeText=getEscaper(/[&<>\u00A0]/g,new Map([[38,"&amp;"],[60,"&lt;"],[62,"&gt;"],[160,"&nbsp;"]])),elementNames=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(n=>[n.toLowerCase(),n])),attributeNames=new Map(["definitionURL","attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(n=>[n.toLowerCase(),n])),unencodedElements=new Set(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]);function replaceQuotes(n){return n.replace(/"/g,"&quot;")}function formatAttributes(n,e){var t;if(!n)return;const r=((t=e.encodeEntities)!==null&&t!==void 0?t:e.decodeEntities)===!1?replaceQuotes:e.xmlMode||e.encodeEntities!=="utf8"?encodeXML:escapeAttribute;return Object.keys(n).map(s=>{var o,a;const u=(o=n[s])!==null&&o!==void 0?o:"";return e.xmlMode==="foreign"&&(s=(a=attributeNames.get(s))!==null&&a!==void 0?a:s),!e.emptyAttrs&&!e.xmlMode&&u===""?s:`${s}="${r(u)}"`}).join(" ")}const singleTag=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]);function render(n,e={}){const t="length"in n?n:[n];let r="";for(let s=0;s<t.length;s++)r+=renderNode(t[s],e);return r}function renderNode(n,e){switch(n.type){case Root:return render(n.children,e);case Doctype:case Directive:return renderDirective(n);case Comment:return renderComment$1(n);case CDATA:return renderCdata(n);case Script:case Style:case Tag:return renderTag(n,e);case Text:return renderText(n,e)}}const foreignModeIntegrationPoints=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),foreignElements=new Set(["svg","math"]);function renderTag(n,e){var t;e.xmlMode==="foreign"&&(n.name=(t=elementNames.get(n.name))!==null&&t!==void 0?t:n.name,n.parent&&foreignModeIntegrationPoints.has(n.parent.name)&&(e={...e,xmlMode:!1})),!e.xmlMode&&foreignElements.has(n.name)&&(e={...e,xmlMode:"foreign"});let r=`<${n.name}`;const s=formatAttributes(n.attribs,e);return s&&(r+=` ${s}`),n.children.length===0&&(e.xmlMode?e.selfClosingTags!==!1:e.selfClosingTags&&singleTag.has(n.name))?(e.xmlMode||(r+=" "),r+="/>"):(r+=">",n.children.length>0&&(r+=render(n.children,e)),(e.xmlMode||!singleTag.has(n.name))&&(r+=`</${n.name}>`)),r}function renderDirective(n){return`<${n.data}>`}function renderText(n,e){var t;let r=n.data||"";return((t=e.encodeEntities)!==null&&t!==void 0?t:e.decodeEntities)!==!1&&!(!e.xmlMode&&n.parent&&unencodedElements.has(n.parent.name))&&(r=e.xmlMode||e.encodeEntities!=="utf8"?encodeXML(r):escapeText(r)),r}function renderCdata(n){return`<![CDATA[${n.children[0].data}]]>`}function renderComment$1(n){return`<!--${n.data}-->`}function getOuterHTML(n,e){return render(n,e)}function findAll(n,e){const t=[],r=[Array.isArray(e)?e:[e]],s=[0];for(;;){if(s[0]>=r[0].length){if(r.length===1)return t;r.shift(),s.shift();continue}const o=r[0][s[0]++];isTag(o)&&n(o)&&t.push(o),hasChildren(o)&&o.children.length>0&&(s.unshift(0),r.unshift(o.children))}}var domelementtype={Text:"text",Directive:"directive",Comment:"comment",Script:"script",Style:"style",Tag:"tag",CDATA:"cdata"},node={exports:{}};node.exports={get firstChild(){var n=this.children;return n&&n[0]||null},get lastChild(){var n=this.children;return n&&n[n.length-1]||null},get nodeType(){return nodeTypes[this.type]||nodeTypes.element}};var domLvl1$1={tagName:"name",childNodes:"children",parentNode:"parent",previousSibling:"prev",nextSibling:"next",nodeValue:"data"},nodeTypes={element:1,text:3,cdata:4,comment:8};Object.keys(domLvl1$1).forEach(function(n){});var nodeExports=node.exports,element={exports:{}},NodePrototype$1=nodeExports,ElementPrototype$1=element.exports=Object.create(NodePrototype$1),domLvl1={tagName:"name"};Object.keys(domLvl1).forEach(function(n){var e=domLvl1[n];Object.defineProperty(ElementPrototype$1,n,{get:function(){return this[e]||null},set:function(t){return this[e]=t,t}})});var elementExports=element.exports,ElementType=domelementtype,re_whitespace=/\s+/g,NodePrototype=nodeExports,ElementPrototype=elementExports;function DomHandler(n,e,t){typeof n=="object"?(t=e,e=n,n=null):typeof e=="function"&&(t=e,e=defaultOpts),this._callback=n,this._options=e||defaultOpts,this._elementCB=t,this.dom=[],this._done=!1,this._tagStack=[],this._parser=this._parser||null}var defaultOpts={normalizeWhitespace:!1,withStartIndices:!1,withEndIndices:!1};DomHandler.prototype.onparserinit=function(n){this._parser=n},DomHandler.prototype.onreset=function(){DomHandler.call(this,this._callback,this._options,this._elementCB)},DomHandler.prototype.onend=function(){this._done||(this._done=!0,this._parser=null,this._handleCallback(null))},DomHandler.prototype._handleCallback=DomHandler.prototype.onerror=function(n){if(typeof this._callback=="function")this._callback(n,this.dom);else if(n)throw n},DomHandler.prototype.onclosetag=function(){var n=this._tagStack.pop();this._options.withEndIndices&&n&&(n.endIndex=this._parser.endIndex),this._elementCB&&this._elementCB(n)},DomHandler.prototype._createDomElement=function(n){if(!this._options.withDomLvl1)return n;var e;n.type==="tag"?e=Object.create(ElementPrototype):e=Object.create(NodePrototype);for(var t in n)n.hasOwnProperty(t)&&(e[t]=n[t]);return e},DomHandler.prototype._addDomElement=function(n){var e=this._tagStack[this._tagStack.length-1],t=e?e.children:this.dom,r=t[t.length-1];n.next=null,this._options.withStartIndices&&(n.startIndex=this._parser.startIndex),this._options.withEndIndices&&(n.endIndex=this._parser.endIndex),r?(n.prev=r,r.next=n):n.prev=null,t.push(n),n.parent=e||null},DomHandler.prototype.onopentag=function(n,e){var t={type:n==="script"?ElementType.Script:n==="style"?ElementType.Style:ElementType.Tag,name:n,attribs:e,children:[]},r=this._createDomElement(t);this._addDomElement(r),this._tagStack.push(r)},DomHandler.prototype.ontext=function(n){var e=this._options.normalizeWhitespace||this._options.ignoreWhitespace,t;if(!this._tagStack.length&&this.dom.length&&(t=this.dom[this.dom.length-1]).type===ElementType.Text)e?t.data=(t.data+n).replace(re_whitespace," "):t.data+=n;else if(this._tagStack.length&&(t=this._tagStack[this._tagStack.length-1])&&(t=t.children[t.children.length-1])&&t.type===ElementType.Text)e?t.data=(t.data+n).replace(re_whitespace," "):t.data+=n;else{e&&(n=n.replace(re_whitespace," "));var r=this._createDomElement({data:n,type:ElementType.Text});this._addDomElement(r)}},DomHandler.prototype.oncomment=function(n){var e=this._tagStack[this._tagStack.length-1];if(e&&e.type===ElementType.Comment){e.data+=n;return}var t={data:n,type:ElementType.Comment},r=this._createDomElement(t);this._addDomElement(r),this._tagStack.push(r)},DomHandler.prototype.oncdatastart=function(){var n={children:[{data:"",type:ElementType.Text}],type:ElementType.CDATA},e=this._createDomElement(n);this._addDomElement(e),this._tagStack.push(e)},DomHandler.prototype.oncommentend=DomHandler.prototype.oncdataend=function(){this._tagStack.pop()},DomHandler.prototype.onprocessinginstruction=function(n,e){var t=this._createDomElement({name:n,data:e,type:ElementType.Directive});this._addDomElement(t)};var domhandler=DomHandler;const replyIcon=`
336
336
  <svg width="18" height="18" fill="#00b3ff">
337
337
  <path xmlns="http://www.w3.org/2000/svg" d="M12.2197 1.65717C7.73973 1.25408 5.14439 0.940234 3.12891 2.6623C0.948817 4.52502 0.63207 7.66213 2.35603 9.88052C3.01043 10.7226 4.28767 11.9877 5.51513 13.1462C6.75696 14.3184 7.99593 15.426 8.60692 15.9671C8.61074 15.9705 8.61463 15.9739 8.61859 15.9774C8.67603 16.0283 8.74753 16.0917 8.81608 16.1433C8.89816 16.2052 9.01599 16.2819 9.17334 16.3288C9.38253 16.3912 9.60738 16.3912 9.81656 16.3288C9.97391 16.2819 10.0917 16.2052 10.1738 16.1433C10.2424 16.0917 10.3139 16.0283 10.3713 15.9774C10.3753 15.9739 10.3792 15.9705 10.383 15.9671C10.994 15.426 12.2329 14.3184 13.4748 13.1462C14.7022 11.9877 15.9795 10.7226 16.6339 9.88052C18.3512 7.67065 18.0834 4.50935 15.8532 2.65572C13.8153 0.961905 11.2476 1.25349 9.49466 2.78774Z"/>
338
338
  </svg>
@@ -533,7 +533,7 @@ ${u}`)}return t}async fetchFollows(e){try{return(await e.followSet()).size}catch
533
533
  ${escapeHtml$1(n)}
534
534
  </div>
535
535
  </div>
536
- `}async function parseText(n,e,t,r){let s=n,o=[];const a=/(nostr:)?(note[a-zA-Z0-9]{59,60}|nevent[a-zA-Z0-9]{58,})/g,u=[...s.matchAll(a)];for(const w of u){const x=w[0],k=w[2],C=w.index||0;o.push({id:k,position:C});try{if(!t.has(k)){const I=await r.getPost(k);I&&t.set(k,I)}}catch(I){console.error(`Failed to fetch embedded post ${k}:`,I)}s=s.replace(x," ")}const c=[...s.matchAll(new RegExp(nip21_exports.NOSTR_URI_REGEX,"g"))],l=[],h=c.map(async w=>{try{const x=nip21_exports.parse(w[0]),k=x.decoded.data;let C="";if(typeof k=="string"?C=k:C=k.pubkey,C){const R=await r.getNDK().getUser({pubkey:C}).fetchProfile(),$=(R==null?void 0:R.displayName)||"";l.push({original:w[0],replacement:`<a href="https://njump.me/${x.value}" target="_blank">@${$}</a>`})}}catch(x){console.error("Failed to process Nostr URI:",x)}});await Promise.all(h);for(const w of l)s=s.replace(w.original,w.replacement);const f=/(\s|^)@(\w+)/g,p=[...s.matchAll(f)],b=[];for(const w of p){const x=w[0],k=w[2];b.push({original:x,replacement:`${w[1]}<span class="nostr-mention" data-username="${k}">@${k}</span>`})}for(const w of b)s=s.replace(w.original,w.replacement);const v=[];if(e){const w=e.getMatchingTags("a");for(const x of w){const k=x[1],C=x[2];k!=null&&k.startsWith("video/")&&C&&v.push({type:"video",value:C})}}const m=/(https:\/\/(?!njump\.me)[\w.-]+(?:\.[\w.-]+)+(?:\/[^\s]*)?)/g,y=[...s.matchAll(m)];if(y.length>0){let w=0;for(const x of y){const k=x.index,C=k+x[0].length;k>w&&v.push({type:"text",value:s.substring(w,k)});const I=x[0],R=new URL(I).pathname.toLowerCase();let $;R.match(/\.(jpg|jpeg|png)$/)?$="image":R.endsWith(".gif")?$="gif":R.match(/\.(mp4|webm|mov)$/)?$="video":$="link",v.push({type:$,value:I}),w=C}w<s.length&&v.push({type:"text",value:s.substring(w)})}else v.push({type:"text",value:s});if(o.length>0){o.sort((w,x)=>x.position-w.position);for(const w of o)v.push({type:"embedded-note",noteId:w.id})}return v}function formatEventDate(n){return n===void 0?"":new Date(n*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function renderContent(n){const e=[];let t=0,r="";for(const s of n)if(s.type==="text")r+=s.value??"";else if(s.type==="embedded-note")r&&(e.push(`<span class="text-content">${r.replace(/\n/g,"<br />")}</span>`),r=""),e.push(`<div class="embedded-post-placeholder" data-note-id="${s.noteId}"></div>`);else{r&&(e.push(`<span class="text-content">${r.replace(/\n/g,"<br />")}</span>`),r="");const o=s.value??"";if(!isValidUrl(o))continue;switch(s.type){case"image":e.push(`<img class="post-media-item" src="${o}" alt="User uploaded image" loading="lazy">`),t++;break;case"gif":e.push(`<img class="post-media-item" src="${o}" alt="User uploaded GIF" loading="lazy">`),t++;break;case"video":e.push(`<video class="post-media-item" src="${o}" controls></video>`),t++;break;case"link":e.push(`<a href="${o}">${o}</a>`);break}}if(r&&e.push(`<span class="text-content">${r.replace(/\n/g,"<br />")}</span>`),t>1){const s=[],o=[];let a=0,u=-1;for(let h=0;h<e.length;h++){const f=e[h];(f.startsWith("<img")||f.startsWith("<video"))&&(u===-1&&(u=h),s.push(`<li class="glide__slide">${f}</li>`),o.push(`<button class="glide__bullet" data-glide-dir="=${a}"></button>`),a++)}const c=e.filter(h=>!h.startsWith("<img")&&!h.startsWith("<video")),l=`
536
+ `}async function parseText(n,e,t,r){let s=n,o=[];const a=/(nostr:)?(note[a-zA-Z0-9]{59,60}|nevent[a-zA-Z0-9]{58,})/g,u=[...s.matchAll(a)];for(const w of u){const x=w[0],k=w[2],C=w.index||0;o.push({id:k,position:C});try{if(!t.has(k)){const P=await r.getPost(k);P&&t.set(k,P)}}catch(P){console.error(`Failed to fetch embedded post ${k}:`,P)}s=s.replace(x," ")}const c=[...s.matchAll(new RegExp(nip21_exports.NOSTR_URI_REGEX,"g"))],l=[],h=c.map(async w=>{try{const x=nip21_exports.parse(w[0]),k=x.decoded.data;let C="";if(typeof k=="string"?C=k:C=k.pubkey,C){const R=await r.getNDK().getUser({pubkey:C}).fetchProfile(),N=(R==null?void 0:R.displayName)||"";l.push({original:w[0],replacement:`<a href="https://njump.me/${x.value}" target="_blank">@${N}</a>`})}}catch(x){console.error("Failed to process Nostr URI:",x)}});await Promise.all(h);for(const w of l)s=s.replace(w.original,w.replacement);const f=/(\s|^)@(\w+)/g,p=[...s.matchAll(f)],b=[];for(const w of p){const x=w[0],k=w[2];b.push({original:x,replacement:`${w[1]}<span class="nostr-mention" data-username="${k}">@${k}</span>`})}for(const w of b)s=s.replace(w.original,w.replacement);const v=[];if(e){const w=e.getMatchingTags("a");for(const x of w){const k=x[1],C=x[2];k!=null&&k.startsWith("video/")&&C&&v.push({type:"video",value:C})}}const m=/(https:\/\/(?!njump\.me)[\w.-]+(?:\.[\w.-]+)+(?:\/[^\s]*)?)/g,y=[...s.matchAll(m)];if(y.length>0){let w=0;for(const x of y){const k=x.index,C=k+x[0].length;k>w&&v.push({type:"text",value:s.substring(w,k)});const P=x[0],R=new URL(P).pathname.toLowerCase();let N;R.match(/\.(jpg|jpeg|png)$/)?N="image":R.endsWith(".gif")?N="gif":R.match(/\.(mp4|webm|mov)$/)?N="video":N="link",v.push({type:N,value:P}),w=C}w<s.length&&v.push({type:"text",value:s.substring(w)})}else v.push({type:"text",value:s});if(o.length>0){o.sort((w,x)=>x.position-w.position);for(const w of o)v.push({type:"embedded-note",noteId:w.id})}return v}function formatEventDate(n){return n===void 0?"":new Date(n*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function renderContent(n){const e=[];let t=0,r="";for(const s of n)if(s.type==="text")r+=s.value??"";else if(s.type==="embedded-note")r&&(e.push(`<span class="text-content">${r.replace(/\n/g,"<br />")}</span>`),r=""),e.push(`<div class="embedded-post-placeholder" data-note-id="${s.noteId}"></div>`);else{r&&(e.push(`<span class="text-content">${r.replace(/\n/g,"<br />")}</span>`),r="");const o=s.value??"";if(!isValidUrl(o))continue;switch(s.type){case"image":e.push(`<img class="post-media-item" src="${o}" alt="User uploaded image" loading="lazy">`),t++;break;case"gif":e.push(`<img class="post-media-item" src="${o}" alt="User uploaded GIF" loading="lazy">`),t++;break;case"video":e.push(`<video class="post-media-item" src="${o}" controls></video>`),t++;break;case"link":e.push(`<a href="${o}">${o}</a>`);break}}if(r&&e.push(`<span class="text-content">${r.replace(/\n/g,"<br />")}</span>`),t>1){const s=[],o=[];let a=0,u=-1;for(let h=0;h<e.length;h++){const f=e[h];(f.startsWith("<img")||f.startsWith("<video"))&&(u===-1&&(u=h),s.push(`<li class="glide__slide">${f}</li>`),o.push(`<button class="glide__bullet" data-glide-dir="=${a}"></button>`),a++)}const c=e.filter(h=>!h.startsWith("<img")&&!h.startsWith("<video")),l=`
537
537
  <div class="glide" style="margin-top: 20px">
538
538
  <div class="glide__track" data-glide-el="track">
539
539
  <ul class="glide__slides">
@@ -1477,25 +1477,25 @@ ${u}`)}return t}async fetchFollows(e){try{return(await e.followSet()).size}catch
1477
1477
  }
1478
1478
  `};function normalizeURL$1(n){try{const e=new URL(n);return e.origin.replace("://m.","://").replace("://mobile.","://").replace("http://","https://").replace(/:\d+/,t=>t===":443"||t===":80"?"":t)+e.pathname.replace(/\/+/g,"/").replace(/\/*$/,"")}catch{return console.error("Invalid URL:",n),n}}function isValidPublicKey(n){return/^[a-f0-9]{64}$/.test(n)}const profileCache={},getProfileMetadata=async n=>{if(profileCache[n])return profileCache[n];const e=new SimplePool,t=["wss://relay.nostr.band","wss://purplepag.es","wss://relay.damus.io","wss://nostr.wine"];try{const r=await e.get(t,{authors:[n],kinds:[0]});return profileCache[n]=r,r}finally{e.close(t)}},getBatchedProfileMetadata=async n=>{const e=n.filter(s=>!profileCache[s]);if(e.length===0)return n.map(s=>({id:s,profile:profileCache[s]}));const t=new SimplePool,r=["wss://relay.nostr.band","wss://purplepag.es","wss://relay.damus.io","wss://nostr.wine"];try{return(await t.querySync(r,{authors:e,kinds:[0]})).forEach(a=>{profileCache[a.pubkey]=a}),n.map(a=>({id:a,profile:profileCache[a]||null}))}finally{t.close(r)}},extractProfileMetadataContent=n=>{try{return JSON.parse((n==null?void 0:n.content)||"{}")}catch{return{}}},getZapEndpoint=async n=>{const e=await nip57_exports.getZapEndpoint(n);if(!e)throw new Error("Failed to retrieve zap LNURL");return e},signEvent$1=async(n,e)=>{if(isNip07ExtAvailable())try{const t=window.nostr;if(t!=null&&t.signEvent)return await t.signEvent(n)}catch{}return finalizeEvent$1(n,generateRandomPrivKey())},makeZapEvent=async({profile:n,nip19Target:e,amount:t,relays:r,comment:s,anon:o,url:a})=>{const u={profile:n,amount:t,relays:r,comment:s||""},c=nip57_exports.makeZapRequest(u);return a&&(c.tags.push(["k","web"]),c.tags.push(["i",normalizeURL$1(a)])),(!isNip07ExtAvailable()||o)&&c.tags.push(["anon"]),signEvent$1(c)},fetchInvoice=async({zapEndpoint:n,amount:e,comment:t,authorId:r,nip19Target:s,normalizedRelays:o,anon:a,url:u})=>{const c=await makeZapEvent({profile:r,nip19Target:s,amount:e,relays:o,comment:t??"",anon:a,url:u});let l=`${n}?amount=${e}&nostr=${encodeURIComponent(JSON.stringify(c))}`;t&&(l+=`&comment=${encodeURIComponent(t??"")}`);const h=await fetch(l,{method:"GET"});if(!h.ok)throw new Error(`LNURL request failed: ${h.status} ${h.statusText}`);let f;try{f=await h.json()}catch{throw new Error("Invalid JSON from LNURL endpoint")}const{pr:p,reason:b,status:v}=f||{};if(p)return p;throw v==="ERROR"?new Error(b??"Unable to fetch invoice"):new Error("Unable to fetch invoice")},generateRandomPrivKey=()=>{const n=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(n);else{console.warn("crypto.getRandomValues not available, using Math.random as fallback");for(let e=0;e<32;e++)n[e]=Math.floor(Math.random()*256)}return n},isNip07ExtAvailable=()=>typeof window<"u"&&!!window.nostr,fetchTotalZapAmount=async({pubkey:n,relays:e,url:t})=>{var u,c,l,h;const r=t?normalizeURL$1(t):void 0,s=new SimplePool;let o=0;const a=[];try{const f={kinds:[9735],"#p":[n],limit:1e3},p=await s.querySync(e,f);for(const b of p){const v=(u=b.tags)==null?void 0:u.find(m=>m[0]==="description");if(v!=null&&v[1])try{const m=JSON.parse(v[1]),y=(c=m==null?void 0:m.tags)==null?void 0:c.find(w=>w[0]==="amount");if(r){const w=(l=m==null?void 0:m.tags)==null?void 0:l.find(C=>C[0]==="k"),x=(h=m==null?void 0:m.tags)==null?void 0:h.find(C=>C[0]==="i"),k=x!=null&&x[1]?normalizeURL$1(x[1]):"";if((w==null?void 0:w[1])==="web"&&k===r&&(y!=null&&y[1])){const C=parseInt(y[1],10);C>0&&(o+=C,a.push({amount:C/1e3,date:new Date(b.created_at*1e3),authorPubkey:m.pubkey,comment:m.content}))}}else if(y!=null&&y[1]){const w=parseInt(y[1],10);w>0&&(o+=w,a.push({amount:w/1e3,date:new Date(b.created_at*1e3),authorPubkey:m.pubkey,comment:m.content}))}}catch(m){console.error("Nostr-Components: Zap button: Could not parse zap request from description tag",m)}}}catch(f){console.error("Nostr-Components: Zap button: Error fetching zap receipts",f)}finally{s.close(e)}return a.sort((f,p)=>p.date.getTime()-f.date.getTime()),{totalAmount:o/1e3,zapDetails:a}},listenForZapReceipt=({relays:n,receiversPubKey:e,invoice:t,onSuccess:r})=>{const s=new SimplePool,o=Array.from(new Set([...n,"wss://relay.nostr.band"])),a=Math.floor((Date.now()-24*60*60*1e3)/1e3);s.subscribe(o,{kinds:[9735],"#p":[e],since:a},{onevent(c){c.tags.some(h=>h[0]==="bolt11"&&h[1]===t)&&(r(),u())}});const u=()=>{s.close(o)};return u},zapUtils=Object.freeze(Object.defineProperty({__proto__:null,extractProfileMetadataContent,fetchInvoice,fetchTotalZapAmount,getBatchedProfileMetadata,getProfileMetadata,getZapEndpoint,isNip07ExtAvailable,listenForZapReceipt},Symbol.toStringTag,{value:"Module"}));var canPromise$1=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},qrcode={},utils$1={};let toSJISFunction;const CODEWORDS_COUNT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];utils$1.getSymbolSize=function n(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17},utils$1.getSymbolTotalCodewords=function n(e){return CODEWORDS_COUNT[e]},utils$1.getBCHDigit=function(n){let e=0;for(;n!==0;)e++,n>>>=1;return e},utils$1.setToSJISFunction=function n(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');toSJISFunction=e},utils$1.isKanjiModeEnabled=function(){return typeof toSJISFunction<"u"},utils$1.toSJIS=function n(e){return toSJISFunction(e)};var errorCorrectionLevel={};(function(n){n.L={bit:1},n.M={bit:0},n.Q={bit:3},n.H={bit:2};function e(t){if(typeof t!="string")throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return n.L;case"m":case"medium":return n.M;case"q":case"quartile":return n.Q;case"h":case"high":return n.H;default:throw new Error("Unknown EC Level: "+t)}}n.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},n.from=function(r,s){if(n.isValid(r))return r;try{return e(r)}catch{return s}}})(errorCorrectionLevel);function BitBuffer$1(){this.buffer=[],this.length=0}BitBuffer$1.prototype={get:function(n){const e=Math.floor(n/8);return(this.buffer[e]>>>7-n%8&1)===1},put:function(n,e){for(let t=0;t<e;t++)this.putBit((n>>>e-t-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(n){const e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),n&&(this.buffer[e]|=128>>>this.length%8),this.length++}};var bitBuffer=BitBuffer$1;function BitMatrix$1(n){if(!n||n<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=n,this.data=new Uint8Array(n*n),this.reservedBit=new Uint8Array(n*n)}BitMatrix$1.prototype.set=function(n,e,t,r){const s=n*this.size+e;this.data[s]=t,r&&(this.reservedBit[s]=!0)},BitMatrix$1.prototype.get=function(n,e){return this.data[n*this.size+e]},BitMatrix$1.prototype.xor=function(n,e,t){this.data[n*this.size+e]^=t},BitMatrix$1.prototype.isReserved=function(n,e){return this.reservedBit[n*this.size+e]};var bitMatrix=BitMatrix$1,alignmentPattern={};(function(n){const e=utils$1.getSymbolSize;n.getRowColCoords=function(r){if(r===1)return[];const s=Math.floor(r/7)+2,o=e(r),a=o===145?26:Math.ceil((o-13)/(2*s-2))*2,u=[o-7];for(let c=1;c<s-1;c++)u[c]=u[c-1]-a;return u.push(6),u.reverse()},n.getPositions=function(r){const s=[],o=n.getRowColCoords(r),a=o.length;for(let u=0;u<a;u++)for(let c=0;c<a;c++)u===0&&c===0||u===0&&c===a-1||u===a-1&&c===0||s.push([o[u],o[c]]);return s}})(alignmentPattern);var finderPattern={};const getSymbolSize=utils$1.getSymbolSize,FINDER_PATTERN_SIZE=7;finderPattern.getPositions=function n(e){const t=getSymbolSize(e);return[[0,0],[t-FINDER_PATTERN_SIZE,0],[0,t-FINDER_PATTERN_SIZE]]};var maskPattern={};(function(n){n.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};n.isValid=function(s){return s!=null&&s!==""&&!isNaN(s)&&s>=0&&s<=7},n.from=function(s){return n.isValid(s)?parseInt(s,10):void 0},n.getPenaltyN1=function(s){const o=s.size;let a=0,u=0,c=0,l=null,h=null;for(let f=0;f<o;f++){u=c=0,l=h=null;for(let p=0;p<o;p++){let b=s.get(f,p);b===l?u++:(u>=5&&(a+=e.N1+(u-5)),l=b,u=1),b=s.get(p,f),b===h?c++:(c>=5&&(a+=e.N1+(c-5)),h=b,c=1)}u>=5&&(a+=e.N1+(u-5)),c>=5&&(a+=e.N1+(c-5))}return a},n.getPenaltyN2=function(s){const o=s.size;let a=0;for(let u=0;u<o-1;u++)for(let c=0;c<o-1;c++){const l=s.get(u,c)+s.get(u,c+1)+s.get(u+1,c)+s.get(u+1,c+1);(l===4||l===0)&&a++}return a*e.N2},n.getPenaltyN3=function(s){const o=s.size;let a=0,u=0,c=0;for(let l=0;l<o;l++){u=c=0;for(let h=0;h<o;h++)u=u<<1&2047|s.get(l,h),h>=10&&(u===1488||u===93)&&a++,c=c<<1&2047|s.get(h,l),h>=10&&(c===1488||c===93)&&a++}return a*e.N3},n.getPenaltyN4=function(s){let o=0;const a=s.data.length;for(let c=0;c<a;c++)o+=s.data[c];return Math.abs(Math.ceil(o*100/a/5)-10)*e.N4};function t(r,s,o){switch(r){case n.Patterns.PATTERN000:return(s+o)%2===0;case n.Patterns.PATTERN001:return s%2===0;case n.Patterns.PATTERN010:return o%3===0;case n.Patterns.PATTERN011:return(s+o)%3===0;case n.Patterns.PATTERN100:return(Math.floor(s/2)+Math.floor(o/3))%2===0;case n.Patterns.PATTERN101:return s*o%2+s*o%3===0;case n.Patterns.PATTERN110:return(s*o%2+s*o%3)%2===0;case n.Patterns.PATTERN111:return(s*o%3+(s+o)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}n.applyMask=function(s,o){const a=o.size;for(let u=0;u<a;u++)for(let c=0;c<a;c++)o.isReserved(c,u)||o.xor(c,u,t(s,c,u))},n.getBestMask=function(s,o){const a=Object.keys(n.Patterns).length;let u=0,c=1/0;for(let l=0;l<a;l++){o(l),n.applyMask(l,s);const h=n.getPenaltyN1(s)+n.getPenaltyN2(s)+n.getPenaltyN3(s)+n.getPenaltyN4(s);n.applyMask(l,s),h<c&&(c=h,u=l)}return u}})(maskPattern);var errorCorrectionCode={};const ECLevel$1=errorCorrectionLevel,EC_BLOCKS_TABLE=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],EC_CODEWORDS_TABLE=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];errorCorrectionCode.getBlocksCount=function n(e,t){switch(t){case ECLevel$1.L:return EC_BLOCKS_TABLE[(e-1)*4+0];case ECLevel$1.M:return EC_BLOCKS_TABLE[(e-1)*4+1];case ECLevel$1.Q:return EC_BLOCKS_TABLE[(e-1)*4+2];case ECLevel$1.H:return EC_BLOCKS_TABLE[(e-1)*4+3];default:return}},errorCorrectionCode.getTotalCodewordsCount=function n(e,t){switch(t){case ECLevel$1.L:return EC_CODEWORDS_TABLE[(e-1)*4+0];case ECLevel$1.M:return EC_CODEWORDS_TABLE[(e-1)*4+1];case ECLevel$1.Q:return EC_CODEWORDS_TABLE[(e-1)*4+2];case ECLevel$1.H:return EC_CODEWORDS_TABLE[(e-1)*4+3];default:return}};var polynomial={},galoisField={};const EXP_TABLE=new Uint8Array(512),LOG_TABLE=new Uint8Array(256);(function n(){let e=1;for(let t=0;t<255;t++)EXP_TABLE[t]=e,LOG_TABLE[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)EXP_TABLE[t]=EXP_TABLE[t-255]})(),galoisField.log=function n(e){if(e<1)throw new Error("log("+e+")");return LOG_TABLE[e]},galoisField.exp=function n(e){return EXP_TABLE[e]},galoisField.mul=function n(e,t){return e===0||t===0?0:EXP_TABLE[LOG_TABLE[e]+LOG_TABLE[t]]},function(n){const e=galoisField;n.mul=function(r,s){const o=new Uint8Array(r.length+s.length-1);for(let a=0;a<r.length;a++)for(let u=0;u<s.length;u++)o[a+u]^=e.mul(r[a],s[u]);return o},n.mod=function(r,s){let o=new Uint8Array(r);for(;o.length-s.length>=0;){const a=o[0];for(let c=0;c<s.length;c++)o[c]^=e.mul(s[c],a);let u=0;for(;u<o.length&&o[u]===0;)u++;o=o.slice(u)}return o},n.generateECPolynomial=function(r){let s=new Uint8Array([1]);for(let o=0;o<r;o++)s=n.mul(s,new Uint8Array([1,e.exp(o)]));return s}}(polynomial);const Polynomial=polynomial;function ReedSolomonEncoder$1(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}ReedSolomonEncoder$1.prototype.initialize=function n(e){this.degree=e,this.genPoly=Polynomial.generateECPolynomial(this.degree)},ReedSolomonEncoder$1.prototype.encode=function n(e){if(!this.genPoly)throw new Error("Encoder not initialized");const t=new Uint8Array(e.length+this.degree);t.set(e);const r=Polynomial.mod(t,this.genPoly),s=this.degree-r.length;if(s>0){const o=new Uint8Array(this.degree);return o.set(r,s),o}return r};var reedSolomonEncoder=ReedSolomonEncoder$1,version={},mode={},versionCheck={};versionCheck.isValid=function n(e){return!isNaN(e)&&e>=1&&e<=40};var regex={};const numeric="[0-9]+",alphanumeric="[A-Z $%*+\\-./:]+";let kanji="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";kanji=kanji.replace(/u/g,"\\u");const byte="(?:(?![A-Z0-9 $%*+\\-./:]|"+kanji+`)(?:.|[\r
1479
1479
  ]))+`;regex.KANJI=new RegExp(kanji,"g"),regex.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),regex.BYTE=new RegExp(byte,"g"),regex.NUMERIC=new RegExp(numeric,"g"),regex.ALPHANUMERIC=new RegExp(alphanumeric,"g");const TEST_KANJI=new RegExp("^"+kanji+"$"),TEST_NUMERIC=new RegExp("^"+numeric+"$"),TEST_ALPHANUMERIC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");regex.testKanji=function n(e){return TEST_KANJI.test(e)},regex.testNumeric=function n(e){return TEST_NUMERIC.test(e)},regex.testAlphanumeric=function n(e){return TEST_ALPHANUMERIC.test(e)},function(n){const e=versionCheck,t=regex;n.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},n.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},n.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},n.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},n.MIXED={bit:-1},n.getCharCountIndicator=function(o,a){if(!o.ccBits)throw new Error("Invalid mode: "+o);if(!e.isValid(a))throw new Error("Invalid version: "+a);return a>=1&&a<10?o.ccBits[0]:a<27?o.ccBits[1]:o.ccBits[2]},n.getBestModeForData=function(o){return t.testNumeric(o)?n.NUMERIC:t.testAlphanumeric(o)?n.ALPHANUMERIC:t.testKanji(o)?n.KANJI:n.BYTE},n.toString=function(o){if(o&&o.id)return o.id;throw new Error("Invalid mode")},n.isValid=function(o){return o&&o.bit&&o.ccBits};function r(s){if(typeof s!="string")throw new Error("Param is not a string");switch(s.toLowerCase()){case"numeric":return n.NUMERIC;case"alphanumeric":return n.ALPHANUMERIC;case"kanji":return n.KANJI;case"byte":return n.BYTE;default:throw new Error("Unknown mode: "+s)}}n.from=function(o,a){if(n.isValid(o))return o;try{return r(o)}catch{return a}}}(mode),function(n){const e=utils$1,t=errorCorrectionCode,r=errorCorrectionLevel,s=mode,o=versionCheck,a=7973,u=e.getBCHDigit(a);function c(p,b,v){for(let m=1;m<=40;m++)if(b<=n.getCapacity(m,v,p))return m}function l(p,b){return s.getCharCountIndicator(p,b)+4}function h(p,b){let v=0;return p.forEach(function(m){const y=l(m.mode,b);v+=y+m.getBitsLength()}),v}function f(p,b){for(let v=1;v<=40;v++)if(h(p,v)<=n.getCapacity(v,b,s.MIXED))return v}n.from=function(b,v){return o.isValid(b)?parseInt(b,10):v},n.getCapacity=function(b,v,m){if(!o.isValid(b))throw new Error("Invalid QR Code version");typeof m>"u"&&(m=s.BYTE);const y=e.getSymbolTotalCodewords(b),w=t.getTotalCodewordsCount(b,v),x=(y-w)*8;if(m===s.MIXED)return x;const k=x-l(m,b);switch(m){case s.NUMERIC:return Math.floor(k/10*3);case s.ALPHANUMERIC:return Math.floor(k/11*2);case s.KANJI:return Math.floor(k/13);case s.BYTE:default:return Math.floor(k/8)}},n.getBestVersionForData=function(b,v){let m;const y=r.from(v,r.M);if(Array.isArray(b)){if(b.length>1)return f(b,y);if(b.length===0)return 1;m=b[0]}else m=b;return c(m.mode,m.getLength(),y)},n.getEncodedBits=function(b){if(!o.isValid(b)||b<7)throw new Error("Invalid QR Code version");let v=b<<12;for(;e.getBCHDigit(v)-u>=0;)v^=a<<e.getBCHDigit(v)-u;return b<<12|v}}(version);var formatInfo={};const Utils$3=utils$1,G15=1335,G15_MASK=21522,G15_BCH=Utils$3.getBCHDigit(G15);formatInfo.getEncodedBits=function n(e,t){const r=e.bit<<3|t;let s=r<<10;for(;Utils$3.getBCHDigit(s)-G15_BCH>=0;)s^=G15<<Utils$3.getBCHDigit(s)-G15_BCH;return(r<<10|s)^G15_MASK};var segments={};const Mode$4=mode;function NumericData(n){this.mode=Mode$4.NUMERIC,this.data=n.toString()}NumericData.getBitsLength=function n(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)},NumericData.prototype.getLength=function n(){return this.data.length},NumericData.prototype.getBitsLength=function n(){return NumericData.getBitsLength(this.data.length)},NumericData.prototype.write=function n(e){let t,r,s;for(t=0;t+3<=this.data.length;t+=3)r=this.data.substr(t,3),s=parseInt(r,10),e.put(s,10);const o=this.data.length-t;o>0&&(r=this.data.substr(t),s=parseInt(r,10),e.put(s,o*3+1))};var numericData=NumericData;const Mode$3=mode,ALPHA_NUM_CHARS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function AlphanumericData(n){this.mode=Mode$3.ALPHANUMERIC,this.data=n}AlphanumericData.getBitsLength=function n(e){return 11*Math.floor(e/2)+6*(e%2)},AlphanumericData.prototype.getLength=function n(){return this.data.length},AlphanumericData.prototype.getBitsLength=function n(){return AlphanumericData.getBitsLength(this.data.length)},AlphanumericData.prototype.write=function n(e){let t;for(t=0;t+2<=this.data.length;t+=2){let r=ALPHA_NUM_CHARS.indexOf(this.data[t])*45;r+=ALPHA_NUM_CHARS.indexOf(this.data[t+1]),e.put(r,11)}this.data.length%2&&e.put(ALPHA_NUM_CHARS.indexOf(this.data[t]),6)};var alphanumericData=AlphanumericData;const Mode$2=mode;function ByteData(n){this.mode=Mode$2.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}ByteData.getBitsLength=function n(e){return e*8},ByteData.prototype.getLength=function n(){return this.data.length},ByteData.prototype.getBitsLength=function n(){return ByteData.getBitsLength(this.data.length)},ByteData.prototype.write=function(n){for(let e=0,t=this.data.length;e<t;e++)n.put(this.data[e],8)};var byteData=ByteData;const Mode$1=mode,Utils$2=utils$1;function KanjiData(n){this.mode=Mode$1.KANJI,this.data=n}KanjiData.getBitsLength=function n(e){return e*13},KanjiData.prototype.getLength=function n(){return this.data.length},KanjiData.prototype.getBitsLength=function n(){return KanjiData.getBitsLength(this.data.length)},KanjiData.prototype.write=function(n){let e;for(e=0;e<this.data.length;e++){let t=Utils$2.toSJIS(this.data[e]);if(t>=33088&&t<=40956)t-=33088;else if(t>=57408&&t<=60351)t-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
1480
- Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),n.put(t,13)}};var kanjiData=KanjiData,dijkstra={exports:{}};(function(n){var e={single_source_shortest_paths:function(t,r,s){var o={},a={};a[r]=0;var u=e.PriorityQueue.make();u.push(r,0);for(var c,l,h,f,p,b,v,m,y;!u.empty();){c=u.pop(),l=c.value,f=c.cost,p=t[l]||{};for(h in p)p.hasOwnProperty(h)&&(b=p[h],v=f+b,m=a[h],y=typeof a[h]>"u",(y||m>v)&&(a[h]=v,u.push(h,v),o[h]=l))}if(typeof s<"u"&&typeof a[s]>"u"){var w=["Could not find a path from ",r," to ",s,"."].join("");throw new Error(w)}return o},extract_shortest_path_from_predecessor_list:function(t,r){for(var s=[],o=r;o;)s.push(o),t[o],o=t[o];return s.reverse(),s},find_path:function(t,r,s){var o=e.single_source_shortest_paths(t,r,s);return e.extract_shortest_path_from_predecessor_list(o,s)},PriorityQueue:{make:function(t){var r=e.PriorityQueue,s={},o;t=t||{};for(o in r)r.hasOwnProperty(o)&&(s[o]=r[o]);return s.queue=[],s.sorter=t.sorter||r.default_sorter,s},default_sorter:function(t,r){return t.cost-r.cost},push:function(t,r){var s={value:t,cost:r};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};n.exports=e})(dijkstra);var dijkstraExports=dijkstra.exports;(function(n){const e=mode,t=numericData,r=alphanumericData,s=byteData,o=kanjiData,a=regex,u=utils$1,c=dijkstraExports;function l(w){return unescape(encodeURIComponent(w)).length}function h(w,x,k){const C=[];let I;for(;(I=w.exec(k))!==null;)C.push({data:I[0],index:I.index,mode:x,length:I[0].length});return C}function f(w){const x=h(a.NUMERIC,e.NUMERIC,w),k=h(a.ALPHANUMERIC,e.ALPHANUMERIC,w);let C,I;return u.isKanjiModeEnabled()?(C=h(a.BYTE,e.BYTE,w),I=h(a.KANJI,e.KANJI,w)):(C=h(a.BYTE_KANJI,e.BYTE,w),I=[]),x.concat(k,C,I).sort(function($,B){return $.index-B.index}).map(function($){return{data:$.data,mode:$.mode,length:$.length}})}function p(w,x){switch(x){case e.NUMERIC:return t.getBitsLength(w);case e.ALPHANUMERIC:return r.getBitsLength(w);case e.KANJI:return o.getBitsLength(w);case e.BYTE:return s.getBitsLength(w)}}function b(w){return w.reduce(function(x,k){const C=x.length-1>=0?x[x.length-1]:null;return C&&C.mode===k.mode?(x[x.length-1].data+=k.data,x):(x.push(k),x)},[])}function v(w){const x=[];for(let k=0;k<w.length;k++){const C=w[k];switch(C.mode){case e.NUMERIC:x.push([C,{data:C.data,mode:e.ALPHANUMERIC,length:C.length},{data:C.data,mode:e.BYTE,length:C.length}]);break;case e.ALPHANUMERIC:x.push([C,{data:C.data,mode:e.BYTE,length:C.length}]);break;case e.KANJI:x.push([C,{data:C.data,mode:e.BYTE,length:l(C.data)}]);break;case e.BYTE:x.push([{data:C.data,mode:e.BYTE,length:l(C.data)}])}}return x}function m(w,x){const k={},C={start:{}};let I=["start"];for(let R=0;R<w.length;R++){const $=w[R],B=[];for(let O=0;O<$.length;O++){const H=$[O],T=""+R+O;B.push(T),k[T]={node:H,lastCount:0},C[T]={};for(let A=0;A<I.length;A++){const N=I[A];k[N]&&k[N].node.mode===H.mode?(C[N][T]=p(k[N].lastCount+H.length,H.mode)-p(k[N].lastCount,H.mode),k[N].lastCount+=H.length):(k[N]&&(k[N].lastCount=H.length),C[N][T]=p(H.length,H.mode)+4+e.getCharCountIndicator(H.mode,x))}}I=B}for(let R=0;R<I.length;R++)C[I[R]].end=0;return{map:C,table:k}}function y(w,x){let k;const C=e.getBestModeForData(w);if(k=e.from(x,C),k!==e.BYTE&&k.bit<C.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(k)+`.
1481
- Suggested mode is: `+e.toString(C));switch(k===e.KANJI&&!u.isKanjiModeEnabled()&&(k=e.BYTE),k){case e.NUMERIC:return new t(w);case e.ALPHANUMERIC:return new r(w);case e.KANJI:return new o(w);case e.BYTE:return new s(w)}}n.fromArray=function(x){return x.reduce(function(k,C){return typeof C=="string"?k.push(y(C,null)):C.data&&k.push(y(C.data,C.mode)),k},[])},n.fromString=function(x,k){const C=f(x,u.isKanjiModeEnabled()),I=v(C),R=m(I,k),$=c.find_path(R.map,"start","end"),B=[];for(let O=1;O<$.length-1;O++)B.push(R.table[$[O]].node);return n.fromArray(b(B))},n.rawSplit=function(x){return n.fromArray(f(x,u.isKanjiModeEnabled()))}})(segments);const Utils$1=utils$1,ECLevel=errorCorrectionLevel,BitBuffer=bitBuffer,BitMatrix=bitMatrix,AlignmentPattern=alignmentPattern,FinderPattern=finderPattern,MaskPattern=maskPattern,ECCode=errorCorrectionCode,ReedSolomonEncoder=reedSolomonEncoder,Version=version,FormatInfo=formatInfo,Mode=mode,Segments=segments;function setupFinderPattern(n,e){const t=n.size,r=FinderPattern.getPositions(e);for(let s=0;s<r.length;s++){const o=r[s][0],a=r[s][1];for(let u=-1;u<=7;u++)if(!(o+u<=-1||t<=o+u))for(let c=-1;c<=7;c++)a+c<=-1||t<=a+c||(u>=0&&u<=6&&(c===0||c===6)||c>=0&&c<=6&&(u===0||u===6)||u>=2&&u<=4&&c>=2&&c<=4?n.set(o+u,a+c,!0,!0):n.set(o+u,a+c,!1,!0))}}function setupTimingPattern(n){const e=n.size;for(let t=8;t<e-8;t++){const r=t%2===0;n.set(t,6,r,!0),n.set(6,t,r,!0)}}function setupAlignmentPattern(n,e){const t=AlignmentPattern.getPositions(e);for(let r=0;r<t.length;r++){const s=t[r][0],o=t[r][1];for(let a=-2;a<=2;a++)for(let u=-2;u<=2;u++)a===-2||a===2||u===-2||u===2||a===0&&u===0?n.set(s+a,o+u,!0,!0):n.set(s+a,o+u,!1,!0)}}function setupVersionInfo(n,e){const t=n.size,r=Version.getEncodedBits(e);let s,o,a;for(let u=0;u<18;u++)s=Math.floor(u/3),o=u%3+t-8-3,a=(r>>u&1)===1,n.set(s,o,a,!0),n.set(o,s,a,!0)}function setupFormatInfo(n,e,t){const r=n.size,s=FormatInfo.getEncodedBits(e,t);let o,a;for(o=0;o<15;o++)a=(s>>o&1)===1,o<6?n.set(o,8,a,!0):o<8?n.set(o+1,8,a,!0):n.set(r-15+o,8,a,!0),o<8?n.set(8,r-o-1,a,!0):o<9?n.set(8,15-o-1+1,a,!0):n.set(8,15-o-1,a,!0);n.set(r-8,8,1,!0)}function setupData(n,e){const t=n.size;let r=-1,s=t-1,o=7,a=0;for(let u=t-1;u>0;u-=2)for(u===6&&u--;;){for(let c=0;c<2;c++)if(!n.isReserved(s,u-c)){let l=!1;a<e.length&&(l=(e[a]>>>o&1)===1),n.set(s,u-c,l),o--,o===-1&&(a++,o=7)}if(s+=r,s<0||t<=s){s-=r,r=-r;break}}}function createData(n,e,t){const r=new BitBuffer;t.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),Mode.getCharCountIndicator(c.mode,n)),c.write(r)});const s=Utils$1.getSymbolTotalCodewords(n),o=ECCode.getTotalCodewordsCount(n,e),a=(s-o)*8;for(r.getLengthInBits()+4<=a&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const u=(a-r.getLengthInBits())/8;for(let c=0;c<u;c++)r.put(c%2?17:236,8);return createCodewords(r,n,e)}function createCodewords(n,e,t){const r=Utils$1.getSymbolTotalCodewords(e),s=ECCode.getTotalCodewordsCount(e,t),o=r-s,a=ECCode.getBlocksCount(e,t),u=r%a,c=a-u,l=Math.floor(r/a),h=Math.floor(o/a),f=h+1,p=l-h,b=new ReedSolomonEncoder(p);let v=0;const m=new Array(a),y=new Array(a);let w=0;const x=new Uint8Array(n.buffer);for(let $=0;$<a;$++){const B=$<c?h:f;m[$]=x.slice(v,v+B),y[$]=b.encode(m[$]),v+=B,w=Math.max(w,B)}const k=new Uint8Array(r);let C=0,I,R;for(I=0;I<w;I++)for(R=0;R<a;R++)I<m[R].length&&(k[C++]=m[R][I]);for(I=0;I<p;I++)for(R=0;R<a;R++)k[C++]=y[R][I];return k}function createSymbol(n,e,t,r){let s;if(Array.isArray(n))s=Segments.fromArray(n);else if(typeof n=="string"){let l=e;if(!l){const h=Segments.rawSplit(n);l=Version.getBestVersionForData(h,t)}s=Segments.fromString(n,l||40)}else throw new Error("Invalid data");const o=Version.getBestVersionForData(s,t);if(!o)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=o;else if(e<o)throw new Error(`
1480
+ Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),n.put(t,13)}};var kanjiData=KanjiData,dijkstra={exports:{}};(function(n){var e={single_source_shortest_paths:function(t,r,s){var o={},a={};a[r]=0;var u=e.PriorityQueue.make();u.push(r,0);for(var c,l,h,f,p,b,v,m,y;!u.empty();){c=u.pop(),l=c.value,f=c.cost,p=t[l]||{};for(h in p)p.hasOwnProperty(h)&&(b=p[h],v=f+b,m=a[h],y=typeof a[h]>"u",(y||m>v)&&(a[h]=v,u.push(h,v),o[h]=l))}if(typeof s<"u"&&typeof a[s]>"u"){var w=["Could not find a path from ",r," to ",s,"."].join("");throw new Error(w)}return o},extract_shortest_path_from_predecessor_list:function(t,r){for(var s=[],o=r;o;)s.push(o),t[o],o=t[o];return s.reverse(),s},find_path:function(t,r,s){var o=e.single_source_shortest_paths(t,r,s);return e.extract_shortest_path_from_predecessor_list(o,s)},PriorityQueue:{make:function(t){var r=e.PriorityQueue,s={},o;t=t||{};for(o in r)r.hasOwnProperty(o)&&(s[o]=r[o]);return s.queue=[],s.sorter=t.sorter||r.default_sorter,s},default_sorter:function(t,r){return t.cost-r.cost},push:function(t,r){var s={value:t,cost:r};this.queue.push(s),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};n.exports=e})(dijkstra);var dijkstraExports=dijkstra.exports;(function(n){const e=mode,t=numericData,r=alphanumericData,s=byteData,o=kanjiData,a=regex,u=utils$1,c=dijkstraExports;function l(w){return unescape(encodeURIComponent(w)).length}function h(w,x,k){const C=[];let P;for(;(P=w.exec(k))!==null;)C.push({data:P[0],index:P.index,mode:x,length:P[0].length});return C}function f(w){const x=h(a.NUMERIC,e.NUMERIC,w),k=h(a.ALPHANUMERIC,e.ALPHANUMERIC,w);let C,P;return u.isKanjiModeEnabled()?(C=h(a.BYTE,e.BYTE,w),P=h(a.KANJI,e.KANJI,w)):(C=h(a.BYTE_KANJI,e.BYTE,w),P=[]),x.concat(k,C,P).sort(function(N,B){return N.index-B.index}).map(function(N){return{data:N.data,mode:N.mode,length:N.length}})}function p(w,x){switch(x){case e.NUMERIC:return t.getBitsLength(w);case e.ALPHANUMERIC:return r.getBitsLength(w);case e.KANJI:return o.getBitsLength(w);case e.BYTE:return s.getBitsLength(w)}}function b(w){return w.reduce(function(x,k){const C=x.length-1>=0?x[x.length-1]:null;return C&&C.mode===k.mode?(x[x.length-1].data+=k.data,x):(x.push(k),x)},[])}function v(w){const x=[];for(let k=0;k<w.length;k++){const C=w[k];switch(C.mode){case e.NUMERIC:x.push([C,{data:C.data,mode:e.ALPHANUMERIC,length:C.length},{data:C.data,mode:e.BYTE,length:C.length}]);break;case e.ALPHANUMERIC:x.push([C,{data:C.data,mode:e.BYTE,length:C.length}]);break;case e.KANJI:x.push([C,{data:C.data,mode:e.BYTE,length:l(C.data)}]);break;case e.BYTE:x.push([{data:C.data,mode:e.BYTE,length:l(C.data)}])}}return x}function m(w,x){const k={},C={start:{}};let P=["start"];for(let R=0;R<w.length;R++){const N=w[R],B=[];for(let O=0;O<N.length;O++){const H=N[O],S=""+R+O;B.push(S),k[S]={node:H,lastCount:0},C[S]={};for(let _=0;_<P.length;_++){const L=P[_];k[L]&&k[L].node.mode===H.mode?(C[L][S]=p(k[L].lastCount+H.length,H.mode)-p(k[L].lastCount,H.mode),k[L].lastCount+=H.length):(k[L]&&(k[L].lastCount=H.length),C[L][S]=p(H.length,H.mode)+4+e.getCharCountIndicator(H.mode,x))}}P=B}for(let R=0;R<P.length;R++)C[P[R]].end=0;return{map:C,table:k}}function y(w,x){let k;const C=e.getBestModeForData(w);if(k=e.from(x,C),k!==e.BYTE&&k.bit<C.bit)throw new Error('"'+w+'" cannot be encoded with mode '+e.toString(k)+`.
1481
+ Suggested mode is: `+e.toString(C));switch(k===e.KANJI&&!u.isKanjiModeEnabled()&&(k=e.BYTE),k){case e.NUMERIC:return new t(w);case e.ALPHANUMERIC:return new r(w);case e.KANJI:return new o(w);case e.BYTE:return new s(w)}}n.fromArray=function(x){return x.reduce(function(k,C){return typeof C=="string"?k.push(y(C,null)):C.data&&k.push(y(C.data,C.mode)),k},[])},n.fromString=function(x,k){const C=f(x,u.isKanjiModeEnabled()),P=v(C),R=m(P,k),N=c.find_path(R.map,"start","end"),B=[];for(let O=1;O<N.length-1;O++)B.push(R.table[N[O]].node);return n.fromArray(b(B))},n.rawSplit=function(x){return n.fromArray(f(x,u.isKanjiModeEnabled()))}})(segments);const Utils$1=utils$1,ECLevel=errorCorrectionLevel,BitBuffer=bitBuffer,BitMatrix=bitMatrix,AlignmentPattern=alignmentPattern,FinderPattern=finderPattern,MaskPattern=maskPattern,ECCode=errorCorrectionCode,ReedSolomonEncoder=reedSolomonEncoder,Version=version,FormatInfo=formatInfo,Mode=mode,Segments=segments;function setupFinderPattern(n,e){const t=n.size,r=FinderPattern.getPositions(e);for(let s=0;s<r.length;s++){const o=r[s][0],a=r[s][1];for(let u=-1;u<=7;u++)if(!(o+u<=-1||t<=o+u))for(let c=-1;c<=7;c++)a+c<=-1||t<=a+c||(u>=0&&u<=6&&(c===0||c===6)||c>=0&&c<=6&&(u===0||u===6)||u>=2&&u<=4&&c>=2&&c<=4?n.set(o+u,a+c,!0,!0):n.set(o+u,a+c,!1,!0))}}function setupTimingPattern(n){const e=n.size;for(let t=8;t<e-8;t++){const r=t%2===0;n.set(t,6,r,!0),n.set(6,t,r,!0)}}function setupAlignmentPattern(n,e){const t=AlignmentPattern.getPositions(e);for(let r=0;r<t.length;r++){const s=t[r][0],o=t[r][1];for(let a=-2;a<=2;a++)for(let u=-2;u<=2;u++)a===-2||a===2||u===-2||u===2||a===0&&u===0?n.set(s+a,o+u,!0,!0):n.set(s+a,o+u,!1,!0)}}function setupVersionInfo(n,e){const t=n.size,r=Version.getEncodedBits(e);let s,o,a;for(let u=0;u<18;u++)s=Math.floor(u/3),o=u%3+t-8-3,a=(r>>u&1)===1,n.set(s,o,a,!0),n.set(o,s,a,!0)}function setupFormatInfo(n,e,t){const r=n.size,s=FormatInfo.getEncodedBits(e,t);let o,a;for(o=0;o<15;o++)a=(s>>o&1)===1,o<6?n.set(o,8,a,!0):o<8?n.set(o+1,8,a,!0):n.set(r-15+o,8,a,!0),o<8?n.set(8,r-o-1,a,!0):o<9?n.set(8,15-o-1+1,a,!0):n.set(8,15-o-1,a,!0);n.set(r-8,8,1,!0)}function setupData(n,e){const t=n.size;let r=-1,s=t-1,o=7,a=0;for(let u=t-1;u>0;u-=2)for(u===6&&u--;;){for(let c=0;c<2;c++)if(!n.isReserved(s,u-c)){let l=!1;a<e.length&&(l=(e[a]>>>o&1)===1),n.set(s,u-c,l),o--,o===-1&&(a++,o=7)}if(s+=r,s<0||t<=s){s-=r,r=-r;break}}}function createData(n,e,t){const r=new BitBuffer;t.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),Mode.getCharCountIndicator(c.mode,n)),c.write(r)});const s=Utils$1.getSymbolTotalCodewords(n),o=ECCode.getTotalCodewordsCount(n,e),a=(s-o)*8;for(r.getLengthInBits()+4<=a&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const u=(a-r.getLengthInBits())/8;for(let c=0;c<u;c++)r.put(c%2?17:236,8);return createCodewords(r,n,e)}function createCodewords(n,e,t){const r=Utils$1.getSymbolTotalCodewords(e),s=ECCode.getTotalCodewordsCount(e,t),o=r-s,a=ECCode.getBlocksCount(e,t),u=r%a,c=a-u,l=Math.floor(r/a),h=Math.floor(o/a),f=h+1,p=l-h,b=new ReedSolomonEncoder(p);let v=0;const m=new Array(a),y=new Array(a);let w=0;const x=new Uint8Array(n.buffer);for(let N=0;N<a;N++){const B=N<c?h:f;m[N]=x.slice(v,v+B),y[N]=b.encode(m[N]),v+=B,w=Math.max(w,B)}const k=new Uint8Array(r);let C=0,P,R;for(P=0;P<w;P++)for(R=0;R<a;R++)P<m[R].length&&(k[C++]=m[R][P]);for(P=0;P<p;P++)for(R=0;R<a;R++)k[C++]=y[R][P];return k}function createSymbol(n,e,t,r){let s;if(Array.isArray(n))s=Segments.fromArray(n);else if(typeof n=="string"){let l=e;if(!l){const h=Segments.rawSplit(n);l=Version.getBestVersionForData(h,t)}s=Segments.fromString(n,l||40)}else throw new Error("Invalid data");const o=Version.getBestVersionForData(s,t);if(!o)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=o;else if(e<o)throw new Error(`
1482
1482
  The chosen QR Code version cannot contain this amount of data.
1483
1483
  Minimum version required to store current data is: `+o+`.
1484
1484
  `);const a=createData(e,t,s),u=Utils$1.getSymbolSize(e),c=new BitMatrix(u);return setupFinderPattern(c,e),setupTimingPattern(c),setupAlignmentPattern(c,e),setupFormatInfo(c,t,0),e>=7&&setupVersionInfo(c,e),setupData(c,a),isNaN(r)&&(r=MaskPattern.getBestMask(c,setupFormatInfo.bind(null,c,t))),MaskPattern.applyMask(r,c),setupFormatInfo(c,t,r),{modules:c,version:e,errorCorrectionLevel:t,maskPattern:r,segments:s}}qrcode.create=function n(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let r=ECLevel.M,s,o;return typeof t<"u"&&(r=ECLevel.from(t.errorCorrectionLevel,ECLevel.M),s=Version.from(t.version),o=MaskPattern.from(t.maskPattern),t.toSJISFunc&&Utils$1.setToSJISFunction(t.toSJISFunc)),createSymbol(e,s,r,o)};var canvas={},utils={};(function(n){function e(t){if(typeof t=="number"&&(t=t.toString()),typeof t!="string")throw new Error("Color should be defined as hex string");let r=t.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+t);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(o){return[o,o]}))),r.length===6&&r.push("F","F");const s=parseInt(r.join(""),16);return{r:s>>24&255,g:s>>16&255,b:s>>8&255,a:s&255,hex:"#"+r.slice(0,6).join("")}}n.getOptions=function(r){r||(r={}),r.color||(r.color={});const s=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,o=r.width&&r.width>=21?r.width:void 0,a=r.scale||4;return{width:o,scale:o?4:a,margin:s,color:{dark:e(r.color.dark||"#000000ff"),light:e(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},n.getScale=function(r,s){return s.width&&s.width>=r+s.margin*2?s.width/(r+s.margin*2):s.scale},n.getImageWidth=function(r,s){const o=n.getScale(r,s);return Math.floor((r+s.margin*2)*o)},n.qrToImageData=function(r,s,o){const a=s.modules.size,u=s.modules.data,c=n.getScale(a,o),l=Math.floor((a+o.margin*2)*c),h=o.margin*c,f=[o.color.light,o.color.dark];for(let p=0;p<l;p++)for(let b=0;b<l;b++){let v=(p*l+b)*4,m=o.color.light;if(p>=h&&b>=h&&p<l-h&&b<l-h){const y=Math.floor((p-h)/c),w=Math.floor((b-h)/c);m=f[u[y*a+w]?1:0]}r[v++]=m.r,r[v++]=m.g,r[v++]=m.b,r[v]=m.a}}})(utils),function(n){const e=utils;function t(s,o,a){s.clearRect(0,0,o.width,o.height),o.style||(o.style={}),o.height=a,o.width=a,o.style.height=a+"px",o.style.width=a+"px"}function r(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}n.render=function(o,a,u){let c=u,l=a;typeof c>"u"&&(!a||!a.getContext)&&(c=a,a=void 0),a||(l=r()),c=e.getOptions(c);const h=e.getImageWidth(o.modules.size,c),f=l.getContext("2d"),p=f.createImageData(h,h);return e.qrToImageData(p.data,o,c),t(f,l,h),f.putImageData(p,0,0),l},n.renderToDataURL=function(o,a,u){let c=u;typeof c>"u"&&(!a||!a.getContext)&&(c=a,a=void 0),c||(c={});const l=n.render(o,a,c),h=c.type||"image/png",f=c.rendererOpts||{};return l.toDataURL(h,f.quality)}}(canvas);var svgTag={};const Utils=utils;function getColorAttrib(n,e){const t=n.a/255,r=e+'="'+n.hex+'"';return t<1?r+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':r}function svgCmd(n,e,t){let r=n+e;return typeof t<"u"&&(r+=" "+t),r}function qrToPath(n,e,t){let r="",s=0,o=!1,a=0;for(let u=0;u<n.length;u++){const c=Math.floor(u%e),l=Math.floor(u/e);!c&&!o&&(o=!0),n[u]?(a++,u>0&&c>0&&n[u-1]||(r+=o?svgCmd("M",c+t,.5+l+t):svgCmd("m",s,0),s=0,o=!1),c+1<e&&n[u+1]||(r+=svgCmd("h",a),a=0)):s++}return r}svgTag.render=function n(e,t,r){const s=Utils.getOptions(t),o=e.modules.size,a=e.modules.data,u=o+s.margin*2,c=s.color.light.a?"<path "+getColorAttrib(s.color.light,"fill")+' d="M0 0h'+u+"v"+u+'H0z"/>':"",l="<path "+getColorAttrib(s.color.dark,"stroke")+' d="'+qrToPath(a,o,s.margin)+'"/>',h='viewBox="0 0 '+u+" "+u+'"',p='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+h+' shape-rendering="crispEdges">'+c+l+`</svg>
1485
- `;return typeof r=="function"&&r(null,p),p};const canPromise=canPromise$1,QRCode=qrcode,CanvasRenderer=canvas,SvgRenderer=svgTag;function renderCanvas(n,e,t,r,s){const o=[].slice.call(arguments,1),a=o.length,u=typeof o[a-1]=="function";if(!u&&!canPromise())throw new Error("Callback required as last argument");if(u){if(a<2)throw new Error("Too few arguments provided");a===2?(s=t,t=e,e=r=void 0):a===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=t,t=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(t=e,e=r=void 0):a===2&&!e.getContext&&(r=t,t=e,e=void 0),new Promise(function(c,l){try{const h=QRCode.create(t,r);c(n(h,e,r))}catch(h){l(h)}})}try{const c=QRCode.create(t,r);s(null,n(c,e,r))}catch(c){s(c)}}QRCode.create,renderCanvas.bind(null,CanvasRenderer.render);var toDataURL=renderCanvas.bind(null,CanvasRenderer.renderToDataURL);renderCanvas.bind(null,function(n,e,t){return SvgRenderer.render(n,t)});const injectCSS=(n="light")=>{document.querySelectorAll("style[data-zap-dialog-styles]").forEach(r=>r.remove());const t=document.createElement("style");t.setAttribute("data-zap-dialog-styles","true"),t.textContent=getDialogStyles(n),document.head.appendChild(t)};async function init(n){var S;const{npub:e,relays:t,cachedDialogComponent:r,buttonColor:s,fixedAmount:o,defaultAmount:a,initialAmount:u,url:c}=n,l=decodeNpub(e);if(customElements.get("dialog-component")||await customElements.whenDefined("dialog-component"),r){const E=document.querySelector(".nostr-base-dialog");if(E){E.classList.remove("success"),E.querySelectorAll(".amount-buttons, .update-zap-container, .comment-container, .cta-btn, .copy-btn").forEach(z=>{z instanceof HTMLElement&&(z.style.display="")});const M=E.querySelector(".update-zap-btn");M&&(M.style.display="");const U=E.querySelector(".success-overlay");return U&&(U.style.opacity="0",U.style.pointerEvents="none"),x(E),r.showModal(),r}}const h=[21,100,1e3];let f;typeof o=="number"&&o>0?f=o:typeof a=="number"&&a>0?f=a:typeof u=="number"&&u>0?f=u:f=h[0];let p="",b="",v=null;async function m(E,L){const M=l,U=await getProfileMetadata(M),z=await getZapEndpoint(U),D=await fetchInvoice({zapEndpoint:z,amount:E*1e3,comment:L,authorId:M,nip19Target:void 0,normalizedRelays:t.split(","),anon:n.anon,url:c});b=D;const V=t.split(",");v&&v(),v=listenForZapReceipt({relays:V,receiversPubKey:l,invoice:D,onSuccess:P})}async function y(E){try{return await toDataURL(E,{width:240,margin:1,color:{dark:"#000000",light:"#ffffff"}})}catch(L){return console.error("Failed to generate QR code:",L),`data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 100 100">
1485
+ `;return typeof r=="function"&&r(null,p),p};const canPromise=canPromise$1,QRCode=qrcode,CanvasRenderer=canvas,SvgRenderer=svgTag;function renderCanvas(n,e,t,r,s){const o=[].slice.call(arguments,1),a=o.length,u=typeof o[a-1]=="function";if(!u&&!canPromise())throw new Error("Callback required as last argument");if(u){if(a<2)throw new Error("Too few arguments provided");a===2?(s=t,t=e,e=r=void 0):a===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=t,t=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(t=e,e=r=void 0):a===2&&!e.getContext&&(r=t,t=e,e=void 0),new Promise(function(c,l){try{const h=QRCode.create(t,r);c(n(h,e,r))}catch(h){l(h)}})}try{const c=QRCode.create(t,r);s(null,n(c,e,r))}catch(c){s(c)}}QRCode.create,renderCanvas.bind(null,CanvasRenderer.render);var toDataURL=renderCanvas.bind(null,CanvasRenderer.renderToDataURL);renderCanvas.bind(null,function(n,e,t){return SvgRenderer.render(n,t)});const injectCSS=(n="light")=>{document.querySelectorAll("style[data-zap-dialog-styles]").forEach(r=>r.remove());const t=document.createElement("style");t.setAttribute("data-zap-dialog-styles","true"),t.textContent=getDialogStyles(n),document.head.appendChild(t)};async function init$1(n){var A;const{npub:e,relays:t,cachedDialogComponent:r,buttonColor:s,fixedAmount:o,defaultAmount:a,initialAmount:u,url:c}=n,l=decodeNpub(e);if(customElements.get("dialog-component")||await customElements.whenDefined("dialog-component"),r){const E=document.querySelector(".nostr-base-dialog");if(E){E.classList.remove("success"),E.querySelectorAll(".amount-buttons, .update-zap-container, .comment-container, .cta-btn, .copy-btn").forEach(z=>{z instanceof HTMLElement&&(z.style.display="")});const M=E.querySelector(".update-zap-btn");M&&(M.style.display="");const U=E.querySelector(".success-overlay");return U&&(U.style.opacity="0",U.style.pointerEvents="none"),x(E),r.showModal(),r}}const h=[21,100,1e3];let f;typeof o=="number"&&o>0?f=o:typeof a=="number"&&a>0?f=a:typeof u=="number"&&u>0?f=u:f=h[0];let p="",b="",v=null;async function m(E,$){const M=l,U=await getProfileMetadata(M),z=await getZapEndpoint(U),D=await fetchInvoice({zapEndpoint:z,amount:E*1e3,comment:$,authorId:M,nip19Target:void 0,normalizedRelays:t.split(","),anon:n.anon,url:c});b=D;const V=t.split(",");v&&v(),v=listenForZapReceipt({relays:V,receiversPubKey:l,invoice:D,onSuccess:I})}async function y(E){try{return await toDataURL(E,{width:240,margin:1,color:{dark:"#000000",light:"#ffffff"}})}catch($){return console.error("Failed to generate QR code:",$),`data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="240" height="240" viewBox="0 0 100 100">
1486
1486
  <rect width="100%" height="100%" fill="white"/>
1487
1487
  <text x="50%" y="50%" font-family="monospace" font-size="10" text-anchor="middle" dominant-baseline="middle" fill="black">
1488
1488
  Invoice: ${E.substring(0,10)}...
1489
1489
  </text>
1490
- </svg>`}}function w(E,L){E.querySelectorAll("button").forEach(M=>{M.dataset.val===String(L)?M.classList.add("active"):M.classList.remove("active")})}async function x(E){E.classList.add("loading");try{await m(f,p);const L=E.querySelector("img.qr");y(b).then(U=>{L.src=U});const M=E.querySelector(".cta-btn");M.disabled=!1}finally{E.classList.remove("loading")}}injectCSS(n.theme||"light");const k=document.createElement("dialog-component");k.setAttribute("header","Send a Zap"),n.theme&&k.setAttribute("data-theme",n.theme);const C=h.map(E=>`<button type="button" data-val="${E}">${E} ⚡</button>`).join(""),I=typeof o=="number"&&o>0;k.innerHTML=`
1490
+ </svg>`}}function w(E,$){E.querySelectorAll("button").forEach(M=>{M.dataset.val===String($)?M.classList.add("active"):M.classList.remove("active")})}async function x(E){E.classList.add("loading");try{await m(f,p);const $=E.querySelector("img.qr");y(b).then(U=>{$.src=U});const M=E.querySelector(".cta-btn");M.disabled=!1}finally{E.classList.remove("loading")}}injectCSS(n.theme||"light");const k=document.createElement("dialog-component");k.setAttribute("header","Send a Zap"),n.theme&&k.setAttribute("data-theme",n.theme);const C=h.map(E=>`<button type="button" data-val="${E}">${E} ⚡</button>`).join(""),P=typeof o=="number"&&o>0;k.innerHTML=`
1491
1491
  <div class="zap-dialog-content">
1492
- ${I?"":`<div class="amount-buttons">${C}</div>`}
1493
- ${I?`<p class="zapping-amount">Zapping ${o} sats</p>`:""}
1494
- ${I?"":`<div class="update-zap-container">
1492
+ ${P?"":`<div class="amount-buttons">${C}</div>`}
1493
+ ${P?`<p class="zapping-amount">Zapping ${o} sats</p>`:""}
1494
+ ${P?"":`<div class="update-zap-container">
1495
1495
  <input type="number" min="1" placeholder="Custom sats" class="custom-amount" style="width:100%;padding:8px;border:1px solid #e2e8f0;border-radius:6px" />
1496
1496
  <button type="button" class="update-zap-btn" style="padding:8px 12px;border:none;border-radius:6px;background:#7f00ff;color:#fff">Update Zap</button>
1497
1497
  </div>`}
1498
- ${I?"":`<div class="comment-container">
1498
+ ${P?"":`<div class="comment-container">
1499
1499
  <input type="text" placeholder="Comment (optional)" class="comment-input" style="width:100%;padding:8px;border:1px solid #e2e8f0;border-radius:6px" />
1500
1500
  <button type="button" class="add-comment-btn" style="padding:8px 12px;border:none;border-radius:6px;background:#7f00ff;color:#fff">Add</button>
1501
1501
  </div>`}
@@ -1506,7 +1506,7 @@ Minimum version required to store current data is: `+o+`.
1506
1506
  <div class="loading-overlay"><div class="loader"></div></div>
1507
1507
  <div class="success-overlay">⚡ Thank you!</div>
1508
1508
  </div>
1509
- `,k.showModal();const R=k.querySelector(".nostr-base-dialog")||((S=k.shadowRoot)==null?void 0:S.querySelector(".nostr-base-dialog"))||document.body.querySelector(".nostr-base-dialog");if(!R)throw console.error("[showZapDialog] Failed to find dialog element after showModal()"),new Error("Dialog element not found. The dialog may not have been created properly.");const $=R,B=$.querySelector(".amount-buttons");B&&B.addEventListener("click",async E=>{const L=E.target;if(L.tagName==="BUTTON"){const M=Number(L.dataset.val);if(!isNaN(M)){f=M,w(B,M);const U=$.querySelector(".cta-btn");U.disabled=!0,await x($)}}});const O=$.querySelector(".custom-amount");O&&O.addEventListener("input",async E=>{const L=Number(E.target.value);if(L>0){f=L,B&&w(B,-1);const M=$.querySelector(".cta-btn");M.disabled=!0}});const H=$.querySelector(".comment-input");H&&H.addEventListener("input",E=>{p=E.target.value.slice(0,200)});const T=async()=>{b&&(await navigator.clipboard.writeText(b),$.querySelector(".copy-btn").textContent="Copied!",setTimeout(()=>{$.querySelector(".copy-btn").textContent="Copy invoice"},1500))};$.querySelector(".copy-btn").onclick=T,$.querySelector("img.qr").onclick=T;const A=$.querySelector(".update-zap-btn");A&&A.addEventListener("click",async()=>{const E=Number(O==null?void 0:O.value);!isNaN(E)&&E>0&&(f=E,A.disabled=!0,await x($),A.disabled=!1)});const N=$.querySelector(".add-comment-btn");N&&N.addEventListener("click",async()=>{N.disabled=!0,await x($),N.disabled=!1}),$.querySelector(".cta-btn").onclick=async()=>{if(b){if(window.webln)try{await window.webln.enable(),await window.webln.sendPayment(b),P();return}catch(E){console.error("Nostr-Components: Zap button: webln payment failed",E),$.close()}window.location.href=`lightning:${b}`}};function P(){$.classList.add("success");const E=$.querySelector(".success-overlay");E.style.opacity="1",E.style.pointerEvents="none",$.querySelectorAll(".amount-buttons, .update-zap-container, .comment-container, .cta-btn, .copy-btn").forEach(M=>{M instanceof HTMLElement&&(M.style.display="none")})}if($.addEventListener("close",()=>{v&&v()}),s){const E=s;$.querySelector(".cta-btn").style.background=E,$.querySelector(".cta-btn").style.color=getContrastingTextColor(E)}if(await x($),B&&h.includes(f))w(B,f);else if(!I){const E=$.querySelector(".custom-amount");E&&(E.value=String(f)),B&&w(B,-1)}return k}function getContrastingTextColor(n){n=n.replace("#",""),n.length===3&&(n=n.split("").map(o=>o+o).join(""));const e=parseInt(n.slice(0,2),16),t=parseInt(n.slice(2,4),16),r=parseInt(n.slice(4,6),16);return(e*299+t*587+r*114)/1e3>125?"#000":"#fff"}const getHelpDialogStyles$1=()=>`
1509
+ `,k.showModal();const R=k.querySelector(".nostr-base-dialog")||((A=k.shadowRoot)==null?void 0:A.querySelector(".nostr-base-dialog"))||document.body.querySelector(".nostr-base-dialog");if(!R)throw console.error("[showZapDialog] Failed to find dialog element after showModal()"),new Error("Dialog element not found. The dialog may not have been created properly.");const N=R,B=N.querySelector(".amount-buttons");B&&B.addEventListener("click",async E=>{const $=E.target;if($.tagName==="BUTTON"){const M=Number($.dataset.val);if(!isNaN(M)){f=M,w(B,M);const U=N.querySelector(".cta-btn");U.disabled=!0,await x(N)}}});const O=N.querySelector(".custom-amount");O&&O.addEventListener("input",async E=>{const $=Number(E.target.value);if($>0){f=$,B&&w(B,-1);const M=N.querySelector(".cta-btn");M.disabled=!0}});const H=N.querySelector(".comment-input");H&&H.addEventListener("input",E=>{p=E.target.value.slice(0,200)});const S=async()=>{b&&(await navigator.clipboard.writeText(b),N.querySelector(".copy-btn").textContent="Copied!",setTimeout(()=>{N.querySelector(".copy-btn").textContent="Copy invoice"},1500))};N.querySelector(".copy-btn").onclick=S,N.querySelector("img.qr").onclick=S;const _=N.querySelector(".update-zap-btn");_&&_.addEventListener("click",async()=>{const E=Number(O==null?void 0:O.value);!isNaN(E)&&E>0&&(f=E,_.disabled=!0,await x(N),_.disabled=!1)});const L=N.querySelector(".add-comment-btn");L&&L.addEventListener("click",async()=>{L.disabled=!0,await x(N),L.disabled=!1}),N.querySelector(".cta-btn").onclick=async()=>{if(b){if(window.webln)try{await window.webln.enable(),await window.webln.sendPayment(b),I();return}catch(E){console.error("Nostr-Components: Zap button: webln payment failed",E),N.close()}window.location.href=`lightning:${b}`}};function I(){N.classList.add("success");const E=N.querySelector(".success-overlay");E.style.opacity="1",E.style.pointerEvents="none",N.querySelectorAll(".amount-buttons, .update-zap-container, .comment-container, .cta-btn, .copy-btn").forEach(M=>{M instanceof HTMLElement&&(M.style.display="none")})}if(N.addEventListener("close",()=>{v&&v()}),s){const E=s;N.querySelector(".cta-btn").style.background=E,N.querySelector(".cta-btn").style.color=getContrastingTextColor(E)}if(await x(N),B&&h.includes(f))w(B,f);else if(!P){const E=N.querySelector(".custom-amount");E&&(E.value=String(f)),B&&w(B,-1)}return k}function getContrastingTextColor(n){n=n.replace("#",""),n.length===3&&(n=n.split("").map(o=>o+o).join(""));const e=parseInt(n.slice(0,2),16),t=parseInt(n.slice(2,4),16),r=parseInt(n.slice(4,6),16);return(e*299+t*587+r*114)/1e3>125?"#000":"#fff"}const getHelpDialogStyles$1=()=>`
1510
1510
  /* Help Dialog Content Styles */
1511
1511
  .help-content {
1512
1512
  padding: var(--nostrc-spacing-md, 12px);
@@ -2008,10 +2008,10 @@ Minimum version required to store current data is: `+o+`.
2008
2008
  max-width: 250px;
2009
2009
  white-space: pre-line;
2010
2010
  }
2011
- `)}class NostrZap extends NostrUserComponent{constructor(){super();g(this,"zapActionStatus",this.channel("zapAction"));g(this,"zapListStatus",this.channel("zapList"));g(this,"totalZapAmount",null);g(this,"cachedZapDetails",[]);g(this,"cachedAmountDialog",null);this.zapListStatus.set(NCStatus.Loading)}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),this.attachDelegatedListeners(),this.render()}static get observedAttributes(){return[...super.observedAttributes,"text","amount","default-amount","url"]}attributeChangedCallback(t,r,s){r!==s&&(super.attributeChangedCallback(t,r,s),this.render())}disconnectedCallback(){this.cachedAmountDialog&&typeof this.cachedAmountDialog.close=="function"&&this.cachedAmountDialog.close()}onStatusChange(t){this.render()}onUserReady(t,r){this.render(),this.updateZapCount()}validateInputs(){if(!super.validateInputs())return this.zapActionStatus.set(NCStatus.Idle),this.zapListStatus.set(NCStatus.Idle),!1;const t=this.getAttribute("text"),r=this.getAttribute("amount"),s=this.getAttribute("default-amount"),o=this.getAttribute("url"),a=this.tagName.toLowerCase();let u=null;if(t&&t.length>128)u="Max text length: 128 characters";else if(r){const c=Number(r);isNaN(c)||c<=0?u="Invalid amount":c>21e4&&(u="Amount too high (max 210,000 sats)")}else if(s){const c=Number(s);isNaN(c)||c<=0?u="Invalid default-amount":c>21e4&&(u="Default-amount too high (max 210,000 sats)")}else o&&(isValidUrl(o)||(u="Invalid URL format"));return u?(this.zapActionStatus.set(NCStatus.Error,u),this.zapListStatus.set(NCStatus.Error,u),this.userStatus.set(NCStatus.Idle),console.error(`Nostr-Components: ${a}: ${u}`),!1):!0}async handleZapClick(){if(this.userStatus.get()===NCStatus.Ready){this.zapActionStatus.set(NCStatus.Loading),this.render();try{if(!this.user){this.zapActionStatus.set(NCStatus.Error,"Could not resolve user to zap."),this.render();return}const t=this.getRelays().join(","),r=this.user.npub;this.cachedAmountDialog=await init({npub:r,relays:t,cachedDialogComponent:this.cachedAmountDialog,theme:this.theme==="dark"?"dark":"light",fixedAmount:(()=>{const s=this.getAttribute("amount");if(!s)return;const o=Number(s);if(isNaN(o)||o<=0||o>21e4){console.error("Nostr-Components: Zap button: Max zap amount: 210,000 sats");return}return o})(),defaultAmount:(()=>{const s=this.getAttribute("default-amount");if(!s)return 21;const o=Number(s);return isNaN(o)||o<=0||o>21e4?(console.error("Nostr-Components: Zap button: Max zap amount: 210,000 sats"),21):o})(),url:this.getAttribute("url")||void 0,anon:!1}),this.zapActionStatus.set(NCStatus.Ready)}catch(t){this.zapActionStatus.set(NCStatus.Error,(t==null?void 0:t.message)||"Unable to zap")}finally{this.render()}}}async handleHelpClick(){try{await showHelpDialog$1(this.theme==="dark"?"dark":"light")}catch(t){console.error("Error showing help dialog:",t)}}async handleZappersClick(){if(this.cachedZapDetails.length!==0)try{await openZappersDialog({zapDetails:this.cachedZapDetails,theme:this.theme==="dark"?"dark":"light"})}catch(t){console.error("Nostr-Components: Zap button: Error opening zappers dialog",t)}}attachDelegatedListeners(){this.delegateEvent("click",".nostr-zap-button",t=>{var r,s;(r=t.preventDefault)==null||r.call(t),(s=t.stopPropagation)==null||s.call(t),this.handleZapClick()}),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()}),this.delegateEvent("click",".total-zap-amount",t=>{var r,s;(r=t.preventDefault)==null||r.call(t),(s=t.stopPropagation)==null||s.call(t),this.handleZappersClick()})}async updateZapCount(){if(this.user)try{this.zapListStatus.set(NCStatus.Loading),this.render(),await this.ensureNostrConnected();const t=await fetchTotalZapAmount({pubkey:this.user.pubkey,relays:this.getRelays(),url:this.getAttribute("url")||void 0});this.totalZapAmount=t.totalAmount,this.cachedZapDetails=t.zapDetails,this.zapListStatus.set(NCStatus.Ready)}catch(t){console.error("Nostr-Components: Zap button: Failed to fetch zap count",t),this.totalZapAmount=null,this.zapListStatus.set(NCStatus.Error)}finally{this.render()}}renderContent(){const t=this.userStatus.get()==NCStatus.Loading,r=this.zapListStatus.get()==NCStatus.Loading,s=this.computeOverall()===NCStatus.Error,o=this.errorMessage,a=this.getAttribute("text")||"Zap",u={isLoading:t,isAmountLoading:r,isError:s,isSuccess:!1,errorMessage:o,buttonText:a,totalZapAmount:this.totalZapAmount,hasZaps:this.cachedZapDetails.length>0};this.shadowRoot.innerHTML=`
2011
+ `)}class NostrZap extends NostrUserComponent{constructor(){super();g(this,"zapActionStatus",this.channel("zapAction"));g(this,"zapListStatus",this.channel("zapList"));g(this,"totalZapAmount",null);g(this,"cachedZapDetails",[]);g(this,"cachedAmountDialog",null);this.zapListStatus.set(NCStatus.Loading)}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),this.attachDelegatedListeners(),this.render()}static get observedAttributes(){return[...super.observedAttributes,"text","amount","default-amount","url"]}attributeChangedCallback(t,r,s){r!==s&&(super.attributeChangedCallback(t,r,s),this.render())}disconnectedCallback(){this.cachedAmountDialog&&typeof this.cachedAmountDialog.close=="function"&&this.cachedAmountDialog.close()}onStatusChange(t){this.render()}onUserReady(t,r){this.render(),this.updateZapCount()}validateInputs(){if(!super.validateInputs())return this.zapActionStatus.set(NCStatus.Idle),this.zapListStatus.set(NCStatus.Idle),!1;const t=this.getAttribute("text"),r=this.getAttribute("amount"),s=this.getAttribute("default-amount"),o=this.getAttribute("url"),a=this.tagName.toLowerCase();let u=null;if(t&&t.length>128)u="Max text length: 128 characters";else if(r){const c=Number(r);isNaN(c)||c<=0?u="Invalid amount":c>21e4&&(u="Amount too high (max 210,000 sats)")}else if(s){const c=Number(s);isNaN(c)||c<=0?u="Invalid default-amount":c>21e4&&(u="Default-amount too high (max 210,000 sats)")}else o&&(isValidUrl(o)||(u="Invalid URL format"));return u?(this.zapActionStatus.set(NCStatus.Error,u),this.zapListStatus.set(NCStatus.Error,u),this.userStatus.set(NCStatus.Idle),console.error(`Nostr-Components: ${a}: ${u}`),!1):!0}async handleZapClick(){if(this.userStatus.get()===NCStatus.Ready){this.zapActionStatus.set(NCStatus.Loading),this.render();try{if(!this.user){this.zapActionStatus.set(NCStatus.Error,"Could not resolve user to zap."),this.render();return}const t=this.getRelays().join(","),r=this.user.npub;this.cachedAmountDialog=await init$1({npub:r,relays:t,cachedDialogComponent:this.cachedAmountDialog,theme:this.theme==="dark"?"dark":"light",fixedAmount:(()=>{const s=this.getAttribute("amount");if(!s)return;const o=Number(s);if(isNaN(o)||o<=0||o>21e4){console.error("Nostr-Components: Zap button: Max zap amount: 210,000 sats");return}return o})(),defaultAmount:(()=>{const s=this.getAttribute("default-amount");if(!s)return 21;const o=Number(s);return isNaN(o)||o<=0||o>21e4?(console.error("Nostr-Components: Zap button: Max zap amount: 210,000 sats"),21):o})(),url:this.getAttribute("url")||void 0,anon:!1}),this.zapActionStatus.set(NCStatus.Ready)}catch(t){this.zapActionStatus.set(NCStatus.Error,(t==null?void 0:t.message)||"Unable to zap")}finally{this.render()}}}async handleHelpClick(){try{await showHelpDialog$1(this.theme==="dark"?"dark":"light")}catch(t){console.error("Error showing help dialog:",t)}}async handleZappersClick(){if(this.cachedZapDetails.length!==0)try{await openZappersDialog({zapDetails:this.cachedZapDetails,theme:this.theme==="dark"?"dark":"light"})}catch(t){console.error("Nostr-Components: Zap button: Error opening zappers dialog",t)}}attachDelegatedListeners(){this.delegateEvent("click",".nostr-zap-button",t=>{var r,s;(r=t.preventDefault)==null||r.call(t),(s=t.stopPropagation)==null||s.call(t),this.handleZapClick()}),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()}),this.delegateEvent("click",".total-zap-amount",t=>{var r,s;(r=t.preventDefault)==null||r.call(t),(s=t.stopPropagation)==null||s.call(t),this.handleZappersClick()})}async updateZapCount(){if(this.user)try{this.zapListStatus.set(NCStatus.Loading),this.render(),await this.ensureNostrConnected();const t=await fetchTotalZapAmount({pubkey:this.user.pubkey,relays:this.getRelays(),url:this.getAttribute("url")||void 0});this.totalZapAmount=t.totalAmount,this.cachedZapDetails=t.zapDetails,this.zapListStatus.set(NCStatus.Ready)}catch(t){console.error("Nostr-Components: Zap button: Failed to fetch zap count",t),this.totalZapAmount=null,this.zapListStatus.set(NCStatus.Error)}finally{this.render()}}renderContent(){const t=this.userStatus.get()==NCStatus.Loading,r=this.zapListStatus.get()==NCStatus.Loading,s=this.computeOverall()===NCStatus.Error,o=this.errorMessage,a=this.getAttribute("text")||"Zap",u={isLoading:t,isAmountLoading:r,isError:s,isSuccess:!1,errorMessage:o,buttonText:a,totalZapAmount:this.totalZapAmount,hasZaps:this.cachedZapDetails.length>0};this.shadowRoot.innerHTML=`
2012
2012
  ${getZapButtonStyles()}
2013
2013
  ${renderZapButton(u)}
2014
- `}}customElements.define("nostr-zap",NostrZap);function escapeHtml(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function formatTimeAgo(n){const t=Date.now()/1e3-n;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:new Date(n*1e3).toLocaleDateString()}function getUserDisplayName(n){var e,t;return(e=n.userProfile)!=null&&e.displayName?n.userProfile.displayName:(t=n.userProfile)!=null&&t.name?n.userProfile.name:`${n.pubkey.slice(0,8)}...${n.pubkey.slice(-4)}`}function getUserAvatar(n){var e,t;if((e=n.userProfile)!=null&&e.image&&n.userProfile.image.trim()!==""){let r=n.userProfile.image.trim();return console.log("Processing image URL:",r,"for user:",n.userProfile.name||n.pubkey),(r.startsWith("Qm")||r.startsWith("bafy"))&&(r=`https://ipfs.io/ipfs/${r}`,console.log("Converted IPFS to gateway URL:",r)),r.startsWith("//")&&(r="https:"+r,console.log("Added protocol to URL:",r)),console.log("Final image URL:",r),r}return console.log("No image found for user:",((t=n.userProfile)==null?void 0:t.name)||n.pubkey,"using default"),"./assets/default_dp.png"}function renderComment(n,e=!1,t=null,r=null,s="anon",o=!1){const a=getUserDisplayName(n),u=getUserAvatar(n),c=formatTimeAgo(n.created_at),l=n.depth||0,h=6,f=t===n.id;return`
2014
+ `}}customElements.define("nostr-zap",NostrZap);function escapeHtml(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function formatTimeAgo(n){const t=Date.now()/1e3-n;return t<60?"just now":t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:t<2592e3?`${Math.floor(t/86400)}d ago`:new Date(n*1e3).toLocaleDateString()}function getUserDisplayName(n){var e,t;return(e=n.userProfile)!=null&&e.displayName?n.userProfile.displayName:(t=n.userProfile)!=null&&t.name?n.userProfile.name:`${n.pubkey.slice(0,8)}...${n.pubkey.slice(-4)}`}function getUserAvatar(n){var e,t;if((e=n.userProfile)!=null&&e.image&&n.userProfile.image.trim()!==""){let r=n.userProfile.image.trim();return console.log("Processing image URL:",r,"for user:",n.userProfile.name||n.pubkey),(r.startsWith("Qm")||r.startsWith("bafy"))&&(r=`https://ipfs.io/ipfs/${r}`,console.log("Converted IPFS to gateway URL:",r)),r.startsWith("//")&&(r="https:"+r,console.log("Added protocol to URL:",r)),console.log("Final image URL:",r),r}return console.log("No image found for user:",((t=n.userProfile)==null?void 0:t.name)||n.pubkey,"using default"),"../../assets/default_dp.png"}function renderComment(n,e=!1,t=null,r=null,s="anon",o=!1){const a=getUserDisplayName(n),u=getUserAvatar(n),c=formatTimeAgo(n.created_at),l=n.depth||0,h=6,f=t===n.id;return`
2015
2015
  <div class="modern-comment" data-comment-id="${escapeHtml(n.id)}" data-depth="${l}">
2016
2016
  <div class="comment-content-wrapper">
2017
2017
  <div class="comment-avatar-section">
@@ -2040,7 +2040,7 @@ Minimum version required to store current data is: `+o+`.
2040
2040
  </div>
2041
2041
  `:""}
2042
2042
  </div>
2043
- `}function renderInlineReplyForm(n,e,t="anon",r=!1){let s="./assets/default_dp.png";if(console.log("renderInlineReplyForm - currentUserProfile:",e),e!=null&&e.image&&e.image.trim()!==""){let a=e.image.trim();console.log("Inline reply form - Processing image URL:",a),(a.startsWith("Qm")||a.startsWith("bafy"))&&(a=`https://ipfs.io/ipfs/${a}`,console.log("Inline reply form - Converted IPFS to gateway URL:",a)),a.startsWith("//")&&(a="https:"+a,console.log("Inline reply form - Added protocol to URL:",a)),console.log("Inline reply form - Final image URL:",a),s=a}else console.log("Inline reply form - No image found, using default");const o=getUserDisplayName(n);return`
2043
+ `}function renderInlineReplyForm(n,e,t="anon",r=!1){let s="../../assets/default_dp.png";if(console.log("renderInlineReplyForm - currentUserProfile:",e),e!=null&&e.image&&e.image.trim()!==""){let a=e.image.trim();console.log("Inline reply form - Processing image URL:",a),(a.startsWith("Qm")||a.startsWith("bafy"))&&(a=`https://ipfs.io/ipfs/${a}`,console.log("Inline reply form - Converted IPFS to gateway URL:",a)),a.startsWith("//")&&(a="https:"+a,console.log("Inline reply form - Added protocol to URL:",a)),console.log("Inline reply form - Final image URL:",a),s=a}else console.log("Inline reply form - No image found, using default");const o=getUserDisplayName(n);return`
2044
2044
  <div class="inline-reply-form">
2045
2045
  <div class="reply-context">
2046
2046
  <span class="reply-context-text">💬 Replying to <strong>${escapeHtml(o)}</strong></span>
@@ -2912,8 +2912,8 @@ Minimum version required to store current data is: `+o+`.
2912
2912
  }
2913
2913
  }
2914
2914
  </style>
2915
- `}/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries,setPrototypeOf,isFrozen,getPrototypeOf,getOwnPropertyDescriptor}=Object;let{freeze,seal,create}=Object,{apply,construct}=typeof Reflect<"u"&&Reflect;freeze||(freeze=function(e){return e}),seal||(seal=function(e){return e}),apply||(apply=function(e,t,r){return e.apply(t,r)}),construct||(construct=function(e,t){return new e(...t)});const arrayForEach=unapply(Array.prototype.forEach),arrayLastIndexOf=unapply(Array.prototype.lastIndexOf),arrayPop=unapply(Array.prototype.pop),arrayPush=unapply(Array.prototype.push),arraySplice=unapply(Array.prototype.splice),stringToLowerCase=unapply(String.prototype.toLowerCase),stringToString=unapply(String.prototype.toString),stringMatch=unapply(String.prototype.match),stringReplace=unapply(String.prototype.replace),stringIndexOf=unapply(String.prototype.indexOf),stringTrim=unapply(String.prototype.trim),objectHasOwnProperty=unapply(Object.prototype.hasOwnProperty),regExpTest=unapply(RegExp.prototype.test),typeErrorCreate=unconstruct(TypeError);function unapply(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,r=new Array(t>1?t-1:0),s=1;s<t;s++)r[s-1]=arguments[s];return apply(n,e,r)}}function unconstruct(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return construct(n,t)}}function addToSet(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:stringToLowerCase;setPrototypeOf&&setPrototypeOf(n,null);let r=e.length;for(;r--;){let s=e[r];if(typeof s=="string"){const o=t(s);o!==s&&(isFrozen(e)||(e[r]=o),s=o)}n[s]=!0}return n}function cleanArray(n){for(let e=0;e<n.length;e++)objectHasOwnProperty(n,e)||(n[e]=null);return n}function clone(n){const e=create(null);for(const[t,r]of entries(n))objectHasOwnProperty(n,t)&&(Array.isArray(r)?e[t]=cleanArray(r):r&&typeof r=="object"&&r.constructor===Object?e[t]=clone(r):e[t]=r);return e}function lookupGetter(n,e){for(;n!==null;){const r=getOwnPropertyDescriptor(n,e);if(r){if(r.get)return unapply(r.get);if(typeof r.value=="function")return unapply(r.value)}n=getPrototypeOf(n)}function t(){return null}return t}const html$1=freeze(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),svg$1=freeze(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),svgFilters=freeze(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),svgDisallowed=freeze(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),mathMl$1=freeze(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),mathMlDisallowed=freeze(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),text=freeze(["#text"]),html=freeze(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),svg=freeze(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),mathMl=freeze(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),xml=freeze(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),MUSTACHE_EXPR=seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ERB_EXPR=seal(/<%[\w\W]*|[\w\W]*%>/gm),TMPLIT_EXPR=seal(/\$\{[\w\W]*/gm),DATA_ATTR=seal(/^data-[\-\w.\u00B7-\uFFFF]+$/),ARIA_ATTR=seal(/^aria-[\-\w]+$/),IS_ALLOWED_URI=seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),IS_SCRIPT_OR_DATA=seal(/^(?:\w+script|data):/i),ATTR_WHITESPACE=seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),DOCTYPE_NAME=seal(/^html$/i),CUSTOM_ELEMENT=seal(/^[a-z][.\w]*(-[.\w]+)+$/i);var EXPRESSIONS=Object.freeze({__proto__:null,ARIA_ATTR,ATTR_WHITESPACE,CUSTOM_ELEMENT,DATA_ATTR,DOCTYPE_NAME,ERB_EXPR,IS_ALLOWED_URI,IS_SCRIPT_OR_DATA,MUSTACHE_EXPR,TMPLIT_EXPR});const NODE_TYPE={element:1,text:3,progressingInstruction:7,comment:8,document:9},getGlobal=function n(){return typeof window>"u"?null:window},_createTrustedTypesPolicy=function n(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(r=t.getAttribute(s));const o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},_createHooksMap=function n(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function createDOMPurify(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:getGlobal();const e=j=>createDOMPurify(j);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==NODE_TYPE.document||!n.Element)return e.isSupported=!1,e;let{document:t}=n;const r=t,s=r.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:u,Element:c,NodeFilter:l,NamedNodeMap:h=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:f,DOMParser:p,trustedTypes:b}=n,v=c.prototype,m=lookupGetter(v,"cloneNode"),y=lookupGetter(v,"remove"),w=lookupGetter(v,"nextSibling"),x=lookupGetter(v,"childNodes"),k=lookupGetter(v,"parentNode");if(typeof a=="function"){const j=t.createElement("template");j.content&&j.content.ownerDocument&&(t=j.content.ownerDocument)}let C,I="";const{implementation:R,createNodeIterator:$,createDocumentFragment:B,getElementsByTagName:O}=t,{importNode:H}=r;let T=_createHooksMap();e.isSupported=typeof entries=="function"&&typeof k=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:A,ERB_EXPR:N,TMPLIT_EXPR:P,DATA_ATTR:S,ARIA_ATTR:E,IS_SCRIPT_OR_DATA:L,ATTR_WHITESPACE:M,CUSTOM_ELEMENT:U}=EXPRESSIONS;let{IS_ALLOWED_URI:z}=EXPRESSIONS,D=null;const V=addToSet({},[...html$1,...svg$1,...svgFilters,...mathMl$1,...text]);let W=null;const Z=addToSet({},[...html,...svg,...mathMl,...xml]);let G=Object.seal(create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),K=null,ne=null,ae=!0,se=!0,pe=!1,ye=!0,J=!1,X=!0,te=!1,be=!1,Be=!1,Me=!1,We=!1,Ge=!1,at=!0,ct=!1;const Rt="user-content-";let Je=!0,ze=!1,De={},Ue=null;const lt=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let dt=null;const ht=addToSet({},["audio","video","img","source","image","track"]);let Qe=null;const ft=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ze="http://www.w3.org/1998/Math/MathML",Ke="http://www.w3.org/2000/svg",xe="http://www.w3.org/1999/xhtml";let Oe=xe,et=!1,tt=null;const Nt=addToSet({},[Ze,Ke,xe],stringToString);let Ye=addToSet({},["mi","mo","mn","ms","mtext"]),Xe=addToSet({},["annotation-xml"]);const Lt=addToSet({},["title","style","font","a","script"]);let qe=null;const Pt=["application/xhtml+xml","text/html"],It="text/html";let ie=null,Fe=null;const Bt=t.createElement("form"),pt=function(_){return _ instanceof RegExp||_ instanceof Function},nt=function(){let _=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Fe&&Fe===_)){if((!_||typeof _!="object")&&(_={}),_=clone(_),qe=Pt.indexOf(_.PARSER_MEDIA_TYPE)===-1?It:_.PARSER_MEDIA_TYPE,ie=qe==="application/xhtml+xml"?stringToString:stringToLowerCase,D=objectHasOwnProperty(_,"ALLOWED_TAGS")?addToSet({},_.ALLOWED_TAGS,ie):V,W=objectHasOwnProperty(_,"ALLOWED_ATTR")?addToSet({},_.ALLOWED_ATTR,ie):Z,tt=objectHasOwnProperty(_,"ALLOWED_NAMESPACES")?addToSet({},_.ALLOWED_NAMESPACES,stringToString):Nt,Qe=objectHasOwnProperty(_,"ADD_URI_SAFE_ATTR")?addToSet(clone(ft),_.ADD_URI_SAFE_ATTR,ie):ft,dt=objectHasOwnProperty(_,"ADD_DATA_URI_TAGS")?addToSet(clone(ht),_.ADD_DATA_URI_TAGS,ie):ht,Ue=objectHasOwnProperty(_,"FORBID_CONTENTS")?addToSet({},_.FORBID_CONTENTS,ie):lt,K=objectHasOwnProperty(_,"FORBID_TAGS")?addToSet({},_.FORBID_TAGS,ie):clone({}),ne=objectHasOwnProperty(_,"FORBID_ATTR")?addToSet({},_.FORBID_ATTR,ie):clone({}),De=objectHasOwnProperty(_,"USE_PROFILES")?_.USE_PROFILES:!1,ae=_.ALLOW_ARIA_ATTR!==!1,se=_.ALLOW_DATA_ATTR!==!1,pe=_.ALLOW_UNKNOWN_PROTOCOLS||!1,ye=_.ALLOW_SELF_CLOSE_IN_ATTR!==!1,J=_.SAFE_FOR_TEMPLATES||!1,X=_.SAFE_FOR_XML!==!1,te=_.WHOLE_DOCUMENT||!1,Me=_.RETURN_DOM||!1,We=_.RETURN_DOM_FRAGMENT||!1,Ge=_.RETURN_TRUSTED_TYPE||!1,Be=_.FORCE_BODY||!1,at=_.SANITIZE_DOM!==!1,ct=_.SANITIZE_NAMED_PROPS||!1,Je=_.KEEP_CONTENT!==!1,ze=_.IN_PLACE||!1,z=_.ALLOWED_URI_REGEXP||IS_ALLOWED_URI,Oe=_.NAMESPACE||xe,Ye=_.MATHML_TEXT_INTEGRATION_POINTS||Ye,Xe=_.HTML_INTEGRATION_POINTS||Xe,G=_.CUSTOM_ELEMENT_HANDLING||{},_.CUSTOM_ELEMENT_HANDLING&&pt(_.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(G.tagNameCheck=_.CUSTOM_ELEMENT_HANDLING.tagNameCheck),_.CUSTOM_ELEMENT_HANDLING&&pt(_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(G.attributeNameCheck=_.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),_.CUSTOM_ELEMENT_HANDLING&&typeof _.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(G.allowCustomizedBuiltInElements=_.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),J&&(se=!1),We&&(Me=!0),De&&(D=addToSet({},text),W=[],De.html===!0&&(addToSet(D,html$1),addToSet(W,html)),De.svg===!0&&(addToSet(D,svg$1),addToSet(W,svg),addToSet(W,xml)),De.svgFilters===!0&&(addToSet(D,svgFilters),addToSet(W,svg),addToSet(W,xml)),De.mathMl===!0&&(addToSet(D,mathMl$1),addToSet(W,mathMl),addToSet(W,xml))),_.ADD_TAGS&&(D===V&&(D=clone(D)),addToSet(D,_.ADD_TAGS,ie)),_.ADD_ATTR&&(W===Z&&(W=clone(W)),addToSet(W,_.ADD_ATTR,ie)),_.ADD_URI_SAFE_ATTR&&addToSet(Qe,_.ADD_URI_SAFE_ATTR,ie),_.FORBID_CONTENTS&&(Ue===lt&&(Ue=clone(Ue)),addToSet(Ue,_.FORBID_CONTENTS,ie)),Je&&(D["#text"]=!0),te&&addToSet(D,["html","head","body"]),D.table&&(addToSet(D,["tbody"]),delete K.tbody),_.TRUSTED_TYPES_POLICY){if(typeof _.TRUSTED_TYPES_POLICY.createHTML!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof _.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=_.TRUSTED_TYPES_POLICY,I=C.createHTML("")}else C===void 0&&(C=_createTrustedTypesPolicy(b,s)),C!==null&&typeof I=="string"&&(I=C.createHTML(""));freeze&&freeze(_),Fe=_}},gt=addToSet({},[...svg$1,...svgFilters,...svgDisallowed]),bt=addToSet({},[...mathMl$1,...mathMlDisallowed]),Mt=function(_){let F=k(_);(!F||!F.tagName)&&(F={namespaceURI:Oe,tagName:"template"});const q=stringToLowerCase(_.tagName),Y=stringToLowerCase(F.tagName);return tt[_.namespaceURI]?_.namespaceURI===Ke?F.namespaceURI===xe?q==="svg":F.namespaceURI===Ze?q==="svg"&&(Y==="annotation-xml"||Ye[Y]):!!gt[q]:_.namespaceURI===Ze?F.namespaceURI===xe?q==="math":F.namespaceURI===Ke?q==="math"&&Xe[Y]:!!bt[q]:_.namespaceURI===xe?F.namespaceURI===Ke&&!Xe[Y]||F.namespaceURI===Ze&&!Ye[Y]?!1:!bt[q]&&(Lt[q]||!gt[q]):!!(qe==="application/xhtml+xml"&&tt[_.namespaceURI]):!1},ve=function(_){arrayPush(e.removed,{element:_});try{k(_).removeChild(_)}catch{y(_)}},He=function(_,F){try{arrayPush(e.removed,{attribute:F.getAttributeNode(_),from:F})}catch{arrayPush(e.removed,{attribute:null,from:F})}if(F.removeAttribute(_),_==="is")if(Me||We)try{ve(F)}catch{}else try{F.setAttribute(_,"")}catch{}},mt=function(_){let F=null,q=null;if(Be)_="<remove></remove>"+_;else{const re=stringMatch(_,/^[\r\n\t ]+/);q=re&&re[0]}qe==="application/xhtml+xml"&&Oe===xe&&(_='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+_+"</body></html>");const Y=C?C.createHTML(_):_;if(Oe===xe)try{F=new p().parseFromString(Y,qe)}catch{}if(!F||!F.documentElement){F=R.createDocument(Oe,"template",null);try{F.documentElement.innerHTML=et?I:Y}catch{}}const ue=F.body||F.documentElement;return _&&q&&ue.insertBefore(t.createTextNode(q),ue.childNodes[0]||null),Oe===xe?O.call(F,te?"html":"body")[0]:te?F.documentElement:ue},yt=function(_){return $.call(_.ownerDocument||_,_,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},rt=function(_){return _ instanceof f&&(typeof _.nodeName!="string"||typeof _.textContent!="string"||typeof _.removeChild!="function"||!(_.attributes instanceof h)||typeof _.removeAttribute!="function"||typeof _.setAttribute!="function"||typeof _.namespaceURI!="string"||typeof _.insertBefore!="function"||typeof _.hasChildNodes!="function")},vt=function(_){return typeof u=="function"&&_ instanceof u};function Ee(j,_,F){arrayForEach(j,q=>{q.call(e,_,F,Fe)})}const wt=function(_){let F=null;if(Ee(T.beforeSanitizeElements,_,null),rt(_))return ve(_),!0;const q=ie(_.nodeName);if(Ee(T.uponSanitizeElement,_,{tagName:q,allowedTags:D}),X&&_.hasChildNodes()&&!vt(_.firstElementChild)&&regExpTest(/<[/\w!]/g,_.innerHTML)&&regExpTest(/<[/\w!]/g,_.textContent)||_.nodeType===NODE_TYPE.progressingInstruction||X&&_.nodeType===NODE_TYPE.comment&&regExpTest(/<[/\w]/g,_.data))return ve(_),!0;if(!D[q]||K[q]){if(!K[q]&&Et(q)&&(G.tagNameCheck instanceof RegExp&&regExpTest(G.tagNameCheck,q)||G.tagNameCheck instanceof Function&&G.tagNameCheck(q)))return!1;if(Je&&!Ue[q]){const Y=k(_)||_.parentNode,ue=x(_)||_.childNodes;if(ue&&Y){const re=ue.length;for(let de=re-1;de>=0;--de){const ke=m(ue[de],!0);ke.__removalCount=(_.__removalCount||0)+1,Y.insertBefore(ke,w(_))}}}return ve(_),!0}return _ instanceof c&&!Mt(_)||(q==="noscript"||q==="noembed"||q==="noframes")&&regExpTest(/<\/no(script|embed|frames)/i,_.innerHTML)?(ve(_),!0):(J&&_.nodeType===NODE_TYPE.text&&(F=_.textContent,arrayForEach([A,N,P],Y=>{F=stringReplace(F,Y," ")}),_.textContent!==F&&(arrayPush(e.removed,{element:_.cloneNode()}),_.textContent=F)),Ee(T.afterSanitizeElements,_,null),!1)},xt=function(_,F,q){if(at&&(F==="id"||F==="name")&&(q in t||q in Bt))return!1;if(!(se&&!ne[F]&&regExpTest(S,F))){if(!(ae&&regExpTest(E,F))){if(!W[F]||ne[F]){if(!(Et(_)&&(G.tagNameCheck instanceof RegExp&&regExpTest(G.tagNameCheck,_)||G.tagNameCheck instanceof Function&&G.tagNameCheck(_))&&(G.attributeNameCheck instanceof RegExp&&regExpTest(G.attributeNameCheck,F)||G.attributeNameCheck instanceof Function&&G.attributeNameCheck(F))||F==="is"&&G.allowCustomizedBuiltInElements&&(G.tagNameCheck instanceof RegExp&&regExpTest(G.tagNameCheck,q)||G.tagNameCheck instanceof Function&&G.tagNameCheck(q))))return!1}else if(!Qe[F]){if(!regExpTest(z,stringReplace(q,M,""))){if(!((F==="src"||F==="xlink:href"||F==="href")&&_!=="script"&&stringIndexOf(q,"data:")===0&&dt[_])){if(!(pe&&!regExpTest(L,stringReplace(q,M,"")))){if(q)return!1}}}}}}return!0},Et=function(_){return _!=="annotation-xml"&&stringMatch(_,U)},kt=function(_){Ee(T.beforeSanitizeAttributes,_,null);const{attributes:F}=_;if(!F||rt(_))return;const q={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:W,forceKeepAttr:void 0};let Y=F.length;for(;Y--;){const ue=F[Y],{name:re,namespaceURI:de,value:ke}=ue,Ve=ie(re),st=ke;let ce=re==="value"?st:stringTrim(st);if(q.attrName=Ve,q.attrValue=ce,q.keepAttr=!0,q.forceKeepAttr=void 0,Ee(T.uponSanitizeAttribute,_,q),ce=q.attrValue,ct&&(Ve==="id"||Ve==="name")&&(He(re,_),ce=Rt+ce),X&&regExpTest(/((--!?|])>)|<\/(style|title)/i,ce)){He(re,_);continue}if(q.forceKeepAttr)continue;if(!q.keepAttr){He(re,_);continue}if(!ye&&regExpTest(/\/>/i,ce)){He(re,_);continue}J&&arrayForEach([A,N,P],Tt=>{ce=stringReplace(ce,Tt," ")});const St=ie(_.nodeName);if(!xt(St,Ve,ce)){He(re,_);continue}if(C&&typeof b=="object"&&typeof b.getAttributeType=="function"&&!de)switch(b.getAttributeType(St,Ve)){case"TrustedHTML":{ce=C.createHTML(ce);break}case"TrustedScriptURL":{ce=C.createScriptURL(ce);break}}if(ce!==st)try{de?_.setAttributeNS(de,re,ce):_.setAttribute(re,ce),rt(_)?ve(_):arrayPop(e.removed)}catch{He(re,_)}}Ee(T.afterSanitizeAttributes,_,null)},Dt=function j(_){let F=null;const q=yt(_);for(Ee(T.beforeSanitizeShadowDOM,_,null);F=q.nextNode();)Ee(T.uponSanitizeShadowNode,F,null),wt(F),kt(F),F.content instanceof o&&j(F.content);Ee(T.afterSanitizeShadowDOM,_,null)};return e.sanitize=function(j){let _=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},F=null,q=null,Y=null,ue=null;if(et=!j,et&&(j="<!-->"),typeof j!="string"&&!vt(j))if(typeof j.toString=="function"){if(j=j.toString(),typeof j!="string")throw typeErrorCreate("dirty is not a string, aborting")}else throw typeErrorCreate("toString is not a function");if(!e.isSupported)return j;if(be||nt(_),e.removed=[],typeof j=="string"&&(ze=!1),ze){if(j.nodeName){const ke=ie(j.nodeName);if(!D[ke]||K[ke])throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place")}}else if(j instanceof u)F=mt("<!---->"),q=F.ownerDocument.importNode(j,!0),q.nodeType===NODE_TYPE.element&&q.nodeName==="BODY"||q.nodeName==="HTML"?F=q:F.appendChild(q);else{if(!Me&&!J&&!te&&j.indexOf("<")===-1)return C&&Ge?C.createHTML(j):j;if(F=mt(j),!F)return Me?null:Ge?I:""}F&&Be&&ve(F.firstChild);const re=yt(ze?j:F);for(;Y=re.nextNode();)wt(Y),kt(Y),Y.content instanceof o&&Dt(Y.content);if(ze)return j;if(Me){if(We)for(ue=B.call(F.ownerDocument);F.firstChild;)ue.appendChild(F.firstChild);else ue=F;return(W.shadowroot||W.shadowrootmode)&&(ue=H.call(r,ue,!0)),ue}let de=te?F.outerHTML:F.innerHTML;return te&&D["!doctype"]&&F.ownerDocument&&F.ownerDocument.doctype&&F.ownerDocument.doctype.name&&regExpTest(DOCTYPE_NAME,F.ownerDocument.doctype.name)&&(de="<!DOCTYPE "+F.ownerDocument.doctype.name+`>
2916
- `+de),J&&arrayForEach([A,N,P],ke=>{de=stringReplace(de,ke," ")}),C&&Ge?C.createHTML(de):de},e.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};nt(j),be=!0},e.clearConfig=function(){Fe=null,be=!1},e.isValidAttribute=function(j,_,F){Fe||nt({});const q=ie(j),Y=ie(_);return xt(q,Y,F)},e.addHook=function(j,_){typeof _=="function"&&arrayPush(T[j],_)},e.removeHook=function(j,_){if(_!==void 0){const F=arrayLastIndexOf(T[j],_);return F===-1?void 0:arraySplice(T[j],F,1)[0]}return arrayPop(T[j])},e.removeHooks=function(j){T[j]=[]},e.removeAllHooks=function(){T=_createHooksMap()},e}var purify=createDOMPurify();class NostrComment extends HTMLElement{constructor(){super();g(this,"rendered",!1);g(this,"nostrService",NostrService.getInstance());g(this,"shadow");g(this,"theme","light");g(this,"isLoading",!0);g(this,"isError",!1);g(this,"errorMessage","");g(this,"comments",[]);g(this,"baseUrl","");g(this,"userPublicKey",null);g(this,"userPrivateKey",null);g(this,"currentUserProfile",null);g(this,"isSubmitting",!1);g(this,"replyingToComment",null);g(this,"commentAs","user");g(this,"hasNip07",!1);g(this,"anonPrivateKeyHex",null);g(this,"eventListeners",[]);g(this,"nip07MonitoringInterval",null);g(this,"loadVersion",0);g(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(",").map(r=>r.trim()):DEFAULT_RELAYS});g(this,"getTheme",()=>{this.theme="light";const t=this.getAttribute("theme");t&&(["light","dark"].includes(t)?this.theme=t:console.warn(`Invalid theme '${t}'. Accepted values are 'light', 'dark'`))});g(this,"getBaseUrl",()=>{const t=this.getAttribute("url");return normalizeURL$1(t||window.location.href)});g(this,"detectNip07Extension",()=>{const t=window.nostr;return t?typeof t.getPublicKey=="function"&&typeof t.signEvent=="function"?!0:(console.warn("NIP-07 extension detected but missing required methods"),!1):!1});g(this,"handleNip07StateChange",async()=>{const t=this.hasNip07,r=this.detectNip07Extension();if(t!==r&&(console.log("NIP-07 extension state changed:",r),this.hasNip07=r,r&&this.commentAs==="user"))try{await this.initializeUser(),this.render()}catch(s){console.warn("Failed to reconnect to NIP-07 extension:",s)}});g(this,"setupNip07StateMonitoring",()=>{const t=setInterval(async()=>{document.contains(this)&&await this.handleNip07StateChange()},2e3);this.nip07MonitoringInterval=t});g(this,"loadComments",async()=>{this.loadVersion++;const t=this.loadVersion;try{this.isLoading=!0,this.isError=!1,this.render();const r=this.getRelays();await this.nostrService.connectToNostr(r);const s={kinds:[1111],"#I":[this.baseUrl],limit:200},o=await this.nostrService.getNDK().fetchEvents(s),a=Array.from(o),u=new Map;a.forEach(v=>u.set(v.id,{content:v.content,id:v.id,tags:v.tags}));const c=[],l=new Set;for(const v of a){let m;const y=(v.tags||[]).filter(x=>x[0]==="e");for(let x=y.length-1;x>=0;x--){const k=y[x];if(k[3]==="reply"){m=k[1];break}}if(!m&&y.length>0){const x=y.filter(k=>k[3]!=="root");x.length>0?m=x[x.length-1][1]:m=y[y.length-1][1]}const w={id:v.id,pubkey:v.pubkey,content:v.content,created_at:v.created_at,replies:[],replyTo:m,depth:0};l.add(v.pubkey),c.push(w)}const h=Array.from(l).map(async v=>{try{console.log("Fetching profile for pubkey:",v);const m=await this.nostrService.getProfile({pubkey:v});return console.log("Profile fetched for",v,":",m),{pubkey:v,profile:m}}catch(m){return console.warn("Failed to fetch profile for:",v,m),{pubkey:v,profile:null}}}),f=await Promise.allSettled(h),p=new Map;if(f.forEach(v=>{if(v.status==="fulfilled"){const{pubkey:m,profile:y}=v.value;p.set(m,y)}}),c.forEach(v=>{v.userProfile=p.get(v.pubkey)||void 0,console.log("Attached profile to comment:",v.pubkey,"Profile:",v.userProfile)}),t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting");return}this.comments=this.buildCommentTree(c);const b=new Map;this.comments.forEach(v=>{const m=[v];for(;m.length;){const y=m.pop();b.set(y.id,y),y.replies.forEach(w=>m.push(w))}}),c.forEach(v=>{const m=v.replyTo?b.get(v.replyTo):void 0,y=m?m.content:"(no parent)";console.log(`[nostr-comment] recv: "${v.content}" -> parent: ${y}`)})}catch(r){if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting error handling");return}this.isError=!0,this.errorMessage=r instanceof Error?r.message:"Failed to load comments",console.error("Error loading comments:",r)}finally{if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting final state update");return}this.isLoading=!1,this.render()}});g(this,"buildCommentTree",t=>{const r=new Map,s=[];t.forEach(a=>{r.set(a.id,a)}),t.forEach(a=>{if(a.replyTo&&r.has(a.replyTo)){const u=r.get(a.replyTo);u.replies.push(a),u.replies.sort((c,l)=>c.created_at-l.created_at)}else s.push(a)});const o=(a,u)=>{for(const c of a)c.depth=u,c.replies&&c.replies.length&&o(c.replies,u+1)};return o(s,0),s.sort((a,u)=>u.created_at-a.created_at)});g(this,"initializeUser",async()=>{if(this.hasNip07=this.detectNip07Extension(),console.log("NIP-07 extension detected:",this.hasNip07),this.hasNip07&&this.commentAs==="user")try{this.userPublicKey=await window.nostr.getPublicKey(),console.log("Successfully connected to NIP-07 extension, public key:",this.userPublicKey),this.userPrivateKey=null,this.anonPrivateKeyHex=null}catch(t){console.warn("NIP-07 extension available but failed to get public key:",t),this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null}if(!this.userPublicKey){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,this.userPrivateKey=t;const{getPublicKey:r}=await Promise.resolve().then(()=>pure);this.userPublicKey=r(new Uint8Array(t.match(/.{1,2}/g).map(s=>parseInt(s,16)))),console.log("Using anonymous key for user:",this.userPublicKey)}if(this.commentAs==="anon"&&!this.anonPrivateKeyHex){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,console.log("Ensured anonymous key is available")}if(this.userPublicKey){try{console.log("Fetching profile for user:",this.userPublicKey);const t=await this.nostrService.getProfile({pubkey:this.userPublicKey});console.log("Profile fetched for current user:",t),t?(this.currentUserProfile=t,console.log("Set currentUserProfile to:",this.currentUserProfile)):(this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"./assets/default_dp.png"},console.log("Set fallback currentUserProfile to:",this.currentUserProfile))}catch(t){console.error("Error fetching current user profile:",t),this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"./assets/default_dp.png"},console.log("Set error fallback currentUserProfile to:",this.currentUserProfile)}this.render()}});g(this,"submitComment",async t=>{if(t.trim()){this.userPublicKey||await this.initializeUser(),this.isSubmitting=!0,this.render();try{const r=[];if(r.push(["I",this.baseUrl]),this.replyingToComment){const{rootId:h}=this.findRootAndParent(this.replyingToComment);r.push(["e",h||this.replyingToComment,"","root"]),r.push(["e",this.replyingToComment,"","reply"]),r.push(["k","1111"])}const s={kind:1111,pubkey:this.userPublicKey,content:t.trim(),created_at:Math.floor(Date.now()/1e3),tags:r};let o;if(console.log(`[nostr-comment] Signing attempt - commentAs: ${this.commentAs}, hasNip07: ${!!window.nostr}, anonKey: ${!!this.anonPrivateKeyHex}, userKey: ${!!this.userPrivateKey}`),this.commentAs==="user"&&this.hasNip07&&window.nostr){console.log("[nostr-comment] Using NIP-07 extension to sign");try{o=await window.nostr.signEvent(s),console.log("[nostr-comment] Successfully signed with NIP-07 extension")}catch(h){throw console.error("[nostr-comment] Failed to sign with NIP-07 extension:",h),new Error("Failed to sign with NIP-07 extension. Please check if your extension is unlocked.")}}else if(this.commentAs==="anon"&&this.anonPrivateKeyHex){console.log("[nostr-comment] Using anonymous private key to sign");const{finalizeEvent:h}=await Promise.resolve().then(()=>pure),f=new Uint8Array(this.anonPrivateKeyHex.match(/.{1,2}/g).map(p=>parseInt(p,16)));o=h(s,f)}else if(this.userPrivateKey){console.log("[nostr-comment] Using local private key to sign (fallback)");const{finalizeEvent:h}=await Promise.resolve().then(()=>pure),f=new Uint8Array(this.userPrivateKey.match(/.{1,2}/g).map(p=>parseInt(p,16)));o=h(s,f)}else throw console.error("[nostr-comment] No signing method available - commentAs:",this.commentAs,"hasNip07:",this.hasNip07,"anonKey:",!!this.anonPrivateKeyHex,"userKey:",!!this.userPrivateKey),new Error("No signing method available. Please check your NIP-07 extension or switch to anonymous mode.");await new NDKEvent(this.nostrService.getNDK(),o).publish();const u={id:o.id,pubkey:o.pubkey,content:o.content,created_at:o.created_at,replies:[],replyTo:this.replyingToComment||void 0,depth:0};if(this.currentUserProfile)u.userProfile=this.currentUserProfile;else{try{const h=await this.nostrService.getProfile({pubkey:o.pubkey});h&&(u.userProfile=h,this.currentUserProfile=h)}catch{console.warn("Could not fetch profile for new comment")}u.userProfile||(u.userProfile={name:this.commentAs==="anon"?"Anonymous":`User ${o.pubkey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${o.pubkey.slice(0,8)}`,image:"./assets/default_dp.png"})}this.replyingToComment?this.addReplyToComment(u,this.replyingToComment):this.comments.unshift(u);const c=r.find(h=>h[0]==="e"&&h[3]==="root"),l=r.find(h=>h[0]==="e"&&h[3]==="reply");if(console.log(`[nostr-comment] send: "${s.content}" root=${c?c[1]:"(none)"} parent=${l?l[1]:"(none)"} `),this.replyingToComment){const h=this.shadow.querySelector(".inline-reply-form"),f=h==null?void 0:h.querySelector('[data-role="comment-input"]');f&&(f.value="")}else{const h=this.shadow.querySelector(".modern-comment-form"),f=h==null?void 0:h.querySelector('[data-role="comment-input"]');f&&(f.value="")}this.replyingToComment=null}catch(r){console.error("Failed to submit comment:",r);let s="Failed to submit comment: "+(r instanceof Error?r.message:"Unknown error");r instanceof Error&&r.message.includes("NIP-07")&&(r.message.includes("extension is unlocked")?s="Please unlock your Nostr extension (nos2x/Alby) and try again.":r.message.includes("getPublicKey")?s="Please authorize this website in your Nostr extension.":s="Nostr extension error. Please check if your extension is working properly."),this.showError(s)}finally{this.isSubmitting=!1,this.render()}}});g(this,"addReplyToComment",(t,r)=>{const s=o=>{for(const a of o){if(a.id===r)return t.depth=(a.depth||0)+1,a.replies.push(t),a.replies.sort((u,c)=>u.created_at-c.created_at),!0;if(a.replies.length>0&&s(a.replies))return!0}return!1};s(this.comments)});g(this,"startReply",t=>{this.replyingToComment=null,this.render(),setTimeout(()=>{this.replyingToComment=t,this.render(),setTimeout(()=>{const r=this.shadow.querySelector(".inline-reply-form"),s=r==null?void 0:r.querySelector('[data-role="comment-input"]');s&&s.focus()},100)},10)});g(this,"cancelReply",()=>{this.replyingToComment=null,this.render()});this.shadow=this.attachShadow({mode:"open"})}findRootAndParent(t){let r,s;const o=(a,u,c)=>{var l;for(const h of a){const f=u??h.id;if(h.id===t)return r=f,s=c,!0;if((l=h.replies)!=null&&l.length&&o(h.replies,f,h.id))return!0}return!1};return o(this.comments),{rootId:r,parentId:s}}async connectedCallback(){if(!this.rendered)try{this.getTheme(),this.baseUrl=this.getBaseUrl(),await this.initializeUser(),await this.loadComments(),this.setupNip07StateMonitoring(),this.rendered=!0}catch(t){console.error("Error in connectedCallback:",t),this.isError=!0,this.errorMessage="Failed to initialize comment component",this.render()}}static get observedAttributes(){return["relays","theme","url","readonly","placeholder"]}async attributeChangedCallback(t,r,s){t==="relays"&&(this.nostrService.connectToNostr(this.getRelays()),await this.loadComments()),t==="theme"&&(this.getTheme(),this.render()),t==="url"&&(this.baseUrl=this.getBaseUrl(),await this.loadComments()),["readonly","placeholder"].includes(t)&&this.render()}disconnectedCallback(){this.removeEventListeners(),this.nip07MonitoringInterval&&(clearInterval(this.nip07MonitoringInterval),this.nip07MonitoringInterval=null)}attachEventListeners(){this.removeEventListeners(),this.shadow.querySelectorAll('[data-role="submit-comment"]').forEach(t=>{const r=s=>{s.preventDefault();const o=s.target.closest(".modern-comment-form, .inline-reply-form"),a=o==null?void 0:o.querySelector('[data-role="comment-input"]');a&&this.submitComment(a.value)};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}),this.shadow.querySelectorAll('[data-role="comment-input"]').forEach(t=>{const r=s=>{const o=s;o.key==="Enter"&&(o.ctrlKey||o.metaKey)&&(o.preventDefault(),this.submitComment(t.value))};t.addEventListener("keydown",r),this.eventListeners.push({element:t,type:"keydown",handler:r})}),this.shadow.querySelectorAll('[data-role="cancel-reply"]').forEach(t=>{const r=s=>{s.preventDefault(),this.cancelReply()};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}),this.shadow.querySelectorAll(".reply-btn").forEach(t=>{const r=s=>{s.preventDefault();const o=s.currentTarget.getAttribute("data-comment-id");o&&this.startReply(o)};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}),this.shadow.querySelectorAll('[data-role="toggle-as-user"]').forEach(t=>{if(!this.hasNip07)t.disabled=!0,t.title="NIP-07 extension not detected";else{const r=async s=>{s.preventDefault(),this.commentAs!=="user"&&(this.commentAs="user",this.userPrivateKey=null,this.anonPrivateKeyHex=null,await this.initializeUser())};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}}),this.shadow.querySelectorAll('[data-role="toggle-as-anon"]').forEach(t=>{t.disabled=!1;const r=async s=>{s.preventDefault(),this.commentAs!=="anon"&&(this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null,await this.initializeUser())};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})})}attachAvatarErrorHandlers(){this.shadow.querySelectorAll("img[src]").forEach(t=>{const r=s=>{const o=s.target;if(o.src===this.getDefaultAvatarUrl()){console.warn("Avatar fallback also failed, preventing infinite loop");return}o.src=this.getDefaultAvatarUrl()};t.addEventListener("error",r),this.eventListeners.push({element:t,type:"error",handler:r})})}removeEventListeners(){this.eventListeners.forEach(({element:t,type:r,handler:s})=>{t.removeEventListener(r,s)}),this.eventListeners=[]}showError(t){const r=document.createElement("div");r.className="nostr-comment-error",r.style.cssText=`
2915
+ `}/*! @license DOMPurify 3.2.6 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.6/LICENSE */const{entries,setPrototypeOf,isFrozen,getPrototypeOf,getOwnPropertyDescriptor}=Object;let{freeze,seal,create}=Object,{apply,construct}=typeof Reflect<"u"&&Reflect;freeze||(freeze=function(e){return e}),seal||(seal=function(e){return e}),apply||(apply=function(e,t,r){return e.apply(t,r)}),construct||(construct=function(e,t){return new e(...t)});const arrayForEach=unapply(Array.prototype.forEach),arrayLastIndexOf=unapply(Array.prototype.lastIndexOf),arrayPop=unapply(Array.prototype.pop),arrayPush=unapply(Array.prototype.push),arraySplice=unapply(Array.prototype.splice),stringToLowerCase=unapply(String.prototype.toLowerCase),stringToString=unapply(String.prototype.toString),stringMatch=unapply(String.prototype.match),stringReplace=unapply(String.prototype.replace),stringIndexOf=unapply(String.prototype.indexOf),stringTrim=unapply(String.prototype.trim),objectHasOwnProperty=unapply(Object.prototype.hasOwnProperty),regExpTest=unapply(RegExp.prototype.test),typeErrorCreate=unconstruct(TypeError);function unapply(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,r=new Array(t>1?t-1:0),s=1;s<t;s++)r[s-1]=arguments[s];return apply(n,e,r)}}function unconstruct(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return construct(n,t)}}function addToSet(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:stringToLowerCase;setPrototypeOf&&setPrototypeOf(n,null);let r=e.length;for(;r--;){let s=e[r];if(typeof s=="string"){const o=t(s);o!==s&&(isFrozen(e)||(e[r]=o),s=o)}n[s]=!0}return n}function cleanArray(n){for(let e=0;e<n.length;e++)objectHasOwnProperty(n,e)||(n[e]=null);return n}function clone(n){const e=create(null);for(const[t,r]of entries(n))objectHasOwnProperty(n,t)&&(Array.isArray(r)?e[t]=cleanArray(r):r&&typeof r=="object"&&r.constructor===Object?e[t]=clone(r):e[t]=r);return e}function lookupGetter(n,e){for(;n!==null;){const r=getOwnPropertyDescriptor(n,e);if(r){if(r.get)return unapply(r.get);if(typeof r.value=="function")return unapply(r.value)}n=getPrototypeOf(n)}function t(){return null}return t}const html$1=freeze(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),svg$1=freeze(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),svgFilters=freeze(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),svgDisallowed=freeze(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),mathMl$1=freeze(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),mathMlDisallowed=freeze(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),text=freeze(["#text"]),html=freeze(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),svg=freeze(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),mathMl=freeze(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),xml=freeze(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),MUSTACHE_EXPR=seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm),ERB_EXPR=seal(/<%[\w\W]*|[\w\W]*%>/gm),TMPLIT_EXPR=seal(/\$\{[\w\W]*/gm),DATA_ATTR=seal(/^data-[\-\w.\u00B7-\uFFFF]+$/),ARIA_ATTR=seal(/^aria-[\-\w]+$/),IS_ALLOWED_URI=seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),IS_SCRIPT_OR_DATA=seal(/^(?:\w+script|data):/i),ATTR_WHITESPACE=seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),DOCTYPE_NAME=seal(/^html$/i),CUSTOM_ELEMENT=seal(/^[a-z][.\w]*(-[.\w]+)+$/i);var EXPRESSIONS=Object.freeze({__proto__:null,ARIA_ATTR,ATTR_WHITESPACE,CUSTOM_ELEMENT,DATA_ATTR,DOCTYPE_NAME,ERB_EXPR,IS_ALLOWED_URI,IS_SCRIPT_OR_DATA,MUSTACHE_EXPR,TMPLIT_EXPR});const NODE_TYPE={element:1,text:3,progressingInstruction:7,comment:8,document:9},getGlobal=function n(){return typeof window>"u"?null:window},_createTrustedTypesPolicy=function n(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null;const s="data-tt-policy-suffix";t&&t.hasAttribute(s)&&(r=t.getAttribute(s));const o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(a){return a},createScriptURL(a){return a}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},_createHooksMap=function n(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function createDOMPurify(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:getGlobal();const e=j=>createDOMPurify(j);if(e.version="3.2.6",e.removed=[],!n||!n.document||n.document.nodeType!==NODE_TYPE.document||!n.Element)return e.isSupported=!1,e;let{document:t}=n;const r=t,s=r.currentScript,{DocumentFragment:o,HTMLTemplateElement:a,Node:u,Element:c,NodeFilter:l,NamedNodeMap:h=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:f,DOMParser:p,trustedTypes:b}=n,v=c.prototype,m=lookupGetter(v,"cloneNode"),y=lookupGetter(v,"remove"),w=lookupGetter(v,"nextSibling"),x=lookupGetter(v,"childNodes"),k=lookupGetter(v,"parentNode");if(typeof a=="function"){const j=t.createElement("template");j.content&&j.content.ownerDocument&&(t=j.content.ownerDocument)}let C,P="";const{implementation:R,createNodeIterator:N,createDocumentFragment:B,getElementsByTagName:O}=t,{importNode:H}=r;let S=_createHooksMap();e.isSupported=typeof entries=="function"&&typeof k=="function"&&R&&R.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:_,ERB_EXPR:L,TMPLIT_EXPR:I,DATA_ATTR:A,ARIA_ATTR:E,IS_SCRIPT_OR_DATA:$,ATTR_WHITESPACE:M,CUSTOM_ELEMENT:U}=EXPRESSIONS;let{IS_ALLOWED_URI:z}=EXPRESSIONS,D=null;const V=addToSet({},[...html$1,...svg$1,...svgFilters,...mathMl$1,...text]);let W=null;const Z=addToSet({},[...html,...svg,...mathMl,...xml]);let G=Object.seal(create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),K=null,ne=null,ae=!0,se=!0,pe=!1,ye=!0,J=!1,Q=!0,te=!1,be=!1,Be=!1,Me=!1,We=!1,Ge=!1,at=!0,ct=!1;const Rt="user-content-";let Je=!0,ze=!1,De={},Ue=null;const lt=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let dt=null;const ht=addToSet({},["audio","video","img","source","image","track"]);let Xe=null;const ft=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ze="http://www.w3.org/1998/Math/MathML",Ke="http://www.w3.org/2000/svg",xe="http://www.w3.org/1999/xhtml";let Oe=xe,et=!1,tt=null;const Lt=addToSet({},[Ze,Ke,xe],stringToString);let Ye=addToSet({},["mi","mo","mn","ms","mtext"]),Qe=addToSet({},["annotation-xml"]);const $t=addToSet({},["title","style","font","a","script"]);let qe=null;const It=["application/xhtml+xml","text/html"],Pt="text/html";let ie=null,Fe=null;const Bt=t.createElement("form"),pt=function(T){return T instanceof RegExp||T instanceof Function},nt=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Fe&&Fe===T)){if((!T||typeof T!="object")&&(T={}),T=clone(T),qe=It.indexOf(T.PARSER_MEDIA_TYPE)===-1?Pt:T.PARSER_MEDIA_TYPE,ie=qe==="application/xhtml+xml"?stringToString:stringToLowerCase,D=objectHasOwnProperty(T,"ALLOWED_TAGS")?addToSet({},T.ALLOWED_TAGS,ie):V,W=objectHasOwnProperty(T,"ALLOWED_ATTR")?addToSet({},T.ALLOWED_ATTR,ie):Z,tt=objectHasOwnProperty(T,"ALLOWED_NAMESPACES")?addToSet({},T.ALLOWED_NAMESPACES,stringToString):Lt,Xe=objectHasOwnProperty(T,"ADD_URI_SAFE_ATTR")?addToSet(clone(ft),T.ADD_URI_SAFE_ATTR,ie):ft,dt=objectHasOwnProperty(T,"ADD_DATA_URI_TAGS")?addToSet(clone(ht),T.ADD_DATA_URI_TAGS,ie):ht,Ue=objectHasOwnProperty(T,"FORBID_CONTENTS")?addToSet({},T.FORBID_CONTENTS,ie):lt,K=objectHasOwnProperty(T,"FORBID_TAGS")?addToSet({},T.FORBID_TAGS,ie):clone({}),ne=objectHasOwnProperty(T,"FORBID_ATTR")?addToSet({},T.FORBID_ATTR,ie):clone({}),De=objectHasOwnProperty(T,"USE_PROFILES")?T.USE_PROFILES:!1,ae=T.ALLOW_ARIA_ATTR!==!1,se=T.ALLOW_DATA_ATTR!==!1,pe=T.ALLOW_UNKNOWN_PROTOCOLS||!1,ye=T.ALLOW_SELF_CLOSE_IN_ATTR!==!1,J=T.SAFE_FOR_TEMPLATES||!1,Q=T.SAFE_FOR_XML!==!1,te=T.WHOLE_DOCUMENT||!1,Me=T.RETURN_DOM||!1,We=T.RETURN_DOM_FRAGMENT||!1,Ge=T.RETURN_TRUSTED_TYPE||!1,Be=T.FORCE_BODY||!1,at=T.SANITIZE_DOM!==!1,ct=T.SANITIZE_NAMED_PROPS||!1,Je=T.KEEP_CONTENT!==!1,ze=T.IN_PLACE||!1,z=T.ALLOWED_URI_REGEXP||IS_ALLOWED_URI,Oe=T.NAMESPACE||xe,Ye=T.MATHML_TEXT_INTEGRATION_POINTS||Ye,Qe=T.HTML_INTEGRATION_POINTS||Qe,G=T.CUSTOM_ELEMENT_HANDLING||{},T.CUSTOM_ELEMENT_HANDLING&&pt(T.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(G.tagNameCheck=T.CUSTOM_ELEMENT_HANDLING.tagNameCheck),T.CUSTOM_ELEMENT_HANDLING&&pt(T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(G.attributeNameCheck=T.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),T.CUSTOM_ELEMENT_HANDLING&&typeof T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(G.allowCustomizedBuiltInElements=T.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),J&&(se=!1),We&&(Me=!0),De&&(D=addToSet({},text),W=[],De.html===!0&&(addToSet(D,html$1),addToSet(W,html)),De.svg===!0&&(addToSet(D,svg$1),addToSet(W,svg),addToSet(W,xml)),De.svgFilters===!0&&(addToSet(D,svgFilters),addToSet(W,svg),addToSet(W,xml)),De.mathMl===!0&&(addToSet(D,mathMl$1),addToSet(W,mathMl),addToSet(W,xml))),T.ADD_TAGS&&(D===V&&(D=clone(D)),addToSet(D,T.ADD_TAGS,ie)),T.ADD_ATTR&&(W===Z&&(W=clone(W)),addToSet(W,T.ADD_ATTR,ie)),T.ADD_URI_SAFE_ATTR&&addToSet(Xe,T.ADD_URI_SAFE_ATTR,ie),T.FORBID_CONTENTS&&(Ue===lt&&(Ue=clone(Ue)),addToSet(Ue,T.FORBID_CONTENTS,ie)),Je&&(D["#text"]=!0),te&&addToSet(D,["html","head","body"]),D.table&&(addToSet(D,["tbody"]),delete K.tbody),T.TRUSTED_TYPES_POLICY){if(typeof T.TRUSTED_TYPES_POLICY.createHTML!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof T.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');C=T.TRUSTED_TYPES_POLICY,P=C.createHTML("")}else C===void 0&&(C=_createTrustedTypesPolicy(b,s)),C!==null&&typeof P=="string"&&(P=C.createHTML(""));freeze&&freeze(T),Fe=T}},gt=addToSet({},[...svg$1,...svgFilters,...svgDisallowed]),bt=addToSet({},[...mathMl$1,...mathMlDisallowed]),Mt=function(T){let F=k(T);(!F||!F.tagName)&&(F={namespaceURI:Oe,tagName:"template"});const q=stringToLowerCase(T.tagName),Y=stringToLowerCase(F.tagName);return tt[T.namespaceURI]?T.namespaceURI===Ke?F.namespaceURI===xe?q==="svg":F.namespaceURI===Ze?q==="svg"&&(Y==="annotation-xml"||Ye[Y]):!!gt[q]:T.namespaceURI===Ze?F.namespaceURI===xe?q==="math":F.namespaceURI===Ke?q==="math"&&Qe[Y]:!!bt[q]:T.namespaceURI===xe?F.namespaceURI===Ke&&!Qe[Y]||F.namespaceURI===Ze&&!Ye[Y]?!1:!bt[q]&&($t[q]||!gt[q]):!!(qe==="application/xhtml+xml"&&tt[T.namespaceURI]):!1},ve=function(T){arrayPush(e.removed,{element:T});try{k(T).removeChild(T)}catch{y(T)}},He=function(T,F){try{arrayPush(e.removed,{attribute:F.getAttributeNode(T),from:F})}catch{arrayPush(e.removed,{attribute:null,from:F})}if(F.removeAttribute(T),T==="is")if(Me||We)try{ve(F)}catch{}else try{F.setAttribute(T,"")}catch{}},mt=function(T){let F=null,q=null;if(Be)T="<remove></remove>"+T;else{const re=stringMatch(T,/^[\r\n\t ]+/);q=re&&re[0]}qe==="application/xhtml+xml"&&Oe===xe&&(T='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+T+"</body></html>");const Y=C?C.createHTML(T):T;if(Oe===xe)try{F=new p().parseFromString(Y,qe)}catch{}if(!F||!F.documentElement){F=R.createDocument(Oe,"template",null);try{F.documentElement.innerHTML=et?P:Y}catch{}}const ue=F.body||F.documentElement;return T&&q&&ue.insertBefore(t.createTextNode(q),ue.childNodes[0]||null),Oe===xe?O.call(F,te?"html":"body")[0]:te?F.documentElement:ue},yt=function(T){return N.call(T.ownerDocument||T,T,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},rt=function(T){return T instanceof f&&(typeof T.nodeName!="string"||typeof T.textContent!="string"||typeof T.removeChild!="function"||!(T.attributes instanceof h)||typeof T.removeAttribute!="function"||typeof T.setAttribute!="function"||typeof T.namespaceURI!="string"||typeof T.insertBefore!="function"||typeof T.hasChildNodes!="function")},vt=function(T){return typeof u=="function"&&T instanceof u};function Ee(j,T,F){arrayForEach(j,q=>{q.call(e,T,F,Fe)})}const wt=function(T){let F=null;if(Ee(S.beforeSanitizeElements,T,null),rt(T))return ve(T),!0;const q=ie(T.nodeName);if(Ee(S.uponSanitizeElement,T,{tagName:q,allowedTags:D}),Q&&T.hasChildNodes()&&!vt(T.firstElementChild)&&regExpTest(/<[/\w!]/g,T.innerHTML)&&regExpTest(/<[/\w!]/g,T.textContent)||T.nodeType===NODE_TYPE.progressingInstruction||Q&&T.nodeType===NODE_TYPE.comment&&regExpTest(/<[/\w]/g,T.data))return ve(T),!0;if(!D[q]||K[q]){if(!K[q]&&Et(q)&&(G.tagNameCheck instanceof RegExp&&regExpTest(G.tagNameCheck,q)||G.tagNameCheck instanceof Function&&G.tagNameCheck(q)))return!1;if(Je&&!Ue[q]){const Y=k(T)||T.parentNode,ue=x(T)||T.childNodes;if(ue&&Y){const re=ue.length;for(let de=re-1;de>=0;--de){const ke=m(ue[de],!0);ke.__removalCount=(T.__removalCount||0)+1,Y.insertBefore(ke,w(T))}}}return ve(T),!0}return T instanceof c&&!Mt(T)||(q==="noscript"||q==="noembed"||q==="noframes")&&regExpTest(/<\/no(script|embed|frames)/i,T.innerHTML)?(ve(T),!0):(J&&T.nodeType===NODE_TYPE.text&&(F=T.textContent,arrayForEach([_,L,I],Y=>{F=stringReplace(F,Y," ")}),T.textContent!==F&&(arrayPush(e.removed,{element:T.cloneNode()}),T.textContent=F)),Ee(S.afterSanitizeElements,T,null),!1)},xt=function(T,F,q){if(at&&(F==="id"||F==="name")&&(q in t||q in Bt))return!1;if(!(se&&!ne[F]&&regExpTest(A,F))){if(!(ae&&regExpTest(E,F))){if(!W[F]||ne[F]){if(!(Et(T)&&(G.tagNameCheck instanceof RegExp&&regExpTest(G.tagNameCheck,T)||G.tagNameCheck instanceof Function&&G.tagNameCheck(T))&&(G.attributeNameCheck instanceof RegExp&&regExpTest(G.attributeNameCheck,F)||G.attributeNameCheck instanceof Function&&G.attributeNameCheck(F))||F==="is"&&G.allowCustomizedBuiltInElements&&(G.tagNameCheck instanceof RegExp&&regExpTest(G.tagNameCheck,q)||G.tagNameCheck instanceof Function&&G.tagNameCheck(q))))return!1}else if(!Xe[F]){if(!regExpTest(z,stringReplace(q,M,""))){if(!((F==="src"||F==="xlink:href"||F==="href")&&T!=="script"&&stringIndexOf(q,"data:")===0&&dt[T])){if(!(pe&&!regExpTest($,stringReplace(q,M,"")))){if(q)return!1}}}}}}return!0},Et=function(T){return T!=="annotation-xml"&&stringMatch(T,U)},kt=function(T){Ee(S.beforeSanitizeAttributes,T,null);const{attributes:F}=T;if(!F||rt(T))return;const q={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:W,forceKeepAttr:void 0};let Y=F.length;for(;Y--;){const ue=F[Y],{name:re,namespaceURI:de,value:ke}=ue,Ve=ie(re),st=ke;let ce=re==="value"?st:stringTrim(st);if(q.attrName=Ve,q.attrValue=ce,q.keepAttr=!0,q.forceKeepAttr=void 0,Ee(S.uponSanitizeAttribute,T,q),ce=q.attrValue,ct&&(Ve==="id"||Ve==="name")&&(He(re,T),ce=Rt+ce),Q&&regExpTest(/((--!?|])>)|<\/(style|title)/i,ce)){He(re,T);continue}if(q.forceKeepAttr)continue;if(!q.keepAttr){He(re,T);continue}if(!ye&&regExpTest(/\/>/i,ce)){He(re,T);continue}J&&arrayForEach([_,L,I],St=>{ce=stringReplace(ce,St," ")});const At=ie(T.nodeName);if(!xt(At,Ve,ce)){He(re,T);continue}if(C&&typeof b=="object"&&typeof b.getAttributeType=="function"&&!de)switch(b.getAttributeType(At,Ve)){case"TrustedHTML":{ce=C.createHTML(ce);break}case"TrustedScriptURL":{ce=C.createScriptURL(ce);break}}if(ce!==st)try{de?T.setAttributeNS(de,re,ce):T.setAttribute(re,ce),rt(T)?ve(T):arrayPop(e.removed)}catch{He(re,T)}}Ee(S.afterSanitizeAttributes,T,null)},Dt=function j(T){let F=null;const q=yt(T);for(Ee(S.beforeSanitizeShadowDOM,T,null);F=q.nextNode();)Ee(S.uponSanitizeShadowNode,F,null),wt(F),kt(F),F.content instanceof o&&j(F.content);Ee(S.afterSanitizeShadowDOM,T,null)};return e.sanitize=function(j){let T=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},F=null,q=null,Y=null,ue=null;if(et=!j,et&&(j="<!-->"),typeof j!="string"&&!vt(j))if(typeof j.toString=="function"){if(j=j.toString(),typeof j!="string")throw typeErrorCreate("dirty is not a string, aborting")}else throw typeErrorCreate("toString is not a function");if(!e.isSupported)return j;if(be||nt(T),e.removed=[],typeof j=="string"&&(ze=!1),ze){if(j.nodeName){const ke=ie(j.nodeName);if(!D[ke]||K[ke])throw typeErrorCreate("root node is forbidden and cannot be sanitized in-place")}}else if(j instanceof u)F=mt("<!---->"),q=F.ownerDocument.importNode(j,!0),q.nodeType===NODE_TYPE.element&&q.nodeName==="BODY"||q.nodeName==="HTML"?F=q:F.appendChild(q);else{if(!Me&&!J&&!te&&j.indexOf("<")===-1)return C&&Ge?C.createHTML(j):j;if(F=mt(j),!F)return Me?null:Ge?P:""}F&&Be&&ve(F.firstChild);const re=yt(ze?j:F);for(;Y=re.nextNode();)wt(Y),kt(Y),Y.content instanceof o&&Dt(Y.content);if(ze)return j;if(Me){if(We)for(ue=B.call(F.ownerDocument);F.firstChild;)ue.appendChild(F.firstChild);else ue=F;return(W.shadowroot||W.shadowrootmode)&&(ue=H.call(r,ue,!0)),ue}let de=te?F.outerHTML:F.innerHTML;return te&&D["!doctype"]&&F.ownerDocument&&F.ownerDocument.doctype&&F.ownerDocument.doctype.name&&regExpTest(DOCTYPE_NAME,F.ownerDocument.doctype.name)&&(de="<!DOCTYPE "+F.ownerDocument.doctype.name+`>
2916
+ `+de),J&&arrayForEach([_,L,I],ke=>{de=stringReplace(de,ke," ")}),C&&Ge?C.createHTML(de):de},e.setConfig=function(){let j=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};nt(j),be=!0},e.clearConfig=function(){Fe=null,be=!1},e.isValidAttribute=function(j,T,F){Fe||nt({});const q=ie(j),Y=ie(T);return xt(q,Y,F)},e.addHook=function(j,T){typeof T=="function"&&arrayPush(S[j],T)},e.removeHook=function(j,T){if(T!==void 0){const F=arrayLastIndexOf(S[j],T);return F===-1?void 0:arraySplice(S[j],F,1)[0]}return arrayPop(S[j])},e.removeHooks=function(j){S[j]=[]},e.removeAllHooks=function(){S=_createHooksMap()},e}var purify=createDOMPurify();class NostrComment extends HTMLElement{constructor(){super();g(this,"rendered",!1);g(this,"nostrService",NostrService.getInstance());g(this,"shadow");g(this,"theme","light");g(this,"isLoading",!0);g(this,"isError",!1);g(this,"errorMessage","");g(this,"comments",[]);g(this,"baseUrl","");g(this,"userPublicKey",null);g(this,"userPrivateKey",null);g(this,"currentUserProfile",null);g(this,"isSubmitting",!1);g(this,"replyingToComment",null);g(this,"commentAs","user");g(this,"hasNip07",!1);g(this,"anonPrivateKeyHex",null);g(this,"eventListeners",[]);g(this,"nip07MonitoringInterval",null);g(this,"loadVersion",0);g(this,"getRelays",()=>{const t=this.getAttribute("relays");return t?t.split(",").map(r=>r.trim()):DEFAULT_RELAYS});g(this,"getTheme",()=>{this.theme="light";const t=this.getAttribute("theme");t&&(["light","dark"].includes(t)?this.theme=t:console.warn(`Invalid theme '${t}'. Accepted values are 'light', 'dark'`))});g(this,"getBaseUrl",()=>{const t=this.getAttribute("url");return normalizeURL$1(t||window.location.href)});g(this,"detectNip07Extension",()=>{const t=window.nostr;return t?typeof t.getPublicKey=="function"&&typeof t.signEvent=="function"?!0:(console.warn("NIP-07 extension detected but missing required methods"),!1):!1});g(this,"handleNip07StateChange",async()=>{const t=this.hasNip07,r=this.detectNip07Extension();if(t!==r&&(console.log("NIP-07 extension state changed:",r),this.hasNip07=r,r&&this.commentAs==="user"))try{await this.initializeUser(),this.render()}catch(s){console.warn("Failed to reconnect to NIP-07 extension:",s)}});g(this,"setupNip07StateMonitoring",()=>{const t=setInterval(async()=>{document.contains(this)&&await this.handleNip07StateChange()},2e3);this.nip07MonitoringInterval=t});g(this,"loadComments",async()=>{this.loadVersion++;const t=this.loadVersion;try{this.isLoading=!0,this.isError=!1,this.render();const r=this.getRelays();await this.nostrService.connectToNostr(r);const s={kinds:[1111],"#I":[this.baseUrl],limit:200},o=await this.nostrService.getNDK().fetchEvents(s),a=Array.from(o),u=new Map;a.forEach(v=>u.set(v.id,{content:v.content,id:v.id,tags:v.tags}));const c=[],l=new Set;for(const v of a){let m;const y=(v.tags||[]).filter(x=>x[0]==="e");for(let x=y.length-1;x>=0;x--){const k=y[x];if(k[3]==="reply"){m=k[1];break}}if(!m&&y.length>0){const x=y.filter(k=>k[3]!=="root");x.length>0?m=x[x.length-1][1]:m=y[y.length-1][1]}const w={id:v.id,pubkey:v.pubkey,content:v.content,created_at:v.created_at,replies:[],replyTo:m,depth:0};l.add(v.pubkey),c.push(w)}const h=Array.from(l).map(async v=>{try{console.log("Fetching profile for pubkey:",v);const m=await this.nostrService.getProfile({pubkey:v});return console.log("Profile fetched for",v,":",m),{pubkey:v,profile:m}}catch(m){return console.warn("Failed to fetch profile for:",v,m),{pubkey:v,profile:null}}}),f=await Promise.allSettled(h),p=new Map;if(f.forEach(v=>{if(v.status==="fulfilled"){const{pubkey:m,profile:y}=v.value;p.set(m,y)}}),c.forEach(v=>{v.userProfile=p.get(v.pubkey)||void 0,console.log("Attached profile to comment:",v.pubkey,"Profile:",v.userProfile)}),t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting");return}this.comments=this.buildCommentTree(c);const b=new Map;this.comments.forEach(v=>{const m=[v];for(;m.length;){const y=m.pop();b.set(y.id,y),y.replies.forEach(w=>m.push(w))}}),c.forEach(v=>{const m=v.replyTo?b.get(v.replyTo):void 0,y=m?m.content:"(no parent)";console.log(`[nostr-comment] recv: "${v.content}" -> parent: ${y}`)})}catch(r){if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting error handling");return}this.isError=!0,this.errorMessage=r instanceof Error?r.message:"Failed to load comments",console.error("Error loading comments:",r)}finally{if(t!==this.loadVersion){console.log("Load operation superseded by newer request, aborting final state update");return}this.isLoading=!1,this.render()}});g(this,"buildCommentTree",t=>{const r=new Map,s=[];t.forEach(a=>{r.set(a.id,a)}),t.forEach(a=>{if(a.replyTo&&r.has(a.replyTo)){const u=r.get(a.replyTo);u.replies.push(a),u.replies.sort((c,l)=>c.created_at-l.created_at)}else s.push(a)});const o=(a,u)=>{for(const c of a)c.depth=u,c.replies&&c.replies.length&&o(c.replies,u+1)};return o(s,0),s.sort((a,u)=>u.created_at-a.created_at)});g(this,"initializeUser",async()=>{if(this.hasNip07=this.detectNip07Extension(),console.log("NIP-07 extension detected:",this.hasNip07),this.hasNip07&&this.commentAs==="user")try{this.userPublicKey=await window.nostr.getPublicKey(),console.log("Successfully connected to NIP-07 extension, public key:",this.userPublicKey),this.userPrivateKey=null,this.anonPrivateKeyHex=null}catch(t){console.warn("NIP-07 extension available but failed to get public key:",t),this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null}if(!this.userPublicKey){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,this.userPrivateKey=t;const{getPublicKey:r}=await Promise.resolve().then(()=>pure);this.userPublicKey=r(new Uint8Array(t.match(/.{1,2}/g).map(s=>parseInt(s,16)))),console.log("Using anonymous key for user:",this.userPublicKey)}if(this.commentAs==="anon"&&!this.anonPrivateKeyHex){const t=await this.ensureAnonKey();this.anonPrivateKeyHex=t,console.log("Ensured anonymous key is available")}if(this.userPublicKey){try{console.log("Fetching profile for user:",this.userPublicKey);const t=await this.nostrService.getProfile({pubkey:this.userPublicKey});console.log("Profile fetched for current user:",t),t?(this.currentUserProfile=t,console.log("Set currentUserProfile to:",this.currentUserProfile)):(this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"../../assets/default_dp.png"},console.log("Set fallback currentUserProfile to:",this.currentUserProfile))}catch(t){console.error("Error fetching current user profile:",t),this.currentUserProfile={name:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${this.userPublicKey.slice(0,8)}`,image:"../../assets/default_dp.png"},console.log("Set error fallback currentUserProfile to:",this.currentUserProfile)}this.render()}});g(this,"submitComment",async t=>{if(t.trim()){this.userPublicKey||await this.initializeUser(),this.isSubmitting=!0,this.render();try{const r=[];if(r.push(["I",this.baseUrl]),this.replyingToComment){const{rootId:h}=this.findRootAndParent(this.replyingToComment);r.push(["e",h||this.replyingToComment,"","root"]),r.push(["e",this.replyingToComment,"","reply"]),r.push(["k","1111"])}const s={kind:1111,pubkey:this.userPublicKey,content:t.trim(),created_at:Math.floor(Date.now()/1e3),tags:r};let o;if(console.log(`[nostr-comment] Signing attempt - commentAs: ${this.commentAs}, hasNip07: ${!!window.nostr}, anonKey: ${!!this.anonPrivateKeyHex}, userKey: ${!!this.userPrivateKey}`),this.commentAs==="user"&&this.hasNip07&&window.nostr){console.log("[nostr-comment] Using NIP-07 extension to sign");try{o=await window.nostr.signEvent(s),console.log("[nostr-comment] Successfully signed with NIP-07 extension")}catch(h){throw console.error("[nostr-comment] Failed to sign with NIP-07 extension:",h),new Error("Failed to sign with NIP-07 extension. Please check if your extension is unlocked.")}}else if(this.commentAs==="anon"&&this.anonPrivateKeyHex){console.log("[nostr-comment] Using anonymous private key to sign");const{finalizeEvent:h}=await Promise.resolve().then(()=>pure),f=new Uint8Array(this.anonPrivateKeyHex.match(/.{1,2}/g).map(p=>parseInt(p,16)));o=h(s,f)}else if(this.userPrivateKey){console.log("[nostr-comment] Using local private key to sign (fallback)");const{finalizeEvent:h}=await Promise.resolve().then(()=>pure),f=new Uint8Array(this.userPrivateKey.match(/.{1,2}/g).map(p=>parseInt(p,16)));o=h(s,f)}else throw console.error("[nostr-comment] No signing method available - commentAs:",this.commentAs,"hasNip07:",this.hasNip07,"anonKey:",!!this.anonPrivateKeyHex,"userKey:",!!this.userPrivateKey),new Error("No signing method available. Please check your NIP-07 extension or switch to anonymous mode.");await new NDKEvent(this.nostrService.getNDK(),o).publish();const u={id:o.id,pubkey:o.pubkey,content:o.content,created_at:o.created_at,replies:[],replyTo:this.replyingToComment||void 0,depth:0};if(this.currentUserProfile)u.userProfile=this.currentUserProfile;else{try{const h=await this.nostrService.getProfile({pubkey:o.pubkey});h&&(u.userProfile=h,this.currentUserProfile=h)}catch{console.warn("Could not fetch profile for new comment")}u.userProfile||(u.userProfile={name:this.commentAs==="anon"?"Anonymous":`User ${o.pubkey.slice(0,8)}`,displayName:this.commentAs==="anon"?"Anonymous":`User ${o.pubkey.slice(0,8)}`,image:"../../assets/default_dp.png"})}this.replyingToComment?this.addReplyToComment(u,this.replyingToComment):this.comments.unshift(u);const c=r.find(h=>h[0]==="e"&&h[3]==="root"),l=r.find(h=>h[0]==="e"&&h[3]==="reply");if(console.log(`[nostr-comment] send: "${s.content}" root=${c?c[1]:"(none)"} parent=${l?l[1]:"(none)"} `),this.replyingToComment){const h=this.shadow.querySelector(".inline-reply-form"),f=h==null?void 0:h.querySelector('[data-role="comment-input"]');f&&(f.value="")}else{const h=this.shadow.querySelector(".modern-comment-form"),f=h==null?void 0:h.querySelector('[data-role="comment-input"]');f&&(f.value="")}this.replyingToComment=null}catch(r){console.error("Failed to submit comment:",r);let s="Failed to submit comment: "+(r instanceof Error?r.message:"Unknown error");r instanceof Error&&r.message.includes("NIP-07")&&(r.message.includes("extension is unlocked")?s="Please unlock your Nostr extension (nos2x/Alby) and try again.":r.message.includes("getPublicKey")?s="Please authorize this website in your Nostr extension.":s="Nostr extension error. Please check if your extension is working properly."),this.showError(s)}finally{this.isSubmitting=!1,this.render()}}});g(this,"addReplyToComment",(t,r)=>{const s=o=>{for(const a of o){if(a.id===r)return t.depth=(a.depth||0)+1,a.replies.push(t),a.replies.sort((u,c)=>u.created_at-c.created_at),!0;if(a.replies.length>0&&s(a.replies))return!0}return!1};s(this.comments)});g(this,"startReply",t=>{this.replyingToComment=null,this.render(),setTimeout(()=>{this.replyingToComment=t,this.render(),setTimeout(()=>{const r=this.shadow.querySelector(".inline-reply-form"),s=r==null?void 0:r.querySelector('[data-role="comment-input"]');s&&s.focus()},100)},10)});g(this,"cancelReply",()=>{this.replyingToComment=null,this.render()});this.shadow=this.attachShadow({mode:"open"})}findRootAndParent(t){let r,s;const o=(a,u,c)=>{var l;for(const h of a){const f=u??h.id;if(h.id===t)return r=f,s=c,!0;if((l=h.replies)!=null&&l.length&&o(h.replies,f,h.id))return!0}return!1};return o(this.comments),{rootId:r,parentId:s}}async connectedCallback(){if(!this.rendered)try{this.getTheme(),this.baseUrl=this.getBaseUrl(),await this.initializeUser(),await this.loadComments(),this.setupNip07StateMonitoring(),this.rendered=!0}catch(t){console.error("Error in connectedCallback:",t),this.isError=!0,this.errorMessage="Failed to initialize comment component",this.render()}}static get observedAttributes(){return["relays","theme","url","readonly","placeholder"]}async attributeChangedCallback(t,r,s){t==="relays"&&(this.nostrService.connectToNostr(this.getRelays()),await this.loadComments()),t==="theme"&&(this.getTheme(),this.render()),t==="url"&&(this.baseUrl=this.getBaseUrl(),await this.loadComments()),["readonly","placeholder"].includes(t)&&this.render()}disconnectedCallback(){this.removeEventListeners(),this.nip07MonitoringInterval&&(clearInterval(this.nip07MonitoringInterval),this.nip07MonitoringInterval=null)}attachEventListeners(){this.removeEventListeners(),this.shadow.querySelectorAll('[data-role="submit-comment"]').forEach(t=>{const r=s=>{s.preventDefault();const o=s.target.closest(".modern-comment-form, .inline-reply-form"),a=o==null?void 0:o.querySelector('[data-role="comment-input"]');a&&this.submitComment(a.value)};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}),this.shadow.querySelectorAll('[data-role="comment-input"]').forEach(t=>{const r=s=>{const o=s;o.key==="Enter"&&(o.ctrlKey||o.metaKey)&&(o.preventDefault(),this.submitComment(t.value))};t.addEventListener("keydown",r),this.eventListeners.push({element:t,type:"keydown",handler:r})}),this.shadow.querySelectorAll('[data-role="cancel-reply"]').forEach(t=>{const r=s=>{s.preventDefault(),this.cancelReply()};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}),this.shadow.querySelectorAll(".reply-btn").forEach(t=>{const r=s=>{s.preventDefault();const o=s.currentTarget.getAttribute("data-comment-id");o&&this.startReply(o)};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}),this.shadow.querySelectorAll('[data-role="toggle-as-user"]').forEach(t=>{if(!this.hasNip07)t.disabled=!0,t.title="NIP-07 extension not detected";else{const r=async s=>{s.preventDefault(),this.commentAs!=="user"&&(this.commentAs="user",this.userPrivateKey=null,this.anonPrivateKeyHex=null,await this.initializeUser())};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})}}),this.shadow.querySelectorAll('[data-role="toggle-as-anon"]').forEach(t=>{t.disabled=!1;const r=async s=>{s.preventDefault(),this.commentAs!=="anon"&&(this.commentAs="anon",this.userPublicKey=null,this.userPrivateKey=null,await this.initializeUser())};t.addEventListener("click",r),this.eventListeners.push({element:t,type:"click",handler:r})})}attachAvatarErrorHandlers(){this.shadow.querySelectorAll("img[src]").forEach(t=>{const r=s=>{const o=s.target;if(o.src===this.getDefaultAvatarUrl()){console.warn("Avatar fallback also failed, preventing infinite loop");return}o.src=this.getDefaultAvatarUrl()};t.addEventListener("error",r),this.eventListeners.push({element:t,type:"error",handler:r})})}removeEventListeners(){this.eventListeners.forEach(({element:t,type:r,handler:s})=>{t.removeEventListener(r,s)}),this.eventListeners=[]}showError(t){const r=document.createElement("div");r.className="nostr-comment-error",r.style.cssText=`
2917
2917
  position: fixed;
2918
2918
  top: 20px;
2919
2919
  right: 20px;
@@ -2927,7 +2927,7 @@ Minimum version required to store current data is: `+o+`.
2927
2927
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
2928
2928
  font-size: 14px;
2929
2929
  line-height: 1.4;
2930
- `,r.textContent=t,document.body.appendChild(r);const s=t.includes("NIP-07")?8e3:5e3;setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},s)}getDefaultAvatarUrl(){try{return new URL("./assets/default_dp.png",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("nostr-components.umd.js",document.baseURI).href).toString()}catch(t){return console.warn("Failed to resolve default avatar URL with import.meta.url, using relative path:",t),"./assets/default_dp.png"}}async ensureAnonKey(){const t="nostr-comment-anon-private-key";try{const o=localStorage.getItem(t);if(o&&o.match(/^[a-f0-9]{64}$/))return o}catch(o){console.warn("Failed to read from localStorage:",o)}const{generateSecretKey:r}=await Promise.resolve().then(()=>pure),s=Array.from(r()).map(o=>o.toString(16).padStart(2,"0")).join("");try{localStorage.setItem(t,s)}catch(o){console.warn("Failed to write to localStorage, using ephemeral key:",o)}return s}render(){this.classList.toggle("dark",this.theme==="dark"),this.classList.toggle("loading",this.isLoading),this.classList.toggle("error-container",this.isError);const t=this.hasAttribute("readonly"),r=this.getAttribute("placeholder")||"Write a comment...",s=renderCommentWidget(this.isLoading,this.isError,this.errorMessage,this.comments,t,r,this.isSubmitting,this.currentUserProfile,this.replyingToComment,this.commentAs,this.hasNip07),o=purify.sanitize(s,{ALLOWED_TAGS:["div","span","button","textarea","img","a","h3","h4","p","ul","li","small","strong","em"],ALLOWED_ATTR:["class","data-role","data-comment-id","data-depth","src","alt","href","target","rel","placeholder","rows","disabled"],ALLOW_DATA_ATTR:!1});this.shadow.innerHTML=`
2930
+ `,r.textContent=t,document.body.appendChild(r);const s=t.includes("NIP-07")?8e3:5e3;setTimeout(()=>{r.parentNode&&r.parentNode.removeChild(r)},s)}getDefaultAvatarUrl(){try{return new URL("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjcAAAJlCAYAAAAmbtNSAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAADqVSURBVHgB7d1bchNZ9u/xlbrQHSf+He0eQatGUOaxow62PAKSEWBGgHnrAkcg4o9d9QaMADMCkhFYmK7oR4sRkDWCcgUVJ7rRZZ+9lRLItmzrkpd9+X4iXDLGUIBl5S/XWntvkcB04n+39uMPbQEAAF6qSUBMsOlL/3gko1gAAICXggk302Cj321FEv1VAACAl4IJNzrYvNYPrexHalMAAICXggg3j+MPT/VD+9tHopYAAAAvReK5x/HJrv5Lvr748aYMv+skO6kAAACveF25MXM2Otg8nfdzQ6m3BQAAeMfrcDOQ/gv5Omdz3pC5GwAAvORtuDHtKCVy5ZLvSKLvBQAAeMfLcHNdO2oGlRsAADzkZbjpS98Em9YNn7bxOD4m4AAA4Bnvwo2p2uiH3UU+N2KoGAAA73gXbia7EC/qrgAAAK94FW7MELHc3I6atdmJjzcEAAB4w6tws8AQ8UUbA2kwdwMAgEe8CTcrVG3GOCEcAAC/eBNudNXmvqwgkmilXwcAAOzkRbjpxL+Y1lJbVrOxH39oCwAA8IIX4aYvw4eyBlpTAAD4w/lTwc1qp4HUPyldgZHVnU1OCT8TAADgNOcrN1+kHq8ZbIyN/7KhHwAAXnA+3Kw6SHyR/odYq7UFAADs4HRbyhy10Jf+J8lJJNHO8+ROVwAAgLOcrtx8kX5bcqREsSwcAADHOR1uavmfDRVzHAMAAG5zfeamLfnaGEhtTwAAgLOcnbkxG/f1ZXgq+WNZOAAADnO2cqODTVuKsdGX+rIHcAIAAEs4G250yWlbirP3ODvSAQAAOMbhmZuoJQWKZPhCAACAc5wNN0pU0ZWV9o/xCcPFAAA4xslw0ympZaT/cZ6ajQIFAAA4w8lwM5BhS8qx0Zf+awEAAM5wMtwokZaUp/0kPmH+BgAARzgZbiJRZe8ivPfk3r84mgEAAAdQuVn4fzp6yfJwAADs5+hqqejvUr6NSIZvGTAGAMBurp8tVbZWX/rHBBwAAOxFuFkeAQcAAIsRblZDwAEAwFKEm9URcAAAsBDhZj0EHAAALEO4WZ8JOKf78Ye2AACAyjkabtSvYpcNJer4cfzhqQAAgEpRuclRJKrzJD55TZsKAIDqXBluHscnu7ZepCORVOy1a+ZwaFMBAFCNK8ONDhBP9UXayjbLSKJU7Naatqk68XHZ52ABABC0ueFmMjvS0m+7Nl6c9R/6TBxg2lR9qZ+aKpgAAIBSXAo3phWlL8q70x8PpLYnlhnIsCfu0P+e8ppZHAAAyhFd/ICp2piKw8yHzpoy/K6T7FhVLdmPT35TIi62fI6a0nzWSf6RCkoxDZUDGbSGojaiyfOmJqo1/Ry12GGsZ/p74/eZX3Omn4Pjt7p+33ysIY1U5M9nneS2E9VFAPDRpXCjKwyfJGtJzTo6SLYeiEX0n/NYP7TFXYScNXXiUx1S/rPxX+lv1rLnrAkoJriYmadWTaKNKgOw/jOk0biFOg4++n31qwlEkUS9kdTObsn/SQlBAJC/c+HGzIaYFsq8T9QX4u9suhDvx+9f6gvFQ3Hfkb7YvXme3OkKLjEB5ov8v5bIcNNUWrIKi9rU/2YtRyt350RZ5adnqj/67/dxqINPJPX0MPnBpdYrAFjlXLjZjz+c6rvNzSs+16rqzXVBzFGpvsA9uyXNbmjVHNM2MtWXun7uTcOLCS4mwEjQlA49UUroAYDlfA035gLTl/6n6z5ZSf22LS+uZhVXX+q/iZ+6+uL+xregY6ow/5XPbd1C2tY/HIdo0z4ixCxuWunR7+rWlrz/kzR7tDYB4Lyv4WbBNk9XV292xBJXzAd5RukLWdTVAeBdQ/6n58qMhgkyA/ljc1IJ/F4/tgkxhUkngeedSL1HdQdA6GbCzbUtqZlfEO3YMh/i0dzNMroyuWu3oU0xOxMTjUOMCZvZTIygEqa6M8qeJ4QdAEEah5tFWlIzrKnemCMOzE7AErxvsxnnV+PUztZpWUxXI5kl1KNx+2g8wDtZkeTPUG8AUv3W1YHn3Z/kL11WaAHw3TjcLDucqy9oDw6TrSOxgMP73ZTKLEs2jzNLky9+xtdl01UvoUbhuvrtXVOaCfM6AHw0Djdm91z9sLvEr0ubMrxtw8Z+gbamgJxkM11K6m9oXwHwxfj4Bd1euHHW5oKWPccy1BIBsKLx9/5eJMNTM6Cv3148jn9Z9vUAAKwSrbOk2paN/WhNAblL9dsrWlcAXFQbSGPlu7S+9C3ZRE+9EgB5aum3F2ahgTnqxMzlZQPmAGC/mhkkldW1f4xPKm9PNWT0UgAUpW0WHPTl829mPs+sUhQAsFi0H7/vKImeyurOdOn6dtWlaw8O0gRcEuxxIQDsZwaK1y01b9jQnookeiYAytLKqjnjttVrs1eWAIAldLgxBxWurf04/rBO9Wdtk12TuwKgbLuzszkCABWr5bXKKBLVqboXT/UGqNR4NscsKSfkAKhSlPOsStqU5k6VPXhmbwBrpEqio1vSeMNcDoAy1SRfrb58eWv2zpGKUL0BrNEyFV3mcgCUzYSbluQq2vwi9coGjJm9Aay0S8gBUBYTblLJme67x5PzqioxlOGD7IBIAJYh5AAoXN5tqVm7Va2g+jnZGe/BIQBsRcgBUJhakRUO0283B/FJBQ6SLbNrcVcA2MyEnOOqt5IA4JeaEvW7FGvvcXxSyZAx7SnACa3JjRBLyAHkolbGxd/M4PSlflp2+Zn2FOCU1nSfnB/jk1gAYEW6chOlUo5WVn7+ZeVTyFdh2lMRp4YDLmnVRN4yjwNgVaZyk0p59J3Z8LTs/npDRh0R1RMALhkPHTOPA2BZ0T/j41Zd6p+kfEdNaT4ra+fS7O9ZO9Z/5ZYAcM24xXyYbB0JANwgMv/Zj09+y+uMqSWV+oJFwAGcV+pNEQA3jfe50QGjqpbNdICwlN66GTAeymhH/41TAeAi06o6/TE+2RMAuMI43ESiPkq1JntdFL8MlIADOG9Dv3C9MKuqGDgGMM9kh+JaItX7ugy06BcsAg7ghRYDxwDmGc/cmA32+lL/TexSeG99MoPz1hz2KQBclurXix1mcQAY0fQdXTE51g9tsU/hIWc/fv9SSfRQADhNfx93DpM7bNwJBG423JgBvUrOgVqEEklqEr16ntzpSgHM31//YzytaNUYgPxQxQEC9zXcVLjfzbJS/fZKv3gleb94sVQc8MaZvlF5xL44QJii2R9Y3Jq6Sle/gL25Jc1unkGHKg7gDd3WHj7qJDscoAsE5Fy42Y/fd3TP2tGVB+Z4hag7Enn/J/mLDju313oxm1RxOvr3vC8AXEabCgjMuXBj6aqpFameORS0JurjUKJeJPX0MPlh6c0KTchpSP21cquiBeACho2BcEQXP+Bga2opUdaLn4acVL+dRaJ+v+7X6BfFv+qHWL+1BIDLaFMBAbgUbvbjD20l6lgAwE+0qQDPRfM+WOFBmgBQBlZTAR6rzf+weiUA4K8Nc9wLRzcAfppbuTGDxQOpf6J6A8B3ZoPQWzJ8wBwO4I+5lZvsm5zqDQD/6Tu8uC/1U04YB/xRu+onGjJ6aVYWCQD4z5wwfvw4/oVDdAEPRNf9pNub+gGuUWl2QxGNH4eifq9NbjBG+mNX/apoPD+iNrL3o79P2sn6TW3q719ay0saiTz6Kdl6KQCcdW24yTb1q51y1hKQDx1CTHjpjUR9jLIQkzak2StqWXI2P9fQIUdt6v/Xtg48LR14qE7cgA3/ALdFN30C+94Aq5kNMjWJukWGmGWYXbdrUm/rP59+k7tUd6708iDZeiQAnHNjuDH245O3KtuhF8A1dGDomfPNalJLGjLoubACJ7uBGe0SdC5jJRXgpoXCDUvDgatF2en075oyPHL5Imi+z79IPa6JekjrapbqNeXWPXY0BtyxULgxdPUm1i/gbwWAN4HmKtNqjv6b3hcYHNkAOGThcGPsx+9f6ju6hwIEyMzQ6JbTG9Nyep7c6UoAzHxOXWodQs4YAQdwxFLhZrJ66lgoWSMg2WCwvDJ7P4U6e2FCTkPqL5i9I+AALlgq3BiTO7ljlofDfyrVlcpnHK74zeP4ZFeHvaeBf//r50X93mHyQ08AWGnpcGMQcOA3Qs1N2ODTnCpe3yHgAHZaKdwYBBz4xrSfTKg5YHfahfAaQMABbLVyuDF4cYMvlKhXt2TUYT+T5QVexSHgABZaK9wYk4DzliFjuMgs6R7J8NFhssPFaQ2TpeOvA73RIeAAllk73EzRg4dLaEHlL/AbnbOmNG+zigqwQ27hxgj87g2OMNWagQwf/JzspILcBXyjwzJxwBK5hhsjO6qhtkcVB5Z6RLWmeAQcAg5QpdzDzRQ7m8IuKo2k9iCUnYVtYI5s0Q+vAzyTjoADVKywcDNFyEHVTBuqIcN7rIQq3+P4l82aDI99Cjjm5PdIop4S9etIorQmop9X0fi51ZBGmn3Wf854vgHVKTzcTGXbt9d29YvcfWZyUBazxPsw2d4TVMbtLSOUDi9RdyTyUUm9e0u+pIQWwH6lhZtZ304clm2CDgrEfI0lXAk4ZhWdrsokJszo1lJCawlwUyXhZpYpW4sMdela7uq7pJZivxysKTvosnaP+Rq72BpwQjztHfBd5eHmomy1VWNTtxPMW0uXhL/Xocf0603wCW0wEUsz50KN7rEpn50mp4uf2jCDY2ax9H+fEWgA/1gXbm5iwo/In8cvjAMZtLKPjsNPiKsycI5KhzLaYf8au1U5ZJxV9eRVQ0YvmZ0B/OVcuJlnPz55q18oY0HACDYueRyf7OoXn9dSmuyk91syTAg1gP+cDzeP4w9P9d1YRxAwgo2LnsQnZhXbCylUFmoOk60jARAMp8PNfvzhoRLFapigEWxcth+/f6nDx0PJGWeHAWFzNtx04n+3+tL/JAiWuYANZHSbYOM2XcE51g9tyYnZ2+iWjDq0n4BwNcRBk2BzLAjaiIqNF4YyfJDPEnGzc3DN7G3UFQBBq4mDdLAxg4gtQcgesdzbDyagKmnckzWYas1Bsn2bZd0ADOfCjRkglhxL2HCPbkcxS+GZw+QHE1QfydLMgajRDkdsAJjl1MzNj/FJrNPYW0Gw9BM2eZ5srXWXD3stM3/DgagAruLMzM1kzqbgZaOwm0obMnog8FZTh5WB1D/dtMGfqd49T7Y7AgBzONOW6svAVGxagiCZlVFmyTd36X7Lvr7RTZW5RwQbANdxoi3FRn3Qd/IP2IjtMlPR/CKjjZp+Mz8eSe3sln5z/TTrefvfcCAqgEVZH2724w9tJYpl3wEzK2EYGP36vbCpg962/lfZjCRqXf8rVE8HhFS/8+6WNLsuBR5zhlxfaqfT5eHZyd2jHVbIAViE1eFmZj+bliBQKm3K6Hao7ahJoLmrv1F31z9ochx2XrkSdL7d2LALNYDlWB1unsQnZj+bXUGwhjL8LsSL2uRgyftS3LYHR01pPrM95JhDcQcyfESwAbAMa8NN+acGwzYhroiZVCvK3KTSiZADAMuwMtzQjoJpRRwk299JICbPeRNq2lIB3a7qHCZ3ngkAeMDKpeAcr4B1t+N3iTndfiD9U6lw522zGlG3gT+ZkCUA4DjrKjfmhV6X5dlaP2xHB8mW95v1deLTjYF8fq1EYrEIVRwArrOqcpPdNbKfTdjMypih9xfWrA31+dS2YGNMqjjsBg7AWVaFG92Oerr+cle4TFcNnvm+MuZx/MvmpA3VEnvtPYnfn5r9ZgQAHGNNW4rVUQhhiPjJvX/dj9TopUMhPm1Kc4fVVABcYkXlxpTodbB5KgjaSKJH4jETbESNjhyrTo5XLjJoDMAlVoQb044SVkcFTYfb5KdkKxFPmf1rTLARNxFwADil8nAzftFnF+LgmV1oxVNmxka33N6K23TA+fKWGRwALmhIxSa7sSJsR74OEU8253vrx6B8tNmXullF5f0y/WVcPNC0JtHG7NdbVyXP9I/NgZ+pfnzv2iGmgIsqHSh+HH94GrH0O3i+nh9l9rExy73Fs5Yr++BkX9sv8sfDmqi9FYNrV/+6N4fJ1pEAyF1l4cbc0ZrlsCz9Dp63G/b5fPDrSOSezzNSV5lU4syM4K7kQ1dzoiM2TQTyVVm44cRvGL5WbQLYafusKc3bobRXppWaAivNpmX1jEoOkI9Kwo0ZsIxkeCoImn7ydZ8nWzvimcnd/SfxX/fAw6/fRSWf1M4p7UAOKlktpYON6ytHkIvIy1L85ET7ELT34/cd8dikAme+ni0pxy7L7oH1lR5uzE7Ewp42EJU+T+50xTNmSF4Cen4riZ5mS939Y87Xqqi1aCp/p+NNHwGspPRww07EMJSHVZtsp+3wVv/pSqxXh2ya+ZrH2UzgnlRnw2z6OAnLAJZUargJ7a4WV1Gpj4OTAbWjLmr/GJ9UGQRy1Zc/jiNLFjuYsEzAAZZXWriZ3NXuCiBRVzwTertVv5A89WH34qxio6xqs5mAQ4sKWE5p4YbzozA1lKFXLSnTxqDdKht9qTv9b5BtKmrp9hS6RTU5qgbAAkoJN5PJ/11B8Mzyb9/2tTH7nwjB3dhz9QLswm7pStRbVlEBiykl3EyqNoDZ2faNeCTUIeKr6Auwc9/rDn0NNzi8FFhM4eGGqg1mnN2SoVdb9hPcL2m7VL2ZbLjo0CD4+PBSnnPADQoPN7z4Y0bSSXbOxBME9/lcqt44OgvobPsPKEuh4YYXf8yKJPKqJUVwv5IT1ZvJCrddcZA5DoL2FHC1QsMNL/74xq8diQnu17O9epPN2Ti9wq1Fewq4WmHhhhd/nOfX3jY6uMeC67RtXtmjv34+rHCjPQVcobBwQ9UGs3xrSWkPBdf6Il+s3LV4Erq82FHZxdVpQBkKCTdUbXDBmU8tKQ5/XYwOtPdtnAvx7MbLqdVpQFkKCTdfZMBW4fhK312+F49EIjy/F2N2Ld4Vi0xOMN8Vj5jhYgFwTiHhhjOkcF7kzd42k6pkW7Cou2IR304wn2hNqokAJnIPN5TscdFIhl3xBLNkS7OmbdLJqjZt8RBnmwHn5R5u+CbDLA/PkmoLljKSkRUry/oy9HkIvMXsDfBNruFmPz4xL2ItASZGoj6KJyYXj5ZgKWawWCoWwiIHVk4B3+QabhTLY3FBTWrezNvoiweDxKvZqLqqEEg7kZVTwERu4YZBS8zj0xJw4fm9MgtaU20JgC0tQKBquYUbBi0xFYk6M8ct6KfXkXiCltR6qmxNhbTIwda9hYCyNSQ/bYFXTEjRrcazSL/pH5nH1Hxct2d+VfrH5udqk59rSGP8c53kH6l4iJbU2satqSoqeYHtSzTdW+ilAAHLJdyw/Nte1wUU8ziSaPzjmn4cSe3sln4T+c9ZJ9k5E8xqC9YyaZl0pUSmXa6rym0Ji9lbiHCDoOUSbtixtXhUUapj9kfpy7AlWItumZiLbqlnOn3RwSaS4LRNa4obFIRs7XAT6J1RDlQ6CSrjx6Go3004ma2kEFLsoINNW5CHlr7otjol7nsU6o0XrSmEbu1wwyBx5ltlZRxW0tmwkj3WU1o+zrLqCAGX6YuuaU2VctEN/MaL1hSClkdbqi1eO19hMW2gi4GFyor32oK8fC8lCbQlNUVrCkFbK9yY1Q/6Yt8SZ2XBRVdbeqbSYqouahxk6j1CC4zJc1yQG1O5eSAl0Dcgd0P+yg2zKtmRAAFaK9zYvDx2pk3Ui8ZVFvlIcMHyRu3x5AbyslHi3E1bAqZf87aFcINArRxuTMmzX/lZLabyks24TNtFhBfkSUm0LciVrii0peCL7qTiFvpmdqVVyQDbrBxuvuiSZzn3s98CjKm+mMeGNHsM5qIM+vm2SVMqX+VUFKi4SblVMsAqK4eb/PvZ4xDTG403l4t6WQXmS0qAQVUm+9uwlX3+2lIwKm6ZMqpkgI1WCjeTJZYrHtB2PsTckmaXFhJs9EWGm0zbFKJV9EoeKm4Z5m4QqpXCzSJLLLPDE8etpPfZKqR6l0oMXFITpS+QxJsiDKSxKQUdxUDF7Zy2AAFaKdxcbEnNBhmqMfCFDjal7ckSGqWDoxQUbqi4ndNivxuEaOlwk62SUps1iY6y5dX17kHyQ08Az9DaKFRhwZGK23lFVskAWy0fbrI7gO8E8NhkqwNaG4UZV26K+Z2puJ1TZJUMsFVNAFwyudtFYaKWFMRU3ASzCHsIDuEGmEMVWFnAmNmDJffKmBkmVlTcLuC5jPAQboA5IqfPTHPDF5GW5GwgI4LNJVFLgMAQboA5mNsoXl3quVcUqLjNVUiVDLAZ4QaYI5KIi0HBVAHVMSpu8xVRJQNsRrgB5qACUDxdHfu75K6I39N9SuotAQJCuAEuoIRfDh0g/yY5Y5h4vhqVGwSGcANccqslKFxUzFxTS3CJol2HwBBugAtYcVOaIv6dW4JLdJD8qwABIdwAF4y4yy1LruGGduLVimgBAjYj3AAXRMxtlEYHkpbk5D983a6kn9MMWiMohBvggkgUF0kHNaTRElyBrQ0QFsINcIFibqM0AwIJgAIQbgBUZphrlYyK2zVaAgSEcANcwkZwZWnkOCczYuYGwAThBgAAeIVwA6AyVFsAFIFwA6AyrEwDUATCDXBZSwAAziLcAAAArxBuAACAVwg3AADAK4QbAADgFcINAC/UJEoFV0kFCAjhBrggkuhMAADOItwAFyhRhJuSqByD5EAGqWCuiMoNAkO4AVAZ/QJEkASQu4YAS+jE/259kdGGyHCzJqql77z/rsZb6KvNSGpnB8md2+I4fZd7pgSu+TnZSZ/EJ4LLFJUbBIZwg7lMiPmv9HWAGe/W+30WXqJWX/ob0eRzlGTvffuvSsUDui31+/RvhWKp/IeAU2GH6Uuy5zQQDsIN5HH8y6apxERZiGlPQ8z5nmUkVDNgOzMMrnimXhKxkgyBIdwEJmsr9duzQUbJcObwwrVCTEs8YIYvuTyWYySDnGduxtXDTcE5I9pSCAzhxnP78Ye2vpPd1BfrbV2Jac+2lajGzKdYCl6aW7kPFKtfaSleVuc5jcAQbjzSiU83BvLHpr5L247GVRnRoUaNqzLjiRgpXic+bnWSnVQcpv+dzrg8liPv54qi/TJXQwY9AQJCuHHctDKj3707kM+mQjMz8ItVmJ1umdsoRe7VBFqKc53pEEnlBkEh3DjGVGe+yOc4GldnJJ5WZgwbXtQH0miJ4/19sxlcXRfyUbT8V9cNZNjja3eefp2gaoPgEG4cMKnO3DUDwH1dnbG5MqPbYS1x3J/1nW5fULQijrkwe93sxydn2d5LMEYsA0eACDcWuro6Y/8kyMiDi4op4XOBLF5xG8uZuRvFiqkJHSK7AgSGcGMJs0S7L/1Yv3tXV2fars7NRDNtMpepbB6EcFOgaLyyKX9KRh/17064mdDhhrYUgkO4qZBpN01XNulg0xYPmOMYxANmTkGx022hhoVddMe/733BGCulECLCTcmmgUY3cHZ1u6nl25Jj/Xf6m3iB/VKKVtTeK6ZSwWq3KZWyUgohItyUYDoQrN/ib4HGzwunvrB8Lx4Y6Qsk0aZYRVUUzO/bZ8XUmI54HwUIEOGmIBcrNOZjURiVAC/mVNjrpnCF7b1ift8n8UlXv9uWwDFMjFARbnKUnds0uH++5RTc/f+GD7sUc/dfrKL3XolEfVQStSVwSoZdAQJEuFmTWbbdl8+7Ml7l1G8HGmjO+cJycNxgpMOHFKqW6Ev7Qwnb2WGywzAxgkS4WcHMPjT3zbJtwTl1qZtluM6/qKrs79AW5C4q+AwoKm/j4f73AgSqJliYmaPRvfwXA/n8SQeb18KFb66hJxuoRYVXF8JV9N4rk3mergQtSgQIFJWbG0znaGqi9qY7BTNmej194fqreIAVU8V5ntzpSvHeScA3ICPmbRAwws0c8+ZoCDRLaYsHzMWBQxiLoEppWQ5lmOiv3wsJkur97PhQP7AO2lIzZttO+ofmRbEtWEVLPGAuDlF2DANypG8USpkFmVzcUwlS9EaAgAVfucmGg/94GMnIbLA3nhWhSrO+x/HxpicrNbr6LRbkRpW490ok6o3+/z2VwJiqlQABCzbcTHYNfvrtkEqmK/Lk0YopU2Ug3ORIybDE50Wtq/+PgYUbWlJAUOFmWqWZHQ5GMfxZMcU5RflSaZkXXjO4HNpuxbpS9UqAwAUxczOZpTnWVZrfdJm6w8ZsxfPljClzcWTuJk+VHAfwTgLCKinA48rNvFkalMqbf3M288tPWcPEs5oyPBpI/WkgNzVHtKQADys35zfaUx19p0iwqcb4jCnxQ1B3/kWqoqpgNvTTNzhBfA0jVkkBY15Ubmb3pdEvYm3zMaYkqjeUels/HInjwt4vJU/VDbpGUjvSrw33xWsqfZ5sdQWA25UbE2oexx+esi+NnXwZKg57v5T8VNGSmprsiNwVjymJngmAMScrNxeXcVOlsZMukd/VD3viAd3ifKcvHqGfMr2W2vik7uro5+OzaWXXPyo9TLaPBMCYM5UbU6V5Ep/smVVP+gXqWKjSuKDViY89GeKs9sLsPtMyKeU8qSv5XL2hagOcZ324ofXktv9mczfOY0n4uipZAn5J5GUIMFWbrSMB8JW14Ya9afwQedUGUKxEWZEtq3h8rN5QtQEusy7cTEMNrSc/TOZuPEFrajXVt6Rm+VW9oWoDzGNFuJm2nvbjk98INd7xZu5mcoFOBUtRlu0TNGkxehFUqdoA81UabmbnaWg9+asv9V3xRERramkjGb0Uywxk+MiDGaojqjbAfJWEG9N60lWat8zThMGn5bcNCy/UNtMBomvjcQDmz6Rfd5yteujXzbOhDKnaAFcoNdzMztPoF5ZYEIRIom1fWlNmK3/xfDO4PI1ErK10HSRbJqh2xUGmHcUZUsDVStnE73F8sqvv4O77u4EWbrAxkIbZrbgrHvB7M7g82b+xnK5+PGhI/dSl6rGZF3qeBTMAVyiscjM7JKy/GV8LQ8JBG8nIm0pdNlisUsENIuuHdk31Q1eXHokzVGrmhQTAtXIPNwwJYx5d7fDs0MLoleBauirixL+RGcrVr1VO/FmVjO7RjgJullu4IdTgBhtm5ko80ZThETsWX+vIpYvw82TbnIHWFbs9Okx2egLgRmuHm07879aT+OQ1K59wE59aU9lgsRt3+1VwcSWPDqz3bG036tfWZwfM2QALi2RF05O5hVkaLO5Mv0D/TTxhVoANpP6JQH/Jkf46PxAH/TM+btWldqxfGltiCRNsdGWpIxUyN7D64aNuL/ca8j+9TnKbqiWstnS4IdRgHfrFccemrfjXtR+/19XK6KngK121+c7luRCbAo4NwWay2vX1+Y8q3R6LejrYvxep9w6TH2iXwSoLhxtCDXLS1Xf1O+IJqjeXOFu1mTUJOG/1S+SmVMSGYGPGDvrSN0fitK77PDN/pr8HTMDpjXTg+ZP8pUt1B1W6MdwQapCzs6a+s59shucFqjffuF61uUh/bV/qr+1DKZHZfVhXOB/9rwVHK0zaUbuyEqUrO1GqLzLvldS7VHdQpivDDaEGRbHhjjRvT+L3n2ya06iCj19XQ1/g9/QL5dNyqnOqN7RkufekavNJcjKt7ujniW5l1brM7qBIl8INoQbFi3oHyZ3b4pHJ982xBEul+qK84+seLKZN1ZD6i6KOjTHVGv3wypxdZktVU4c6E2xaUqhsdke3st79SZo67PwjFSAHl8KNOftJCDYomG+DxUbI3zv6ov8ghBOqs+Fac/MXtSQn5jgFs+uwTcHQ7FlmtvaQ8qWT2Z13DCpjHYQbVMWrwWJjcnfv1DlFOfFiiHgZJuTUxuflrfZaaSo15lDRka7U2FbtyrsdtQ7TytL/Tl0zt2OWoft2Q4TiEG5QmaYM/+bTYLFh5jP0wwsJhLlID2R0O9QjAUygrUm9rYPOXV2/aqkrVldN2k7mHKv3NaklDRn0bH3ul9OOWs3FuR3CDq5CuEFlPB5ADel76BE7555nKh8DGbTM+w1ppOOPOTJLop+7JpjviVu6hB1cRLhBlbxbFm4E1J4Krh3ls/mb9TmJsAN9YwFUZ2MgNXOX2BGPmBbNfnxiLvpvxVvj1VHOnR+F+bJqU9+sBvNBW7cH2/o5+lR/H043F3zHzE5YqNygal5Wb4wqNoAri5LhbU6o9kMnPt3oy+dTsXTOJk/TAWVhNZb3qNygal5Wb4znyfaevln4Xjy7WchOqCbY+GIgn00rqiUBMK3iKNurKDb7aevvz1S/3zVnZN2SZpd9dvxB5QY28LZ6Y86e6kvt1Jfdi30dAg9VhfvZWGq8qWBXt7DesYOy2wg3sILPF02bTplej3pzkGzvCrxAsFlIV7+942ws9xBuYAtvqzeG+yuoVK8pox1fvz6h2Y8/PFSiWMK/nFRoYTmDcANr+N7yeBz/slmT4bF7AYdg45Mn9/51X9ToSLAulpxbjHADm+jqTfO2z3dErrWo9AtEtyHDewQbPxBsCpMKVR2rEG5gFf3ikBwmW/fEY+4EHGZsfEKwKVVXmNWpFOEG1vHxxPCLJgHnrVxxFlHVWBXlF2ZsKpXKuIUVvaF9VR7CDSykerpicFsCsB+/7yiJnoolsgMea/dsexE2O+hS6l8Nq6LsMbuJIO2rYhFuYKWQKgf78Ums76pfVN2mMvM1Axk+sO2E78nFebcpzR0uBoszOw9/kc8v9Nd1V2Crrn57p5/bCc/tfBFuYCvvh4tnTdpUHf0teV9KZqo1unr0zMbTvU3Fpi/9T5MfpgScxWT/bgPd9lRWtj0xV6rfErOBIO2r9RFuYLOuvuDuSEDKDDlZC0peNWT00tbVUHNej0xZ/8FPyVYimGs//tDWoeZtAKfS+ywV5nTWQriB1fSF7NFPFlYUimb2xIlksFdEyHEh1BjXDcHqSlPnMLnDqeQX6Ndv3d6UPYFPUiHoLI1wA9sF1Z66yFRyalJv10TpC/3qK6uyQBP1hjrU/EmGXdv3rTFtlYH0b9rRuaufGw9oU9GGCoUZSDbbZeibvndUL69HuIEDwlk9dZ3JEQ6bI1E67ETf66pGa94QcjZDI2f6Tq9nNhUzjw0Z9FzaiE+/Dpk5m9YCn5rqv+Ozw2TrSAJlKlz6e6RDGyosBJ3rEW7gipcHydYjwSXm5HGRP48vbD5UMVZcunykqzjPQqrimNkafXF7QbUG06BD6+obwg2coe9Q7nGH4rds1mh4KqtJ9XPkle8zWmaJd18+m9maXQEuS4UZHcINnBL0/I3vJsu+zetPS9bjZasq27fmj4c1UXu0oLCgVMZnXtVfhXYMBOEGrkmbMrzNQY7+2Y9PzPLlWPLjRcgh1CAn4++HUHZGJtzARUcHydYDgTcKPiJAv6hHR7ek8calF/VspkaZoznaAuTLnGD+5pb8Jekkt728USTcwEnsc+KPx/HJrn4hei3lsPpF3cwciYzuUqVBiY58nM8h3MBZoW7w55MF97MpSle/vVNS71Y1j2BaTgP5Y1NXaO7qt1hfZFoCVMOrthXhBm6LarsHb//vG4FzchwgXttkKW1Pt8beDyXSj/W0iMBj/s5fpN/W/7/v9Q839eMmFRpYyPmtFQg3cJ6+874d2koA19kUbK6n9PMqMu2rVAefX3U7dLxBonmrZx8/ZzTeWHH8wrqhP39Df/7fs/CiNqnKwEHjNq6LQ/mEG/hAX2zqOwQcN2T7tPxxzOZzgDOcW3lYE8B9+i55eJwNY8J2A/n8mmADOKVlhv7NsShmAYA4gHADXxBwHKBfGF/nvJcNgPI4E3IIN/CJCTinT+79677AOibYRBwZAPjA+pDDzA28xD449sh22P38gmADeKvblOYDm1ZXUbmBl8xut2bXW0GlpsPDBBvAa+2+9D/p4shrsxJSLEC4gbeygHPythMfs49IBbLl3p9PGR4GgrFrtniwoVVFuIHXdMUg7kv91Ja7iVCYwW439rEBkLPpPM5xla+7hBuEwGwYd+rKEkbXmYHumgwJNkDYTKvq9Mf4ZE8qMGeg+P2R/jCrTeCrl00ZPuskO16ehFu1gk/3BuCm0geOqdwgNHumTbUff2gLcmPKz6YMTbABMEe77Fkcwg1C1FKijvXF+AXDxuszQdGc7C1sIQHgauNZnLJWsdKWQuicOzPFFtky78/mhaqSnjoAV6leU27dK7JNReUGoZvcTZgl46yoWpSp1mTLvAk2AJYVjVdTFvmaS+UGOO+oKc1nNu20aZNs75r+a6EFBWB9ZyORBz8lW4nkjHADzEfImZEdofDHw5qoPd3GY04JQG50wHmkA85LyRHhBrhe0CGHUAOgDHmfB0i4ARbT1XcXr4oon9qIUAOgbHkGHMINsJxUvyW6mvPKx2oOoQZAlfIKOIQbYHVdHQDe3JJm1+WgYwLNQD639d/loTAoDKBieQQcwg2QC9XT3zfdSKJ3z5M7XbFcFmj+2FSi7pvDRanSALDJukPGhBugGDroqPcitW5D/qfXSW5XfpaV2ZtGh5lN/e5d/Y2/SaABYDMdcO6tOudIuAFKoL/RznSY0NWd8duvusLTa0gjLaKdZfai+SIjHVyGm/r/+73+0CZhBoCDzprSvL3K6yThBqiYrqakOuykkx+OH3XV59ebf1309+xRNvTnt7LHqCUA4I+0KUMdcHaWqn43BEClJoGkNfsxdfm+45pfP/ldBAC80+pL/a1+3FnmF3G2FAAAsFn7x/hkqXPsCDcAAMBqOqy8eBz/srnE5wMAANgtkuHbTny80MIIwg0AAHCBmb95usgnEm4AAIAr9hZpTxFuAACAM3R76sVNn0O4AQAALjGrp+LrPoFwAwAAnGJWT93w8wAAAE5pPY5Pdq/6ScINAABwTiRy5copwg0AAHDRldUbwg0AAHCSrt7MPeibcAMAAFzV3o8/tC9+kHADAACcNZLRpWXhhBsAAOCsSKL7F8+cItwAAACXbQylfq56Q7gBAABOG4oi3AAAAH/o1tT2bGuKcAMAAFy3MZDG19PCCTcAAMB5s6umCDcAAMB5ujX1/fR9wg0AAPDB5nTuhnADAAB8sPFFpGXeIdwAAAAv1KU+Hiom3AAAAC8MRRFuAACAV1rmP4QbAADghemKKcINAADwBaulAACAVwg3AADAL534uEW4AQAAXiHcAAAArxBuAACAN76IbBBuAACAVwg3AADAG7dEzgg3AADAK4QbAADgk7OGAAAQsEjUmdIXxOz9KM0eJZ3+/FDU77XJzxujyefkoSaqdf7PEv19+r6anJOUvT/9vKgluFYn2SHcAAD8Mg0rJqiYkDINJyaUZCEl0he/Rmo+t5P8IxUHdeLjDZE/bwxk0Mo+ojZG41VCqmUe6xL9dRqOsmAUtSQMqfkP4QYA4BilQ0vU08FFhxj1axZaojQLLP85M3fu4rnJ39G8pQv/mnOBSG2Y8KOD4IapFmVBSJmjC1pKog1xVES4AQDYKwswIx1e9CWrVxvPUTR7rlZabLBMIOrE/27NhiBT/allLTMdfNSmrQFIP19+N4+EGwBAhZSpunR1K+WjuesmwNhh8jVIr/ucx/EvmzUZ6fCjNqNx1Sf6XioOPzoE98wj4QYAUDgzByNZJeajeRSp927JlzSEFpKvDpMfepN3u/N+fjb8TCo/32eVoGhTClPrmv8SbgAAuboYZG5Js0s1JjzXhR8z/zOQxuZoHHrGA8+5VH0aMqByAwDIw7fWkpJ69+DbRQ2Ya1Kx6879uUnwyQac1ebiwUf1ppVAwg0AYEkqVSLvqMqgCBeCT3Lu5+YGn/EeQGaV19dQTbgBANxgNswME+ZkUJXrgs8swg0A4BwzMxNJlAxF3lOZgYsINwAAs/lZV1do3pvVJs+Tra4ADiPcAECAJiuazBDwO1pN8A3hBgACYQKNDjNvalJLGjLsEWjgK8INAHhsNtDQbkIoCDcA4BkCDUJHuAEADxBogG8INwDgqOkxB/rtGYEG+IZwAwCOMcu2zaZ6DRkdMRQMXEa4AQAHZFUaeTWSRsLZTcD1CDcAYLFscz3aTsAyCDcAYJlplUa3nV7SdgKWR7gBAEuYKs1Qh5qfku1EAKyMcAMAFTq/hPtOVwCsjXADABWg9QQUh3ADACUyrSdTqTlIto8EQCEINwBQgm+rnmg9AUUj3ABAsY4iid4QaoDyEG4AIGfTIeGRjF7+nOykAqBUhBsAyAlDwoAdCDcAsCZCDWAXwg0ArIhQA9iJcAMASyLUAHYj3ADAEnSweUaoAexGuAGAxRwNZfiM1U+A/Qg3AHANNt8D3EO4AYA5CDWAuwg3AHCOSkcSPfop2UoEgJMINwAgrIACfEK4ARA8JepVU0YdQg3gB8INgGCZuZqRDB8dJjs9AeANwg2AADFXA/iMcAMgGMzVAGEg3AAIgmlBDWT0gE34AP8RbgB4TqWR1B6wXw0QjpoAgKd0tSZpyug2wQYIC5UbAN4xszVqvLvw1ksBEBzCDQCvMFsDgHADwBu6YqOrNdsdARA0wg0AD6ie0tWaAzbjAyCEGwCOo1oD4CLCDQAnTY9OoFoD4CLCDQCnsBIKwE0INwCcwUooAIsg3ABwALsMA1gcOxQDsJZpQZmBYXYZBrAMKjcALKV6I92COmRgGMCSqNwAsI4S9UpXa3YINgBWQeUGgEWy2ZqDZKsrALAiKjcArMAJ3gDyQuUGQKXYtwZA3gg3ACqkegMZ3WPfGgB5ItwAqIQZGj5MtvcEAHJGuAFQKtOGEqndY2gYQFEYKAZQmsnxCQwNAygUlRsApTA7DT9PtjsCAAUj3AAo2PRcKNpQAMpBuAFQmG+neG+nAgAlIdwAKARtKABVIdwAyNV0NRRtKABVIdwAyNF0Uz7aUACqw1JwALmYnuTNbsMAqkblBkAeHh0m25wNBcAKhBsAa1Cp0m2ow2SnJwBgCcINgBWp3pBDLwFYiHADYGkcegnAZgwUA1jWI4INAJtRuQGwkG/713DoJQC7EW4ALEClg/Eyb/avAWA/2lIAbjAeHGb/GgDOINwAuIZ6w8Z8AFxDWwrAXBx8CcBVhBsA8zx6zo7DABxFuAHwFSuiAPiAmRsAEyodyWiHYAPAdVRuAIgJNqyIAuALKjdA8FjqDcAvVG6AoKmeWep9kOycCQB4gsoNEKxsD5sOwQaAZ6jcAEFSbw6S7V0BAA9RuQGCQ7AB4DfCDRAQs+swwQaA7wg3QCA4TgFAKAg3QAAINgBCQrgBPEewARAawg3gMYINgBARbgBPEWwAhIp9bgAPKVGvDgg2AAJF5QbwjnpzmGzvCQAEinADeIUN+gCAcAN4Q/UINgBAuAE8kZ3uLQAABooB96l0KKN7B5zuDQBjVG4Ap42Dzc7PyU4qAIAxwg3gLIINAMxDuAEcFIk6I9gAwHyEG8BBI4INAFyJcAM4Rn/TPjhMdnoCAJiLcAM4xJwX9b/J1pEAAK5EuAEcwUGYALAYwg3gBPWGYAMAiyHcANYb7z7MQZgAsCB2KAasxu7DALAsKjeAtdikDwBWQeUGsFQktQc/J9upAACWQuUGsNOj58mdrgAAlka4ASxjlnwfJFsvBQCwEsINYJFIJGHJNwCsh5kbwBoqbcjogQAA1kK4AayQrYxiyTcArI9wA1iAlVEAkB9mboCKZWdGsTIKAPJC5QaokBL16oABYgDIFZUboDIqvSWjjgAAckXlBqgEA8QAUBTCDVABBogBoDi0pYCSMUAMAMUi3AAlYgdiACgebSmgNCodyOiRAAAKReUGKIkZIP452UkFAFAowg1QjkcEGwAoB+EGKN7RQbL1UgAApWDmBiiUSpvM2QBAqQg3QIHYqA8AykdbCiiI2c+GORsAKB/hBigA+9kAQHVoSwG5Yz8bAKgSlRsgZ0oi2lEAUCHCDZAjJerVYbJ1JACAyhBugNyo9JaMOgIAqBQzN0BOWPYNAHagcgPkgGXfAGAPwg2wNpWy7BsA7EG4AdZk2lECALAG4QZYA+0oALAP4QZYGe0oALAR4QZYEe0oALAT4QZYAe0oALAX4QZYGu0oALAZ4QZYkjk7SgAA1iLcAMs54uwoALAb4QZYUCTqbChDqjYAYDnCDbC4VwwRA4D9CDfAQhgiBgBXEG6ABTBEDADuINwAN2OIGAAcQrgBbsAQMQC4hXADXO+IIWIAcAvhBrgGVRsAcA/hBrgC50cBgJsIN8BcKh3I6EgAAM65FG4ikTMBAqe/D95QtQEAN82r3BBuEDiqNgDgMtpSwAVUbQDAbYQb4ByqNgDgOsINMIOqDQC4j3ADfEXVBgB8QLgBJqjaAIAfCDdA5oyqDQD4gXADZBKqNgDgB8INIJwhBQA+IdwAnPwNAF4h3CB4VG0AwC+EG4SOqg0AeIZwg6BRtQEA/xBuEDKqNgDgIcINgqVk+EoAAN4h3CBIkUj3MNnpCQDAO4QbBCpi1gYAPEW4QYBU+jy50xUAgJcINwiOomoDAF4j3CAwKj1Mto4EAOAtwg2CQtUGAPzXECAYKh3JqCsAAK9RuUFAoi6b9gGA/wg3CAZHLQBAGAg3CAVHLQBAIAg3CEIk0RsBAASBcIMAqB6b9gFAOAg38J6SiAMyASAghBt4jk37ACA0hBt4LkoEABAUwg28NpQhLSkACAzhBj5j+TcABIhwA2+x/BsAwkS4gadUyvJvAAgT4QZe4vRvAAgX4QY+OhvJsCsAgCARbuCjhEFiAAgX4QbeUSz/BoCgEW7gGdU7THZ6AgAIFuEGXuEcKQAA4QZeYZAYAEC4gU/YkRgAQLiBP9iRGABgzAk3tW4k0hXAKexIDADIXAo35gLxPNnaGcrwO33BeGMuGgJYj0FiAEAmWuST9uMPbSWjXf3p9wWwkAnjzNsAAIyFws3UP+PjVk3q7Zqoh0qiTQEsYNqoptooAADIkuFmlgk6dal19Lvb+rdpCVARJfLgMNk6EgAAZI1wM4u2FarUlOHfOsnOmQAAIDmFm6lOfLzxRepxTeS+vptuC1C8o4Nk64EAADCRa7iZlbWt6rFuGjykbYWijETu/ZRsJQIAwERh4WbW4/iXzUgGe8J8DnKl0oNk+zsBAGBGKeFm1nQ+R/+P7yqJNgRYHS0pAMAlpYebWY/jk93aOORILMCSIol22JUYAHBRpeFm6tv+OQwiY1G0pAAA81kRbmaxUSAWREsKADCXdeFmFiuucBVaUgCAq1gdbmaZFVcig/EgMkEndLSkAABXcybczGJpefBoSQEAruRkuJn17egHgk4o2LgPAHAd58PNLIJOEM501eZvAgDAFbwKN7MIOn5Sot4dJtvsiwQAuJK34WYWQccfSuTBYbJ1JAAAXCGIcDOLoOO2oQy/+znZSQUAgCsEF25msbzcNap3kGzfFgAArhF0uJk1DTo1XdFhZ2Q7KVGvDpPtPQEA4BqEmzmmOyNnJ5dz1pUt2JUYALAIws0NONTTGiwBBwAshHCzhJmgYyo6LEcuEUvAAQCLItysqBMfbwx00NEX3Un7KtoQFIYl4ACARRFucsIS82IpGd4+THZ6AgDADQg3BTArr2oyMC2Uu6y8ygOngAMAFke4KRgDyetj3gYAsAzCTYmY01nZo4Nk66UAALAAwk2FzJzOSEYxOyRfj3kbAMAyCDeWYOPAK7G/DQBgKYQbC822ryTw1Vf6Cdp9nmztCAAACyLcOGDavgrx3CvOkwIALItw45jZXZL1pb/t+1DySOTeT8lWIgAALIhw4zjfqzoMEwMAlkW48YiHVR2GiQEASyPceMz1qg7DxACAVTQE3nqe3OnqB/PmZFVnJOqjAACwJCo3gTJVHR0f9Fu0bfG+OuxMDABYGuEG1u6rE0m0M6k+AQCwMMINLjGnmosMN6tuYTVl+F0n2UkFAIAlEG5wo6paWLolxfMTALA0Lh5YStbCamwWvwpL9Q6S7dsCAMCSCDdYi1mF1ZD6Zt7zOiwDBwCsinCDXE2XnEei2rJG2NFh6d1hsh0LAABLItygULPDyTqwbC4adjgwEwCwKjbxQ6EOkx/MuVDm7cj8eNGwo3/+TAAAWAHhBqW6GHauamMpiQg3AICV0JaCVaYDyiOpp5MgBADAUv4/zJKZqV/UjMwAAAAASUVORK5CYII=",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:_documentCurrentScript&&_documentCurrentScript.tagName.toUpperCase()==="SCRIPT"&&_documentCurrentScript.src||new URL("nostr-components.umd.js",document.baseURI).href).toString()}catch(t){return console.warn("Failed to resolve default avatar URL with import.meta.url, using relative path:",t),"../../assets/default_dp.png"}}async ensureAnonKey(){const t="nostr-comment-anon-private-key";try{const o=localStorage.getItem(t);if(o&&o.match(/^[a-f0-9]{64}$/))return o}catch(o){console.warn("Failed to read from localStorage:",o)}const{generateSecretKey:r}=await Promise.resolve().then(()=>pure),s=Array.from(r()).map(o=>o.toString(16).padStart(2,"0")).join("");try{localStorage.setItem(t,s)}catch(o){console.warn("Failed to write to localStorage, using ephemeral key:",o)}return s}render(){this.classList.toggle("dark",this.theme==="dark"),this.classList.toggle("loading",this.isLoading),this.classList.toggle("error-container",this.isError);const t=this.hasAttribute("readonly"),r=this.getAttribute("placeholder")||"Write a comment...",s=renderCommentWidget(this.isLoading,this.isError,this.errorMessage,this.comments,t,r,this.isSubmitting,this.currentUserProfile,this.replyingToComment,this.commentAs,this.hasNip07),o=purify.sanitize(s,{ALLOWED_TAGS:["div","span","button","textarea","img","a","h3","h4","p","ul","li","small","strong","em"],ALLOWED_ATTR:["class","data-role","data-comment-id","data-depth","src","alt","href","target","rel","placeholder","rows","disabled"],ALLOW_DATA_ATTR:!1});this.shadow.innerHTML=`
2931
2931
  ${getCommentStyles(this.theme)}
2932
2932
  <div class="nostr-comment-wrapper">
2933
2933
  ${o}
@@ -3194,11 +3194,11 @@ Minimum version required to store current data is: `+o+`.
3194
3194
  </div>
3195
3195
  `:`
3196
3196
  <div class="nostr-chat-history">
3197
- ${o.map(I=>`
3198
- <div class="nostr-chat-message-row nostr-chat-message-${safeSenderClass(I.sender)} ${I.sender==="me"&&I.status==="sending"?"sending":""} ${I.sender==="me"&&I.status==="failed"?"failed":""}">
3199
- <div class="nostr-chat-message-bubble">${sanitizeHtml(I.text)}</div>
3197
+ ${o.map(P=>`
3198
+ <div class="nostr-chat-message-row nostr-chat-message-${safeSenderClass(P.sender)} ${P.sender==="me"&&P.status==="sending"?"sending":""} ${P.sender==="me"&&P.status==="failed"?"failed":""}">
3199
+ <div class="nostr-chat-message-bubble">${sanitizeHtml(P.text)}</div>
3200
3200
  <div class="nostr-chat-message-meta">
3201
- <span class="nostr-chat-message-timestamp" title="${sanitizeHtml(formatTimestamp(I.timestamp))}">${sanitizeHtml(formatRelativeTime(I.timestamp))}</span>
3201
+ <span class="nostr-chat-message-timestamp" title="${sanitizeHtml(formatTimestamp(P.timestamp))}">${sanitizeHtml(formatRelativeTime(P.timestamp))}</span>
3202
3202
  </div>
3203
3203
  </div>
3204
3204
  `).join("")}
@@ -3961,7 +3961,7 @@ Minimum version required to store current data is: `+o+`.
3961
3961
  `,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);this.likeListStatus.set(NCStatus.Loading)}connectedCallback(){var t;(t=super.connectedCallback)==null||t.call(this),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=`
3962
3962
  ${getLikeButtonStyles()}
3963
3963
  ${renderLikeButton(u)}
3964
- `}}customElements.define("nostr-like",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`
3964
+ `}}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`
3965
3965
  .likers-dialog-content {
3966
3966
  padding: 0;
3967
3967
  max-height: 60vh;
@@ -4196,5 +4196,5 @@ Minimum version required to store current data is: `+o+`.
4196
4196
  ${n.map((r,s)=>renderSkeletonLikeEntry(r,e[s],s)).join("")}
4197
4197
  </div>
4198
4198
  </div>
4199
- `}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,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
4199
+ `}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"})});
4200
4200
  //# sourceMappingURL=nostr-components.umd.js.map