holosphere 2.0.0-alpha12 → 2.0.0-alpha13
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.
- package/dist/{2019-DQdDE6DG.js → 2019-CLMqIAfQ.js} +1722 -1668
- package/dist/{2019-DQdDE6DG.js.map → 2019-CLMqIAfQ.js.map} +1 -1
- package/dist/2019-Cp3uYhyY.cjs +8 -0
- package/dist/{2019-Ew-DTDlI.cjs.map → 2019-Cp3uYhyY.cjs.map} +1 -1
- package/dist/{browser-D2qtVhH5.cjs → browser-D6cNVl0v.cjs} +2 -2
- package/dist/{browser-D2qtVhH5.cjs.map → browser-D6cNVl0v.cjs.map} +1 -1
- package/dist/{browser-CckFyRI9.js → browser-nUQt1cnB.js} +2 -2
- package/dist/{browser-CckFyRI9.js.map → browser-nUQt1cnB.js.map} +1 -1
- package/dist/cjs/holosphere.cjs +1 -1
- package/dist/esm/holosphere.js +1 -1
- package/dist/{index-TDDyakLc.js → index-BN_uoxQK.js} +610 -128
- package/dist/index-BN_uoxQK.js.map +1 -0
- package/dist/{index-DrYM1LOY.js → index-CoAjtqsD.js} +2 -2
- package/dist/{index-DrYM1LOY.js.map → index-CoAjtqsD.js.map} +1 -1
- package/dist/{index-kyf1sjaC.cjs → index-Cp3tI53z.cjs} +2 -2
- package/dist/{index-kyf1sjaC.cjs.map → index-Cp3tI53z.cjs.map} +1 -1
- package/dist/{index-C0ITDyFo.cjs → index-DJjGSwXG.cjs} +2 -2
- package/dist/{index-C0ITDyFo.cjs.map → index-DJjGSwXG.cjs.map} +1 -1
- package/dist/index-V8EHMYEY.cjs +29 -0
- package/dist/index-V8EHMYEY.cjs.map +1 -0
- package/dist/{index-lbSQUoRz.js → index-Z5TstN1e.js} +2 -2
- package/dist/{index-lbSQUoRz.js.map → index-Z5TstN1e.js.map} +1 -1
- package/dist/indexeddb-storage-CZK5A7XH.cjs +2 -0
- package/dist/indexeddb-storage-CZK5A7XH.cjs.map +1 -0
- package/dist/{indexeddb-storage-CXhjqwhA.js → indexeddb-storage-bpA01pAU.js} +39 -2
- package/dist/indexeddb-storage-bpA01pAU.js.map +1 -0
- package/dist/{memory-storage-D1tc1bjk.cjs → memory-storage-B1k8Jszd.cjs} +2 -2
- package/dist/{memory-storage-D1tc1bjk.cjs.map → memory-storage-B1k8Jszd.cjs.map} +1 -1
- package/dist/{memory-storage-DkewsdcM.js → memory-storage-BqhmytP_.js} +2 -2
- package/dist/{memory-storage-DkewsdcM.js.map → memory-storage-BqhmytP_.js.map} +1 -1
- package/package.json +1 -1
- package/src/crypto/secp256k1.js +58 -9
- package/src/federation/card-storage.js +72 -0
- package/src/federation/handshake.js +363 -8
- package/src/federation/hologram.js +31 -3
- package/src/federation/holon-registry.js +22 -1
- package/src/federation/registry.js +54 -4
- package/src/index.js +52 -4
- package/src/storage/indexeddb-storage.js +41 -0
- package/src/storage/nostr-async.js +12 -3
- package/src/storage/nostr-client.js +112 -11
- package/src/storage/nostr-wrapper.js +5 -2
- package/dist/2019-Ew-DTDlI.cjs +0 -8
- package/dist/index-9sqetkAn.cjs +0 -29
- package/dist/index-9sqetkAn.cjs.map +0 -1
- package/dist/index-TDDyakLc.js.map +0 -1
- package/dist/indexeddb-storage-CXhjqwhA.js.map +0 -1
- package/dist/indexeddb-storage-DFESDYIj.cjs +0 -2
- package/dist/indexeddb-storage-DFESDYIj.cjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-V8EHMYEY.cjs"),t=require("nostr-tools"),n="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;
|
|
2
2
|
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
3
3
|
function r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function i(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function s(e,...t){if(!r(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function o(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");i(e.outputLen),i(e.blockLen)}function a(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function u(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function c(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function l(e,t){return e<<32-t|e>>>t}const h=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),d=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function f(e){if(s(e),h)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=d[e[n]];return t}const p=48,y=57,g=65,b=70,m=97,v=102;function w(e){return e>=p&&e<=y?e-p:e>=g&&e<=b?e-(g-10):e>=m&&e<=v?e-(m-10):void 0}function k(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(h)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const t=w(e.charCodeAt(s)),n=w(e.charCodeAt(s+1));if(void 0===t||void 0===n){const t=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+t+'" at index '+s)}r[i]=16*t+n}return r}function E(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function _(e){return"string"==typeof e&&(e=E(e)),s(e),e}function x(...e){let t=0;for(let r=0;r<e.length;r++){const n=e[r];s(n),t+=n.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const t=e[r];n.set(t,i),i+=t.length}return n}class S{}function R(e){const t=t=>e().update(_(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function P(e=32){if(n&&"function"==typeof n.getRandomValues)return n.getRandomValues(new Uint8Array(e));if(n&&"function"==typeof n.randomBytes)return Uint8Array.from(n.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function T(e,t,n){return e&t^~e&n}function A(e,t,n){return e&t^e&n^t&n}class O extends S{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=c(this.buffer)}update(e){a(this),s(e=_(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const t=c(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){a(this),function(e,t){s(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:o}=this;t[o++]=128,u(this.buffer.subarray(o)),this.padOffset>r-o&&(this.process(n,0),o=0);for(let s=o;s<r;s++)t[s]=0;!function(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),u=r?4:0,c=r?0:4;e.setUint32(t+u,o,r),e.setUint32(t+c,a,r)}(n,r-8,BigInt(8*this.length),i),this.process(n,0);const l=c(e),h=this.outputLen;if(h%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const d=h/4,f=this.get();if(d>f.length)throw new Error("_sha2: outputLen bigger than state");for(let s=0;s<d;s++)l.setUint32(4*s,f[s],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const I=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),B=Uint32Array.from([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]),N=new Uint32Array(64);class C extends O{constructor(e=32){super(64,e,8,!1),this.A=0|I[0],this.B=0|I[1],this.C=0|I[2],this.D=0|I[3],this.E=0|I[4],this.F=0|I[5],this.G=0|I[6],this.H=0|I[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let l=0;l<16;l++,t+=4)N[l]=e.getUint32(t,!1);for(let h=16;h<64;h++){const e=N[h-15],t=N[h-2],n=l(e,7)^l(e,18)^e>>>3,r=l(t,17)^l(t,19)^t>>>10;N[h]=r+N[h-7]+n+N[h-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:u,H:c}=this;for(let h=0;h<64;h++){const e=c+(l(o,6)^l(o,11)^l(o,25))+T(o,a,u)+B[h]+N[h]|0,t=(l(n,2)^l(n,13)^l(n,22))+A(n,r,i)|0;c=u,u=a,a=o,o=s+e|0,s=i,i=r,r=n,n=e+t|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,u=u+this.G|0,c=c+this.H|0,this.set(n,r,i,s,o,a,u,c)}roundClean(){u(N)}destroy(){this.set(0,0,0,0,0,0,0,0),u(this.buffer)}}const K=R(()=>new C);class D extends S{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,o(e);const n=_(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const r=this.blockLen,i=new Uint8Array(r);i.set(n.length>r?e.create().update(n).digest():n);for(let s=0;s<i.length;s++)i[s]^=54;this.iHash.update(i),this.oHash=e.create();for(let s=0;s<i.length;s++)i[s]^=106;this.oHash.update(i),u(i)}update(e){return a(this),this.iHash.update(e),this}digestInto(e){a(this),s(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:n,finished:r,destroyed:i,blockLen:s,outputLen:o}=this;return e.finished=r,e.destroyed=i,e.blockLen=s,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const U=(e,t,n)=>new D(e,t).update(n).digest();U.create=(e,t)=>new D(e,t);
|
|
4
4
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
@@ -10,4 +10,4 @@ const $e=(e,t)=>(e+(e>=0?t:-t)/Ye)/t;function Me(e){if(!["compact","recovered","
|
|
|
10
10
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
11
11
|
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
12
12
|
const it={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},st={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ot=BigInt(0),at=BigInt(1),ut=BigInt(2);const ct=_e(it.p,{sqrt:function(e){const t=it.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),u=BigInt(88),c=e*e*e%t,l=c*c*e%t,h=de(l,n,t)*l%t,d=de(h,n,t)*l%t,f=de(d,ut,t)*c%t,p=de(f,i,t)*f%t,y=de(p,s,t)*p%t,g=de(y,a,t)*y%t,b=de(g,u,t)*g%t,m=de(b,a,t)*y%t,v=de(m,n,t)*l%t,w=de(v,o,t)*p%t,k=de(w,r,t)*c%t,E=de(k,ut,t);if(!ct.eql(ct.sqr(E),e))throw new Error("Cannot find square root");return E}}),lt=function(e,t){const n=t=>rt({...e,hash:t});return{...n(t),create:n}}({...it,Fp:ct,lowS:!0,endo:st},K),ht={};function dt(e,...t){let n=ht[e];if(void 0===n){const t=K(E(e));n=x(t,t),ht[e]=n}return K(x(n,...t))}const ft=e=>e.toBytes(!0).slice(1),pt=(()=>lt.Point)(),yt=e=>e%ut===ot;function gt(e){const{Fn:t,BASE:n}=pt,r=Qe(t,e),i=n.multiply(r);return{scalar:yt(i.y)?r:t.neg(r),bytes:ft(i)}}function bt(e){const t=ct;if(!t.isValidNot0(e))throw new Error("invalid x: Fail if x ≥ p");const n=t.create(e*e),r=t.create(n*e+BigInt(7));let i=t.sqrt(r);yt(i)||(i=t.neg(i));const s=pt.fromAffine({x:e,y:i});return s.assertValidity(),s}const mt=V;function vt(...e){return pt.Fn.create(mt(dt("BIP0340/challenge",...e)))}function wt(e){return gt(e).bytes}function kt(e,t,n=P(32)){const{Fn:r}=pt,i=Y("message",e),{bytes:s,scalar:o}=gt(t),a=Y("auxRand",n,32),u=r.toBytes(o^mt(dt("BIP0340/aux",a))),c=dt("BIP0340/nonce",u,s,i),{bytes:l,scalar:h}=gt(c),d=vt(l,s,i),f=new Uint8Array(64);if(f.set(l,0),f.set(r.toBytes(r.create(h+d*o)),32),!Et(f,i,s))throw new Error("sign: Invalid signature produced");return f}function Et(e,t,n){const{Fn:r,BASE:i}=pt,s=Y("signature",e,64),o=Y("message",t),a=Y("publicKey",n,32);try{const e=bt(mt(a)),t=mt(s.subarray(0,32));if(!J(t,at,it.p))return!1;const n=mt(s.subarray(32,64));if(!J(n,at,it.n))return!1;const u=vt(r.toBytes(t),ft(e),o),c=i.multiplyUnsafe(n).add(e.multiplyUnsafe(r.neg(u))),{x:l,y:h}=c.toAffine();return!(c.is0()||!yt(h)||l!==t)}catch(u){return!1}}const _t=(()=>{const e=(e=P(48))=>Re(e,it.n);return lt.utils.randomSecretKey,{keygen:function(t){const n=e(t);return{secretKey:n,publicKey:wt(n)}},getPublicKey:wt,sign:kt,verify:Et,Point:pt,utils:{randomSecretKey:e,randomPrivateKey:e,taggedHash:dt,lift_x:bt,pointToBytes:ft,numberToBytesBE:H,bytesToNumberBE:V,mod:he},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})(),xt=K;var St=new TextDecoder("utf-8"),Rt=new TextEncoder,Pt=5e3;function Tt(t){let{prefix:n,words:r}=e.lib.bech32.decode(t,Pt),i=new Uint8Array(e.lib.bech32.fromWords(r));switch(n){case"nprofile":{let t=At(i);if(!t[0]?.[0])throw new Error("missing TLV 0 for nprofile");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");return{type:"nprofile",data:{pubkey:e.bytesToHex(t[0][0]),relays:t[1]?t[1].map(e=>St.decode(e)):[]}}}case"nevent":{let t=At(i);if(!t[0]?.[0])throw new Error("missing TLV 0 for nevent");if(32!==t[0][0].length)throw new Error("TLV 0 should be 32 bytes");if(t[2]&&32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(t[3]&&4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"nevent",data:{id:e.bytesToHex(t[0][0]),relays:t[1]?t[1].map(e=>St.decode(e)):[],author:t[2]?.[0]?e.bytesToHex(t[2][0]):void 0,kind:t[3]?.[0]?parseInt(e.bytesToHex(t[3][0]),16):void 0}}}case"naddr":{let t=At(i);if(!t[0]?.[0])throw new Error("missing TLV 0 for naddr");if(!t[2]?.[0])throw new Error("missing TLV 2 for naddr");if(32!==t[2][0].length)throw new Error("TLV 2 should be 32 bytes");if(!t[3]?.[0])throw new Error("missing TLV 3 for naddr");if(4!==t[3][0].length)throw new Error("TLV 3 should be 4 bytes");return{type:"naddr",data:{identifier:St.decode(t[0][0]),pubkey:e.bytesToHex(t[2][0]),kind:parseInt(e.bytesToHex(t[3][0]),16),relays:t[1]?t[1].map(e=>St.decode(e)):[]}}}case"nsec":return{type:n,data:i};case"npub":case"note":return{type:n,data:e.bytesToHex(i)};default:throw new Error(`unknown prefix ${n}`)}}function At(e){let t={},n=e;for(;n.length>0;){let e=n[0],r=n[1],i=n.slice(2,2+r);if(n=n.slice(2+r),i.length<r)throw new Error(`not enough data to read on TLV ${e}`);t[e]=t[e]||[],t[e].push(i)}return t}function Ot(t,n){let r=e.lib.bech32.toWords(n);return e.lib.bech32.encode(t,r,Pt)}function It(e,t){return Ot(e,t)}function Bt(t){let n=[];return Object.entries(t).reverse().forEach(([e,t])=>{t.forEach(t=>{let r=new Uint8Array(t.length+2);r.set([parseInt(e)],0),r.set([t.length],1),r.set(t,2),n.push(r)})}),e.concatBytes$1(...n)}const Nt=Object.freeze(Object.defineProperty({__proto__:null,BECH32_REGEX:/[\x21-\x7E]{1,83}1[023456789acdefghjklmnpqrstuvwxyz]{6,}/,Bech32MaxSize:Pt,NostrTypeGuard:{isNProfile:e=>/^nprofile1[a-z\d]+$/.test(e||""),isNEvent:e=>/^nevent1[a-z\d]+$/.test(e||""),isNAddr:e=>/^naddr1[a-z\d]+$/.test(e||""),isNSec:e=>/^nsec1[a-z\d]{58}$/.test(e||""),isNPub:e=>/^npub1[a-z\d]{58}$/.test(e||""),isNote:e=>/^note1[a-z\d]+$/.test(e||""),isNcryptsec:e=>/^ncryptsec1[a-z\d]+$/.test(e||"")},decode:Tt,decodeNostrURI:function(e){try{return e.startsWith("nostr:")&&(e=e.substring(6)),Tt(e)}catch(t){return{type:"invalid",data:null}}},encodeBytes:It,naddrEncode:function(t){let n=new ArrayBuffer(4);return new DataView(n).setUint32(0,t.kind,!1),Ot("naddr",Bt({0:[Rt.encode(t.identifier)],1:(t.relays||[]).map(e=>Rt.encode(e)),2:[e.hexToBytes(t.pubkey)],3:[new Uint8Array(n)]}))},neventEncode:function(t){let n;return void 0!==t.kind&&(n=function(e){const t=new Uint8Array(4);return t[0]=e>>24&255,t[1]=e>>16&255,t[2]=e>>8&255,t[3]=255&e,t}(t.kind)),Ot("nevent",Bt({0:[e.hexToBytes(t.id)],1:(t.relays||[]).map(e=>Rt.encode(e)),2:t.author?[e.hexToBytes(t.author)]:[],3:n?[new Uint8Array(n)]:[]}))},noteEncode:function(t){return It("note",e.hexToBytes(t))},nprofileEncode:function(t){return Ot("nprofile",Bt({0:[e.hexToBytes(t.pubkey)],1:(t.relays||[]).map(e=>Rt.encode(e))}))},npubEncode:function(t){return It("npub",e.hexToBytes(t))},nsecEncode:function(e){return It("nsec",e)}},Symbol.toStringTag,{value:"Module"}));var Ct=Object.defineProperty,Kt=Object.getOwnPropertyDescriptor,Dt=Object.getOwnPropertyNames,Ut=Object.prototype.hasOwnProperty;function jt(e,t,n="write"){if(!e.outboxTracker)return;const r=e.outboxTracker.data.get(t);return r?"write"===n?r.writeRelays:r.readRelays:void 0}function Ft(e,t,n,{count:r,preferredRelays:i}={}){r??=2,i??=new Set;const s=e.pool,o=s.connectedRelays();o.forEach(e=>{i?.add(e.url)});const a=new Map,{pubkeysToRelays:u,authorsMissingRelays:c}=function(e,t,n="read"){const r=new Map,i=new Set;return t.forEach(t=>{const s=jt(e,t,n);s&&s.size>0?(s.forEach(e=>{(r.get(e)||new Set).add(t)}),r.set(t,s)):i.add(t)}),{pubkeysToRelays:r,authorsMissingRelays:i}}(e,t,n),l=function(e,t){const n=new Map;return t.forEach(t=>{const r=jt(e,t);r&&r.forEach(e=>{const t=n.get(e)||0;n.set(e,t+1)})}),Array.from(n.entries()).sort((e,t)=>t[1]-e[1]).map(e=>e[0])}(e,t),h=(e,t)=>{const n=a.get(t)||[];n.push(e),a.set(t,n)};for(const[d,f]of u.entries()){let e=r;const t=new Set;for(const n of o)f.has(n.url)&&(h(d,n.url),t.add(n.url),e--);for(const n of f)t.has(n)||a.has(n)&&(h(d,n),t.add(n),e--);if(!(e<=0))for(const n of l){if(e<=0)break;t.has(n)||f.has(n)&&(h(d,n),t.add(n),e--)}}for(const d of c)s.permanentAndConnectedRelays().forEach(e=>{const t=a.get(e.url)||[];t.push(d),a.set(e.url,t)});return a}function qt(e){let t=function(e,t={}){"string"!=typeof(t={defaultProtocol:"http",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,removeExplicitPort:!1,sortQueryParameters:!0,...t}).defaultProtocol||t.defaultProtocol.endsWith(":")||(t.defaultProtocol=`${t.defaultProtocol}:`);if(e=e.trim(),/^data:/i.test(e))return Vt(e,t);if(zt(e))return e;const n=e.startsWith("//");!n&&/^\.*\//.test(e)||(e=e.replace(/^(?!(?:\w+:)?\/\/)|^\/\//,t.defaultProtocol));const r=new URL(e);if(r.hostname=r.hostname.toLowerCase(),t.forceHttp&&t.forceHttps)throw new Error("The `forceHttp` and `forceHttps` options cannot be used together");t.forceHttp&&"https:"===r.protocol&&(r.protocol="http:");t.forceHttps&&"http:"===r.protocol&&(r.protocol="https:");t.stripAuthentication&&(r.username="",r.password="");t.stripHash?r.hash="":t.stripTextFragment&&(r.hash=r.hash.replace(/#?:~:text.*?$/i,""));if(r.pathname){const e=/\b[a-z][a-z\d+\-.]{1,50}:\/\//g;let t=0,n="";for(;;){const i=e.exec(r.pathname);if(!i)break;const s=i[0],o=i.index;n+=r.pathname.slice(t,o).replace(/\/{2,}/g,"/"),n+=s,t=o+s.length}n+=r.pathname.slice(t,r.pathname.length).replace(/\/{2,}/g,"/"),r.pathname=n}if(r.pathname)try{r.pathname=decodeURI(r.pathname)}catch{}!0===t.removeDirectoryIndex&&(t.removeDirectoryIndex=[/^index\.[a-z]+$/]);if(Array.isArray(t.removeDirectoryIndex)&&t.removeDirectoryIndex.length>0){let e=r.pathname.split("/");const n=e[e.length-1];$t(n,t.removeDirectoryIndex)&&(e=e.slice(0,-1),r.pathname=`${e.slice(1).join("/")}/`)}r.hostname&&(r.hostname=r.hostname.replace(/\.$/,""),t.stripWWW&&/^www\.(?!www\.)[a-z\-\d]{1,63}\.[a-z.\-\d]{2,63}$/.test(r.hostname)&&(r.hostname=r.hostname.replace(/^www\./,"")));if(Array.isArray(t.removeQueryParameters))for(const s of[...r.searchParams.keys()])$t(s,t.removeQueryParameters)&&r.searchParams.delete(s);Array.isArray(t.keepQueryParameters)||!0!==t.removeQueryParameters||(r.search="");if(Array.isArray(t.keepQueryParameters)&&t.keepQueryParameters.length>0)for(const s of[...r.searchParams.keys()])$t(s,t.keepQueryParameters)||r.searchParams.delete(s);if(t.sortQueryParameters){r.searchParams.sort();try{r.search=decodeURIComponent(r.search)}catch{}}t.removeTrailingSlash&&(r.pathname=r.pathname.replace(/\/$/,""));t.removeExplicitPort&&r.port&&(r.port="");const i=e;e=r.toString(),t.removeSingleSlash||"/"!==r.pathname||i.endsWith("/")||""!==r.hash||(e=e.replace(/\/$/,""));(t.removeTrailingSlash||"/"===r.pathname)&&""===r.hash&&t.removeSingleSlash&&(e=e.replace(/\/$/,""));n&&!t.normalizeProtocol&&(e=e.replace(/^http:\/\//,"//"));t.stripProtocol&&(e=e.replace(/^(?:https?:)?\/\//,""));return e}(e,{stripAuthentication:!1,stripWWW:!1,stripHash:!0});return t.endsWith("/")||(t+="/"),t}var $t=(e,t)=>t.some(t=>t instanceof RegExp?t.test(e):t===e),Mt=new Set(["https:","http:","file:"]),zt=e=>{try{const{protocol:t}=new URL(e);return t.endsWith(":")&&!t.includes(".")&&!Mt.has(t)}catch{return!1}},Vt=(e,{stripHash:t})=>{const n=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(e);if(!n)throw new Error(`Invalid URL: ${e}`);const r=n.groups?.type??"",i=n.groups?.data??"";let s=n.groups?.hash??"";const o=r.split(";");s=t?"":s;let a=!1;"base64"===o[o.length-1]&&(o.pop(),a=!0);const u=o.shift()?.toLowerCase()??"",c=[...o.map(e=>{let[t,n=""]=e.split("=").map(e=>e.trim());return"charset"===t&&(n=n.toLowerCase(),"us-ascii"===n)?"":`${t}${n?`=${n}`:""}`}).filter(Boolean)];return a&&c.push("base64"),(c.length>0||u&&"text/plain"!==u)&&c.unshift(u),`data:${c.join(";")},${a?i.trim():i}${s?`#${s}`:""}`};var Lt=class{constructor(e=3e4,t){this.onSilenceDetected=t,this.timeout=e}lastActivity=Date.now();timer;timeout;isRunning=!1;recordActivity(){this.lastActivity=Date.now(),this.isRunning&&this.resetTimer()}start(){this.isRunning||(this.isRunning=!0,this.lastActivity=Date.now(),this.resetTimer())}stop(){this.isRunning=!1,this.timer&&(clearTimeout(this.timer),this.timer=void 0)}resetTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{const e=Date.now()-this.lastActivity;if(e>=this.timeout)this.onSilenceDetected();else{const t=this.timeout-e;this.timer=setTimeout(()=>{this.onSilenceDetected()},t)}},this.timeout)}};async function Ht(e){const t=`probe-${Math.random().toString(36).substring(7)}`;return new Promise(n=>{let r=!1;const i=setTimeout(()=>{r||(r=!0,e.send(["CLOSE",t]),n(!1))},5e3);e.once("message",()=>{r||(r=!0,clearTimeout(i),e.send(["CLOSE",t]),n(!0))}),e.send(["REQ",t,{kinds:[99999],limit:0}])})}var Wt=class{ndkRelay;ws;_status;timeoutMs;connectedAt;_connectionStats={attempts:0,success:0,durations:[]};debug;netDebug;connectTimeout;reconnectTimeout;ndk;openSubs=new Map;openCountRequests=new Map;openEventPublishes=new Map;serial=0;baseEoseTimeout=4400;keepalive;wsStateMonitor;sleepDetector;lastSleepCheck=Date.now();lastMessageSent=Date.now();wasIdle=!1;constructor(e,t){this.ndkRelay=e,this._status=1;const n=Math.floor(1e3*Math.random());this.debug=this.ndkRelay.debug.extend(`connectivity${n}`),this.ndk=t,this.setupMonitoring()}setupMonitoring(){this.keepalive=new Lt(3e4,async()=>{this.debug("Relay silence detected, probing connection");await Ht({send:e=>this.send(JSON.stringify(e)),once:(e,t)=>{const n=e=>{try{const r=JSON.parse(e.data);"EOSE"!==r[0]&&"EVENT"!==r[0]&&"NOTICE"!==r[0]||(t(),this.ws?.removeEventListener("message",n))}catch{}};this.ws?.addEventListener("message",n)}})||(this.debug("Probe failed, connection is stale"),this.handleStaleConnection())}),this.wsStateMonitor=setInterval(()=>{5===this._status&&(this.ws&&this.ws.readyState===WebSocket.OPEN||(this.debug("WebSocket died silently, reconnecting"),this.handleStaleConnection()))},5e3),this.sleepDetector=setInterval(()=>{const e=Date.now(),t=e-this.lastSleepCheck;t>15e3&&(this.debug(`Detected possible sleep/wake (${t}ms gap)`),this.handlePossibleWake()),this.lastSleepCheck=e},1e4)}handleStaleConnection(){this._status=1,this.wasIdle=!0,this.onDisconnect()}handlePossibleWake(){this.debug("System wake detected, checking all connections"),this.wasIdle=!0,this._status>=5&&(this.ws&&this.ws.readyState===WebSocket.OPEN?Ht({send:e=>this.send(JSON.stringify(e)),once:(e,t)=>{const n=e=>{try{const r=JSON.parse(e.data);"EOSE"!==r[0]&&"EVENT"!==r[0]&&"NOTICE"!==r[0]||(t(),this.ws?.removeEventListener("message",n))}catch{}};this.ws?.addEventListener("message",n)}}).then(e=>{e||this.handleStaleConnection()}):this.handleStaleConnection())}resetReconnectionState(){this.wasIdle=!0,this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}async connect(e,t=!0){if(this.ws&&this.ws.readyState!==WebSocket.OPEN&&this.ws.readyState!==WebSocket.CONNECTING){this.debug("Cleaning up stale WebSocket connection");try{this.ws.close()}catch(n){}this.ws=void 0,this._status=1}if(2!==this._status&&1!==this._status||this.reconnectTimeout)this.debug("Relay requested to be connected but was in state %s or it had a reconnect timeout",this._status);else{this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),e??=this.timeoutMs,!this.timeoutMs&&e&&(this.timeoutMs=e),this.timeoutMs&&(this.connectTimeout=setTimeout(()=>this.onConnectionError(t),this.timeoutMs));try{this.updateConnectionStats.attempt(),1===this._status?this._status=4:this._status=2,this.ws=new WebSocket(this.ndkRelay.url),this.ws.onopen=this.onConnect.bind(this),this.ws.onclose=this.onDisconnect.bind(this),this.ws.onmessage=this.onMessage.bind(this),this.ws.onerror=this.onError.bind(this)}catch(n){throw this.debug(`Failed to connect to ${this.ndkRelay.url}`,n),this._status=1,t?this.handleReconnection():this.ndkRelay.emit("delayed-connect",1728e5),n}}}disconnect(){this._status=0,this.keepalive?.stop(),this.wsStateMonitor&&(clearInterval(this.wsStateMonitor),this.wsStateMonitor=void 0),this.sleepDetector&&(clearInterval(this.sleepDetector),this.sleepDetector=void 0);try{this.ws?.close()}catch(e){this.debug("Failed to disconnect",e),this._status=1}}onConnectionError(e){this.debug(`Error connecting to ${this.ndkRelay.url}`,this.timeoutMs),e&&!this.reconnectTimeout&&this.handleReconnection()}onConnect(){this.netDebug?.("connected",this.ndkRelay),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0),this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=void 0),this.updateConnectionStats.connected(),this._status=5,this.keepalive?.start(),this.wasIdle=!1,this.ndkRelay.emit("connect"),this.ndkRelay.emit("ready")}onDisconnect(){this.netDebug?.("disconnected",this.ndkRelay),this.updateConnectionStats.disconnected(),this.keepalive?.stop(),5===this._status&&this.handleReconnection(),this._status=1,this.ndkRelay.emit("disconnect")}onMessage(e){this.netDebug?.(e.data,this.ndkRelay,"recv"),this.keepalive?.recordActivity();try{const t=JSON.parse(e.data),[n,r,...i]=t;switch(n){case"EVENT":{const e=this.openSubs.get(r),n=t[2];return e?void e.onevent(n):void this.debug(`Received event for unknown subscription ${r}`)}case"COUNT":{const e=t[2],n=this.openCountRequests.get(r);return void(n&&(n.resolve(e.count),this.openCountRequests.delete(r)))}case"EOSE":{const e=this.openSubs.get(r);if(!e)return;return void e.oneose(r)}case"OK":{const e=t[2],n=t[3],i=this.openEventPublishes.get(r),s=i?.pop();return i&&s?(e?s.resolve(n):s.reject(new Error(n)),void(0===i.length?this.openEventPublishes.delete(r):this.openEventPublishes.set(r,i))):void this.debug("Received OK for unknown event publish",r)}case"CLOSED":{const e=this.openSubs.get(r);if(!e)return;return void e.onclosed(t[2])}case"NOTICE":return void this.onNotice(t[1]);case"AUTH":return void this.onAuthRequested(t[1])}}catch(t){return void this.debug(`Error parsing message from ${this.ndkRelay.url}: ${t.message}`,t?.stack)}}async onAuthRequested(e){const t=this.ndkRelay.authPolicy??this.ndk?.relayAuthDefaultPolicy;if(this.debug("Relay requested authentication",{havePolicy:!!t}),7!==this._status)if(this._status=6,t){if(this._status>=5){let r;this._status=7;try{r=await t(this.ndkRelay,e)}catch(n){this.debug("Authentication policy threw an error",n),r=!1}if(this.debug("Authentication policy returned",!!r),r instanceof Bn||!0===r){r instanceof Bn&&await this.auth(r);const t=async()=>{if(this._status>=5&&this._status<8){const t=new Bn(this.ndk);t.kind=22242,t.tags=[["relay",this.ndkRelay.url],["challenge",e]],await t.sign(),this.auth(t).then(()=>{this._status=8,this.ndkRelay.emit("authed"),this.debug("Authentication successful")}).catch(e=>{this._status=6,this.ndkRelay.emit("auth:failed",e),this.debug("Authentication failed",e)})}else this.debug("Authentication failed, it changed status, status is %d",this._status)};!0===r&&(this.ndk?.signer?t().catch(e=>{console.error("Error authenticating",e)}):(this.debug("No signer available for authentication localhost"),this.ndk?.once("signer:ready",t))),this._status=5,this.ndkRelay.emit("authed")}}}else this.ndkRelay.emit("auth",e);else this.debug("Already authenticating, ignoring")}onError(e){this.debug(`WebSocket error on ${this.ndkRelay.url}:`,e)}get status(){return this._status}isAvailable(){return 5===this._status}isFlapping(){const e=this._connectionStats.durations;if(e.length%3!=0)return!1;const t=e.reduce((e,t)=>e+t,0)/e.length,n=e.map(e=>(e-t)**2).reduce((e,t)=>e+t,0)/e.length;return Math.sqrt(n)<1e3}async onNotice(e){this.ndkRelay.emit("notice",e)}handleReconnection(e=0){if(this.reconnectTimeout)return;if(this.isFlapping())return this.ndkRelay.emit("flapping",this._connectionStats),void(this._status=3);let t;if(this.wasIdle){const n=[0,1e3,2e3,5e3,1e4,3e4];t=n[Math.min(e,n.length-1)],this.debug(`Using aggressive reconnect after idle, attempt ${e}, delay ${t}ms`)}else this.connectedAt?t=Math.max(0,6e4-(Date.now()-this.connectedAt)):(t=Math.min(1e3*Math.pow(2,e),3e4),this.debug(`Using standard backoff, attempt ${e}, delay ${t}ms`));this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=void 0,this._status=2,this.connect().catch(t=>{e<5?this.handleReconnection(e+1):(this.debug("Max reconnect attempts reached"),this.wasIdle=!1)})},t),this.ndkRelay.emit("delayed-connect",t),this.debug("Reconnecting in",t),this._connectionStats.nextReconnectAt=Date.now()+t}async send(e){Date.now()-this.lastMessageSent>12e4&&(this.wasIdle=!0),this._status>=5&&this.ws?.readyState===WebSocket.OPEN?(this.ws?.send(e),this.netDebug?.(e,this.ndkRelay,"send"),this.lastMessageSent=Date.now()):(this.debug(`Not connected to ${this.ndkRelay.url} (%d), not sending message ${e}`,this._status),this._status>=5&&this.ws?.readyState!==WebSocket.OPEN&&(this.debug(`Stale connection detected, WebSocket state: ${this.ws?.readyState}`),this.handleStaleConnection()))}async auth(e){const t=new Promise((t,n)=>{const r=this.openEventPublishes.get(e.id)??[];r.push({resolve:t,reject:n}),this.openEventPublishes.set(e.id,r)});return this.send(`["AUTH",${JSON.stringify(e.rawEvent())}]`),t}async publish(e){const t=new Promise((t,n)=>{const r=this.openEventPublishes.get(e.id)??[];r.length>0&&console.warn(`Duplicate event publishing detected, you are publishing event ${e.id} twice`),r.push({resolve:t,reject:n}),this.openEventPublishes.set(e.id,r)});return this.send(`["EVENT",${JSON.stringify(e)}]`),t}async count(e,t){this.serial++;const n=t?.id||`count:${this.serial}`,r=new Promise((e,t)=>{this.openCountRequests.set(n,{resolve:e,reject:t})});return this.send(`["COUNT","${n}",${JSON.stringify(e).substring(1)}`),r}close(e,t){this.send(`["CLOSE","${e}"]`);const n=this.openSubs.get(e);this.openSubs.delete(e),n&&n.onclose(t)}req(e){this.send(`["REQ","${e.subId}",${JSON.stringify(e.executeFilters).substring(1)}`),this.openSubs.set(e.subId,e)}updateConnectionStats={connected:()=>{this._connectionStats.success++,this._connectionStats.connectedAt=Date.now()},disconnected:()=>{this._connectionStats.connectedAt&&(this._connectionStats.durations.push(Date.now()-this._connectionStats.connectedAt),this._connectionStats.durations.length>100&&this._connectionStats.durations.shift()),this._connectionStats.connectedAt=void 0},attempt:()=>{this._connectionStats.attempts++,this._connectionStats.connectedAt=Date.now()}};get connectionStats(){return this._connectionStats}get url(){return this.ndkRelay.url}get connected(){return this._status>=5&&this.ws?.readyState===WebSocket.OPEN}},Yt=class{ndkRelay;debug;constructor(e){this.ndkRelay=e,this.debug=e.debug.extend("publisher")}async publish(e,t=2500){let n;const r=()=>new Promise((t,n)=>{try{this.publishEvent(e).then(n=>{this.ndkRelay.emit("published",e),e.emit("relay:published",this.ndkRelay),t(!0)}).catch(n)}catch(r){n(r)}}),i=new Promise((e,r)=>{n=setTimeout(()=>{n=void 0,r(new Error(`Timeout: ${t}ms`))},t)}),s=()=>{r().then(e=>o(e)).catch(e=>a(e))};let o,a;const u=t=>{throw this.ndkRelay.debug("Publish failed",t,e.id),this.ndkRelay.emit("publish:failed",e,t),e.emit("relay:publish:failed",this.ndkRelay,t),t},c=()=>{n&&clearTimeout(n),this.ndkRelay.removeListener("connect",s)};return this.ndkRelay.status>=5?Promise.race([r(),i]).catch(u).finally(c):(this.ndkRelay.status<=1?(console.warn("Relay is disconnected, trying to connect to publish an event",this.ndkRelay.url),this.ndkRelay.connect()):console.warn("Relay not connected, waiting for connection to publish an event",this.ndkRelay.url),Promise.race([new Promise((e,t)=>{o=e,a=t,this.ndkRelay.on("connect",s)}),i]).catch(u).finally(c))}async publishEvent(e){return this.ndkRelay.connectivity.publish(e.rawEvent())}};function Zt(e){const t=[],n={};return e.filter(e=>!!e.limit).forEach(e=>t.push(e)),0===(e=e.filter(e=>!e.limit)).length?t:(e.forEach(e=>{Object.entries(e).forEach(([e,t])=>{Array.isArray(t)?void 0===n[e]?n[e]=[...t]:n[e]=Array.from(new Set([...n[e],...t])):n[e]=t})}),[...t,n])}var Jt=class{fingerprint;items=new Map;topSubManager;debug;status=0;onClose;relay;eosed=!1;executionTimer;fireTime;delayType;executeFilters;id=Math.random().toString(36).substring(7);constructor(e,t,n){this.relay=e,this.topSubManager=n,this.debug=e.debug.extend(`sub[${this.id}]`),this.fingerprint=t||Math.random().toString(36).substring(7)}_subId;get subId(){return this._subId||(this._subId=this.fingerprint.slice(0,15)),this._subId}subIdParts=new Set;addSubIdPart(e){this.subIdParts.add(e)}addItem(e,t){if(this.debug("Adding item",{filters:t,internalId:e.internalId,status:this.status,fingerprint:this.fingerprint,id:this.subId,items:this.items,itemsSize:this.items.size}),!this.items.has(e.internalId))switch(e.on("close",this.removeItem.bind(this,e)),this.items.set(e.internalId,{subscription:e,filters:t}),3!==this.status&&e.subId&&(!this._subId||this._subId.length<48)&&(0!==this.status&&1!==this.status||this.addSubIdPart(e.subId)),this.status){case 0:case 1:this.evaluateExecutionPlan(e);break;case 3:break;case 4:throw this.debug("Subscription is closed, cannot add new items %o (%o)",e,t),new Error("Cannot add new items to a closed subscription")}}removeItem(e){if(this.items.delete(e.internalId),0===this.items.size){if(!this.eosed)return;this.close(),this.cleanup()}}close(){if(4===this.status)return;const e=this.status;if(this.status=4,3===e)try{this.relay.close(this.subId)}catch(t){this.debug("Error closing subscription",t,this)}else this.debug("Subscription wanted to close but it wasn't running, this is probably ok",{subId:this.subId,prevStatus:e,sub:this});this.cleanup()}cleanup(){this.executionTimer&&clearTimeout(this.executionTimer),this.relay.off("ready",this.executeOnRelayReady),this.relay.off("authed",this.reExecuteAfterAuth),this.onClose&&this.onClose(this)}evaluateExecutionPlan(e){if(!e.isGroupable())return this.status=1,void this.execute();if(e.filters.find(e=>!!e.limit)&&(this.executeFilters=this.compileFilters(),this.executeFilters.length>=10))return this.status=1,void this.execute();const t=e.groupableDelay,n=e.groupableDelayType;if(!t)throw new Error("Cannot group a subscription without a delay");if(0===this.status)this.schedule(t,n);else{const e=this.delayType,r=this.fireTime-Date.now();if("at-least"===e&&"at-least"===n)r<t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else if("at-least"===e&&"at-most"===n)r>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else if("at-most"===e&&"at-most"===n)r>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n));else{if("at-most"!==e||"at-least"!==n)throw new Error(`Unknown delay type combination ${e} ${n}`);r>t&&(this.executionTimer&&clearTimeout(this.executionTimer),this.schedule(t,n))}}}schedule(e,t){this.status=1;const n=Date.now();this.fireTime=n+e,this.delayType=t;const r=setTimeout(this.execute.bind(this),e);"at-least"===t&&(this.executionTimer=r)}executeOnRelayReady=()=>{if(2===this.status){if(0===this.items.size)return this.debug("No items to execute; this relay was probably too slow to respond and the caller gave up",{status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size,id:this.id,subId:this.subId}),void this.cleanup();this.debug("Executing on relay ready",{status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.status=1,this.execute()}};finalizeSubId(){this.subIdParts.size>0?this._subId=Array.from(this.subIdParts).join("-"):this._subId=this.fingerprint.slice(0,15),this._subId+=`-${Math.random().toString(36).substring(2,7)}`}reExecuteAfterAuth=(()=>{const e=this.subId;this.debug("Re-executing after auth",this.items.size),this.eosed?this.relay.close(this.subId):this.debug("We are abandoning an opened subscription, once it EOSE's, the handler will close it",{oldSubId:e}),this._subId=void 0,this.status=1,this.execute(),this.debug("Re-executed after auth %s 👉 %s",e,this.subId)}).bind(this);execute(){if(1===this.status){if(!this.relay.connected)return this.status=2,this.debug("Waiting for relay to be ready",{status:this.status,id:this.subId,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),void this.relay.once("ready",this.executeOnRelayReady);this.relay.status<8&&this.relay.once("authed",this.reExecuteAfterAuth),this.status=3,this.finalizeSubId(),this.executeFilters=this.compileFilters(),this.relay.req(this)}}onstart(){}onevent(e){this.topSubManager.dispatchEvent(e,this.relay)}oneose(e){if(this.eosed=!0,e!==this.subId)return this.debug("Received EOSE for an abandoned subscription",e,this.subId),void this.relay.close(e);0===this.items.size&&this.close();for(const{subscription:t}of this.items.values())t.eoseReceived(this.relay),t.closeOnEose&&(this.debug("Removing item because of EOSE",{filters:t.filters,internalId:t.internalId,status:this.status,fingerprint:this.fingerprint,items:this.items,itemsSize:this.items.size}),this.removeItem(t))}onclose(e){this.status=4}onclosed(e){if(e)for(const{subscription:t}of this.items.values())t.closedReceived(this.relay,e)}compileFilters(){const e=[],t=Array.from(this.items.values()).map(e=>e.filters);if(!t[0])return this.debug("👀 No filters to merge",this.items),console.error("BUG: No filters to merge!",this.items),[];const n=t[0].length;for(let r=0;r<n;r++){const n=t.map(e=>e[r]);e.push(...Zt(n))}return e}},Qt=class{relay;subscriptions;generalSubManager;constructor(e,t){this.relay=e,this.subscriptions=new Map,this.generalSubManager=t}addSubscription(e,t){let n;if(e.isGroupable()){const r=function(e,t){const n=[];for(const i of e){const e=Object.entries(i||{}).map(([e,t])=>["since","until"].includes(e)?`${e}:${t}`:e).sort().join("-");n.push(e)}let r=t?"+":"";return r+=n.join("|"),r}(t,e.closeOnEose);if(r){n=(this.subscriptions.get(r)||[]).find(e=>e.status<3)}n??=this.createSubscription(e,t,r)}else n=this.createSubscription(e,t);n.addItem(e,t)}createSubscription(e,t,n){const r=new Jt(this.relay,n||null,this.generalSubManager);r.onClose=this.onRelaySubscriptionClose.bind(this);const i=this.subscriptions.get(r.fingerprint)??[];return this.subscriptions.set(r.fingerprint,[...i,r]),r}onRelaySubscriptionClose(e){let t=this.subscriptions.get(e.fingerprint)??[];t?1===t.length?this.subscriptions.delete(e.fingerprint):(t=t.filter(t=>t.id!==e.id),this.subscriptions.set(e.fingerprint,t)):console.warn("Unexpectedly did not find a subscription with fingerprint",e.fingerprint)}},Gt=class t extends e.lib$1.EventEmitter{url;scores;connectivity;subs;publisher;authPolicy;lowestValidationRatio;targetValidationRatio;validationRatioFn;validatedEventCount=0;nonValidatedEventCount=0;trusted=!1;complaining=!1;debug;static defaultValidationRatioUpdateFn=(e,t,n)=>{if(void 0===e.lowestValidationRatio||void 0===e.targetValidationRatio)return 1;let r=e.validationRatio;if(e.validationRatio>e.targetValidationRatio){const n=t/100;r=Math.max(e.lowestValidationRatio,e.validationRatio-n)}return r<e.validationRatio?r:e.validationRatio};constructor(n,r,i){super(),this.url=qt(n),this.scores=new Map,this.debug=e.createDebug2(`ndk:relay:${n}`),this.connectivity=new Wt(this,i),this.connectivity.netDebug=i?.netDebug,this.req=this.connectivity.req.bind(this.connectivity),this.close=this.connectivity.close.bind(this.connectivity),this.subs=new Qt(this,i.subManager),this.publisher=new Yt(this),this.authPolicy=r,this.targetValidationRatio=i?.initialValidationRatio,this.lowestValidationRatio=i?.lowestValidationRatio,this.validationRatioFn=(i?.validationRatioFn??t.defaultValidationRatioUpdateFn).bind(this),this.updateValidationRatio(),i||console.trace("relay created without ndk")}updateValidationRatio(){if(this.validationRatioFn&&this.validatedEventCount>0){const e=this.validationRatioFn(this,this.validatedEventCount,this.nonValidatedEventCount);this.targetValidationRatio=e}setTimeout(()=>{this.updateValidationRatio()},3e4)}get status(){return this.connectivity.status}get connectionStats(){return this.connectivity.connectionStats}async connect(e,t=!0){return this.connectivity.connect(e,t)}disconnect(){1!==this.status&&this.connectivity.disconnect()}subscribe(e,t){this.subs.addSubscription(e,t)}async publish(e,t=2500){return this.publisher.publish(e,t)}referenceTags(){return[["r",this.url]]}addValidatedEvent(){this.validatedEventCount++}addNonValidatedEvent(){this.nonValidatedEventCount++}get validationRatio(){return 0===this.nonValidatedEventCount?1:this.validatedEventCount/(this.validatedEventCount+this.nonValidatedEventCount)}shouldValidateEvent(){return!this.trusted&&(void 0===this.targetValidationRatio||(this.targetValidationRatio>=1||Math.random()<this.targetValidationRatio))}get connected(){return this.connectivity.connected}req;close},Xt=class extends Error{errors;publishedToRelays;intendedRelaySet;constructor(e,t,n,r){super(e),this.errors=t,this.publishedToRelays=n,this.intendedRelaySet=r}get relayErrors(){const e=[];for(const[t,n]of this.errors)e.push(`${t.url}: ${n}`);return e.join("\n")}},en=class e{relays;debug;ndk;pool;constructor(e,t,n){this.relays=e,this.ndk=t,this.pool=n??t.pool,this.debug=t.debug.extend("relayset")}addRelay(e){this.relays.add(e)}get relayUrls(){return Array.from(this.relays).map(e=>e.url)}static fromRelayUrls(t,n,r=!0,i){if(!(i=i??n.pool))throw new Error("No pool provided");const s=new Set;for(const e of t){const o=i.relays.get(qt(e));if(o)o.status<5&&r&&o.connect(),s.add(o);else{const r=new Gt(qt(e),n?.relayAuthDefaultPolicy,n);i.useTemporaryRelay(r,void 0,`requested from fromRelayUrls ${t}`),s.add(r)}}return new e(new Set(s),n,i)}async publish(e,t,n=1){const r=new Set,i=new Map,s=e.isEphemeral();e.publishStatus="pending";const o=e=>{r.add(e)};e.on("relay:published",o);try{const o=Array.from(this.relays).map(n=>new Promise(o=>{const a=t?setTimeout(()=>{r.has(n)||(i.set(n,new Error(`Publish timeout after ${t}ms`)),o(!1))},t):null;n.publish(e,t).then(e=>{a&&clearTimeout(a),e?(r.add(n),o(!0)):o(!1)}).catch(e=>{a&&clearTimeout(a),s||i.set(n,e),o(!1)})}));if(await Promise.all(o),r.size<n){if(!s){const t=new Xt("Not enough relays received the event ("+r.size+" published, "+n+" required)",i,r,this);throw e.publishStatus="error",e.publishError=t,this.ndk?.emit("event:publish-failed",e,t,this.relayUrls),t}}else e.publishStatus="success",e.emit("published",{relaySet:this,publishedToRelays:r});return r}finally{e.off("relay:published",o)}}get size(){return this.relays.size}},tn=e.createDebug2("ndk:outbox:calculate");async function nn(e,t,n){const r=new Set,i=await async function(e,t,n="write"){if(e.outboxTracker)return e.outboxTracker.data.has(t)||await e.outboxTracker.trackUsers([t]),jt(e,t,n)}(e,t.pubkey);i&&i.forEach(t=>{const n=e.pool?.getRelay(t);n&&r.add(n)});let s=t.tags.filter(e=>["a","e"].includes(e[0])).map(e=>e[2]).filter(e=>e?.startsWith("wss://")).filter(e=>{try{return new URL(e),!0}catch{return!1}}).map(e=>qt(e));s=Array.from(new Set(s)).slice(0,5),s.forEach(t=>{const n=e.pool?.getRelay(t,!0,!0);n&&(tn("Adding relay hint %s",t),r.add(n))});const o=t.getMatchingTags("p").map(e=>e[1]);if(o.length<5){Array.from(Ft(e,o,"read",{preferredRelays:new Set(i)}).keys()).forEach(t=>{const n=e.pool?.getRelay(t,!1,!0);n&&(tn("Adding p-tagged relay %s",t),r.add(n))})}else tn("Too many p-tags to consider %d",o.length);if(e.pool?.permanentAndConnectedRelays().forEach(e=>r.add(e)),n&&r.size<n){const t=e.explicitRelayUrls?.filter(e=>!Array.from(r).some(t=>t.url===e)).slice(0,n-r.size);t?.forEach(t=>{const n=e.pool?.getRelay(t,!1,!0);n&&(tn("Adding explicit relay %s",t),r.add(n))})}return new en(r,e)}function rn(e,t){const n=new Map,r=(e,t)=>e.every((e,n)=>e===t[n]);return e.concat(t).forEach(e=>{for(const[t,i]of n)if(r(i,e)||r(e,i))return void(e.length>=i.length&&n.set(t,e));n.set((e=>e.join(","))(e),e)}),Array.from(n.values())}var sn=/(?<=\s|^)(#[^\s!@#$%^&*()=+./,[{\]};:'"?><]+)/g;async function on(e,n=[],r,i){if(r?.skipContentTagging)return{content:e,tags:n};const s=[],o=e=>{n.find(t=>["q",e[0]].includes(t[0])&&t[1]===e[1])||n.push(e)};if(e=e.replace(/(@|nostr:)(npub|nprofile|note|nevent|naddr)[a-zA-Z0-9]+/g,e=>{try{const n=e.split(/(@|nostr:)/)[2],{type:i,data:a}=t.nip19.decode(n);let u;if(r?.filters){const t=!r.filters.includeTypes||r.filters.includeTypes.includes(i),n=r.filters.excludeTypes?.includes(i);if(!t||n)return e}switch(i){case"npub":!1!==r?.pTags&&(u=["p",a]);break;case"nprofile":!1!==r?.pTags&&(u=["p",a.pubkey]);break;case"note":s.push(new Promise(async e=>{const t=await an(n);o(["q",a,t]),e()}));break;case"nevent":s.push(new Promise(async e=>{const{id:t,author:i}=a;let{relays:s}=a;s&&0!==s.length||(s=[await an(n)]),o(["q",t,s[0]]),i&&!1!==r?.pTags&&!1!==r?.pTagOnQTags&&o(["p",i]),e()}));break;case"naddr":s.push(new Promise(async e=>{const t=[a.kind,a.pubkey,a.identifier].join(":");let i=a.relays??[];0===i.length&&(i=[await an(n)]),o(["q",t,i[0]]),!1!==r?.pTags&&!1!==r?.pTagOnQTags&&!1!==r?.pTagOnATags&&o(["p",a.pubkey]),e()}));break;default:return e}return u&&o(u),`nostr:${n}`}catch(n){return e}}),await Promise.all(s),!r?.filters?.excludeTypes?.includes("hashtag")){const t=function(e){const t=e.match(sn),n=new Set,r=new Set;if(t)for(const i of t)n.has(i.slice(1))||(r.add(i.slice(1)),n.add(i.slice(1)));return Array.from(r)}(e).map(e=>["t",e]);n=rn(n,t)}if(!1!==r?.pTags&&r?.copyPTagsFromTarget&&i){const e=i.getMatchingTags("p");for(const t of e)n.find(e=>"p"===e[0]&&e[1]===t[1])||n.push(t)}return{content:e,tags:n}}async function an(e){return""}async function un(e,t,n="nip44"){let r;if(!this.ndk)throw new Error("No NDK instance found!");let i=t;if(i||(this.ndk.assertSigner(),i=this.ndk.signer),!i)throw new Error("no NDK signer");const s=e||(()=>{const e=this.getMatchingTags("p");if(1!==e.length)throw new Error("No recipient could be determined and no explicit recipient was provided");return this.ndk.getUser({pubkey:e[0][1]})})();if("nip44"===n&&await ln(i,"nip44")&&(r=await i.encrypt(s,this.content,"nip44")),r&&"nip04"!==n||!(await ln(i,"nip04"))||(r=await i.encrypt(s,this.content,"nip04")),!r)throw new Error("Failed to encrypt event.");this.content=r}async function cn(e,t,n){if(this.ndk?.cacheAdapter?.getDecryptedEvent){let e=null;if("function"==typeof this.ndk.cacheAdapter.getDecryptedEvent&&(e=this.ndk.cacheAdapter.getDecryptedEvent(this.id)),e)return void(this.content=e.content)}let r;if(!this.ndk)throw new Error("No NDK instance found!");let i=t;if(i||(this.ndk.assertSigner(),i=this.ndk.signer),!i)throw new Error("no NDK signer");const s=e||this.author;if(!s)throw new Error("No sender provided and no author available");const o=n||(this.content.match(/\\?iv=/)?"nip04":"nip44");if(("nip04"===o||4===this.kind)&&await ln(i,"nip04")&&this.content.search("\\?iv=")&&(r=await i.decrypt(s,this.content,"nip04")),!r&&"nip44"===o&&await ln(i,"nip44")&&(r=await i.decrypt(s,this.content,"nip44")),!r)throw new Error("Failed to decrypt event.");this.content=r,this.ndk?.cacheAdapter?.addDecryptedEvent&&this.ndk.cacheAdapter.addDecryptedEvent(this)}async function ln(e,t){return!!e.encryptionEnabled&&(!t||Boolean(await e.encryptionEnabled(t)))}var hn=new Set(["A","E","I"]),dn=new Set(["a","e","i"]);function fn(e){return"E"===e[0]||"root"===e[3]}async function pn(e,t){if(!this.ndk)throw new Error("NDK instance not found");const n=this.getMatchingTags(e,t);if(0===n.length)return;const[r,i,s]=n[0];let o=""!==s?this.ndk.pool.getRelay(s):void 0;return await this.ndk.fetchEvent(i,{},o)}async function yn(e){if(!this.ndk)throw new Error("NDK instance not found");const t=function(e,t){t??=e.tagType();const n=e.tags.find(fn);if(!n){if(function(e){for(const t of e.tags)if("e"===t[0]&&(t[3]??"").length>0)return!0;return!1}(e))return;const n=e.getMatchingTags(t);if(n.length<3)return n[0]}return n}(this);if(t)return this.ndk.fetchEventFromTag(t,this,e)}async function gn(e){if(!this.ndk)throw new Error("NDK instance not found");const t=function(e,t){if(1111===e.kind){let t;for(const n of e.tags)if(hn.has(n[0]))t=n;else if(dn.has(n[0])){t=n;break}return t}t??=e.tagType();let n,r=!1;for(const i of e.tags)if(i[0]===t){if((i[3]??"").length>0&&(r=!0),r&&"reply"===i[3])return i;r&&"root"===i[3]&&(n=i),r||(n=i)}return n}(this);if(t)return this.ndk.fetchEventFromTag(t,this,e)}function bn(){if(void 0===this.kind)throw new Error("Kind not set");return[0,3].includes(this.kind)||this.kind>=1e4&&this.kind<2e4||this.kind>=3e4&&this.kind<4e4}function mn(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=2e4&&this.kind<3e4}function vn(){if(void 0===this.kind)throw new Error("Kind not set");return this.kind>=3e4&&this.kind<4e4}function wn(e=2){let n=[];return this.onRelays.length>0?n=this.onRelays.map(e=>e.url):this.relay&&(n=[this.relay.url]),n.length>e&&(n=n.slice(0,e)),this.isParamReplaceable()?t.nip19.naddrEncode({kind:this.kind,pubkey:this.pubkey,identifier:this.replaceableDTag(),relays:n}):n.length>0?t.nip19.neventEncode({id:this.tagId(),relays:n,author:this.pubkey}):t.nip19.noteEncode(this.tagId())}async function kn(e=!0,t){if(!t&&e){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t=this.ndk.signer}const n=new Bn(this.ndk,{kind:En(this)});return this.isProtected||(n.content=JSON.stringify(this.rawEvent())),n.tag(this),1!==this.kind&&n.tags.push(["k",`${this.kind}`]),t&&await n.sign(t),e&&await n.publish(),n}function En(e){return 1===e.kind?6:16}function _n(e=!1,t=!1){const n=[0,this.pubkey,this.created_at,this.kind,this.tags,this.content];return e&&n.push(this.sig),t&&n.push(this.id),JSON.stringify(n)}function xn(e){const t=JSON.parse(e),n={pubkey:t[1],created_at:t[2],kind:t[3],tags:t[4],content:t[5]};if(t.length>=7){const e=t[6],r=t[7];e&&128===e.length?(n.sig=e,r&&64===r.length&&(n.id=r)):e&&64===e.length&&(n.id=e,r&&128===r.length&&(n.sig=r))}return n}var Sn={};var Rn=/^[a-f0-9]{64}$/;function Pn(){if("number"!=typeof this.kind)return!1;if("string"!=typeof this.content)return!1;if("number"!=typeof this.created_at)return!1;if("string"!=typeof this.pubkey)return!1;if(!this.pubkey.match(Rn))return!1;if(!Array.isArray(this.tags))return!1;for(let e=0;e<this.tags.length;e++){const t=this.tags[e];if(!Array.isArray(t))return!1;for(let e=0;e<t.length;e++)if("object"==typeof t[e])return!1}return!0}var Tn=new e.dist.LRUCache({maxSize:1e3,entryExpirationTimeInMS:6e4});function An(e){if("boolean"==typeof this.signatureVerified)return this.signatureVerified;const t=Tn.get(this.id);if(null!==t)return this.signatureVerified=!!t,this.signatureVerified;try{if(!this.ndk?.asyncSigVerification){const e=xt((new TextEncoder).encode(this.serialize())),t=_t.verify(this.sig,e,this.pubkey);return t?Tn.set(this.id,this.sig):Tn.set(this.id,!1),this.signatureVerified=t,t}(async function(e,t,n){const r=e.ndk,i=Date.now();let s;return r.signatureVerificationFunction?(console.log("[NDK-CORE] Using custom signature verification function async"),s=await r.signatureVerificationFunction(e),console.log("Custom signature verification result",e.id,{result:s})):(console.log("Using worker-based signature verification async"),s=await new Promise(t=>{e.serialize();let r=!1;Sn[e.id]||(Sn[e.id]={event:e,resolves:[],relay:n},r=!0),Sn[e.id].resolves.push(t)})),r.signatureVerificationTimeMs+=Date.now()-i,s})(this,0,this.relay).then(t=>{e&&(this.signatureVerified=t,t&&Tn.set(this.id,this.sig)),t||(this.relay?this.ndk?.reportInvalidSignature(this,this.relay):this.ndk?.reportInvalidSignature(this),Tn.set(this.id,!1))}).catch(e=>{console.error("signature verification error",this.id,e)})}catch(n){return this.signatureVerified=!1,!1}}function On(){return e=this.serialize(),f(xt((new TextEncoder).encode(e)));var e}var In=new Set([0,4,1059,13,3,9734,5]),Bn=class t extends e.lib$1.EventEmitter{ndk;created_at;content="";tags=[];kind;id="";sig;pubkey="";signatureVerified;_author=void 0;relay;get onRelays(){let e=[];return this.ndk?e=this.ndk.subManager.seenEvents.get(this.id)||[]:this.relay&&e.push(this.relay),e}publishStatus="success";publishError;constructor(e,n){super(),this.ndk=e,this.created_at=n?.created_at,this.content=n?.content||"",this.tags=n?.tags||[],this.id=n?.id||"",this.sig=n?.sig,this.pubkey=n?.pubkey||"",this.kind=n?.kind,n instanceof t&&(this.relay&&(this.relay=n.relay,this.ndk?.subManager.seenEvent(n.id,this.relay)),this.publishStatus=n.publishStatus,this.publishError=n.publishError)}static deserialize(e,n){return new t(e,xn(n))}rawEvent(){return{created_at:this.created_at,content:this.content,tags:this.tags,kind:this.kind,pubkey:this.pubkey,id:this.id,sig:this.sig}}set author(e){this.pubkey=e.pubkey,this._author=e,this._author.ndk??=this.ndk}get author(){if(this._author)return this._author;if(!this.ndk)throw new Error("No NDK instance found");const e=this.ndk.getUser({pubkey:this.pubkey});return this._author=e,e}tagExternal(e,t,n){const r=["i"],i=["k"];switch(t){case"url":{const t=new URL(e);t.hash="",r.push(t.toString()),i.push(`${t.protocol}//${t.host}`);break}case"hashtag":r.push(`#${e.toLowerCase()}`),i.push("#");break;case"geohash":r.push(`geo:${e.toLowerCase()}`),i.push("geo");break;case"isbn":r.push(`isbn:${e.replace(/-/g,"")}`),i.push("isbn");break;case"podcast:guid":r.push(`podcast:guid:${e}`),i.push("podcast:guid");break;case"podcast:item:guid":r.push(`podcast:item:guid:${e}`),i.push("podcast:item:guid");break;case"podcast:publisher:guid":r.push(`podcast:publisher:guid:${e}`),i.push("podcast:publisher:guid");break;case"isan":r.push(`isan:${e.split("-").slice(0,4).join("-")}`),i.push("isan");break;case"doi":r.push(`doi:${e.toLowerCase()}`),i.push("doi");break;default:throw new Error(`Unsupported NIP-73 entity type: ${t}`)}n&&r.push(n),this.tags.push(r),this.tags.push(i)}tag(e,n,r,i,s){let o=[];if(void 0!==e.fetchProfile){if(i??="p","p"===i&&!1===s?.pTags)return;const t=[i,e.pubkey];n&&t.push("",n),o.push(t)}else if(e instanceof t){const t=e;if(r??=t?.pubkey===this.pubkey,o=t.referenceTags(n,r,i,s),!1!==s?.pTags)for(const e of t.getMatchingTags("p"))e[1]!==this.pubkey&&(this.tags.find(t=>"p"===t[0]&&t[1]===e[1])||this.tags.push(["p",e[1]]))}else{if(!Array.isArray(e))throw new Error("Invalid argument",e);o=[e]}this.tags=rn(this.tags,o)}async toNostrEvent(e,t){if(!e&&""===this.pubkey){const e=await(this.ndk?.signer?.user());this.pubkey=e?.pubkey||""}this.created_at||(this.created_at=Math.floor(Date.now()/1e3));const{content:n,tags:r}=await this.generateTags(t);this.content=n||"",this.tags=r;try{this.id=this.getEventHash()}catch(i){}return this.rawEvent()}serialize=_n.bind(this);getEventHash=On.bind(this);validate=Pn.bind(this);verifySignature=An.bind(this);isReplaceable=bn.bind(this);isEphemeral=mn.bind(this);isDvm=()=>this.kind&&this.kind>=5e3&&this.kind<=7e3;isParamReplaceable=vn.bind(this);encode=wn.bind(this);encrypt=un.bind(this);decrypt=cn.bind(this);getMatchingTags(e,t){const n=this.tags.filter(t=>t[0]===e);return void 0===t?n:n.filter(e=>e[3]===t)}hasTag(e,t){return this.tags.some(n=>n[0]===e&&(!t||n[3]===t))}tagValue(e,t){const n=this.getMatchingTags(e,t);if(0!==n.length)return n[0][1]}get alt(){return this.tagValue("alt")}set alt(e){this.removeTag("alt"),e&&this.tags.push(["alt",e])}get dTag(){return this.tagValue("d")}set dTag(e){this.removeTag("d"),e&&this.tags.push(["d",e])}removeTag(e,t){const n=Array.isArray(e)?e:[e];this.tags=this.tags.filter(e=>{const r=n.includes(e[0]),i=!t||e[3]===t;return!(r&&i)})}replaceTag(e){this.removeTag(e[0]),this.tags.push(e)}async sign(e,t){e?this.author=await e.user():(this.ndk?.assertSigner(),e=this.ndk?.signer);const n=await this.toNostrEvent(void 0,t);return this.sig=await e.sign(n),this.sig}async publishReplaceable(e,t,n){return this.id="",this.created_at=Math.floor(Date.now()/1e3),this.sig="",this.publish(e,t,n)}async publish(e,t,n,r){if(n||(n=1),this.sig||await this.sign(void 0,r),!this.ndk)throw new Error("NDKEvent must be associated with an NDK instance to publish");if(e&&0!==e.size||(e=this.ndk.devWriteRelaySet||await nn(this.ndk,this,n)),5===this.kind&&this.ndk.cacheAdapter?.deleteEventIds){const e=this.getMatchingTags("e").map(e=>e[1]);this.ndk.cacheAdapter.deleteEventIds(e)}const i=this.rawEvent();if(this.ndk.cacheAdapter?.addUnpublishedEvent&&(s=this,!Nn.has(s.kind)))try{this.ndk.cacheAdapter.addUnpublishedEvent(this,e.relayUrls)}catch(a){console.error("Error adding unpublished event to cache",a)}var s;5===this.kind&&this.ndk.cacheAdapter?.deleteEventIds&&this.ndk.cacheAdapter.deleteEventIds(this.getMatchingTags("e").map(e=>e[1])),this.ndk.subManager.dispatchEvent(i,void 0,!0);const o=await e.publish(this,t,n);return o.forEach(e=>this.ndk?.subManager.seenEvent(this.id,e)),o}async generateTags(e){let t=[];const n=await on(this.content,this.tags,e,this),r=n.content;if(t=n.tags,this.kind&&this.isParamReplaceable()){if(!this.getMatchingTags("d")[0]){const e=this.tagValue("title");let n=[...Array(e?6:16)].map(()=>Math.random().toString(36)[2]).join("");e&&e.length>0&&(n=`${e.replace(/[^a-z0-9]+/gi,"-").replace(/^-|-$/g,"")}-${n}`),t.push(["d",n])}}if(this.shouldAddClientTag){const e=["client",this.ndk?.clientName??""];this.ndk?.clientNip89&&e.push(this.ndk?.clientNip89),t.push(e)}else this.shouldStripClientTag&&(t=t.filter(e=>"client"!==e[0]));return{content:r||"",tags:t}}get shouldAddClientTag(){return!(!this.ndk?.clientName&&!this.ndk?.clientNip89)&&(!In.has(this.kind)&&(!this.isEphemeral()&&(!(this.isReplaceable()&&!this.isParamReplaceable())&&(!this.isDvm()&&!this.hasTag("client")))))}get shouldStripClientTag(){return In.has(this.kind)}muted(){const e=this.ndk?.mutedIds.get(this.pubkey);if(e&&"p"===e)return"author";const t=this.tagReference(),n=this.ndk?.mutedIds.get(t[1]);return n&&n===t[0]?"event":null}replaceableDTag(){if(this.kind&&this.kind>=3e4&&this.kind<=4e4){const e=this.getMatchingTags("d")[0];return e?e[1]:""}throw new Error("Event is not a parameterized replaceable event")}deduplicationKey(){return 0===this.kind||3===this.kind||this.kind&&this.kind>=1e4&&this.kind<2e4?`${this.kind}:${this.pubkey}`:this.tagId()}tagId(){return this.isParamReplaceable()?this.tagAddress():this.id}tagAddress(){if(this.isParamReplaceable()){const e=this.dTag??"";return`${this.kind}:${this.pubkey}:${e}`}if(this.isReplaceable())return`${this.kind}:${this.pubkey}:`;throw new Error("Event is not a replaceable event")}tagType(){return this.isParamReplaceable()?"a":"e"}tagReference(e){let t;return t=this.isParamReplaceable()?["a",this.tagAddress()]:["e",this.tagId()],this.relay?t.push(this.relay.url):t.push(""),t.push(e??""),this.isParamReplaceable()||t.push(this.pubkey),t}referenceTags(e,t,n,r){let i=[];return i=this.isParamReplaceable()?[[n??"a",this.tagAddress()],[n??"e",this.id]]:[[n??"e",this.id]],i=i.map(t=>("e"===t[0]||e?t.push(this.relay?.url??""):this.relay?.url&&t.push(this.relay?.url),t)),i.forEach(t=>{"e"===t[0]?(t.push(e??""),t.push(this.pubkey)):e&&t.push(e)}),i=[...i,...this.getMatchingTags("h")],t||!1===r?.pTags||i.push(...this.author.referenceTags()),i}filter(){return this.isParamReplaceable()?{"#a":[this.tagId()]}:{"#e":[this.tagId()]}}nip22Filter(){return this.isParamReplaceable()?{"#A":[this.tagId()]}:{"#E":[this.tagId()]}}async delete(e,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const r=new t(this.ndk,{kind:5,content:e||""});return r.tag(this,void 0,!0),r.tags.push(["k",this.kind?.toString()]),n&&(this.emit("deleted"),await r.publish()),r}set isProtected(e){this.removeTag("-"),e&&this.tags.push(["-"])}get isProtected(){return this.hasTag("-")}fetchTaggedEvent=pn.bind(this);fetchRootEvent=yn.bind(this);fetchReplyEvent=gn.bind(this);repost=kn.bind(this);async react(e,n=!0){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner();const r=new t(this.ndk,{kind:7,content:e});return r.tag(this),1!==this.kind&&r.tags.push(["k",`${this.kind}`]),n&&await r.publish(),r}get isValid(){return this.validate()}get inspect(){return JSON.stringify(this.rawEvent(),null,4)}dump(){console.debug(JSON.stringify(this.rawEvent(),null,4)),console.debug("Event on relays:",this.onRelays.map(e=>e.url).join(", "))}reply(e,n){const r=new t(this.ndk);if(1!==this.kind||e){r.kind=1111;const e=["A","E","I","P"],t=this.tags.filter(t=>e.includes(t[0]));if(t.length>0){const e=this.tagValue("K");let n;if(r.tags.push(...t),e&&r.tags.push(["K",e]),this.isParamReplaceable()){n=["a",this.tagAddress()];const e=this.relay?.url??"";e&&n.push(e)}else{n=["e",this.tagId()];const e=this.relay?.url??"";n.push(e),n.push(this.pubkey)}r.tags.push(n)}else{let e,t;const i=this.relay?.url??"";this.isParamReplaceable()?(e=["a",this.tagAddress(),i],t=["A",this.tagAddress(),i]):(e=["e",this.tagId(),i,this.pubkey],t=["E",this.tagId(),i,this.pubkey]),r.tags.push(e),r.tags.push(t),r.tags.push(["K",this.kind?.toString()]),!1!==n?.pTags&&!1!==n?.pTagOnATags&&r.tags.push(["P",this.pubkey])}r.tags.push(["k",this.kind?.toString()]),!1!==n?.pTags&&(r.tags.push(...this.getMatchingTags("p")),r.tags.push(["p",this.pubkey]))}else{r.kind=1;this.hasTag("e")?r.tags=[...r.tags,...this.getMatchingTags("e"),...this.getMatchingTags("p"),...this.getMatchingTags("a"),...this.referenceTags("reply",!1,void 0,n)]:r.tag(this,"root",!1,void 0,n)}return r}},Nn=new Set([24133,13194,23194,23195]);var Cn=class extends e.lib$1.EventEmitter{_relays=new Map;status="idle";autoConnectRelays=new Set;poolBlacklistRelayUrls=new Set;debug;temporaryRelayTimers=new Map;flappingRelays=new Set;backoffTimes=new Map;ndk;disconnectionTimes=new Map;systemEventDetector;get blacklistRelayUrls(){const e=new Set(this.ndk.blacklistRelayUrls);return this.poolBlacklistRelayUrls.forEach(t=>e.add(t)),e}constructor(e,t,n,{debug:r,name:i}={}){super(),this.debug=r??n.debug.extend("pool"),i&&(this._name=i),this.ndk=n,this.relayUrls=e,this.poolBlacklistRelayUrls=new Set(t),this.ndk.pools.push(this)}get relays(){return this._relays}set relayUrls(e){this._relays.clear();for(const t of e){const e=new Gt(t,void 0,this.ndk);e.connectivity.netDebug=this.ndk.netDebug,this.addRelay(e)}}_name="unnamed";get name(){return this._name}set name(e){this._name=e,this.debug=this.debug.extend(e)}useTemporaryRelay(e,t=3e4,n){const r=this.relays.has(e.url);r||(this.addRelay(e),this.debug("Adding temporary relay %s for filters %o",e.url,n));const i=this.temporaryRelayTimers.get(e.url);if(i&&clearTimeout(i),!r||i){const n=setTimeout(()=>{this.ndk.explicitRelayUrls?.includes(e.url)||this.removeRelay(e.url)},t);this.temporaryRelayTimers.set(e.url,n)}}addRelay(e,t=!0){const n=this.relays.has(e.url),r=this.blacklistRelayUrls?.has(e.url),i=e.url.includes("/npub1");let s=!0;const o=e.url;if(n)return;if(r)return void this.debug(`Refusing to add relay ${o}: blacklisted`);if(i)return void this.debug(`Refusing to add relay ${o}: is a filter relay`);if(this.ndk.cacheAdapter?.getRelayStatus){const n=this.ndk.cacheAdapter.getRelayStatus(o);if(n?.dontConnectBefore){if(n.dontConnectBefore>Date.now()){const r=n.dontConnectBefore-Date.now();return this.debug(`Refusing to add relay ${o}: delayed connect for ${r}ms`),void setTimeout(()=>{this.addRelay(e,t)},r)}s=!1}}const a=t=>this.emit("notice",e,t),u=()=>this.handleRelayConnect(o),c=()=>this.handleRelayReady(e),l=()=>{this.recordDisconnection(e),this.emit("relay:disconnect",e)},h=()=>this.handleFlapping(e),d=t=>this.emit("relay:auth",e,t),f=()=>this.emit("relay:authed",e);e.off("notice",a),e.off("connect",u),e.off("ready",c),e.off("disconnect",l),e.off("flapping",h),e.off("auth",d),e.off("authed",f),e.on("notice",a),e.on("connect",u),e.on("ready",c),e.on("disconnect",l),e.on("flapping",h),e.on("auth",d),e.on("authed",f),e.on("delayed-connect",t=>{this.ndk.cacheAdapter?.updateRelayStatus&&this.ndk.cacheAdapter.updateRelayStatus(e.url,{dontConnectBefore:Date.now()+t})}),this._relays.set(o,e),t&&this.autoConnectRelays.add(o),t&&"active"===this.status&&(this.emit("relay:connecting",e),e.connect(void 0,s).catch(e=>{this.debug(`Failed to connect to relay ${o}`,e)}))}removeRelay(e){const t=this.relays.get(e);if(t)return t.disconnect(),this.relays.delete(e),this.autoConnectRelays.delete(e),this.emit("relay:disconnect",t),!0;const n=this.temporaryRelayTimers.get(e);return n&&(clearTimeout(n),this.temporaryRelayTimers.delete(e)),!1}isRelayConnected(e){const t=qt(e),n=this.relays.get(t);return!!n&&5===n.status}getRelay(e,t=!0,n=!1,r){let i=this.relays.get(qt(e));return i||(i=new Gt(e,void 0,this.ndk),i.connectivity.netDebug=this.ndk.netDebug,n?this.useTemporaryRelay(i,3e4,r):this.addRelay(i,t)),i}handleRelayConnect(e){const t=this.relays.get(e);t?(this.emit("relay:connect",t),this.stats().connected===this.relays.size&&this.emit("connect")):console.error("NDK BUG: relay not found in pool",{relayUrl:e})}handleRelayReady(e){this.emit("relay:ready",e)}async connect(e){this.status="active",this.debug(`Connecting to ${this.relays.size} relays${e?`, timeout ${e}ms`:""}...`);const t=Array.from(this.autoConnectRelays.keys()).map(e=>this.relays.get(e)).filter(e=>!!e);for(const s of t)5!==s.status&&4!==s.status&&(this.emit("relay:connecting",s),s.connect().catch(e=>{this.debug(`Failed to connect to relay ${s.url}: ${e??"No reason specified"}`)}));const n=()=>t.every(e=>5===e.status),r=new Promise(e=>{if(n())return void e();const r=[];for(const i of t){const s=()=>{if(n()){for(let e=0;e<t.length;e++)t[e].off("connect",r[e]);e()}};r.push(s),i.on("connect",s)}}),i=new Promise("number"==typeof e?t=>setTimeout(t,e):()=>{});await Promise.race([r,i])}checkOnFlappingRelays(){if(this.flappingRelays.size/this.relays.size>=.8)for(const e of this.flappingRelays)this.backoffTimes.set(e,0)}recordDisconnection(e){const t=Date.now();this.disconnectionTimes.set(e.url,t);for(const[n,r]of this.disconnectionTimes.entries())t-r>1e4&&this.disconnectionTimes.delete(n);this.checkForSystemWideDisconnection()}checkForSystemWideDisconnection(){const e=Date.now(),t=[];for(const n of this.disconnectionTimes.values())e-n<5e3&&t.push(n);t.length>this.relays.size/2&&this.relays.size>1&&(this.debug(`System-wide disconnection detected: ${t.length}/${this.relays.size} relays disconnected`),this.handleSystemWideReconnection())}handleSystemWideReconnection(){this.debug("Initiating system-wide reconnection with reset backoff"),this.systemEventDetector&&clearTimeout(this.systemEventDetector),this.systemEventDetector=setTimeout(()=>{this.systemEventDetector=void 0},1e4);for(const e of this.relays.values())e.connectivity&&(e.connectivity.resetReconnectionState(),5!==e.status&&4!==e.status&&e.connect().catch(t=>{this.debug(`Failed to reconnect relay ${e.url} after system event: ${t}`)}));this.disconnectionTimes.clear()}handleFlapping(e){this.debug(`Relay ${e.url} is flapping`);let t=this.backoffTimes.get(e.url)||5e3;t*=2,this.backoffTimes.set(e.url,t),this.debug(`Backoff time for ${e.url} is ${t}ms`),setTimeout(()=>{this.debug(`Attempting to reconnect to ${e.url}`),this.emit("relay:connecting",e),e.connect(),this.checkOnFlappingRelays()},t),e.disconnect(),this.emit("flapping",e)}size(){return this.relays.size}stats(){const e={total:0,connected:0,disconnected:0,connecting:0};for(const t of this.relays.values())e.total++,5===t.status?e.connected++:1===t.status?e.disconnected++:4===t.status&&e.connecting++;return e}connectedRelays(){return Array.from(this.relays.values()).filter(e=>e.status>=5)}permanentAndConnectedRelays(){return Array.from(this.relays.values()).filter(e=>e.status>=5&&!this.temporaryRelayTimers.has(e.url))}urls(){return Array.from(this.relays.keys())}},Kn=class e extends Bn{static kind=10019;static kinds=[10019];_p2pk;constructor(e,t){super(e,t),this.kind??=10019}static from(t){return new e(t.ndk,t)}set relays(e){this.tags=this.tags.filter(e=>"relay"!==e[0]);for(const t of e)this.tags.push(["relay",t])}get relays(){const e=[];for(const t of this.tags)"relay"===t[0]&&e.push(t[1]);return e}set mints(e){this.tags=this.tags.filter(e=>"mint"!==e[0]);for(const t of e)this.tags.push(["mint",t])}get mints(){const e=[];for(const t of this.tags)"mint"===t[0]&&e.push(t[1]);return Array.from(new Set(e))}get p2pk(){return this._p2pk||(this._p2pk=this.tagValue("pubkey")??this.pubkey),this._p2pk}set p2pk(e){this._p2pk=e,this.removeTag("pubkey"),e&&this.tags.push(["pubkey",e])}get relaySet(){return en.fromRelayUrls(this.relays,this.ndk)}};(class t extends Bn{debug;_proofs=[];static kind=9321;static kinds=[t.kind];constructor(t,n){super(t,n),this.kind??=9321,this.debug=t?.debug.extend("nutzap")??e.createDebug2("ndk:nutzap"),this.alt||(this.alt="This is a nutzap");try{const e=this.getMatchingTags("proof");e.length?this._proofs=e.map(e=>JSON.parse(e[1])):this._proofs=JSON.parse(this.content)}catch{return}}static from(e){const n=new t(e.ndk,e);if(n._proofs&&n._proofs.length)return n}set comment(e){this.content=e??""}get comment(){const e=this.tagValue("comment");return e||this.content}set proofs(e){this._proofs=e,this.tags=this.tags.filter(e=>"proof"!==e[0]);for(const t of e)this.tags.push(["proof",JSON.stringify(t)])}get proofs(){return this._proofs}get rawP2pk(){const e=this.proofs[0];try{const t=JSON.parse(e.secret);let n;if("string"==typeof t?(n=JSON.parse(t),this.debug("stringified payload",e.secret)):"object"==typeof t&&(n=t),Array.isArray(n)&&"P2PK"===n[0]&&n.length>1&&"object"==typeof n[1]&&null!==n[1])return n[1].data;if("object"==typeof n&&null!==n&&"string"==typeof n[1]?.data)return n[1].data}catch(t){this.debug("error parsing p2pk pubkey",t,this.proofs[0])}}get p2pk(){const e=this.rawP2pk;if(e)return e.startsWith("02")?e.slice(2):e}get mint(){return this.tagValue("u")}set mint(e){this.replaceTag(["u",e])}get unit(){let e=this.tagValue("unit")??"sat";return e?.startsWith("msat")&&(e="sat"),e}set unit(e){if(this.removeTag("unit"),e?.startsWith("msat"))throw new Error("msat is not allowed, use sat denomination instead");e&&this.tag(["unit",e])}get amount(){return this.proofs.reduce((e,t)=>e+t.amount,0)}sender=this.author;set target(e){this.tags=this.tags.filter(e=>"p"!==e[0]),e instanceof Bn&&this.tags.push(e.tagReference())}set recipientPubkey(e){this.removeTag("p"),this.tag(["p",e])}get recipientPubkey(){return this.tagValue("p")}get recipient(){const e=this.recipientPubkey;return this.ndk?this.ndk.getUser({pubkey:e}):new Vn({pubkey:e})}async toNostrEvent(){"msat"===this.unit&&(this.unit="sat"),this.removeTag("amount"),this.tags.push(["amount",this.amount.toString()]);const e=await super.toNostrEvent();return e.content=this.comment,e}get isValid(){let e=0,t=0,n=0;for(const r of this.tags)"e"===r[0]&&e++,"p"===r[0]&&t++,"u"===r[0]&&n++;return 1===t&&1===n&&e<=1&&this.proofs.length>0}});var Dn=new Map;function Un(e,t){Dn.set(e,t)}var jn=class e{_user;_privateKey;_pubkey;constructor(e,n){if("string"==typeof e)if(e.startsWith("nsec1")){const{type:n,data:r}=t.nip19.decode(e);if("nsec"!==n)throw new Error("Invalid private key provided.");this._privateKey=r}else{if(64!==e.length)throw new Error("Invalid private key provided.");this._privateKey=k(e)}else this._privateKey=e;this._pubkey=t.getPublicKey(this._privateKey),n&&(this._user=n.getUser({pubkey:this._pubkey})),this._user??=new Vn({pubkey:this._pubkey})}get privateKey(){if(!this._privateKey)throw new Error("Not ready");return f(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 t.nip19.nsecEncode(this._privateKey)}get npub(){if(!this._pubkey)throw new Error("Not ready");return t.nip19.npubEncode(this._pubkey)}static generate(){const n=t.generateSecretKey();return new e(n)}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 t.finalizeEvent(e,this._privateKey).sig}async encryptionEnabled(e){const t=[];return e&&"nip04"!==e||t.push("nip04"),e&&"nip44"!==e||t.push("nip44"),t}async encrypt(e,n,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to encrypt without a private key");const i=e.pubkey;if("nip44"===r){const e=t.nip44.v2.utils.getConversationKey(this._privateKey,i);return await t.nip44.v2.encrypt(n,e)}return await t.nip04.encrypt(this._privateKey,i,n)}async decrypt(e,n,r){if(!this._privateKey||!this.privateKey)throw Error("Attempted to decrypt without a private key");const i=e.pubkey;if("nip44"===r){const e=t.nip44.v2.utils.getConversationKey(this._privateKey,i);return await t.nip44.v2.decrypt(n,e)}return await t.nip04.decrypt(this._privateKey,i,n)}toPayload(){if(!this._privateKey)throw new Error("Private key not available");const e={type:"private-key",payload:this.privateKey};return JSON.stringify(e)}static async fromPayload(t,n){const r=JSON.parse(t);if("private-key"!==r.type)throw new Error(`Invalid payload type: expected 'private-key', got ${r.type}`);if(!r.payload||"string"!=typeof r.payload)throw new Error("Invalid payload content for private-key signer");return new e(r.payload,n)}};async function Fn(e,t,n=3){if(!this.ndk)throw new Error("NDK not set");const r=await this.ndk.fetchEvent({kinds:[n],authors:[this.pubkey]},e||{groupable:!1});if(r){const e=new Set;return r.tags.forEach(t=>{"p"===t[0]&&e.add(t[1])}),t&&this.ndk?.outboxTracker?.trackUsers(Array.from(e)),[...e].reduce((e,t)=>{const n=new Vn({pubkey:t});return n.ndk=this.ndk,e.add(n),e},new Set)}return new Set}Un("private-key",jn);var qn=/^(?:([\w.+-]+)@)?([\w.-]+)$/;async function $n(e,t,n=fetch,r={}){return await e.queuesNip05.add({id:t,func:async()=>{if(e.cacheAdapter?.loadNip05){const n=await e.cacheAdapter.loadNip05(t);if("missing"!==n){if(n){const t=new Vn({pubkey:n.pubkey,relayUrls:n.relays,nip46Urls:n.nip46});return t.ndk=e,t}if("no-cache"!==r.cache)return null}}const i=t.match(qn);if(!i)return null;const[s,o="_",a]=i;try{const i=await n(`https://${a}/.well-known/nostr.json?name=${o}`,r),{names:s,relays:u,nip46:c}=function(e){const t={names:{}};for(const[n,r]of Object.entries(e.names))"string"==typeof n&&"string"==typeof r&&(t.names[n.toLowerCase()]=r);if(e.relays){t.relays={};for(const[n,r]of Object.entries(e.relays))"string"==typeof n&&Array.isArray(r)&&(t.relays[n]=r.filter(e=>"string"==typeof e))}if(e.nip46){t.nip46={};for(const[n,r]of Object.entries(e.nip46))"string"==typeof n&&Array.isArray(r)&&(t.nip46[n]=r.filter(e=>"string"==typeof e))}return t}(await i.json()),l=s[o.toLowerCase()];let h=null;return l&&(h={pubkey:l,relays:u?.[l],nip46:c?.[l]}),e?.cacheAdapter?.saveNip05&&e.cacheAdapter.saveNip05(t,h),h}catch(u){return e?.cacheAdapter?.saveNip05&&e?.cacheAdapter.saveNip05(t,null),console.error("Failed to fetch NIP05 for",t,u),null}}})}function Mn(e){const t={};let n;try{n=JSON.parse(e.content)}catch(r){throw new Error(`Failed to parse profile event: ${r}`)}t.profileEvent=JSON.stringify(e.rawEvent());for(const i of Object.keys(n))switch(i){case"name":t.name=n.name;break;case"display_name":t.displayName=n.display_name;break;case"image":case"picture":t.picture=n.picture||n.image,t.image=t.picture;break;case"banner":t.banner=n.banner;break;case"bio":t.bio=n.bio;break;case"nip05":t.nip05=n.nip05;break;case"lud06":t.lud06=n.lud06;break;case"lud16":t.lud16=n.lud16;break;case"about":t.about=n.about;break;case"website":t.website=n.website;break;default:t[i]=n[i]}return t.created_at=e.created_at,t}function zn(e){const t={};for(const[n,r]of Object.entries(e))switch(n){case"username":case"name":t.name=r;break;case"displayName":t.display_name=r;break;case"image":case"picture":t.picture=r;break;case"bio":case"about":t.about=r;break;default:t[n]=r}return JSON.stringify(t)}var Vn=class e{ndk;profile;profileEvent;_npub;_pubkey;relayUrls=[];nip46Urls=[];constructor(e){if(e.npub&&(this._npub=e.npub),e.hexpubkey&&(this._pubkey=e.hexpubkey),e.pubkey&&(this._pubkey=e.pubkey),e.relayUrls&&(this.relayUrls=e.relayUrls),e.nip46Urls&&(this.nip46Urls=e.nip46Urls),e.nprofile)try{const n=t.nip19.decode(e.nprofile);"nprofile"===n.type&&(this._pubkey=n.data.pubkey,n.data.relays&&n.data.relays.length>0&&this.relayUrls.push(...n.data.relays))}catch(n){console.error("Failed to decode nprofile",n)}}get npub(){if(!this._npub){if(!this._pubkey)throw new Error("pubkey not set");this._npub=t.nip19.npubEncode(this.pubkey)}return this._npub}get nprofile(){const e=this.profileEvent?.onRelays?.map(e=>e.url);return t.nip19.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=t.nip19.decode(this.npub).data}return this._pubkey}set pubkey(e){this._pubkey=e}filter(){return{"#p":[this.pubkey]}}async getZapInfo(e){if(!this.ndk)throw new Error("No NDK instance found");const t=async t=>{if(!e)return t;let n;const r=new Promise((t,r)=>{n=setTimeout(()=>r(new Error("Timeout")),e)});try{const e=await Promise.race([t,r]);return n&&clearTimeout(n),e}catch(i){if(i instanceof Error&&"Timeout"===i.message)try{return await t}catch(s){return}return}},[n,r]=await Promise.all([t(this.fetchProfile()),t(this.ndk.fetchEvent({kinds:[10019],authors:[this.pubkey]}))]),i=new Map;if(r){const e=Kn.from(r);e.mints.length>0&&i.set("nip61",{mints:e.mints,relays:e.relays,p2pk:e.p2pk})}if(n){const{lud06:e,lud16:t}=n;i.set("nip57",{lud06:e,lud16:t})}return i}static async fromNip05(t,n,r=!1){if(!n)throw new Error("No NDK instance found");const i={};r&&(i.cache="no-cache");const s=await $n(n,t,n?.httpFetch,i);if(s){const t=new e({pubkey:s.pubkey,relayUrls:s.relays,nip46Urls:s.nip46});return t.ndk=n,t}}async fetchProfile(e,t=!1){if(!this.ndk)throw new Error("NDK not set");let n=null;if(this.ndk.cacheAdapter&&(this.ndk.cacheAdapter.fetchProfile||this.ndk.cacheAdapter.fetchProfileSync)&&"ONLY_RELAY"!==e?.cacheUsage){let e=null;if(this.ndk.cacheAdapter.fetchProfileSync?e=this.ndk.cacheAdapter.fetchProfileSync(this.pubkey):this.ndk.cacheAdapter.fetchProfile&&(e=await this.ndk.cacheAdapter.fetchProfile(this.pubkey)),e)return this.profile=e,e}return e??={},e.cacheUsage??="ONLY_RELAY",e.closeOnEose??=!0,e.groupable??=!0,e.groupableDelay??=250,n||(n=await this.ndk.fetchEvent({kinds:[0],authors:[this.pubkey]},e)),n?(this.profile=Mn(n),t&&this.profile&&this.ndk.cacheAdapter&&this.ndk.cacheAdapter.saveProfile&&this.ndk.cacheAdapter.saveProfile(this.pubkey,this.profile),this.profile):null}follows=Fn.bind(this);async followSet(e,t,n=3){const r=await this.follows(e,t,n);return new Set(Array.from(r).map(e=>e.pubkey))}tagReference(){return["p",this.pubkey]}referenceTags(e){const t=[["p",this.pubkey]];return e?(t[0].push("",e),t):t}async publish(){if(!this.ndk)throw new Error("No NDK instance found");if(!this.profile)throw new Error("No profile available");this.ndk.assertSigner();const e=new Bn(this.ndk,{kind:0,content:zn(this.profile)});await e.publish()}async follow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");if(this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n)),t.has(e))return!1;t.add(e);const r=new Bn(this.ndk,{kind:n});for(const i of t)r.tag(i);return await r.publish(),!0}async unfollow(e,t,n=3){if(!this.ndk)throw new Error("No NDK instance found");this.ndk.assertSigner(),t||(t=await this.follows(void 0,void 0,n));const r=new Set;let i=!1;for(const o of t)o.pubkey!==e.pubkey?r.add(o):i=!0;if(!i)return!1;const s=new Bn(this.ndk,{kind:n});for(const o of r)s.tag(o);return await s.publish()}async validateNip05(e){if(!this.ndk)throw new Error("No NDK instance found");const t=await $n(this.ndk,e);return null===t?null:t.pubkey===this.pubkey}};async function Ln(e,t,n,r,i,s){try{await e.sign(n),i(e)}catch(o){r?.(`Failed to publish auth event to relay ${t.url}`,o),s(e)}}var Hn={disconnect:function(t,n){return n??=e.createDebug2("ndk:relay:auth-policies:disconnect"),async e=>{n?.(`Relay ${e.url} requested authentication, disconnecting`),t.removeRelay(e.url)}},signIn:function({ndk:t,signer:n,debug:r}={}){return r??=e.createDebug2("ndk:auth-policies:signIn"),async(e,i)=>{r?.(`Relay ${e.url} requested authentication, signing in`);const s=new Bn(t);return s.kind=22242,s.tags=[["relay",e.url],["challenge",i]],n??=t?.signer,new Promise(async(i,o)=>{n?await Ln(s,e,n,r,i,o):t?.once("signer:ready",async t=>{await Ln(s,e,t,r,i,o)})})}}};Un("nip07",class t{_userPromise;encryptionQueue=[];encryptionProcessing=!1;debug;waitTimeout;_pubkey;ndk;_user;constructor(t=1e3,n){this.debug=e.createDebug2("ndk:nip07"),this.waitTimeout=t,this.ndk=n}get pubkey(){if(!this._pubkey)throw new Error("Not ready");return this._pubkey}async blockUntilReady(){await this.waitForExtension();const e=await(window.nostr?.getPublicKey());if(!e)throw new Error("User rejected access");let t;return this._pubkey=e,t=this.ndk?this.ndk.getUser({pubkey:e}):new Vn({pubkey:e}),this._user=t,t}async user(){return this._userPromise||(this._userPromise=this.blockUntilReady()),this._userPromise}get userSync(){if(!this._user)throw new Error("User not ready");return this._user}async sign(e){await this.waitForExtension();const t=await(window.nostr?.signEvent(e));if(!t)throw new Error("Failed to sign event");return t.sig}async relays(e){await this.waitForExtension();const t=await(window.nostr?.getRelays?.())||{},n=[];for(const r of Object.keys(t))t[r].read&&t[r].write&&n.push(r);return n.map(t=>new Gt(t,e?.relayAuthDefaultPolicy,e))}async encryptionEnabled(e){const t=[];return e&&"nip04"!==e||!Boolean(window.nostr?.nip04)||t.push("nip04"),e&&"nip44"!==e||!Boolean(window.nostr?.nip44)||t.push("nip44"),t}async encrypt(e,t,n="nip04"){if(!(await this.encryptionEnabled(n)))throw new Error(`${n}encryption is not available from your browser extension`);await this.waitForExtension();const r=e.pubkey;return this.queueEncryption(n,"encrypt",r,t)}async decrypt(e,t,n="nip04"){if(!(await this.encryptionEnabled(n)))throw new Error(`${n}encryption is not available from your browser extension`);await this.waitForExtension();const r=e.pubkey;return this.queueEncryption(n,"decrypt",r,t)}async queueEncryption(e,t,n,r){return new Promise((i,s)=>{this.encryptionQueue.push({scheme:e,method:t,counterpartyHexpubkey:n,value:r,resolve:i,reject:s}),this.encryptionProcessing||this.processEncryptionQueue()})}async processEncryptionQueue(e,t=0){if(!e&&0===this.encryptionQueue.length)return void(this.encryptionProcessing=!1);this.encryptionProcessing=!0;const n=e||this.encryptionQueue.shift();if(!n)return void(this.encryptionProcessing=!1);const{scheme:r,method:i,counterpartyHexpubkey:s,value:o,resolve:a,reject:u}=n;this.debug("Processing encryption queue item",{method:i,counterpartyHexpubkey:s,value:o});try{const e=await(window.nostr?.[r]?.[i](s,o));if(!e)throw new Error("Failed to encrypt/decrypt");a(e)}catch(c){const e=c instanceof Error?c.message:String(c);if(e.includes("call already executing")&&t<5)return this.debug("Retrying encryption queue item",{method:i,counterpartyHexpubkey:s,value:o,retries:t}),void setTimeout(()=>{this.processEncryptionQueue(n,t+1)},50*t);u(c instanceof Error?c:new Error(e))}this.processEncryptionQueue()}waitForExtension(){return new Promise((e,t)=>{if(window.nostr)return void e();let n;const r=setInterval(()=>{window.nostr&&(clearTimeout(n),clearInterval(r),e())},100);n=setTimeout(()=>{clearInterval(r),t(new Error("NIP-07 extension not available"))},this.waitTimeout)})}toPayload(){return JSON.stringify({type:"nip07",payload:""})}static async fromPayload(e,n){const r=JSON.parse(e);if("nip07"!==r.type)throw new Error(`Invalid payload type: expected 'nip07', got ${r.type}`);return new t(void 0,n)}});var Wn=class extends e.lib$1.EventEmitter{ndk;signer;relaySet;debug;encryptionType="nip04";pool;constructor(e,t,n,r){if(super(),this.ndk=e,this.signer=t,r){this.pool=new Cn(r,[],e,{debug:n.extend("rpc-pool"),name:"Nostr RPC"}),this.relaySet=new en(new Set,e,this.pool);for(const i of r){const r=this.pool.getRelay(i,!1,!1);r.authPolicy=Hn.signIn({ndk:e,signer:t,debug:n}),this.relaySet.addRelay(r),r.connect()}}this.debug=n.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 e=>{try{const t=await this.parseEvent(e);t.method?this.emit("request",t):(this.emit(`response-${t.id}`,t),this.emit("response",t))}catch(t){this.debug("error parsing event",t,e.rawEvent())}}),new Promise(e=>{t.on("eose",()=>{this.debug("eosed"),e(t)}),t.start()})}async parseEvent(e){"nip44"===this.encryptionType&&e.content.includes("?iv=")?this.encryptionType="nip04":"nip04"!==this.encryptionType||e.content.includes("?iv=")||(this.encryptionType="nip44");const t=this.ndk.getUser({pubkey:e.pubkey});let n;t.ndk=this.ndk;try{n=await this.signer.decrypt(t,e.content,this.encryptionType)}catch(c){const r="nip04"===this.encryptionType?"nip44":"nip04";n=await this.signer.decrypt(t,e.content,r),this.encryptionType=r}const r=JSON.parse(n),{id:i,method:s,params:o,result:a,error:u}=r;return s?{id:i,pubkey:e.pubkey,method:s,params:o,event:e}:{id:i,result:a,error:u,event:e}}async sendResponse(e,t,n,r=24133,i){const s={id:e,result:n};i&&(s.error=i);const o=await this.signer.user(),a=this.ndk.getUser({pubkey:t}),u=new Bn(this.ndk,{kind:r,content:JSON.stringify(s),tags:[["p",t]],pubkey:o.pubkey});u.content=await this.signer.encrypt(a,u.content,this.encryptionType),await u.sign(this.signer),await u.publish(this.relaySet)}async sendRequest(e,t,n=[],r=24133,i){const s=Math.random().toString(36).substring(7),o=await this.signer.user(),a=this.ndk.getUser({pubkey:e}),u={id:s,method:t,params:n},c=new Promise(()=>{const e=t=>{"auth_url"===t.result?(this.once(`response-${s}`,e),this.emit("authUrl",t.error)):i&&i(t)};this.once(`response-${s}`,e)}),l=new Bn(this.ndk,{kind:r,content:JSON.stringify(u),tags:[["p",e]],pubkey:o.pubkey});return l.content=await this.signer.encrypt(a,l.content,this.encryptionType),await l.sign(this.signer),await l.publish(this.relaySet),c}};Un("nip46",class t extends e.lib$1.EventEmitter{ndk;_user;bunkerPubkey;userPubkey;get pubkey(){if(!this.userPubkey)throw new Error("Not ready");return this.userPubkey}secret;localSigner;nip05;rpc;debug;relayUrls;subscription;nostrConnectUri;nostrConnectSecret;constructor(e,t,n,r,i){super(),this.ndk=e,this.debug=e.debug.extend("nip46:signer"),this.relayUrls=r,this.localSigner=n?"string"==typeof n?new jn(n):n:jn.generate(),!1===t||(t?t.startsWith("bunker://")?this.bunkerFlowInit(t):this.nip05Init(t):this.nostrconnectFlowInit(i)),this.rpc=new Wn(this.ndk,this.localSigner,this.debug,this.relayUrls)}static bunker(e,n,r){return new t(e,n,r)}static nostrconnect(e,n,r,i){return new t(e,void 0,r,[n],i)}nostrconnectFlowInit(e){this.nostrConnectSecret=Math.random().toString(36).substring(2,15);const t=this.localSigner.pubkey;this.nostrConnectUri=function(e,t,n,r){const i=r?.name?encodeURIComponent(r.name):"",s=r?.url?encodeURIComponent(r.url):"";let o=`nostrconnect://${e}?image=${r?.image?encodeURIComponent(r.image):""}&url=${s}&name=${i}&perms=${r?.perms?encodeURIComponent(r.perms):""}&secret=${encodeURIComponent(t)}`;return n&&(o+=`&relay=${encodeURIComponent(n)}`),o}(t,this.nostrConnectSecret,this.relayUrls?.[0],e)}bunkerFlowInit(e){const t=new URL(e),n=t.hostname||t.pathname.replace(/^\/\//,""),r=t.searchParams.get("pubkey"),i=t.searchParams.getAll("relay"),s=t.searchParams.get("secret");this.bunkerPubkey=n,this.userPubkey=r,this.relayUrls=i,this.secret=s}nip05Init(e){this.nip05=e}async startListening(){if(this.subscription)return;const e=await this.localSigner.user();if(!e)throw new Error("Local signer not ready");this.subscription=await this.rpc.subscribe({kinds:[24133],"#p":[e.pubkey]})}async user(){return this._user?this._user:this.blockUntilReady()}get userSync(){if(!this._user)throw new Error("Remote user not ready synchronously");return this._user}async blockUntilReadyNostrConnect(){return new Promise((e,t)=>{const n=t=>{t.result===this.nostrConnectSecret&&(this._user=t.event.author,this.userPubkey=t.event.pubkey,this.bunkerPubkey=t.event.pubkey,this.rpc.off("response",n),e(this._user))};this.startListening(),this.rpc.on("response",n)})}async blockUntilReady(){if(!this.bunkerPubkey&&!this.nostrConnectSecret&&!this.nip05)throw new Error("Bunker pubkey not set");if(this.nostrConnectSecret)return this.blockUntilReadyNostrConnect();if(this.nip05&&!this.userPubkey){const e=await Vn.fromNip05(this.nip05,this.ndk);e&&(this._user=e,this.userPubkey=e.pubkey,this.relayUrls=e.nip46Urls,this.rpc=new Wn(this.ndk,this.localSigner,this.debug,this.relayUrls))}if(!this.bunkerPubkey&&this.userPubkey)this.bunkerPubkey=this.userPubkey;else if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");return await this.startListening(),this.rpc.on("authUrl",(...e)=>{this.emit("authUrl",...e)}),new Promise((e,t)=>{const n=[this.userPubkey??""];if(this.secret&&n.push(this.secret),!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"connect",n,24133,n=>{"ack"===n.result?this.getPublicKey().then(t=>{this.userPubkey=t,this._user=this.ndk.getUser({pubkey:t}),e(this._user)}):t(n.error)})})}stop(){this.subscription?.stop(),this.subscription=void 0}async getPublicKey(){return this.userPubkey?this.userPubkey:new Promise((e,t)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"get_public_key",[],24133,t=>{e(t.result)})})}async encryptionEnabled(e){return e?[e]:Promise.resolve(["nip04","nip44"])}async encrypt(e,t,n="nip04"){return this.encryption(e,t,n,"encrypt")}async decrypt(e,t,n="nip04"){return this.encryption(e,t,n,"decrypt")}async encryption(e,t,n,r){return new Promise((i,s)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,`${n}_${r}`,[e.pubkey,t],24133,e=>{e.error?s(e.error):i(e.result)})})}async sign(e){return new Promise((t,n)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"sign_event",[JSON.stringify(e)],24133,e=>{if(e.error)n(e.error);else{const n=JSON.parse(e.result);t(n.sig)}})})}async createAccount(e,t,n){await this.startListening();const r=[];return e&&r.push(e),t&&r.push(t),n&&r.push(n),new Promise((e,t)=>{if(!this.bunkerPubkey)throw new Error("Bunker pubkey not set");this.rpc.sendRequest(this.bunkerPubkey,"create_account",r,24133,n=>{if(n.error)t(n.error);else{const t=n.result;e(t)}})})}toPayload(){if(!this.bunkerPubkey||!this.userPubkey)throw new Error("NIP-46 signer is not fully initialized for serialization");const e={type:"nip46",payload:{bunkerPubkey:this.bunkerPubkey,userPubkey:this.userPubkey,relayUrls:this.relayUrls,secret:this.secret,localSignerPayload:this.localSigner.toPayload(),nip05:this.nip05||null}};return JSON.stringify(e)}static async fromPayload(e,n){if(!n)throw new Error("NDK instance is required to deserialize NIP-46 signer");const r=JSON.parse(e);if("nip46"!==r.type)throw new Error(`Invalid payload type: expected 'nip46', got ${r.type}`);const i=r.payload;if(!i||"object"!=typeof i||!i.localSignerPayload)throw new Error("Invalid payload content for nip46 signer");const s=await async function(e,t){let n;try{n=JSON.parse(e)}catch(i){return void console.error("Failed to parse signer payload string",e,i)}if(!n||"string"!=typeof n.type)return void console.error("Failed to parse signer payload string",e,new Error("Missing type field"));const r=Dn.get(n.type);if(!r)throw new Error(`Unknown signer type: ${n.type}`);try{return await r.fromPayload(e,t)}catch(i){const e=i instanceof Error?i.message:String(i);throw new Error(`Failed to deserialize signer type ${n.type}: ${e}`)}}(i.localSignerPayload,n);if(!s)throw new Error("Failed to deserialize local signer for NIP-46");if(!(s instanceof jn))throw new Error("Local signer must be an instance of NDKPrivateKeySigner");let o;return o=new t(n,!1,s,i.relayUrls),o.userPubkey=i.userPubkey,o.bunkerPubkey=i.bunkerPubkey,o.relayUrls=i.relayUrls,o.secret=i.secret,i.userPubkey&&(o._user=new Vn({pubkey:i.userPubkey}),o._user&&(o._user.ndk=n)),o}}),e.createDebug2("ndk:active-user"),e.createDebug2("ndk:zapper:ln"),e.createDebug2("ndk:zapper");((e,t,n,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of Dt(t))Ut.call(e,i)||i===n||Ct(e,i,{get:()=>t[i],enumerable:!(r=Kt(t,i))||r.enumerable})})({},Nt,"default");var Yn,Zn={exports:{}};Yn=Zn,e.commonjsGlobal,Yn.exports=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])})(e,n)},n=function(){return(n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function r(e,t,n){for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||((r=r||Array.prototype.slice.call(t,0,i))[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}var i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:e.commonjsGlobal,s=Object.keys,o=Array.isArray;function a(e,t){return"object"!=typeof t||s(t).forEach(function(n){e[n]=t[n]}),e}"undefined"==typeof Promise||i.Promise||(i.Promise=Promise);var u=Object.getPrototypeOf,c={}.hasOwnProperty;function l(e,t){return c.call(e,t)}function h(e,t){"function"==typeof t&&(t=t(u(e))),("undefined"==typeof Reflect?s:Reflect.ownKeys)(t).forEach(function(n){f(e,n,t[n])})}var d=Object.defineProperty;function f(e,t,n,r){d(e,t,a(n&&l(n,"get")&&"function"==typeof n.get?{get:n.get,set:n.set,configurable:!0}:{value:n,configurable:!0,writable:!0},r))}function p(e){return{from:function(t){return e.prototype=Object.create(t.prototype),f(e.prototype,"constructor",e),{extend:h.bind(null,e.prototype)}}}}var y=Object.getOwnPropertyDescriptor,g=[].slice;function b(e,t,n){return g.call(e,t,n)}function m(e,t){return t(e)}function v(e){if(!e)throw new Error("Assertion Failed")}function w(e){i.setImmediate?setImmediate(e):setTimeout(e,0)}function k(e,t){if("string"==typeof t&&l(e,t))return e[t];if(!t)return e;if("string"!=typeof t){for(var n=[],r=0,i=t.length;r<i;++r){var s=k(e,t[r]);n.push(s)}return n}var o=t.indexOf(".");if(-1!==o){var a=e[t.substr(0,o)];return null==a?void 0:k(a,t.substr(o+1))}}function E(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){v("string"!=typeof n&&"length"in n);for(var r=0,i=t.length;r<i;++r)E(e,t[r],n[r])}else{var s,a,u=t.indexOf(".");-1!==u?(s=t.substr(0,u),""===(a=t.substr(u+1))?void 0===n?o(e)&&!isNaN(parseInt(s))?e.splice(s,1):delete e[s]:e[s]=n:E(u=(u=e[s])&&l(e,s)?u:e[s]={},a,n)):void 0===n?o(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}function _(e){var t,n={};for(t in e)l(e,t)&&(n[t]=e[t]);return n}var x=[].concat;function S(e){return x.apply([],e)}var R="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(S([8,16,32,64].map(function(e){return["Int","Uint","Float"].map(function(t){return t+e+"Array"})}))).filter(function(e){return i[e]}),P=new Set(R.map(function(e){return i[e]})),T=null;function A(e){return T=new WeakMap,e=function e(t){if(!t||"object"!=typeof t)return t;var n=T.get(t);if(n)return n;if(o(t)){n=[],T.set(t,n);for(var r=0,i=t.length;r<i;++r)n.push(e(t[r]))}else if(P.has(t.constructor))n=t;else{var s,a=u(t);for(s in n=a===Object.prototype?{}:Object.create(a),T.set(t,n),t)l(t,s)&&(n[s]=e(t[s]))}return n}(e),T=null,e}var O={}.toString;function I(e){return O.call(e).slice(8,-1)}var B="undefined"!=typeof Symbol?Symbol.iterator:"@@iterator",N="symbol"==typeof B?function(e){var t;return null!=e&&(t=e[B])&&t.apply(e)}:function(){return null};function C(e,t){return 0<=(t=e.indexOf(t))&&e.splice(t,1),0<=t}var K={};function D(e){var t,n,r,i;if(1===arguments.length){if(o(e))return e.slice();if(this===K&&"string"==typeof e)return[e];if(i=N(e)){for(n=[];!(r=i.next()).done;)n.push(r.value);return n}if(null==e)return[e];if("number"!=typeof(t=e.length))return[e];for(n=new Array(t);t--;)n[t]=e[t];return n}for(t=arguments.length,n=new Array(t);t--;)n[t]=arguments[t];return n}var U="undefined"!=typeof Symbol?function(e){return"AsyncFunction"===e[Symbol.toStringTag]}:function(){return!1},j=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ue=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"]),F={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function q(e,t){this.name=e,this.message=t}function $(e,t){return e+". Errors: "+Object.keys(t).map(function(e){return t[e].toString()}).filter(function(e,t,n){return n.indexOf(e)===t}).join("\n")}function M(e,t,n,r){this.failures=t,this.failedKeys=r,this.successCount=n,this.message=$(e,t)}function z(e,t){this.name="BulkError",this.failures=Object.keys(t).map(function(e){return t[e]}),this.failuresByPos=t,this.message=$(e,this.failures)}p(q).from(Error).extend({toString:function(){return this.name+": "+this.message}}),p(M).from(q),p(z).from(q);var V=j.reduce(function(e,t){return e[t]=t+"Error",e},{}),L=q,H=j.reduce(function(e,t){var n=t+"Error";function r(e,r){this.name=n,e?"string"==typeof e?(this.message="".concat(e).concat(r?"\n "+r:""),this.inner=r||null):"object"==typeof e&&(this.message="".concat(e.name," ").concat(e.message),this.inner=e):(this.message=F[t]||n,this.inner=null)}return p(r).from(L),e[t]=r,e},{});H.Syntax=SyntaxError,H.Type=TypeError,H.Range=RangeError;var W=ue.reduce(function(e,t){return e[t+"Error"]=H[t],e},{}),Y=j.reduce(function(e,t){return-1===["Syntax","Type","Range"].indexOf(t)&&(e[t+"Error"]=H[t]),e},{});function Z(){}function J(e){return e}function Q(e,t){return null==e||e===J?t:function(n){return t(e(n))}}function G(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function X(e,t){return e===Z?t:function(){var n=e.apply(this,arguments);void 0!==n&&(arguments[0]=n);var r=this.onsuccess,i=this.onerror;this.onsuccess=null,this.onerror=null;var s=t.apply(this,arguments);return r&&(this.onsuccess=this.onsuccess?G(r,this.onsuccess):r),i&&(this.onerror=this.onerror?G(i,this.onerror):i),void 0!==s?s:n}}function ee(e,t){return e===Z?t:function(){e.apply(this,arguments);var n=this.onsuccess,r=this.onerror;this.onsuccess=this.onerror=null,t.apply(this,arguments),n&&(this.onsuccess=this.onsuccess?G(n,this.onsuccess):n),r&&(this.onerror=this.onerror?G(r,this.onerror):r)}}function te(e,t){return e===Z?t:function(n){var r=e.apply(this,arguments);a(n,r);var i=this.onsuccess,s=this.onerror;return this.onsuccess=null,this.onerror=null,n=t.apply(this,arguments),i&&(this.onsuccess=this.onsuccess?G(i,this.onsuccess):i),s&&(this.onerror=this.onerror?G(s,this.onerror):s),void 0===r?void 0===n?void 0:n:a(r,n)}}function ne(e,t){return e===Z?t:function(){return!1!==t.apply(this,arguments)&&e.apply(this,arguments)}}function re(e,t){return e===Z?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,i=arguments.length,s=new Array(i);i--;)s[i]=arguments[i];return n.then(function(){return t.apply(r,s)})}return t.apply(this,arguments)}}Y.ModifyError=M,Y.DexieError=q,Y.BulkError=z;var ie="undefined"!=typeof location&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function se(e){ie=e}var oe={},ae=100,ue=(R="undefined"==typeof Promise?[]:function(){var e=Promise.resolve();if("undefined"==typeof crypto||!crypto.subtle)return[e,u(e),e];var t=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[t,u(t),e]}())[0],ce=(j=R[1],R=R[2],j=j&&j.then,ue&&ue.constructor),le=!!R,he=function(e,t){ve.push([e,t]),fe&&(queueMicrotask(Ae),fe=!1)},de=!0,fe=!0,pe=[],ye=[],ge=J,be={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Z,pgp:!1,env:{},finalize:Z},me=be,ve=[],we=0,ke=[];function Ee(e){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var t=this._PSD=me;if("function"!=typeof e){if(e!==oe)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(!1===this._state&&Se(this,this._value))}this._state=null,this._value=null,++t.ref,function e(t,n){try{n(function(n){if(null===t._state){if(n===t)throw new TypeError("A promise cannot be resolved with itself.");var r=t._lib&&Oe();n&&"function"==typeof n.then?e(t,function(e,t){n instanceof Ee?n._then(e,t):n.then(e,t)}):(t._state=!0,t._value=n,Re(t)),r&&Ie()}},Se.bind(null,t))}catch(r){Se(t,r)}}(this,e)}var _e={get:function(){var e=me,t=Fe;function n(n,r){var i=this,s=!e.global&&(e!==me||t!==Fe),o=s&&!ze(),a=new Ee(function(t,a){Pe(i,new xe(Ze(n,e,s,o),Ze(r,e,s,o),t,a,e))});return this._consoleTask&&(a._consoleTask=this._consoleTask),a}return n.prototype=oe,n},set:function(e){f(this,"then",e&&e.prototype===oe?_e:{get:function(){return e},set:_e.set})}};function xe(e,t,n,r,i){this.onFulfilled="function"==typeof e?e:null,this.onRejected="function"==typeof t?t:null,this.resolve=n,this.reject=r,this.psd=i}function Se(e,t){var n,r;ye.push(t),null===e._state&&(n=e._lib&&Oe(),t=ge(t),e._state=!1,e._value=t,r=e,pe.some(function(e){return e._value===r._value})||pe.push(r),Re(e),n&&Ie())}function Re(e){var t=e._listeners;e._listeners=[];for(var n=0,r=t.length;n<r;++n)Pe(e,t[n]);var i=e._PSD;--i.ref||i.finalize(),0===we&&(++we,he(function(){0==--we&&Be()},[]))}function Pe(e,t){if(null!==e._state){var n=e._state?t.onFulfilled:t.onRejected;if(null===n)return(e._state?t.resolve:t.reject)(e._value);++t.psd.ref,++we,he(Te,[n,e,t])}else e._listeners.push(t)}function Te(e,t,n){try{var r,i=t._value;!t._state&&ye.length&&(ye=[]),r=ie&&t._consoleTask?t._consoleTask.run(function(){return e(i)}):e(i),t._state||-1!==ye.indexOf(i)||function(e){for(var t=pe.length;t;)if(pe[--t]._value===e._value)return pe.splice(t,1)}(t),n.resolve(r)}catch(s){n.reject(s)}finally{0==--we&&Be(),--n.psd.ref||n.psd.finalize()}}function Ae(){Ye(be,function(){Oe()&&Ie()})}function Oe(){var e=de;return fe=de=!1,e}function Ie(){var e,t,n;do{for(;0<ve.length;)for(e=ve,ve=[],n=e.length,t=0;t<n;++t){var r=e[t];r[0].apply(null,r[1])}}while(0<ve.length);fe=de=!0}function Be(){var e=pe;pe=[],e.forEach(function(e){e._PSD.onunhandled.call(null,e._value,e)});for(var t=ke.slice(0),n=t.length;n;)t[--n]()}function Ne(e){return new Ee(oe,!1,e)}function Ce(e,t){var n=me;return function(){var r=Oe(),i=me;try{return He(n,!0),e.apply(this,arguments)}catch(s){t&&t(s)}finally{He(i,!1),r&&Ie()}}}h(Ee.prototype,{then:_e,_then:function(e,t){Pe(this,new xe(null,null,e,t,me))},catch:function(e){if(1===arguments.length)return this.then(null,e);var t=e,n=arguments[1];return"function"==typeof t?this.then(null,function(e){return(e instanceof t?n:Ne)(e)}):this.then(null,function(e){return(e&&e.name===t?n:Ne)(e)})},finally:function(e){return this.then(function(t){return Ee.resolve(e()).then(function(){return t})},function(t){return Ee.resolve(e()).then(function(){return Ne(t)})})},timeout:function(e,t){var n=this;return e<1/0?new Ee(function(r,i){var s=setTimeout(function(){return i(new H.Timeout(t))},e);n.then(r,i).finally(clearTimeout.bind(null,s))}):this}}),"undefined"!=typeof Symbol&&Symbol.toStringTag&&f(Ee.prototype,Symbol.toStringTag,"Dexie.Promise"),be.env=We(),h(Ee,{all:function(){var e=D.apply(null,arguments).map(Ve);return new Ee(function(t,n){0===e.length&&t([]);var r=e.length;e.forEach(function(i,s){return Ee.resolve(i).then(function(n){e[s]=n,--r||t(e)},n)})})},resolve:function(e){return e instanceof Ee?e:e&&"function"==typeof e.then?new Ee(function(t,n){e.then(t,n)}):new Ee(oe,!0,e)},reject:Ne,race:function(){var e=D.apply(null,arguments).map(Ve);return new Ee(function(t,n){e.map(function(e){return Ee.resolve(e).then(t,n)})})},PSD:{get:function(){return me},set:function(e){return me=e}},totalEchoes:{get:function(){return Fe}},newPSD:$e,usePSD:Ye,scheduler:{get:function(){return he},set:function(e){he=e}},rejectionMapper:{get:function(){return ge},set:function(e){ge=e}},follow:function(e,t){return new Ee(function(n,r){return $e(function(t,n){var r=me;r.unhandleds=[],r.onunhandled=n,r.finalize=G(function(){var e,r=this;e=function(){0===r.unhandleds.length?t():n(r.unhandleds[0])},ke.push(function t(){e(),ke.splice(ke.indexOf(t),1)}),++we,he(function(){0==--we&&Be()},[])},r.finalize),e()},t,n,r)})}}),ce&&(ce.allSettled&&f(Ee,"allSettled",function(){var e=D.apply(null,arguments).map(Ve);return new Ee(function(t){0===e.length&&t([]);var n=e.length,r=new Array(n);e.forEach(function(e,i){return Ee.resolve(e).then(function(e){return r[i]={status:"fulfilled",value:e}},function(e){return r[i]={status:"rejected",reason:e}}).then(function(){return--n||t(r)})})})}),ce.any&&"undefined"!=typeof AggregateError&&f(Ee,"any",function(){var e=D.apply(null,arguments).map(Ve);return new Ee(function(t,n){0===e.length&&n(new AggregateError([]));var r=e.length,i=new Array(r);e.forEach(function(e,s){return Ee.resolve(e).then(function(e){return t(e)},function(e){i[s]=e,--r||n(new AggregateError(i))})})})}),ce.withResolvers&&(Ee.withResolvers=ce.withResolvers));var Ke={awaits:0,echoes:0,id:0},De=0,Ue=[],je=0,Fe=0,qe=0;function $e(e,t,n,r){var i=me,s=Object.create(i);return s.parent=i,s.ref=0,s.global=!1,s.id=++qe,be.env,s.env=le?{Promise:Ee,PromiseProp:{value:Ee,configurable:!0,writable:!0},all:Ee.all,race:Ee.race,allSettled:Ee.allSettled,any:Ee.any,resolve:Ee.resolve,reject:Ee.reject}:{},t&&a(s,t),++i.ref,s.finalize=function(){--this.parent.ref||this.parent.finalize()},r=Ye(s,e,n,r),0===s.ref&&s.finalize(),r}function Me(){return Ke.id||(Ke.id=++De),++Ke.awaits,Ke.echoes+=ae,Ke.id}function ze(){return!!Ke.awaits&&(0==--Ke.awaits&&(Ke.id=0),Ke.echoes=Ke.awaits*ae,!0)}function Ve(e){return Ke.echoes&&e&&e.constructor===ce?(Me(),e.then(function(e){return ze(),e},function(e){return ze(),Qe(e)})):e}function Le(){var e=Ue[Ue.length-1];Ue.pop(),He(e,!1)}function He(e,t){var n,r=me;(t?!Ke.echoes||je++&&e===me:!je||--je&&e===me)||queueMicrotask(t?function(e){++Fe,Ke.echoes&&0!=--Ke.echoes||(Ke.echoes=Ke.awaits=Ke.id=0),Ue.push(me),He(e,!0)}.bind(null,e):Le),e!==me&&(me=e,r===be&&(be.env=We()),le&&(n=be.env.Promise,t=e.env,(r.global||e.global)&&(Object.defineProperty(i,"Promise",t.PromiseProp),n.all=t.all,n.race=t.race,n.resolve=t.resolve,n.reject=t.reject,t.allSettled&&(n.allSettled=t.allSettled),t.any&&(n.any=t.any))))}function We(){var e=i.Promise;return le?{Promise:e,PromiseProp:Object.getOwnPropertyDescriptor(i,"Promise"),all:e.all,race:e.race,allSettled:e.allSettled,any:e.any,resolve:e.resolve,reject:e.reject}:{}}function Ye(e,t,n,r,i){var s=me;try{return He(e,!0),t(n,r,i)}finally{He(s,!1)}}function Ze(e,t,n,r){return"function"!=typeof e?e:function(){var i=me;n&&Me(),He(t,!0);try{return e.apply(this,arguments)}finally{He(i,!1),r&&queueMicrotask(ze)}}}function Je(e){Promise===ce&&0===Ke.echoes?0===je?e():enqueueNativeMicroTask(e):setTimeout(e,0)}-1===(""+j).indexOf("[native code]")&&(Me=ze=Z);var Qe=Ee.reject,Ge=String.fromCharCode(65535),Xe="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",et="String expected.",tt=[],nt="__dbnames",rt="readonly",it="readwrite";function st(e,t){return e?t?function(){return e.apply(this,arguments)&&t.apply(this,arguments)}:e:t}var ot={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function at(e){return"string"!=typeof e||/\./.test(e)?function(e){return e}:function(t){return void 0===t[e]&&e in t&&delete(t=A(t))[e],t}}function ut(){throw H.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function ct(e,t){try{var n=lt(e),r=lt(t);if(n!==r)return"Array"===n?1:"Array"===r?-1:"binary"===n?1:"binary"===r?-1:"string"===n?1:"string"===r?-1:"Date"===n?1:"Date"!==r?NaN:-1;switch(n){case"number":case"Date":case"string":return t<e?1:e<t?-1:0;case"binary":return function(e,t){for(var n=e.length,r=t.length,i=n<r?n:r,s=0;s<i;++s)if(e[s]!==t[s])return e[s]<t[s]?-1:1;return n===r?0:n<r?-1:1}(ht(e),ht(t));case"Array":return function(e,t){for(var n=e.length,r=t.length,i=n<r?n:r,s=0;s<i;++s){var o=ct(e[s],t[s]);if(0!==o)return o}return n===r?0:n<r?-1:1}(e,t)}}catch(i){}return NaN}function lt(e){var t=typeof e;return"object"!=t?t:ArrayBuffer.isView(e)||"ArrayBuffer"===(e=I(e))?"binary":e}function ht(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e)}function dt(e,t,n){var r=e.schema.yProps;return r?(t&&0<n.numFailures&&(t=t.filter(function(e,t){return!n.failures[t]})),Promise.all(r.map(function(n){return n=n.updatesTable,t?e.db.table(n).where("k").anyOf(t).delete():e.db.table(n).clear()})).then(function(){return n})):n}var ft=(pt.prototype.execute=function(e){var t=this["@@propmod"];if(void 0!==t.add){var n=t.add;if(o(n))return r(r([],o(e)?e:[],!0),n).sort();if("number"==typeof n)return(Number(e)||0)+n;if("bigint"==typeof n)try{return BigInt(e)+n}catch(s){return BigInt(0)+n}throw new TypeError("Invalid term ".concat(n))}if(void 0!==t.remove){var i=t.remove;if(o(i))return o(e)?e.filter(function(e){return!i.includes(e)}).sort():[];if("number"==typeof i)return Number(e)-i;if("bigint"==typeof i)try{return BigInt(e)-i}catch(s){return BigInt(0)-i}throw new TypeError("Invalid subtrahend ".concat(i))}return(n=null===(n=t.replacePrefix)||void 0===n?void 0:n[0])&&"string"==typeof e&&e.startsWith(n)?t.replacePrefix[1]+e.substring(n.length):e},pt);function pt(e){this["@@propmod"]=e}function yt(e,t){for(var n=s(t),r=n.length,i=!1,o=0;o<r;++o){var a=n[o],u=t[a],c=k(e,a);u instanceof ft?(E(e,a,u.execute(c)),i=!0):c!==u&&(E(e,a,u),i=!0)}return i}var gt=(bt.prototype._trans=function(e,t,n){var r=this._tx||me.trans,i=this.name,s=ie&&"undefined"!=typeof console&&console.createTask&&console.createTask("Dexie: ".concat("readonly"===e?"read":"write"," ").concat(this.name));function o(e,n,r){if(!r.schema[i])throw new H.NotFound("Table "+i+" not part of transaction");return t(r.idbtrans,r)}var a=Oe();try{var u=r&&r.db._novip===this.db._novip?r===me.trans?r._promise(e,o,n):$e(function(){return r._promise(e,o,n)},{trans:r,transless:me.transless||me}):function e(t,n,r,i){if(t.idbdb&&(t._state.openComplete||me.letThrough||t._vip)){var s=t._createTransaction(n,r,t._dbSchema);try{s.create(),t._state.PR1398_maxLoop=3}catch(o){return o.name===V.InvalidState&&t.isOpen()&&0<--t._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),t.close({disableAutoOpen:!1}),t.open().then(function(){return e(t,n,r,i)})):Qe(o)}return s._promise(n,function(e,t){return $e(function(){return me.trans=s,i(e,t,s)})}).then(function(e){if("readwrite"===n)try{s.idbtrans.commit()}catch(t){}return"readonly"===n?e:s._completion.then(function(){return e})})}if(t._state.openComplete)return Qe(new H.DatabaseClosed(t._state.dbOpenError));if(!t._state.isBeingOpened){if(!t._state.autoOpen)return Qe(new H.DatabaseClosed);t.open().catch(Z)}return t._state.dbReadyPromise.then(function(){return e(t,n,r,i)})}(this.db,e,[this.name],o);return s&&(u._consoleTask=s,u=u.catch(function(e){return console.trace(e),Qe(e)})),u}finally{a&&Ie()}},bt.prototype.get=function(e,t){var n=this;return e&&e.constructor===Object?this.where(e).first(t):null==e?Qe(new H.Type("Invalid argument to Table.get()")):this._trans("readonly",function(t){return n.core.get({trans:t,key:e}).then(function(e){return n.hook.reading.fire(e)})}).then(t)},bt.prototype.where=function(e){if("string"==typeof e)return new this.db.WhereClause(this,e);if(o(e))return new this.db.WhereClause(this,"[".concat(e.join("+"),"]"));var t=s(e);if(1===t.length)return this.where(t[0]).equals(e[t[0]]);var n=this.schema.indexes.concat(this.schema.primKey).filter(function(e){if(e.compound&&t.every(function(t){return 0<=e.keyPath.indexOf(t)})){for(var n=0;n<t.length;++n)if(-1===t.indexOf(e.keyPath[n]))return!1;return!0}return!1}).sort(function(e,t){return e.keyPath.length-t.keyPath.length})[0];if(n&&this.db._maxKey!==Ge){var r=n.keyPath.slice(0,t.length);return this.where(r).equals(r.map(function(t){return e[t]}))}!n&&ie&&console.warn("The query ".concat(JSON.stringify(e)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(t.join("+"),"]"));var i=this.schema.idxByName;function a(e,t){return 0===ct(e,t)}r=(u=t.reduce(function(t,n){var r=t[0],s=t[1],u=(t=i[n],e[n]);return[r||t,r||!t?st(s,t&&t.multi?function(e){return e=k(e,n),o(e)&&e.some(function(e){return a(u,e)})}:function(e){return a(u,k(e,n))}):s]},[null,null]))[0];var u=u[1];return r?this.where(r.name).equals(e[r.keyPath]).filter(u):n?this.filter(u):this.where(t).equals("")},bt.prototype.filter=function(e){return this.toCollection().and(e)},bt.prototype.count=function(e){return this.toCollection().count(e)},bt.prototype.offset=function(e){return this.toCollection().offset(e)},bt.prototype.limit=function(e){return this.toCollection().limit(e)},bt.prototype.each=function(e){return this.toCollection().each(e)},bt.prototype.toArray=function(e){return this.toCollection().toArray(e)},bt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},bt.prototype.orderBy=function(e){return new this.db.Collection(new this.db.WhereClause(this,o(e)?"[".concat(e.join("+"),"]"):e))},bt.prototype.reverse=function(){return this.toCollection().reverse()},bt.prototype.mapToClass=function(e){var n,r=this.db,i=this.name;function s(){return null!==n&&n.apply(this,arguments)||this}(this.schema.mappedClass=e).prototype instanceof ut&&(function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}(s,n=e),Object.defineProperty(s.prototype,"db",{get:function(){return r},enumerable:!1,configurable:!0}),s.prototype.table=function(){return i},e=s);for(var o=new Set,a=e.prototype;a;a=u(a))Object.getOwnPropertyNames(a).forEach(function(e){return o.add(e)});function c(t){if(!t)return t;var n,r=Object.create(e.prototype);for(n in t)if(!o.has(n))try{r[n]=t[n]}catch(i){}return r}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=c,this.hook("reading",c),e},bt.prototype.defineClass=function(){return this.mapToClass(function(e){a(this,e)})},bt.prototype.add=function(e,t){var n=this,r=this.schema.primKey,i=r.auto,s=r.keyPath,o=e;return s&&i&&(o=at(s)(e)),this._trans("readwrite",function(e){return n.core.mutate({trans:e,type:"add",keys:null!=t?[t]:null,values:[o]})}).then(function(e){return e.numFailures?Ee.reject(e.failures[0]):e.lastResult}).then(function(t){if(s)try{E(e,s,t)}catch(n){}return t})},bt.prototype.upsert=function(e,t){var n=this,r=this.schema.primKey.keyPath;return this._trans("readwrite",function(i){return n.core.get({trans:i,key:e}).then(function(s){var o=null!=s?s:{};return yt(o,t),r&&E(o,r,e),n.core.mutate({trans:i,type:"put",values:[o],keys:[e],upsert:!0,updates:{keys:[e],changeSpecs:[t]}}).then(function(e){return e.numFailures?Ee.reject(e.failures[0]):!!s})})})},bt.prototype.update=function(e,t){return"object"!=typeof e||o(e)?this.where(":id").equals(e).modify(t):void 0===(e=k(e,this.schema.primKey.keyPath))?Qe(new H.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(e).modify(t)},bt.prototype.put=function(e,t){var n=this,r=this.schema.primKey,i=r.auto,s=r.keyPath,o=e;return s&&i&&(o=at(s)(e)),this._trans("readwrite",function(e){return n.core.mutate({trans:e,type:"put",values:[o],keys:null!=t?[t]:null})}).then(function(e){return e.numFailures?Ee.reject(e.failures[0]):e.lastResult}).then(function(t){if(s)try{E(e,s,t)}catch(n){}return t})},bt.prototype.delete=function(e){var t=this;return this._trans("readwrite",function(n){return t.core.mutate({trans:n,type:"delete",keys:[e]}).then(function(n){return dt(t,[e],n)}).then(function(e){return e.numFailures?Ee.reject(e.failures[0]):void 0})})},bt.prototype.clear=function(){var e=this;return this._trans("readwrite",function(t){return e.core.mutate({trans:t,type:"deleteRange",range:ot}).then(function(t){return dt(e,null,t)})}).then(function(e){return e.numFailures?Ee.reject(e.failures[0]):void 0})},bt.prototype.bulkGet=function(e){var t=this;return this._trans("readonly",function(n){return t.core.getMany({keys:e,trans:n}).then(function(e){return e.map(function(e){return t.hook.reading.fire(e)})})})},bt.prototype.bulkAdd=function(e,t,n){var r=this,i=Array.isArray(t)?t:void 0,s=(n=n||(i?void 0:t))?n.allKeys:void 0;return this._trans("readwrite",function(t){var n=(a=r.schema.primKey).auto;if((a=a.keyPath)&&i)throw new H.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(i&&i.length!==e.length)throw new H.InvalidArgument("Arguments objects and keys must have the same length");var o=e.length,a=a&&n?e.map(at(a)):e;return r.core.mutate({trans:t,type:"add",keys:i,values:a,wantResults:s}).then(function(e){var t=e.numFailures,n=e.results,i=e.lastResult;if(e=e.failures,0===t)return s?n:i;throw new z("".concat(r.name,".bulkAdd(): ").concat(t," of ").concat(o," operations failed"),e)})})},bt.prototype.bulkPut=function(e,t,n){var r=this,i=Array.isArray(t)?t:void 0,s=(n=n||(i?void 0:t))?n.allKeys:void 0;return this._trans("readwrite",function(t){var n=(a=r.schema.primKey).auto;if((a=a.keyPath)&&i)throw new H.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(i&&i.length!==e.length)throw new H.InvalidArgument("Arguments objects and keys must have the same length");var o=e.length,a=a&&n?e.map(at(a)):e;return r.core.mutate({trans:t,type:"put",keys:i,values:a,wantResults:s}).then(function(e){var t=e.numFailures,n=e.results,i=e.lastResult;if(e=e.failures,0===t)return s?n:i;throw new z("".concat(r.name,".bulkPut(): ").concat(t," of ").concat(o," operations failed"),e)})})},bt.prototype.bulkUpdate=function(e){var t=this,n=this.core,r=e.map(function(e){return e.key}),i=e.map(function(e){return e.changes}),s=[];return this._trans("readwrite",function(o){return n.getMany({trans:o,keys:r,cache:"clone"}).then(function(a){var u=[],c=[];e.forEach(function(e,n){var r=e.key,i=e.changes,o=a[n];if(o){for(var l=0,h=Object.keys(i);l<h.length;l++){var d=h[l],f=i[d];if(d===t.schema.primKey.keyPath){if(0!==ct(f,r))throw new H.Constraint("Cannot update primary key in bulkUpdate()")}else E(o,d,f)}s.push(n),u.push(r),c.push(o)}});var l=u.length;return n.mutate({trans:o,type:"put",keys:u,values:c,updates:{keys:r,changeSpecs:i}}).then(function(e){var n=e.numFailures,r=e.failures;if(0===n)return l;for(var i=0,o=Object.keys(r);i<o.length;i++){var a,u=o[i],c=s[Number(u)];null!=c&&(a=r[u],delete r[u],r[c]=a)}throw new z("".concat(t.name,".bulkUpdate(): ").concat(n," of ").concat(l," operations failed"),r)})})})},bt.prototype.bulkDelete=function(e){var t=this,n=e.length;return this._trans("readwrite",function(n){return t.core.mutate({trans:n,type:"delete",keys:e}).then(function(n){return dt(t,e,n)})}).then(function(e){var r=e.numFailures,i=e.lastResult;if(e=e.failures,0===r)return i;throw new z("".concat(t.name,".bulkDelete(): ").concat(r," of ").concat(n," operations failed"),e)})},bt);function bt(){}function mt(e){function t(t,r){if(r){for(var i=arguments.length,s=new Array(i-1);--i;)s[i-1]=arguments[i];return n[t].subscribe.apply(null,s),e}if("string"==typeof t)return n[t]}var n={};t.addEventType=a;for(var r=1,i=arguments.length;r<i;++r)a(arguments[r]);return t;function a(e,r,i){if("object"!=typeof e){var u;r=r||ne;var c={subscribers:[],fire:i=i||Z,subscribe:function(e){-1===c.subscribers.indexOf(e)&&(c.subscribers.push(e),c.fire=r(c.fire,e))},unsubscribe:function(e){c.subscribers=c.subscribers.filter(function(t){return t!==e}),c.fire=c.subscribers.reduce(r,i)}};return n[e]=t[e]=c}s(u=e).forEach(function(e){var t=u[e];if(o(t))a(e,u[e][0],u[e][1]);else{if("asap"!==t)throw new H.InvalidArgument("Invalid event config");var n=a(e,J,function(){for(var e=arguments.length,t=new Array(e);e--;)t[e]=arguments[e];n.subscribers.forEach(function(e){w(function(){e.apply(null,t)})})})}})}}function vt(e,t){return p(t).from({prototype:e}),t}function wt(e,t){return!(e.filter||e.algorithm||e.or)&&(t?e.justLimit:!e.replayFilter)}function kt(e,t){e.filter=st(e.filter,t)}function Et(e,t,n){var r=e.replayFilter;e.replayFilter=r?function(){return st(r(),t())}:t,e.justLimit=n&&!r}function _t(e,t){if(e.isPrimKey)return t.primaryKey;var n=t.getIndexByKeyPath(e.index);if(!n)throw new H.Schema("KeyPath "+e.index+" on object store "+t.name+" is not indexed");return n}function xt(e,t,n){var r=_t(e,t.schema);return t.openCursor({trans:n,values:!e.keysOnly,reverse:"prev"===e.dir,unique:!!e.unique,query:{index:r,range:e.range}})}function St(e,t,n,r){var i=e.replayFilter?st(e.filter,e.replayFilter()):e.filter;if(e.or){var s={},o=function(e,n,r){var o,a;i&&!i(n,r,function(e){return n.stop(e)},function(e){return n.fail(e)})||("[object ArrayBuffer]"==(a=""+(o=n.primaryKey))&&(a=""+new Uint8Array(o)),l(s,a)||(s[a]=!0,t(e,n,r)))};return Promise.all([e.or._iterate(o,n),Rt(xt(e,r,n),e.algorithm,o,!e.keysOnly&&e.valueMapper)])}return Rt(xt(e,r,n),st(e.algorithm,i),t,!e.keysOnly&&e.valueMapper)}function Rt(e,t,n,r){var i=Ce(r?function(e,t,i){return n(r(e),t,i)}:n);return e.then(function(e){if(e)return e.start(function(){var n=function(){return e.continue()};t&&!t(e,function(e){return n=e},function(t){e.stop(t),n=Z},function(t){e.fail(t),n=Z})||i(e.value,e,function(e){return n=e}),n()})})}var Pt=(Tt.prototype._read=function(e,t){var n=this._ctx;return n.error?n.table._trans(null,Qe.bind(null,n.error)):n.table._trans("readonly",e).then(t)},Tt.prototype._write=function(e){var t=this._ctx;return t.error?t.table._trans(null,Qe.bind(null,t.error)):t.table._trans("readwrite",e,"locked")},Tt.prototype._addAlgorithm=function(e){var t=this._ctx;t.algorithm=st(t.algorithm,e)},Tt.prototype._iterate=function(e,t){return St(this._ctx,e,t,this._ctx.table.core)},Tt.prototype.clone=function(e){var t=Object.create(this.constructor.prototype),n=Object.create(this._ctx);return e&&a(n,e),t._ctx=n,t},Tt.prototype.raw=function(){return this._ctx.valueMapper=null,this},Tt.prototype.each=function(e){var t=this._ctx;return this._read(function(n){return St(t,e,n,t.table.core)})},Tt.prototype.count=function(e){var t=this;return this._read(function(e){var n=t._ctx,r=n.table.core;if(wt(n,!0))return r.count({trans:e,query:{index:_t(n,r.schema),range:n.range}}).then(function(e){return Math.min(e,n.limit)});var i=0;return St(n,function(){return++i,!1},e,r).then(function(){return i})}).then(e)},Tt.prototype.sortBy=function(e,t){var n=e.split(".").reverse(),r=n[0],i=n.length-1;function s(e,t){return t?s(e[n[t]],t-1):e[r]}var o="next"===this._ctx.dir?1:-1;function a(e,t){return ct(s(e,i),s(t,i))*o}return this.toArray(function(e){return e.sort(a)}).then(t)},Tt.prototype.toArray=function(e){var t=this;return this._read(function(e){var n=t._ctx;if("next"===n.dir&&wt(n,!0)&&0<n.limit){var r=n.valueMapper,i=_t(n,n.table.core.schema);return n.table.core.query({trans:e,limit:n.limit,values:!0,query:{index:i,range:n.range}}).then(function(e){return e=e.result,r?e.map(r):e})}var s=[];return St(n,function(e){return s.push(e)},e,n.table.core).then(function(){return s})},e)},Tt.prototype.offset=function(e){var t=this._ctx;return e<=0||(t.offset+=e,wt(t)?Et(t,function(){var t=e;return function(e,n){return 0===t||(1===t?--t:n(function(){e.advance(t),t=0}),!1)}}):Et(t,function(){var t=e;return function(){return--t<0}})),this},Tt.prototype.limit=function(e){return this._ctx.limit=Math.min(this._ctx.limit,e),Et(this._ctx,function(){var t=e;return function(e,n,r){return--t<=0&&n(r),0<=t}},!0),this},Tt.prototype.until=function(e,t){return kt(this._ctx,function(n,r,i){return!e(n.value)||(r(i),t)}),this},Tt.prototype.first=function(e){return this.limit(1).toArray(function(e){return e[0]}).then(e)},Tt.prototype.last=function(e){return this.reverse().first(e)},Tt.prototype.filter=function(e){var t;return kt(this._ctx,function(t){return e(t.value)}),(t=this._ctx).isMatch=st(t.isMatch,e),this},Tt.prototype.and=function(e){return this.filter(e)},Tt.prototype.or=function(e){return new this.db.WhereClause(this._ctx.table,e,this)},Tt.prototype.reverse=function(){return this._ctx.dir="prev"===this._ctx.dir?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Tt.prototype.desc=function(){return this.reverse()},Tt.prototype.eachKey=function(e){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each(function(t,n){e(n.key,n)})},Tt.prototype.eachUniqueKey=function(e){return this._ctx.unique="unique",this.eachKey(e)},Tt.prototype.eachPrimaryKey=function(e){var t=this._ctx;return t.keysOnly=!t.isMatch,this.each(function(t,n){e(n.primaryKey,n)})},Tt.prototype.keys=function(e){var t=this._ctx;t.keysOnly=!t.isMatch;var n=[];return this.each(function(e,t){n.push(t.key)}).then(function(){return n}).then(e)},Tt.prototype.primaryKeys=function(e){var t=this._ctx;if("next"===t.dir&&wt(t,!0)&&0<t.limit)return this._read(function(e){var n=_t(t,t.table.core.schema);return t.table.core.query({trans:e,values:!1,limit:t.limit,query:{index:n,range:t.range}})}).then(function(e){return e.result}).then(e);t.keysOnly=!t.isMatch;var n=[];return this.each(function(e,t){n.push(t.primaryKey)}).then(function(){return n}).then(e)},Tt.prototype.uniqueKeys=function(e){return this._ctx.unique="unique",this.keys(e)},Tt.prototype.firstKey=function(e){return this.limit(1).keys(function(e){return e[0]}).then(e)},Tt.prototype.lastKey=function(e){return this.reverse().firstKey(e)},Tt.prototype.distinct=function(){var e;if(!(e=(e=this._ctx).index&&e.table.schema.idxByName[e.index])||!e.multi)return this;var t={};return kt(this._ctx,function(e){var n=e.primaryKey.toString();return e=l(t,n),t[n]=!0,!e}),this},Tt.prototype.modify=function(e){var t=this,n=this._ctx;return this._write(function(r){var i,o="function"==typeof e?e:function(t){return yt(t,e)},a=n.table.core,u=(i=a.schema.primaryKey).outbound,c=i.extractKey,l=200;function h(e,t){var n=t.failures;t=t.numFailures,f+=e-t;for(var r=0,i=s(n);r<i.length;r++){var o=i[r];d.push(n[o])}}(i=t.db._options.modifyChunkSize)&&(l="object"==typeof i?i[a.name]||i["*"]||200:i);var d=[],f=0,p=[],y=e===At;return t.clone().primaryKeys().then(function(t){function i(d){var f=Math.min(l,t.length-d),p=t.slice(d,d+f);return(y?Promise.resolve([]):a.getMany({trans:r,keys:p,cache:"immutable"})).then(function(g){var b=[],m=[],v=u?[]:null,w=y?p:[];if(!y)for(var k=0;k<f;++k){var E=g[k],_={value:A(E),primKey:t[d+k]};!1!==o.call(_,_.value,_)&&(null==_.value?w.push(t[d+k]):u||0===ct(c(E),c(_.value))?(m.push(_.value),u&&v.push(t[d+k])):(w.push(t[d+k]),b.push(_.value)))}return Promise.resolve(0<b.length&&a.mutate({trans:r,type:"add",values:b}).then(function(e){for(var t in e.failures)w.splice(parseInt(t),1);h(b.length,e)})).then(function(){return(0<m.length||s&&"object"==typeof e)&&a.mutate({trans:r,type:"put",keys:v,values:m,criteria:s,changeSpec:"function"!=typeof e&&e,isAdditionalChunk:0<d}).then(function(e){return h(m.length,e)})}).then(function(){return(0<w.length||s&&y)&&a.mutate({trans:r,type:"delete",keys:w,criteria:s,isAdditionalChunk:0<d}).then(function(e){return dt(n.table,w,e)}).then(function(e){return h(w.length,e)})}).then(function(){return t.length>d+f&&i(d+l)})})}var s=wt(n)&&n.limit===1/0&&("function"!=typeof e||y)&&{index:n.index,range:n.range};return i(0).then(function(){if(0<d.length)throw new M("Error modifying one or more objects",d,f,p);return t.length})})})},Tt.prototype.delete=function(){var e=this._ctx,t=e.range;return!wt(e)||e.table.schema.yProps||!e.isPrimKey&&3!==t.type?this.modify(At):this._write(function(n){var r=e.table.core.schema.primaryKey,i=t;return e.table.core.count({trans:n,query:{index:r,range:i}}).then(function(t){return e.table.core.mutate({trans:n,type:"deleteRange",range:i}).then(function(e){var n=e.failures;if(e=e.numFailures)throw new M("Could not delete some values",Object.keys(n).map(function(e){return n[e]}),t-e);return t-e})})})},Tt);function Tt(){}var At=function(e,t){return t.value=null};function Ot(e,t){return e<t?-1:e===t?0:1}function It(e,t){return t<e?-1:e===t?0:1}function Bt(e,t,n){return(e=e instanceof Ut?new e.Collection(e):e)._ctx.error=new(n||TypeError)(t),e}function Nt(e){return new e.Collection(e,function(){return Dt("")}).limit(0)}function Ct(e,t,n,r){var i,s,o,a,u,c,l,h=n.length;if(!n.every(function(e){return"string"==typeof e}))return Bt(e,et);function d(e){i="next"===e?function(e){return e.toUpperCase()}:function(e){return e.toLowerCase()},s="next"===e?function(e){return e.toLowerCase()}:function(e){return e.toUpperCase()},o="next"===e?Ot:It;var t=n.map(function(e){return{lower:s(e),upper:i(e)}}).sort(function(e,t){return o(e.lower,t.lower)});a=t.map(function(e){return e.upper}),u=t.map(function(e){return e.lower}),l="next"===(c=e)?"":r}d("next"),(e=new e.Collection(e,function(){return Kt(a[0],u[h-1]+r)}))._ondirectionchange=function(e){d(e)};var f=0;return e._addAlgorithm(function(e,n,r){var i=e.key;if("string"!=typeof i)return!1;var d=s(i);if(t(d,u,f))return!0;for(var p=null,y=f;y<h;++y){var g=function(e,t,n,r,i,s){for(var o=Math.min(e.length,r.length),a=-1,u=0;u<o;++u){var c=t[u];if(c!==r[u])return i(e[u],n[u])<0?e.substr(0,u)+n[u]+n.substr(u+1):i(e[u],r[u])<0?e.substr(0,u)+r[u]+n.substr(u+1):0<=a?e.substr(0,a)+t[a]+n.substr(a+1):null;i(e[u],c)<0&&(a=u)}return o<r.length&&"next"===s?e+n.substr(e.length):o<e.length&&"prev"===s?e.substr(0,n.length):a<0?null:e.substr(0,a)+r[a]+n.substr(a+1)}(i,d,a[y],u[y],o,c);null===g&&null===p?f=y+1:(null===p||0<o(p,g))&&(p=g)}return n(null!==p?function(){e.continue(p+l)}:r),!1}),e}function Kt(e,t,n,r){return{type:2,lower:e,upper:t,lowerOpen:n,upperOpen:r}}function Dt(e){return{type:1,lower:e,upper:e}}var Ut=(Object.defineProperty(jt.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),jt.prototype.between=function(e,t,n,r){n=!1!==n,r=!0===r;try{return 0<this._cmp(e,t)||0===this._cmp(e,t)&&(n||r)&&(!n||!r)?Nt(this):new this.Collection(this,function(){return Kt(e,t,!n,!r)})}catch(i){return Bt(this,Xe)}},jt.prototype.equals=function(e){return null==e?Bt(this,Xe):new this.Collection(this,function(){return Dt(e)})},jt.prototype.above=function(e){return null==e?Bt(this,Xe):new this.Collection(this,function(){return Kt(e,void 0,!0)})},jt.prototype.aboveOrEqual=function(e){return null==e?Bt(this,Xe):new this.Collection(this,function(){return Kt(e,void 0,!1)})},jt.prototype.below=function(e){return null==e?Bt(this,Xe):new this.Collection(this,function(){return Kt(void 0,e,!1,!0)})},jt.prototype.belowOrEqual=function(e){return null==e?Bt(this,Xe):new this.Collection(this,function(){return Kt(void 0,e)})},jt.prototype.startsWith=function(e){return"string"!=typeof e?Bt(this,et):this.between(e,e+Ge,!0,!0)},jt.prototype.startsWithIgnoreCase=function(e){return""===e?this.startsWith(e):Ct(this,function(e,t){return 0===e.indexOf(t[0])},[e],Ge)},jt.prototype.equalsIgnoreCase=function(e){return Ct(this,function(e,t){return e===t[0]},[e],"")},jt.prototype.anyOfIgnoreCase=function(){var e=D.apply(K,arguments);return 0===e.length?Nt(this):Ct(this,function(e,t){return-1!==t.indexOf(e)},e,"")},jt.prototype.startsWithAnyOfIgnoreCase=function(){var e=D.apply(K,arguments);return 0===e.length?Nt(this):Ct(this,function(e,t){return t.some(function(t){return 0===e.indexOf(t)})},e,Ge)},jt.prototype.anyOf=function(){var e=this,t=D.apply(K,arguments),n=this._cmp;try{t.sort(n)}catch(s){return Bt(this,Xe)}if(0===t.length)return Nt(this);var r=new this.Collection(this,function(){return Kt(t[0],t[t.length-1])});r._ondirectionchange=function(r){n="next"===r?e._ascending:e._descending,t.sort(n)};var i=0;return r._addAlgorithm(function(e,r,s){for(var o=e.key;0<n(o,t[i]);)if(++i===t.length)return r(s),!1;return 0===n(o,t[i])||(r(function(){e.continue(t[i])}),!1)}),r},jt.prototype.notEqual=function(e){return this.inAnyRange([[-1/0,e],[e,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},jt.prototype.noneOf=function(){var e=D.apply(K,arguments);if(0===e.length)return new this.Collection(this);try{e.sort(this._ascending)}catch(n){return Bt(this,Xe)}var t=e.reduce(function(e,t){return e?e.concat([[e[e.length-1][1],t]]):[[-1/0,t]]},null);return t.push([e[e.length-1],this.db._maxKey]),this.inAnyRange(t,{includeLowers:!1,includeUppers:!1})},jt.prototype.inAnyRange=function(e,t){var n=this,r=this._cmp,i=this._ascending,s=this._descending,o=this._min,a=this._max;if(0===e.length)return Nt(this);if(!e.every(function(e){return void 0!==e[0]&&void 0!==e[1]&&i(e[0],e[1])<=0}))return Bt(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",H.InvalidArgument);var u,c=!t||!1!==t.includeLowers,l=t&&!0===t.includeUppers,h=i;function d(e,t){return h(e[0],t[0])}try{(u=e.reduce(function(e,t){for(var n=0,i=e.length;n<i;++n){var s=e[n];if(r(t[0],s[1])<0&&0<r(t[1],s[0])){s[0]=o(s[0],t[0]),s[1]=a(s[1],t[1]);break}}return n===i&&e.push(t),e},[])).sort(d)}catch(b){return Bt(this,Xe)}var f=0,p=l?function(e){return 0<i(e,u[f][1])}:function(e){return 0<=i(e,u[f][1])},y=c?function(e){return 0<s(e,u[f][0])}:function(e){return 0<=s(e,u[f][0])},g=p;return(e=new this.Collection(this,function(){return Kt(u[0][0],u[u.length-1][1],!c,!l)}))._ondirectionchange=function(e){h="next"===e?(g=p,i):(g=y,s),u.sort(d)},e._addAlgorithm(function(e,t,r){for(var s,o=e.key;g(o);)if(++f===u.length)return t(r),!1;return!p(s=o)&&!y(s)||(0===n._cmp(o,u[f][1])||0===n._cmp(o,u[f][0])||t(function(){h===i?e.continue(u[f][0]):e.continue(u[f][1])}),!1)}),e},jt.prototype.startsWithAnyOf=function(){var e=D.apply(K,arguments);return e.every(function(e){return"string"==typeof e})?0===e.length?Nt(this):this.inAnyRange(e.map(function(e){return[e,e+Ge]})):Bt(this,"startsWithAnyOf() only works with strings")},jt);function jt(){}function Ft(e){return Ce(function(t){return qt(t),e(t.target.error),!1})}function qt(e){e.stopPropagation&&e.stopPropagation(),e.preventDefault&&e.preventDefault()}var $t="storagemutated",Mt="x-storagemutated-1",zt=mt(null,$t),Vt=(Lt.prototype._lock=function(){return v(!me.global),++this._reculock,1!==this._reculock||me.global||(me.lockOwnerFor=this),this},Lt.prototype._unlock=function(){if(v(!me.global),0==--this._reculock)for(me.global||(me.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var e=this._blockedFuncs.shift();try{Ye(e[1],e[0])}catch(t){}}return this},Lt.prototype._locked=function(){return this._reculock&&me.lockOwnerFor!==this},Lt.prototype.create=function(e){var t=this;if(!this.mode)return this;var n=this.db.idbdb,r=this.db._state.dbOpenError;if(v(!this.idbtrans),!e&&!n)switch(r&&r.name){case"DatabaseClosedError":throw new H.DatabaseClosed(r);case"MissingAPIError":throw new H.MissingAPI(r.message,r);default:throw new H.OpenFailed(r)}if(!this.active)throw new H.TransactionInactive;return v(null===this._completion._state),(e=this.idbtrans=e||(this.db.core||n).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Ce(function(n){qt(n),t._reject(e.error)}),e.onabort=Ce(function(n){qt(n),t.active&&t._reject(new H.Abort(e.error)),t.active=!1,t.on("abort").fire(n)}),e.oncomplete=Ce(function(){t.active=!1,t._resolve(),"mutatedParts"in e&&zt.storagemutated.fire(e.mutatedParts)}),this},Lt.prototype._promise=function(e,t,n){var r=this;if("readwrite"===e&&"readwrite"!==this.mode)return Qe(new H.ReadOnly("Transaction is readonly"));if(!this.active)return Qe(new H.TransactionInactive);if(this._locked())return new Ee(function(i,s){r._blockedFuncs.push([function(){r._promise(e,t,n).then(i,s)},me])});if(n)return $e(function(){var e=new Ee(function(e,n){r._lock();var i=t(e,n,r);i&&i.then&&i.then(e,n)});return e.finally(function(){return r._unlock()}),e._lib=!0,e});var i=new Ee(function(e,n){var i=t(e,n,r);i&&i.then&&i.then(e,n)});return i._lib=!0,i},Lt.prototype._root=function(){return this.parent?this.parent._root():this},Lt.prototype.waitFor=function(e){var t,n=this._root(),r=Ee.resolve(e);n._waitingFor?n._waitingFor=n._waitingFor.then(function(){return r}):(n._waitingFor=r,n._waitingQueue=[],t=n.idbtrans.objectStore(n.storeNames[0]),function e(){for(++n._spinCount;n._waitingQueue.length;)n._waitingQueue.shift()();n._waitingFor&&(t.get(-1/0).onsuccess=e)}());var i=n._waitingFor;return new Ee(function(e,t){r.then(function(t){return n._waitingQueue.push(Ce(e.bind(null,t)))},function(e){return n._waitingQueue.push(Ce(t.bind(null,e)))}).finally(function(){n._waitingFor===i&&(n._waitingFor=null)})})},Lt.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new H.Abort))},Lt.prototype.table=function(e){var t=this._memoizedTables||(this._memoizedTables={});if(l(t,e))return t[e];var n=this.schema[e];if(!n)throw new H.NotFound("Table "+e+" not part of transaction");return(n=new this.db.Table(e,n,this)).core=this.db.core.table(e),t[e]=n},Lt);function Lt(){}function Ht(e,t,n,r,i,s,o,a){return{name:e,keyPath:t,unique:n,multi:r,auto:i,compound:s,src:(n&&!o?"&":"")+(r?"*":"")+(i?"++":"")+Wt(t),type:a}}function Wt(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}function Yt(e,t,n){return{name:e,primKey:t,indexes:n,mappedClass:null,idxByName:(r=function(e){return[e.name,e]},n.reduce(function(e,t,n){return(n=r(t,n))&&(e[n[0]]=n[1]),e},{}))};var r}var Zt=function(e){try{return e.only([[]]),Zt=function(){return[[]]},[[]]}catch(t){return Zt=function(){return Ge},Ge}};function Jt(e){return null==e?function(){}:"string"==typeof e?1===(t=e).split(".").length?function(e){return e[t]}:function(e){return k(e,t)}:function(t){return k(t,e)};var t}function Qt(e){return[].slice.call(e)}var Gt=0;function Xt(e){return null==e?":id":"string"==typeof e?e:"[".concat(e.join("+"),"]")}function en(e,t,n){function r(e){if(3===e.type)return null;if(4===e.type)throw new Error("Cannot convert never type to IDBKeyRange");var n=e.lower,r=e.upper,i=e.lowerOpen;return e=e.upperOpen,void 0===n?void 0===r?null:t.upperBound(r,!!e):void 0===r?t.lowerBound(n,!!i):t.bound(n,r,!!i,!!e)}function i(e){var t,n=e.name;return{name:n,schema:e,mutate:function(e){var t=e.trans,i=e.type,s=e.keys,o=e.values,a=e.range;return new Promise(function(e,u){e=Ce(e);var c=t.objectStore(n),l=null==c.keyPath,h="put"===i||"add"===i;if(!h&&"delete"!==i&&"deleteRange"!==i)throw new Error("Invalid operation type: "+i);var d,f=(s||o||{length:1}).length;if(s&&o&&s.length!==o.length)throw new Error("Given keys array must have same length as given values array.");if(0===f)return e({numFailures:0,failures:{},results:[],lastResult:void 0});function p(e){++b,qt(e)}var y=[],g=[],b=0;if("deleteRange"===i){if(4===a.type)return e({numFailures:b,failures:g,results:[],lastResult:void 0});3===a.type?y.push(d=c.clear()):y.push(d=c.delete(r(a)))}else{var m=(l=h?l?[o,s]:[o,null]:[s,null])[0],v=l[1];if(h)for(var w=0;w<f;++w)y.push(d=v&&void 0!==v[w]?c[i](m[w],v[w]):c[i](m[w])),d.onerror=p;else for(w=0;w<f;++w)y.push(d=c[i](m[w])),d.onerror=p}function k(t){t=t.target.result,y.forEach(function(e,t){return null!=e.error&&(g[t]=e.error)}),e({numFailures:b,failures:g,results:"delete"===i?s:y.map(function(e){return e.result}),lastResult:t})}d.onerror=function(e){p(e),k(e)},d.onsuccess=k})},getMany:function(e){var t=e.trans,r=e.keys;return new Promise(function(e,i){e=Ce(e);for(var s,o=t.objectStore(n),a=r.length,u=new Array(a),c=0,l=0,h=function(t){t=t.target,u[t._pos]=t.result,++l===c&&e(u)},d=Ft(i),f=0;f<a;++f)null!=r[f]&&((s=o.get(r[f]))._pos=f,s.onsuccess=h,s.onerror=d,++c);0===c&&e(u)})},get:function(e){var t=e.trans,r=e.key;return new Promise(function(e,i){e=Ce(e);var s=t.objectStore(n).get(r);s.onsuccess=function(t){return e(t.target.result)},s.onerror=Ft(i)})},query:(t=c,function(e){return new Promise(function(i,s){i=Ce(i);var o,a,u,c=e.trans,l=e.values,h=e.limit,d=e.query,f=h===1/0?void 0:h,p=d.index;if(d=d.range,c=c.objectStore(n),p=p.isPrimaryKey?c:c.index(p.name),d=r(d),0===h)return i({result:[]});t?((f=l?p.getAll(d,f):p.getAllKeys(d,f)).onsuccess=function(e){return i({result:e.target.result})},f.onerror=Ft(s)):(o=0,a=!l&&"openKeyCursor"in p?p.openKeyCursor(d):p.openCursor(d),u=[],a.onsuccess=function(e){var t=a.result;return t?(u.push(l?t.value:t.primaryKey),++o===h?i({result:u}):void t.continue()):i({result:u})},a.onerror=Ft(s))})}),openCursor:function(e){var t=e.trans,i=e.values,s=e.query,o=e.reverse,a=e.unique;return new Promise(function(e,u){e=Ce(e);var c=s.index,l=s.range,h=t.objectStore(n),d=(h=c.isPrimaryKey?h:h.index(c.name),c=o?a?"prevunique":"prev":a?"nextunique":"next",!i&&"openKeyCursor"in h?h.openKeyCursor(r(l),c):h.openCursor(r(l),c));d.onerror=Ft(u),d.onsuccess=Ce(function(n){var r,i,s,o,a=d.result;a?(a.___id=++Gt,a.done=!1,r=a.continue.bind(a),i=(i=a.continuePrimaryKey)&&i.bind(a),s=a.advance.bind(a),o=function(){throw new Error("Cursor not stopped")},a.trans=t,a.stop=a.continue=a.continuePrimaryKey=a.advance=function(){throw new Error("Cursor not started")},a.fail=Ce(u),a.next=function(){var e=this,t=1;return this.start(function(){return t--?e.continue():e.stop()}).then(function(){return e})},a.start=function(e){function t(){if(d.result)try{e()}catch(t){a.fail(t)}else a.done=!0,a.start=function(){throw new Error("Cursor behind last entry")},a.stop()}var n=new Promise(function(e,t){e=Ce(e),d.onerror=Ft(t),a.fail=t,a.stop=function(t){a.stop=a.continue=a.continuePrimaryKey=a.advance=o,e(t)}});return d.onsuccess=Ce(function(e){d.onsuccess=t,t()}),a.continue=r,a.continuePrimaryKey=i,a.advance=s,t(),n},e(a)):e(null)},u)})},count:function(e){var t=e.query,i=e.trans,s=t.index,o=t.range;return new Promise(function(e,t){var a=i.objectStore(n),u=s.isPrimaryKey?a:a.index(s.name);(u=(a=r(o))?u.count(a):u.count()).onsuccess=Ce(function(t){return e(t.target.result)}),u.onerror=Ft(t)})}}}n=(a=n,u=Qt((s=e).objectStoreNames),l={schema:{name:s.name,tables:u.map(function(e){return a.objectStore(e)}).map(function(e){var t=e.keyPath,n=e.autoIncrement,r=o(t),i={};return n={name:e.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:null==t,compound:r,keyPath:t,autoIncrement:n,unique:!0,extractKey:Jt(t)},indexes:Qt(e.indexNames).map(function(t){return e.index(t)}).map(function(e){var t=e.name,n=e.unique,r=e.multiEntry;return e=e.keyPath,r={name:t,compound:o(e),keyPath:e,unique:n,multiEntry:r,extractKey:Jt(e)},i[Xt(e)]=r}),getIndexByKeyPath:function(e){return i[Xt(e)]}},i[":id"]=n.primaryKey,null!=t&&(i[Xt(t)]=n.primaryKey),n})},hasGetAll:0<u.length&&"getAll"in a.objectStore(u[0])&&!("undefined"!=typeof navigator&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}).schema;var s,a,u,c=l.hasGetAll,l=n.tables.map(i),h={};return l.forEach(function(e){return h[e.name]=e}),{stack:"dbcore",transaction:e.transaction.bind(e),table:function(e){if(!h[e])throw new Error("Table '".concat(e,"' not found"));return h[e]},MIN_KEY:-1/0,MAX_KEY:Zt(t),schema:n}}function tn(e,t,r,i){var s=r.IDBKeyRange;return r.indexedDB,{dbcore:(i=en(t,s,i),e.dbcore.reduce(function(e,t){return t=t.create,n(n({},e),t(e))},i))}}function nn(e,t){var n=t.db;t=tn(e._middlewares,n,e._deps,t),e.core=t.dbcore,e.tables.forEach(function(t){var n=t.name;e.core.schema.tables.some(function(e){return e.name===n})&&(t.core=e.core.table(n),e[n]instanceof e.Table&&(e[n].core=t.core))})}function rn(e,t,n,r){n.forEach(function(n){var i=r[n];t.forEach(function(t){var r=function e(t,n){return y(t,n)||(t=u(t))&&e(t,n)}(t,n);(!r||"value"in r&&void 0===r.value)&&(t===e.Transaction.prototype||t instanceof e.Transaction?f(t,n,{get:function(){return this.table(n)},set:function(e){d(this,n,{value:e,writable:!0,configurable:!0,enumerable:!0})}}):t[n]=new e.Table(n,i))})})}function sn(e,t){t.forEach(function(t){for(var n in t)t[n]instanceof e.Table&&delete t[n]})}function on(e,t){return e._cfg.version-t._cfg.version}function an(e,t,n,r){var i=e._dbSchema;n.objectStoreNames.contains("$meta")&&!i.$meta&&(i.$meta=Yt("$meta",yn("")[0],[]),e._storeNames.push("$meta"));var o=e._createTransaction("readwrite",e._storeNames,i);o.create(n),o._completion.catch(r);var a=o._reject.bind(o),u=me.transless||me;$e(function(){return me.trans=o,me.transless=u,0!==t?(nn(e,n),c=t,((r=o).storeNames.includes("$meta")?r.table("$meta").get("version").then(function(e){return null!=e?e:c}):Ee.resolve(c)).then(function(t){return i=t,a=o,u=n,c=[],t=(r=e)._versions,l=r._dbSchema=fn(0,r.idbdb,u),0!==(t=t.filter(function(e){return e._cfg.version>=i})).length?(t.forEach(function(e){c.push(function(){var t=l,n=e._cfg.dbschema;pn(r,t,u),pn(r,n,u),l=r._dbSchema=n;var o=cn(t,n);o.add.forEach(function(e){ln(u,e[0],e[1].primKey,e[1].indexes)}),o.change.forEach(function(e){if(e.recreate)throw new H.Upgrade("Not yet support for changing primary key");var t=u.objectStore(e.name);e.add.forEach(function(e){return dn(t,e)}),e.change.forEach(function(e){t.deleteIndex(e.name),dn(t,e)}),e.del.forEach(function(e){return t.deleteIndex(e)})});var c=e._cfg.contentUpgrade;if(c&&e._cfg.version>i){nn(r,u),a._memoizedTables={};var h=_(n);o.del.forEach(function(e){h[e]=t[e]}),sn(r,[r.Transaction.prototype]),rn(r,[r.Transaction.prototype],s(h),h),a.schema=h;var d,f=U(c);return f&&Me(),o=Ee.follow(function(){var e;(d=c(a))&&f&&(e=ze.bind(null,null),d.then(e,e))}),d&&"function"==typeof d.then?Ee.resolve(d):o.then(function(){return d})}}),c.push(function(t){var n,i,s=e._cfg.dbschema;n=s,i=t,[].slice.call(i.db.objectStoreNames).forEach(function(e){return null==n[e]&&i.db.deleteObjectStore(e)}),sn(r,[r.Transaction.prototype]),rn(r,[r.Transaction.prototype],r._storeNames,r._dbSchema),a.schema=r._dbSchema}),c.push(function(t){r.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(r.idbdb.version/10)===e._cfg.version?(r.idbdb.deleteObjectStore("$meta"),delete r._dbSchema.$meta,r._storeNames=r._storeNames.filter(function(e){return"$meta"!==e})):t.objectStore("$meta").put(e._cfg.version,"version"))})}),function e(){return c.length?Ee.resolve(c.shift()(a.idbtrans)).then(e):Ee.resolve()}().then(function(){hn(l,u)})):Ee.resolve();var r,i,a,u,c,l}).catch(a)):(s(i).forEach(function(e){ln(n,e,i[e].primKey,i[e].indexes)}),nn(e,n),void Ee.follow(function(){return e.on.populate.fire(o)}).catch(a));var r,c})}function un(e,t){hn(e._dbSchema,t),t.db.version%10!=0||t.objectStoreNames.contains("$meta")||t.db.createObjectStore("$meta").add(Math.ceil(t.db.version/10-1),"version");var n=fn(0,e.idbdb,t);pn(e,e._dbSchema,t);for(var r=0,i=cn(n,e._dbSchema).change;r<i.length;r++){var s=function(e){if(e.change.length||e.recreate)return console.warn("Unable to patch indexes of table ".concat(e.name," because it has changes on the type of index or primary key.")),{value:void 0};var n=t.objectStore(e.name);e.add.forEach(function(t){ie&&console.debug("Dexie upgrade patch: Creating missing index ".concat(e.name,".").concat(t.src)),dn(n,t)})}(i[r]);if("object"==typeof s)return s.value}}function cn(e,t){var n,r={del:[],add:[],change:[]};for(n in e)t[n]||r.del.push(n);for(n in t){var i=e[n],s=t[n];if(i){var o={name:n,def:s,recreate:!1,del:[],add:[],change:[]};if(""+(i.primKey.keyPath||"")!=""+(s.primKey.keyPath||"")||i.primKey.auto!==s.primKey.auto)o.recreate=!0,r.change.push(o);else{var a=i.idxByName,u=s.idxByName,c=void 0;for(c in a)u[c]||o.del.push(c);for(c in u){var l=a[c],h=u[c];l?l.src!==h.src&&o.change.push(h):o.add.push(h)}(0<o.del.length||0<o.add.length||0<o.change.length)&&r.change.push(o)}}else r.add.push([n,s])}return r}function ln(e,t,n,r){var i=e.db.createObjectStore(t,n.keyPath?{keyPath:n.keyPath,autoIncrement:n.auto}:{autoIncrement:n.auto});return r.forEach(function(e){return dn(i,e)}),i}function hn(e,t){s(e).forEach(function(n){t.db.objectStoreNames.contains(n)||(ie&&console.debug("Dexie: Creating missing table",n),ln(t,n,e[n].primKey,e[n].indexes))})}function dn(e,t){e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multi})}function fn(e,t,n){var r={};return b(t.objectStoreNames,0).forEach(function(e){for(var t=n.objectStore(e),i=Ht(Wt(a=t.keyPath),a||"",!0,!1,!!t.autoIncrement,a&&"string"!=typeof a,!0),s=[],o=0;o<t.indexNames.length;++o){var a=(u=t.index(t.indexNames[o])).keyPath,u=Ht(u.name,a,!!u.unique,!!u.multiEntry,!1,a&&"string"!=typeof a,!1);s.push(u)}r[e]=Yt(e,i,s)}),r}function pn(e,t,n){for(var r=n.db.objectStoreNames,s=0;s<r.length;++s){var o=r[s],a=n.objectStore(o);e._hasGetAll="getAll"in a;for(var u=0;u<a.indexNames.length;++u){var c=a.indexNames[u],l=a.index(c).keyPath,h="string"==typeof l?l:"["+b(l).join("+")+"]";!t[o]||(l=t[o].idxByName[h])&&(l.name=c,delete t[o].idxByName[h],t[o].idxByName[c]=l)}}"undefined"!=typeof navigator&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&i.WorkerGlobalScope&&i instanceof i.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(e._hasGetAll=!1)}function yn(e){return e.split(",").map(function(e,t){var n=null===(r=(i=e.split(":"))[1])||void 0===r?void 0:r.trim(),r=(e=i[0].trim()).replace(/([&*]|\+\+)/g,""),i=/^\[/.test(r)?r.match(/^\[(.*)\]$/)[1].split("+"):r;return Ht(r,i||null,/\&/.test(e),/\*/.test(e),/\+\+/.test(e),o(i),0===t,n)})}var gn=(bn.prototype._createTableSchema=Yt,bn.prototype._parseIndexSyntax=yn,bn.prototype._parseStoresSpec=function(e,t){var n=this;s(e).forEach(function(r){if(null!==e[r]){var i=n._parseIndexSyntax(e[r]),s=i.shift();if(!s)throw new H.Schema("Invalid schema for table "+r+": "+e[r]);if(s.unique=!0,s.multi)throw new H.Schema("Primary key cannot be multiEntry*");i.forEach(function(e){if(e.auto)throw new H.Schema("Only primary key can be marked as autoIncrement (++)");if(!e.keyPath)throw new H.Schema("Index must have a name and cannot be an empty string")}),i=n._createTableSchema(r,s,i),t[r]=i}})},bn.prototype.stores=function(e){var t=this.db;this._cfg.storesSource=this._cfg.storesSource?a(this._cfg.storesSource,e):e,e=t._versions;var n={},r={};return e.forEach(function(e){a(n,e._cfg.storesSource),r=e._cfg.dbschema={},e._parseStoresSpec(n,r)}),t._dbSchema=r,sn(t,[t._allTables,t,t.Transaction.prototype]),rn(t,[t._allTables,t,t.Transaction.prototype,this._cfg.tables],s(r),r),t._storeNames=s(r),this},bn.prototype.upgrade=function(e){return this._cfg.contentUpgrade=re(this._cfg.contentUpgrade||Z,e),this},bn);function bn(){}function mn(e,t){var n=e._dbNamesDB;return n||(n=e._dbNamesDB=new rr(nt,{addons:[],indexedDB:e,IDBKeyRange:t})).version(1).stores({dbnames:"name"}),n.table("dbnames")}function vn(e){return e&&"function"==typeof e.databases}function wn(e){return $e(function(){return me.letThrough=!0,e()})}function kn(e){return!("from"in e)}var En=function(e,t){if(!this){var n=new En;return e&&"d"in e&&a(n,e),n}a(this,arguments.length?{d:1,from:e,to:1<arguments.length?t:e}:{d:0})};function _n(e,t,n){var r=ct(t,n);if(!isNaN(r)){if(0<r)throw RangeError();if(kn(e))return a(e,{from:t,to:n,d:1});var i=e.l;if(r=e.r,ct(n,e.from)<0)return i?_n(i,t,n):e.l={from:t,to:n,d:1,l:null,r:null},Pn(e);if(0<ct(t,e.to))return r?_n(r,t,n):e.r={from:t,to:n,d:1,l:null,r:null},Pn(e);ct(t,e.from)<0&&(e.from=t,e.l=null,e.d=r?r.d+1:1),0<ct(n,e.to)&&(e.to=n,e.r=null,e.d=e.l?e.l.d+1:1),n=!e.r,i&&!e.l&&xn(e,i),r&&n&&xn(e,r)}}function xn(e,t){kn(t)||function e(t,n){var r=n.from,i=n.to,s=n.l;n=n.r,_n(t,r,i),s&&e(t,s),n&&e(t,n)}(e,t)}function Sn(e,t){var n=Rn(t),r=n.next();if(r.done)return!1;for(var i=r.value,s=Rn(e),o=s.next(i.from),a=o.value;!r.done&&!o.done;){if(ct(a.from,i.to)<=0&&0<=ct(a.to,i.from))return!0;ct(i.from,a.from)<0?i=(r=n.next(a.from)).value:a=(o=s.next(i.from)).value}return!1}function Rn(e){var t=kn(e)?null:{s:0,n:e};return{next:function(e){for(var n=0<arguments.length;t;)switch(t.s){case 0:if(t.s=1,n)for(;t.n.l&&ct(e,t.n.from)<0;)t={up:t,n:t.n.l,s:1};else for(;t.n.l;)t={up:t,n:t.n.l,s:1};case 1:if(t.s=2,!n||ct(e,t.n.to)<=0)return{value:t.n,done:!1};case 2:if(t.n.r){t.s=3,t={up:t,n:t.n.r,s:0};continue}case 3:t=t.up}return{done:!0}}}}function Pn(e){var t,r,i=((null===(t=e.r)||void 0===t?void 0:t.d)||0)-((null===(r=e.l)||void 0===r?void 0:r.d)||0),s=1<i?"r":i<-1?"l":"";s&&(t="r"==s?"l":"r",r=n({},e),i=e[s],e.from=i.from,e.to=i.to,e[s]=i[s],r[s]=i[t],(e[t]=r).d=Tn(r)),e.d=Tn(e)}function Tn(e){var t=e.r;return e=e.l,(t?e?Math.max(t.d,e.d):t.d:e?e.d:0)+1}function An(e,t){return s(t).forEach(function(n){e[n]?xn(e[n],t[n]):e[n]=function e(t){var n,r,i={};for(n in t)l(t,n)&&(r=t[n],i[n]=!r||"object"!=typeof r||P.has(r.constructor)?r:e(r));return i}(t[n])}),e}function On(e,t){return e.all||t.all||Object.keys(e).some(function(n){return t[n]&&Sn(t[n],e[n])})}h(En.prototype,((j={add:function(e){return xn(this,e),this},addKey:function(e){return _n(this,e,e),this},addKeys:function(e){var t=this;return e.forEach(function(e){return _n(t,e,e)}),this},hasKey:function(e){var t=Rn(this).next(e).value;return t&&ct(t.from,e)<=0&&0<=ct(t.to,e)}})[B]=function(){return Rn(this)},j));var In={},Bn={},Nn=!1;function Cn(e){An(Bn,e),Nn||(Nn=!0,setTimeout(function(){Nn=!1,Kn(Bn,!(Bn={}))},0))}function Kn(e,t){void 0===t&&(t=!1);var n=new Set;if(e.all)for(var r=0,i=Object.values(In);r<i.length;r++)Dn(o=i[r],e,n,t);else for(var s in e){var o,a=/^idb\:\/\/(.*)\/(.*)\//.exec(s);a&&(s=a[1],a=a[2],(o=In["idb://".concat(s,"/").concat(a)])&&Dn(o,e,n,t))}n.forEach(function(e){return e()})}function Dn(e,t,n,r){for(var i=[],s=0,o=Object.entries(e.queries.query);s<o.length;s++){for(var a=o[s],u=a[0],c=[],l=0,h=a[1];l<h.length;l++){var d=h[l];On(t,d.obsSet)?d.subscribers.forEach(function(e){return n.add(e)}):r&&c.push(d)}r&&i.push([u,c])}if(r)for(var f=0,p=i;f<p.length;f++){var y=p[f];u=y[0],c=y[1],e.queries.query[u]=c}}function Un(e){var t=e._state,n=e._deps.indexedDB;if(t.isBeingOpened||e.idbdb)return t.dbReadyPromise.then(function(){return t.dbOpenError?Qe(t.dbOpenError):e});t.isBeingOpened=!0,t.dbOpenError=null,t.openComplete=!1;var r=t.openCanceller,i=Math.round(10*e.verno),o=!1;function a(){if(t.openCanceller!==r)throw new H.DatabaseClosed("db.open() was cancelled")}function u(){return new Ee(function(r,c){if(a(),!n)throw new H.MissingAPI;var l=e.name,f=t.autoSchema||!i?n.open(l):n.open(l,i);if(!f)throw new H.MissingAPI;f.onerror=Ft(c),f.onblocked=Ce(e._fireOnBlocked),f.onupgradeneeded=Ce(function(r){var i;h=f.transaction,t.autoSchema&&!e._options.allowEmptyDB?(f.onerror=qt,h.abort(),f.result.close(),(i=n.deleteDatabase(l)).onsuccess=i.onerror=Ce(function(){c(new H.NoSuchDatabase("Database ".concat(l," doesnt exist")))})):(h.onerror=Ft(c),r=r.oldVersion>Math.pow(2,62)?0:r.oldVersion,d=r<1,e.idbdb=f.result,o&&un(e,h),an(e,r/10,h,c))},c),f.onsuccess=Ce(function(){h=null;var n,a,c,p,y,g=e.idbdb=f.result,m=b(g.objectStoreNames);if(0<m.length)try{var v=g.transaction(1===(p=m).length?p[0]:p,"readonly");if(t.autoSchema)a=g,c=v,(n=e).verno=a.version/10,c=n._dbSchema=fn(0,a,c),n._storeNames=b(a.objectStoreNames,0),rn(n,[n._allTables],s(c),c);else if(pn(e,e._dbSchema,v),((y=cn(fn(0,(y=e).idbdb,v),y._dbSchema)).add.length||y.change.some(function(e){return e.add.length||e.change.length}))&&!o)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),g.close(),i=g.version+1,o=!0,r(u());nn(e,v)}catch(w){}tt.push(e),g.onversionchange=Ce(function(n){t.vcFired=!0,e.on("versionchange").fire(n)}),g.onclose=Ce(function(){e.close({disableAutoOpen:!1})}),d&&(y=e._deps,v=l,g=y.indexedDB,y=y.IDBKeyRange,vn(g)||v===nt||mn(g,y).put({name:v}).catch(Z)),r()},c)}).catch(function(e){switch(null==e?void 0:e.name){case"UnknownError":if(0<t.PR1398_maxLoop)return t.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),u();break;case"VersionError":if(0<i)return i=0,u()}return Ee.reject(e)})}var c,l=t.dbReadyResolve,h=null,d=!1;return Ee.race([r,("undefined"==typeof navigator?Ee.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(e){function t(){return indexedDB.databases().finally(e)}c=setInterval(t,100),t()}).finally(function(){return clearInterval(c)}):Promise.resolve()).then(u)]).then(function(){return a(),t.onReadyBeingFired=[],Ee.resolve(wn(function(){return e.on.ready.fire(e.vip)})).then(function n(){if(0<t.onReadyBeingFired.length){var r=t.onReadyBeingFired.reduce(re,Z);return t.onReadyBeingFired=[],Ee.resolve(wn(function(){return r(e.vip)})).then(n)}})}).finally(function(){t.openCanceller===r&&(t.onReadyBeingFired=null,t.isBeingOpened=!1)}).catch(function(n){t.dbOpenError=n;try{h&&h.abort()}catch(i){}return r===t.openCanceller&&e._close(),Qe(n)}).finally(function(){t.openComplete=!0,l()}).then(function(){var t;return d&&(t={},e.tables.forEach(function(n){n.schema.indexes.forEach(function(r){r.name&&(t["idb://".concat(e.name,"/").concat(n.name,"/").concat(r.name)]=new En(-1/0,[[[]]]))}),t["idb://".concat(e.name,"/").concat(n.name,"/")]=t["idb://".concat(e.name,"/").concat(n.name,"/:dels")]=new En(-1/0,[[[]]])}),zt($t).fire(t),Kn(t,!0)),e})}function jn(e){function t(t){return e.next(t)}var n=i(t),r=i(function(t){return e.throw(t)});function i(e){return function(t){var i=e(t);return t=i.value,i.done?t:t&&"function"==typeof t.then?t.then(n,r):o(t)?Promise.all(t).then(n,r):n(t)}}return i(t)()}function Fn(e,t,n){for(var r=o(e)?e.slice():[e],i=0;i<n;++i)r.push(t);return r}var qn={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(e){return n(n({},e),{table:function(t){var r=e.table(t),i=r.schema,s={},o=[];function a(e,t,r){var i=Xt(e),u=s[i]=s[i]||[],c=null==e?0:"string"==typeof e?1:e.length,l=0<t;return l=n(n({},r),{name:l?"".concat(i,"(virtual-from:").concat(r.name,")"):r.name,lowLevelIndex:r,isVirtual:l,keyTail:t,keyLength:c,extractKey:Jt(e),unique:!l&&r.unique}),u.push(l),l.isPrimaryKey||o.push(l),1<c&&a(2===c?e[0]:e.slice(0,c-1),t+1,r),u.sort(function(e,t){return e.keyTail-t.keyTail}),l}t=a(i.primaryKey.keyPath,0,i.primaryKey),s[":id"]=[t];for(var u=0,c=i.indexes;u<c.length;u++){var l=c[u];a(l.keyPath,0,l)}function h(t){var r,i=t.query.index;return i.isVirtual?n(n({},t),{query:{index:i.lowLevelIndex,range:(r=t.query.range,i=i.keyTail,{type:1===r.type?2:r.type,lower:Fn(r.lower,r.lowerOpen?e.MAX_KEY:e.MIN_KEY,i),lowerOpen:!0,upper:Fn(r.upper,r.upperOpen?e.MIN_KEY:e.MAX_KEY,i),upperOpen:!0})}}):t}return n(n({},r),{schema:n(n({},i),{primaryKey:t,indexes:o,getIndexByKeyPath:function(e){return(e=s[Xt(e)])&&e[0]}}),count:function(e){return r.count(h(e))},query:function(e){return r.query(h(e))},openCursor:function(t){var n=t.query.index,i=n.keyTail,s=n.isVirtual,o=n.keyLength;return s?r.openCursor(h(t)).then(function(e){return e&&a(e)}):r.openCursor(t);function a(n){return Object.create(n,{continue:{value:function(r){null!=r?n.continue(Fn(r,t.reverse?e.MAX_KEY:e.MIN_KEY,i)):t.unique?n.continue(n.key.slice(0,o).concat(t.reverse?e.MIN_KEY:e.MAX_KEY,i)):n.continue()}},continuePrimaryKey:{value:function(t,r){n.continuePrimaryKey(Fn(t,e.MAX_KEY,i),r)}},primaryKey:{get:function(){return n.primaryKey}},key:{get:function(){var e=n.key;return 1===o?e[0]:e.slice(0,o)}},value:{get:function(){return n.value}}})}}})}})}};function $n(e,t,n,r){return n=n||{},r=r||"",s(e).forEach(function(i){var s,o,a;l(t,i)?(s=e[i],o=t[i],"object"==typeof s&&"object"==typeof o&&s&&o?(a=I(s))!==I(o)?n[r+i]=t[i]:"Object"===a?$n(s,o,n,r+i+"."):s!==o&&(n[r+i]=t[i]):s!==o&&(n[r+i]=t[i])):n[r+i]=void 0}),s(t).forEach(function(i){l(e,i)||(n[r+i]=t[i])}),n}function Mn(e,t){return"delete"===t.type?t.keys:t.keys||t.values.map(e.extractKey)}var zn={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(e){return n(n({},e),{table:function(t){var i=e.table(t),s=i.schema.primaryKey;return n(n({},i),{mutate:function(e){var o=me.trans,a=o.table(t).hook,u=a.deleting,c=a.creating,h=a.updating;switch(e.type){case"add":if(c.fire===Z)break;return o._promise("readwrite",function(){return d(e)},!0);case"put":if(c.fire===Z&&h.fire===Z)break;return o._promise("readwrite",function(){return d(e)},!0);case"delete":if(u.fire===Z)break;return o._promise("readwrite",function(){return d(e)},!0);case"deleteRange":if(u.fire===Z)break;return o._promise("readwrite",function(){return function e(t,r,o){return i.query({trans:t,values:!1,query:{index:s,range:r},limit:o}).then(function(i){var s=i.result;return d({type:"delete",keys:s,trans:t}).then(function(i){return 0<i.numFailures?Promise.reject(i.failures[0]):s.length<o?{failures:[],numFailures:0,lastResult:void 0}:e(t,n(n({},r),{lower:s[s.length-1],lowerOpen:!0}),o)})})}(e.trans,e.range,1e4)},!0)}return i.mutate(e);function d(e){var t,o,a,d=me.trans,f=e.keys||Mn(s,e);if(!f)throw new Error("Keys missing");return"delete"!==(e="add"===e.type||"put"===e.type?n(n({},e),{keys:f}):n({},e)).type&&(e.values=r([],e.values)),e.keys&&(e.keys=r([],e.keys)),t=i,a=f,("add"===(o=e).type?Promise.resolve([]):t.getMany({trans:o.trans,keys:a,cache:"immutable"})).then(function(t){var n=f.map(function(n,r){var i,o,a,f=t[r],p={onerror:null,onsuccess:null};return"delete"===e.type?u.fire.call(p,n,f,d):"add"===e.type||void 0===f?(i=c.fire.call(p,n,e.values[r],d),null==n&&null!=i&&(e.keys[r]=n=i,s.outbound||E(e.values[r],s.keyPath,n))):(i=$n(f,e.values[r]),(o=h.fire.call(p,i,n,f,d))&&(a=e.values[r],Object.keys(o).forEach(function(e){l(a,e)?a[e]=o[e]:E(a,e,o[e])}))),p});return i.mutate(e).then(function(r){for(var i=r.failures,s=r.results,o=r.numFailures,a=(r=r.lastResult,0);a<f.length;++a){var u=(s||f)[a],c=n[a];null==u?c.onerror&&c.onerror(i[a]):c.onsuccess&&c.onsuccess("put"===e.type&&t[a]?e.values[a]:u)}return{failures:i,results:s,numFailures:o,lastResult:r}}).catch(function(e){return n.forEach(function(t){return t.onerror&&t.onerror(e)}),Promise.reject(e)})})}}})}})}};function Vn(e,t,n){try{if(!t)return null;if(t.keys.length<e.length)return null;for(var r=[],i=0,s=0;i<t.keys.length&&s<e.length;++i)0===ct(t.keys[i],e[s])&&(r.push(n?A(t.values[i]):t.values[i]),++s);return r.length===e.length?r:null}catch(o){return null}}var Ln={stack:"dbcore",level:-1,create:function(e){return{table:function(t){var r=e.table(t);return n(n({},r),{getMany:function(e){if(!e.cache)return r.getMany(e);var t=Vn(e.keys,e.trans._cache,"clone"===e.cache);return t?Ee.resolve(t):r.getMany(e).then(function(t){return e.trans._cache={keys:e.keys,values:"clone"===e.cache?A(t):t},t})},mutate:function(e){return"add"!==e.type&&(e.trans._cache=null),r.mutate(e)}})}}}};function Hn(e,t){return"readonly"===e.trans.mode&&!!e.subscr&&!e.trans.explicit&&"disabled"!==e.trans.db._options.cache&&!t.schema.primaryKey.outbound}function Wn(e,t){switch(e){case"query":return t.values&&!t.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var Yn={stack:"dbcore",level:0,name:"Observability",create:function(e){var t=e.schema.name,r=new En(e.MIN_KEY,e.MAX_KEY);return n(n({},e),{transaction:function(t,n,r){if(me.subscr&&"readonly"!==n)throw new H.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(me.querier));return e.transaction(t,n,r)},table:function(i){var a=e.table(i),u=a.schema,c=u.primaryKey,l=u.indexes,h=c.extractKey,d=c.outbound,f=c.autoIncrement&&l.filter(function(e){return e.compound&&e.keyPath.includes(c.keyPath)}),p=n(n({},a),{mutate:function(n){function s(e){return e="idb://".concat(t,"/").concat(i,"/").concat(e),y[e]||(y[e]=new En)}var l,h,d,p=n.trans,y=n.mutatedParts||(n.mutatedParts={}),g=s(""),b=s(":dels"),m=n.type,v=(k="deleteRange"===n.type?[n.range]:"delete"===n.type?[n.keys]:n.values.length<50?[Mn(c,n).filter(function(e){return e}),n.values]:[])[0],w=k[1],k=n.trans._cache;return o(v)?(g.addKeys(v),(k="delete"===m||v.length===w.length?Vn(v,k):null)||b.addKeys(v),(k||w)&&(l=s,h=k,d=w,u.indexes.forEach(function(e){var t=l(e.name||"");function n(t){return null!=t?e.extractKey(t):null}function r(n){return e.multiEntry&&o(n)?n.forEach(function(e){return t.addKey(e)}):t.addKey(n)}(h||d).forEach(function(e,t){var i=h&&n(h[t]);0!==ct(i,t=d&&n(d[t]))&&(null!=i&&r(i),null!=t&&r(t))})}))):v?(w={from:null!==(w=v.lower)&&void 0!==w?w:e.MIN_KEY,to:null!==(w=v.upper)&&void 0!==w?w:e.MAX_KEY},b.add(w),g.add(w)):(g.add(r),b.add(r),u.indexes.forEach(function(e){return s(e.name).add(r)})),a.mutate(n).then(function(e){return!v||"add"!==n.type&&"put"!==n.type||(g.addKeys(e.results),f&&f.forEach(function(t){for(var r=n.values.map(function(e){return t.extractKey(e)}),i=t.keyPath.findIndex(function(e){return e===c.keyPath}),o=0,a=e.results.length;o<a;++o)r[o][i]=e.results[o];s(t.name).addKeys(r)})),p.mutatedParts=An(p.mutatedParts||{},y),e})}}),y={get:function(e){return[c,new En(e.key)]},getMany:function(e){return[c,(new En).addKeys(e.keys)]},count:l=function(t){t=(n=t.query).index;var n=n.range;return[t,new En(null!==(t=n.lower)&&void 0!==t?t:e.MIN_KEY,null!==(n=n.upper)&&void 0!==n?n:e.MAX_KEY)]},query:l,openCursor:l};return s(y).forEach(function(e){p[e]=function(s){var o=!!(p=me.subscr),u=Hn(me,a)&&Wn(e,s)?s.obsSet={}:p;if(o){var c=function(e){return e="idb://".concat(t,"/").concat(i,"/").concat(e),u[e]||(u[e]=new En)},l=c(""),f=c(":dels"),p=(o=(p=y[e](s))[0],p[1]);if(("query"===e&&o.isPrimaryKey&&!s.values?f:c(o.name||"")).add(p),!o.isPrimaryKey){if("count"!==e){var g="query"===e&&d&&s.values&&a.query(n(n({},s),{values:!1}));return a[e].apply(this,arguments).then(function(t){if("query"===e){if(d&&s.values)return g.then(function(e){return e=e.result,l.addKeys(e),t});var n=s.values?t.result.map(h):t.result;(s.values?l:f).addKeys(n)}else if("openCursor"===e){var r=t,i=s.values;return r&&Object.create(r,{key:{get:function(){return f.addKey(r.primaryKey),r.key}},primaryKey:{get:function(){var e=r.primaryKey;return f.addKey(e),e}},value:{get:function(){return i&&l.addKey(r.primaryKey),r.value}}})}return t})}f.add(r)}}return a[e].apply(this,arguments)}}),p}})}};function Zn(e,t,r){if(0===r.numFailures)return t;if("deleteRange"===t.type)return null;var i=t.keys?t.keys.length:"values"in t&&t.values?t.values.length:1;return r.numFailures===i?null:(t=n({},t),o(t.keys)&&(t.keys=t.keys.filter(function(e,t){return!(t in r.failures)})),"values"in t&&o(t.values)&&(t.values=t.values.filter(function(e,t){return!(t in r.failures)})),t)}function Jn(e,t){return n=e,(void 0===(r=t).lower||(r.lowerOpen?0<ct(n,r.lower):0<=ct(n,r.lower)))&&(void 0===t.upper||(t.upperOpen?ct(e,t.upper)<0:ct(e,t.upper)<=0));var n,r}function Qn(e,t,n,r,i,s){if(!n||0===n.length)return e;var a=t.query.index,u=a.multiEntry,c=t.query.range,l=r.schema.primaryKey.extractKey,h=a.extractKey,d=(a.lowLevelIndex||a).extractKey;return(n=n.reduce(function(e,n){var r=e,i=[];if("add"===n.type||"put"===n.type)for(var s=new En,a=n.values.length-1;0<=a;--a){var d,f=n.values[a],p=l(f);s.hasKey(p)||(d=h(f),(u&&o(d)?d.some(function(e){return Jn(e,c)}):Jn(d,c))&&(s.addKey(p),i.push(f)))}switch(n.type){case"add":var y=(new En).addKeys(t.values?e.map(function(e){return l(e)}):e);r=e.concat(t.values?i.filter(function(e){return e=l(e),!y.hasKey(e)&&(y.addKey(e),!0)}):i.map(function(e){return l(e)}).filter(function(e){return!y.hasKey(e)&&(y.addKey(e),!0)}));break;case"put":var g=(new En).addKeys(n.values.map(function(e){return l(e)}));r=e.filter(function(e){return!g.hasKey(t.values?l(e):e)}).concat(t.values?i:i.map(function(e){return l(e)}));break;case"delete":var b=(new En).addKeys(n.keys);r=e.filter(function(e){return!b.hasKey(t.values?l(e):e)});break;case"deleteRange":var m=n.range;r=e.filter(function(e){return!Jn(l(e),m)})}return r},e))===e?e:(n.sort(function(e,t){return ct(d(e),d(t))||ct(l(e),l(t))}),t.limit&&t.limit<1/0&&(n.length>t.limit?n.length=t.limit:e.length===t.limit&&n.length<t.limit&&(i.dirty=!0)),s?Object.freeze(n):n)}function Gn(e,t){return 0===ct(e.lower,t.lower)&&0===ct(e.upper,t.upper)&&!!e.lowerOpen==!!t.lowerOpen&&!!e.upperOpen==!!t.upperOpen}function Xn(e,t){return function(e,t,n,r){if(void 0===e)return void 0!==t?-1:0;if(void 0===t)return 1;if(0===(t=ct(e,t))){if(n&&r)return 0;if(n)return 1;if(r)return-1}return t}(e.lower,t.lower,e.lowerOpen,t.lowerOpen)<=0&&0<=function(e,t,n,r){if(void 0===e)return void 0!==t?1:0;if(void 0===t)return-1;if(0===(t=ct(e,t))){if(n&&r)return 0;if(n)return-1;if(r)return 1}return t}(e.upper,t.upper,e.upperOpen,t.upperOpen)}function er(e,t,n,r){e.subscribers.add(n),r.addEventListener("abort",function(){var r,i;e.subscribers.delete(n),0===e.subscribers.size&&(r=e,i=t,setTimeout(function(){0===r.subscribers.size&&C(i,r)},3e3))})}var tr={stack:"dbcore",level:0,name:"Cache",create:function(e){var t=e.schema.name;return n(n({},e),{transaction:function(n,r,i){var s,o,a=e.transaction(n,r,i);return"readwrite"===r&&(o=(s=new AbortController).signal,i=function(i){return function(){if(s.abort(),"readwrite"===r){for(var o=new Set,u=0,c=n;u<c.length;u++){var l=c[u],h=In["idb://".concat(t,"/").concat(l)];if(h){var d=e.table(l),f=h.optimisticOps.filter(function(e){return e.trans===a});if(a._explicit&&i&&a.mutatedParts)for(var p=0,y=Object.values(h.queries.query);p<y.length;p++)for(var g=0,b=(w=y[p]).slice();g<b.length;g++)On((k=b[g]).obsSet,a.mutatedParts)&&(C(w,k),k.subscribers.forEach(function(e){return o.add(e)}));else if(0<f.length){h.optimisticOps=h.optimisticOps.filter(function(e){return e.trans!==a});for(var m=0,v=Object.values(h.queries.query);m<v.length;m++)for(var w,k,E,_=0,x=(w=v[m]).slice();_<x.length;_++)null!=(k=x[_]).res&&a.mutatedParts&&(i&&!k.dirty?(E=Object.isFrozen(k.res),E=Qn(k.res,k.req,f,d,k,E),k.dirty?(C(w,k),k.subscribers.forEach(function(e){return o.add(e)})):E!==k.res&&(k.res=E,k.promise=Ee.resolve({result:E}))):(k.dirty&&C(w,k),k.subscribers.forEach(function(e){return o.add(e)})))}}}o.forEach(function(e){return e()})}}},a.addEventListener("abort",i(!1),{signal:o}),a.addEventListener("error",i(!1),{signal:o}),a.addEventListener("complete",i(!0),{signal:o})),a},table:function(r){var i=e.table(r),s=i.schema.primaryKey;return n(n({},i),{mutate:function(e){var o=me.trans;if(s.outbound||"disabled"===o.db._options.cache||o.explicit||"readwrite"!==o.idbtrans.mode)return i.mutate(e);var a=In["idb://".concat(t,"/").concat(r)];return a?(o=i.mutate(e),"add"!==e.type&&"put"!==e.type||!(50<=e.values.length||Mn(s,e).some(function(e){return null==e}))?(a.optimisticOps.push(e),e.mutatedParts&&Cn(e.mutatedParts),o.then(function(t){0<t.numFailures&&(C(a.optimisticOps,e),(t=Zn(0,e,t))&&a.optimisticOps.push(t),e.mutatedParts&&Cn(e.mutatedParts))}),o.catch(function(){C(a.optimisticOps,e),e.mutatedParts&&Cn(e.mutatedParts)})):o.then(function(t){var r=Zn(0,n(n({},e),{values:e.values.map(function(e,r){var i;return t.failures[r]||E(e=null!==(i=s.keyPath)&&void 0!==i&&i.includes(".")?A(e):n({},e),s.keyPath,t.results[r]),e})}),t);a.optimisticOps.push(r),queueMicrotask(function(){return e.mutatedParts&&Cn(e.mutatedParts)})}),o):i.mutate(e)},query:function(e){if(!Hn(me,i)||!Wn("query",e))return i.query(e);var n="immutable"===(null===(a=me.trans)||void 0===a?void 0:a.db._options.cache),s=(c=me).requery,o=c.signal,a=function(e,t,n,r){var i=In["idb://".concat(e,"/").concat(t)];if(!i)return[];if(!(t=i.queries[n]))return[null,!1,i,null];var s=t[(r.query?r.query.index.name:null)||""];if(!s)return[null,!1,i,null];switch(n){case"query":var o=s.find(function(e){return e.req.limit===r.limit&&e.req.values===r.values&&Gn(e.req.query.range,r.query.range)});return o?[o,!0,i,s]:[s.find(function(e){return("limit"in e.req?e.req.limit:1/0)>=r.limit&&(!r.values||e.req.values)&&Xn(e.req.query.range,r.query.range)}),!1,i,s];case"count":return[o=s.find(function(e){return Gn(e.req.query.range,r.query.range)}),!!o,i,s]}}(t,r,"query",e),u=a[0],c=a[1],l=a[2],h=a[3];return u&&c?u.obsSet=e.obsSet:(c=i.query(e).then(function(e){var t=e.result;if(u&&(u.res=t),n){for(var r=0,i=t.length;r<i;++r)Object.freeze(t[r]);Object.freeze(t)}else e.result=A(t);return e}).catch(function(e){return h&&u&&C(h,u),Promise.reject(e)}),u={obsSet:e.obsSet,promise:c,subscribers:new Set,type:"query",req:e,dirty:!1},h?h.push(u):(h=[u],(l=l||(In["idb://".concat(t,"/").concat(r)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[e.query.index.name||""]=h)),er(u,h,s,o),u.promise.then(function(t){return{result:Qn(t.result,e,null==l?void 0:l.optimisticOps,i,u,n)}})}})}})}};function nr(e,t){return new Proxy(e,{get:function(e,n,r){return"db"===n?t:Reflect.get(e,n,r)}})}var rr=(ir.prototype.version=function(e){if(isNaN(e)||e<.1)throw new H.Type("Given version is not a positive number");if(e=Math.round(10*e)/10,this.idbdb||this._state.isBeingOpened)throw new H.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,e);var t=this._versions,n=t.filter(function(t){return t._cfg.version===e})[0];return n||(n=new this.Version(e),t.push(n),t.sort(on),n.stores({}),this._state.autoSchema=!1,n)},ir.prototype._whenReady=function(e){var t=this;return this.idbdb&&(this._state.openComplete||me.letThrough||this._vip)?e():new Ee(function(e,n){if(t._state.openComplete)return n(new H.DatabaseClosed(t._state.dbOpenError));if(!t._state.isBeingOpened){if(!t._state.autoOpen)return void n(new H.DatabaseClosed);t.open().catch(Z)}t._state.dbReadyPromise.then(e,n)}).then(e)},ir.prototype.use=function(e){var t=e.stack,n=e.create,r=e.level,i=e.name;return i&&this.unuse({stack:t,name:i}),(e=this._middlewares[t]||(this._middlewares[t]=[])).push({stack:t,create:n,level:null==r?10:r,name:i}),e.sort(function(e,t){return e.level-t.level}),this},ir.prototype.unuse=function(e){var t=e.stack,n=e.name,r=e.create;return t&&this._middlewares[t]&&(this._middlewares[t]=this._middlewares[t].filter(function(e){return r?e.create!==r:!!n&&e.name!==n})),this},ir.prototype.open=function(){var e=this;return Ye(be,function(){return Un(e)})},ir.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var e=this._state,t=tt.indexOf(this);if(0<=t&&tt.splice(t,1),this.idbdb){try{this.idbdb.close()}catch(n){}this.idbdb=null}e.isBeingOpened||(e.dbReadyPromise=new Ee(function(t){e.dbReadyResolve=t}),e.openCanceller=new Ee(function(t,n){e.cancelOpen=n}))},ir.prototype.close=function(e){var t=(void 0===e?{disableAutoOpen:!0}:e).disableAutoOpen;e=this._state,t?(e.isBeingOpened&&e.cancelOpen(new H.DatabaseClosed),this._close(),e.autoOpen=!1,e.dbOpenError=new H.DatabaseClosed):(this._close(),e.autoOpen=this._options.autoOpen||e.isBeingOpened,e.openComplete=!1,e.dbOpenError=null)},ir.prototype.delete=function(e){var t=this;void 0===e&&(e={disableAutoOpen:!0});var n=0<arguments.length&&"object"!=typeof arguments[0],r=this._state;return new Ee(function(i,s){function o(){t.close(e);var n=t._deps.indexedDB.deleteDatabase(t.name);n.onsuccess=Ce(function(){var e,n,r;e=t._deps,n=t.name,r=e.indexedDB,e=e.IDBKeyRange,vn(r)||n===nt||mn(r,e).delete(n).catch(Z),i()}),n.onerror=Ft(s),n.onblocked=t._fireOnBlocked}if(n)throw new H.InvalidArgument("Invalid closeOptions argument to db.delete()");r.isBeingOpened?r.dbReadyPromise.then(o):o()})},ir.prototype.backendDB=function(){return this.idbdb},ir.prototype.isOpen=function(){return null!==this.idbdb},ir.prototype.hasBeenClosed=function(){var e=this._state.dbOpenError;return e&&"DatabaseClosed"===e.name},ir.prototype.hasFailed=function(){return null!==this._state.dbOpenError},ir.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(ir.prototype,"tables",{get:function(){var e=this;return s(this._allTables).map(function(t){return e._allTables[t]})},enumerable:!1,configurable:!0}),ir.prototype.transaction=function(){var e=function(e,t,n){var r=arguments.length;if(r<2)throw new H.InvalidArgument("Too few arguments");for(var i=new Array(r-1);--r;)i[r-1]=arguments[r];return n=i.pop(),[e,S(i),n]}.apply(this,arguments);return this._transaction.apply(this,e)},ir.prototype._transaction=function(e,t,n){var r=this,i=me.trans;i&&i.db===this&&-1===e.indexOf("!")||(i=null);var s,o,a=-1!==e.indexOf("?");e=e.replace("!","").replace("?","");try{if(o=t.map(function(e){if("string"!=typeof(e=e instanceof r.Table?e.name:e))throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return e}),"r"==e||e===rt)s=rt;else{if("rw"!=e&&e!=it)throw new H.InvalidArgument("Invalid transaction mode: "+e);s=it}if(i){if(i.mode===rt&&s===it){if(!a)throw new H.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");i=null}i&&o.forEach(function(e){if(i&&-1===i.storeNames.indexOf(e)){if(!a)throw new H.SubTransaction("Table "+e+" not included in parent transaction.");i=null}}),a&&i&&!i.active&&(i=null)}}catch(c){return i?i._promise(null,function(e,t){t(c)}):Qe(c)}var u=function e(t,n,r,i,s){return Ee.resolve().then(function(){var o=me.transless||me,a=t._createTransaction(n,r,t._dbSchema,i);if(a.explicit=!0,o={trans:a,transless:o},i)a.idbtrans=i.idbtrans;else try{a.create(),a.idbtrans._explicit=!0,t._state.PR1398_maxLoop=3}catch(l){return l.name===V.InvalidState&&t.isOpen()&&0<--t._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),t.close({disableAutoOpen:!1}),t.open().then(function(){return e(t,n,r,null,s)})):Qe(l)}var u,c=U(s);return c&&Me(),o=Ee.follow(function(){var e;(u=s.call(a,a))&&(c?(e=ze.bind(null,null),u.then(e,e)):"function"==typeof u.next&&"function"==typeof u.throw&&(u=jn(u)))},o),(u&&"function"==typeof u.then?Ee.resolve(u).then(function(e){return a.active?e:Qe(new H.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):o.then(function(){return u})).then(function(e){return i&&a._resolve(),a._completion.then(function(){return e})}).catch(function(e){return a._reject(e),Qe(e)})})}.bind(null,this,s,o,i,n);return i?i._promise(s,u,"lock"):me.trans?Ye(me.transless,function(){return r._whenReady(u)}):this._whenReady(u)},ir.prototype.table=function(e){if(!l(this._allTables,e))throw new H.InvalidTable("Table ".concat(e," does not exist"));return this._allTables[e]},ir);function ir(e,t){var r=this;this._middlewares={},this.verno=0;var i=ir.dependencies;this._options=t=n({addons:ir.addons,autoOpen:!0,indexedDB:i.indexedDB,IDBKeyRange:i.IDBKeyRange,cache:"cloned"},t),this._deps={indexedDB:t.indexedDB,IDBKeyRange:t.IDBKeyRange},i=t.addons,this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;var s,o,a,u,c,l={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Z,dbReadyPromise:null,cancelOpen:Z,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:t.autoOpen};l.dbReadyPromise=new Ee(function(e){l.dbReadyResolve=e}),l.openCanceller=new Ee(function(e,t){l.cancelOpen=t}),this._state=l,this.name=e,this.on=mt(this,"populate","blocked","versionchange","close",{ready:[re,Z]}),this.once=function(e,t){var n=function(){for(var i=[],s=0;s<arguments.length;s++)i[s]=arguments[s];r.on(e).unsubscribe(n),t.apply(r,i)};return r.on(e,n)},this.on.ready.subscribe=m(this.on.ready.subscribe,function(e){return function(t,n){ir.vip(function(){var i,s=r._state;s.openComplete?(s.dbOpenError||Ee.resolve().then(t),n&&e(t)):s.onReadyBeingFired?(s.onReadyBeingFired.push(t),n&&e(t)):(e(t),i=r,n||e(function e(){i.on.ready.unsubscribe(t),i.on.ready.unsubscribe(e)}))})}}),this.Collection=(s=this,vt(Pt.prototype,function(e,t){this.db=s;var n=ot,r=null;if(t)try{n=t()}catch(o){r=o}var i=e._ctx;e=(t=i.table).hook.reading.fire,this._ctx={table:t,index:i.index,isPrimKey:!i.index||t.schema.primKey.keyPath&&i.index===t.schema.primKey.name,range:n,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:r,or:i.or,valueMapper:e!==J?e:null}})),this.Table=(o=this,vt(gt.prototype,function(e,t,n){this.db=o,this._tx=n,this.name=e,this.schema=t,this.hook=o._allTables[e]?o._allTables[e].hook:mt(null,{creating:[X,Z],reading:[Q,J],updating:[te,Z],deleting:[ee,Z]})})),this.Transaction=(a=this,vt(Vt.prototype,function(e,t,n,r,i){var s=this;"readonly"!==e&&t.forEach(function(e){(e=null===(e=n[e])||void 0===e?void 0:e.yProps)&&(t=t.concat(e.map(function(e){return e.updatesTable})))}),this.db=a,this.mode=e,this.storeNames=t,this.schema=n,this.chromeTransactionDurability=r,this.idbtrans=null,this.on=mt(this,"complete","error","abort"),this.parent=i||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Ee(function(e,t){s._resolve=e,s._reject=t}),this._completion.then(function(){s.active=!1,s.on.complete.fire()},function(e){var t=s.active;return s.active=!1,s.on.error.fire(e),s.parent?s.parent._reject(e):t&&s.idbtrans&&s.idbtrans.abort(),Qe(e)})})),this.Version=(u=this,vt(gn.prototype,function(e){this.db=u,this._cfg={version:e,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(c=this,vt(Ut.prototype,function(e,t,n){if(this.db=c,this._ctx={table:e,index:":id"===t?null:t,or:n},this._cmp=this._ascending=ct,this._descending=function(e,t){return ct(t,e)},this._max=function(e,t){return 0<ct(e,t)?e:t},this._min=function(e,t){return ct(e,t)<0?e:t},this._IDBKeyRange=c._deps.IDBKeyRange,!this._IDBKeyRange)throw new H.MissingAPI})),this.on("versionchange",function(e){0<e.newVersion?console.warn("Another connection wants to upgrade database '".concat(r.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(r.name,"'. Closing db now to resume the delete request.")),r.close({disableAutoOpen:!1})}),this.on("blocked",function(e){!e.newVersion||e.newVersion<e.oldVersion?console.warn("Dexie.delete('".concat(r.name,"') was blocked")):console.warn("Upgrade '".concat(r.name,"' blocked by other connection holding version ").concat(e.oldVersion/10))}),this._maxKey=Zt(t.IDBKeyRange),this._createTransaction=function(e,t,n,i){return new r.Transaction(e,t,n,r._options.chromeTransactionDurability,i)},this._fireOnBlocked=function(e){r.on("blocked").fire(e),tt.filter(function(e){return e.name===r.name&&e!==r&&!e._state.vcFired}).map(function(t){return t.on("versionchange").fire(e)})},this.use(Ln),this.use(tr),this.use(Yn),this.use(qn),this.use(zn);var h=new Proxy(this,{get:function(e,t,n){if("_vip"===t)return!0;if("table"===t)return function(e){return nr(r.table(e),h)};var i=Reflect.get(e,t,n);return i instanceof gt?nr(i,h):"tables"===t?i.map(function(e){return nr(e,h)}):"_createTransaction"===t?function(){return nr(i.apply(this,arguments),h)}:i}});this.vip=h,i.forEach(function(e){return e(r)})}j="undefined"!=typeof Symbol&&"observable"in Symbol?Symbol.observable:"@@observable";var sr,or=(ar.prototype.subscribe=function(e,t,n){return this._subscribe(e&&"function"!=typeof e?e:{next:e,error:t,complete:n})},ar.prototype[j]=function(){return this},ar);function ar(e){this._subscribe=e}try{sr={indexedDB:i.indexedDB||i.mozIndexedDB||i.webkitIndexedDB||i.msIndexedDB,IDBKeyRange:i.IDBKeyRange||i.webkitIDBKeyRange}}catch(pr){sr={indexedDB:null,IDBKeyRange:null}}function ur(e){var t,n=!1,r=new or(function(r){var i,s=U(e),o=!1,a={},u={},c={get closed(){return o},unsubscribe:function(){o||(o=!0,i&&i.abort(),h&&zt.storagemutated.unsubscribe(f))}};r.start&&r.start(c);var h=!1,d=function(){return Je(p)},f=function(e){An(a,e),On(u,a)&&d()},p=function(){var c,p,y;!o&&sr.indexedDB&&(a={},c={},i&&i.abort(),i=new AbortController,y=function(t){var n=Oe();try{s&&Me();var r=$e(e,t);return r=s?r.finally(ze):r}finally{n&&Ie()}}(p={subscr:c,signal:i.signal,requery:d,querier:e,trans:null}),Promise.resolve(y).then(function(e){n=!0,t=e,o||p.signal.aborted||(a={},function(e){for(var t in e)if(l(e,t))return;return 1}(u=c)||h||(zt($t,f),h=!0),Je(function(){return!o&&r.next&&r.next(e)}))},function(e){n=!1,["DatabaseClosedError","AbortError"].includes(null==e?void 0:e.name)||o||Je(function(){o||r.error&&r.error(e)})}))};return setTimeout(d,0),c});return r.hasValue=function(){return n},r.getValue=function(){return t},r}var cr=rr;function lr(e){var t=dr;try{dr=!0,zt.storagemutated.fire(e),Kn(e,!0)}finally{dr=t}}h(cr,n(n({},Y),{delete:function(e){return new cr(e,{addons:[]}).delete()},exists:function(e){return new cr(e,{addons:[]}).open().then(function(e){return e.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(e){try{return n=(t=cr.dependencies).indexedDB,t=t.IDBKeyRange,(vn(n)?Promise.resolve(n.databases()).then(function(e){return e.map(function(e){return e.name}).filter(function(e){return e!==nt})}):mn(n,t).toCollection().primaryKeys()).then(e)}catch(r){return Qe(new H.MissingAPI)}var t,n},defineClass:function(){return function(e){a(this,e)}},ignoreTransaction:function(e){return me.trans?Ye(me.transless,e):e()},vip:wn,async:function(e){return function(){try{var t=jn(e.apply(this,arguments));return t&&"function"==typeof t.then?t:Ee.resolve(t)}catch(n){return Qe(n)}}},spawn:function(e,t,n){try{var r=jn(e.apply(n,t||[]));return r&&"function"==typeof r.then?r:Ee.resolve(r)}catch(i){return Qe(i)}},currentTransaction:{get:function(){return me.trans||null}},waitFor:function(e,t){return t=Ee.resolve("function"==typeof e?cr.ignoreTransaction(e):e).timeout(t||6e4),me.trans?me.trans.waitFor(t):t},Promise:Ee,debug:{get:function(){return ie},set:function(e){se(e)}},derive:p,extend:a,props:h,override:m,Events:mt,on:zt,liveQuery:ur,extendObservabilitySet:An,getByKeyPath:k,setByKeyPath:E,delByKeyPath:function(e,t){"string"==typeof t?E(e,t,void 0):"length"in t&&[].map.call(t,function(t){E(e,t,void 0)})},shallowClone:_,deepClone:A,getObjectDiff:$n,cmp:ct,asap:w,minKey:-1/0,addons:[],connections:tt,errnames:V,dependencies:sr,cache:In,semVer:"4.2.1",version:"4.2.1".split(".").map(function(e){return parseInt(e)}).reduce(function(e,t,n){return e+t/Math.pow(10,2*n)})})),cr.maxKey=Zt(cr.dependencies.IDBKeyRange),"undefined"!=typeof dispatchEvent&&"undefined"!=typeof addEventListener&&(zt($t,function(e){dr||(e=new CustomEvent(Mt,{detail:e}),dr=!0,dispatchEvent(e),dr=!1)}),addEventListener(Mt,function(e){e=e.detail,dr||lr(e)}));var hr,dr=!1,fr=function(){};return"undefined"!=typeof BroadcastChannel&&((fr=function(){(hr=new BroadcastChannel(Mt)).onmessage=function(e){return e.data&&lr(e.data)}})(),"function"==typeof hr.unref&&hr.unref(),zt($t,function(e){dr||hr.postMessage(e)})),"undefined"!=typeof addEventListener&&(addEventListener("pagehide",function(e){if(!rr.disableBfCache&&e.persisted){ie&&console.debug("Dexie: handling persisted pagehide"),null!=hr&&hr.close();for(var t=0,n=tt;t<n.length;t++)n[t].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(e){!rr.disableBfCache&&e.persisted&&(ie&&console.debug("Dexie: handling persisted pageshow"),fr(),lr({all:new En(-1/0,[[]])}))})),Ee.rejectionMapper=function(e,t){return!e||e instanceof q||e instanceof TypeError||e instanceof SyntaxError||!e.name||!W[e.name]?e:(t=new W[e.name](t||e.message,e),"stack"in e&&f(t,"stack",{get:function(){return this.inner.stack}}),t)},se(ie),n(rr,Object.freeze({__proto__:null,Dexie:rr,liveQuery:ur,Entity:ut,cmp:ct,PropModification:ft,replacePrefix:function(e,t){return new ft({replacePrefix:[e,t]})},add:function(e){return new ft({add:e})},remove:function(e){return new ft({remove:e})},default:rr,RangeSet:En,mergeRanges:xn,rangesOverlap:Sn}),{default:rr}),rr}();var Jn=Zn.exports;const Qn=e.getDefaultExportFromCjs(Jn),Gn=Symbol.for("Dexie"),Xn=globalThis[Gn]||(globalThis[Gn]=Qn);if(Qn.semVer!==Xn.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Qn.semVer} and ${Xn.semVer}`);const{liveQuery:er,mergeRanges:tr,rangesOverlap:nr,RangeSet:rr,cmp:ir,Entity:sr,PropModification:or,replacePrefix:ar,add:ur,remove:cr,DexieYProvider:lr}=Xn;var hr=(e,t)=>async(n,r)=>{const i=[];for(const e of n){const t=r.get(e);if(t)for(const n of t)i.push({tagValue:e,eventId:n})}i.length>0&&(t(`Saving ${i.length} events cache entries to database`),await e.bulkPut(i)),n.clear()};var dr=(e,t)=>async(n,r)=>{const i=[];for(const e of n){const t=r.get(e);t&&i.push(t)}i.length>0&&(t(`Saving ${i.length} events cache entries to database`),await e.bulkPut(i)),n.clear()};var fr=(e,t)=>async(n,r)=>{const i=[];for(const e of n){const t=r.get(e);t&&i.push({nip05:e,...t})}i.length&&(t(`Saving ${i.length} NIP-05 cache entries to database`),await e.bulkPut(i)),n.clear()},pr=class extends Xn{profiles;events;eventTags;nip05;lnurl;relayStatus;unpublishedEvents;constructor(e){super(e),this.version(15).stores({profiles:"&pubkey",events:"&id, kind",eventTags:"&tagValue",nip05:"&nip05",lnurl:"&pubkey",relayStatus:"&url",unpublishedEvents:"&id"})}};exports.db=void 0;var yr=e.createDebug2("ndk:dexie-adapter:profiles");var gr=(e,t)=>async(n,r)=>{const i=[];for(const e of n){const t=r.get(e);t&&i.push({url:e,updatedAt:t.updatedAt,lastConnectedAt:t.lastConnectedAt,dontConnectBefore:t.dontConnectBefore})}i.length>0&&(t(`Saving ${i.length} relay status cache entries to database`),await e.bulkPut(i)),n.clear()};function br(e,t){return async(n,r)=>{const i=[];for(const e of n){const t=r.get(e);t&&i.push(t)}i.length>0&&(t(`Saving ${i.length} unpublished events cache entries to database`),await e.bulkPut(i)),n.clear()}}function mr(e,t){const n={};t.forEach(e=>n[e]=!1),this.unpublishedEvents.set(e.id,{id:e.id,event:e.rawEvent(),relays:n});const r=t=>{const n=t.url,i=this.unpublishedEvents.get(e.id);if(!i)return void e.off("publushed",r);i.relays[n]=!0,this.unpublishedEvents.set(e.id,i);const s=Object.values(i.relays).filter(e=>e).length,o=Object.values(i.relays).length-s;(s>=3||0===o)&&(this.unpublishedEvents.delete(e.id),e.off("published",r))};e.on("published",r)}var vr=(e,t)=>async(n,r)=>{const i=[];for(const e of n){const t=r.get(e);t&&i.push({pubkey:e,...t})}i.length&&(t(`Saving ${i.length} zapper cache entries to database`),await e.bulkPut(i)),n.clear()},wr=class{cache;dirtyKeys=new Set;options;debug;indexes;isSet=!1;maxSize=0;constructor(t){this.debug=t.debug,this.options=t,this.maxSize=t.maxSize,t.maxSize>0&&(this.cache=new e.dist.LRUCache({maxSize:t.maxSize}),setInterval(()=>this.dump().catch(console.error),1e4)),this.indexes=new Map}getSet(e){return this.cache?.get(e)}getAllWithFilter(e){const t=new Map;return this.cache?.forEach((n,r)=>{e(r,n)&&t.set(r,n)}),t}get(e){return this.cache?.get(e)}async getWithFallback(e,t){let n=this.get(e);return n||(n=await t.get(e),n&&this.set(e,n)),n}async getManyWithFallback(e,t){const n=[],r=[];for(const i of e){const e=this.get(i);e?n.push(e):r.push(i)}if(n.length>0&&this.debug(`Cache hit for keys ${n.length} and miss for ${r.length} keys`),r.length>0){const e=Date.now(),i=await t.bulkGet(r),s=Date.now();let o=0;for(const t of i)t&&(this.set(t.id,t),n.push(t),o++);this.debug(`Time spent querying database: ${s-e}ms for ${r.length} keys, which added ${o} entries to the cache`)}return n}add(e,t,n=!0){const r=this.get(e)??new Set;r.add(t),this.cache?.set(e,r),n&&this.dirtyKeys.add(e)}set(e,t,n=!0){this.cache?.set(e,t),n&&this.dirtyKeys.add(e);for(const[r,i]of this.indexes.entries()){const n=t[r];if(n){const t=i.get(n)||new Set;t.add(e),i.set(n,t)}}}size(){return this.cache?.size||0}delete(e){this.cache?.delete(e),this.dirtyKeys.add(e)}async dump(){this.dirtyKeys.size>0&&this.cache&&(await this.options.dump(this.dirtyKeys,this.cache),this.dirtyKeys.clear())}addIndex(t){this.indexes.set(t,new e.dist.LRUCache({maxSize:this.options.maxSize}))}getFromIndex(e,t){const n=new Set,r=this.indexes.get(e);if(r){const e=r.get(t);if(e)for(const t of e.values()){const e=this.get(t);e&&n.add(e)}}return n}};function kr(e,t,n){n?.limit&&t.length>n.limit&&(t=t.sort((e,t)=>t.createdAt-e.createdAt).slice(0,n.limit));for(const r of t)Er(e,r,r.relay,n)}function Er(e,n,r,i){try{const s=xn(n.event);if(i&&!t.matchFilter(i,s))return;const o=new Bn(void 0,s),a=r?e.pool.getRelay(r,!1):void 0;o.relay=a,e.eventReceived(o,a,!0)}catch(s){console.error("failed to deserialize event",s)}}exports.default=class{debug;locking=!1;ready=!1;profiles;zappers;nip05s;events;eventTags;relayInfo;unpublishedEvents;warmedUp=!1;warmUpPromise;devMode=!1;saveSig;_onReady;constructor(t={}){var n,r,i;n=t.dbName||"ndk",exports.db=new pr(n),this.debug=t.debug||e.createDebug2("ndk:dexie-adapter"),this.saveSig=t.saveSig||!1,this.profiles=new wr({maxSize:t.profileCacheSize||1e5,dump:(r=exports.db.profiles,i=this.debug,async(e,t)=>{const n=[];for(const r of e){const e=t.get(r);e&&n.push(e)}n.length&&(i(`Saving ${n.length} users to database`),await r.bulkPut(n)),e.clear()}),debug:this.debug}),this.zappers=new wr({maxSize:t.zapperCacheSize||200,dump:vr(exports.db.lnurl,this.debug),debug:this.debug}),this.nip05s=new wr({maxSize:t.nip05CacheSize||1e3,dump:fr(exports.db.nip05,this.debug),debug:this.debug}),this.events=new wr({maxSize:t.eventCacheSize||5e4,dump:dr(exports.db.events,this.debug),debug:this.debug}),this.events.addIndex("pubkey"),this.events.addIndex("kind"),this.eventTags=new wr({maxSize:t.eventTagsCacheSize||1e5,dump:hr(exports.db.eventTags,this.debug),debug:this.debug}),this.relayInfo=new wr({maxSize:500,debug:this.debug,dump:gr(exports.db.relayStatus,this.debug)}),this.unpublishedEvents=new wr({maxSize:5e3,debug:this.debug,dump:br(exports.db.unpublishedEvents,this.debug)});const s=(e,t)=>{const n=Date.now();return t().then(()=>{const t=Date.now();this.debug(e,"took",t-n,"ms")})},o=Date.now();this.warmUpPromise=Promise.allSettled([s("profilesWarmUp",()=>async function(e,t){const n=await t.limit(e.maxSize).toArray();for(const r of n){const t=r;e.set(r.pubkey,t,!1)}yr("Loaded %d profiles from database",e.size())}(this.profiles,exports.db.profiles)),s("zapperWarmUp",()=>async function(e,t){const n=await t.limit(e.maxSize).toArray();for(const r of n)e.set(r.pubkey,{document:r.document,fetchedAt:r.fetchedAt},!1)}(this.zappers,exports.db.lnurl)),s("nip05WarmUp",()=>async function(e,t){const n=await t.limit(e.maxSize).toArray();for(const r of n)e.set(r.nip05,r,!1)}(this.nip05s,exports.db.nip05)),s("relayInfoWarmUp",()=>async function(e,t){const n=await t.limit(e.maxSize).toArray();for(const r of n)e.set(r.url,{url:r.url,updatedAt:r.updatedAt,lastConnectedAt:r.lastConnectedAt,dontConnectBefore:r.dontConnectBefore},!1)}(this.relayInfo,exports.db.relayStatus)),s("unpublishedEventsWarmUp",()=>async function(e,t){await t.each(t=>{e.set(t.event.id,t,!1)})}(this.unpublishedEvents,exports.db.unpublishedEvents)),s("eventsWarmUp",()=>async function(e,t){const n=await t.limit(e.maxSize).toArray();for(const r of n)e.set(r.id,r,!1)}(this.events,exports.db.events)),s("eventTagsWarmUp",()=>async function(e,t){const n=await t.limit(e.maxSize).toArray();for(const r of n)e.add(r.tagValue,r.eventId,!1)}(this.eventTags,exports.db.eventTags))]),this.warmUpPromise.then(()=>{const e=Date.now();this.warmedUp=!0,this.ready=!0,this.locking=!0,this.debug("Warm up completed, time",e-o,"ms"),this._onReady&&this._onReady()})}onReady(e){this._onReady=e}async query(e){if(!this.warmedUp){const t=Date.now();await this.warmUpPromise,this.debug("froze query for",Date.now()-t,"ms",e.filters)}const t=Date.now();e.filters.map(t=>this.processFilter(t,e));const n=Date.now()-t;return n>100&&this.debug("query took",n,"ms",e.filter),[]}async fetchProfile(e){if(!this.profiles)return null;return await this.profiles.getWithFallback(e,exports.db.profiles)}fetchProfileSync(e){if(!this.profiles)return null;return this.profiles.get(e)}async getProfiles(e){if(this.profiles)return this.profiles.getAllWithFilter(e)}saveProfile(e,t){const n=this.profiles.get(e);if(n?.created_at&&t.created_at&&n.created_at>=t.created_at)return;const r=Math.floor(Date.now()/1e3);this.profiles.set(e,{pubkey:e,...t,cachedAt:r}),this.debug("Saved profile for pubkey",e,t)}async loadNip05(e,t=3600){const n=this.nip05s?.get(e);if(n){if(null===n.profile)return n.fetchedAt+1e3*t<Date.now()?"missing":null;try{return JSON.parse(n.profile)}catch(s){return"missing"}}const r=await exports.db.nip05.get({nip05:e});if(!r)return"missing";const i=Date.now();if(null===r.profile)return r.fetchedAt+1e3*t<i?"missing":null;try{return JSON.parse(r.profile)}catch(s){return"missing"}}async saveNip05(e,t){try{const n=t?JSON.stringify(t):null;this.nip05s.set(e,{profile:n,fetchedAt:Date.now()})}catch(n){console.error("Failed to save NIP-05 profile for nip05:",e,n)}}async loadUsersLNURLDoc(e,t=86400,n=3600){const r=this.zappers?.get(e);if(r){if(null===r.document)return r.fetchedAt+1e3*n<Date.now()?"missing":null;try{return JSON.parse(r.document)}catch(o){return"missing"}}const i=await exports.db.lnurl.get({pubkey:e});if(!i)return"missing";const s=Date.now();if(i.fetchedAt+1e3*t<s)return"missing";if(null===i.document)return i.fetchedAt+1e3*n<s?"missing":null;try{return JSON.parse(i.document)}catch(o){return"missing"}}async saveUsersLNURLDoc(e,t){try{const n=t?JSON.stringify(t):null;this.zappers?.set(e,{document:n,fetchedAt:Date.now()})}catch(n){console.error("Failed to save LNURL document for pubkey:",e,n)}}processFilter(e,t){const n={...e};n.limit=void 0;const r=new Set(Object.keys(n||{}));r.delete("since"),r.delete("limit"),r.delete("until");try{if(this.byNip33Query(r,e,t))return;if(this.byAuthors(e,t))return;if(this.byIdsQuery(e,t))return;if(this.byTags(e,t))return;if(this.byKinds(r,e,t))return}catch(i){console.error(i)}}async deleteEventIds(e){e.forEach(e=>this.events.delete(e)),await exports.db.events.where({id:e}).delete()}addUnpublishedEvent=mr.bind(this);getUnpublishedEvents=()=>async function(e){const t=[];return await e.each(e=>{t.push({event:new Bn(void 0,e.event),relays:Object.keys(e.relays),lastTryAt:e.lastTryAt})}),t}(exports.db.unpublishedEvents);discardUnpublishedEvent=e=>async function(e,t){await e.delete(t)}(exports.db.unpublishedEvents,e);async setEvent(e,t,n){if(0===e.kind){if(!this.profiles)return;try{const t=Mn(e);this.saveProfile(e.pubkey,t)}catch{this.debug(`Failed to save profile for pubkey: ${e.pubkey}`)}}let r=!0;if(e.isParamReplaceable()){const t=this.events.get(e.tagId());t&&e.created_at&&t.createdAt>e.created_at&&(r=!1)}if(r){const t={id:e.tagId(),pubkey:e.pubkey,kind:e.kind,createdAt:e.created_at??Date.now(),relay:n?.url,event:e.serialize(this.saveSig,!0)};this.saveSig&&e.sig&&(t.sig=e.sig),this.events.set(e.tagId(),t);const r=function(e){const t=[];if(3===e.kind)return[];for(const n of e.tags)if(1===n[0].length&&(t.push(n),t.length>=10))return[];return t}(e);for(const n of r)this.eventTags.add(n[0]+n[1],e.tagId())}}updateRelayStatus(e,t){const n={url:e,updatedAt:Date.now(),...t};this.relayInfo.set(e,n)}getRelayStatus(e){const t=this.relayInfo.get(e);if(t)return{lastConnectedAt:t.lastConnectedAt,dontConnectBefore:t.dontConnectBefore}}byAuthors(e,t){if(!e.authors)return!1;let n=0;for(const r of e.authors){let i=Array.from(this.events.getFromIndex("pubkey",r));e.kinds&&(i=i.filter(t=>e.kinds?.includes(t.kind))),kr(t,i,e),n+=i.length}return!0}byIdsQuery(e,t){if(e.ids){for(const n of e.ids){const r=this.events.get(n);r&&Er(t,r,r.relay,e)}return!0}return!1}byNip33Query(e,t,n){const r=["#d","authors","kinds"];if(e.size===r.length&&r.every(t=>e.has(t))&&t.kinds&&t.authors){for(const e of t.kinds){if(e>=3e4&&e<4e4)for(const r of t.authors)for(const i of t["#d"]){const s=`${e}:${r}:${i}`,o=this.events.get(s);o&&Er(n,o,o.relay,t)}}return!0}return!1}byTags(e,t){const n=Object.entries(e).filter(([e])=>e.startsWith("#")&&2===e.length).map(([e,t])=>[e[1],t]);if(0===n.length)return!1;for(const[r,i]of n)for(const n of i){const i=r+n,s=this.eventTags.getSet(i);s&&s.forEach(n=>{const r=this.events.get(n);r&&(e.kinds&&!e.kinds.includes(r.kind)||Er(t,r,r.relay,e))})}return!0}byKinds(e,t,n){if(!t.kinds||1!==e.size||!e.has("kinds"))return!1;const r=t.limit||500;let i=0;const s=new Set,o=[...t.kinds].sort((e,t)=>(this.events.indexes.get("kind")?.get(e)?.size||0)-(this.events.indexes.get("kind")?.get(t)?.size||0));for(const a of o){const e=this.events.getFromIndex("kind",a);for(const o of e)if(!s.has(o.id)&&(s.add(o.id),Er(n,o,o.relay,t),i++,i>=r))break;if(i>=r)break}return!0}},exports.foundEvent=Er,exports.foundEvents=kr;
|
|
13
|
-
//# sourceMappingURL=index-
|
|
13
|
+
//# sourceMappingURL=index-DJjGSwXG.cjs.map
|