rx-nostr
Version:
A library based on RxJS, which allows Nostr applications to easily communicate with relays.
3 lines • 66.2 kB
JavaScript
(function(y,x){typeof exports=="object"&&typeof module<"u"?x(exports):typeof define=="function"&&define.amd?define(["exports"],x):(y=typeof globalThis<"u"?globalThis:y||self,x(y["rx-nostr"]={}))})(this,function(y){"use strict";var zr=Object.defineProperty;var Hr=(y,x,_)=>x in y?zr(y,x,{enumerable:!0,configurable:!0,writable:!0,value:_}):y[x]=_;var h=(y,x,_)=>(Hr(y,typeof x!="symbol"?x+"":x,_),_);class x extends Error{}class _ extends x{constructor(e){super(`RxNostrWebSocketError: WebSocket was closed with code ${e} by relay.`),this.code=e,this.name="RxNostrWebSocketError"}}class F extends x{constructor(e){super(`RxNostrInvalidUsageError: ${e}`),this.name="RxNostrInvalidUsageError"}}class ne extends x{constructor(e){super(`RxNostrEnvironmentError: ${e}`),this.name="RxNostrEnvironmentError"}}class re extends x{constructor(){super("RxNostrLogicError: This is rx-nostr's internal bug. Please report to the author of the library."),this.name="RxNostrLogicError"}}class k extends x{constructor(){super("RxNostrAlreadyDisposedError: Attempted to access a disposed resource."),this.name="RxNostrAlreadyDisposedError"}}const C=(n,e)=>({...e,...n});function Ut(n){if(typeof n.id!="string"||typeof n.sig!="string"||typeof n.kind!="number"||typeof n.pubkey!="string"||typeof n.content!="string"||typeof n.created_at!="number"||!Array.isArray(n.tags))return!1;for(let e=0;e<n.tags.length;e++){const 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}function Mt(n,e){return V(n,e)<0?n:e}function Ft(n,e){return V(n,e)<0?e:n}function V(n,e){return n.id===e.id?0:n.created_at<e.created_at||n.created_at===e.created_at&&n.id<e.id?-1:1}function be(n){throw n}function Le(n){return{async signEvent(e){var r,i;const t={...e,pubkey:e.pubkey??await((r=window==null?void 0:window.nostr)==null?void 0:r.getPublicKey())??be(new ne("window.nostr.getPublicKey() is not found")),tags:[...e.tags??[],...(n==null?void 0:n.tags)??[]],created_at:e.created_at??Math.floor(Date.now()/1e3)};return Ut(t)?t:await((i=window==null?void 0:window.nostr)==null?void 0:i.signEvent(t))??be(new ne("window.nostr.signEvent() is not found"))},getPublicKey(){var e;return((e=window==null?void 0:window.nostr)==null?void 0:e.getPublicKey())??be(new ne("window.nostr.getPublicKey() is not found"))}}}function Vt(){return{async signEvent(n){return n},async getPublicKey(){throw new F("noopSigner cannot calculate pubkey.")}}}const Bt=n=>C(n,{signer:Le(),connectionStrategy:"lazy",retry:{strategy:"exponential",maxCount:5,initialDelay:1e3},disconnectTimeout:1e4,eoseTimeout:30*1e3,okTimeout:30*1e3,authTimeout:30*1e3,skipVerify:!1,skipValidateFilterMatching:!1,skipExpirationCheck:!1,skipFetchNip11:!1}),Kt=async()=>!0;function ve(n){return"length"in n?n.map(Ue):[Ue(n)]}function Ue(n){return{...n,since:n.since?Me(n.since):void 0,until:n.until?Me(n.until):void 0}}function Me(n){return typeof n=="number"?n:n()}async function Fe(n){try{const e=new URL(n);return e.protocol=e.protocol.replace(/^ws(s?):/,"http$1:"),await(await fetch(e.toString(),{headers:{Accept:"application/nostr+json"}})).json()}catch{return{}}}function Ve(n,e){try{return n()}catch(t){return e instanceof Function?e(t):e}}function j(n){let e="";try{e=n.trim();const t=new URL(e);t.hash="",t.pathname=Ve(()=>decodeURI(t.pathname),t.pathname),t.pathname=t.pathname.replace(/\/$/,""),t.hostname=t.hostname.replace(/\.$/,""),t.searchParams.sort(),t.search=Ve(()=>decodeURIComponent(t.search),t.search);let r=t.toString();return t.search||(r=r.replace(/\/$/,"")),r}catch{return e}}class B extends Map{constructor(e){if(super(),!!e)for(const[t,r]of Object.entries(e))this.set(j(t),r)}get(e){return super.get(j(e))}getMany(e){const t=[];for(const r of new Set(e.map(j))){const i=this.get(r);i!==void 0&&t.push(i)}return t}set(e,t){return super.set(j(e),t)}has(e){return super.has(j(e))}delete(e){return super.delete(j(e))}toObject(){const e={};for(const[t,r]of this.entries())e[t]=r;return e}toKeys(){return[...super.keys()]}toValues(){return[...super.values()]}copy(){return new B(this.toObject())}}class G{static async getValue(e,t,r){if(!(r!=null&&r.skipCache)){const i=await this.cache.get(e);if(i)return t(i)}if(!(r!=null&&r.skipFetch)){const i=await this.fetch(e);if(i)return t(i)}return t(this.default)}static get(e){const t=this.cache.get(e);if(t&&!(t instanceof Promise))return t}static async fetch(e){const t=Fe(e);return this.cache.set(e,t),t.then(r=>{this.cache.set(e,r)}),t}static async getOrFetch(e){return this.cache.get(e)??this.fetch(e)}static set(e,t){this.cache.set(e,t)}static getDefault(){return this.default}static setDefault(e){this.default=e}static forget(e){this.cache.delete(e)}static forgetAll(){this.cache.clear()}}h(G,"cache",new B),h(G,"default",{});function Wt(n){return n instanceof Uint8Array||n!=null&&typeof n=="object"&&n.constructor.name==="Uint8Array"}function zt(n,...e){if(!Wt(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-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */new Uint8Array(new Uint32Array([287454020]).buffer)[0];const Ht=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function Gt(n){zt(n);let e="";for(let t=0;t<n.length;t++)e+=Ht[n[t]];return e}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Yt(n){return n instanceof Uint8Array||n!=null&&typeof n=="object"&&n.constructor.name==="Uint8Array"}function Qt(...n){const e=s=>s,t=(s,o)=>u=>s(o(u)),r=n.map(s=>s.encode).reduceRight(t,e),i=n.map(s=>s.decode).reduce(t,e);return{encode:r,decode:i}}function Xt(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(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 Jt(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)}}}const Be=(n,e)=>e?Be(e,n%e):n,ie=(n,e)=>n+(e-Be(n,e));function pe(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(ie(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${ie(e,t)}`);let i=0,s=0;const o=2**t-1,u=[];for(const a of n){if(a>=2**e)throw new Error(`convertRadix2: invalid data word=${a} from=${e}`);if(i=i<<e|a,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=t;s-=t)u.push((i>>s-t&o)>>>0);i&=2**s-1}if(i=i<<t-s&o,!r&&s>=e)throw new Error("Excess padding");if(!r&&i)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&u.push(i>>>0),u}function Zt(n,e=!1){if(n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(ie(8,n)>32||ie(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!Yt(t))throw new Error("radix2.encode input should be Uint8Array");return pe(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 numbers");return Uint8Array.from(pe(t,n,8,e))}}}function Ke(n){if(typeof n!="function")throw new Error("unsafeWrapper fn should be function");return function(...e){try{return n.apply(null,e)}catch{}}}const ge=Qt(Xt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Jt("")),We=[996825010,642813549,513874426,1027748829,705979059];function Y(n){const e=n>>25;let t=(n&33554431)<<5;for(let r=0;r<We.length;r++)(e>>r&1)===1&&(t^=We[r]);return t}function ze(n,e,t=1){const r=n.length;let i=1;for(let s=0;s<r;s++){const o=n.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${n})`);i=Y(i)^o>>5}i=Y(i);for(let s=0;s<r;s++)i=Y(i)^n.charCodeAt(s)&31;for(let s of e)i=Y(i)^s;for(let s=0;s<6;s++)i=Y(i);return i^=t,ge.encode(pe([i%2**30],30,5,!1))}function en(n){const e=n==="bech32"?1:734539939,t=Zt(5),r=t.decode,i=t.encode,s=Ke(r);function o(c,f,d=90){if(typeof c!="string")throw new Error(`bech32.encode prefix should be string, not ${typeof c}`);if(!Array.isArray(f)||f.length&&typeof f[0]!="number")throw new Error(`bech32.encode words should be array of numbers, not ${typeof f}`);if(c.length===0)throw new TypeError(`Invalid prefix length ${c.length}`);const b=c.length+7+f.length;if(d!==!1&&b>d)throw new TypeError(`Length ${b} exceeds limit ${d}`);const v=c.toLowerCase(),p=ze(v,f,e);return`${v}1${ge.encode(f)}${p}`}function u(c,f=90){if(typeof c!="string")throw new Error(`bech32.decode input should be string, not ${typeof c}`);if(c.length<8||f!==!1&&c.length>f)throw new TypeError(`Wrong string length: ${c.length} (${c}). Expected (8..${f})`);const d=c.toLowerCase();if(c!==d&&c!==c.toUpperCase())throw new Error("String must be lowercase or uppercase");const b=d.lastIndexOf("1");if(b===0||b===-1)throw new Error('Letter "1" must be present between prefix and data only');const v=d.slice(0,b),p=d.slice(b+1);if(p.length<6)throw new Error("Data must be at least 6 characters long");const w=ge.decode(p).slice(0,-6),R=ze(v,w,e);if(!p.endsWith(R))throw new Error(`Invalid checksum in ${c}: expected "${R}"`);return{prefix:v,words:w}}const a=Ke(u);function l(c){const{prefix:f,words:d}=u(c,!1);return{prefix:f,words:d,bytes:r(d)}}return{encode:o,decode:u,decodeToBytes:l,decodeUnsafe:a,fromWords:r,fromWordsUnsafe:s,toWords:i}}const He=en("bech32");function tn(n){const{words:e}=He.decode(n),t=new Uint8Array(He.fromWords(e));return Gt(t)}function me(n,e,t){return Array.isArray(e)?e.some(r=>Ge(n,r,t)):Ge(n,e,t)}function Ge(n,e,t){const{sinceInclusive:r,untilInclusive:i}=C(t??{},{sinceInclusive:!0,untilInclusive:!0});if(e.ids&&e.ids.every(s=>!n.id.startsWith(s))||e.kinds&&!e.kinds.includes(n.kind)||e.authors&&e.authors.every(s=>!n.pubkey.startsWith(s))||e.since&&(r&&!(e.since<=n.created_at)||!r&&!(e.since<n.created_at))||e.until&&(i&&!(n.created_at<=e.until)||!i&&!(n.created_at<e.until)))return!1;for(const[s,o]of Object.entries(e)){if(!s.startsWith("#")||!Array.isArray(o))continue;const u=s.slice(1);if(!n.tags.find(([a,l])=>u===a&&o.includes(l)))return!1}return!0}function we(n,e){const t=n.tags.find(r=>r[0]==="expiration");if(!t)return!1;try{const r=Number(t[1]);return Number.isInteger(r)?r<=(e??Math.floor(Date.now()/1e3)):!1}catch{return!1}}var Ee=function(n,e){return Ee=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,r){t.__proto__=r}||function(t,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[i]=r[i])},Ee(n,e)};function N(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Ee(n,e);function t(){this.constructor=n}n.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}function nn(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function u(c){try{l(r.next(c))}catch(f){o(f)}}function a(c){try{l(r.throw(c))}catch(f){o(f)}}function l(c){c.done?s(c.value):i(c.value).then(u,a)}l((r=r.apply(n,e||[])).next())})}function Ye(n,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(l){return function(c){return a([l,c])}}function a(l){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(r=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(n,t)}catch(c){l=[6,c],i=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function K(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],r=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&r>=n.length&&(n=void 0),{value:n&&n[r++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function L(n,e){var t=typeof Symbol=="function"&&n[Symbol.iterator];if(!t)return n;var r=t.call(n),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(t=r.return)&&t.call(r)}finally{if(o)throw o.error}}return s}function U(n,e,t){if(t||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return n.concat(s||Array.prototype.slice.call(e))}function W(n){return this instanceof W?(this.v=n,this):new W(n)}function rn(n,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(n,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(d){r[d]&&(i[d]=function(b){return new Promise(function(v,p){s.push([d,b,v,p])>1||u(d,b)})})}function u(d,b){try{a(r[d](b))}catch(v){f(s[0][3],v)}}function a(d){d.value instanceof W?Promise.resolve(d.value.v).then(l,c):f(s[0][2],d)}function l(d){u("next",d)}function c(d){u("throw",d)}function f(d,b){d(b),s.shift(),s.length&&u(s[0][0],s[0][1])}}function sn(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof K=="function"?K(n):n[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(s){t[s]=n[s]&&function(o){return new Promise(function(u,a){o=n[s](o),i(u,a,o.done,o.value)})}}function i(s,o,u,a){Promise.resolve(a).then(function(l){s({value:l,done:u})},o)}}typeof SuppressedError=="function"&&SuppressedError;function E(n){return typeof n=="function"}function se(n){var e=function(r){Error.call(r),r.stack=new Error().stack},t=n(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Se=se(function(n){return function(t){n(this),this.message=t?t.length+` errors occurred during unsubscription:
`+t.map(function(r,i){return i+1+") "+r.toString()}).join(`
`):"",this.name="UnsubscriptionError",this.errors=t}});function oe(n,e){if(n){var t=n.indexOf(e);0<=t&&n.splice(t,1)}}var Q=function(){function n(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return n.prototype.unsubscribe=function(){var e,t,r,i,s;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var u=K(o),a=u.next();!a.done;a=u.next()){var l=a.value;l.remove(this)}}catch(p){e={error:p}}finally{try{a&&!a.done&&(t=u.return)&&t.call(u)}finally{if(e)throw e.error}}else o.remove(this);var c=this.initialTeardown;if(E(c))try{c()}catch(p){s=p instanceof Se?p.errors:[p]}var f=this._finalizers;if(f){this._finalizers=null;try{for(var d=K(f),b=d.next();!b.done;b=d.next()){var v=b.value;try{Je(v)}catch(p){s=s??[],p instanceof Se?s=U(U([],L(s)),L(p.errors)):s.push(p)}}}catch(p){r={error:p}}finally{try{b&&!b.done&&(i=d.return)&&i.call(d)}finally{if(r)throw r.error}}}if(s)throw new Se(s)}},n.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)Je(e);else{if(e instanceof n){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},n.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},n.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},n.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&oe(t,e)},n.prototype.remove=function(e){var t=this._finalizers;t&&oe(t,e),e instanceof n&&e._removeParent(this)},n.EMPTY=function(){var e=new n;return e.closed=!0,e}(),n}(),Qe=Q.EMPTY;function Xe(n){return n instanceof Q||n&&"closed"in n&&E(n.remove)&&E(n.add)&&E(n.unsubscribe)}function Je(n){E(n)?n():n.unsubscribe()}var Ze={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Oe={setTimeout:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var i=Oe.delegate;return i!=null&&i.setTimeout?i.setTimeout.apply(i,U([n,e],L(t))):setTimeout.apply(void 0,U([n,e],L(t)))},clearTimeout:function(n){var e=Oe.delegate;return((e==null?void 0:e.clearTimeout)||clearTimeout)(n)},delegate:void 0};function et(n){Oe.setTimeout(function(){throw n})}function X(){}function ue(n){n()}var xe=function(n){N(e,n);function e(t){var r=n.call(this)||this;return r.isStopped=!1,t?(r.destination=t,Xe(t)&&t.add(r)):r.destination=an,r}return e.create=function(t,r,i){return new ce(t,r,i)},e.prototype.next=function(t){this.isStopped||this._next(t)},e.prototype.error=function(t){this.isStopped||(this.isStopped=!0,this._error(t))},e.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,n.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(t){this.destination.next(t)},e.prototype._error=function(t){try{this.destination.error(t)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e}(Q),on=Function.prototype.bind;function Re(n,e){return on.call(n,e)}var un=function(){function n(e){this.partialObserver=e}return n.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(r){ae(r)}},n.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(r){ae(r)}else ae(e)},n.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(t){ae(t)}},n}(),ce=function(n){N(e,n);function e(t,r,i){var s=n.call(this)||this,o;if(E(t)||!t)o={next:t??void 0,error:r??void 0,complete:i??void 0};else{var u;s&&Ze.useDeprecatedNextContext?(u=Object.create(t),u.unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&Re(t.next,u),error:t.error&&Re(t.error,u),complete:t.complete&&Re(t.complete,u)}):o=t}return s.destination=new un(o),s}return e}(xe);function ae(n){et(n)}function cn(n){throw n}var an={closed:!0,next:X,error:cn,complete:X},$e=function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"}();function D(n){return n}function z(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return tt(n)}function tt(n){return n.length===0?D:n.length===1?n[0]:function(t){return n.reduce(function(r,i){return i(r)},t)}}var $=function(){function n(e){e&&(this._subscribe=e)}return n.prototype.lift=function(e){var t=new n;return t.source=this,t.operator=e,t},n.prototype.subscribe=function(e,t,r){var i=this,s=fn(e)?e:new ce(e,t,r);return ue(function(){var o=i,u=o.operator,a=o.source;s.add(u?u.call(s,a):a?i._subscribe(s):i._trySubscribe(s))}),s},n.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},n.prototype.forEach=function(e,t){var r=this;return t=nt(t),new t(function(i,s){var o=new ce({next:function(u){try{e(u)}catch(a){s(a),o.unsubscribe()}},error:s,complete:i});r.subscribe(o)})},n.prototype._subscribe=function(e){var t;return(t=this.source)===null||t===void 0?void 0:t.subscribe(e)},n.prototype[$e]=function(){return this},n.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return tt(e)(this)},n.prototype.toPromise=function(e){var t=this;return e=nt(e),new e(function(r,i){var s;t.subscribe(function(o){return s=o},function(o){return i(o)},function(){return r(s)})})},n.create=function(e){return new n(e)},n}();function nt(n){var e;return(e=n??Ze.Promise)!==null&&e!==void 0?e:Promise}function ln(n){return n&&E(n.next)&&E(n.error)&&E(n.complete)}function fn(n){return n&&n instanceof xe||ln(n)&&Xe(n)}function hn(n){return E(n==null?void 0:n.lift)}function S(n){return function(e){if(hn(e))return e.lift(function(t){try{return n(t,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function m(n,e,t,r,i){return new rt(n,e,t,r,i)}var rt=function(n){N(e,n);function e(t,r,i,s,o,u){var a=n.call(this,t)||this;return a.onFinalize=o,a.shouldUnsubscribe=u,a._next=r?function(l){try{r(l)}catch(c){t.error(c)}}:n.prototype._next,a._error=s?function(l){try{s(l)}catch(c){t.error(c)}finally{this.unsubscribe()}}:n.prototype._error,a._complete=i?function(){try{i()}catch(l){t.error(l)}finally{this.unsubscribe()}}:n.prototype._complete,a}return e.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;n.prototype.unsubscribe.call(this),!r&&((t=this.onFinalize)===null||t===void 0||t.call(this))}},e}(xe),dn=se(function(n){return function(){n(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),g=function(n){N(e,n);function e(){var t=n.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return e.prototype.lift=function(t){var r=new it(this,this);return r.operator=t,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new dn},e.prototype.next=function(t){var r=this;ue(function(){var i,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var o=K(r.currentObservers),u=o.next();!u.done;u=o.next()){var a=u.value;a.next(t)}}catch(l){i={error:l}}finally{try{u&&!u.done&&(s=o.return)&&s.call(o)}finally{if(i)throw i.error}}}})},e.prototype.error=function(t){var r=this;ue(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=t;for(var i=r.observers;i.length;)i.shift().error(t)}})},e.prototype.complete=function(){var t=this;ue(function(){if(t._throwIfClosed(),!t.isStopped){t.isStopped=!0;for(var r=t.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var t;return((t=this.observers)===null||t===void 0?void 0:t.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),n.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var r=this,i=this,s=i.hasError,o=i.isStopped,u=i.observers;return s||o?Qe:(this.currentObservers=null,u.push(t),new Q(function(){r.currentObservers=null,oe(u,t)}))},e.prototype._checkFinalizedStatuses=function(t){var r=this,i=r.hasError,s=r.thrownError,o=r.isStopped;i?t.error(s):o&&t.complete()},e.prototype.asObservable=function(){var t=new $;return t.source=this,t},e.create=function(t,r){return new it(t,r)},e}($),it=function(n){N(e,n);function e(t,r){var i=n.call(this)||this;return i.destination=t,i.source=r,i}return e.prototype.next=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,t)},e.prototype.error=function(t){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.call(r,t)},e.prototype.complete=function(){var t,r;(r=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||r===void 0||r.call(t)},e.prototype._subscribe=function(t){var r,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(t))!==null&&i!==void 0?i:Qe},e}(g),yn=function(n){N(e,n);function e(t){var r=n.call(this)||this;return r._value=t,r}return Object.defineProperty(e.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),e.prototype._subscribe=function(t){var r=n.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},e.prototype.getValue=function(){var t=this,r=t.hasError,i=t.thrownError,s=t._value;if(r)throw i;return this._throwIfClosed(),s},e.prototype.next=function(t){n.prototype.next.call(this,this._value=t)},e}(g),st={now:function(){return(st.delegate||Date).now()},delegate:void 0},bn=function(n){N(e,n);function e(t,r){return n.call(this)||this}return e.prototype.schedule=function(t,r){return this},e}(Q),le={setInterval:function(n,e){for(var t=[],r=2;r<arguments.length;r++)t[r-2]=arguments[r];var i=le.delegate;return i!=null&&i.setInterval?i.setInterval.apply(i,U([n,e],L(t))):setInterval.apply(void 0,U([n,e],L(t)))},clearInterval:function(n){var e=le.delegate;return((e==null?void 0:e.clearInterval)||clearInterval)(n)},delegate:void 0},vn=function(n){N(e,n);function e(t,r){var i=n.call(this,t,r)||this;return i.scheduler=t,i.work=r,i.pending=!1,i}return e.prototype.schedule=function(t,r){var i;if(r===void 0&&(r=0),this.closed)return this;this.state=t;var s=this.id,o=this.scheduler;return s!=null&&(this.id=this.recycleAsyncId(o,s,r)),this.pending=!0,this.delay=r,this.id=(i=this.id)!==null&&i!==void 0?i:this.requestAsyncId(o,this.id,r),this},e.prototype.requestAsyncId=function(t,r,i){return i===void 0&&(i=0),le.setInterval(t.flush.bind(t,this),i)},e.prototype.recycleAsyncId=function(t,r,i){if(i===void 0&&(i=0),i!=null&&this.delay===i&&this.pending===!1)return r;r!=null&&le.clearInterval(r)},e.prototype.execute=function(t,r){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var i=this._execute(t,r);if(i)return i;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},e.prototype._execute=function(t,r){var i=!1,s;try{this.work(t)}catch(o){i=!0,s=o||new Error("Scheduled action threw falsy error")}if(i)return this.unsubscribe(),s},e.prototype.unsubscribe=function(){if(!this.closed){var t=this,r=t.id,i=t.scheduler,s=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,oe(s,this),r!=null&&(this.id=this.recycleAsyncId(i,r,null)),this.delay=null,n.prototype.unsubscribe.call(this)}},e}(bn),ot=function(){function n(e,t){t===void 0&&(t=n.now),this.schedulerActionCtor=e,this.now=t}return n.prototype.schedule=function(e,t,r){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},n.now=st.now,n}(),pn=function(n){N(e,n);function e(t,r){r===void 0&&(r=ot.now);var i=n.call(this,t,r)||this;return i.actions=[],i._active=!1,i}return e.prototype.flush=function(t){var r=this.actions;if(this._active){r.push(t);return}var i;this._active=!0;do if(i=t.execute(t.state,t.delay))break;while(t=r.shift());if(this._active=!1,i){for(;t=r.shift();)t.unsubscribe();throw i}},e}(ot),Ae=new pn(vn),gn=Ae,J=new $(function(n){return n.complete()});function ut(n){return n&&E(n.schedule)}function Ie(n){return n[n.length-1]}function mn(n){return E(Ie(n))?n.pop():void 0}function fe(n){return ut(Ie(n))?n.pop():void 0}function wn(n,e){return typeof Ie(n)=="number"?n.pop():e}var ct=function(n){return n&&typeof n.length=="number"&&typeof n!="function"};function at(n){return E(n==null?void 0:n.then)}function lt(n){return E(n[$e])}function ft(n){return Symbol.asyncIterator&&E(n==null?void 0:n[Symbol.asyncIterator])}function ht(n){return new TypeError("You provided "+(n!==null&&typeof n=="object"?"an invalid object":"'"+n+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function En(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var dt=En();function yt(n){return E(n==null?void 0:n[dt])}function bt(n){return rn(this,arguments,function(){var t,r,i,s;return Ye(this,function(o){switch(o.label){case 0:t=n.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,W(t.read())];case 3:return r=o.sent(),i=r.value,s=r.done,s?[4,W(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,W(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function vt(n){return E(n==null?void 0:n.getReader)}function I(n){if(n instanceof $)return n;if(n!=null){if(lt(n))return Sn(n);if(ct(n))return On(n);if(at(n))return xn(n);if(ft(n))return pt(n);if(yt(n))return Rn(n);if(vt(n))return $n(n)}throw ht(n)}function Sn(n){return new $(function(e){var t=n[$e]();if(E(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function On(n){return new $(function(e){for(var t=0;t<n.length&&!e.closed;t++)e.next(n[t]);e.complete()})}function xn(n){return new $(function(e){n.then(function(t){e.closed||(e.next(t),e.complete())},function(t){return e.error(t)}).then(null,et)})}function Rn(n){return new $(function(e){var t,r;try{for(var i=K(n),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(u){t={error:u}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}e.complete()})}function pt(n){return new $(function(e){An(n,e).catch(function(t){return e.error(t)})})}function $n(n){return pt(bt(n))}function An(n,e){var t,r,i,s;return nn(this,void 0,void 0,function(){var o,u;return Ye(this,function(a){switch(a.label){case 0:a.trys.push([0,5,6,11]),t=sn(n),a.label=1;case 1:return[4,t.next()];case 2:if(r=a.sent(),!!r.done)return[3,4];if(o=r.value,e.next(o),e.closed)return[2];a.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=a.sent(),i={error:u},[3,11];case 6:return a.trys.push([6,,9,10]),r&&!r.done&&(s=t.return)?[4,s.call(t)]:[3,8];case 7:a.sent(),a.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function P(n,e,t,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var s=e.schedule(function(){t(),i?n.add(this.schedule(null,r)):this.unsubscribe()},r);if(n.add(s),!i)return s}function gt(n,e){return e===void 0&&(e=0),S(function(t,r){t.subscribe(m(r,function(i){return P(r,n,function(){return r.next(i)},e)},function(){return P(r,n,function(){return r.complete()},e)},function(i){return P(r,n,function(){return r.error(i)},e)}))})}function mt(n,e){return e===void 0&&(e=0),S(function(t,r){r.add(n.schedule(function(){return t.subscribe(r)},e))})}function In(n,e){return I(n).pipe(mt(e),gt(e))}function Tn(n,e){return I(n).pipe(mt(e),gt(e))}function kn(n,e){return new $(function(t){var r=0;return e.schedule(function(){r===n.length?t.complete():(t.next(n[r++]),t.closed||this.schedule())})})}function Pn(n,e){return new $(function(t){var r;return P(t,e,function(){r=n[dt](),P(t,e,function(){var i,s,o;try{i=r.next(),s=i.value,o=i.done}catch(u){t.error(u);return}o?t.complete():t.next(s)},0,!0)}),function(){return E(r==null?void 0:r.return)&&r.return()}})}function wt(n,e){if(!n)throw new Error("Iterable cannot be null");return new $(function(t){P(t,e,function(){var r=n[Symbol.asyncIterator]();P(t,e,function(){r.next().then(function(i){i.done?t.complete():t.next(i.value)})},0,!0)})})}function _n(n,e){return wt(bt(n),e)}function Cn(n,e){if(n!=null){if(lt(n))return In(n,e);if(ct(n))return kn(n,e);if(at(n))return Tn(n,e);if(ft(n))return wt(n,e);if(yt(n))return Pn(n,e);if(vt(n))return _n(n,e)}throw ht(n)}function q(n,e){return e?Cn(n,e):I(n)}function he(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=fe(n);return q(n,t)}var Te=se(function(n){return function(){n(this),this.name="EmptyError",this.message="no elements in sequence"}});function Et(n,e){var t=typeof e=="object";return new Promise(function(r,i){var s=new ce({next:function(o){r(o),s.unsubscribe()},error:i,complete:function(){t?r(e.defaultValue):i(new Te)}});n.subscribe(s)})}function St(n){return n instanceof Date&&!isNaN(n)}var Ot=se(function(n){return function(t){t===void 0&&(t=null),n(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});function xt(n,e){var t=St(n)?{first:n}:typeof n=="number"?{each:n}:n,r=t.first,i=t.each,s=t.with,o=s===void 0?jn:s,u=t.scheduler,a=u===void 0?e??Ae:u,l=t.meta,c=l===void 0?null:l;if(r==null&&i==null)throw new TypeError("No timeout provided.");return S(function(f,d){var b,v,p=null,w=0,R=function(A){v=P(d,a,function(){try{b.unsubscribe(),I(o({meta:c,lastValue:p,seen:w})).subscribe(d)}catch(qe){d.error(qe)}},A)};b=f.subscribe(m(d,function(A){v==null||v.unsubscribe(),w++,d.next(p=A),i>0&&R(i)},void 0,void 0,function(){v!=null&&v.closed||v==null||v.unsubscribe(),p=null})),!w&&R(r!=null?typeof r=="number"?r:+r-a.now():i)})}function jn(n){throw new Ot(n)}function T(n,e){return S(function(t,r){var i=0;t.subscribe(m(r,function(s){r.next(n.call(e,s,i++))}))})}var Nn=Array.isArray;function Dn(n,e){return Nn(e)?n.apply(void 0,U([],L(e))):n(e)}function qn(n){return T(function(e){return Dn(n,e)})}var Ln=Array.isArray,Un=Object.getPrototypeOf,Mn=Object.prototype,Fn=Object.keys;function Vn(n){if(n.length===1){var e=n[0];if(Ln(e))return{args:e,keys:null};if(Bn(e)){var t=Fn(e);return{args:t.map(function(r){return e[r]}),keys:t}}}return{args:n,keys:null}}function Bn(n){return n&&typeof n=="object"&&Un(n)===Mn}function Kn(n,e){return n.reduce(function(t,r,i){return t[r]=e[i],t},{})}function Wn(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=fe(n),r=mn(n),i=Vn(n),s=i.args,o=i.keys;if(s.length===0)return q([],t);var u=new $(zn(s,t,o?function(a){return Kn(o,a)}:D));return r?u.pipe(qn(r)):u}function zn(n,e,t){return t===void 0&&(t=D),function(r){Rt(e,function(){for(var i=n.length,s=new Array(i),o=i,u=i,a=function(c){Rt(e,function(){var f=q(n[c],e),d=!1;f.subscribe(m(r,function(b){s[c]=b,d||(d=!0,u--),u||r.next(t(s.slice()))},function(){--o||r.complete()}))},r)},l=0;l<i;l++)a(l)},r)}}function Rt(n,e,t){n?P(t,n,e):e()}function Hn(n,e,t,r,i,s,o,u){var a=[],l=0,c=0,f=!1,d=function(){f&&!a.length&&!l&&e.complete()},b=function(p){return l<r?v(p):a.push(p)},v=function(p){s&&e.next(p),l++;var w=!1;I(t(p,c++)).subscribe(m(e,function(R){i==null||i(R),s?b(R):e.next(R)},function(){w=!0},void 0,function(){if(w)try{l--;for(var R=function(){var A=a.shift();o?P(e,o,function(){return v(A)}):v(A)};a.length&&l<r;)R();d()}catch(A){e.error(A)}}))};return n.subscribe(m(e,b,function(){f=!0,d()})),function(){u==null||u()}}function M(n,e,t){return t===void 0&&(t=1/0),E(e)?M(function(r,i){return T(function(s,o){return e(r,s,i,o)})(I(n(r,i)))},t):(typeof e=="number"&&(t=e),S(function(r,i){return Hn(r,i,n,t)}))}function de(n){return n===void 0&&(n=1/0),M(D,n)}function Gn(){return de(1)}function Yn(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];return Gn()(q(n,fe(n)))}function ke(n,e,t){n===void 0&&(n=0),t===void 0&&(t=gn);var r=-1;return e!=null&&(ut(e)?t=e:r=e),new $(function(i){var s=St(n)?+n-t.now():n;s<0&&(s=0);var o=0;return t.schedule(function(){i.closed||(i.next(o++),0<=r?this.schedule(void 0,r):i.complete())},s)})}function Qn(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];var t=fe(n),r=wn(n,1/0),i=n;return i.length?i.length===1?I(i[0]):de(r)(q(i,t)):J}function O(n,e){return S(function(t,r){var i=0;t.subscribe(m(r,function(s){return n.call(e,s,i++)&&r.next(s)}))})}function $t(n){return S(function(e,t){var r=null,i=!1,s;r=e.subscribe(m(t,void 0,void 0,function(o){s=I(n(o,$t(n)(e))),r?(r.unsubscribe(),r=null,s.subscribe(t)):i=!0})),i&&(r.unsubscribe(),r=null,s.subscribe(t))})}function Xn(n,e,t,r,i){return function(s,o){var u=t,a=e,l=0;s.subscribe(m(o,function(c){var f=l++;a=u?n(a,c,f):(u=!0,c),r&&o.next(a)},i&&function(){u&&o.next(a),o.complete()}))}}function Jn(n){return S(function(e,t){var r=!1;e.subscribe(m(t,function(i){r=!0,t.next(i)},function(){r||t.next(n),t.complete()}))})}function Pe(n){return n<=0?function(){return J}:S(function(e,t){var r=0;e.subscribe(m(t,function(i){++r<=n&&(t.next(i),n<=r&&t.complete())}))})}function Zn(){return S(function(n,e){n.subscribe(m(e,X))})}function er(n){return T(function(){return n})}function At(n,e){return e?function(t){return Yn(e.pipe(Pe(1),Zn()),t.pipe(At(n)))}:M(function(t,r){return I(n(t,r)).pipe(Pe(1),er(t))})}function tr(n,e){e===void 0&&(e=Ae);var t=ke(n,e);return At(function(){return t})}function nr(n,e){return S(function(t,r){var i=new Set;t.subscribe(m(r,function(s){var o=n?n(s):s;i.has(o)||(i.add(o),r.next(s))})),e&&I(e).subscribe(m(r,function(){return i.clear()},X))})}function It(n,e){return e===void 0&&(e=D),n=n??rr,S(function(t,r){var i,s=!0;t.subscribe(m(r,function(o){var u=e(o);(s||!n(i,u))&&(s=!1,i=u,r.next(o))}))})}function rr(n,e){return n===e}function ir(n){return n===void 0&&(n=sr),S(function(e,t){var r=!1;e.subscribe(m(t,function(i){r=!0,t.next(i)},function(){return r?t.complete():t.error(n())}))})}function sr(){return new Te}function _e(n){return S(function(e,t){try{e.subscribe(t)}finally{t.add(n)}})}function Ce(n,e){var t=arguments.length>=2;return function(r){return r.pipe(n?O(function(i,s){return n(i,s,r)}):D,Pe(1),t?Jn(e):ir(function(){return new Te}))}}function or(n,e,t,r){return S(function(i,s){var o;!e||typeof e=="function"?o=e:(t=e.duration,o=e.element,r=e.connector);var u=new Map,a=function(v){u.forEach(v),v(s)},l=function(v){return a(function(p){return p.error(v)})},c=0,f=!1,d=new rt(s,function(v){try{var p=n(v),w=u.get(p);if(!w){u.set(p,w=r?r():new g);var R=b(p,w);if(s.next(R),t){var A=m(w,function(){w.complete(),A==null||A.unsubscribe()},void 0,void 0,function(){return u.delete(p)});d.add(I(t(R)).subscribe(A))}}w.next(o?o(v):v)}catch(qe){l(qe)}},function(){return a(function(v){return v.complete()})},l,function(){return u.clear()},function(){return f=!0,c===0});i.subscribe(d);function b(v,p){var w=new $(function(R){c++;var A=p.subscribe(R);return function(){A.unsubscribe(),--c===0&&f&&d.unsubscribe()}});return w.key=v,w}})}function Tt(n,e){return S(Xn(n,e,arguments.length>=2,!0))}function ur(n,e){return S(function(t,r){var i=null,s=0,o=!1,u=function(){return o&&!i&&r.complete()};t.subscribe(m(r,function(a){i==null||i.unsubscribe();var l=0,c=s++;I(n(a,c)).subscribe(i=m(r,function(f){return r.next(e?e(a,f,c,l++):f)},function(){i=null,u()}))},function(){o=!0,u()}))})}function cr(){return ur(D)}function Z(n){return S(function(e,t){I(n).subscribe(m(t,function(){return t.complete()},X)),!t.closed&&e.subscribe(t)})}function ar(n,e){return e===void 0&&(e=!1),S(function(t,r){var i=0;t.subscribe(m(r,function(s){var o=n(s,i++);(o||e)&&r.next(s),!o&&r.complete()}))})}function ee(n,e,t){var r=E(n)||e||t?{next:n,error:e,complete:t}:n;return r?S(function(i,s){var o;(o=r.subscribe)===null||o===void 0||o.call(r);var u=!0;i.subscribe(m(s,function(a){var l;(l=r.next)===null||l===void 0||l.call(r,a),s.next(a)},function(){var a;u=!1,(a=r.complete)===null||a===void 0||a.call(r),s.complete()},function(a){var l;u=!1,(l=r.error)===null||l===void 0||l.call(r,a),s.error(a)},function(){var a,l;u&&((a=r.unsubscribe)===null||a===void 0||a.call(r)),(l=r.finalize)===null||l===void 0||l.call(r)}))}):D}function lr(n){return nr(({event:e})=>e.id,n)}function fr(n,e){const t=new Set;return[O(r=>{var s,o;const i=n(r);return i===null?!0:t.has(i)?((s=e==null?void 0:e.onHit)==null||s.call(e,r,t),!1):(t.add(i),(o=e==null?void 0:e.onCache)==null||o.call(e,r,t),!0)}),t]}function hr(n){const[e,t]=kt();return n&&q(n).subscribe(()=>{t.clear()}),e}function kt(){const n=new Map;return[z(O(e=>{var t;return!((t=n.get(e.event.id))!=null&&t.has(e.from))}),T(e=>{const t=n.get(e.event.id)??new Set,r=t.size<=0;return t.add(e.from),n.set(e.event.id,t),{...e,seenOn:t,isNew:r}})),n]}function Pt(){return z(Tt((n,e)=>V(n.event,e.event)<0?e:n),It((n,e)=>n===e,({event:n})=>n.id))}function dr(n){return z(or(n),T(z(Pt())),de())}function yr(n){return je(({event:e})=>n(e))}function br(n,e){const{not:t}=C(e,{not:!1});return O(({event:r})=>te(r.kind===n,t))}function vr(n,e){const{not:t}=C(e,{not:!1});return O(({event:r})=>te(n.includes(r.kind),t))}function pr(n,e){const{not:t}=C(e,{not:!1}),r=ve(n);return O(({event:i})=>te(me(i,r,e),t))}function gr(n){return Tt((e,t)=>{const r=[...e,t].sort((i,s)=>-1*V(i.event,s.event));return n!==void 0&&r.splice(n),r},[])}function mr(n,e){return _t(n,e??((t,r)=>V(t.event,r.event)))}function wr(n){let e;return n&&(e=Math.floor((n==null?void 0:n.getTime())/1e3)),O(({event:t})=>!we(t,e))}function Er(n){return O(e=>e.type===n)}function Sr(n,e){const{not:t}=C(e,{not:!1});return O(r=>te(r.eventId===n,t))}function Or(n){return M(e=>{const t=[];for(const r of xr(e)){if(!r[0])continue;const i=r.map(({filters:s})=>s).reduce((s,o)=>(n??$r)(s,o),[]);t.push({...r[0],filters:i})}return q(t)})}function xr(n){const e={},t=r=>r?r.join(","):"*";for(const r of n){const i=t(r.relays);e[i]??(e[i]=[]),e[i].push(r)}return Object.values(e)}function Rr(n,e){return M(t=>n(t.filters)?q(e(t.filters).map(r=>({...t,filters:r}))):he(t))}function je(n){return M((e,t)=>q(n(e,t)).pipe(M(r=>r?he(e):J)))}function Ne(n){return z(xt(n),$t(e=>{if(e instanceof Ot)return J;throw e}))}function _t(n,e){const t=[];return z(ee(r=>{t.push(r),t.sort(e)}),tr(n),T(()=>{if(t.length<=0)throw new re;return t.shift()}))}function ye(n,e){const{not:t}=C(e,{not:!1});return O(r=>te(r.subId===n,t))}function $r(n,e){return[...n,...e]}function te(n,e){return!n&&e||n&&!e}class Ar{constructor(e){h(this,"relay");h(this,"config");h(this,"authenticator");h(this,"ongoings",new Set);h(this,"authResult$",new g);h(this,"disposed",!1);this.relay=e.relay,this.config=e.config,this.authenticator=e.authenticator;const t=this.relay.getOKObservable().subscribe(i=>{const{eventId:s,ok:o}=i;this.ongoings.has(s)&&(this.ongoings.delete(s),this.authResult$.next(o),o||(t.unsubscribe(),r.unsubscribe()))}),r=this.relay.getAUTHObservable().subscribe(({challenge:i})=>{this.challenge(i)})}getAuthResultObservable(){return this.authResult$.asObservable()}async challenge(e){try{const t=await this.signer.signEvent({kind:22242,content:"",tags:[["relay",this.relay.url],["challenge",e]]});this.ongoings.add(t.id),this.relay.send(["AUTH",t])}catch{}}get signer(){return this.authenticator.signer??this.config.signer}dispose(){this[Symbol.dispose]()}[Symbol.dispose](){if(this.disposed)return;this.disposed=!0;const e=[this.authResult$];for(const t of e)t.complete()}}class Ct extends yn{constructor(e){super(e??0)}increment(){this.next(this.getValue()+1)}decrement(){this.next(this.getValue()-1)}next(e){typeof e=="number"?super.next(e):super.next(e(this.getValue()))}}class Ir extends g{waitNext(){return Et(this.pipe(Ce(null,void 0)))}}class Tr{constructor(e){h(this,"relay");h(this,"authProxy");h(this,"pubs",new Map);h(this,"authRequiredPubs",new Set);h(this,"count$",new Ct(0));h(this,"ok$",new g);h(this,"disposed",!1);var t;this.relay=e.relay,this.authProxy=e.authProxy,this.relay.getReconnectedObservable().subscribe(r=>{for(const[i,s]of r)i==="EVENT"&&this.pubs.has(s.id)&&this.sendEVENT(s)}),this.relay.getOKObservable().subscribe(async r=>{const{eventId:i,notice:s}=r;this.pubs.get(i)&&(this.authProxy&&(s!=null&&s.startsWith("auth-required:"))?(this.authRequiredPubs.add(i),this.ok$.next({...r,done:!1})):(this.ok$.next({...r,done:!0}),this.confirmOK(i)))}),(t=this.authProxy)==null||t.getAuthResultObservable().subscribe(r=>{if(r)for(const i of this.authRequiredPubs){const s=this.pubs.get(i);s&&this.sendEVENT(s)}else for(const i of this.authRequiredPubs)this.confirmOK(i);this.authRequiredPubs.clear()})}async publish(e){if(!this.disposed)return this.pubs.has(e.id)||(this.pubs.set(e.id,e),this.count$.increment()),this.sendEVENT(e)}confirmOK(e){this.disposed||this.pubs.has(e)||(this.pubs.delete(e),this.count$.decrement())}getOkAgainstEventObservable(){return this.ok$.asObservable()}getLogicalConnectionSizeObservable(){return this.count$.asObservable()}dispose(){this[Symbol.dispose]()}[Symbol.dispose](){if(this.disposed)return;this.disposed=!0;const e=[this.count$,this.ok$];for(const t of e)t.complete()}sendEVENT(e){return this.relay.send(["EVENT",e])}}const jt={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3};class kr{constructor(e,t){h(this,"socket",null);h(this,"buffer",[]);h(this,"unsent",[]);h(this,"reconnected$",new g);h(this,"outgoing$",new g);h(this,"message$",new g);h(this,"error$",new g);h(this,"retryTimer",null);h(this,"sendAttempted$",new Ir);h(this,"isFirstTry",!0);h(this,"maybeDown",!1);h(this,"disposed",!1);h(this,"state$",new g);h(this,"_state","initialized");this.url=e,this.config=t,t.skipFetchNip11||G.getOrFetch(e),this.setState("initialized")}get state(){return this._state}setState(e){this._state=e,this.state$.next(e)}connectManually(){this.connect()}connect(e){if(this.state==="terminated")return;const t=typeof e=="number";(this.state==="initialized"||this.state==="dormant"||this.state==="error"||this.state==="rejected"||t)&&(this.socket=this.createSocket(e??0))}createSocket(e){const t=this.isFirstTry;this.isFirstTry=!1;let r=!1;const i=e>0,s=this.state==="error"||this.state==="rejected";i?this.setState("retrying"):this.setState("connecting");const o=async()=>{if(this.state==="terminated"){c==null||c.close(H.RX_NOSTR_DISPOSED);return}this.setState("connected"),r=!0,(i||s)&&(this.reconnected$.next(this.unsent),this.unsent=[]);try{for(const f of this.buffer)this.send(f)}catch(f){this.error$.next(f)}finally{this.buffer=[]}},u=({data:f})=>{if(this.state!=="terminated")try{this.message$.next(this.pack(JSON.parse(f)))}catch(d){this.error$.next(d)}},a=({code:f})=>{var d;if(c==null||c.removeEventListener("open",o),c==null||c.removeEventListener("message",u),c==null||c.removeEventListener("close",a),this.socket===c&&(this.socket=null),this.state==="terminated"||f===H.RX_NOSTR_DISPOSED){this.unsent=[],this.buffer=[];return}if(f===H.RX_NOSTR_IDLE)this.setState("dormant"),this.buffer.length>0&&this.connect();else if(f===H.DONT_RETRY)this.unsent=[],this.buffer=[],this.error$.next(new _(f)),this.setState("rejected");else{t&&!r&&(this.maybeDown=!0),this.unsent.push(...this.buffer),this.buffer=[],this.error$.next(new _(f));const b=e+1;this.config.retry.strategy!=="off"&&!(this.config.retry.polite&&this.maybeDown)&&b<=this.config.retry.maxCount?(this.setState("waiting-for-retrying"),(d=this.retryTimer)==null||d.unsubscribe(),this.retryTimer=Pr(this.config.retry,b).subscribe(()=>{this.disposed||this.connect(b)})):this.setState("error")}},l=this.config.websocketCtor??globalThis.WebSocket;if(!l)throw new F("WebSocket constructor is missing");const c=(()=>{try{return new l(this.url)}catch(f){return a({type:"close",code:0,reason:`${f}`}),null}})();return c==null||c.addEventListener("open",o),c==null||c.addEventListener("message",u),c==null||c.addEventListener("close",a),c}pack(e){const t=e[0],r=this.url;switch(t){case"EVENT":return{from:r,type:t,message:e,subId:e[1],event:e[2]};case"EOSE":return{from:r,type:t,message:e,subId:e[1]};case"OK":return{from:r,type:t,message:e,eventId:e[1],ok:e[2],notice:e[3]};case"CLOSED":return{from:r,type:t,message:e,subId:e[1],notice:e[2]};case"NOTICE":return{from:r,type:t,message:e,notice:e[1]};case"AUTH":return{from:r,type:t,message:e,challenge:e[1]};case"COUNT":return{from:r,type:t,message:e,subId:e[1],count:e[2]};default:return{from:r,type:"unknown",message:e}}}disconnect(e){var t;((t=this.socket)==null?void 0:t.readyState)===jt.OPEN&&this.socket.close(e)}send(e){const t=this.sendAttempted$.waitNext();switch(this.state){case"terminated":case"rejected":return this.sendAttempted$.next(),t;case"initialized":case"connecting":case"dormant":return this.buffer.push(e),this.connect(),t;case"connected":{if(!this.socket)throw new re;return this.socket.readyState===jt.OPEN?(this.outgoing$.next({to:this.url,message:e}),this.socket.send(JSON.stringify(e)),this.sendAttempted$.next(),t):(this.buffer.push(e),t)}case"waiting-for-retrying":case"retrying":case"error":return this.sendAttempted$.next(),this.unsent.push(e),t}}getEVENTObservable(){return this.message$.pipe(O(e=>e.type==="EVENT"))}getEOSEObservable(){return this.message$.pipe(O(e=>e.type==="EOSE"))}getCLOSEDObservable(){return this.message$.pipe(O(e=>e.type==="CLOSED"))}getOKObservable(){return this.message$.pipe(O(e=>e.type==="OK"))}getAUTHObservable(){return this.message$.pipe(O(e=>e.type==="AUTH"))}getAllMessageObservable(){return this.message$.asObservable()}getOutgoingMessageObservable(){return this.outgoing$.asObservable()}getReconnectedObservable(){return this.reconnected$.asObservable()}getConnectionStateObservable(){return this.state$.pipe(It(),T(e=>({from:this.url,state:e})))}getErrorObservable(){return this.error$.asObservable()}dispose(){this[Symbol.dispose]()}[Symbol.dispose](){var t,r;if(this.disposed)return;this.disposed=!0,this.setState("terminated"),(t=this.retryTimer)==null||t.unsubscribe(),(r=this.socket)==null||r.close(H.RX_NOSTR_DISPOSED),this.socket=null;const e=[this.state$,this.outgoing$,this.message$,this.error$,this.reconnected$,this.sendAttempted$];for(const i of e)i.complete()}}function Pr(n,e){switch(n.strategy){case"exponential":{const t=Math.max(n.initialDelay*2**(e-1)+(Math.random()-.5)*1e3,1e3);return ke(t)}case"immediately":return he(0);case"linear":return ke(n.interval);case"off":return J}}const H={ABNORMAL_CLOSURE:1006,DONT_RETRY:4e3,RX_NOSTR_IDLE:4537,RX_NOSTR_DISPOSED:4538};class _r{constructor(e){h(this,"relay");h(this,"authProxy");h(this,"config");h(this,"subs",new Map