1var Rp=Object.defineProperty;var xu=e=>{throw TypeError(e)};var Dp=(e,t,r)=>t in e?Rp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var ya=(e,t,r)=>Dp(e,typeof t!="symbol"?t+"":t,r),Ou=(e,t,r)=>t.has(e)||xu("Cannot "+r);var Q=(e,t,r)=>(Ou(e,t,"read from private field"),r?r.call(e):t.get(e)),Le=(e,t,r)=>t.has(e)?xu("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Ue=(e,t,r,n)=>(Ou(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);import{j as ce}from"./jsx-runtime-D_zvdyIk.js";import{g as xp,n as Op,v as Pe}from"./chunk-4N6VE7H7-CYH4PXiQ.js";import{E as rn,u as Ct,n as Tp,e as sc,k as Kp,m as Ap,h as ad,l as Np,A as Br,j as Mp,b as us,g as di,a as Bp,i as Fp,w as Ba,r as Lp,f as Up}from"./get-api-DWzc_bBF.js";import{B as sd,R as wt,J as Et,V as nn}from"./runtime-a9fv597q.js";import{B as Wp,J as an,V as va}from"./runtime-2_b2CLRu.js";import{a as $p}from"./VerificationStatusEnum-BMWjV5ER.js";import{a as Tu}from"./AccountSubscriptionTier-Cz37hh3K.js";import{b as qp,d as Hp,a as Jp,c as jp}from"./UsStateCodeAlpha2-sRkxuwjy.js";import{a as Ke,r as bt,c as Ku}from"./result-BtcenhOc.js";import{f as od,n as zp}from"./form-schema-utils-CKHKKg7G.js";import{u as cd}from"./use-state-ref-0aYGV7fB.js";import{u as ni}from"./use-callback-ref-CJ9SODNh.js";import{M as ud,r as Gp,d as ld,h as dd,g as hd}from"./modal-content-window-title-header-DByhHMtf.js";import{A as Ia}from"./alert-Bsob527P.js";import{j as Fa}from"./form-validation-BmVkRcjs.js";import{B as Do}from"./button-CB2fQLpx.js";import{ar as fd,aF as Vp,o as Yp,N as Qp}from"./types-CeqL-daw.js";import{L as Xp}from"./link-button-Dgv_yPAf.js";const dn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ti=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e<dn.length;e++)ti[dn.charCodeAt(e)]=e;const _t=e=>{let t=e.length*.75,r=0,n,i,a,o;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const u=new ArrayBuffer(t),d=new Uint8Array(u);for(let f=0;f<e.length;f+=4)n=ti[e.charCodeAt(f)],i=ti[e.charCodeAt(f+1)],a=ti[e.charCodeAt(f+2)],o=ti[e.charCodeAt(f+3)],d[r++]=n<<2|i>>4,d[r++]=(i&15)<<4|a>>2,d[r++]=(a&3)<<6|o&63;return u},Ne=e=>{const t=new Uint8Array(e),r=t.length;let n="";for(let i=0;i<r;i+=3)n+=dn[t[i]>>2],n+=dn[(t[i]&3)<<4|t[i+1]>>4],n+=dn[(t[i+1]&15)<<2|t[i+2]>>6],n+=dn[t[i+2]&63];return r%3===2?n=n.substring(0,n.length-1)+"=":r%3===1&&(n=n.substring(0,n.length-2)+"=="),n},pd=e=>e?e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):"",md=e=>{if(!e)return"";let t=e.replace(/-/g,"+").replace(/_/g,"/");const r=4-t.length%4;return r!==4&&(t+="=".repeat(r)),t};class Zp{constructor(t){this.events=new Map,this.anyEvents=new Set,t&&this.addEvents(t)}addEvents(t){return this.addRemoveEvents(!1,t)}on(t,r){return this.manageEventSet(!1,t,r)}onAny(t){return this.manageAnyEventSet(!1,t)}removeEvents(t){return this.addRemoveEvents(!0,t)}off(t,r){return this.manageEventSet(!0,t,r)}offAny(t){return this.manageAnyEventSet(!0,t)}emit(t,r){this.events.forEach((n,i)=>{i===t&&n.forEach(a=>{a(...r)})}),this.anyEvents.forEach(n=>{n({eventName:t,args:r})})}clear(t){t?this.events.forEach((r,n)=>{t===n&&r.clear()}):this.events.clear()}clearAny(){this.anyEvents.clear()}addRemoveEvents(t,r){const n=Object.entries(r).reduce((i,[a,o])=>(i.push(this.manageEventSet(t,a,o)),i),[]);return()=>{n.forEach(i=>i())}}manageEventSet(t,r,n){const i=this.events.get(r)||new Set;return(Array.isArray(n)?n:[n]).forEach(a=>{typeof a=="function"&&(t?i.delete(a):i.add(a))}),this.events.set(r,i),()=>{this.manageEventSet(!t,r,n)}}manageAnyEventSet(t,r){return(Array.isArray(r)?r:[r]).forEach(i=>{typeof i=="function"&&(t?this.anyEvents.delete(i):this.anyEvents.add(i))}),()=>{this.manageAnyEventSet(!t,r)}}}function em(e){return e?pd(btoa(JSON.stringify(e))):""}const Au="last-event-id",so="text/event-stream";class Nu extends Error{}const tm=(e,t)=>{let r="connecting",n=null;const i=new Headers,a=new AbortController,{onOpen:o,onError:u,onMessage:d,onClose:f,onConnectionStateChange:m,appendLastEventIdHeader:y=!1,...g}=t||{},{promise:w,resolve:S}=Ke(),E=M=>{const U=r;U!==M&&(r=M,m==null||m(r,U))},D=M=>{E("closed"),f==null||f(M),S(M),a.signal.aborted||a.abort(M)};return a.signal.addEventListener("abort",()=>{const{reason:M}=a.signal;D(bt(new rn(Ct(M,new Error(`Event-source aborted: ${M}`)))))}),(async()=>{E("connecting");const M=new URL(Tp(e));M.searchParams.set("event-source-id",crypto.randomUUID());const U=await sc(M,{...g,async retry(F,j){return E("connecting"),u==null||u(j),await Np(g.retry,F,j)??n},async init(F){const j=await Kp(g.init,F)||{};return Ap(a,j.signal),{...j,signal:a.signal,headers:ad({accept:so},(j||{}).headers,i)}},async inspect(F,j){if(!F.ok)return bt(new rn(new Error(`Event-source not available from "${F.url}"`),F));const $=F.headers.get("content-type")||"";if(!$.startsWith(so))return bt(new rn(new Nu(`Response content-type is "${$}" instead of "${so}"`)));if(!(F.body instanceof ReadableStream))return bt(new rn(new Nu("Response body is no Readable Stream")));E("connected"),o==null||o(F,j);const V=nm({onId(W){(typeof y=="function"?y(W):y)?i.set(Au,W):i.delete(Au)},onRetry(W){n=W},onMessage:d});try{await F.body.pipeTo(new WritableStream({write(W){V(W)}}),{signal:a.signal})}catch(W){return bt(new rn(Ct(W,new Error(`Event-source stream error: ${W}`)),F))}}});D(U)})(),{close:()=>D(bt(new rn(new Error("Event-source closed")))),getState:()=>r,result:w}},Qn={newLine:10,carriageReturn:13,space:32,colon:58},rm=(e,t)=>
1{const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r},Mu=()=>({data:"",event:"",id:"",retry:void 0}),nm=({onId:e,onRetry:t,onMessage:r})=>{const n=new TextDecoder;let i=Mu(),a,o,u,d=!1;const f=(m,y)=>{if(m.length===0)r==null||r(i),i=Mu();else if(y>0){const g=n.decode(m.subarray(0,y)),w=y+(m[y+1]===Qn.space?2:1),S=n.decode(m.subarray(w));switch(g){case"data":{i.data=i.data?i.data+` 2`+S:S;break}case"event":{i.event=S;break}case"id":{e==null||e(i.id=S);break}case"retry":{const E=parseInt(S,10);isNaN(E)||t==null||t(i.retry=E);break}}}};return m=>{a===void 0?(a=m,o=0,u=-1):a=rm(a,m);const y=a.length;let g=0;for(;o<y;){d&&(a[o]===Qn.newLine&&(g=++o),d=!1);let w=-1;for(;o<y&&w===-1;++o)switch(a[o]){case Qn.colon:u===-1&&(u=o-g);break;case Qn.carriageReturn:d=!0;case Qn.newLine:w=o;break}if(w===-1)break;f(a.subarray(g,w),u),g=o,u=-1}g===y?a=void 0:g!==0&&(a=a.subarray(g),o-=g)}},im=e=>e instanceof TypeError,am="/build/assets/download-service-worker-response-body-test-B_SY1GJM.txt",vC={Month:"MONTH",Year:"YEAR"};function Bu(e){return sm(e)}function sm(e,t){return e}const gC={Trialing:"TRIALING"};function om(e){return cm(e)}function cm(e,t){return e==null?e:{status:e.status==null?void 0:e.status,purchasePriceUsdcCent:e.purchasePriceUsdcCent,period:Bu(e.period),periodAfterCurrentTerm:e.periodAfterCurrentTerm==null?void 0:Bu(e.periodAfterCurrentTerm),createdAt:new Date(e.createdAt),currentTermStart:new Date(e.currentTermStart),currentTermEnd:e.currentTermEnd==null?void 0:new Date(e.currentTermEnd),trialEnd:e.trialEnd==null?void 0:new Date(e.trialEnd)}}function um(e){return lm(e)}function lm(e,t){return e==null?e:{subscription:om(e.subscription),tier:Tu(e.tier),tierAfterCurrentTerm:Tu(e.tierAfterCurrentTerm),discountedByLimeWireOriginal:e.discountedByLimeWireOriginal,discountedByLimeWireOriginalAfterCurrentTerm:e.discountedByLimeWireOriginalAfterCurrentTerm,nextCreditsForYearlySubscription:e.nextCreditsForYearlySubscription==null?void 0:new Date(e.nextCreditsForYearlySubscription),nextCreditsForTrialingSubscription:e.nextCreditsForTrialingSubscription==null?void 0:new Date(e.nextCreditsForTrialingSubscription),nextCreditsForBasicLmwoSubscription:e.nextCreditsForBasicLmwoSubscription==null?void 0:new Date(e.nextCreditsForBasicLmwoSubscription)}}function xo(e){return dm(e)}function dm(e,t){return e==null?e:{downloadUrl:e.downloadUrl==null?void 0:e.downloadUrl,id:e.id,uploadType:e.uploadType,ownerId:e.ownerId,mimeType:e.mimeType==null?void 0:e.mimeType,assetType:e.assetType,assetPurpose:e.assetPurpose==null?void 0:e.assetPurpose,postProcessingStatus:e.postProcessingStatus==null?void 0:e.postProcessingStatus,postProcessingFailureReason:e.postProcessingFailureReason==null?void 0:e.postProcessingFailureReason,childAssetTrackingDocuments:e.childAssetTrackingDocuments==null?void 0:e.childAssetTrackingDocuments.map(xo),childAssetType:e.childAssetType==null?void 0:e.childAssetType,parentAssetTrackingDocumentId:e.parentAssetTrackingDocumentId==null?void 0:e.parentAssetTrackingDocumentId,fileName:e.fileName,fileType:e.fileType,additionalUrls:e.additionalUrls==null?void 0:e.additionalUrls,assetMetaInfo:e.assetMetaInfo==null?void 0:e.assetMetaInfo,sizeInBytes:e.sizeInBytes==null?void 0:e.sizeInBytes,createdDate:new Date(e.createdDate)}}function hm(e){return fm(e)}function fm(e,t){return e==null?e:{credits:e.credits}}function pm(e){return mm(e)}function mm(e,t){return e==null?e:{passphrase:e.passphrase}}function ym(e){return e==null?e:{email:e.email}}function vm(e){return e==null?e:{logoutAllClients:e.logoutAllClients}}function gm(e){return wm(e)}function wm(e,t){return e==null?e:{passphrase:e.passphrase}}function bm(e){return Sm(e)}function Sm(e,t){return e==null?e:{vatNumber:e.vatNumber==null?void 0:e.vatNumber,companyName:e.companyName==null?void 0:e.companyName,firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phoneNumber,addressLine1:e.addressLine1,addressLine2:e.addressLine2==null?void 0:e.addressLine2,postalCode:e.postalCode,city:e.city,usStateCodeAlpha2:e.usStateCodeAlpha2==null?void 0:jp(e.usStateCodeAlpha2),countryCodeAlpha2:Jp(e.countryCodeAlpha2)}}function Em(e){return e==null?e:{vatNumber:e.vatNumber,companyName:e.companyName,firstName:e.firstName,lastName:e.lastName,phoneNumber:e.phoneNumber,addressLine1:e.addressLine1,addressLine2:e.addressLine2,postalCode:e.postalCode,city:e.city,usStateCodeAlpha2:Hp(e.usStateCodeAlpha2),countryCodeAlpha2:qp(e.countryCodeAlpha2)}}function _m(e){return e==null?e:{newEmail:e.newEmail}}function Pm(e){return Im(e)}function Im(e,t){return e==null?e:{newEmail:e.newEmail,oldEmail:e.oldEmail}}function Cm(e){return km(e)}function km(e,t){return e==null?e:{releaseDate:new Date(e.releaseDate),amountLmwr:e.amountLmwr}}const Rm={Managed:"MANAGED"};function Dm(e){return xm(e)}function xm(e,t){return e==null?e:{userId:e.userId,email:e.email,nick:e.nick,name:e.name==null?void 0:e.name,description:e.description==null?void 0:e.description,authorities:e.authorities,level:e.level,verificationStatus:$p(e.verificationStatus),referralCode:e.referralCode,kycPassed:e.kycPassed,billingAddress:e.billingAddress==null?void 0:bm(e.billingAddress),accountSubscription:e.accountSubscription==null?void 0:um(e.accountSubscription),avatarAsset:e.avatarAsset==null?void 0:xo(e.avatarAsset),heroAsset:e.heroAsset==null?void 0:xo(e.heroAsset),twitterHandle:e.twitterHandle==null?void 0:e.twitterHandle,instagramHandle:e.instagramHandle==null?void 0:e.instagramHandle,lmwrReleaseSchedule:e.lmwrReleaseSchedule==null?void 0:e.lmwrReleaseSchedule.map(Cm),paidSubscriptionPlanAllowed:e.paidSubscriptionPlanAllowed,planSelectionShown:e.planSelectionShown,allowUsdcWithdrawals:e.allowUsdcWithdrawals,mintDestinationWalletAddress:e.mintDestinationWalletAddress==null?void 0:e.mintDestinationWalletAddress,userEncryptionKeyType:e.userEncryptionKeyType,totp2faEnabled:e.totp2faEnabled,walletLoginEnabled:e.walletLoginEnabled}}
2function Om(e){return e==null?e:{nick:e.nick,name:e.name,description:e.description,email:e.email,billing_address:Em(e.billingAddress),avatar_asset_id:e.avatarAssetId,hero_asset_id:e.heroAssetId,two_factor_code:e.twoFactorCode,two_factor_code_new_email:e.twoFactorCodeNewEmail,plan_selection_shown:e.planSelectionShown,mint_destination_wallet_address:e.mintDestinationWalletAddress,walletLoginEnabled:e.walletLoginEnabled}}function Tm(e){return Km(e)}function Km(e,t){return e==null?e:{accessToken:e.access_token}}class yd extends Wp{async getPassphraseRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/users/self/passphrase",method:"GET",headers:n,query:r},t);return new an(i,a=>pm(a))}async getPassphrase(t){return await(await this.getPassphraseRaw(t)).value()}async getSelfRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/users/self",method:"GET",headers:n,query:r},t);return new an(i,a=>Dm(a))}
2async getSelf(t){return await(await this.getSelfRaw(t)).value()}async getUserCreditsRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/users/self/credits",method:"GET",headers:n,query:r},t);return new an(i,a=>hm(a))}async getUserCredits(t){return await(await this.getUserCreditsRaw(t)).value()}async issueTwoFaTokenRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/users/self/2fa",method:"POST",headers:n,query:r},t);return new va(i)}async issueTwoFaToken(t){await this.issueTwoFaTokenRaw(t)}async issueTwoFaTokenForEmailRaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/users/2fa",method:"POST",headers:i,query:n,body:ym(t.issueTwoFaTokenForEmailRequest)},r);return new va(a)}async issueTwoFaTokenForEmail(t={},r){await this.issueTwoFaTokenForEmailRaw(t,r)}async logoutRaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/users/logout",method:"POST",headers:i,query:n,body:vm(t.logoutRequest)},r);return new va(a)}async logout(t={},r){await this.logoutRaw(t,r)}async resetPassphraseRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/users/self/passphrase/reset",method:"POST",headers:n,query:r},t);return new an(i,a=>gm(a))}async resetPassphrase(t){return await(await this.resetPassphraseRaw(t)).value()}async updateEmailRaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/users/self/email",method:"POST",headers:i,query:n,body:_m(t.userEmailUpdateRequest)},r);return new an(a,o=>Pm(o))}async updateEmail(t={},r){return await(await this.updateEmailRaw(t,r)).value()}async updateUserRaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/users/self",method:"PATCH",headers:i,query:n,body:Om(t.userUpdateRequest)},r);return new an(a,o=>Tm(o))}async updateUser(t={},r){return await(await this.updateUserRaw(t,r)).value()}async userPingRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/users/ping",method:"GET",headers:n,query:r},t);return new va(i)}async userPing(t){await this.userPingRaw(t)}}const ga="turnstile_required",Am="Verification failed, please start the download again.",Nm=3,Mm=500,Fu=180*1e3;let oc=null;class Bm extends Error{constructor(t="Turnstile challenge was cancelled"){super(t),this.name="TurnstileChallengeCancelledError"}}let oo=null;const wC=e=>{oc=e},Fm=()=>oc,Lm=e=>new Promise(t=>setTimeout(t,e)),Um=async(e,t=oc)=>{let r=await e();if(r.ok||r.error.code!==ga||!t)return r;let n=null;for(let i=0;i<Nm;i++){i&&await Lm(Mm*2**(i-1));const a=oo;if(a){const d=await a;if(d)return bt(d);if(r=await e(),r.ok||r.error.code!==ga)return r;continue}const o=Ke();oo=o.promise;let u=null;try{let d;try{d=await t()}catch(f){if(f instanceof Bm)return u=f,bt(f);n=Ct(f);continue}if(r=await e(d),r.ok||r.error.code!==ga)return r;n=null}finally{oo=null,o.resolve(u)}}return n?(console.error("Turnstile challenge could not be solved:",n),bt(new Br(Am,ga))):r};class vd{constructor(t,r){this.target=t,this.apiOptions=r}start(){var r,n;const t=async i=>{const{data:a}=i,o=this.apiOptions;switch(a.type){case"msgChannelClientApiOptions":{this.target.postMessage({type:"msgChannelServerApiOptions",id:a.id,apiOptions:{basePath:o.basePath,retry:Array.isArray(o.retry)?o.retry:void 0,timeout:o.timeout}});break}case"msgChannelClientApiOptionsInit":{const u=await Mp(o.init,a.apiInput,a.apiInit);this.target.postMessage({type:"msgChannelServerApiOptionsInit",id:a.id,apiOptionsInit:{...u,headers:ad(u.headers),signal:void 0}});break}case"msgChannelClientApiOptionsGetCsrfToken":{this.target.postMessage({type:"msgChannelServerApiOptionsGetCsrfToken",id:a.id,csrfToken:o.csrfFetcher&&await o.csrfFetcher.getCsrfToken()});break}case"msgChannelClientApiOptionsInvalidateCsrfToken":{o.csrfFetcher&&await o.csrfFetcher.invalidateCsrfToken(),this.target.postMessage({type:"msgChannelServerApiOptionsInvalidateCsrfToken",id:a.id});break}case"msgChannelClientApiOptionsFetchedCsrfToken":{this.target.postMessage({type:"msgChannelServerApiOptionsFetchedCsrfToken",id:a.id,csrfToken:o.csrfFetcher&&await o.csrfFetcher.getFetchedCsrfToken()||""});break}case"msgChannelClientApiOptionsGetTurnstileToken":{const u={type:"msgChannelServerApiOptionsGetTurnstileToken",id:a.id},d=Fm();if(d)try{const f=new Promise((m,y)=>{setTimeout(()=>y(new Error(`Turnstile token request timed out after ${Fu}ms`)),Fu)});u.turnstileToken=await Promise.race([d(),f])}catch(f){u.error=Ct(f).message}else u.error="Turnstile challenge handler is not configured";this.target.postMessage(u);break}case"msgChannelClientApiOptionsGetAuthToken":{this.target.postMessage({type:"msgChannelServerApiOptionsGetAuthToken",id:a.id,authToken:o.authFetcher&&await o.authFetcher.getAuthToken()});break}case"msgChannelClientApiOptionsInvalidateAuthToken":{o.authFetcher&&await o.authFetcher.invalidateAuthToken(),this.target.postMessage({type:"msgChannelServerApiOptionsInvalidateAuthToken",id:a.id});break}}};return(n=(r=this.target).start)==null||n.call(r),this.target.addEventListener("message",t),()=>{this.target.removeEventListener("message",t)}}}const co=256,Lu=["encrypt","decrypt"],Wm={ASYMMETRIC_PRIVATE_KEY:{keyFormat:"jwk",keyProperties:{name:"ECDH",namedCurve:"P-256"},keyUsages:["deriveBits","deriveKey"]},"SYMMETRIC_AES-GCM_KEY":{keyFormat:"raw",keyProperties:{name:"AES-GCM",length:co},keyUsages:Lu},"SYMMETRIC_AES-CTR_KEY":{keyFormat:"raw",keyProperties:{name:"AES-CTR",length:co},keyUsages:Lu},WRAPPING_KEY:{keyFormat:"raw",keyProperties:{name:"AES-KW",length:co},keyUsages:["wrapKey","unwrapKey"]},WRAPPED_ASYMMETRIC_PRIVATE_KEY:{keyFormat:"raw",keyProperties:{name:"AES-CTR"},keyUsages:["wrapKey"]}},Uu=new Map,Wu=new Map;class rt{static getKeyProperties(t){return Wm[t]}async createKeyWrappingKey(){const t=rt.getKeyProperties("WRAPPING_KEY");return crypto.subtle.generateKey(t.keyProperties,!0,t.keyUsages)}async createEncryptionAesCryptoKey(t){const r=rt.getKeyProperties(t);return{aesKeyType:t,cryptoKey:await crypto.subtle.generateKey(r.keyProperties,!0,r.keyUsages)}}async deriveEncryptionKeyFromAesKey(t,r){const n=rt.getKeyProperties(t.aesKeyType),i=await crypto.subtle.exportKey("raw",t.cryptoKey),a=await crypto.subtle.importKey("raw",i,"HKDF",!1,["deriveKey"]),o=new TextEncoder;return{aesKeyType:t.aesKeyType,cryptoKey:await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",info:o.encode(r),salt:o.encode("no-salt-because-it-needs-to-be-deterministic")},a,n.keyProperties,!0,n.keyUsages)}}async serializeEncryptionAesCryptoKey({aesKeyType:t,cryptoKey:r}){return{aesKeyType:t,jwk:await crypto.subtle.exportKey("jwk",r)}}async deserializeEncryptionAesCryptoKey({aesKeyType:t,jwk:r}){const n=rt.getKeyProperties(t);return{aesKeyType:t,cryptoKey:await crypto.subtle.importKey("jwk",r,n.keyProperties,!0,n.keyUsages)}}randomSalt(){return crypto.getRandomValues(new Uint8Array(16))}async wrapWithPassphrase(t,r,n){const i=await this.generateWrappingKeyFromPassphrase(t,r),a=this.getWrappingFormat(n);return crypto.subtle.wrapKey(a,n,i,"AES-KW")}async extractPrivateKeyAndWrapWithPassphrase(t,r,n){const i=await this.generateWrappingKeyFromPassphrase(t,r);return this.extractPrivateKeyAndWrapWithWrappingKey(i,n)}async unwrapKeyWithPassphrase(t,r,n,i){const a=`${i}_${t}_${Ne(r)}_${Ne(n)}`,o=Wu.get(a);if(o)return o;const u=await this.generateWrappingKeyFromPassphrase(t,r),{keyFormat:d,keyProperties:f,keyUsages:m}=rt.getKeyProperties(i),y=await crypto.subtle.unwrapKey(d,n,u,"AES-KW",f,!0,m);return Wu.set(a,y),y}async unwrapKeyWithWrappingKey(t,r,n){const{keyFormat:i,keyProperties:a,keyUsages:o}=rt.getKeyProperties(n);return crypto.subtle.unwrapKey(i,r,t,"AES-KW",a,!0,o)}wrapWithWrappingKey(t,r){return crypto.subtle.wrapKey(this.getWrappingFormat(r),r,t,"AES-KW")}async extractPrivateKeyAndWrapWithWrappingKey(t,r){const n=await this.extractPrivateKey(r),i=await crypto.subtle.importKey("raw",_t(n),{name:"AES-CTR"},!0,["wrapKey"]);return crypto.subtle.wrapKey("raw",i,t,"AES-KW")}async encryptAesGcm(t,r,n){const i=await crypto.subtle.encrypt({name:"AES-GCM",iv:n},t.cryptoKey,r);return{iv:n,encryptedData:i}}async encryptAesCtr(t,r,n,i){const a=this.getAesCtrNonce(n,i),o=await crypto.subtle.encrypt({name:"AES-CTR",counter:a,length:40},t.cryptoKey,r),u=i+Math.ceil(r.byteLength/16);return{iv:n,encryptedData:o,newCounter:u}}getAesCtrNonce(t,r){if(t.byteLength!==11)throw new Error("IV must be 11 bytes");if(r<0||r>0xffffffffff||!Number.isInteger(r))throw new Error("Counter must be a non-negative integer not exceeding 40 bits");const n=new ArrayBuffer(16);new Uint8Array(n).set(new Uint8Array(t),0);const a=new DataView(n,11,5);return a.setUint32(0,Math.floor(r/256),!1),a.setUint8(4,r%256),n}decryptAesGcm(t,r,n){return n.byteLength===0?new ArrayBuffer(0):crypto.subtle.decrypt({
2name:"AES-GCM",iv:r},t.cryptoKey,n)}async decryptAesCtr(t,r,n,i){if(i.byteLength==0)return{decryptedData:new ArrayBuffer(0),newCounter:n};const o={name:"AES-CTR",counter:this.getAesCtrNonce(r,n),length:40},u=await crypto.subtle.decrypt(o,t.cryptoKey,i),d=n+Math.ceil(i.byteLength/16);return{decryptedData:u,newCounter:d}}async exportPrivateKey(t){return JSON.stringify(await crypto.subtle.exportKey("jwk",t))}async importPrivateKey(t){const{keyProperties:r}=rt.getKeyProperties("ASYMMETRIC_PRIVATE_KEY");return await crypto.subtle.importKey("jwk",t,r,!0,["deriveKey","deriveBits"])}async generateWrappingKeyFromPassphrase(t,r){const n=`${t}_${Ne(r)}`,i=Uu.get(n);if(i)return i;const a=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),{name:"PBKDF2"},!1,["deriveBits","deriveKey"]),o=rt.getKeyProperties("WRAPPING_KEY"),u=await crypto.subtle.deriveKey({name:"PBKDF2",iterations:1e5,hash:"SHA-256",salt:r},a,o.keyProperties,!0,o.keyUsages);return Uu.set(n,u),u}getWrappingFormat(t){switch(t.type){case"private":return"jwk";case"public":case"secret":return"raw";default:throw new Error("Unsupported")}}async extractPrivateKey(t){if(t.type==="secret")return Ne(await crypto.subtle.exportKey("raw",t));const n=(await crypto.subtle.exportKey("jwk",t)).d;if(!n)throw Error("Could not extract private-key part");return md(n)}}const Ca=async e=>{const t=new rt,[r,n]=await Promise.all([t.serializeEncryptionAesCryptoKey(e.aesGcmCryptoKey),t.serializeEncryptionAesCryptoKey(e.aesCtrCryptoKey)]);return{aesGcmJwk:r,aesCtrJwk:n}};class $m{constructor(t,r){this.target=t,this.options=r}start(){var r,n;const t=async i=>{var o,u,d,f;const{data:a}=i;switch(a.type){case"msgChannelClientDownloadContentItemDecryptionKeys":{const m=await this.options.getContentItemDecryptionKeys(a.contentItemId).catch(()=>null);if(!m)return;this.target.postMessage({type:"msgChannelServerDownloadContentItemDecryptionKeys",id:a.id,contentItemId:a.contentItemId,decryptionKeysSerialized:await Ca(m)});break}case"msgChannelClientDownloadMultipartOptions":{this.target.postMessage({type:"msgChannelServerDownloadMultipartOptions",id:a.id,multipartOptions:this.options.multipartOptions});break}case"msgChannelClientDownloadProgress":{(u=(o=this.options).onProgress)==null||u.call(o,a.progress);break}case"msgChannelClientDownloadContentItemProgress":{(f=(d=this.options).onContentItemProgress)==null||f.call(d,a.contentItemId,a.progress);break}}};return(n=(r=this.target).start)==null||n.call(r),this.target.addEventListener("message",t),()=>{this.target.removeEventListener("message",t)}}}const qm=8e3,Hm=2e3;class Jm{constructor(t,r,n,i){this.serviceWorker=t,this.downloadInfo=r,this.downloadOptions=n,this.onServiceWorkerUnresponsive=i,this.downloadUrlPromise=Ke();const{apiOptions:a,multipartOptions:o,getContentItemDecryptionKeys:u,onProgress:d,onContentItemProgress:f,onStart:m,onResult:y}=n;let g=null,w=null;const S=Date.now(),E=new MessageChannel,D=new MessageChannel,M=()=>{this.cancel()},U=()=>{g!==null&&(clearTimeout(g),g=null),w!==null&&(clearTimeout(w),w=null)},F=(Se,ue)=>{w=setTimeout(()=>{y==null||y(!1,"ServiceWorker is not responding, please try again."),i==null||i(Date.now()-S),this.cleanup()},Hm),this.serviceWorker.postMessage({type:"downloadServiceWorkerDownloadKeepAlive",downloadId:Se,time:qm,port:ue},ue?[ue]:[])},j=async Se=>{const{data:ue}=Se;switch(ue.type){case"downloadServiceWorkerDownloadRegister":{this.downloadUrlPromise.resolve(ue.url);break}case"downloadServiceWorkerDownloadStart":{m==null||m(),addEventListener("beforeunload",M),F(ue.downloadId,D.port2);break}case"downloadServiceWorkerDownloadResult":{y==null||y(ue.canceled,ue.error),this.cleanup();break}}},$=async Se=>{const{data:ue}=Se;switch(ue.type){case"downloadServiceWorkerDownloadKeepAlive":{U(),g=setTimeout(()=>{F(ue.downloadId)},ue.time);break}}};E.port1.start(),E.port2.start(),D.port1.start(),D.port2.start(),E.port1.addEventListener("message",j),D.port1.addEventListener("message",$);const V=new vd(E.port1,a),W=new $m(E.port1,{getContentItemDecryptionKeys:u,onContentItemProgress:f,onProgress:d,multipartOptions:o}),ie=V.start(),de=W.start();this.cleanup=()=>{removeEventListener("beforeunload",M),U(),ie(),de(),E.port1.removeEventListener("message",j),E.port1.close(),E.port2.close(),D.port1.removeEventListener("message",$),D.port1.close(),D.port2.close()},this.downloadMessageChannel=E,this.serviceWorker.postMessage({type:"downloadServiceWorkerDownloadRegister",port:E.port2,downloadInfo:r},[E.port2])}getUrl(){return this.downloadUrlPromise.promise}cancel(){this.downloadMessageChannel.port1.postMessage({type:"downloadServiceWorkerDownloadCancel"}),setTimeout(()=>this.cleanup(),1e3)}}const jm="/decrypt",zm=e=>{const{sharingBucketId:t,contentItem:r,decryptionKeysSerialized:n,downloadUrl:i,previewItem:a}=e||{},{mediaType:o}
2=a??r,u=new URL(location.origin);return u.pathname=jm,u.searchParams.set("sharingBucketId",t),u.searchParams.set("contentItemId",r.id),u.searchParams.set("downloadUrl",i),u.searchParams.set("mediaType",o),u.searchParams.set("decryptionKeys",em(n)),a&&u.searchParams.set("preview",a.id),u.href};class Gm{constructor(t,r,n){this.serviceWorker=t,this.contentItemUrlTarget=r,this.apiOptions=n;const{port1:i,port2:a}=new MessageChannel,o=new vd(i,n);this.cleanup=o.start(),this.serviceWorker.postMessage({type:"downloadServiceWorkerContentItemRegister",port:a,contentItemUrlTarget:r},[a])}getUrl(){return zm(this.contentItemUrlTarget)}dispose(){this.cleanup()}}const Vm=["downloadServiceWorkerKeepAliveFetch"],Ym=e=>!e||typeof e!="object"||typeof e.type!="string"?!1:Vm.includes(e.type),Qm=2e4,os=class os{constructor(){this.serviceWorkerReadyPromiseWithResolvers=Ke(),this.streamSupportPromiseWithResolvers=Ke(),this.activeServiceWorker=null,this.initialized=!1}static getInstance(){return this.instance||(this.instance=new os),this.instance}async createContentItem(t,r){return!await this.isSupportedAndReady()||!this.activeServiceWorker?null:new Gm(this.activeServiceWorker,t,r)}async createDownload(t,r){return!await this.isSupportedAndReady()||!this.activeServiceWorker?null:new Jm(this.activeServiceWorker,t,r,n=>{console.error(`Service Worker unresponsive after ${n/1e3} seconds`),this.activeServiceWorker=null})}async isSupportedAndReady(){if(!this.initialized)return!1;await this.serviceWorkerReadyPromiseWithResolvers.promise;const t=await this.streamSupportPromiseWithResolvers.promise;return!!this.activeServiceWorker&&t}init(t){this.initialized||(this.initialized=!0,Promise.resolve(t).then(r=>{if(!r.ok){this.serviceWorkerReadyPromiseWithResolvers.resolve();return}try{let n=null;const i=()=>{let o=!1;const u=new AbortController,d=m=>{const{data:y}=m;if(!(y&&typeof y.source=="string")&&Ym(y))switch(y.type){case"downloadServiceWorkerKeepAliveFetch":{if(o)return;(async()=>{for(o=!0;o;){const g=await fetch(y.url,{signal:u.signal}).catch(()=>null);if(!g||g.status!==204){o=!1;break}await new Promise(w=>{setTimeout(()=>w(),Qm)})}})();break}}},f=navigator.serviceWorker.controller;return f&&f.scriptURL.endsWith(r.value.scriptURL)?(this.activeServiceWorker=f,navigator.serviceWorker.addEventListener("message",d)):this.activeServiceWorker=null,this.serviceWorkerReadyPromiseWithResolvers.resolve(),u},a=()=>{n==null||n.abort(),n=i()};navigator.serviceWorker.ready.then(a),navigator.serviceWorker.addEventListener("controllerchange",a)}catch{this.serviceWorkerReadyPromiseWithResolvers.resolve()}}).catch(()=>{this.serviceWorkerReadyPromiseWithResolvers.resolve()}),sc(am,{retry:us({maxDelay:2e3})}).then(r=>{this.streamSupportPromiseWithResolvers.resolve(r.ok&&r.value.body instanceof ReadableStream)}))}};os.instance=void 0;let Oo=os;function hi(e){"@babel/helpers - typeof";return hi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hi(e)}function Xm(e,t){if(hi(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(hi(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function Zm(e){var t=Xm(e,"string");return hi(t)=="symbol"?t:t+""}function ey(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,Zm(n.key),n)}}function wr(e,t,r){return t&&ey(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function ls(e){return e[e.length-1]}function bn(e){return Array.isArray(e)?e.slice(0):[e]}function ty(e,t){e=e.slice(0);for(var r=[];e.length;){var n=e.splice(0,t);r.push(n)}return r}function La(e){return Array.isArray(e)}function ry(e){return e!=null}function uo(e,t){var r=0,n=-1;for(var i of e){n=n+1;var a=t(i,n);if(a)r=r+1;else break}return r}function Ur(e,t){var r=t.length;if(r!==0){var n=e.length;e.length=n+t.length;for(var i=0;i<r;++i)e[n+i]=t[i]}}function ny(e){return e.filter(function(t,r,n){return n.indexOf(t)===r})}function yr(e){for(var t="",r=0;r<e.length;r++){var n=e[r];if(n==="-")return parseInt(t,10);t+=n}throw new Error("malformatted revision: "+e)}function zt(e,t){var r=t?yr(t._rev)+1:1;return r+"-"+e}function gd(e){var t=e.split("."),r=t.length;return r===1?n=>n[e]:n=>{for(var i=n,a=0;a<r;++a){var o=t[a];if(i=i[o],typeof i>"u")return i}return i}}function Oe(e){return Object.assign({},e)}function iy(e){return Object.keys(e)[0]}function Ua(e,t=!1){if(!e)return e;if(!t&&Array.isArray(e))return e.sort((n,i)=>typeof n=="string"&&typeof i=="string"?n.localeCompare(i):typeof n=="object"?
21:-1).map(n=>Ua(n,t));if(typeof e=="object"&&!Array.isArray(e)){var r={};return Object.keys(e).sort((n,i)=>n.localeCompare(i)).forEach(n=>{r[n]=Ua(e[n],t)}),r}return e}function To(e){if(!e||e===null||typeof e!="object")return e;if(Array.isArray(e)){for(var t=new Array(e.length),r=t.length;r--;)t[r]=To(e[r]);return t}var n={};for(var i in e)n[i]=To(e[i]);return n}var st=To;function Jt(e,t,r){return Object.defineProperty(e,t,{get:function(){return r}}),r}var cc=1;function Dn(){return{lwt:cc}}function kt(){return""}function ay(e){return Object.assign({},e,{_meta:void 0,_deleted:void 0,_rev:void 0})}function sy(e,t,r){if(t.length!==r.length)return!1;for(var n=0,i=t.length;n<i;){var a=t[n],o=r[n];if(n++,a[e]!==o[e]||a._rev!==o._rev||a._meta.lwt!==o._meta.lwt)return!1}return!0}function fi(e,t){return fi=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,n){return r.__proto__=n,r},fi(e,t)}function uc(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,fi(e,t)}function Ko(e){return Ko=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},Ko(e)}function oy(e){try{return Function.toString.call(e).indexOf("[native code]")!==-1}catch{return typeof e=="function"}}function wd(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(wd=function(){return!!e})()}function cy(e,t,r){if(wd())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&fi(i,r.prototype),i}function Wa(e){var t=typeof Map=="function"?new Map:void 0;return Wa=function(n){if(n===null||!oy(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(n))return t.get(n);t.set(n,i)}function i(){return cy(n,arguments,Ko(this).constructor)}return i.prototype=Object.create(n.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),fi(i,n)},Wa(e)}var xe={isDevMode(){return!1},deepFreezeWhenDevMode(e){return e},tunnelErrorMessage(e){return` 3 RxDB Error-Code: `+e+`. 4 Hint: Error messages are not included in RxDB core to reduce build size. 5 To show the full error messages and to ensure that you do not make any mistakes when using RxDB, 6 use the dev-mode plugin when you are in development mode: https://rxdb.info/dev-mode.html?console=error 7 `}};function uy(e){var t="";return Object.keys(e).length===0||(t+="-".repeat(20)+` 8`,t+=`Parameters: 9`,t+=Object.keys(e).map(r=>{var n="[object Object]";try{r==="errors"?n=e[r].map(i=>JSON.stringify(i,Object.getOwnPropertyNames(i))):n=JSON.stringify(e[r],function(i,a){return a===void 0?null:a},2)}catch{}return r+": "+n}).join(` 10`),t+=` 11`),t}function bd(e,t,r){return` 12`+e+` 13`+uy(r)}var Ao=(function(e){function t(n,i,a={}){var o,u=bd(i,n,a);return o=e.call(this,u)||this,o.code=n,o.message=u,o.url=lc(n),o.parameters=a,o.rxdb=!0,o}uc(t,e);var r=t.prototype;return r.toString=function(){return this.message},wr(t,[{key:"name",get:function(){return"RxError ("+this.code+")"}},{key:"typeError",get:function(){return!1}}])})(Wa(Error)),ly=(function(e){function t(n,i,a={}){var o,u=bd(i,n,a);return o=e.call(this,u)||this,o.code=n,o.message=u,o.url=lc(n),o.parameters=a,o.rxdb=!0,o}uc(t,e);var r=t.prototype;return r.toString=function(){return this.message},wr(t,[{key:"name",get:function(){return"RxTypeError ("+this.code+")"}},{key:"typeError",get:function(){return!0}}])})(Wa(TypeError));function lc(e){return"https://rxdb.info/errors.html?console=errors#"+e}function Sd(e){return` 14Find out more about this error here: `+lc(e)+` 15`}function ee(e,t){return new Ao(e,xe.tunnelErrorMessage(e)+Sd(e),t)}function $a(e,t){return new ly(e,xe.tunnelErrorMessage(e)+Sd(e),t)}function Sn(e){return e&&e.status===409?e:!1}var dy={409:"document write conflict",422:"schema validation error",510:"attachment data missing"};function Ed(e){return ee("COL20",{name:dy[e.status],document:e.documentId,writeError:e})}var wa;function hy(){var e;if(wa)return wa;if(typeof crypto>"u"||typeof crypto.subtle>"u"||typeof crypto.subtle.digest!="function")throw ee("UT8",{args:{typeof_crypto:typeof crypto,typeof_crypto_subtle:typeof(crypto==null?void 0:crypto.subtle),typeof_crypto_subtle_digest:typeof((e=crypto==null?void 0:crypto.subtle)==null?void 0:e.digest)}});return wa=crypto.subtle.digest.bind(crypto.subtle),wa}async function fy(e){var t=new TextEncoder().encode(e),r=await hy()("SHA-256",t),n=Array.prototype.map.call(new Uint8Array(r),i=>("00"+i.toString(16)).slice(-2)).join("");return n}var _d=fy;function py(){return new Promise(e=>setTimeout(e,0))}function pi(e=0){return new Promise(t=>setTimeout(t,e))}function Pd(e){return e&&typeof e.then=="function"?e:Promise.resolve(e)}
15var xn=Promise.resolve(!0),Rt=Promise.resolve(!1),dc=Promise.resolve(null),nt=Promise.resolve();function On(e=1e4){return typeof requestIdleCallback=="function"?new Promise(t=>{requestIdleCallback(()=>t(),{timeout:e})}):pi(0)}var lo=nt;function my(e=void 0){return lo=lo.then(()=>On(e)),lo}function yy(e,t){return e.reduce((r,n)=>r.then(n),Promise.resolve(t))}var vy=/\./g,$u="abcdefghijklmnopqrstuvwxyz";function Tn(e=10){for(var t="",r=0;r<e;r++)t+=$u.charAt(Math.floor(Math.random()*$u.length));return t}function Id(e){e+="";var t=e.charAt(0).toUpperCase();return t+e.substr(1)}function ri(e){for(;e.charAt(0)===".";)e=e.substr(1);for(;e.slice(-1)===".";)e=e.slice(0,-1);return e}function En(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var r,n;if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(n=r;n--!==0;)if(!En(e[n],t[n]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();var i=Object.keys(e);if(r=i.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[n]))return!1;for(n=r;n--!==0;){var a=i[n];if(!En(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}var No=e=>{var t=typeof e;return e!==null&&(t==="object"||t==="function")},ho=new Set(["__proto__","prototype","constructor"]),gy=new Set("0123456789");function Cd(e){var t=[],r="",n="start",i=!1;for(var a of e)switch(a){case"\\":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");i&&(r+=a),n="property",i=!i;break}case".":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="property";break}if(i){i=!1,r+=a;break}if(ho.has(r))return[];t.push(r),r="",n="property";break}case"[":{if(n==="index")throw new Error("Invalid character in an index");if(n==="indexEnd"){n="index";break}if(i){i=!1,r+=a;break}if(n==="property"){if(ho.has(r))return[];t.push(r),r=""}n="index";break}case"]":{if(n==="index"){t.push(Number.parseInt(r,10)),r="",n="indexEnd";break}if(n==="indexEnd")throw new Error("Invalid character after an index")}default:{if(n==="index"&&!gy.has(a))throw new Error("Invalid character in an index");if(n==="indexEnd")throw new Error("Invalid character after an index");n==="start"&&(n="property"),i&&(i=!1,r+="\\"),r+=a}}switch(i&&(r+="\\"),n){case"property":{if(ho.has(r))return[];t.push(r);break}case"index":throw new Error("Index was not closed");case"start":{t.push("");break}}return t}function kd(e,t){if(typeof t!="number"&&Array.isArray(e)){var r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}function wy(e,t){if(kd(e,t))throw new Error("Cannot use string index")}function vr(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!t.includes(".")&&!t.includes("["))return e[t];if(!No(e)||typeof t!="string")return r===void 0?e:r;var n=Cd(t);if(n.length===0)return r;for(var i=0;i<n.length;i++){var a=n[i];if(kd(e,a)?e=i===n.length-1?void 0:null:e=e[a],e==null){if(i!==n.length-1)return r;break}}return e===void 0?r:e}function Rd(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!No(e)||typeof t!="string")return e;for(var n=e,i=Cd(t),a=0;a<i.length;a++){var o=i[a];wy(e,o),a===i.length-1?e[o]=r:No(e[o])||(e[o]=typeof i[a+1]=="number"?[]:{}),e=e[o]}return n}function Wr(e,t){var r=e.get(t);if(typeof r>"u")throw new Error("missing value from map "+t);return r}function it(e,t,r,n){var i=e.get(t);return typeof i>"u"&&(i=r(),e.set(t,i)),i}function De(e){var t=e.split("-"),r="RxDB";return t.forEach(n=>{r+=Id(n)}),r+="Plugin",new Error(`You are using a function which must be overwritten by a plugin. 16 You should either prevent the usage of this function or add the plugin via: 17 import { `+r+" } from 'rxdb/plugins/"+e+`'; 18 addRxPlugin(`+r+`); 19 `)}function Mo(e){var t={name:e.name,message:e.message,rxdb:e.rxdb,parameters:e.parameters,extensions:e.extensions,code:e.code,url:e.url,stack:e.stack?e.
19stack.replace(/\n/g,` 20 `):void 0};return t}var fo=0;function Ze(){var e=Date.now();e=e+.01,e<=fo&&(e=fo+.01);var t=parseFloat(e.toFixed(2));return fo=t,t}function Z(e,t){if(!e)throw t||(t=""),new Error("ensureNotFalsy() is falsy: "+t);return e}var xi={bufferSize:1,refCount:!0},hc="16.15.0",ka={},by="6da4936d1425ff3a5c44c02342c6daf791d266be3ae8479b8ec59e261df41b93",qu=16,po=Rt,Hu=!1;async function Dd(){return Hu||(Hu=!0,po=(async()=>!!(ka.premium&&typeof ka.premium=="string"&&await _d(ka.premium)===by))()),po}var mi={preAddRxPlugin:[],preCreateRxDatabase:[],createRxDatabase:[],preCreateRxCollection:[],createRxCollection:[],createRxState:[],postCloseRxCollection:[],postRemoveRxCollection:[],preCreateRxSchema:[],createRxSchema:[],prePrepareRxQuery:[],preCreateRxQuery:[],prePrepareQuery:[],createRxDocument:[],postCreateRxDocument:[],preCreateRxStorageInstance:[],preStorageWrite:[],preMigrateDocument:[],postMigrateDocument:[],preCloseRxDatabase:[],postRemoveRxDatabase:[],postCleanup:[],preReplicationMasterWrite:[],preReplicationMasterWriteDocumentsHandle:[]};function ot(e,t){mi[e].length>0&&mi[e].forEach(r=>r(t))}async function Gt(e,t){for(var r of mi[e])await r(t)}function Vt(e,t){var r=t;r=r.replace(vy,".properties."),r="properties."+r,r=ri(r);var n=vr(e,r);return n}function Sy(e,t,r){if(typeof t.primaryKey=="string")return r;var n=br(t,r),i=r[e];if(i&&i!==n)throw ee("DOC19",{args:{documentData:r,existingPrimary:i,newPrimary:n},schema:t});return r[e]=n,r}function et(e){return typeof e=="string"?e:e.key}function Ey(e){var t=et(e.primaryKey),r=Vt(e,t);return Z(r.maxLength)}function br(e,t){if(typeof e.primaryKey=="string")return t[e.primaryKey];var r=e.primaryKey;return r.fields.map(n=>{var i=vr(t,n);if(typeof i>"u")throw ee("DOC18",{args:{field:n,documentData:t}});return i}).join(r.separator)}function _y(e){var t=Ua(e,!0);return t}function Py(e){return["_deleted",e]}function ds(e){e=Oe(e);var t=et(e.primaryKey);e.properties=Oe(e.properties),e.additionalProperties=!1,Object.prototype.hasOwnProperty.call(e,"keyCompression")||(e.keyCompression=!1),e.indexes=e.indexes?e.indexes.slice(0):[],e.required=e.required?e.required.slice(0):[],e.encrypted=e.encrypted?e.encrypted.slice(0):[],e.properties._rev={type:"string",minLength:1},e.properties._attachments={type:"object"},e.properties._deleted={type:"boolean"},e.properties._meta=Cy,e.required=e.required?e.required.slice(0):[],e.required.push("_deleted"),e.required.push("_rev"),e.required.push("_meta"),e.required.push("_attachments");var r=xd(e);Ur(e.required,r),e.required=e.required.filter(a=>!a.includes(".")).filter((a,o,u)=>u.indexOf(a)===o),e.version=e.version||0;var n=e.indexes.map(a=>{var o=La(a)?a.slice(0):[a];return o.includes(t)||o.push(t),o[0]!=="_deleted"&&o.unshift("_deleted"),o});n.length===0&&n.push(Py(t)),n.push(["_meta.lwt",t]),e.internalIndexes&&e.internalIndexes.map(a=>{n.push(a)});var i=new Set;return n.filter(a=>{var o=a.join(",");return i.has(o)?!1:(i.add(o),!0)}),e.indexes=n,e}var Iy=1e15,Cy={type:"object",properties:{lwt:{type:"number",minimum:cc,maximum:Iy,multipleOf:.01}},additionalProperties:!0,required:["lwt"]};function xd(e){var t=Object.keys(e.properties).filter(n=>e.properties[n].final),r=et(e.primaryKey);return t.push(r),typeof e.primaryKey!="string"&&e.primaryKey.fields.forEach(n=>t.push(n)),t}function ky(e,t){for(var r=Object.keys(e.defaultValues),n=0;n<r.length;++n){var i=r[n];(!Object.prototype.hasOwnProperty.call(t,i)||typeof t[i]>"u")&&(t[i]=e.defaultValues[i])}return t}var Od=(function(){function e(r,n){if(this.jsonSchema=r,this.hashFunction=n,this.indexes=Ry(this.jsonSchema),this.primaryPath=et(this.jsonSchema.primaryKey),!r.properties[this.primaryPath].maxLength)throw ee("SC39",{schema:r});this.finalFields=xd(this.jsonSchema)}var t=e.prototype;return t.validateChange=function(n,i){this.finalFields.forEach(a=>{if(!En(n[a],i[a]))throw ee("DOC9",{dataBefore:n,dataAfter:i,fieldName:a,schema:this.jsonSchema})})},t.getDocumentPrototype=function(){var n={},i=Vt(this.jsonSchema,"");
20return Object.keys(i).forEach(a=>{var o=a;n.__defineGetter__(a,function(){if(!(!this.get||typeof this.get!="function")){var u=this.get(o);return u}}),Object.defineProperty(n,a+"$",{get:function(){return this.get$(o)},enumerable:!1,configurable:!1}),Object.defineProperty(n,a+"$$",{get:function(){return this.get$$(o)},enumerable:!1,configurable:!1}),Object.defineProperty(n,a+"_",{get:function(){return this.populate(o)},enumerable:!1,configurable:!1})}),Jt(this,"getDocumentPrototype",()=>n),n},t.getPrimaryOfDocumentData=function(n){return br(this.jsonSchema,n)},wr(e,[{key:"version",get:function(){return this.jsonSchema.version}},{key:"defaultValues",get:function(){var r={};return Object.entries(this.jsonSchema.properties).filter(([,n])=>Object.prototype.hasOwnProperty.call(n,"default")).forEach(([n,i])=>r[n]=i.default),Jt(this,"defaultValues",r)}},{key:"hash",get:function(){return Jt(this,"hash",this.hashFunction(JSON.stringify(this.jsonSchema)))}}])})();function Ry(e){return(e.indexes||[]).map(t=>La(t)?t:[t])}function Dy(e){var t=e.version?e.version:0,r=0;return new Array(t).fill(0).map(()=>r++)}function xy(e,t,r=!0){r&&ot("preCreateRxSchema",e);var n=ds(e);n=_y(n),xe.deepFreezeWhenDevMode(n);var i=new Od(n,t);return ot("createRxSchema",i),i}function $e(e){return typeof e=="function"}function Oy(e){return $e(e==null?void 0:e.lift)}function Bt(e){return function(t){if(Oy(t))return t.lift(function(r){try{return e(r,this)}catch(n){this.error(n)}});throw new TypeError("Unable to lift unknown Observable type")}}var Bo=function(e,t){return Bo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[i]=n[i])},Bo(e,t)};function jr(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Bo(e,t);function r(){this.constructor=e}e.prototype=t===null?Object.create(t):(r.prototype=t.prototype,new r)}function Ty(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function u(m){try{f(n.next(m))}catch(y){o(y)}}function d(m){try{f(n.throw(m))}catch(y){o(y)}}function f(m){m.done?a(m.value):i(m.value).then(u,d)}f((n=n.apply(e,t||[])).next())})}function Td(e,t){var r={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},n,i,a,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=u(0),o.throw=u(1),o.return=u(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function u(f){return function(m){return d([f,m])}}function d(f){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,f[0]&&(r=0)),r;)try{if(n=1,i&&(a=f[0]&2?i.return:f[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,f[1])).done)return a;switch(i=0,a&&(f=[f[0]&2,a.value]),f[0]){case 0:case 1:a=f;break;case 4:return r.label++,{value:f[1],done:!1};case 5:r.label++,i=f[1],f=[0];continue;case 7:f=r.ops.pop(),r.trys.pop();continue;default:if(a=r.trys,!(a=a.length>0&&a[a.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!a||f[1]>a[0]&&f[1]<a[3])){r.label=f[1];break}if(f[0]===6&&r.label<a[1]){r.label=a[1],a=f;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(f);break}a[2]&&r.ops.pop(),r.trys.pop();continue}f=t.call(e,r)}catch(m){f=[6,m],i=0}finally{n=a=0}if(f[0]&5)throw f[1];return{value:f[0]?f[1]:void 0,done:!0}}}function _n(e){var t=typeof Symbol=="function"&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function $r(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),i,a=[],o;try{for(;(t===void 0||t-- >0)&&!(i=n.next()).done;)a.push(i.value)}catch(u){o={error:u}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return a}function qr(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,a;n<i;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}function fn(e){return this instanceof fn?(this.v=e,this):new fn(e)}function Ky(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),u("next"),u("throw"),u("return",o),i[Symbol.asyncIterator]=function(){return this},i;function o(w){return function(S){return Promise.resolve(S).then(w,y)}}function u(w,S){n[w]&&(i[w]=function(E){return new Promise(function(D,M){a.push([w,E,D,M])>1||d(w,E)})},S&&(i[w]=S(i[w])))}function d(w,S){try{f(n[w](S))}catch(E){g(a[0][3],E)}}function f(w){w.value instanceof fn?Promise.resolve(w.value.v).then(m,y):g(a[0][2],w)}function m(w){d("next",w)}function y(w){d("throw",w)}function g(w,S){w(S),a.shift(),a.length&&d(a[0][0],a[0][1])}}function Ay(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof _n=="function"?_n(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=e[a]&&function(o){return new Promise(function(u,d){o=e[a](o),i(u,d,o.done,o.value)})}}function i(a,o,u,d){Promise.resolve(d).then(function(f){a({value:f,done:u})},o)}}var Kd=(function(e){return e&&typeof e.length=="number"&&typeof e!="function"});function Ad(e){return $e(e==null?void 0:e.then)}function fc(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var mo=fc(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription: 21`+r.map(function(n,i){return i+1+") "+n.toString()}).join(` 22 `):"",this.name="UnsubscriptionError",this.errors=r}});function Fo(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var hs=(function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,i,a;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var u=_n(o),d=u.next();!d.done;d=u.next()){var f=d.value;f.remove(this)}}catch(E){t={error:E}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(t)throw t.error}}else o.remove(this);var m=this.initialTeardown;
vendor: 4,739 bytes, line 22
22if($e(m))try{m()}catch(E){a=E instanceof mo?E.errors:[E]}var y=this._finalizers;if(y){this._finalizers=null;try{for(var g=_n(y),w=g.next();!w.done;w=g.next()){var S=w.value;try{Ju(S)}catch(E){a=a??[],E instanceof mo?a=qr(qr([],$r(a)),$r(E.errors)):a.push(E)}}}catch(E){n={error:E}}finally{try{w&&!w.done&&(i=g.return)&&i.call(g)}finally{if(n)throw n.error}}}if(a)throw new mo(a)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)Ju(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&Fo(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&Fo(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e})(),Nd=hs.EMPTY;function Md(e){return e instanceof hs||e&&"closed"in e&&$e(e.remove)&&$e(e.add)&&$e(e.unsubscribe)}function Ju(e){$e(e)?e():e.unsubscribe()}var Ny={Promise:void 0},My={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];return setTimeout.apply(void 0,qr([e,t],$r(r)))},clearTimeout:function(e){return clearTimeout(e)},delegate:void 0};function Bd(e){My.setTimeout(function(){throw e})}function ju(){}function Ra(e){e()}var pc=(function(e){jr(t,e);function t(r){var n=e.call(this)||this;return n.isStopped=!1,r?(n.destination=r,Md(r)&&r.add(n)):n.destination=Ly,n}return t.create=function(r,n,i){return new Pn(r,n,i)},t.prototype.next=function(r){this.isStopped||this._next(r)},t.prototype.error=function(r){this.isStopped||(this.isStopped=!0,this._error(r))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(r){this.destination.next(r)},t.prototype._error=function(r){try{this.destination.error(r)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t})(hs),By=(function(){function e(t){this.partialObserver=t}return e.prototype.next=function(t){var r=this.partialObserver;if(r.next)try{r.next(t)}catch(n){ba(n)}},e.prototype.error=function(t){var r=this.partialObserver;if(r.error)try{r.error(t)}catch(n){ba(n)}else ba(t)},e.prototype.complete=function(){var t=this.partialObserver;if(t.complete)try{t.complete()}catch(r){ba(r)}},e})(),Pn=(function(e){jr(t,e);function t(r,n,i){var a=e.call(this)||this,o;return $e(r)||!r?o={next:r??void 0,error:n??void 0,complete:i??void 0}:o=r,a.destination=new By(o),a}return t})(pc);function ba(e){Bd(e)}function Fy(e){throw e}var Ly={closed:!0,next:ju,error:Fy,complete:ju},mc=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Oi(e){return e}function Uy(e){return e.length===0?Oi:e.length===1?e[0]:function(r){return e.reduce(function(n,i){return i(n)},r)}}var ht=(function(){function e(t){t&&(this._subscribe=t)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(t,r,n){var i=this,a=$y(t)?t:new Pn(t,r,n);return Ra(function(){var o=i,u=o.operator,d=o.source;a.add(u?u.call(a,d):d?i._subscribe(a):i._trySubscribe(a))}),a},e.prototype._trySubscribe=function(t){try{return this._subscribe(t)}catch(r){t.error(r)}},e.prototype.forEach=function(t,r){var n=this;return r=zu(r),new r(function(i,a){var o=new Pn({next:function(u){try{t(u)}catch(d){a(d),o.unsubscribe()}},error:a,complete:i});n.subscribe(o)})},e.prototype._subscribe=function(t){var r;return(r=this.source)===null||r===void 0?void 0:r.subscribe(t)},e.prototype[mc]=function(){return this},e.prototype.pipe=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return Uy(t)(this)},e.prototype.toPromise=function(t){var r=this;return t=zu(t),new t(function(n,i){var a;r.subscribe(function(o){return a=o},function(o){return i(o)},function(){return n(a)})})},e.create=function(t){return new e(t)},e})();function zu(e){var t;return(t=e??Ny.Promise)!==null&&t!==void 0?t:Promise}function Wy(e){return e&&$e(e.next)&&$e(e.error)&&$e(e.complete)}function $y(e){return e&&e instanceof pc||Wy(e)&&Md(e)}function Fd(e){return $e(e[mc])}function Ld(e){return Symbol.asyncIterator&&$e(e==null?void 0:e[Symbol.asyncIterator])}function Ud(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invali
22d object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function qy(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Wd=qy();function $d(e){return $e(e==null?void 0:e[Wd])}function qd(e){return Ky(this,arguments,function(){var r,n,i,a;return Td(this,function(o){switch(o.label){case 0:r=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,fn(r.read())];case 3:return n=o.sent(),i=n.value,a=n.done,a?[4,fn(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,fn(i)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function Hd(e){return $e(e==null?void 0:e.getReader)}function Xt(e){if(e instanceof ht)return e;if(e!=null){if(Fd(e))return Hy(e);if(Kd(e))return Jy(e);if(Ad(e))return jy(e);if(Ld(e))return Jd(e);if($d(e))return zy(e);if(Hd(e))return Gy(e)}throw Ud(e)}function Hy(e){return new ht(function(t){var r=e[mc]();if($e(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Jy(e){return new ht(function(t){for(var r=0;r<e.length&&!t.closed;r++)t.next(e[r]);t.complete()})}function jy(e){return new ht(function(t){e.then(function(r){t.closed||(t.next(r),t.complete())},function(r){return t.error(r)}).then(null,Bd)})}function zy(e){return new ht(function(t){var r,n;try{for(var i=_n(e),a=i.next();!a.done;a=i.next()){var o=a.value;if(t.next(o),t.closed)return}}catch(u){r={error:u}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}t.complete()})}function Jd(e){return new ht(function(t){Vy(e,t).catch(function(r){return t.error(r)})})}function Gy(e){return Jd(qd(e))}function Vy(e,t){var r,n,i,a;return Ty(this,void 0,void 0,function(){var o,u;return Td(this,function(d){switch(d.label){case 0:d.trys.push([0,5,6,11]),r=Ay(e),d.label=1;case 1:return[4,r.next()];case 2:if(n=d.sent(),!!n.done)return[3,4];if(o=n.value,t.next(o),t.closed)return[2];d.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=d.sent(),i={error:u},[3,11];case 6:return d.trys.push([6,,9,10]),n&&!n.done&&(a=r.return)?[4,a.call(r)]:[3,8];case 7:d.sent(),d.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function Yt(e,t,r,n,i){return new Yy(e,t,r,n,i)}var Yy=(function(e){jr(t,e);function t(r,n,i,a,o,u){var d=e.call(this,r)||this;return d.onFinalize=o,d.shouldUnsubscribe=u,d._next=n?function(f){try{n(f)}catch(m){r.error(m)}}:e.prototype._next,d._error=a?function(f){try{a(f)}catch(m){r.error(m)}finally{this.unsubscribe()}}:e.prototype._error,d._complete=i?function(){try{i()}catch(f){r.error(f)}finally{this.unsubscribe()}}:e.prototype._complete,d}return t.prototype.unsubscribe=function(){var r;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((r=this.onFinalize)===null||r===void 0||r.call(this))}},t})(pc),jd={now:function(){return(jd.delegate||Date).now()},delegate:void 0};function Qy(e){return e&&$e(e.schedule)}function yc(e){return e[e.length-1]}function Xy(e){return $e(yc(e))?e.pop():void 0}function Ti(e){return Qy(yc(e))?e.pop():void 0}function zd(e,t){return typeof yc(e)=="number"?e.pop():t}function fr(e,t,r,n,i){n===void 0&&(n=0),i===void 0&&(i=!1);var a=t.schedule(function(){r(),i?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(a),!i)return a}var Zy=Array.isArray,ev=Object.getPrototypeOf,tv=Object.prototype,rv=Object.keys;function nv(e){if(e.length===1){var t=e[0];if(Zy(t))return{args:t,keys:null};if(iv(t)){var r=rv(t);return{args:r.map(function(n){return t[n]}),keys:r}}}return{args:e,keys:null}}function iv(e){return e&&typeof e=="object"&&ev(e)===tv}function Gd(e,t){return t===void 0&&(t=0),Bt(function(r,n){r.subscribe(Yt(n,function(i){return fr(n,e,function(){return n.next(i)},t)},function(){return fr(n,e,function(){return n.complete()},t)},function(i){return fr(n,e,function(){return n.error(i)},t)}))})}function Vd(e,t){return t===void 0&&(t=0),Bt(function(r,n){n.add(e.schedule(function(){return r.subscribe(n)},t))})}function av(e,t){return Xt(e).pipe(Vd(t),Gd(t))}function sv(e,t){return Xt(e).pipe(Vd(t),Gd(t))}function ov(e,t){return new ht(function(r){var n=0;return t.schedule(function(){n===e.length?r.complete():(r.next(e[
22n++]),r.closed||this.schedule())})})}function cv(e,t){return new ht(function(r){var n;return fr(r,t,function(){n=e[Wd](),fr(r,t,function(){var i,a,o;try{i=n.next(),a=i.value,o=i.done}catch(u){r.error(u);return}o?r.complete():r.next(a)},0,!0)}),function(){return $e(n==null?void 0:n.return)&&n.return()}})}function Yd(e,t){if(!e)throw new Error("Iterable cannot be null");return new ht(function(r){fr(r,t,function(){var n=e[Symbol.asyncIterator]();fr(r,t,function(){n.next().then(function(i){i.done?r.complete():r.next(i.value)})},0,!0)})})}function uv(e,t){return Yd(qd(e),t)}function lv(e,t){if(e!=null){if(Fd(e))return av(e,t);if(Kd(e))return ov(e,t);if(Ad(e))return sv(e,t);if(Ld(e))return Yd(e,t);if($d(e))return cv(e,t);if(Hd(e))return uv(e,t)}throw Ud(e)}function Ki(e,t){return t?lv(e,t):Xt(e)}function We(e,t){return Bt(function(r,n){var i=0;r.subscribe(Yt(n,function(a){n.next(e.call(t,a,i++))}))})}var dv=Array.isArray;function hv(e,t){return dv(t)?e.apply(void 0,qr([],$r(t))):e(t)}function fv(e){return We(function(t){return hv(e,t)})}function pv(e,t){return e.reduce(function(r,n,i){return r[n]=t[i],r},{})}function Qd(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Ti(e),n=Xy(e),i=nv(e),a=i.args,o=i.keys;if(a.length===0)return Ki([],r);var u=new ht(mv(a,r,o?function(d){return pv(o,d)}:Oi));return n?u.pipe(fv(n)):u}function mv(e,t,r){return r===void 0&&(r=Oi),function(n){Gu(t,function(){for(var i=e.length,a=new Array(i),o=i,u=i,d=function(m){Gu(t,function(){var y=Ki(e[m],t),g=!1;y.subscribe(Yt(n,function(w){a[m]=w,g||(g=!0,u--),u||n.next(r(a.slice()))},function(){--o||n.complete()}))},n)},f=0;f<i;f++)d(f)},n)}}function Gu(e,t,r){e?fr(r,e,t):t()}function yv(e,t,r,n,i,a,o,u){var d=[],f=0,m=0,y=!1,g=function(){y&&!d.length&&!f&&t.complete()},w=function(E){return f<n?S(E):d.push(E)},S=function(E){f++;var D=!1;Xt(r(E,m++)).subscribe(Yt(t,function(M){t.next(M)},function(){D=!0},void 0,function(){if(D)try{f--;for(var M=function(){var U=d.shift();o||S(U)};d.length&&f<n;)M();g()}catch(U){t.error(U)}}))};return e.subscribe(Yt(t,w,function(){y=!0,g()})),function(){}}function Mt(e,t,r){return r===void 0&&(r=1/0),$e(t)?Mt(function(n,i){return We(function(a,o){return t(n,a,i,o)})(Xt(e(n,i)))},r):(typeof t=="number"&&(r=t),Bt(function(n,i){return yv(n,i,e,r)}))}function vc(e){return e===void 0&&(e=1/0),Mt(Oi,e)}function vv(){return vc(1)}var gv=fc(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),He=(function(e){jr(t,e);function t(){var r=e.call(this)||this;return r.closed=!1,r.currentObservers=null,r.observers=[],r.isStopped=!1,r.hasError=!1,r.thrownError=null,r}return t.prototype.lift=function(r){var n=new Vu(this,this);return n.operator=r,n},t.prototype._throwIfClosed=function(){if(this.closed)throw new gv},t.prototype.next=function(r){var n=this;Ra(function(){var i,a;if(n._throwIfClosed(),!n.isStopped){n.currentObservers||(n.currentObservers=Array.from(n.observers));try{for(var o=_n(n.currentObservers),u=o.next();!u.done;u=o.next()){var d=u.value;d.next(r)}}catch(f){i={error:f}}finally{try{u&&!u.done&&(a=o.return)&&a.call(o)}finally{if(i)throw i.error}}}})},t.prototype.error=function(r){var n=this;Ra(function(){if(n._throwIfClosed(),!n.isStopped){n.hasError=n.isStopped=!0,n.thrownError=r;for(var i=n.observers;i.length;)i.shift().error(r)}})},t.prototype.complete=function(){var r=this;Ra(function(){if(r._throwIfClosed(),!r.isStopped){r.isStopped=!0;for(var n=r.observers;n.length;)n.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var r;return((r=this.observers)===null||r===void 0?void 0:r.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,i=this,a=i.hasError,o=i.isStopped,u=i.observers;return a||o?Nd:(this.currentObservers=null,u.push(r),new hs(function(){n.currentObservers=null,Fo(u,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,i=n.hasError,a=n.thrownError,o=n.isStopped;i?r.error(a):o&&r.complete()},t.prototype.asObservable=function(){var r=new ht;return r.source=this,r},t.create=function(r,n){return new Vu(r,n)},t})(ht),Vu=(function(e){jr(t,e);function t(r,n){var i=e.call(this)||this;return i.destination=r,i.source=n,i}return t.prototype.next=function(r){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,r)},t.prototype.error=function(r){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.call(n,r)},t.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},t.prototype._subscribe=function(r){var n,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&i!==void 0?i:Nd},t})(He);function Yu(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return vv()(Ki(e,Ti(e)))}var wv=new ht(function(e){return e.complete()});function yi(e,t){return t===void 0&&(t=Oi),e=e??bv,Bt(function(r,n){var i,a=!0;r.subscribe(Yt(n,function(o){var u=t(o);(a||!e(i,u))&&(a=!1,i=u,n.next(o))}
22))})}function bv(e,t){return e===t}function Ce(e,t){return Bt(function(r,n){var i=0;r.subscribe(Yt(n,function(a){return e.call(t,a,i++)&&n.next(a)}))})}var Sv=fc(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}});function Ev(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Ti(e),n=zd(e,1/0);return Bt(function(i,a){vc(n)(Ki(qr([i],$r(e)),r)).subscribe(a)})}function _v(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ev.apply(void 0,qr([],$r(e)))}var Kt=(function(e){jr(t,e);function t(r){var n=e.call(this)||this;return n._value=r,n}return Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(r){var n=e.prototype._subscribe.call(this,r);return!n.closed&&r.next(this._value),n},t.prototype.getValue=function(){var r=this,n=r.hasError,i=r.thrownError,a=r._value;if(n)throw i;return this._throwIfClosed(),a},t.prototype.next=function(r){e.prototype.next.call(this,this._value=r)},t})(He),Pv=(function(e){jr(t,e);function t(r,n,i){r===void 0&&(r=1/0),n===void 0&&(n=1/0),i===void 0&&(i=jd);var a=e.call(this)||this;return a._bufferSize=r,a._windowTime=n,a._timestampProvider=i,a._buffer=[],a._infiniteTimeWindow=!0,a._infiniteTimeWindow=n===1/0,a._bufferSize=Math.max(1,r),a._windowTime=Math.max(1,n),a}return t.prototype.next=function(r){var n=this,i=n.isStopped,a=n._buffer,o=n._infiniteTimeWindow,u=n._timestampProvider,d=n._windowTime;i||(a.push(r),!o&&a.push(u.now()+d)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),i=this,a=i._infiniteTimeWindow,o=i._buffer,u=o.slice(),d=0;d<u.length&&!r.closed;d+=a?1:2)r.next(u[d]);return this._checkFinalizedStatuses(r),n},t.prototype._trimBuffer=function(){var r=this,n=r._bufferSize,i=r._timestampProvider,a=r._buffer,o=r._infiniteTimeWindow,u=(o?1:2)*n;if(n<1/0&&u<a.length&&a.splice(0,a.length-u),!o){for(var d=i.now(),f=0,m=1;m<a.length&&a[m]<=d;m+=2)f=m;f&&a.splice(0,f+1)}},t})(He);function Iv(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new He}:t,n=e.resetOnError,i=n===void 0?!0:n,a=e.resetOnComplete,o=a===void 0?!0:a,u=e.resetOnRefCountZero,d=u===void 0?!0:u;return function(f){var m,y,g,w=0,S=!1,E=!1,D=function(){y==null||y.unsubscribe(),y=void 0},M=function(){D(),m=g=void 0,S=E=!1},U=function(){var F=m;M(),F==null||F.unsubscribe()};return Bt(function(F,j){w++,!E&&!S&&D();var $=g=g??r();j.add(function(){w--,w===0&&!E&&!S&&(y=yo(U,d))}),$.subscribe(j),!m&&w>0&&(m=new Pn({next:function(V){return $.next(V)},error:function(V){E=!0,D(),y=yo(M,i,V),$.error(V)},complete:function(){S=!0,D(),y=yo(M,o),$.complete()}}),Xt(F).subscribe(m))})(f)}}function yo(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];if(t===!0){e();return}if(t!==!1){var i=new Pn({next:function(){i.unsubscribe(),e()}});return Xt(t.apply(void 0,qr([],$r(r)))).subscribe(i)}}function Ai(e,t,r){var n,i,a,o,u=!1;return e&&typeof e=="object"?(n=e.bufferSize,o=n===void 0?1/0:n,i=e.windowTime,t=i===void 0?1/0:i,a=e.refCount,u=a===void 0?!1:a,r=e.scheduler):o=e??1/0,Iv({connector:function(){return new Pv(o,t,r)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:u})}function Ni(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Ti(e);return Bt(function(n,i){(r?Yu(e,n,r):Yu(e,n)).subscribe(i)})}function Cv(e,t){return Bt(function(r,n){var i=null,a=0,o=!1,u=function(){return o&&!i&&n.complete()};r.subscribe(Yt(n,function(d){i==null||i.unsubscribe();var f=0,m=a++;Xt(e(d,m)).subscribe(i=Yt(n,function(y){return n.next(t?t(d,y,m,f++):y)},function(){i=null,u()}))},function(){o=!0,u()}))})}function Xd(e){return e.documentData?e.documentData:e.previousDocumentData}function kv(e){switch(e.operation){case"INSERT":return{operation:e.operation,id:e.documentId,doc:e.documentData,previous:null};case"UPDATE":return{operation:e.operation,id:e.documentId,doc:xe.deepFreezeWhenDevMode(e.documentData),previous:e.previousDocumentData?e.previousDocumentData:"UNKNOWN"};case"DELETE":return{operation:e.operation,id:e.documentId,doc:null,previous:e.previousDocumentData}}}var Rv=new Map;function Zd(e){return it(Rv,e,()=>{for(var t=new Array(e.events.length),r=e.events,n=e.collectionName,i=e.isLocal,a=xe.deepFreezeWhenDevMode,o=0;o<r.length;o++){var u=r[o];t[o]={documentId:u.documentId,collectionName:n,isLocal:i,operation:u.operation,documentData:a(u.documentData),previousDocumentData:a(u.previousDocumentData)}}return t})}function Nt(e,t){return new Promise(function(r,n){var i=new Pn({next:function(a){r(a),i.unsubscribe()},error:n,complete:function(){n(new Sv)}});e.subscribe(i)})}function Dv(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=Ti(e),n=zd(e,1/0),i=e;return i.length?i.length===1?Xt(i[0]):vc(n)(Ki(i,r)):wv}var Pt="ï¿¿",It=Number.MIN_SAFE_INTEGER;function xv(e,t){var r=t.selector,n=e.indexes?e.indexes.slice(0):[];t.index&&(n=[t.index]);var i=!!t.sort.find(m=>Object.values(m)[0]==="desc"),a=new Set;Object.keys(r).forEach(m=>{var y=Vt(e,m);y&&y.type==="boolean"&&Object.prototype.hasOwnProperty.call(r[m],"$eq")&&a.add(m)});var o=t.sort.map(m=>Object.keys(m)[0]),u=o.filter(m=>!a.has(m)).join(","),d=-1,f;if(n.forEach(m=>{var y=!0,g=!0,w=m.map(U=>{var F=r[U],j=F?Object.keys(F):[],$={};if(!F||!j.length){var V=g?It:Pt;$={startKey:V,endKey:y?Pt:It,inclusiveStart:!0,inclusiveEnd:!0}}
22else j.forEach(W=>{if(gc.has(W)){var ie=F[W],de=Av(W,ie);$=Object.assign($,de)}});return typeof $.startKey>"u"&&($.startKey=It),typeof $.endKey>"u"&&($.endKey=Pt),typeof $.inclusiveStart>"u"&&($.inclusiveStart=!0),typeof $.inclusiveEnd>"u"&&($.inclusiveEnd=!0),g&&!$.inclusiveStart&&(g=!1),y&&!$.inclusiveEnd&&(y=!1),$}),S=w.map(U=>U.startKey),E=w.map(U=>U.endKey),D={index:m,startKeys:S,endKeys:E,inclusiveEnd:y,inclusiveStart:g,sortSatisfiedByIndex:!i&&u===m.filter(U=>!a.has(U)).join(","),selectorSatisfiedByIndex:Kv(m,t.selector,S,E)},M=Nv(e,t,D);(M>=d||t.index)&&(d=M,f=D)}),!f)throw ee("SNH",{query:t});return f}var gc=new Set(["$eq","$gt","$gte","$lt","$lte"]),Ov=new Set(["$eq","$gt","$gte"]),Tv=new Set(["$eq","$lt","$lte"]);function Kv(e,t,r,n){var i=Object.entries(t),a=i.find(([W,ie])=>{if(!e.includes(W))return!0;var de=Object.entries(ie).find(([Se,ue])=>!gc.has(Se));return de});if(a||t.$and||t.$or)return!1;var o=[],u=new Set;for(var[d,f]of Object.entries(t)){if(!e.includes(d))return!1;var m=Object.keys(f).filter(W=>Ov.has(W));if(m.length>1)return!1;var y=m[0];if(y&&u.add(d),y!=="$eq"){if(o.length>0)return!1;o.push(y)}}var g=[],w=new Set;for(var[S,E]of Object.entries(t)){if(!e.includes(S))return!1;var D=Object.keys(E).filter(W=>Tv.has(W));if(D.length>1)return!1;var M=D[0];if(M&&w.add(S),M!=="$eq"){if(g.length>0)return!1;g.push(M)}}var U=0;for(var F of e){for(var j of[u,w]){if(!j.has(F)&&j.size>0)return!1;j.delete(F)}var $=r[U],V=n[U];if($!==V&&u.size>0&&w.size>0)return!1;U++}return!0}function Av(e,t){switch(e){case"$eq":return{startKey:t,endKey:t,inclusiveEnd:!0,inclusiveStart:!0};case"$lte":return{endKey:t,inclusiveEnd:!0};case"$gte":return{startKey:t,inclusiveStart:!0};case"$lt":return{endKey:t,inclusiveEnd:!1};case"$gt":return{startKey:t,inclusiveStart:!1};default:throw new Error("SNH")}}function Nv(e,t,r){var n=0,i=m=>{m>0&&(n=n+m)},a=10,o=uo(r.startKeys,m=>m!==It&&m!==Pt);i(o*a);var u=uo(r.startKeys,m=>m!==Pt&&m!==It);i(u*a);var d=uo(r.startKeys,(m,y)=>m===r.endKeys[y]);i(d*a*1.5);var f=r.sortSatisfiedByIndex?5:0;return i(f),n}class fs extends Error{}const vi=Symbol("missing"),eh=Object.freeze(new Error("mingo: cycle detected while processing object/array")),ps=e=>{const t=Da(e);let r=0,n=t.length;for(;n;)r=(r<<5)-r^t.charCodeAt(--n);return r>>>0},dr=e=>typeof e!="object"&&typeof e!="function"||e===null,th=e=>dr(e)||wi(e)||Fr(e),rh={undefined:1,null:2,number:3,string:4,symbol:5,object:6,array:7,arraybuffer:8,boolean:9,date:10,regexp:11,function:12},gr=(e,t)=>{e===vi&&(e=void 0),t===vi&&(t=void 0);const[r,n]=[e,t].map(i=>rh[gi(i)]||0);return r!==n?r-n:pr(e,t)?0:e<t?-1:e>t?1:0};var Ci,Wt,Ar;const Vc=class Vc extends Map{constructor(){super();Le(this,Ci,ps);Le(this,Wt,new Map);Le(this,Ar,r=>{const n=Q(this,Ci).call(this,r);return[(Q(this,Wt).get(n)||[]).find(i=>pr(i,r)),n]})}static init(r){const n=new Vc;return r&&Ue(n,Ci,r),n}clear(){super.clear(),Q(this,Wt).clear()}delete(r){if(dr(r))return super.delete(r);const[n,i]=Q(this,Ar).call(this,r);return super.delete(n)?(Q(this,Wt).set(i,Q(this,Wt).get(i).filter(a=>!pr(a,n))),!0):!1}get(r){if(dr(r))return super.get(r);const[n,i]=Q(this,Ar).call(this,r);return super.get(n)}has(r){if(dr(r))return super.has(r);const[n,i]=Q(this,Ar).call(this,r);return super.has(n)}set(r,n){if(dr(r))return super.set(r,n);const[i,a]=Q(this,Ar).call(this,r);if(super.has(i))super.set(i,n);else{super.set(r,n);const o=Q(this,Wt).get(a)||[];o.push(r),Q(this,Wt).set(a,o)}return this}get size(){return super.size}};Ci=new WeakMap,Wt=new WeakMap,Ar=new WeakMap;let qa=Vc;function Ve(e,t){if(!e)throw new fs(t)}const Mv=Object.keys(rh).reduce((e,t)=>(e["[object "+t[0].toUpperCase()+t.substring(1)+"]"]=t,e),{});function gi(e){var r,n;const t=Object.prototype.toString.call(e);return t==="[object Object]"?((n=(r=e==null?void 0:e.constructor)==null?void 0:r.name)==null?void 0:n.toLowerCase())||"object":Mv[t]||t.substring(8,t.length-1).toLowerCase()}const pn=e=>typeof e=="boolean",Dt=e=>typeof e=="string",Bv=e=>typeof e=="symbol",dt=e=>!isNaN(e)&&typeof e=="number",ke=Array.isArray;function at(e){if(!e)return!1;const t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&gi(e)==="object"}const nh=e=>!dr(e),wi=e=>e instanceof Date,Fr=e=>e instanceof RegExp,wc=e=>typeof e=="function",ft=e=>e==null,Fv=(e,t=!0)=>!!e||t&&e==="",bc=e=>ft(e)||Dt(e)&&!e||ke(e)&&e.length===0||at(e)&&Object.keys(e).length===0,Mi=e=>ke(e)?e:[e],In=(e,t)=>!!e&&Object.prototype.hasOwnProperty.call(e,t),Lv=e=>typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e),bi=(e,t)=>{if(ft(e)||pn(e)||dt(e)||Dt(e))return e;if(wi(e))return new Date(e);if(Fr(e))return new RegExp(e);if(Lv(e)){const r=e.constructor;return new r(e)}if(t instanceof Set||(t=new Set),t.has(e))throw eh;t.add(e);try{if(ke(e)){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=bi(e[n],t);return r}if(at(e)){const r={};for(const n of Object.keys(e))r[n]=bi(e[n],t);return r}}finally{t.delete(e)}return e},Qu=e=>e===vi;function Lo(e,t){if(Qu(e)||ft(e))return t;if(Qu(t)||ft(t))return e;if(dr(e)||dr(t))return t;ke(e)&&ke(t)&&Ve(e.length===t.length,"arrays must be of equal length to merge.");for(const r of Object.keys(t))e[r]=Lo(e[r],t[r]);return e}function Uv(e,t=ps){const r=[qa.init(t),qa.init(t)];if(e.length===0)return[];if(e.some(n=>n.length===0))return[];if(e.length===1)return[...e];
22e[e.length-1].forEach(n=>r[0].set(n,!0));for(let n=e.length-2;n>-1;n--){if(e[n].forEach(i=>{r[0].has(i)&&r[1].set(i,!0)}),r[1].size===0)return[];r.reverse(),r[1].clear()}return Array.from(r[0].keys())}function ih(e,t=1){const r=new Array;function n(i,a){for(let o=0,u=i.length;o<u;o++)ke(i[o])&&(a>0||a<0)?n(i[o],Math.max(-1,a-1)):r.push(i[o])}return n(e,t),r}function Wv(e){const t={};for(;e;){for(const r of Object.getOwnPropertyNames(e))r in t||(t[r]=e[r]);e=Object.getPrototypeOf(e)}return t}function ah(e){for(;e;){if(Object.getOwnPropertyNames(e).includes("toString"))return e.toString!==Object.prototype.toString;e=Object.getPrototypeOf(e)}return!1}function pr(e,t){if(e===t||Object.is(e,t))return!0;if(e===null||t===null||typeof e!=typeof t||typeof e!="object"||e.constructor!==t.constructor)return!1;if(e instanceof Date)return+e==+t;if(e instanceof RegExp)return e.toString()===t.toString();const r=e.constructor;if(r===Array||r===Object){const n=Object.keys(e).sort(),i=Object.keys(t).sort();if(n.length!==i.length)return!1;for(let a=0,o=n[a];a<n.length;o=n[++a])if(o!==i[a]||!pr(e[o],t[o]))return!1;return!0}return ah(e)&&e.toString()===t.toString()}const Da=(e,t)=>{if(e===null)return"null";if(e===void 0)return"undefined";if(Dt(e)||dt(e)||pn(e))return JSON.stringify(e);if(wi(e))return e.toISOString();if(Fr(e)||Bv(e)||wc(e))return e.toString();if(t instanceof Set||(t=new Set),t.has(e))throw eh;try{if(t.add(e),ke(e))return"["+e.map(n=>Da(n,t)).join(",")+"]";if(at(e))return"{"+Object.keys(e).sort().map(i=>`${i}:${Da(e[i],t)}`).join()+"}";const r=ah(e)?e.toString():Da(Wv(e),t);return gi(e)+"("+r+")"}finally{t.delete(e)}};function $v(e,t){return ft(e)?null:(t=t||ps,t(e))}function qv(e,t,r=ps){if(e.length<1)return new Map;const n=new Map,i=new Map;for(let a=0;a<e.length;a++){const o=e[a],u=t(o,a),d=$v(u,r);if(d===null)i.has(null)?i.get(null).push(o):i.set(null,[o]);else{const f=n.has(d)?n.get(d).find(m=>pr(m,u)):null;ft(f)?(i.set(u,[o]),n.has(d)?n.get(d).push(u):n.set(d,[u])):i.get(f).push(o)}}return i}function Uo(e,t){return nh(e)?e[t]:void 0}function Hv(e,t){if(t<1)return e;for(;t--&&e.length===1;)e=e[0];return e}function Hr(e,t,r){let n=0;function i(o,u){let d=o;for(let f=0;f<u.length;f++){const m=u[f];if(/^\d+$/.exec(m)===null&&ke(d)){if(f===0&&n>0)break;n+=1;const g=u.slice(f);d=d.reduce((w,S)=>{const E=i(S,g);return E!==void 0&&w.push(E),w},[]);break}else d=Uo(d,m);if(d===void 0)break}return d}const a=th(e)?e:i(e,t.split("."));return ke(a)&&(r!=null&&r.unwrapArray)?Hv(a,n):a}function ii(e,t,r){const n=t.indexOf("."),i=n==-1?t:t.substring(0,n),a=t.substring(n+1),o=n!=-1;if(ke(e)){const f=/^\d+$/.test(i),m=f&&(r!=null&&r.preserveIndex)?[...e]:[];if(f){const y=parseInt(i);let g=Uo(e,y);o&&(g=ii(g,a,r)),r!=null&&r.preserveIndex?m[y]=g:m.push(g)}else for(const y of e){const g=ii(y,t,r);r!=null&&r.preserveMissing?m.push(g??vi):(g!=null||r!=null&&r.preserveIndex)&&m.push(g)}return m}const u=r!=null&&r.preserveKeys?{...e}:{};let d=Uo(e,i);if(o&&(d=ii(d,a,r)),d!==void 0)return u[i]=d,u}function Wo(e){if(ke(e))for(let t=e.length-1;t>=0;t--)e[t]===vi?e.splice(t,1):Wo(e[t]);else if(at(e))for(const t in e)In(e,t)&&Wo(e[t])}const Xu=/^\d+$/;function Ha(e,t,r,n){const i=t.split("."),a=i[0],o=i.slice(1).join(".");if(i.length===1)(at(e)||ke(e)&&Xu.test(a))&&r(e,a);else{n!=null&&n.buildGraph&&ft(e[a])&&(e[a]={});const u=e[a];if(!u)return;const d=!!(i.length>1&&Xu.test(i[1]));ke(u)&&(n!=null&&n.descendArray)&&!d?u.forEach(f=>Ha(f,o,r,n)):Ha(u,o,r,n)}}function Jv(e,t,r){Ha(e,t,(n,i)=>{n[i]=wc(r)?r(n[i]):r},{buildGraph:!0})}function Zu(e,t,r){Ha(e,t,(n,i)=>{if(ke(n)){if(/^\d+$/.test(i))n.splice(parseInt(i),1);else if(r&&r.descendArray)for(const a of n)at(a)&&delete a[i]}else at(n)&&delete n[i]},r)}const jv=/^\$[a-zA-Z0-9_]+$/;function zr(e){return jv.test(e)}function sh(e){if(th(e))return Fr(e)?{$regex:e}:{$eq:e};if(nh(e)){if(!Object.keys(e).some(zr))return{$eq:e};if(In(e,"$regex")){const t={...e};return t.$regex=new RegExp(e.$regex,e.$options),delete t.$options,t}}return e}var $o=(e=>(e[e.CLONE_OFF=0]="CLONE_OFF",e[e.CLONE_INPUT=1]="CLONE_INPUT",e[e.CLONE_OUTPUT=2]="CLONE_OUTPUT",e[e.CLONE_ALL=3]="CLONE_ALL",e))($o||{}),Ge,ki,$t;const li=class li{constructor(t,r,n){Le(this,Ge);Le(this,ki);Le(this,$t);Ue(this,Ge,t),this.update(r,n)}static init(t,r,n){var i;return t instanceof li?new li(Q(t,Ge),t.root??r,{...Q(t,$t),...n,variables:Object.assign({},(i=Q(t,$t))==null?void 0:i.variables,n==null?void 0:n.variables)}):new li(t,r,n)}update(t,r){var i;Ue(this,ki,t);const n=Object.assign({},(i=Q(this,$t))==null?void 0:i.variables,r==null?void 0:r.variables);return Object.keys(n).length?Ue(this,$t,{...r,variables:n}):Ue(this,$t,r??{}),this}getOptions(){return Object.freeze({...Q(this,Ge),context:Cn.from(Q(this,Ge).context)})}get root(){return Q(this,ki)}get local(){return Q(this,$t)}get idKey(){return Q(this,Ge).idKey}get collation(){var t;return(t=Q(this,Ge))==null?void 0:t.collation}get processingMode(){var t;return((t=Q(this,Ge))==null?void 0:t.processingMode)||0}get useStrictMode(){var t;return(t=Q(this,Ge))==null?void 0:t.useStrictMode}get scriptEnabled(){var t;return(t=Q(this,Ge))==null?void 0:t.scriptEnabled}get useGlobalContext(){var t;return(t=Q(this,Ge))==null?void 0:t.useGlobalContext}get hashFunction(){var t;return(t=Q(this,Ge))==null?void 0:t.hashFunction}get collectionResolver(){var t;return(t=Q(this,Ge))==null?void 0:t.collectionResolver}get jsonSchemaValidator(){var t;return(t=Q(this,Ge))==null?void 0:t.jsonSchemaValidator}get variables(){var t;return(t=Q(this,Ge))==null?void 0:t.variables}get context(){var t;return(t=Q(this,Ge))==null?void 0:t.context}};Ge=new WeakMap,ki=new WeakMap,$t=new WeakMap;let Si=li;function zv(e){return e instanceof Si?e.getOptions():Object.freeze({idKey:"_id",scriptEnabled:!0,useStrictMode:!0,useGlobalContext:!0,processingMode:0,...e,context:e!=null&&e.context?Cn.from(e==null?void 0:e.context):Cn.init()})}var cr;const cs=class cs{constructor(){Le(this,cr,new Map)}static init(){return new cs}static from(t){const r=cs.init();return ft(t)||Q(t,cr).forEach((n,i)=>r.addOperators(i,n)),r}addOperators(t,r){Q(this,cr).has(t)||Q(this,cr).set(t,{});for(const[n,i]of Object.entries(r))this.getOperator(t,n)||(Q(this,cr).get(t)[n]=i);return this}getOperator(t,r){return(Q(this,cr).get(t)??{})[r]??null}addAccumulatorOps(t){return this.addOperators("accumulator",t)}addExpressionOps(t){return this.addOperators("expression",t)}addQueryOps(t){return this.addOperators("query",t)}addPipelineOps(t){return this.addOperators("pipeline",t)}addProjectionOps(t){return this.addOperators("projection",t)}addWindowOps(t){return this.addOperators("window",t)}};cr=new WeakMap;let Cn=cs;const Tr=Cn.init();function el(e,t){for(const[r,n]of Object.entries(t)){Ve(wc(n)&&zr(r),`'${r}' is not a valid operator`);const i=Ei(e,r,null);Ve(!i||n===i,`${r} already exists for '${e}' operators. Cannot change operator function once registered.`)}switch(e){case"accumulator":Tr.addAccumulatorOps(t);break;case"expression":Tr.addExpressionOps(t);break;case"pipeline":Tr.addPipelineOps(t);break;case"projection":Tr.addProjectionOps(t);break;case"query":Tr.addQueryOps(t);break;case"window":Tr.addWindowOps(t);break}}function Ei(e,t,r){const{context:n,useGlobalContext:i}=r||{},a=n?n.getOperator(e,t):null;return!a&&i?Tr.getOperator(e,t):a}function cn(e,t,r,n){const i=Si.init(n,e);return r&&zr(r)?oh(e,t,r,i):Ja(e,t,i)}const Gv=["$$ROOT","$$CURRENT","$$REMOVE","$$NOW"];function Ja(e,t,r){var n;if(Dt(t)&&t.length>0&&t[0]==="$"){if(Vv.includes(t))return t;let i=r.root;const a=t.split(".");if(Gv.includes(a[0])){switch(a[0]){case"$$ROOT":break;case"$$CURRENT":i=e;break;case"$$REMOVE":i=void 0;break;case"$$NOW":i=new Date;break}
22t=t.slice(a[0].length+1)}else if(a[0].slice(0,2)==="$$"){i=Object.assign({},r.variables,{this:e},(n=r==null?void 0:r.local)==null?void 0:n.variables);const o=a[0].slice(2);Ve(In(i,o),`Use of undefined variable: ${o}`),t=t.slice(2)}else t=t.slice(1);return t===""?i:Hr(i,t)}if(ke(t))return t.map(i=>Ja(e,i,r));if(at(t)){const i={},a=Object.entries(t);for(const[o,u]of a){if(zr(o))return Ve(a.length==1,"expression must have single operator."),oh(e,u,o,r);i[o]=Ja(e,u,r)}return i}return t}function oh(e,t,r,n){const i=Ei("expression",r,n);if(i)return i(e,t,n);const a=Ei("accumulator",r,n);return Ve(!!a,`accumulator '${r}' is not registered.`),ke(e)||(e=Ja(e,t,n),t=null),Ve(ke(e),`arguments must resolve to array for ${r}.`),a(e,t,n)}const Vv=["$$KEEP","$$PRUNE","$$DESCEND"];function _i(e){return e instanceof tl?e:new tl(e)}function Yv(...e){let t=0;return _i(()=>{for(;t<e.length;){const r=e[t].next();if(!r.done)return r;t++}return{done:!0}})}function Qv(e){return!!e&&typeof e=="object"&&(e==null?void 0:e.next)instanceof Function}function Xv(e,t){const r=e.slice(t+1);e.splice(t),Array.prototype.push.apply(e,r)}const qo=new Error;function Zv(e,t,r){let n=!1,i=-1,a=0;return function(o){try{e:for(;!n;){let u=e();i++;let d=-1;const f=t.length;let m=!1;for(;++d<f;){const y=t[d];switch(y.action){case 0:u=y.func(u,i);break;case 1:if(!y.func(u,i))continue e;break;case 2:--y.count,y.count||(m=!0);break;case 3:--y.count,y.count||Xv(t,d);continue e;default:break e}}if(n=m,o)r[a++]=u;else return{value:u,done:!1}}}catch(u){if(u!==qo)throw u}return n=!0,{done:n}}}var Nr,yn,vn,id;let tl=(id=class{constructor(t){Le(this,Nr);Le(this,yn);Le(this,vn);Ue(this,Nr,[]),Ue(this,yn,[]),this.isDone=!1;let r;if(t instanceof Function&&(t={next:t}),Qv(t)){const n=t;r=()=>{const i=n.next();if(i.done)throw qo;return i.value}}else if(ke(t)){const n=t,i=n.length;let a=0;r=()=>{if(a<i)return n[a++];throw qo}}else if(!(t instanceof Function))throw new fs("Lazy must be initialized with an array, generator, or function.");Ue(this,vn,Zv(r,Q(this,Nr),Q(this,yn)))}push(t,r){return typeof r=="function"?Q(this,Nr).push({action:t,func:r}):typeof r=="number"&&Q(this,Nr).push({action:t,count:r}),this}next(){return Q(this,vn).call(this)}map(t){return this.push(0,t)}filter(t){return this.push(1,t)}take(t){return t>0?this.push(2,t):this}drop(t){return t>0?this.push(3,t):this}transform(t){const r=this;let n;return _i(()=>(n||(n=_i(t(r.value()))),n.next()))}value(){return this.isDone||(this.isDone=Q(this,vn).call(this,!0).done),Q(this,yn)}each(t){for(;;){const r=this.next();if(r.done)break;if(t(r.value)===!1)return!1}return!0}reduce(t,r){let n=this.next();for(r===void 0&&!n.done&&(r=n.value,n=this.next());!n.done;)r=t(r,n.value),n=this.next();return r}size(){return this.reduce((t,r)=>++t,0)}[Symbol.iterator](){return this}},Nr=new WeakMap,yn=new WeakMap,vn=new WeakMap,id);const eg=(e,t,r)=>e.take(t),ch=(e,t,r)=>bc(t)?e:(lh(t,r),e.map(uh(t,Si.init(r))));function uh(e,t,r=!0){const n=t.idKey,i=Object.keys(e),a=new Array,o=new Array,u={};for(const w of i){const S=e[w];if(dt(S)||pn(S))S?o.push(w):a.push(w);else if(ke(S))u[w]=E=>S.map(D=>cn(E,D,null,t.update(E))??null);else if(at(S)){const E=Object.keys(S),D=E.length==1?E[0]:"",M=Ei("projection",D,t);M?D==="$slice"&&!Mi(S[D]).every(dt)?u[w]=F=>cn(F,S,w,t.update(F)):u[w]=F=>M(F,S[D],w,t.update(F)):zr(D)?u[w]=U=>cn(U,S[D],D,t):(lh(S,t),u[w]=U=>{if(!In(U,w))return cn(U,S,null,t);r&&t.update(U);const F=Hr(U,w),j=uh(S,t,!1);return ke(F)?F.map(j):at(F)?j(F):j(U)})}else u[w]=Dt(S)&&S[0]==="$"?E=>cn(E,S,w,t):E=>S}const d=Object.keys(u),f=a.includes(n);if(r&&f&&a.length===1&&!o.length&&!d.length)return w=>{const S={...w};return delete S[n],S};const y=r&&!f&&!o.includes(n),g={preserveMissing:!0};return w=>{const S={};if(a.length&&!o.length){Lo(S,w);for(const E of a)Zu(S,E,{descendArray:!0})}for(const E of o){const D=ii(w,E,g)??{};Lo(S,D)}o.length&&Wo(S);for(const E of d){const D=u[E](w);D===void 0?Zu(S,E,{descendArray:!0}):Jv(S,E,D)}return y&&In(w,n)&&(S[n]=Hr(w,n)),S}}function lh(e,t){let r=!1,n=!1;for(const[i,a]of Object.entries(e))Ve(!i.startsWith("$"),"Field names may not start with '$'."),Ve(!i.endsWith(".$"),"Positional projection operator '$' is not supported."),i!==(t==null?void 0:t.idKey)&&(a===0||a===!1?r=!0:(a===1||a===!0)&&(n=!0),Ve(!(r&&n),"Projection cannot have a mix of inclusion and exclusion."))}const tg=(e,t,r)=>e.drop(t),dh=(e,t,r)=>{if(bc(t)||!at(t))return e;let n=gr;const i=r.collation;return at(i)&&Dt(i.locale)&&(n=ng(i)),e.transform(a=>{const o=Object.keys(t);for(const u of o.reverse()){const d=qv(a,y=>Hr(y,u),r.hashFunction),f=Array.from(d.keys()).sort(n);t[u]===-1&&f.reverse();let m=0;for(const y of f)for(const g of d.get(y))a[m++]=g;Ve(m==a.length,"bug: counter must match collection size.")}return a})},rg={1:"base",2:"accent",3:"variant"};function ng(e){const t={sensitivity:rg[e.strength||3],caseFirst:e.caseFirst==="off"?"false":e.caseFirst||"false",numeric:e.numericOrdering||!1,ignorePunctuation:e.alternate==="shifted"};(e.caseLevel||!1)===!0&&(t.sensitivity==="base"&&(t.sensitivity="case"),t.sensitivity==="accent"&&(t.sensitivity="variant"));const r=new Intl.Collator(e.locale,t);return(n,i)=>{if(!Dt(n)||!Dt(i))return gr(n,i);const a=r.compare(n,i);return a<0?-1:a>0?1:0}}const ig={$sort:dh,$skip:tg,$limit:eg};var Ri,Di,gn,qt,ur,lt,Ht;class ag{constructor(t,r,n,i){Le(this,Ri);Le(this,Di);Le(this,gn);Le(this,qt);Le(this,ur,{});Le(this,lt,null);Le(this,Ht,[]);Ue(this,Ri,t),Ue(this,Di,r),Ue(this,gn,n),Ue(this,qt,i)}fetch(){if(Q(this,lt))return Q(this,lt);Ue(this,lt,_i(Q(this,Ri)).filter(Q(this,Di)));const t=Q(this,qt).processingMode;t&$o.CLONE_INPUT&&Q(this,lt).map(bi);for(const r of["$sort","$skip","$limit"])In(Q(this,ur),r)&&Ue(this,lt,ig[r](Q(this,lt),Q(this,ur)[r],Q(this,qt)));return Object.keys(Q(this,gn)).length&&Ue(this,lt,ch(Q(this,lt),Q(this,gn),Q(this,qt))),t&$o.CLONE_OUTPUT&&Q(this,lt).map(bi),Q(this,lt)}fetchAll(){const t=_i([...Q(this,Ht)]);return Ue(this,Ht,[]),Yv(t,this.fetch())}
22all(){return this.fetchAll().value()}count(){return this.all().length}skip(t){return Q(this,ur).$skip=t,this}limit(t){return Q(this,ur).$limit=t,this}sort(t){return Q(this,ur).$sort=t,this}collation(t){return Ue(this,qt,{...Q(this,qt),collation:t}),this}next(){if(Q(this,Ht).length>0)return Q(this,Ht).pop();const t=this.fetch().next();if(!t.done)return t.value}hasNext(){if(Q(this,Ht).length>0)return!0;const t=this.fetch().next();return t.done?!1:(Q(this,Ht).push(t.value),!0)}map(t){return this.all().map(t)}forEach(t){this.all().forEach(t)}[Symbol.iterator](){return this.fetchAll()}}Ri=new WeakMap,Di=new WeakMap,gn=new WeakMap,qt=new WeakMap,ur=new WeakMap,lt=new WeakMap,Ht=new WeakMap;const sg=new Set(Array.from(["$and","$or","$nor","$expr","$jsonSchema"]));var wn,lr,Mr;class Bi{constructor(t,r){Le(this,wn);Le(this,lr);Le(this,Mr);Ue(this,Mr,bi(t)),Ue(this,lr,zv(r)),Ue(this,wn,[]),this.compile()}compile(){Ve(at(Q(this,Mr)),`query criteria must be an object: ${JSON.stringify(Q(this,Mr))}`);const t={};for(const[r,n]of Object.entries(Q(this,Mr))){if(r==="$where")Ve(Q(this,lr).scriptEnabled,"$where operator requires 'scriptEnabled' option to be true."),Object.assign(t,{field:r,expr:n});else if(sg.has(r))this.processOperator(r,r,n);else{Ve(!zr(r),`unknown top level operator: ${r}`);for(const[i,a]of Object.entries(sh(n)))this.processOperator(r,i,a)}t.field&&this.processOperator(t.field,t.field,t.expr)}}processOperator(t,r,n){const i=Ei("query",r,Q(this,lr));Ve(!!i,`unknown query operator ${r}`),Q(this,wn).push(i(t,n,Q(this,lr)))}test(t){return Q(this,wn).every(r=>r(t))}find(t,r){return new ag(t,n=>this.test(n),r||{},Q(this,lr))}remove(t){return t.reduce((r,n)=>(this.test(n)||r.push(n),r),[])}}wn=new WeakMap,lr=new WeakMap,Mr=new WeakMap;const og=["monday","mon","tuesday","tue","wednesday","wed","thursday","thu","friday","fri","saturday","sat","sunday","sun"];new Set(og);function pt(e){return(r,n,i)=>{const a={unwrapArray:!0},o=Math.max(1,r.split(".").length-1);return u=>{const d=Hr(u,r,a);return e(d,n,{...i,depth:o})}}}function hh(e,t,r){return pr(e,t)||ft(e)&&ft(t)?!0:ke(e)?e.some(n=>pr(n,t))||ih(e,r==null?void 0:r.depth).some(n=>pr(n,t)):!1}function cg(e,t,r){return!hh(e,t,r)}function fh(e,t,r){return ft(e)?t.some(n=>n===null):Uv([Mi(e),t],r==null?void 0:r.hashFunction).length>0}function ug(e,t,r){return!fh(e,t,r)}function lg(e,t,r){return ms(e,t,(n,i)=>gr(n,i)<0)}function dg(e,t,r){return ms(e,t,(n,i)=>gr(n,i)<=0)}function hg(e,t,r){return ms(e,t,(n,i)=>gr(n,i)>0)}function fg(e,t,r){return ms(e,t,(n,i)=>gr(n,i)>=0)}function pg(e,t,r){return Mi(e).some(n=>t.length===2&&n%t[0]===t[1])}function mg(e,t,r){const n=Mi(e),i=a=>Dt(a)&&Fv(t.exec(a),r==null?void 0:r.useStrictMode);return n.some(i)||ih(n,1).some(i)}function yg(e,t,r){return Array.isArray(e)&&e.length===t}function vg(e){return zr(e)&&["$and","$or","$nor"].indexOf(e)===-1}function gg(e,t,r){if(ke(e)&&!bc(e)){let n=o=>o,i=t;Object.keys(t).every(vg)&&(i={temp:t},n=o=>({temp:o}));const a=new Bi(i,r);for(let o=0,u=e.length;o<u;o++)if(a.test(n(e[o])))return!0}return!1}const rl=e=>e===null,wg={array:ke,boolean:pn,bool:pn,date:wi,number:dt,int:dt,long:dt,double:dt,decimal:dt,null:rl,object:at,regexp:Fr,regex:Fr,string:Dt,undefined:ft,function:e=>{throw new fs("unsupported type key `function`.")},1:dt,2:Dt,3:at,4:ke,6:ft,8:pn,9:wi,10:rl,11:Fr,16:dt,18:dt,19:dt};function nl(e,t,r){const n=wg[t];return n?n(e):!1}function bg(e,t,r){return ke(t)?t.findIndex(n=>nl(e,n))>=0:nl(e,t)}function ms(e,t,r){return Mi(e).some(n=>gi(n)===gi(t)&&r(n,t))}const il=(e,t)=>{const r={};return e.split("").forEach((n,i)=>r[n]=t*(i+1)),r};({...il("ABCDEFGHIKLM",1),...il("NOPQRSTUVWXY",-1)});const al={undefined:null,null:null,NaN:NaN,Infinity:new Error,"-Infinity":new Error};function mt(e,t=al){const r=Object.assign({},al,t),n=new Set(Object.keys(r));return(i,a,o)=>{const u=cn(i,a,null,o);if(n.has(`${u}`)){const d=r[`${u}`];if(d instanceof Error)throw new fs(`cannot apply $${e.name} to -inf, value must in (-inf,inf)`);return d}return e(u)}}mt(Math.acos,{Infinity:1/0,0:new Error});mt(Math.acosh,{Infinity:1/0,0:new Error});mt(Math.asin);mt(Math.asinh,{Infinity:1/0,"-Infinity":-1/0});mt(Math.atan);mt(Math.atanh,{1:1/0,"-1":-1/0}
22);mt(Math.cos);mt(Math.cosh,{"-Infinity":1/0,Infinity:1/0});const Sg=Math.PI/180;mt(e=>e*Sg,{Infinity:1/0,"-Infinity":1/0});const Eg=180/Math.PI;mt(e=>e*Eg,{Infinity:1/0,"-Infinity":-1/0});mt(Math.sin);mt(Math.sinh,{"-Infinity":-1/0,Infinity:1/0});mt(Math.tan);const _g=(e,t,r)=>{Ve(ke(t),"Invalid expression: $and expects value to be an Array.");const n=t.map(i=>new Bi(i,r));return i=>n.every(a=>a.test(i))},ph=(e,t,r)=>{Ve(ke(t),"Invalid expression. $or expects value to be an Array");const n=t.map(i=>new Bi(i,r));return i=>n.some(a=>a.test(i))},Pg=(e,t,r)=>{Ve(ke(t),"Invalid expression. $nor expects value to be an array.");const n=ph("$or",t,r);return i=>!n(i)},Ig=(e,t,r)=>{const n={};n[e]=sh(t);const i=new Bi(n,r);return a=>!i.test(a)},Cg=pt(hh),kg=pt(hg),Rg=pt(fg),Dg=pt(fh),xg=pt(lg),Og=pt(dg),Tg=pt(cg),Kg=pt(ug),Ag=pt(pg),Ng=pt(mg),Mg=pt(gg),Bg=pt(yg),Fg=(e,t,r)=>{const n=e.includes("."),i=!!t;return!n||e.match(/\.\d+$/)?a=>Hr(a,e)!==void 0===i:a=>{const o=ii(a,e,{preserveIndex:!0}),u=Hr(o,e.substring(0,e.lastIndexOf(".")));return ke(u)?u.some(d=>d!==void 0)===i:u!==void 0===i}},Lg=pt(bg);var sl=!1;function Ug(e){return sl||(el("pipeline",{$sort:dh,$project:ch}),el("query",{$and:_g,$eq:Cg,$elemMatch:Mg,$exists:Fg,$gt:kg,$gte:Rg,$in:Dg,$lt:xg,$lte:Og,$ne:Tg,$nin:Kg,$mod:Ag,$nor:Pg,$not:Ig,$or:ph,$regex:Ng,$size:Bg,$type:Lg}),sl=!0),new Bi(e)}function mn(e,t){var r=et(e.primaryKey);t=Oe(t);var n=st(t);if(typeof n.skip!="number"&&(n.skip=0),n.selector?(n.selector=n.selector,Object.entries(n.selector).forEach(([y,g])=>{(typeof g!="object"||g===null)&&(n.selector[y]={$eq:g})})):n.selector={},n.index){var i=bn(n.index);i.includes(r)||i.push(r),n.index=i}if(n.sort){var m=n.sort.find(y=>iy(y)===r);m||(n.sort=n.sort.slice(0),n.sort.push({[r]:"asc"}))}else if(n.index)n.sort=n.index.map(y=>({[y]:"asc"}));else{if(e.indexes){var a=new Set;Object.entries(n.selector).forEach(([y,g])=>{var w=!1;typeof g=="object"&&g!==null?w=!!Object.keys(g).find(S=>gc.has(S)):w=!0,w&&a.add(y)});var o=-1,u;e.indexes.forEach(y=>{var g=La(y)?y:[y],w=g.findIndex(S=>!a.has(S));w>0&&w>o&&(o=w,u=g)}),u&&(n.sort=u.map(y=>({[y]:"asc"})))}if(!n.sort)if(e.indexes&&e.indexes.length>0){var d=e.indexes[0],f=La(d)?d:[d];n.sort=f.map(y=>({[y]:"asc"}))}else n.sort=[{[r]:"asc"}]}return n}function ys(e,t){if(!t.sort)throw ee("SNH",{query:t});var r=[];t.sort.forEach(i=>{var a=Object.keys(i)[0],o=Object.values(i)[0];r.push({key:a,direction:o,getValueFn:gd(a)})});var n=(i,a)=>{for(var o=0;o<r.length;++o){var u=r[o],d=u.getValueFn(i),f=u.getValueFn(a);if(d!==f){var m=u.direction==="asc"?gr(d,f):gr(f,d);return m}}};return n}function Fi(e,t){if(!t.sort)throw ee("SNH",{query:t});var r=Ug(t.selector),n=i=>r.test(i);return n}async function Xn(e,t){var r=await e.exec();if(!r)return null;if(Array.isArray(r))return Promise.all(r.map(i=>t(i)));if(r instanceof Map)return Promise.all([...r.values()].map(i=>t(i)));var n=await t(r);return n}function vs(e,t){if(!t.sort)throw ee("SNH",{query:t});var r=xv(e,t);return{query:t,queryPlan:r}}var Wg="_rxdb_internal";async function Kn(e,t){var r=await e.findDocumentsById([t],!1),n=r[0];if(n)return n}async function kn(e,t,r){var n=await e.bulkWrite([t],r);if(n.error.length>0){var i=n.error[0];throw i}else{var a=et(e.schema.primaryKey),o=St(a,[t],n),u=o[0];return u}}function $g(e,t){var r=Kn(e,t),n=e.changeStream().pipe(We(i=>i.events.find(a=>a.documentId===t)),Ce(i=>!!i),We(i=>Promise.resolve(Z(i).documentData)),Ni(r),Cv(i=>i),Ce(i=>!!i));return n}function Pi(e){return Object.assign({},...e)}function ja(e,t,r,n){if(n)throw n.status===409?ee("CONFLICT",{collection:e.name,id:t,writeError:n,data:r}):n.status===422?ee("VD2",{collection:e.name,id:t,writeError:n,data:r}):n}function Sc(e,t,r,n,i,a,o){for(var u=!!e.schema.attachments,d=[],f=[],m=[],y=T
22n(10),g={id:y,events:[],checkpoint:null,context:i},w=g.events,S=[],E=[],D=[],M=r.size>0,U,F=n.length,j=function(){var V=n[$],W=V.document,ie=V.previous,de=W[t],Se=W._deleted,ue=ie&&ie._deleted,re=void 0;M&&(re=r.get(de));var oe;if(re){var Je=re._rev;if(!ie||ie&&Je!==ie._rev){var Me={isError:!0,status:409,documentId:de,writeRow:V,documentInDb:re};return m.push(Me),1}var fe=u?vo(V):V;u&&(Se?ie&&Object.keys(ie._attachments).forEach(ge=>{E.push({documentId:de,attachmentId:ge,digest:Z(ie)._attachments[ge].digest})}):(Object.entries(W._attachments).find(([ge,qe])=>{var yt=ie?ie._attachments[ge]:void 0;return!yt&&!qe.data&&(oe={documentId:de,documentInDb:re,isError:!0,status:510,writeRow:V,attachmentId:ge}),!0}),oe||Object.entries(W._attachments).forEach(([ge,qe])=>{var yt=ie?ie._attachments[ge]:void 0;if(!yt)S.push({documentId:de,attachmentId:ge,attachmentData:qe,digest:qe.digest});else{var Zt=fe.document._attachments[ge].digest;qe.data&&yt.digest!==Zt&&D.push({documentId:de,attachmentId:ge,attachmentData:qe,digest:qe.digest})}}))),oe?m.push(oe):(u?f.push(vo(fe)):f.push(fe),U=fe);var ve=null,ne=null,we=null;if(ue&&!Se)we="INSERT",ve=u?At(W):W;else if(ie&&!ue&&!Se)we="UPDATE",ve=u?At(W):W,ne=ie;else if(Se)we="DELETE",ve=Z(W),ne=ie;else throw ee("SNH",{args:{writeRow:V}});var _e={documentId:de,documentData:ve,previousDocumentData:ne,operation:we};w.push(_e)}else{var ye=!!Se;if(u&&Object.entries(W._attachments).forEach(([ge,qe])=>{qe.data?S.push({documentId:de,attachmentId:ge,attachmentData:qe,digest:qe.digest}):(oe={documentId:de,isError:!0,status:510,writeRow:V,attachmentId:ge},m.push(oe))}),oe||(u?d.push(vo(V)):d.push(V),U=V),!ye){var Ie={documentId:de,operation:"INSERT",documentData:u?At(W):W,previousDocumentData:u&&ie?At(ie):ie};w.push(Ie)}}},$=0;$<F;$++)j();return{bulkInsertDocs:d,bulkUpdateDocs:f,newestRow:U,errors:m,eventBulk:g,attachmentsAdd:S,attachmentsRemove:E,attachmentsUpdate:D}}function vo(e){return{previous:e.previous,document:At(e.document)}}function qg(e){return atob(e).length}function Hg(e){var t=e.data;if(!t)return e;var r={length:qg(t),digest:e.digest,type:e.type};return r}function At(e){if(!e._attachments||Object.keys(e._attachments).length===0)return e;var t=Oe(e);return t._attachments={},Object.entries(e._attachments).forEach(([r,n])=>{t._attachments[r]=Hg(n)}),t}function Li(e){return Object.assign({},e,{_meta:Oe(e._meta)})}function Ec(e,t,r){xe.deepFreezeWhenDevMode(r);var n=et(t.schema.primaryKey),i={originalStorageInstance:t,schema:t.schema,internals:t.internals,collectionName:t.collectionName,databaseName:t.databaseName,options:t.options,async bulkWrite(a,o){for(var u=e.token,d=new Array(a.length),f=Ze(),m=0;m<a.length;m++){var y=a[m],g=Li(y.document);g._meta.lwt=f;var w=y.previous;g._rev=zt(u,w),d[m]={document:g,previous:w}}ot("preStorageWrite",{storageInstance:this.originalStorageInstance,rows:d});var S=await e.lockedRun(()=>t.bulkWrite(d,o)),E={error:[]};yh.set(E,d);var D=S.error.length===0?[]:S.error.filter(V=>V.status===409&&!V.writeRow.previous&&!V.writeRow.document._deleted&&Z(V.documentInDb)._deleted?!0:(E.error.push(V),!1));if(D.length>0){var M=new Set,U=D.map(V=>(M.add(V.documentId),{previous:V.documentInDb,document:Object.assign({},V.writeRow.document,{_rev:zt(e.token,V.documentInDb)})})),F=await e.lockedRun(()=>t.bulkWrite(U,o));Ur(E.error,F.error);var j=St(n,d,E,M),$=St(n,U,F);return Ur(j,$),E}return E},query(a){return e.lockedRun(()=>t.query(a))},count(a){return e.lockedRun(()=>t.count(a))},findDocumentsById(a,o){return e.lockedRun(()=>t.findDocumentsById(a,o))},getAttachmentData(a,o,u){return e.lockedRun(()=>t.getAttachmentData(a,o,u))},getChangedDocumentsSince:t.getChangedDocumentsSince?(a,o)=>e.lockedRun(()=>t.getChangedDocumentsSince(Z(a),o)):void 0,cleanup(a){return e.lockedRun(()=>t.cleanup(a))},remove(){return e.storageInstances.delete(i),e.lockedRun(()=>t.remove())},close(){return e.storageInstances.delete(i),e.lockedRun(()=>t.close())},changeStream(){return t.changeStream()}};return e.storageInstances.add(i),i}function _c(e){if(e.schema.keyCompression)throw ee("UT5",{args:{params:e}});if(za(e.schema))throw ee("UT6",{args:{params:e}});if(e.schema.attachments&&e.schema.attachments.compression)throw ee("UT7",{args:{params:e}})}function za(e){return!!(e.encrypted&&e.encrypted.length>0||e.attachments&&e.attachments.encrypted)}function Jg(e,t,r){var n=et(e.schema.primaryKey),i=r?r.lwt:cc,a=r?r.id:"";return mn(e.schema,{selector:{$or:[{"_meta.lwt":{$gt:i}},{"_meta.lwt":{$eq:i},[n]:{$gt:r?a:""}}],"_meta.lwt":{$gte:i}},sort:[{"_meta.lwt":"asc"},{[n]:"asc"}],skip:0,limit:t})}async function mh(e,t,r){if(e.getChangedDocumentsSince)return e.getChangedDocumentsSince(t,r);var n=et(e.schema.primaryKey),i=vs(e.schema,Jg(e,t,r)),a=await e.query(i),o=a.documents,u=ls(o);return{documents:o,checkpoint:u?{id:u[n],lwt:u._meta.lwt}:r||{id:"",lwt:0}}}var yh=new WeakMap,jg=new WeakMap;function St(e,t,r,n){return it(jg,r,()=>{var i=[],a=yh.get(r);if(a||(a=t),r.error.length>0||n){for(var o=n||new Set,u=0;u<r.error.length;u++){var d=r.error[u];o.add(d.documentId)}for(var f=0;f<a.length;f++){var m=a[f].document;o.has(m[e])||i.push(At(m))}}else{i.length=t.length-r.error.length;for(var y=0;y<a.length;y++){var g=a[y].document;i[y]=At(g)}}return i})}var vh=(function(){function e(r,n,i,a){this.queueByDocId=new Map,this.isRunning=!1,this.storageInstance=r,this.primaryPath=n,this.preWrite=i,this.postWrite=a}var t=e.prototype;return t.addWrite=function(n,i){var a=n[this.primaryPath],o=it(this.queueByDocId,a,()=>[]),u=new Promise((d,f)=>{var m={lastKnownDocumentState:n,modifier:i,resolve:d,reject:f};Z(o).push(m),this.triggerRun()});return u},t.triggerRun=async function(){if(!(this.isRunning===!0||this.queueByDocId.size===0)){this.isRunning=!0;var n=[],i=this.queueByDocId;this.queueByDocId=new Map,await Promise.all(Array.from(i.entries()).map(async([o,u])=>{var d=zg(u.map(y=>y.lastKnownDocumentState)),f=d;for(var m of u)try{f=await m.modifier(st(f))}catch(y){m.reject(y),m.reject=()=>{},m.resolve=()=>{}}try{await this.preWrite(f,d)}catch(y){u.forEach(g=>g.reject(y));return}n.push({previous:d,document:f})}));var a=n.length>0?await this.storageInstance.bulkWrite(n,"incremental-write"):{error:[]};return await Promise.all(St(this.primaryPath,n,a).map(o=>{var u=o[this.primaryPath];this.postWrite(o);var d=Wr(i,u);d.forEach(f=>f.resolve(o))}
22)),a.error.forEach(o=>{var u=o.documentId,d=Wr(i,u),f=Sn(o);if(f){var m=it(this.queueByDocId,u,()=>[]);d.reverse().forEach(g=>{g.lastKnownDocumentState=Z(f.documentInDb),Z(m).unshift(g)})}else{var y=Ed(o);d.forEach(g=>g.reject(y))}}),this.isRunning=!1,this.triggerRun()}},e})();function ol(e){var t=async r=>{var n=ay(r);n._deleted=r._deleted;var i=await e(n),a=Object.assign({},i,{_meta:r._meta,_attachments:r._attachments,_rev:r._rev,_deleted:typeof i._deleted<"u"?i._deleted:r._deleted});return typeof a._deleted>"u"&&(a._deleted=!1),a};return t}function zg(e){var t=e[0],r=yr(t._rev);return e.forEach(n=>{var i=yr(n._rev);i>r&&(t=n,r=i)}),t}var gs={get primaryPath(){var e=this;if(e.isInstanceOfRxDocument)return e.collection.schema.primaryPath},get primary(){var e=this;if(e.isInstanceOfRxDocument)return e._data[e.primaryPath]},get revision(){var e=this;if(e.isInstanceOfRxDocument)return e._data._rev},get deleted$(){var e=this;if(e.isInstanceOfRxDocument)return e.$.pipe(We(t=>t._data._deleted))},get deleted$$(){var e=this,t=e.collection.database.getReactivityFactory();return t.fromObservable(e.deleted$,e.getLatest().deleted,e.collection.database)},get deleted(){var e=this;if(e.isInstanceOfRxDocument)return e._data._deleted},getLatest(){var e=this.collection._docCache.getLatestDocumentData(this.primary);return this.collection._docCache.getCachedRxDocument(e)},get $(){var e=this,t=this.primary;return e.collection.eventBulks$.pipe(Ce(r=>!r.isLocal),We(r=>r.events.find(n=>n.documentId===t)),Ce(r=>!!r),We(r=>Xd(Z(r))),Ni(e.collection._docCache.getLatestDocumentData(t)),yi((r,n)=>r._rev===n._rev),We(r=>this.collection._docCache.getCachedRxDocument(r)),Ai(xi))},get $$(){var e=this,t=e.collection.database.getReactivityFactory();return t.fromObservable(e.$,e.getLatest()._data,e.collection.database)},get$(e){if(xe.isDevMode()){if(e.includes(".item."))throw ee("DOC1",{path:e});if(e===this.primaryPath)throw ee("DOC2");if(this.collection.schema.finalFields.includes(e))throw ee("DOC3",{path:e});var t=Vt(this.collection.schema.jsonSchema,e);if(!t)throw ee("DOC4",{path:e})}return this.$.pipe(We(r=>vr(r,e)),yi())},get$$(e){var t=this.get$(e),r=this.collection.database.getReactivityFactory();return r.fromObservable(t,this.getLatest().get(e),this.collection.database)},populate(e){var t=Vt(this.collection.schema.jsonSchema,e),r=this.get(e);if(!r)return dc;if(!t)throw ee("DOC5",{path:e});if(!t.ref)throw ee("DOC6",{path:e,schemaObj:t});var n=this.collection.database.collections[t.ref];if(!n)throw ee("DOC7",{ref:t.ref,path:e,schemaObj:t});return t.type==="array"?n.findByIds(r).exec().then(i=>{var a=i.values();return Array.from(a)}):n.findOne(r).exec()},get(e){return bh(this,e)},toJSON(e=!1){if(e)return xe.deepFreezeWhenDevMode(this._data);var t=Oe(this._data);return delete t._rev,delete t._attachments,delete t._deleted,delete t._meta,xe.deepFreezeWhenDevMode(t)},toMutableJSON(e=!1){return st(this.toJSON(e))},update(e){throw De("update")},incrementalUpdate(e){throw De("update")},updateCRDT(e){throw De("crdt")},putAttachment(){throw De("attachments")},putAttachmentBase64(){throw De("attachments")},getAttachment(){throw De("attachments")},allAttachments(){throw De("attachments")},get allAttachments$(){throw De("attachments")},async modify(e,t){var r=this._data,n=await ol(e)(r);return this._saveData(n,r)},incrementalModify(e,t){return this.collection.incrementalWriteQueue.addWrite(this._data,ol(e)).then(r=>this.collection._docCache.getCachedRxDocument(r))},patch(e){var t=this._data,r=st(t);return Object.entries(e).forEach(([n,i])=>{r[n]=i}),this._saveData(r,t)},incrementalPatch(e){return this.incrementalModify(t=>(Object.entries(e).forEach(([r,n])=>{t[r]=n}),t))},async _saveData(e,t){if(e=Oe(e),this._data._deleted)throw ee("DOC11",{id:this.primary,document:this});await wh(this.collection,e,t);var r=[{previous:t,document:e}],n=await this.collection.storageInstance.bulkWrite(r,"rx-document-save-data"),i=n.error[0];return ja(this.collection,this.primary,e,i),await this.collection._runHooks("post","save",e,this),this.collection._docCache.getCachedRxDocument(St(this.collection.schema.primaryPath,r,n)[0])},async remove(){if(this.deleted)return Promise.reject(ee("DOC13",{document:this,id:this.primary}));var e=await this.collection.bulkRemove([this]);if(e.error.length>0){var t=e.error[0];ja(this.collection,this.primary,this._data,t)}return e.success[0]},incrementalRemove(){return this.incrementalModify(async e=>(await this.collection._runHooks("pre","remove",e,this),e._deleted=!0,e)).then(async e=>(await this.collection._runHooks("post","remove",e._data,e),e))},close(){throw ee("DOC14")}};function gh(e=gs){var t=function(n,i){this.collection=n,this._data=i,this._propertyCache=new Map,this.isInstanceOfRxDocument=!0};return t.prototype=e,t}function Gg(e,t,r){var n=new e(t,r);return ot("createRxDocument",n),n}function wh(e,t,r){return t._meta=Object.assign({},r._meta,t._meta),xe.isDevMode()&&e.schema.validateChange(r,t),e._runHooks("pre","save",t,r)}function bh(e,t){return it(e._propertyCache,t,()=>{var r=vr(e._data,t);if(typeof r!="object"||r===null||Array.isArray(r))return xe.deepFreezeWhenDevMode(r);var n=new Proxy(Oe(r),{get(i,a){if(typeof a!="string")return i[a];var o=a.charAt(a.length-1);if(o==="$")if(a.endsWith("$$")){var u=a.slice(0,-2);return e.get$$(ri(t+"."+u))}else{var d=a.slice(0,-1);
22return e.get$(ri(t+"."+d))}else if(o==="_"){var f=a.slice(0,-1);return e.populate(ri(t+"."+f))}else{var m=i[a];return typeof m=="number"||typeof m=="string"||typeof m=="boolean"?m:bh(e,ri(t+"."+a))}}});return n})}function Pc(e){return e[e.length-1]}function Vg(e){const t=typeof e;return e!==null&&(t==="object"||t==="function")}function cl(e,t,r){if(Array.isArray(t)&&(t=t.join(".")),!Vg(e)||typeof t!="string")return e;const n=t.split(".");if(n.length===0)return r;for(let i=0;i<n.length;i++){const a=n[i];if(Yg(e,a)?e=i===n.length-1?void 0:null:e=e[a],e==null){if(i!==n.length-1)return r;break}}return e===void 0?r:e}function Yg(e,t){if(typeof t!="number"&&Array.isArray(e)){const r=Number.parseInt(t,10);return Number.isInteger(r)&&e[r]===e[t]}return!1}const Sh=e=>!!e.queryParams.limit,Qg=e=>e.queryParams.limit===1,Xg=e=>!!(e.queryParams.skip&&e.queryParams.skip>0),Zg=e=>e.changeEvent.operation==="DELETE",ew=e=>e.changeEvent.operation==="INSERT",tw=e=>e.changeEvent.operation==="UPDATE",rw=e=>Sh(e)&&e.previousResults.length>=e.queryParams.limit,nw=e=>{const t=e.queryParams.sortFields,r=e.changeEvent.previous,n=e.changeEvent.doc;if(!n)return!1;if(!r)return!0;for(let i=0;i<t.length;i++){const a=t[i],o=cl(r,a),u=cl(n,a);if(o!==u)return!0}return!1},iw=e=>{const t=e.changeEvent.id;if(e.keyDocumentMap)return e.keyDocumentMap.has(t);{const r=e.queryParams.primaryKey,n=e.previousResults;for(let i=0;i<n.length;i++)if(n[i][r]===t)return!0;return!1}},aw=e=>{const t=e.previousResults[0];return!!(t&&t[e.queryParams.primaryKey]===e.changeEvent.id)},sw=e=>{const t=Pc(e.previousResults);return!!(t&&t[e.queryParams.primaryKey]===e.changeEvent.id)},ow=e=>{const t=e.changeEvent.previous;if(!t)return!1;const r=e.previousResults[0];return r?r[e.queryParams.primaryKey]===e.changeEvent.id?!0:e.queryParams.sortComparator(t,r)<0:!1},cw=e=>{const t=e.changeEvent.previous;if(!t)return!1;const r=Pc(e.previousResults);return r?r[e.queryParams.primaryKey]===e.changeEvent.id?!0:e.queryParams.sortComparator(t,r)>0:!1},uw=e=>{const t=e.changeEvent.doc;if(!t)return!1;const r=e.previousResults[0];return r?r[e.queryParams.primaryKey]===e.changeEvent.id?!0:e.queryParams.sortComparator(t,r)<0:!1},lw=e=>{const t=e.changeEvent.doc;if(!t)return!1;const r=Pc(e.previousResults);return r?r[e.queryParams.primaryKey]===e.changeEvent.id?!0:e.queryParams.sortComparator(t,r)>0:!1},dw=e=>{const t=e.changeEvent.previous;return t?e.queryParams.queryMatcher(t):!1},hw=e=>{const t=e.changeEvent.doc;return t?e.queryParams.queryMatcher(t):!1},fw=e=>e.previousResults.length===0,pw={0:ew,1:tw,2:Zg,3:Sh,4:Qg,5:Xg,6:fw,7:rw,8:aw,9:sw,10:nw,11:iw,12:ow,13:cw,14:uw,15:lw,16:dw,17:hw};function Eh(e,t,r,n){var i=e.length,a=i-1,o=0;if(i===0)return e.push(t),0;for(var u;n<=a;)o=n+(a-n>>1),u=e[o],r(u,t)<=0?n=o+1:a=o-1;return r(u,t)<=0&&o++,e.splice(o,0,t),o}const mw=e=>{},Ic=e=>{e.previousResults.unshift(e.changeEvent.doc),e.keyDocumentMap&&e.keyDocumentMap.set(e.changeEvent.id,e.changeEvent.doc)},Cc=e=>{e.previousResults.push(e.changeEvent.doc),e.keyDocumentMap&&e.keyDocumentMap.set(e.changeEvent.id,e.changeEvent.doc)},kc=e=>{const t=e.previousResults.shift();e.keyDocumentMap&&t&&e.keyDocumentMap.delete(t[e.queryParams.primaryKey])},Rc=e=>{const t=e.previousResults.pop();e.keyDocumentMap&&t&&e.keyDocumentMap.delete(t[e.queryParams.primaryKey])},yw=e=>{kc(e),Cc(e)},vw=e=>{Rc(e),Ic(e)},gw=e=>{kc(e),Ic(e)},ww=e=>{Rc(e),Cc(e)},_h=e=>{e.keyDocumentMap&&e.keyDocumentMap.delete(e.changeEvent.id);const t=e.queryParams.primaryKey,r=e.previousResults;for(let n=0;n<r.length;n++)if(r[n][t]===e.changeEvent.id){r.splice(n,1);break}},bw=e=>{const t=e.changeEvent.doc,r=e.queryParams.primaryKey,n=e.previousResults;for(let i=0;i<n.length;i++)if(n[i][r]===e.changeEvent.id){n[i]=t,e.keyDocumentMap&&e.keyDocumentMap.set(e.changeEvent.id,t);break}},Sw=e=>{const t={_id:"wrongHuman"+new Date().getTime()};e.previousResults.length=0,e.previousResults.push(t),e.keyDocumentMap&&(e.keyDocumentMap.clear(),e.keyDocumentMap.set(t._id,t))},Ph=e=>{const t=e.changeEvent.id,r=e.changeEvent.doc;if(e.keyDocumentMap){if(e.keyDocumentMap.has(t))return;e.keyDocumentMap.set(t,r)}else if(e.previousResults.find(i=>i[e.queryParams.primaryKey]===t))return;Eh(e.previousResults,r,e.queryParams.sortComparator,0)},Ew=e=>{_h(e),Ph(e)},_w=e=>{throw new Error("Action runFullQueryAgain must be implemented by yourself")},Pw=e=>{throw new Error("Action unknownAction should never be called")},Iw=["doNothing","insertFirst","insertLast","removeFirstItem","removeLastItem","removeFirstInsertLast","removeLastInsertFirst","removeFirstInsertFirst","removeLastInsertLast","removeExisting","replaceExisting","alwaysWrong","insertAtSortPosition","removeExistingAndInsertAtSortPosition","runFullQueryAgain","unknownAction"],Cw={doNothing:mw,insertFirst:Ic,insertLast:Cc,removeFirstItem:kc,removeLastItem:Rc,removeFirstInsertLast:yw,removeLastInsertFirst:vw,removeFirstInsertFirst:gw,removeLastInsertLast:ww,removeExisting:_h,replaceExisting:bw,alwaysWrong:Sw,insertAtSortPosition:Ph,removeExistingAndInsertAtSortPosition:Ew,runFullQueryAgain:_w,unknownAction:Pw},kw=40;function go(e){return e.charCodeAt(0)-kw}function Rw(e){return e?"1":"0"}function ul(e,t){const r=[];for(let n=0,i=e.length;n<i;n+=t)r.push(e.substring(n,n+t));return r}function Dw(e){const t=new Map,n=2+parseInt(e.charAt(0)+e.charAt(1),10)*2,i=e.substring(2,n),a=ul(i,2);for(let E=0;E<a.length;E++){const D=a[E],M=D.charAt(0),U=go(D.charAt(1));t.set(M,U)}const o=e.substring(n,e.length-3),u=ul(o,4);for(let E=0;E<u.length;E++){const D=u[E],M=D.charAt(0),U=D.charAt(1),F=D.charAt(2),j=go(D.charAt(3));
22if(!t.has(U))throw new Error("missing node with id "+U);if(!t.has(F))throw new Error("missing node with id "+F);const $=t.get(U),V=t.get(F),W={l:j,0:$,1:V};t.set(M,W)}const d=e.slice(-3),f=d.charAt(0),m=d.charAt(1),y=go(d.charAt(2)),g=t.get(f),w=t.get(m);return{l:y,0:g,1:w}}function xw(e,t,r){let n=e,i=e.l;for(;;){const a=t[i](r),o=Rw(a);if(n=n[o],typeof n=="number"||typeof n=="string")return n;i=n.l}}const Ow="14a1b,c+d2e5f0g/h.i4j*k-l)m(n6oeh6pnm6qen6ril6snh6tin6ubo9vce9wmh9xns9yne9zmi9{cm9|ad9}cp9~aq9�ae9¡bf9¢bq9£cg9¤ck9Â¥cn9¦nd9§np9¨nq9©nf9ªng9«nm9¬nk9Âmr9®ms9¯mt9°mj9±mk9²ml9³mn9´mc8µ³{8¶¯}8·°¤8¸³§8¹mn8º³«8»³m8¼m´4½z²4¾³w4¿zµ4ï¶4ð·4óº4ó¸4Ãm¹4Ã
v¤7Ãyn7ÃÃÃ7Ã~�7Ã¥¤7ÃÃÃ7èn7ú¹7ð7îm7ï°7ñm7óm7üm5ÃÃm5ùm5ý°5þm5ÿ°5ÃÃÃ5ÃÃm5ÃÃÃ5ñm5úm5ÃÃÃ5ÃÃÃ2Ã|�2à ¡u2á£Ã
2âÃÃ2ã¦Ã2ä©x2åªÃ2æÃÃ2ç|Ã2è¡¢2é£Ã2ꤥ2ëÃÃ2ì¦Ã2én2îªn2ïÃÃ2ðÃÃ2ñ¬n2òÃÃ/óan/ôbn/õcn/öÃâ/÷Ãã/øà ä/ùáå/úæë/ûçì/üèÃ/ýéî/þÃÃ/ÿÃÃ/ÄòÃ,Äcn,Äöï,Ĥñ,Äúð,Ä
êñ,ÄþÃ,ÄÿÃ,Äac0Äbc0Äóõ0ÄôÄ0ÄÃá0Äà ¤0Äçé0Äèê0Ä÷ù0ÄøÄ0Äûý0ÄüÄ
0ÄmÃ-ÄmÄ-ÄÃæ-ÄÄÄ-ÄÄÄ-ÄÄÄ-ÄÄÄ-ÄÄÄ-IJ»-ÄÃÃ-ÄÄÄ-IJ³-Ä ÄÄ3Ä¡ÄÄ3Ä¢ÄÄ3Ä£ÄÄ3ĤĢÄ(Ä¥ÄÄ(ĦģÄ(Ä§Ä Ä¡+ĨÄÄ+ĩĤĦ+ĪÄÄ+īħĨ1ĬĩĪ1ÄĬī*Įĥm*ÄÄ®.";let wo;function Tw(){return wo||(wo=Dw(Ow)),wo}const Kw=e=>xw(Tw(),pw,e);function Aw(e){const t=Kw(e);return Iw[t]}function Nw(e,t,r,n,i){const a=Cw[e];return a({queryParams:t,changeEvent:r,previousResults:n,keyDocumentMap:i}),n}function Mw(e,t){return!t.sort||t.sort.length===0?[e]:t.sort.map(r=>Object.keys(r)[0])}var Bw=new WeakMap;function Fw(e){return it(Bw,e,()=>{var t=e.collection,r=mn(t.storageInstance.schema,st(e.mangoQuery)),n=t.schema.primaryPath,i=ys(t.schema.jsonSchema,r),a=(f,m)=>{var y={docA:f,docB:m};return i(y.docA,y.docB)},o=Fi(t.schema.jsonSchema,r),u=f=>{var m={doc:f};return o(m.doc)},d={primaryKey:e.collection.schema.primaryPath,skip:r.skip,limit:r.limit,sortFields:Mw(n,r),sortComparator:a,queryMatcher:u};return d})}function Lw(e,t){if(!e.collection.database.eventReduce)return{runFullQueryAgain:!0};for(var r=Fw(e),n=Z(e._result).docsData.slice(0),i=Z(e._result).docsDataMap,a=!1,o=[],u=0;u<t.length;u++){var d=t[u],f=kv(d);f&&o.push(f)}var m=o.find(y=>{var g={queryParams:r,changeEvent:y,previousResults:n,keyDocumentMap:i},w=Aw(g);if(w==="runFullQueryAgain")return!0;if(w!=="doNothing")return a=!0,Nw(w,r,y,n,i),!1});return m?{runFullQueryAgain:!0}:{runFullQueryAgain:!1,changed:a,newResults:n}}var Uw=(function(){function e(){this._map=new Map}var t=e.prototype;return t.getByQuery=function(n){var i=n.toString(),a=it(this._map,i,()=>n);return a},e})();function Ww(){return new Uw}function ll(e,t){t.uncached=!0;var r=t.toString();e._map.delete(r)}function $w(e){return e.refCount$.observers.length}var qw=100,Hw=30*1e3,Jw=(e,t)=>(r,n)=>{if(!(n._map.size<e)){var i=Ze()-t,a=[],o=Array.from(n._map.values());for(var u of o)if(!($w(u)>0)){if(u._lastEnsureEqual===0&&u._creationTime<i){ll(n,u);continue}a.push(u)}var d=a.length-e;if(!(d<=0)){var f=a.sort((y,g)=>y._lastEnsureEqual-g._lastEnsureEqual),m=f.slice(0,d);m.forEach(y=>ll(n,y))}}},Ih=Jw(qw,Hw),bo=new WeakSet;function jw(e){bo.has(e)||(bo.add(e),py().then(()=>my(200)).then(()=>{e.closed||e.cacheReplacementPolicy(e,e._queryCache),bo.delete(e)}))}var Ch=(function(){function e(r,n,i){this.cacheItemByDocId=new Map,this.tasks=new Set,this.registry=typeof FinalizationRegistry=="function"?new FinalizationRegistry(a=>{var o=a.docId,u=this.cacheItemByDocId.get(o);u&&(u[0].delete(a.revisionHeight+a.lwt+""),u[0].size===0&&this.cacheItemByDocId.delete(o))}):void 0,this.primaryPath=r,this.changes$=n,this.documentCreator=i,n.subscribe(a=>{this.tasks.add(()=>{for(var o=this.cacheItemByDocId,u=0;u<a.length;u++){var d=a[u],f=o.get(d.documentId);if(f){var m=d.documentData;m||(m=d.previousDocumentData),f[1]=m}}}),this.tasks.size<=1&&On().then(()=>{this.processTasks()})})}var t=e.prototype;return t.processTasks=function(){if(this.tasks.size!==0){var n=Array.from(this.tasks);
22n.forEach(i=>i()),this.tasks.clear()}},t.getLatestDocumentData=function(n){this.processTasks();var i=Wr(this.cacheItemByDocId,n);return i[1]},t.getLatestDocumentDataIfExists=function(n){this.processTasks();var i=this.cacheItemByDocId.get(n);if(i)return i[1]},wr(e,[{key:"getCachedRxDocuments",get:function(){var r=dl(this);return Jt(this,"getCachedRxDocuments",r)}},{key:"getCachedRxDocument",get:function(){var r=dl(this);return Jt(this,"getCachedRxDocument",n=>r([n])[0])}}])})();function dl(e){var t=e.primaryPath,r=e.cacheItemByDocId,n=e.registry,i=xe.deepFreezeWhenDevMode,a=e.documentCreator,o=u=>{for(var d=new Array(u.length),f=[],m=0;m<u.length;m++){var y=u[m],g=y[t],w=yr(y._rev),S=void 0,E=void 0,D=r.get(g);D?(S=D[0],E=S.get(w+y._meta.lwt+"")):(S=new Map,D=[S,y],r.set(g,D));var M=E?E.deref():void 0;M||(y=i(y),M=a(y),S.set(w+y._meta.lwt+"",Gw(M)),n&&f.push(M)),d[m]=M}return f.length>0&&n&&(e.tasks.add(()=>{for(var U=0;U<f.length;U++){var F=f[U];n.register(F,{docId:F.primary,revisionHeight:yr(F.revision),lwt:F._data._meta.lwt})}}),e.tasks.size<=1&&On().then(()=>{e.processTasks()})),d};return o}function Ho(e,t){var r=e.getCachedRxDocuments;return r(t)}var zw=typeof WeakRef=="function",Gw=zw?Vw:Yw;function Vw(e){return new WeakRef(e)}function Yw(e){return{deref(){return e}}}var hl=(function(){function e(r,n,i){this.time=Ze(),this.query=r,this.count=i,this.documents=Ho(this.query.collection._docCache,n)}var t=e.prototype;return t.getValue=function(n){var i=this.query.op;if(i==="count")return this.count;if(i==="findOne"){var a=this.documents.length===0?null:this.documents[0];if(!a&&n)throw ee("QU10",{collection:this.query.collection.name,query:this.query.mangoQuery,op:i});return a}else return i==="findByIds"?this.docsMap:this.documents.slice(0)},wr(e,[{key:"docsData",get:function(){return Jt(this,"docsData",this.documents.map(r=>r._data))}},{key:"docsDataMap",get:function(){var r=new Map;return this.documents.forEach(n=>{r.set(n.primary,n._data)}),Jt(this,"docsDataMap",r)}},{key:"docsMap",get:function(){for(var r=new Map,n=this.documents,i=0;i<n.length;i++){var a=n[i];r.set(a.primary,a)}return Jt(this,"docsMap",r)}}])})(),Qw=0,Xw=function(){return++Qw},kh=(function(){function e(r,n,i,a={}){this.id=Xw(),this._execOverDatabaseCount=0,this._creationTime=Ze(),this._lastEnsureEqual=0,this.uncached=!1,this.refCount$=new Kt(null),this._result=null,this._latestChangeEvent=-1,this._ensureEqualQueue=Rt,this.op=r,this.mangoQuery=n,this.collection=i,this.other=a,n||(this.mangoQuery=xa()),this.isFindOneByIdQuery=rb(this.collection.schema.primaryPath,n)}var t=e.prototype;return t._setResultData=function(n){if(typeof n>"u")throw ee("QU18",{database:this.collection.database.name,collection:this.collection.name});if(typeof n=="number"){this._result=new hl(this,[],n);return}else n instanceof Map&&(n=Array.from(n.values()));var i=new hl(this,n,n.length);this._result=i},t._execOverDatabase=async function(){if(this._execOverDatabaseCount=this._execOverDatabaseCount+1,this.op==="count"){var n=this.getPreparedQuery(),i=await this.collection.storageInstance.count(n);if(i.mode==="slow"&&!this.collection.database.allowSlowCount)throw ee("QU14",{collection:this.collection,queryObj:this.mangoQuery});return i.count}if(this.op==="findByIds"){var a=Z(this.mangoQuery.selector)[this.collection.schema.primaryPath].$in,o=new Map,u=[];if(a.forEach(m=>{var y=this.collection._docCache.getLatestDocumentDataIfExists(m);if(y){if(!y._deleted){var g=this.collection._docCache.getCachedRxDocument(y);o.set(m,g)}}else u.push(m)}),u.length>0){var d=await this.collection.storageInstance.findDocumentsById(u,!1);d.forEach(m=>{var y=this.collection._docCache.getCachedRxDocument(m);o.set(y.primary,y)})}return o}var f=tb(this);return f.then(m=>m)},t.exec=async function(n){if(n&&this.op!=="findOne")throw ee("QU9",{collection:this.collection.name,query:this.mangoQuery,op:this.op});await fl(this);var i=Z(this._result);return i.getValue(n)},t.toString=function(){var n=Ua({op:this.op,query:mn(this.collection.schema.jsonSchema,this.mangoQuery),other:this.other},!0),i=JSON.stringify(n);return this.toString=()=>i,i},t.getPreparedQuery=function(){var n={rxQuery:this,mangoQuery:mn(this.collection.schema.jsonSchema,this.mangoQuery)};n.mangoQuery.selector._deleted={$eq:!1},n.mangoQuery.index&&n.mangoQuery.index.unshift("_deleted"),ot("prePrepareQuery",n);var i=vs(this.collection.schema.jsonSchema,n.mangoQuery);return this.getPreparedQuery=()=>i,i},t.doesDocumentDataMatch=function(n){return n._deleted?!1:this.queryMatcher(n)},t.remove=async function(){var n=await this.exec();if(Array.isArray(n)){var i=await this.collection.bulkRemove(n);if(i.error.length>0)throw Ed(i.error[0]);return i.success}else return n.remove()},t.incrementalRemove=function(){return Xn(this.asRxQuery,n=>n.incrementalRemove())},t.update=function(n){throw De("update")},t.patch=function(n){return Xn(this.asRxQuery,i=>i.patch(n))},t.incrementalPatch=function(n){return Xn(this.asRxQuery,i=>i.incrementalPatch(n))},t.modify=function(n){return Xn(this.asRxQuery,i=>i.modify(n))},t.incrementalModify=function(n){return Xn(this.asRxQuery,i=>i.incrementalModify(n))},t.where=function(n){throw De("query-builder")},t.sort=function(n){throw De("query-builder")},t.skip=function(n){throw De("query-builder")},t.limit=function(n){throw De("query-builder")},wr(e,[{key:"$",get:function(){if(!this._$){var r=this.collection.eventBulks$.pipe(Ce(n=>!n.isLocal),Ni(null),Mt(()=>fl(this)),We(()=>this._result),Ai(xi),yi((n,i)=>!!(n&&n.time===Z(i).time)),Ce(n=>!!n),We(n=>Z(n).getValue()));this._$=Dv(r,this.refCount$.pipe(Ce(()=>!1)))}return this._$}}
22,{key:"$$",get:function(){var r=this.collection.database.getReactivityFactory();return r.fromObservable(this.$,void 0,this.collection.database)}},{key:"queryMatcher",get:function(){var r=this.collection.schema.jsonSchema,n=mn(this.collection.schema.jsonSchema,this.mangoQuery);return Jt(this,"queryMatcher",Fi(r,n))}},{key:"asRxQuery",get:function(){return this}}])})();function xa(){return{selector:{}}}function Zw(e){return e.collection._queryCache.getByQuery(e)}function Zn(e,t,r,n){ot("preCreateRxQuery",{op:e,queryObj:t,collection:r,other:n});var i=new kh(e,t,r,n);return i=Zw(i),jw(r),i}function Rh(e){var t=e.asRxQuery.collection._changeEventBuffer.getCounter();return e._latestChangeEvent>=t}async function fl(e){return e.collection.awaitBeforeReads.size>0&&await Promise.all(Array.from(e.collection.awaitBeforeReads).map(t=>t())),e.collection.database.closed||Rh(e)?!1:(e._ensureEqualQueue=e._ensureEqualQueue.then(()=>eb(e)),e._ensureEqualQueue)}function eb(e){if(e._lastEnsureEqual=Ze(),e.collection.database.closed||Rh(e))return Rt;var t=!1,r=!1;if(e._latestChangeEvent===-1&&(r=!0),!r){var n=e.asRxQuery.collection._changeEventBuffer.getFrom(e._latestChangeEvent+1);if(n===null)r=!0;else{e._latestChangeEvent=e.asRxQuery.collection._changeEventBuffer.getCounter();var i=e.asRxQuery.collection._changeEventBuffer.reduceByLastOfDoc(n);if(e.op==="count"){var a=Z(e._result).count,o=a;i.forEach(d=>{var f=d.previousDocumentData&&e.doesDocumentDataMatch(d.previousDocumentData),m=e.doesDocumentDataMatch(d.documentData);!f&&m&&o++,f&&!m&&o--}),o!==a&&(t=!0,e._setResultData(o))}else{var u=Lw(e,i);u.runFullQueryAgain?r=!0:u.changed&&(t=!0,e._setResultData(u.newResults))}}}return r?e._execOverDatabase().then(d=>(e._latestChangeEvent=e.collection._changeEventBuffer.getCounter(),typeof d=="number"?((!e._result||d!==e._result.count)&&(t=!0,e._setResultData(d)),t):((!e._result||!sy(e.collection.schema.primaryPath,d,e._result.docsData))&&(t=!0,e._setResultData(d)),t))):Promise.resolve(t)}async function tb(e){var t=[],r=e.collection;if(e.isFindOneByIdQuery)if(Array.isArray(e.isFindOneByIdQuery)){var n=e.isFindOneByIdQuery;if(n=n.filter(m=>{var y=e.collection._docCache.getLatestDocumentDataIfExists(m);return y?(y._deleted||t.push(y),!1):!0}),n.length>0){var i=await r.storageInstance.findDocumentsById(n,!1);Ur(t,i)}}else{var a=e.isFindOneByIdQuery,o=e.collection._docCache.getLatestDocumentDataIfExists(a);if(!o){var u=await r.storageInstance.findDocumentsById([a],!1);u[0]&&(o=u[0])}o&&!o._deleted&&t.push(o)}else{var d=e.getPreparedQuery(),f=await r.storageInstance.query(d);t=f.documents}return t}function rb(e,t){if(!t.skip&&t.selector&&Object.keys(t.selector).length===1&&t.selector[e]){var r=t.selector[e];if(typeof r=="string")return r;if(Object.keys(r).length===1&&typeof r.$eq=="string"||Object.keys(r).length===1&&Array.isArray(r.$eq)&&!r.$eq.find(n=>typeof n!="string"))return r.$eq}return!1}var mr="collection",Dc="storage-token",Oa="rx-migration-status",nb="rx-pipeline-checkpoint",ib="RxInternalDocument",xc=ds({version:0,title:ib,primaryKey:{key:"id",fields:["context","key"],separator:"|"},type:"object",properties:{id:{type:"string",maxLength:200},key:{type:"string"},context:{type:"string",enum:[mr,Dc,Oa,nb,"OTHER"]},data:{type:"object",additionalProperties:!0}},indexes:[],required:["key","context","data"],additionalProperties:!1,sharding:{shards:1,mode:"collection"}});function Jr(e,t){return br(xc,{key:e,context:t})}async function Dh(e){var t=vs(e.schema,{selector:{context:mr,_deleted:{$eq:!1}},sort:[{id:"asc"}],skip:0}),r=await e.query(t),n=r.documents;return n}var xh="storageToken",ab=Jr(xh,Dc);async function sb(e){var t=Tn(10),r=e.password?await e.hashFunction(JSON.stringify(e.password)):void 0,n={id:ab,context:Dc,key:xh,data:{rxdbVersion:e.rxdbVersion,token:t,instanceToken:e.token,passwordHash:r},_deleted:!1,_meta:Dn(),_rev:kt(),_attachments:{}},i=[{document:n}],a=await e.internalStore.bulkWrite(i,"internal-add-storage-token");if(!a.error[0])return St("id",i,a)[0];var o=Z(a.error[0]);if(o.isError&&Sn(o)){var u=o;if(!ob(u.documentInDb.data.rxdbVersion,e.rxdbVersion))throw ee("DM5",{args:{database:e.name,databaseStateVersion:u.documentInDb.data.rxdbVersion,codeVersion:e.rxdbVersion}});if(r&&r!==u.documentInDb.data.passwordHash)throw ee("DB1",{passwordHash:r,existingPasswordH
22ash:u.documentInDb.data.passwordHash});var d=u.documentInDb;return Z(d)}throw o}function ob(e,t){if(!e)return!1;var r=e.split(".")[0],n=t.split(".")[0];return r==="15"&&n==="16"?!0:r===n}async function Oh(e,t,r){if(e.schema.version!==r.version)throw ee("SNH",{schema:r,version:e.schema.version,name:e.name,collection:e,args:{storageCollectionName:t}});for(var n=Ga(e.name,e.schema.jsonSchema),i=Jr(n,mr);;){var a=await Kn(e.database.internalStore,i),o=st(Z(a)),u=o.data.connectedStorages.find(d=>d.collectionName===t&&d.schema.version===r.version);if(u)return;o.data.connectedStorages.push({collectionName:t,schema:r});try{await kn(e.database.internalStore,{previous:Z(a),document:o},"add-connected-storage-to-collection")}catch(d){if(!Sn(d))throw d}}}async function cb(e,t,r){if(e.schema.version!==r.version)throw ee("SNH",{schema:r,version:e.schema.version,name:e.name,collection:e,args:{storageCollectionName:t}});for(var n=Ga(e.name,e.schema.jsonSchema),i=Jr(n,mr);;){var a=await Kn(e.database.internalStore,i),o=st(Z(a)),u=o.data.connectedStorages.find(d=>d.collectionName===t&&d.schema.version===r.version);if(!u)return;o.data.connectedStorages=o.data.connectedStorages.filter(d=>d.collectionName!==t);try{await kn(e.database.internalStore,{previous:Z(a),document:o},"remove-connected-storage-from-collection")}catch(d){if(!Sn(d))throw d}}}function Ga(e,t){return e+"-"+t.version}function Sa(e,t){return t=Oe(t),t=ky(e,t),typeof e.jsonSchema.primaryKey!="string"&&(t=Sy(e.primaryPath,e.jsonSchema,t)),t._meta=Dn(),Object.prototype.hasOwnProperty.call(t,"_deleted")||(t._deleted=!1),Object.prototype.hasOwnProperty.call(t,"_attachments")||(t._attachments={}),Object.prototype.hasOwnProperty.call(t,"_rev")||(t._rev=kt()),t}async function ub(e,t){t.multiInstance=e.multiInstance;var r=await e.storage.createStorageInstance(t);return r}async function Th(e,t,r,n,i,a,o,u){var d=await Dh(t),f=d.filter(w=>w.data.name===i),m=[];f.forEach(w=>{m.push({collectionName:w.data.name,schema:w.data.schema,isCollection:!0}
22),w.data.connectedStorages.forEach(S=>m.push({collectionName:S.collectionName,isCollection:!1,schema:S.schema}))});var y=new Set;if(m=m.filter(w=>{var S=w.collectionName+"||"+w.schema.version;return y.has(S)?!1:(y.add(S),!0)}),await Promise.all(m.map(async w=>{var S=await e.createStorageInstance({collectionName:w.collectionName,databaseInstanceToken:r,databaseName:n,multiInstance:a,options:{},schema:w.schema,password:o,devMode:xe.isDevMode()});await S.remove(),w.isCollection&&await Gt("postRemoveRxCollection",{storage:e,databaseName:n,collectionName:i})})),u){var g=f.map(w=>{var S=Li(w);return S._deleted=!0,S._meta.lwt=Ze(),S._rev=zt(r,w),{previous:w,document:S}});await t.bulkWrite(g,"rx-database-remove-collection-all")}}function gt(e){if(e.closed)throw ee("COL21",{collection:e.name,version:e.schema.version})}var lb=(function(){function e(r){this.subs=[],this.counter=0,this.eventCounterMap=new WeakMap,this.buffer=[],this.limit=100,this.tasks=new Set,this.collection=r,this.subs.push(this.collection.eventBulks$.pipe(Ce(n=>!n.isLocal)).subscribe(n=>{this.tasks.add(()=>this._handleChangeEvents(n.events)),this.tasks.size<=1&&On().then(()=>{this.processTasks()})}))}var t=e.prototype;return t.processTasks=function(){if(this.tasks.size!==0){var n=Array.from(this.tasks);n.forEach(i=>i()),this.tasks.clear()}},t._handleChangeEvents=function(n){var i=this.counter;this.counter=this.counter+n.length,n.length>this.limit?this.buffer=n.slice(n.length*-1):(Ur(this.buffer,n),this.buffer=this.buffer.slice(this.limit*-1));for(var a=i+1,o=this.eventCounterMap,u=0;u<n.length;u++){var d=n[u];o.set(d,a+u)}},t.getCounter=function(){return this.processTasks(),this.counter},t.getBuffer=function(){return this.processTasks(),this.buffer},t.getArrayIndexByPointer=function(n){this.processTasks();var i=this.buffer[0],a=this.eventCounterMap.get(i);if(n<a)return null;var o=n-a;return o},t.getFrom=function(n){this.processTasks();var i=[],a=this.getArrayIndexByPointer(n);if(a===null)return null;for(;;){var o=this.buffer[a];if(a++,o)i.push(o);else return i}},t.runFrom=function(n,i){this.processTasks();var a=this.getFrom(n);if(a===null)throw new Error("out of bounds");a.forEach(o=>i(o))},t.reduceByLastOfDoc=function(n){return this.processTasks(),n.slice(0)},t.close=function(){this.tasks.clear(),this.subs.forEach(n=>n.unsubscribe())},e})();function db(e){return new lb(e)}var hb=new WeakMap;function fb(e){var t=e.schema.getDocumentPrototype(),r=yb(e),n=gs,i={};return[t,r,n].forEach(a=>{var o=Object.getOwnPropertyNames(a);o.forEach(u=>{var d=Object.getOwnPropertyDescriptor(a,u),f=!0;(u.startsWith("_")||u.endsWith("_")||u.startsWith("$")||u.endsWith("$"))&&(f=!1),typeof d.value=="function"?Object.defineProperty(i,u,{get(){return d.value.bind(this)},enumerable:f,configurable:!1}):(d.enumerable=f,d.configurable=!1,d.writable&&(d.writable=!1),Object.defineProperty(i,u,d))})}),i}function pb(e){return it(hb,e,()=>gh(fb(e)))}function mb(e,t,r){var n=Gg(t,e,xe.deepFreezeWhenDevMode(r));return e._runHooksSync("post","create",r,n),ot("postCreateRxDocument",n),n}function yb(e){var t={};return Object.entries(e.methods).forEach(([r,n])=>{t[r]=n}),t}var Va={isEqual(e,t){return En(At(e),At(t))},resolve(e){return e.realMasterState}},Kh=["pre","post"],Ah=["insert","save","remove","create"],pl=!1,un=new Set,Nh=(function(){function e(r,n,i,a,o={},u={},d={},f={},m={},y=Ih,g={},w=Va){this.storageInstance={},this.timeouts=new Set,this.incrementalWriteQueue={},this.awaitBeforeReads=new Set,this._incrementalUpsertQueues=new Map,this.synced=!1,this.hooks={},this._subs=[],this._docCache={},this._queryCache=Ww(),this.$={},this.checkpoint$={},this._changeEventBuffer={},this.eventBulks$={},this.onClose=[],this.closed=!1,this.onRemove=[],this.database=r,this.name=n,this.schema=i,this.internalStorageInstance=a,this.instanceCreationOptions=o,this.migrationStrategies=u,this.methods=d,this.attachments=f,this.options=m,this.cacheReplacementPolicy=y,this.statics=g,this.conflictHandler=w,vb(this.asRxCollection),r&&(this.eventBulks$=r.eventBulks$.pipe(Ce(S=>S.collectionName===this.name))),this.database&&un.add(this)}var t=e.prototype;return t.prepare=async function(){if(!await Dd()){for(var n=0;n<10&&un.size>qu;)n++,await this.promiseWait(30);if(un.size>qu)throw ee("COL23",{database:this.database.name,collection:this.name,args:{existing:Array.from(un.values()).map(d=>({db:d.database?d.database.name:"",c:d.name}))}})}this.storageInstance=Ec(this.database,this.internalStorageInstance,this.schema.jsonSchema),this.incrementalWriteQueue=new vh(this.storageInstance,this.schema.primaryPath,(d,f)=>wh(this,d,f),d=>this._runHooks("post","save",d)),this.$=this.eventBulks$.pipe(Mt(d=>Zd(d))),this.checkpoint$=this.eventBulks$.pipe(We(d=>d.checkpoint)),this._changeEventBuffer=db(this.asRxCollection);var i;this._docCache=new Ch(this.schema.primaryPath,this.eventBulks$.pipe(Ce(d=>!d.isLocal),We(d=>d.events)),d=>(i||(i=pb(this.asRxCollection)),mb(this.asRxCollection,i,d)));var a=this.database.internalStore.changeStream().pipe(Ce(d=>{var f=this.name+"-"+this.schema.version,m=d.events.find(y=>y.documentData.context==="collection"&&y.documentData.key===f&&y.operation==="DELETE");return!!m})).subscribe(async()=>{await this.close(),await Promise.all(this.onRemove.map(d=>d()))});this._subs.push(a);var o=await this.database.storageToken,u=this.storageInstance.changeStream().subscribe(d=>{var f={id:d.id,isLocal:!1,internal:!1,collectionName:this.name,storageToken:o,events:d.events,databaseToken:this.database.token,checkpoint:d.checkpoint,context:d.context};this.database.$emit(f)});return this._subs.push(u),nt},t.cleanup=function(n){throw gt(this),De("cleanup")},t.migrationNeeded=function(){throw De("migration-schema")},t.getMigrationState=function(){throw De("migration-schema")},t.startMigration=function(n=10){return gt(this),this.getMigrationState().startMigration(n)},t.migratePromise=function(n=10){return this.getMigrationState().migratePromise(n)},t.insert=async function(n){gt(this);var i=await this.bulkInsert([n]),a=i.error[0];ja(this,n[this.schema.primaryPath],n,a);var o=Z(i.success[0]);return o},t.insertIfNotExists=async function(n){var i=await this.bulkInsert([n]);if(i.error.length>0){var a=i.error[0];if(a.status===409){var o=a.documentInDb;return Ho(this._docCache,[o])[0]}else throw a}return i.success[0]},t.bulkInsert=async function(n){if(gt(this),n.length===0)return{success:[],error:[]};var i=this.schema.primaryPath,a=new Set,o;
22if(this.hasHooks("pre","insert"))o=await Promise.all(n.map(D=>{var M=Sa(this.schema,D);return this._runHooks("pre","insert",M).then(()=>(a.add(M[i]),{document:M}))}));else{o=new Array(n.length);for(var u=this.schema,d=0;d<n.length;d++){var f=n[d],m=Sa(u,f);a.add(m[i]),o[d]={document:m}}}if(a.size!==n.length)throw ee("COL22",{collection:this.name,args:{documents:n}});var y=await this.storageInstance.bulkWrite(o,"rx-collection-bulk-insert"),g,w=this,S={get success(){if(!g){var D=St(w.schema.primaryPath,o,y);g=Ho(w._docCache,D)}return g},error:y.error};if(this.hasHooks("post","insert")){var E=new Map;o.forEach(D=>{var M=D.document;E.set(M[i],M)}),await Promise.all(S.success.map(D=>this._runHooks("post","insert",E.get(D.primary),D)))}return S},t.bulkRemove=async function(n){gt(this);var i=this.schema.primaryPath;if(n.length===0)return{success:[],error:[]};var a;typeof n[0]=="string"?a=await this.findByIds(n).exec():(a=new Map,n.forEach(w=>a.set(w.primary,w)));var o=[],u=new Map;Array.from(a.values()).forEach(w=>{var S=w.toMutableJSON(!0);o.push(S),u.set(w.primary,S)}),await Promise.all(o.map(w=>{var S=w[this.schema.primaryPath];return this._runHooks("pre","remove",w,a.get(S))}));var d=o.map(w=>{var S=Oe(w);return S._deleted=!0,{previous:w,document:S}}),f=await this.storageInstance.bulkWrite(d,"rx-collection-bulk-remove"),m=St(this.schema.primaryPath,d,f),y=[],g=m.map(w=>{var S=w[i],E=this._docCache.getCachedRxDocument(w);return y.push(E),S});return await Promise.all(g.map(w=>this._runHooks("post","remove",u.get(w),a.get(w)))),{success:y,error:f.error}},t.bulkUpsert=async function(n){gt(this);var i=[],a=new Map;n.forEach(f=>{var m=Sa(this.schema,f),y=m[this.schema.primaryPath];if(!y)throw ee("COL3",{primaryPath:this.schema.primaryPath,data:m,schema:this.schema.jsonSchema});a.set(y,m),i.push(m)});var o=await this.bulkInsert(i),u=o.success.slice(0),d=[];return await Promise.all(o.error.map(async f=>{if(f.status!==409)d.push(f);else{var m=f.documentId,y=Wr(a,m),g=Z(f.documentInDb),w=this._docCache.getCachedRxDocuments([g])[0],S=await w.incrementalModify(()=>y);u.push(S)}})),{error:d,success:u}},t.upsert=async function(n){gt(this);var i=await this.bulkUpsert([n]);return ja(this.asRxCollection,n[this.schema.primaryPath],n,i.error[0]),i.success[0]},t.incrementalUpsert=function(n){gt(this);var i=Sa(this.schema,n),a=i[this.schema.primaryPath];if(!a)throw ee("COL4",{data:n});var o=this._incrementalUpsertQueues.get(a);return o||(o=nt),o=o.then(()=>wb(this,a,i)).then(u=>u.inserted?u.doc:gb(u.doc,i)),this._incrementalUpsertQueues.set(a,o),o},t.find=function(n){gt(this),ot("prePrepareRxQuery",{op:"find",queryObj:n,collection:this}),n||(n=xa());var i=Zn("find",n,this);return i},t.findOne=function(n){gt(this),ot("prePrepareRxQuery",{op:"findOne",queryObj:n,collection:this});var i;if(typeof n=="string")i=Zn("findOne",{selector:{[this.schema.primaryPath]:n},limit:1},this);else{if(n||(n=xa()),n.limit)throw ee("QU6");n=Oe(n),n.limit=1,i=Zn("findOne",n,this)}return i},t.count=function(n){gt(this),n||(n=xa());var i=Zn("count",n,this);return i},t.findByIds=function(n){gt(this);var i={selector:{[this.schema.primaryPath]:{$in:n.slice(0)}}},a=Zn("findByIds",i,this);return a},t.exportJSON=function(){throw De("json-dump")},t.importJSON=function(n){throw De("json-dump")},t.insertCRDT=function(n){throw De("crdt")},t.addPipeline=function(n){throw De("pipeline")},t.addHook=function(n,i,a,o=!1){if(typeof a!="function")throw $a("COL7",{key:i,when:n});if(!Kh.includes(n))throw $a("COL8",{key:i,when:n});if(!Ah.includes(i))throw ee("COL9",{key:i});if(n==="post"&&i==="create"&&o===!0)throw ee("COL10",{when:n,key:i,parallel:o});var u=a.bind(this),d=o?"parallel":"series";this.hooks[i]=this.hooks[i]||{},this.hooks[i][n]=this.hooks[i][n]||{series:[],parallel:[]},this.hooks[i][n][d].push(u)},t.getHooks=function(n,i){return!this.hooks[i]||!this.hooks[i][n]?{series:[],parallel:[]}:this.hooks[i][n]},t.hasHooks=function(n,i){if(!this.hooks[i]||!this.hooks[i][n])return!1;var a=this.getHooks(n,i);return a?a.series.length>0||a.parallel.length>0:!1},t._runHooks=function(n,i,a,o){var u=this.getHooks(n,i);if(!u)return nt;var d=u.series.map(f=>()=>f(a,o));return yy(d).then(()=>Promise.all(u.parallel.map(f=>f(a,o))))},t._runHooksSync=function(n,i,a,o){if(this.hasHooks(n,i)){var u=this.getHooks(n,i);
22u&&u.series.forEach(d=>d(a,o))}},t.promiseWait=function(n){var i=new Promise(a=>{var o=setTimeout(()=>{this.timeouts.delete(o),a()},n);this.timeouts.add(o)});return i},t.close=async function(){return this.closed?Rt:(un.delete(this),await Promise.all(this.onClose.map(n=>n())),this.closed=!0,Array.from(this.timeouts).forEach(n=>clearTimeout(n)),this._changeEventBuffer&&this._changeEventBuffer.close(),this.database.requestIdlePromise().then(()=>this.storageInstance.close()).then(()=>(this._subs.forEach(n=>n.unsubscribe()),delete this.database.collections[this.name],Gt("postCloseRxCollection",this).then(()=>!0))))},t.remove=async function(){await this.close(),await Promise.all(this.onRemove.map(n=>n())),await Th(this.database.storage,this.database.internalStore,this.database.token,this.database.name,this.name,this.database.multiInstance,this.database.password,this.database.hashFunction)},wr(e,[{key:"insert$",get:function(){return this.$.pipe(Ce(r=>r.operation==="INSERT"))}},{key:"update$",get:function(){return this.$.pipe(Ce(r=>r.operation==="UPDATE"))}},{key:"remove$",get:function(){return this.$.pipe(Ce(r=>r.operation==="DELETE"))}},{key:"asRxCollection",get:function(){return this}}])})();function vb(e){if(!pl){pl=!0;var t=Object.getPrototypeOf(e);Ah.forEach(r=>{Kh.map(n=>{var i=n+Id(r);t[i]=function(a,o){return this.addHook(n,r,a,o)}})})}}function gb(e,t){return e.incrementalModify(r=>t)}function wb(e,t,r){var n=e._docCache.getLatestDocumentDataIfExists(t);return n?Promise.resolve({doc:e._docCache.getCachedRxDocuments([n])[0],inserted:!1}):e.findOne(t).exec().then(i=>i?{doc:i,inserted:!1}:e.insert(r).then(a=>({doc:a,inserted:!0})))}async function bb({database:e,name:t,schema:r,instanceCreationOptions:n={},migrationStrategies:i={},autoMigrate:a=!0,statics:o={},methods:u={},attachments:d={},options:f={},localDocuments:m=!1,cacheReplacementPolicy:y=Ih,conflictHandler:g=Va}){var w={databaseInstanceToken:e.token,databaseName:e.name,collectionName:t,schema:r.jsonSchema,options:n,multiInstance:e.multiInstance,password:e.password,devMode:xe.isDevMode()};ot("preCreateRxStorageInstance",w);var S=await ub(e,w),E=new Nh(e,t,r,S,n,i,u,d,f,y,o,g);try{await E.prepare(),Object.entries(o).forEach(([D,M])=>{Object.defineProperty(E,D,{get:()=>M.bind(E)})}),ot("createRxCollection",{collection:E,creator:{name:t,schema:r,storageInstance:S,instanceCreationOptions:n,migrationStrategies:i,methods:u,attachments:d,options:f,cacheReplacementPolicy:y,localDocuments:m,statics:o}}),a&&E.schema.version!==0&&await E.migratePromise()}catch(D){throw un.delete(E),await S.close(),D}return E}var Mh=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this._parallels=t||1,this._qC=0,this._iC=new Set,this._lHN=0,this._hPM=new Map,this._pHM=new Map};Mh.prototype={isIdle:function(){return this._qC<this._parallels},lock:function(){this._qC++},unlock:function(){this._qC--,Jo(this)},wrapCall:function(t){var r=this;this._qC++;var n;try{n=t()}catch(i){throw this.unlock(),i}return!n.then||typeof n.then!="function"?(this.unlock(),n):n.then(function(i){return r.unlock(),i}).catch(function(i){throw r.unlock(),i})},requestIdlePromise:function(t){var r=this;t=t||{};var n,i=new Promise(function(u){return n=u}),a=function(){So(r,i),n()};if(i._manRes=a,t.timeout){var o=setTimeout(function(){i._manRes()},t.timeout);i._timeoutObj=o}return this._iC.add(i),Jo(this),i},cancelIdlePromise:function(t){So(this,t)},requestIdleCallback:function(t,r){var n=this._lHN++,i=this.requestIdlePromise(r);return this._hPM.set(n,i),this._pHM.set(i,n),i.then(function(){return t()}),n},cancelIdleCallback:function(t){var r=this._hPM.get(t);this.cancelIdlePromise(r)},clear:function(){var t=this;this._iC.forEach(function(r){return So(t,r)}),this._qC=0,this._iC.clear(),this._hPM=new Map,this._pHM=new Map}};function Sb(e){if(e._iC.size!==0){var t=e._iC.values(),r=t.next().value;r._manRes(),setTimeout(function(){return Jo(e)},0)}}function So(e,t){if(t){if(t._timeoutObj&&clearTimeout(t._timeoutObj),e._pHM.has(t)){var r=e._pHM.get(t);e._hPM.delete(r),e._pHM.delete(t)}e._iC.delete(t)}}function Jo(e){e._tryIR||e._iC.size===0||(e._tryIR=!0,setTimeout(function(){if(!e.isIdle()){e._tryIR=!1;return}setTimeout(function(){if(!e.isIdle()){e._tryIR=!1;return}Sb(e),e._tryIR=!1},0)},0))}class Oc{constructor(t){ya(this,"ttl");ya(this,"map",new Map);ya(this,"_to",!1);this.ttl=t}
22has(t){return this.map.has(t)}add(t){this.map.set(t,Bh()),this._to||(this._to=!0,setTimeout(()=>{this._to=!1,Eb(this)},0))}clear(){this.map.clear()}}function Eb(e){const t=Bh()-e.ttl,r=e.map[Symbol.iterator]();for(;;){const n=r.next().value;if(!n)return;const i=n[0];if(n[1]<t)e.map.delete(i);else return}}function Bh(){return Date.now()}var jo=new Set,ml=new Map,Tc=(function(){function e(r,n,i,a,o,u,d=!1,f={},m,y,g,w,S,E){this.idleQueue=new Mh,this.rxdbVersion=hc,this.storageInstances=new Set,this._subs=[],this.startupErrors=[],this.onClose=[],this.closed=!1,this.collections={},this.states={},this.eventBulks$=new He,this.closePromise=null,this.observable$=this.eventBulks$.pipe(Mt(D=>Zd(D))),this.storageToken=Rt,this.storageTokenDocument=Rt,this.emittedEventBulkIds=new Oc(60*1e3),this.name=r,this.token=n,this.storage=i,this.instanceCreationOptions=a,this.password=o,this.multiInstance=u,this.eventReduce=d,this.options=f,this.internalStore=m,this.hashFunction=y,this.cleanupPolicy=g,this.allowSlowCount=w,this.reactivity=S,this.onClosed=E,this.name!=="pseudoInstance"&&(this.internalStore=Ec(this.asRxDatabase,m,xc),this.storageTokenDocument=sb(this.asRxDatabase).catch(D=>this.startupErrors.push(D)),this.storageToken=this.storageTokenDocument.then(D=>D.data.token).catch(D=>this.startupErrors.push(D)))}var t=e.prototype;return t.getReactivityFactory=function(){if(!this.reactivity)throw ee("DB14",{database:this.name});return this.reactivity},t.$emit=function(n){this.emittedEventBulkIds.has(n.id)||(this.emittedEventBulkIds.add(n.id),this.eventBulks$.next(n))},t.removeCollectionDoc=async function(n,i){var a=await Kn(this.internalStore,Jr(Ga(n,i),mr));if(!a)throw ee("SNH",{name:n,schema:i});var o=Li(a);o._deleted=!0,await this.internalStore.bulkWrite([{document:o,previous:a}],"rx-database-remove-collection")},t.addCollections=async function(n){var i={},a={},o=[],u={};await Promise.all(Object.entries(n).map(async([m,y])=>{var g=m,w=y.schema;i[g]=w;var S=xy(w,this.hashFunction);if(a[g]=S,this.collections[m])throw ee("DB3",{name:m});var E=Ga(m,w),D={id:Jr(E,mr),key:E,context:mr,data:{name:g,schemaHash:await S.hash,schema:S.jsonSchema,version:S.version,connectedStorages:[]},_deleted:!1,_meta:Dn(),_rev:kt(),_attachments:{}};o.push({document:D});var M=Object.assign({},y,{name:g,schema:S,database:this}),U=Oe(y);U.database=this,U.name=m,ot("preCreateRxCollection",U),M.conflictHandler=U.conflictHandler,u[g]=M}));var d=await this.internalStore.bulkWrite(o,"rx-database-add-collection");await Ib(this),await Promise.all(d.error.map(async m=>{if(m.status!==409)throw ee("DB12",{database:this.name,writeError:m});var y=Z(m.documentInDb),g=y.data.name,w=a[g];if(y.data.schemaHash!==await w.hash)throw ee("DB6",{database:this.name,collection:g,previousSchemaHash:y.data.schemaHash,schemaHash:await w.hash,previousSchema:y.data.schema,schema:Z(i[g])})}));var f={};return await Promise.all(Object.keys(n).map(async m=>{var y=u[m],g=await bb(y);f[m]=g,this.collections[m]=g,this[m]||Object.defineProperty(this,m,{get:()=>this.collections[m]})})),f},t.lockedRun=function(n){return this.idleQueue.wrapCall(n)},t.requestIdlePromise=function(){return this.idleQueue.requestIdlePromise()},t.exportJSON=function(n){throw De("json-dump")},t.addState=function(n){throw De("state")},t.importJSON=function(n){throw De("json-dump")},t.backup=function(n){throw De("backup")},t.leaderElector=function(){throw De("leader-election")},t.isLeader=function(){throw De("leader-election")},t.waitForLeadership=function(){throw De("leader-election")},t.migrationStates=function(){throw De("migration-schema")},t.close=function(){if(this.closePromise)return this.closePromise;var{promise:n,resolve:i}=Fh(),a=o=>{this.onClosed&&this.onClosed(),this.closed=!0,i(o)};return this.closePromise=n,(async()=>{if(await Gt("preCloseRxDatabase",this),this.eventBulks$.complete(),this._subs.map(o=>o.unsubscribe()),this.name==="pseudoInstance"){a(!1);return}return this.requestIdlePromise().then(()=>Promise.all(this.onClose.map(o=>o()))).then(()=>Promise.all(Object.keys(this.collections).map(o=>this.collections[o]).map(o=>o.close()))).then(()=>this.internalStore.close()).then(()=>a(!0))})(),n},t.remove=function(){return this.close().then(()=>Kc(this.name,this.storage,this.multiInstance,this.password))},wr(e,[{key:"$",get:function(){return this.observable$}},{key:"asRxDatabase",get:function(){return this}}])})();function _b(e,t){if(jo.has(Lh(e,t)))throw ee("DB8",{name:e,storage:t.name,link:"https://rxdb.info/rx-database.html#ignoreduplicate"})}function Fh(){var e,t,r=new Promise((n,i)=>{e=n,t=i});return{promise:r,resolve:e,reject:t}}function Lh(e,t){return t.name+"|"+e}async function Uh(e,t,r,n,i,a){var o=await t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:Wg,schema:xc,options:n,multiInstance:i,password:a,devMode:xe.isDevMode()});return o}function Pb({storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:i=!0,eventReduce:a=!0,ignoreDuplicate:o=!1,options:u={},cleanupPolicy:d,closeDuplicates:f=!1,allowSlowCount:m=!1,localDocuments:y=!1,hashFunction:g=_d,reactivity:w}){ot("preCreateRxDatabase",{storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:i,eventReduce:a,ignoreDuplicate:o,options:u,localDocuments:y});var S=Lh(r,e),E=ml.get(S)||new Set,D=Fh(),M=Array.from(E),U=()=>{E.delete(D.promise),jo.delete(S)};return E.add(D.promise),ml.set(S,E),(async()=>
22{if(f&&await Promise.all(M.map(V=>V.catch(()=>null).then(W=>W&&W.close()))),o){if(!xe.isDevMode())throw ee("DB9",{database:r})}else _b(r,e);jo.add(S);var F=Tn(10),j=await Uh(F,e,r,t,i,n),$=new Tc(r,F,e,t,n,i,a,u,j,g,d,m,w,U);return await Gt("createRxDatabase",{database:$,creator:{storage:e,instanceCreationOptions:t,name:r,password:n,multiInstance:i,eventReduce:a,ignoreDuplicate:o,options:u,localDocuments:y}}),$})().then(F=>{D.resolve(F)}).catch(F=>{D.reject(F),U()}),D.promise}async function Kc(e,t,r=!0,n){var i=Tn(10),a=await Uh(i,t,e,{},r,n),o=await Dh(a),u=new Set;o.forEach(f=>u.add(f.data.name));var d=Array.from(u);return await Promise.all(d.map(f=>Th(t,a,i,e,f,r,n))),await Gt("postRemoveRxDatabase",{databaseName:e,storage:t}),await a.remove(),d}function Wh(e){return e instanceof Tc}async function Ib(e){if(await e.storageToken,e.startupErrors[0])throw e.startupErrors[0]}var Cb={RxSchema:Od.prototype,RxDocument:gs,RxQuery:kh.prototype,RxCollection:Nh.prototype,RxDatabase:Tc.prototype},Eo=new Set,yl=new Set;function hn(e){if(ot("preAddRxPlugin",{plugin:e,plugins:Eo}),!Eo.has(e)){{if(yl.has(e.name))throw ee("PL3",{name:e.name,plugin:e});Eo.add(e),yl.add(e.name)}if(!e.rxdb)throw $a("PL1",{plugin:e});e.init&&e.init(),e.prototypes&&Object.entries(e.prototypes).forEach(([t,r])=>r(Cb[t])),e.overwritable&&Object.assign(xe,e.overwritable),e.hooks&&Object.entries(e.hooks).forEach(([t,r])=>{r.after&&mi[t].push(r.after),r.before&&mi[t].unshift(r.before)})}}async function Ya(e,t){var r=br(e.input.metaInstance.schema,{isCheckpoint:"1",itemId:t}),n=await e.input.metaInstance.findDocumentsById([r],!1),i=n[0];if(e.lastCheckpointDoc[t]=i,i)return i.checkpointData}async function Qa(e,t,r){e.checkpointQueue=e.checkpointQueue.then(async()=>{var n=e.lastCheckpointDoc[t];if(r&&!e.events.canceled.getValue()&&(!n||JSON.stringify(n.checkpointData)!==JSON.stringify(r))){var i={id:"",isCheckpoint:"1",itemId:t,_deleted:!1,_attachments:{},checkpointData:r,_meta:Dn(),_rev:kt()};for(i.id=br(e.input.metaInstance.schema,i);!e.events.canceled.getValue();){if(n&&(i.checkpointData=Pi([n.checkpointData,i.checkpointData])),i._meta.lwt=Ze(),i._rev=zt(await e.checkpointKey,n),e.events.canceled.getValue())return;var a=[{previous:n,document:i}],o=await e.input.metaInstance.bulkWrite(a,"replication-set-checkpoint"),u=St(e.primaryPath,a,o)[0];if(u){e.lastCheckpointDoc[t]=u;return}else{var d=o.error[0];if(d.status!==409)throw d;n=Z(d.documentInDb),i._rev=zt(await e.checkpointKey,n)}}}}),await e.checkpointQueue}async function kb(e){var t=await e.hashFunction([e.identifier,e.forkInstance.databaseName,e.forkInstance.collectionName].join("||"));return"rx_storage_replication_"+t}function vl(e,t,r,n,i){var a=Object.assign({},n,{_attachments:t&&n._attachments?n._attachments:{},_meta:r?n._meta:Object.assign({},i?i._meta:{},{lwt:Ze()}),_rev:r?n._rev:kt()});return a._rev||(a._rev=zt(e,i)),a}function or(e,t,r){var n=Oe(e);return t||delete n._attachments,r||(delete n._meta,delete n._rev),n}function zo(e,t){return e.hasAttachments?t.map(r=>{var n=st(r.document);return n.docData=At(n.docData),{document:n,previous:r.previous}}):t}function Go(e){for(;;)if(e.underlyingPersistentStorage)e=e.underlyingPersistentStorage;else return e}var Ta="RxReplicationProtocolMetaData";function Vo(e,t){var r=Ey(e),n={title:Ta,primaryKey:{key:"id",fields:["itemId","isCheckpoint"],separator:"|"},type:"object",version:e.version,additionalProperties:!1,properties:{id:{type:"string",minLength:1,maxLength:r+2},isCheckpoint:{type:"string",enum:["0","1"],minLength:1,maxLength:1},itemId:{type:"string",maxLength:r>4?r:4},checkpointData:{type:"object",additionalProperties:!0},docData:{type:"object",properties:e.properties},isResolvedConflict:{type:"string"}},keyCompression:e.keyCompression,required:["id","isCheckpoint","itemId"]};t&&(n.encrypted=["docData"]);var i=ds(n);return i}function $h(e,t){return e.input.metaInstance.findDocumentsById(t.map(r=>{var n=br(e.input.metaInstance.schema,{itemId:r,isCheckpoint:"0"});return n}),!0).then(r=>{var n={};return Object.values(r).forEach(i=>{n[i.itemId]={docData:i.docData,metaDocument:i}}),n})}async function Xa(e,t,r,n){var i=t[e.primaryPath],a=r?Li(r):{id:"",isCheckpoint:"0",itemId:i,docData:t,_attachments:{},_deleted:!1,_rev:kt(),_meta:{lwt:0}};a.docData=t,n&&(a.isResolvedConflict=n),a._meta.lwt=Ze(),a.id=br(e.input.metaInstance.schema,a),a._rev=zt(await e.checkpointKey,r);var o={previous:r,document:a};return o}async function Rb(e){if(e.input.initialCheckpoint&&e.input.initialCheckpoint.downstream){var t=await Ya(e,"down");t||await Qa(e,"down",e.input.initialCheckpoint.downstream)}var r=await e.input.hashFunction(e.input.identifier),n=e.input.replicationHandler,i=0,a=[];function o(S){e.stats.down.addNewTask=e.stats.down.addNewTask+1;var E={time:i++,task:S};a.push(E),e.streamQueue.down=e.streamQueue.down.then(()=>{for(var D=[];a.length>0;){e.events.active.down.next(!0);var M=Z(a.shift());if(!(M.time<d)){if(M.task==="RESYNC")if(D.length===0){D.push(M.task);break}else break;D.push(M.task)}}if(D.length!==0)return D[0]==="RESYNC"?f():m(D)}).then(()=>{e.events.active.down.next(!1),!e.firstSyncDone.down.getValue()&&!e.events.canceled.getValue()&&e.firstSyncDone.down.next(!0)})}if(o("RESYNC"),!e.events.canceled.getValue()){var u=n.masterChangeStream$.pipe(Mt(async S=>
22(await Nt(e.events.active.up.pipe(Ce(E=>!E))),S))).subscribe(S=>{e.stats.down.masterChangeStreamEmit=e.stats.down.masterChangeStreamEmit+1,o(S)});Nt(e.events.canceled.pipe(Ce(S=>!!S))).then(()=>u.unsubscribe())}var d=-1;async function f(){if(e.stats.down.downstreamResyncOnce=e.stats.down.downstreamResyncOnce+1,!e.events.canceled.getValue()){e.checkpointQueue=e.checkpointQueue.then(()=>Ya(e,"down"));for(var S=await e.checkpointQueue,E=[];!e.events.canceled.getValue();){d=i++;var D=await n.masterChangesSince(S,e.input.pullBatchSize);if(D.documents.length===0||(S=Pi([S,D.checkpoint]),E.push(w(D.documents,S)),D.documents.length<e.input.pullBatchSize))break}await Promise.all(E)}}function m(S){e.stats.down.downstreamProcessChanges=e.stats.down.downstreamProcessChanges+1;var E=[],D=null;return S.forEach(M=>{if(M==="RESYNC")throw new Error("SNH");Ur(E,M.documents),D=Pi([D,M.checkpoint])}),w(E,Z(D))}var y=nt,g={docs:{}};function w(S,E){var D=e.primaryPath;return e.stats.down.persistFromMaster=e.stats.down.persistFromMaster+1,S.forEach(M=>{var U=M[D];g.docs[U]=M}),g.checkpoint=E,y=y.then(()=>{var M=g.docs;g.docs={};var U=g.checkpoint,F=Object.keys(M);if(e.events.canceled.getValue()||F.length===0)return nt;var j=[],$={},V={},W=[];return Promise.all([e.input.forkInstance.findDocumentsById(F,!0),$h(e,F)]).then(([ie,de])=>{var Se=new Map;return ie.forEach(ue=>Se.set(ue[D],ue)),Promise.all(F.map(async ue=>{var re=Se.get(ue),oe=re?or(re,e.hasAttachments,!1):void 0,ye=M[ue],Ie=de[ue];Ie&&re&&Ie.metaDocument.isResolvedConflict===re._rev&&await e.streamQueue.up;var Je=!Ie||!oe?!1:e.input.conflictHandler.isEqual(Ie.docData,oe,"downstream-check-if-equal-0");if(!Je&&Ie&&Ie.docData._rev&&re&&re._meta[e.input.identifier]&&yr(re._rev)===re._meta[e.input.identifier]&&(Je=!0),re&&Ie&&Je===!1||re&&!Ie)return nt;var Me=oe?e.input.conflictHandler.isEqual(ye,oe,"downstream-check-if-equal-1"):!1;if(oe&&Me)return(!Ie||Je===!1)&&W.push(await Xa(e,oe,Ie?Ie.metaDocument:void 0)),nt;var fe=Object.assign({},ye,re?{_meta:Oe(re._meta),_attachments:e.hasAttachments&&ye._attachments?ye._attachments:{},_rev:kt()}:{_meta:{lwt:Ze()},_rev:kt(),_attachments:e.hasAttachments&&ye._attachments?ye._attachments:{}});if(ye._rev){var ve=re?yr(re._rev)+1:1;fe._meta[e.input.identifier]=ve,e.input.keepMeta&&(fe._rev=ye._rev)}e.input.keepMeta&&ye._meta&&(fe._meta=ye._meta);var ne={previous:re,document:fe};ne.document._rev=ne.document._rev?ne.document._rev:zt(r,ne.previous),j.push(ne),$[ue]=ne,V[ue]=await Xa(e,ye,Ie?Ie.metaDocument:void 0)}))}).then(async()=>{if(j.length>0)return e.input.forkInstance.bulkWrite(j,await e.downstreamBulkWriteFlag).then(ie=>{var de=St(e.primaryPath,j,ie);de.forEach(ue=>{var re=ue[D];e.events.processed.down.next($[re]),W.push(V[re])});var Se;if(ie.error.forEach(ue=>{if(ue.status!==409){var re=ee("RC_PULL",{writeError:ue});
22e.events.error.next(re),Se=re}}),Se)throw Se})}).then(()=>{if(W.length>0)return e.input.metaInstance.bulkWrite(zo(e,W),"replication-down-write-meta").then(ie=>{ie.error.forEach(de=>{e.events.error.next(ee("RC_PULL",{id:de.documentId,writeError:de}))})})}).then(()=>{Qa(e,"down",U)})}).catch(M=>e.events.error.next(M)),y}}async function Db(e,t,r){var n=e.input.conflictHandler,i=n.isEqual(t.realMasterState,t.newDocumentState,"replication-resolve-conflict");if(!i){var a=await n.resolve(t,"replication-resolve-conflict"),o=Object.assign({},a,{_meta:Oe(r._meta),_rev:kt(),_attachments:Oe(r._attachments)});return o._meta.lwt=Ze(),o._rev=zt(await e.checkpointKey,r),o}}async function Yo(e,t,r,n){if(!r._attachments||n&&!n._attachments)throw new Error("_attachments missing");var i=r[e],a=new Set(n&&n._attachments?Object.keys(n._attachments):[]);return await Promise.all(Object.entries(r._attachments).map(async([o,u])=>{if((!a.has(o)||n&&Z(n._attachments)[o].digest!==u.digest)&&!u.data){var d=await t.getAttachmentData(i,o,u.digest);u.data=d}})),r}async function xb(e){if(e.input.initialCheckpoint&&e.input.initialCheckpoint.upstream){var t=await Ya(e,"up");t||await Qa(e,"up",e.input.initialCheckpoint.upstream)}var r=e.input.replicationHandler;e.streamQueue.up=e.streamQueue.up.then(()=>m().then(()=>y()));var n=0,i=-1,a=[],o=Rt,u={docs:{}},d=e.input.forkInstance.changeStream().subscribe(w=>{if(!e.events.paused.getValue())return e.stats.up.forkChangeStreamEmit=e.stats.up.forkChangeStreamEmit+1,a.push({task:w,time:n++}),e.events.active.up.getValue()||e.events.active.up.next(!0),e.input.waitBeforePersist?e.input.waitBeforePersist().then(()=>y()):y()}),f=r.masterChangeStream$.pipe(Ce(w=>w==="RESYNC")).subscribe(()=>{a.push({task:"RESYNC",time:n++}),y()});Nt(e.events.canceled.pipe(Ce(w=>!!w))).then(()=>{d.unsubscribe(),f.unsubscribe()});async function m(){if(e.stats.up.upstreamInitialSync=e.stats.up.upstreamInitialSync+1,!e.events.canceled.getValue()){e.checkpointQueue=e.checkpointQueue.then(()=>Ya(e,"up"));for(var w=await e.checkpointQueue,S=new Set,E=async function(){i=n++,S.size>3&&await Promise.race(Array.from(S));var U=await mh(e.input.forkInstance,e.input.pushBatchSize,w);if(U.documents.length===0)return 1;w=Pi([w,U.checkpoint]);var F=g(U.documents,Z(w));S.add(F),F.catch().then(()=>S.delete(F))};!e.events.canceled.getValue()&&!await E(););var D=await Promise.all(S),M=D.find(U=>!!U);M?await m():!e.firstSyncDone.up.getValue()&&!e.events.canceled.getValue()&&e.firstSyncDone.up.next(!0)}}function y(){if(e.events.canceled.getValue()||a.length===0){e.events.active.up.next(!1);return}e.stats.up.processTasks=e.stats.up.processTasks+1,e.events.active.up.next(!0),e.streamQueue.up=e.streamQueue.up.then(async()=>{for(var w=[],S={};a.length>0;){var E=Z(a.shift());if(!(E.time<i)){if(E.task==="RESYNC"){e.events.active.up.next(!1),await m();return}E.task.context!==await e.downstreamBulkWriteFlag&&Ur(w,E.task.events.map(D=>D.documentData)),S=Pi([S,E.task.checkpoint])}}if(await g(w,S),a.length===0)e.events.active.up.next(!1);else return y()})}function g(w,S){return e.stats.up.persistToMaster=e.stats.up.persistToMaster+1,w.forEach(E=>{var D=E[e.primaryPath];u.docs[D]=E}),u.checkpoint=S,o=o.then(async()=>{if(e.events.canceled.getValue())return!1;var E=u.docs;u.docs={};var D=u.checkpoint,M=Object.keys(E);function U(){return Qa(e,"up",D)}if(M.length===0)return U(),!1;var F=await $h(e,M),j={},$=[],V={},W={};if(await Promise.all(M.map(async ne=>{var we=E[ne];W[ne]=we;var _e=or(we,e.hasAttachments,!!e.input.keepMeta),ge=F[ne];ge&&ge.metaDocument.isResolvedConflict!==we._rev&&e.input.conflictHandler.isEqual(ge.docData,_e,"upstream-check-if-equal")||ge&&ge.docData._rev&&yr(we._rev)===we._meta[e.input.identifier]||($.push(ne),j[ne]={assumedMasterState:ge?ge.docData:void 0,newDocumentState:_e},V[ne]=await Xa(e,_e,ge?ge.metaDocument:void 0))})),$.length===0)return U(),!1;var ie=Object.values(j),de=new Set,Se={},ue=ty(ie,e.input.pushBatchSize);await Promise.all(ue.map(async ne=>{e.hasAttachments&&await Promise.all(ne.map(async _e=>{_e.newDocumentState=await Yo(e.primaryPath,e.input.forkInstance,st(_e.newDocumentState),_e.assumedMasterState)}));var we=await r.masterWrite(ne);we.forEach(_e=>{var ge=_e[e.primaryPath];de.add(ge),Se[ge]=_e})}));var re=[];if($.forEach(ne=>{de.has(ne)||(e.events.processed.up.next(j[ne]),re.push(V[ne]))}),e.events.canceled.getValue())return!1;re.length>0&&await e.input.metaInstance.bulkWrite(zo(e,re),"replication-up-write-meta");var oe=!1;if(de.size>0){e.stats.up.persistToMasterHadConflicts=e.stats.up.persistToMasterHadConflicts+1;var ye=[],Ie={};if(await Promise.all(Object.entries(Se).map(([ne,we])=>{var _e=j[ne],ge={newDocumentState:_e.newDocumentState,assumedMasterState:_e.assumedMasterState,realMasterState:we};return Db(e,ge,W[ne]).then(async qe=>{if(qe){e.events.resolvedConflicts.next({input:ge,output:qe}
22),ye.push({previous:W[ne],document:qe});var yt=F[ne];Ie[ne]=await Xa(e,Z(we),yt?yt.metaDocument:void 0,qe._rev)}})})),ye.length>0){oe=!0,e.stats.up.persistToMasterConflictWrites=e.stats.up.persistToMasterConflictWrites+1;var Je=await e.input.forkInstance.bulkWrite(ye,"replication-up-write-conflict"),Me;if(Je.error.forEach(ne=>{if(ne.status!==409){var we=ee("RC_PUSH",{writeError:ne});e.events.error.next(we),Me=we}}),Me)throw Me;var fe=[],ve=St(e.primaryPath,ye,Je);ve.forEach(ne=>{var we=ne[e.primaryPath];fe.push(Ie[we])}),fe.length>0&&await e.input.metaInstance.bulkWrite(zo(e,fe),"replication-up-write-conflict-meta")}}return U(),oe}).catch(E=>(e.events.error.next(E),!1)),o}}function qh(e){e=Oe(e),e.forkInstance=Go(e.forkInstance),e.metaInstance=Go(e.metaInstance);var t=kb(e),r={primaryPath:et(e.forkInstance.schema.primaryKey),hasAttachments:!!e.forkInstance.schema.attachments,input:e,checkpointKey:t,downstreamBulkWriteFlag:t.then(n=>"replication-downstream-"+n),events:{canceled:new Kt(!1),paused:new Kt(!1),active:{down:new Kt(!0),up:new Kt(!0)},processed:{down:new He,up:new He},resolvedConflicts:new He,error:new He},stats:{down:{addNewTask:0,downstreamProcessChanges:0,downstreamResyncOnce:0,masterChangeStreamEmit:0,persistFromMaster:0},up:{forkChangeStreamEmit:0,persistToMaster:0,persistToMasterConflictWrites:0,persistToMasterHadConflicts:0,processTasks:0,upstreamInitialSync:0}},firstSyncDone:{down:new Kt(!1),up:new Kt(!1)},streamQueue:{down:nt,up:nt},checkpointQueue:nt,lastCheckpointDoc:{}};return Rb(r),xb(r),r}
22function Ka(e){return Nt(Qd([e.firstSyncDone.down.pipe(Ce(t=>!!t)),e.firstSyncDone.up.pipe(Ce(t=>!!t))])).then(()=>{})}function Qo(e){return Promise.all([e.streamQueue.up,e.streamQueue.down,e.checkpointQueue])}function Ob(e,t,r,n=!1){e=Go(e);var i=!!e.schema.attachments,a=et(e.schema.primaryKey),o={masterChangeStream$:e.changeStream().pipe(Mt(async u=>{var d={checkpoint:u.checkpoint,documents:await Promise.all(u.events.map(async f=>{var m=or(f.documentData,i,n);return i&&(m=await Yo(a,e,st(m),void 0)),m}))};return d})),masterChangesSince(u,d){return mh(e,d,u).then(async f=>({checkpoint:f.documents.length>0?f.checkpoint:u,documents:await Promise.all(f.documents.map(async m=>{var y=or(m,i,n);return i&&(y=await Yo(a,e,st(y),void 0)),y}))}))},async masterWrite(u){var d={};u.forEach(E=>{var D=E.newDocumentState[a];d[D]=E});var f=Object.keys(d),m=await e.findDocumentsById(f,!0),y=new Map;m.forEach(E=>y.set(E[a],E));var g=[],w=[];if(await Promise.all(Object.entries(d).map(([E,D])=>{var M=y.get(E);M?M&&!D.assumedMasterState?g.push(or(M,i,n)):t.isEqual(or(M,i,n),Z(D.assumedMasterState),"rxStorageInstanceToReplicationHandler-masterWrite")===!0?w.push({previous:M,document:vl(r,i,n,D.newDocumentState,M)}):g.push(or(M,i,n)):w.push({document:vl(r,i,n,D.newDocumentState)})})),w.length>0){var S=await e.bulkWrite(w,"replication-master-write");S.error.forEach(E=>{if(E.status!==409)throw ee("SNH",{name:"non conflict error",error:E});g.push(or(Z(E.documentInDb),i,n))})}return g}};return o}async function Hh(e){e.events.canceled.next(!0),e.events.active.up.complete(),e.events.active.down.complete(),e.events.processed.up.complete(),e.events.processed.down.complete(),e.events.resolvedConflicts.complete(),e.events.canceled.complete(),await e.checkpointQueue}function Tb(e){return e&&typeof e.then=="function"}Promise.resolve(!1);var Kb=Promise.resolve(!0),jt=Promise.resolve();function Kr(e,t){return e||(e=0),new Promise(function(r){return setTimeout(function(){return r(t)},e)})}function Ab(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function Ui(){return Math.random().toString(36).substring(2)}var _o=0;function Wi(){var e=Date.now()*1e3;return e<=_o&&(e=_o+1),_o=e,e}function Nb(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}var Mb=Wi,Bb="native";function Fb(e){var t={time:Wi(),messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(r){t.messagesCallback&&t.messagesCallback(r.data)},t}function Lb(e){e.bc.close(),e.subFns=[]}function Ub(e,t){try{return e.bc.postMessage(t,!1),jt}catch(r){return Promise.reject(r)}}function Wb(e,t){e.messagesCallback=t}function $b(){if(typeof globalThis<"u"&&globalThis.Deno&&globalThis.Deno.args)return!0;if((typeof window<"u"||typeof self<"u")&&typeof BroadcastChannel=="function"){if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}else return!1}function qb(){return 150}var Hb={create:Fb,close:Lb,onMessage:Wb,postMessage:Ub,canBeUsed:$b,type:Bb,averageResponseTime:qb,microSeconds:Mb};function Ac(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=JSON.parse(JSON.stringify(e));return typeof t.webWorkerSupport>"u"&&(t.webWorkerSupport=!0),t.idb||(t.idb={}),t.idb.ttl||(t.idb.ttl=1e3*45),t.idb.fallbackInterval||(t.idb.fallbackInterval=150),e.idb&&typeof e.idb.onclose=="function"&&(t.idb.onclose=e.idb.onclose),t.localstorage||(t.localstorage={}),t.localstorage.removeTimeout||(t.localstorage.removeTimeout=1e3*60),e.methods&&(t.methods=e.methods),t.node||(t.node={}),t.node.ttl||(t.node.ttl=1e3*60*2),t.node.maxParallelWrites||(t.node.maxParallelWrites=2048),typeof t.node.useFastPath>"u"&&(t.node.useFastPath=!0),t}var Jb=Wi,jb="pubkey.broadcast-channel-0-",Qt="messages",ws={durability:"relaxed"},zb="idb";function Jh(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"){if(typeof window.mozIndexedDB<"u")return window.mozIndexedDB;if(typeof window.webkitIndexedDB<"u")return window.webkitIndexedDB;if(typeof window.msIndexedDB<"u")return window.msIndexedDB}return!1}function Nc(e){e.commit&&e.commit()}function Gb(e){var t=Jh(),r=jb+e,n=t.open(r);return n.onupgradeneeded=function(i){var a=i.target.result;a.createObjectStore(Qt,{keyPath:"id",autoIncrement:!0})},new Promise(function(i,a){n.onerror=function(o){return a(o)},n.onsuccess=function(){i(n.result)}})}function Vb(e,t,r){var n=Date.now(),i={uuid:t,time:n,data:r},a=e.transaction([Qt],"readwrite",ws);return new Promise(function(o,u){a.oncomplete=function(){return o()},a.onerror=function(f){return u(f)};var d=a.objectStore(Qt);d.add(i),Nc(a)})}function Yb(e,t){var r=e.transaction(Qt,"readonly",ws),n=r.objectStore(Qt),i=[],a=IDBKeyRange.bound(t+1,1/0);if(n.getAll){var o=n.getAll(a);return new Promise(function(d,f){o.onerror=function(m){return f(m)},o.onsuccess=function(m){d(m.target.result)}})}function u(){try{return a=IDBKeyRange.bound(t+1,1/0),n.openCursor(a)}catch{return n.openCursor()}}return new Promise(function(d,f){var m=u();m.onerror=function(y){return f(y)},m.onsuccess=function(y){var g=y.target.result;g?g.value.id<t+1?g.continue(t+1):(i.push(g.value),g.continue()):(Nc(r),d(i))}})}function Qb(e,t){if(e.closed)return Promise.resolve([]);var r=e.db.transaction(Qt,"readwrite",ws),n=r.objectStore(Qt);return Promise.all(t.map(function(i){var a=n.delete(i);return new Promise(function(o){a.onsuccess=function(){return o()}})}))}function Xb(e,t){var r=Date.now()-t,n=e.transaction(Qt,"readonly",ws),i=n.objectStore(Qt),a=[];return new Promise(function(o){i.openCursor().onsuccess=function(u){var d=u.target.result;if(d){var f=d.value;f.time<r?(a.push(f),d.continue()):(Nc(n),o(a))}else o(a)}})}function Zb(e){return Xb(e.db,e.options.idb.ttl).then(function(t){return Qb(e,t.map(function(r){return r.id}))})}function eS(e,t){return t=Ac(t),Gb(e).then(function(r){var n={closed:!1,lastCursorId:0,channelName:e,options:t,uuid:Ui(),eMIs:new Oc(t.idb.ttl*2),writeBlockPromise:jt,messagesCallback:null,readQueuePromises:[],db:r};return r.onclose=function(){n.closed=!0,t.idb.onclose&&t.idb.onclose()},jh(n),n})}function jh(e){e.closed||zh(e).then(function(){return Kr(e.options.idb.fallbackInterval)}).then(function(){return jh(e)})}function tS(e,t){return!(e.uuid===t.uuid||t.eMIs.has(e.id)||e.data.time<t.messagesCallbackTime)}function zh(e){return e.closed||!e.messagesCallback?jt:Yb(e.db,e.lastCursorId).then(function(t){var r=t.filter(function(n){return!!n}).map(function(n){return n.id>e.lastCursorId&&(e.lastCursorId=n.id),n}).filter(function(n){return tS(n,e)}).sort(function(n,i){return n.time-i.time});return r.forEach(function(n){e.messagesCallback&&(e.eMIs.add(n.id),e.messagesCallback(n.data))}),jt})}function rS(e){e.closed=!0,e.db.close()}function nS(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return Vb(e.db,e.uuid,t)}).then(function(){Ab(0,10)===0&&Zb(e)}
22),e.writeBlockPromise}function iS(e,t,r){e.messagesCallbackTime=r,e.messagesCallback=t,zh(e)}function aS(){return!!Jh()}function sS(e){return e.idb.fallbackInterval*2}var oS={create:eS,close:rS,onMessage:iS,postMessage:nS,canBeUsed:aS,type:zb,averageResponseTime:sS,microSeconds:Jb},cS=Wi,uS="pubkey.broadcastChannel-",lS="localstorage";function Gh(){var e;if(typeof window>"u")return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch{}return e}function Vh(e){return uS+e}function dS(e,t){return new Promise(function(r){Kr().then(function(){var n=Vh(e.channelName),i={token:Ui(),time:Date.now(),data:t,uuid:e.uuid},a=JSON.stringify(i);Gh().setItem(n,a);var o=document.createEvent("Event");o.initEvent("storage",!0,!0),o.key=n,o.newValue=a,window.dispatchEvent(o),r()})})}function hS(e,t){var r=Vh(e),n=function(a){a.key===r&&t(JSON.parse(a.newValue))};return window.addEventListener("storage",n),n}function fS(e){window.removeEventListener("storage",e)}function pS(e,t){if(t=Ac(t),!Yh())throw new Error("BroadcastChannel: localstorage cannot be used");var r=Ui(),n=new Oc(t.localstorage.removeTimeout),i={channelName:e,uuid:r,eMIs:n};return i.listener=hS(e,function(a){i.messagesCallback&&a.uuid!==r&&(!a.token||n.has(a.token)||a.data.time&&a.data.time<i.messagesCallbackTime||(n.add(a.token),i.messagesCallback(a.data)))}),i}function mS(e){fS(e.listener)}function yS(e,t,r){e.messagesCallbackTime=r,e.messagesCallback=t}function Yh(){var e=Gh();if(!e)return!1;try{var t="__broadcastchannel_check";e.setItem(t,"works"),e.removeItem(t)}catch{return!1}return!0}function vS(){var e=120,t=navigator.userAgent.toLowerCase();return t.includes("safari")&&!t.includes("chrome")?e*2:e}var gS={create:pS,close:mS,onMessage:yS,postMessage:dS,canBeUsed:Yh,type:lS,averageResponseTime:vS,microSeconds:cS},Qh=Wi,wS="simulate",Mc=new Set;function bS(e){var t={time:Qh(),name:e,messagesCallback:null};return Mc.add(t),t}function SS(e){Mc.delete(e)}var Xh=5;function ES(e,t){return new Promise(function(r){return setTimeout(function(){var n=Array.from(Mc);n.forEach(function(i){i.name===e.name&&i!==e&&i.messagesCallback&&i.time<t.time&&i.messagesCallback(t)}),r()},Xh)})}function _S(e,t){e.messagesCallback=t}function PS(){return!0}function IS(){return Xh}var CS={create:bS,close:SS,onMessage:_S,postMessage:ES,canBeUsed:PS,type:wS,averageResponseTime:IS,microSeconds:Qh},gl=[Hb,oS,gS];function kS(e){var t=[].concat(e.methods,gl).filter(Boolean);if(e.type){if(e.type==="simulate")return CS;var r=t.find(function(i){return i.type===e.type});if(r)return r;throw new Error("method-type "+e.type+" not found")}e.webWorkerSupport||(t=t.filter(function(i){return i.type!=="idb"}));var n=t.find(function(i){return i.canBeUsed()});if(n)return n;throw new Error("No usable method found in "+JSON.stringify(gl.map(function(i){return i.type})))}var Zh=new Set,RS=0,bs=function(t,r){this.id=RS++,Zh.add(this),this.name=t,this.options=Ac(r),this.method=kS(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,DS(this)};bs._pubkey=!0;bs.prototype={postMessage:function(t){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(t));return wl(this,"message",t)},postInternal:function(t){return wl(this,"internal",t)},set onmessage(e){var t=this.method.microSeconds(),r={time:t,fn:e};Sl(this,"message",this._onML),e&&typeof e=="function"?(this._onML=r,bl(this,"message",r)):this._onML=null},addEventListener:function(t,r){var n=this.method.microSeconds(),i={time:n,fn:r};bl(this,t,i)},removeEventListener:function(t,r){var n=this._addEL[t].find(function(i){return i.fn===r});Sl(this,t,n)},close:function(){var t=this;if(!this.closed){Zh.delete(this),this.closed=!0;var r=this._prepP?this._prepP:jt;return this._onML=null,this._addEL.message=[],r.then(function(){return Promise.all(Array.from(t._uMP))}).then(function(){return Promise.all(t._befC.map(function(n){return n()}))}).then(function(){return t.method.close(t._state)})}},get type(){return this.method.type},get isClosed(){return this.closed}};function wl(e,t,r){var n=e.method.microSeconds(),i={time:n,type:t,data:r},a=e._prepP?e._prepP:jt;return a.then(function(){var o=e.method.postMessage(e._state,i);
22return e._uMP.add(o),o.catch().then(function(){return e._uMP.delete(o)}),o})}function DS(e){var t=e.method.create(e.name,e.options);Tb(t)?(e._prepP=t,t.then(function(r){e._state=r})):e._state=t}function ef(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function bl(e,t,r){e._addEL[t].push(r),xS(e)}function Sl(e,t,r){e._addEL[t]=e._addEL[t].filter(function(n){return n!==r}),OS(e)}function xS(e){if(!e._iL&&ef(e)){var t=function(i){e._addEL[i.type].forEach(function(a){i.time>=a.time&&a.fn(i.data)})},r=e.method.microSeconds();e._prepP?e._prepP.then(function(){e._iL=!0,e.method.onMessage(e._state,t,r)}):(e._iL=!0,e.method.onMessage(e._state,t,r))}}function OS(e){if(e._iL&&!ef(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}function TS(e){if(typeof WorkerGlobalScope=="function"&&self instanceof WorkerGlobalScope){var t=self.close.bind(self);self.close=function(){return e(),t()}}else{if(typeof window.addEventListener!="function")return;window.addEventListener("beforeunload",function(){e()},!0),window.addEventListener("unload",function(){e()},!0)}}function KS(e){process.on("exit",function(){return e()}),process.on("beforeExit",function(){return e().then(function(){return process.exit()})}),process.on("SIGINT",function(){return e().then(function(){return process.exit()})}),process.on("uncaughtException",function(t){return e().then(function(){console.trace(t),process.exit(101)})})}var AS=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",NS=AS?KS:TS,ai=new Set,El=!1;function MS(){El||(El=!0,NS(FS))}function BS(e){if(MS(),typeof e!="function")throw new Error("Listener is no function");ai.add(e);var t={remove:function(){return ai.delete(e)},run:function(){return ai.delete(e),e()}};return t}function FS(){var e=[];return ai.forEach(function(t){e.push(t()),ai.delete(t)}),Promise.all(e)}function Lr(e,t){var r={context:"leader",action:t,token:e.token};return e.broadcastChannel.postInternal(r)}function tf(e){e.isLeader=!0,e._hasLeader=!0;var t=BS(function(){return e.die()});e._unl.push(t);var r=function(i){i.context==="leader"&&i.action==="apply"&&Lr(e,"tell"),i.context==="leader"&&i.action==="tell"&&!e._dpLC&&(e._dpLC=!0,e._dpL(),Lr(e,"tell"))};return e.broadcastChannel.addEventListener("internal",r),e._lstns.push(r),Lr(e,"tell")}var rf=function(t,r){var n=this;this.broadcastChannel=t,t._befC.push(function(){return n.die()}),this._options=r,this.isLeader=!1,this.isDead=!1,this.token=Ui(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=!1,this._wKMC={},this.lN="pubkey-bc||"+t.method.type+"||"+t.name};rf.prototype={hasLeader:function(){var t=this;return navigator.locks.query().then(function(r){var n=r.held?r.held.filter(function(i){return i.name===t.lN}):[];return!!(n&&n.length>0)})},awaitLeadership:function(){var t=this;if(!this._wLMP){this._wKMC.c=new AbortController;var r=new Promise(function(n,i){t._wKMC.res=n,t._wKMC.rej=i});this._wLMP=new Promise(function(n){navigator.locks.request(t.lN,{signal:t._wKMC.c.signal},function(){return t._wKMC.c=void 0,tf(t),n(),r}).catch(function(){})})}return this._wLMP},set onduplicate(e){},die:function(){var t=this;return this._lstns.forEach(function(r){return t.broadcastChannel.removeEventListener("internal",r)}),this._lstns=[],this._unl.forEach(function(r){return r.remove()}),this._unl=[],this.isLeader&&(this.isLeader=!1),this.isDead=!0,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort("LeaderElectionWebLock.die() called"),Lr(this,"death")}};var nf=function(t,r){var n=this;this.broadcastChannel=t,this._options=r,this.isLeader=!1,this._hasLeader=!1,this.isDead=!1,this.token=Ui(),this._aplQ=jt,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=!1;var i=function(o){o.context==="leader"&&(o.action==="death"&&(n._hasLeader=!1),o.action==="tell"&&(n._hasLeader=!0))};this.broadcastChannel.addEventListener("internal",i),this._lstns.push(i)};nf.prototype={hasLeader:function(){return Promise.resolve(this._hasLeader)},applyOnce:function(t){var r=this;if(this.isLeader)return Kr(0,!0);if(this.isDead)return Kr(0,!1);if(this._aplQC>1)return this._aplQ;var n=function(){if(r.isLeader)return Kb;var a=!1,o,u=new Promise(function(m){o=function(){a=!0,m()}}),d=function(y){y.context==="leader"&&y.token!=r.token&&(y.action==="apply"&&y.token>r.token&&o(),y.action==="tell"&&(o(),r._hasLeader=!0))};r.broadcastChannel.addEventListener("internal",d);var f=t?r._options.responseTime*4:r._options.responseTime;return Lr(r,"apply").then(function(){return Promise.race([Kr(f),u.then(function(){return Promise.reject(new Error)})])}).then(function(){return Lr(r,"apply")}).then(function(){return Promise.race([Kr(f),u.then(function(){return Promise.reject(new Error)})])}).catch(function(){}).then(function(){return r.broadcastChannel.removeEventListener("internal",d),a?!1:tf(r).then(function(){return!0})})};return this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then(function(){return n()}).then(function(){r._aplQC=r._aplQC-1}),this._aplQ.then(function(){return r.isLeader})},awaitLeadership:function(){return this._aLP||(this._aLP=LS(this)),this._aLP},set onduplicate(e){this._dpL=e},die:function(){var t=this;return this._lstns.forEach(function(r){return t.broadcastChannel.removeEventListener("internal",r)}),this._lstns=[],this._unl.forEach(function(r){return r.remove()}),this._unl=[],this.isLeader&&(this._hasLeader=!1,this.isLeader=!1),this.isDead=!0,Lr(this,"death")}};
22function LS(e){return e.isLeader?jt:new Promise(function(t){var r=!1;function n(){r||(r=!0,e.broadcastChannel.removeEventListener("internal",a),t(!0))}e.applyOnce().then(function(){e.isLeader&&n()});var i=function(){return Kr(e._options.fallbackInterval).then(function(){if(!(e.isDead||r))if(e.isLeader)n();else return e.applyOnce(!0).then(function(){e.isLeader?n():i()})})};i();var a=function(u){u.context==="leader"&&u.action==="death"&&(e._hasLeader=!1,e.applyOnce().then(function(){e.isLeader&&n()}))};e.broadcastChannel.addEventListener("internal",a),e._lstns.push(a)})}function US(e,t){return e||(e={}),e=JSON.parse(JSON.stringify(e)),e.fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}function af(e,t){if(e._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");t=US(t,e);var r=Nb()?new rf(e,t):new nf(e,t);return e._befC.push(function(){return r.die()}),e._leaderElector=r,r}var Za=new Map;function sf(e,t,r,n){var i=Za.get(t);return i||(i={bc:new bs(["RxDB:",e,r].join("|")),refs:new Set},Za.set(t,i)),i.refs.add(n),i.bc}function Xo(e,t){var r=Za.get(e);if(r&&(r.refs.delete(t),r.refs.size===0))return Za.delete(e),r.bc.close()}function of(e,t,r,n){if(t.multiInstance){var i=sf(e,t.databaseInstanceToken,r.databaseName,r),a=new He,o=g=>{g.storageName===e&&g.databaseName===t.databaseName&&g.collectionName===t.collectionName&&g.version===t.schema.version&&a.next(g.eventBulk)};i.addEventListener("message",o);var u=r.changeStream(),d=!1,f=u.subscribe(g=>{d||i.postMessage({storageName:e,databaseName:t.databaseName,collectionName:t.collectionName,version:t.schema.version,eventBulk:g})});r.changeStream=function(){return a.asObservable().pipe(_v(u))};var m=r.close.bind(r);r.close=async function(){return d=!0,f.unsubscribe(),i.removeEventListener("message",o),await Xo(t.databaseInstanceToken,r),m()};var y=r.remove.bind(r);r.remove=async function(){return d=!0,f.unsubscribe(),i.removeEventListener("message",o),await Xo(t.databaseInstanceToken,r),y()}}}function WS(e,t){var r=t.map(n=>{var i=Vt(e,n);if(!i)throw new Error("not in schema: "+n);
22var a=i.type,o;(a==="number"||a==="integer")&&(o=Bc(i));var u=gd(n),d=i.maxLength?i.maxLength:0,f;a==="string"?f=y=>{var g=u(y);return g||(g=""),g.padEnd(d," ")}:a==="boolean"?f=y=>{var g=u(y);return g?"1":"0"}:f=y=>{var g=u(y);return es(o,g)};var m={fieldName:n,schemaPart:i,parsedLengths:o,getValue:u,getIndexStringPart:f};return m});return r}function cf(e,t){var r=WS(e,t),n=r.length,i=r.map(o=>o.getIndexStringPart),a=function(o){for(var u="",d=0;d<n;++d)u+=i[d](o);return u};return a}function Bc(e){var t=Math.floor(e.minimum),r=Math.ceil(e.maximum),n=e.multipleOf,i=r-t,a=i.toString().length,o=n.toString().split("."),u=0;return o.length>1&&(u=o[1].length),{minimum:t,maximum:r,nonDecimals:a,decimals:u,roundedMinimum:t}}function es(e,t){typeof t>"u"&&(t=0),t<e.minimum&&(t=e.minimum),t>e.maximum&&(t=e.maximum);var r=(Math.floor(t)-e.roundedMinimum).toString(),n=r.padStart(e.nonDecimals,"0");if(e.decimals>0){var i=t.toString().split("."),a=i.length>1?i[1]:"0";n+=a.padEnd(e.decimals,"0")}return n}function Ii(e,t,r){var n="";return t.forEach((i,a)=>{var o=Vt(e,i),u=r[a],d=o.type;switch(d){case"string":var f=Z(o.maxLength,"maxLength not set");typeof u=="string"?n+=u.padEnd(f," "):n+="".padEnd(f," ");break;case"boolean":if(u===null)n+="0";else if(u===It)n+="0";else if(u===Pt)n+="1";else{var m=u?"1":"0";n+=m}break;case"number":case"integer":var y=Bc(o);if(u===null||u===It){var g="0";n+=g.repeat(y.nonDecimals+y.decimals)}else if(u===Pt)n+=es(y,y.maximum);else{var w=es(y,u);n+=w}break;default:throw new Error("unknown index type "+d)}}),n}function Ss(e,t,r){var n="";return t.forEach((i,a)=>{var o=Vt(e,i),u=r[a],d=o.type;switch(d){case"string":var f=Z(o.maxLength,"maxLength not set");typeof u=="string"&&u!==Pt?n+=u.padEnd(f," "):u===It?n+="".padEnd(f," "):n+="".padEnd(f,Pt);break;case"boolean":if(u===null)n+="1";else{var m=u?"1":"0";n+=m}break;case"number":case"integer":var y=Bc(o);if(u===null||u===Pt){var g="9";n+=g.repeat(y.nonDecimals+y.decimals)}else if(u===It){var w="0";n+=w.repeat(y.nonDecimals+y.decimals)}else n+=es(y,u);break;default:throw new Error("unknown index type "+d)}}),n}var uf=new WeakMap,$S=new WeakMap;function _l(e){return it($S,e,()=>af(e))}function qS(){var e=sf(this.storage.name,this.token,this.name,this),t=this.close.bind(this);this.close=function(){return Xo(this.token,this),t()};var r=_l(e);return r||(r=_l(e),uf.set(this,r)),this.leaderElector=()=>r,r}function HS(){return this.multiInstance?this.leaderElector().isLeader:!0}function JS(){return this.multiInstance?this.leaderElector().awaitLeadership().then(()=>!0):xn}function jS(e){var t=uf.get(e);t&&t.die()}var zS=!0,GS={RxDatabase:e=>{e.leaderElector=qS,e.isLeader=HS,e.waitForLeadership=JS}},lf={name:"leader-election",rxdb:zS,prototypes:GS,hooks:{preCloseRxDatabase:{after:jS}}},Pl=e=>Promise.resolve(e);function Il(e,t){if(e==="_deleted")return t;t=Oe(t);var r=!!t._deleted;return t[e]=r,delete t._deleted,t}function Po(e,t,r){return r.map(n=>{var i=Oe(n);if(t!=="_deleted"){var a=!!i[t];i._deleted=a,delete i[t]}else i._deleted=!!i._deleted;var o=e.schema.primaryPath;return i[o]=br(e.schema.jsonSchema,i),i})}function Cl(e,t){if(typeof window>"u"||typeof window!="object"||typeof window.addEventListener>"u"||navigator.onLine)return e.promiseWait(t);var r,n=new Promise(i=>{r=()=>{window.removeEventListener("online",r),i()},window.addEventListener("online",r)});return Promise.race([n,e.promiseWait(t)]).then(()=>{window.removeEventListener("online",r)})}function VS(e){function t(){if(!(typeof document>"u"||typeof document.dispatchEvent!="function")){var n=new Event("mousemove");document.dispatchEvent(n)}}var r=setInterval(t,20*1e3);e.onCancel.push(()=>clearInterval(r))}var Fc=new WeakMap,YS=(function(){function e(r,n,i,a,o,u,d,f,m){this.subs=[],this.subjects={received:new He,sent:new He,error:new He,canceled:new Kt(!1),active:new Kt(!1)},this.received$=this.subjects.received.asObservable(),this.sent$=this.subjects.sent.asObservable(),this.error$=this.subjects.error.asObservable(),this.canceled$=this.subjects.canceled.asObservable(),this.active$=this.subjects.active.asObservable(),this.wasStarted=!1,this.startQueue=nt,this.onCancel=[],this.callOnStart=void 0,this.remoteEvents$=new He,this.replicationIdentifier=r,this.collection=n,this.deletedField=i,this.pull=a,this.push=o,this.live=u,this.retryTime=d,this.autoStart=f,this.toggleOnDocumentVisible=m,this.metaInfoPromise=(async()=>{var w="rx-replication-meta-"+await n.database.hashFunction([this.collection.name,this.replicationIdentifier].join("-")),S=Vo(this.collection.schema.jsonSchema,za(this.collection.schema.jsonSchema));return{collectionName:w,schema:S}})();var y=it(Fc,n,()=>[]);y.push(this),this.collection.onClose.push(()=>
22this.cancel()),Object.keys(this.subjects).forEach(w=>{Object.defineProperty(this,w+"$",{get:function(){return this.subjects[w].asObservable()}})});var g=new Promise(w=>{this.callOnStart=w});this.startPromise=g}var t=e.prototype;return t.start=function(){return this.startQueue=this.startQueue.then(()=>this._start()),this.startQueue},t._start=async function(){if(!this.isStopped()){if(this.internalReplicationState&&this.internalReplicationState.events.paused.next(!1),this.wasStarted){this.reSync();return}this.wasStarted=!0,this.toggleOnDocumentVisible||VS(this);var n=this.pull&&this.pull.modifier?this.pull.modifier:Pl,i=this.push&&this.push.modifier?this.push.modifier:Pl,a=this.collection.database,o=await this.metaInfoPromise,[u]=await Promise.all([this.collection.database.storage.createStorageInstance({databaseName:a.name,collectionName:o.collectionName,databaseInstanceToken:a.token,multiInstance:a.multiInstance,options:{},schema:o.schema,password:a.password,devMode:xe.isDevMode()}),Oh(this.collection,o.collectionName,o.schema)]);this.metaInstance=u,this.internalReplicationState=qh({pushBatchSize:this.push&&this.push.batchSize?this.push.batchSize:100,pullBatchSize:this.pull&&this.pull.batchSize?this.pull.batchSize:100,initialCheckpoint:{upstream:this.push?this.push.initialCheckpoint:void 0,downstream:this.pull?this.pull.initialCheckpoint:void 0},forkInstance:this.collection.storageInstance,metaInstance:this.metaInstance,hashFunction:a.hashFunction,identifier:"rxdbreplication"+this.replicationIdentifier,conflictHandler:this.collection.conflictHandler,replicationHandler:{masterChangeStream$:this.remoteEvents$.asObservable().pipe(Ce(d=>!!this.pull),Mt(async d=>{if(d==="RESYNC")return d;var f=Oe(d);return f.documents=Po(this.collection,this.deletedField,f.documents),f.documents=await Promise.all(f.documents.map(m=>n(m))),f})),masterChangesSince:async(d,f)=>{if(!this.pull)return{checkpoint:null,documents:[]};for(var m=!1,y={};!m&&!this.isStoppedOrPaused();)try{y=await this.pull.handler(d,f),m=!0}catch(S){var g=ee("RC_PULL",{checkpoint:d,errors:bn(S).map(E=>Mo(E)),direction:"pull"});this.subjects.error.next(g),await Cl(this.collection,Z(this.retryTime))}if(this.isStoppedOrPaused())return{checkpoint:null,documents:[]};var w=Oe(y);return w.documents=Po(this.collection,this.deletedField,w.documents),w.documents=await Promise.all(w.documents.map(S=>n(S))),w},masterWrite:async d=>{if(!this.push)return[];var f=!1;await Gt("preReplicationMasterWrite",{rows:d,collection:this.collection});var m=await Promise.all(d.map(async E=>(E.newDocumentState=await i(E.newDocumentState),E.newDocumentState===null?null:(E.assumedMasterState&&(E.assumedMasterState=await i(E.assumedMasterState)),this.deletedField!=="_deleted"&&(E.newDocumentState=Il(this.deletedField,E.newDocumentState),E.assumedMasterState&&(E.assumedMasterState=Il(this.deletedField,E.assumedMasterState))),E)))),y=m.filter(ry),g=null;for(y.length===0&&(f=!0,g=[]);!f&&!this.isStoppedOrPaused();)try{if(g=await this.push.handler(y),!Array.isArray(g))throw ee("RC_PUSH_NO_AR",{pushRows:d,direction:"push",args:{result:g}});f=!0}catch(E){var w=E.rxdb?E:ee("RC_PUSH",{pushRows:d,errors:bn(E).map(D=>Mo(D)),direction:"push"});this.subjects.error.next(w),await Cl(this.collection,Z(this.retryTime))}if(this.isStoppedOrPaused())return[];await Gt("preReplicationMasterWriteDocumentsHandle",{result:g,collection:this.collection});var S=Po(this.collection,this.deletedField,Z(g));return S}}}),this.subs.push(this.internalReplicationState.events.error.subscribe(d=>{this.subjects.error.next(d)}),this.internalReplicationState.events.processed.down.subscribe(d=>this.subjects.received.next(d.document)),this.internalReplicationState.events.processed.up.subscribe(d=>{this.subjects.sent.next(d.newDocumentState)}),Qd([this.internalReplicationState.events.active.down,this.internalReplicationState.events.active.up]).subscribe(([d,f])=>{var m=d||f;this.subjects.active.next(m)})),this.pull&&this.pull.stream$&&this.live&&this.subs.push(this.pull.stream$.subscribe({next:d=>{this.isStoppedOrPaused()||this.remoteEvents$.next(d)},error:d=>
22{this.subjects.error.next(d)}})),this.live||(await Ka(this.internalReplicationState),await Qo(this.internalReplicationState),await this._cancel()),this.callOnStart()}},t.pause=function(){return this.startQueue=this.startQueue.then(()=>{Z(this.internalReplicationState).events.paused.next(!0)}),this.startQueue},t.isPaused=function(){return!!(this.internalReplicationState&&this.internalReplicationState.events.paused.getValue())},t.isStopped=function(){return!!this.subjects.canceled.getValue()},t.isStoppedOrPaused=function(){return this.isPaused()||this.isStopped()},t.awaitInitialReplication=async function(){return await this.startPromise,Ka(Z(this.internalReplicationState))},t.awaitInSync=async function(){await this.startPromise,await Ka(Z(this.internalReplicationState));for(var n=2;n>0;)n--,await this.collection.database.requestIdlePromise(),await Qo(Z(this.internalReplicationState));return!0},t.reSync=function(){this.remoteEvents$.next("RESYNC")},t.emitEvent=function(n){this.remoteEvents$.next(n)},t.cancel=async function(){this.startQueue=this.startQueue.catch(()=>{}).then(async()=>{await this._cancel()}),await this.startQueue},t._cancel=async function(n=!1){if(this.isStopped())return Rt;var i=this.onCancel.map(a=>Pd(a()));return this.internalReplicationState&&await Hh(this.internalReplicationState),this.metaInstance&&!n&&i.push(Z(this.internalReplicationState).checkpointQueue.then(()=>Z(this.metaInstance).close())),this.subs.forEach(a=>a.unsubscribe()),this.subjects.canceled.next(!0),this.subjects.active.complete(),this.subjects.canceled.complete(),this.subjects.error.complete(),this.subjects.received.complete(),this.subjects.sent.complete(),Promise.all(i)},t.remove=async function(){return this.startQueue=this.startQueue.then(async()=>{var n=await this.metaInfoPromise;await this._cancel(!0),await Z(this.internalReplicationState).checkpointQueue.then(()=>Z(this.metaInstance).remove()),await cb(this.collection,n.collectionName,n.schema)}),this.startQueue},e})();function QS({replicationIdentifier:e,collection:t,deletedField:r="_deleted",pull:n,push:i,live:a=!0,retryTime:o=1e3*5,waitForLeadership:u=!0,autoStart:d=!0,toggleOnDocumentVisible:f=!1}){if(hn(lf),!n&&!i)throw ee("UT3",{collection:t.name,args:{replicationIdentifier:e}});var m=new YS(e,t,r,n,i,a,o,d,f);if(f&&typeof document<"u"&&typeof document.addEventListener=="function"&&typeof document.visibilityState=="string"){var y=()=>{if(!m.isStopped()){var g=document.visibilityState==="visible";g?m.start():t.database.isLeader()||m.pause()}};document.addEventListener("visibilitychange",y),m.onCancel.push(()=>document.removeEventListener("visibilitychange",y))}return XS(u,m),m}function XS(e,t){var r=e&&t.collection.database.multiInstance,n=r?t.collection.database.waitForLeadership():xn;return n.then(()=>{t.isStopped()||t.autoStart&&t.start()})}const ZS={Free:"FREE",Pro:"PRO"};function kl(e){return eE(e)}function eE(e,t){return e}function Rl(e){return tE(e)}function tE(e,t){return e}function rE(e){return nE(e)}function nE(e,t){return e==null?e:{status:e.status==null?void 0:e.status,purchasePriceUsdcCent:e.purchasePriceUsdcCent,period:Rl(e.period),periodAfterCurrentTerm:e.periodAfterCurrentTerm==null?void 0:Rl(e.periodAfterCurrentTerm),createdAt:new Date(e.createdAt),currentTermStart:new Date(e.currentTermStart),currentTermEnd:e.currentTermEnd==null?void 0:new Date(e.currentTermEnd),trialEnd:e.trialEnd==null?void 0:new Date(e.trialEnd)}}function iE(e){return e==null?e:{status:e.status,purchasePriceUsdcCent:e.purchasePriceUsdcCent,period:e.period,periodAfterCurrentTerm:e.periodAfterCurrentTerm,createdAt:e.createdAt.toISOString(),currentTermStart:e.currentTermStart.toISOString(),currentTermEnd:e.currentTermEnd==null?void 0:e.currentTermEnd.toISOString(),trialEnd:e.trialEnd==null?void 0:e.trialEnd.toISOString()}}function aE(e){return sE(e)}function sE(e,t){return e==null?e:{subscription:rE(e.subscription),tier:kl(e.tier),tierAfterCurrentTerm:kl(e.tierAfterCurrentTerm),discountedByLimeWireOriginal:e.discountedByLimeWireOriginal,discountedByLimeWireOriginalAfterCurrentTerm:e.discountedByLimeWireOriginalAfterCurrentTerm,nextCreditsForYearlySubscription:e.nextCreditsForYearlySubscription==null?void 0:new Date(e.nextCreditsForYearlySubscription),nextCreditsForTrialingSubscription:e.nextCreditsForTrialingSubscription==null?void 0:new Date(e.nextCreditsForTrialingSubscription),nextCreditsForBasicLmwoSubscription:e.nextCreditsForBasicLmwoSubscription==null?void 0:new Date(e.nextCreditsForBasicLmwoSubscription)}}function oE(e){return e==null?e:{subscription:iE(e.subscription),tier:e.tier,tierAfterCurrentTerm:e.tierAfterCurrentTerm,discountedByLimeWireOriginal:e.discountedByLimeWireOriginal,discountedByLimeWireOriginalAfterCurrentTerm:e.discountedByLimeWireOriginalAfterCurrentTerm,nextCreditsForYearlySubscription:e.nextCreditsForYearlySubscription==null?void 0:e.nextCreditsForYearlySubscription.toISOString(),nextCreditsForTrialingSubscription:e.nextCreditsForTrialingSubscription==null?void 0:e.nextCreditsForTrialingSubscription.toISOString(),nextCreditsForBasicLmwoSubscription:e.nextCreditsForBasicLmwoSubscription==null?void 0:e.nextCreditsForBasicLmwoSubscription.toISOString()}}const SC={FileEncryptionKey:"FILE_ENCRYPTION_KEY"};function cE(e){return uE(e)}function uE(e,t){return e==null?e:{encryptedPrivateKey:e.encryptedPrivateKey,encryptedByKeyType:e.encryptedByKeyType,encryptedByKeyId:e.encryptedByKeyId}}function df(e){return e==null?e:{encryptedPrivateKey:e.encryptedPrivateKey,encryptedByKeyType:e.encryptedByKeyType,encryptedByKeyId:e.encryptedByKeyId}}function lE(e){return e==null?e:{solvedNonce:e.solvedNonce,nonceEncryptionIv:e.nonceEncryptionIv,wrappedFileSharingKey:df(e.wrappedFileSharingKey)}}function hf(e){return dE(e)}function dE(e,t){return e==null?e:{lmwr:e.lmwr,credits:e.credits}}function ff(e){return e==null?e:{lmwr:e.lmwr,credits:e.credits}}const EC={Viewer:"VIEWER"};function hE(e){return fE(e)}function fE(e,t){return e}const _C={Shared:"SHARED",NotShared:"NOT_SHARED"};function pE(e){return mE(e)}function mE(e,t){return e}function yE(e){return vE(e)}function vE(e,t){return e==null?e:{type:e.type,wrappedKeyWrappingKey:e.wrappedKeyWrappingKey,wrappedAsymmetricPrivateKey:e.wrappedAsymmetricPrivateKey,keyWrappingKeyPassphraseSalt:e.keyWrappingKeyPassphraseSalt==null?void 0:e.keyWrappingKeyPassphraseSalt,asymmetricKeyPassphraseSalt:e.asymmetricKeyPassphraseSalt==null?void 0:e.asymmetricKeyPassphraseSalt,wrappedByKeyId:e.wrappedByKeyId==null?void 0:e.wrappedByKeyId}}function gE(e){return e==null?e:{type:e.type,wrappedKeyWrappingKey:e.wrappedKeyWrappingKey,wrappedAsymmetricPrivateKey:e.wrappedAsymmetricPrivateKey,keyWrappingKeyPassphraseSalt:e.keyWrappingKeyPassphraseSalt,asymmetricKeyPassphraseSalt:e.asymmetricKeyPassphraseSalt,wrappedByKeyId:e.wrappedByKeyId}}function Gr(e){return wE(e)}
22function wE(e,t){return e==null?e:{time:e.time,increment:e.increment}}function An(e){return e==null?e:{time:e.time,increment:e.increment}}function pf(e){return bE(e)}function bE(e,t){return e==null?e:{id:e.id,publicKey:e.publicKey,privateKeys:e.privateKeys.map(yE),deleted:e.deleted,createdDate:new Date(e.createdDate),lastModifiedTimestamp:e.lastModifiedTimestamp==null?void 0:Gr(e.lastModifiedTimestamp)}}function Rn(e){return e==null?e:{id:e.id,publicKey:e.publicKey,privateKeys:e.privateKeys.map(gE),deleted:e.deleted,createdDate:e.createdDate.toISOString(),lastModifiedTimestamp:An(e.lastModifiedTimestamp)}}function SE(e){return e==null?e:{userEncryptionKey:Rn(e.userEncryptionKey)}}function EE(e){return _E(e)}function _E(e,t){return e==null?e:{amountBucketsClaimed:e.amountBucketsClaimed}}function PE(e){return e==null?e:{claimToken:e.claimToken,userEncryptionKey:Rn(e.userEncryptionKey)}}function IE(e){return CE(e)}function CE(e,t){return e==null?e:{amountBucketsClaimed:e.amountBucketsClaimed}}const PC={Uploaded:"UPLOADED"};function kE(e){return RE(e)}function RE(e,t){return e}function DE(e){return xE(e)}function xE(e,t){return e}function OE(e){return TE(e)}function TE(e,t){return e==null?e:{id:e.id,mediaType:e.mediaType,type:DE(e.type)}}function KE(e){return e==null?e:{id:e.id,mediaType:e.mediaType,type:e.type}}const IC={Explicit:"EXPLICIT"};function AE(e){return NE(e)}function NE(e,t){return e}function ME(e){return BE(e)}function BE(e,t){return e}function mf(e){return FE(e)}function FE(e,t){return e==null?e:{id:e.id,originalSharingBucketId:e.originalSharingBucketId,s3Status:kE(e.s3Status),itemType:ME(e.itemType),mediaType:e.mediaType,size:e.size,nameEncrypted:e.nameEncrypted==null?void 0:e.nameEncrypted,sha1Encrypted:e.sha1Encrypted==null?void 0:e.sha1Encrypted,baseFileEncryptionKeyId:e.baseFileEncryptionKeyId,ephemeralPublicKey:e.ephemeralPublicKey,metadata:e.metadata==null?void 0:e.metadata,previews:e.previews==null?void 0:e.previews.map(OE),nsfw:e.nsfw==null?void 0:AE(e.nsfw),createdDate:new Date(e.createdDate),lastModifiedTimestamp:e.lastModifiedTimestamp==null?void 0:Gr(e.lastModifiedTimestamp),deleted:e.deleted}}function LE(e){return e==null?e:{id:e.id,originalSharingBucketId:e.originalSharingBucketId,s3Status:e.s3Status,itemType:e.itemType,mediaType:e.mediaType,size:e.size,nameEncrypted:e.nameEncrypted,sha1Encrypted:e.sha1Encrypted,baseFileEncryptionKeyId:e.baseFileEncryptionKeyId,ephemeralPublicKey:e.ephemeralPublicKey,metadata:e.metadata,previews:e.previews==null?void 0:e.previews.map(KE),nsfw:e.nsfw,createdDate:e.createdDate.toISOString(),lastModifiedTimestamp:An(e.lastModifiedTimestamp),deleted:e.deleted}}function UE(e){return e==null?e:{id:e.id,metadataId:e.metadataId}}function WE(e){return $E(e)}function $E(e,t){return e==null?e:{id:e.id,metadataId:e.metadataId==null?void 0:e.metadataId,downloadUrl:e.downloadUrl}}function Lc(e){return qE(e)}function qE(e,t){return e==null?e:{id:e.id,ownerId:e.ownerId==null?void 0:e.ownerId,clientDeviceId:e.clientDeviceId==null?void 0:e.clientDeviceId,ownerNick:e.ownerNick==null?void 0:e.ownerNick,sharingStatus:pE(e.sharingStatus),sharingPermission:hE(e.sharingPermission),sharingId:e.sharingId==null?void 0:e.sharingId,primaryEncryptionKeyId:e.primaryEncryptionKeyId,contentItemIds:e.contentItemIds,totalFileSize:e.totalFileSize==null?void 0:e.totalFileSize,name:e.name,createdDate:new Date(e.createdDate),lastModifiedTimestamp:e.lastModifiedTimestamp==null?void 0:Gr(e.lastModifiedTimestamp),deleted:e.deleted,expiresAt:e.expiresAt==null?null:new Date(e.expiresAt),downloadCounter:e.downloadCounter==null?void 0:e.downloadCounter,publicDownloadCounter:e.publicDownloadCounter==null?void 0:e.publicDownloadCounter,pinned:e.pinned}}function HE(e){return e==null?e:{id:e.id,ownerId:e.ownerId,clientDeviceId:e.clientDeviceId,ownerNick:e.ownerNick,sharingStatus:e.sharingStatus,sharingPermission:e.sharingPermission,sharingId:e.sharingId,primaryEncryptionKeyId:e.primaryEncryptionKeyId,contentItemIds:e.contentItemIds,totalFileSize:e.totalFileSize,name:e.name,createdDate:e.createdDate.toISOString(),lastModifiedTimestamp:An(e.lastModifiedTimestamp),deleted:e.deleted,expiresAt:e.expiresAt==null?null:e.expiresAt.toISOString(),downloadCounter:e.downloadCounter,publicDownloadCounter:e.publicDownloadCounter,pinned:e.pinned}}function Uc(e){return JE(e)}function JE(e,t){return e==null?e:{id:e.id,publicKey:e.publicKey,privateKeys:e.privateKeys.map(cE),encryptedPassphrase:e.encryptedPassphrase==null?void 0:e.encryptedPassphrase,passphraseWrappedPrivateKey:e.passphraseWrappedPrivateKey==null?void 0:e.passphraseWrappedPrivateKey,deleted:e.deleted,createdDate:new Date(e.createdDate),lastModifiedTimestamp:e.lastModifiedTimestamp==null?void 0:Gr(e.lastModifiedTimestamp)}}function jE(e){return e==null?e:{id:e.id,publicKey:e.publicKey,privateKeys:e.privateKeys.map(df),encryptedPassphrase:e.encryptedPassphrase,passphraseWrappedPrivateKey:e.passphraseWrappedPrivateKey,deleted:e.deleted,createdDate:e.createdDate.toISOString(),lastModifiedTimestamp:An(e.lastModifiedTimestamp)}}function zE(e){return e==null?e:{passphrase:e.passphrase,primaryUserEncryptionKey:Rn(e.primaryUserEncryptionKey)}}function GE(e){return VE(e)}function VE(e,t){return e==null?e:{contentItems:e.contentItems.map(WE)}}function YE(e){return e==null?e:{oldUserEncryptionKey:Rn(e.oldUserEncryptionKey),newUserEncryptionKey:Rn(e.newUserEncryptionKey)}}function QE(e){return e==null?e:{sharingPermission:e.sharingPermission,encryptedPassphrase:e.encryptedPassphrase,passphraseWrappedPrivateKey:e.passphraseWrappedPrivateKey}}function XE(e){return ZE(e)}function ZE(e,t){return e==null?e:{sharingBucket:Lc(e.sharingBucket),fileEncryptionKey:Uc(e.f
22ileEncryptionKey)}}function e_(e){return t_(e)}function t_(e,t){return e==null?e:{contentItemId:e.contentItemId,errorCode:e.errorCode}}function r_(e){return e==null?e:{contentItemId:e.contentItemId,errorCode:e.errorCode}}function n_(e){return e==null?e:{contentItems:e.contentItems.map(UE)}}function i_(e){return a_(e)}function a_(e,t){return e==null?e:{ephemeralPublicKey:e.ephemeralPublicKey,nonce:e.nonce}}function Dl(e){return s_(e)}function s_(e,t){return e==null?e:{sharingBucket:Lc(e.sharingBucket),contentItemList:e.contentItemList.map(mf),fileEncryptionKeys:e.fileEncryptionKeys.map(Uc),displayAds:e.displayAds}}function o_(e){return c_(e)}function c_(e,t){return e==null?e:{id:e.id,status:e.status,platformActionId:e.platformActionId,cost:hf(e.cost),sharingBucketId:e.sharingBucketId,succeededContentItemIds:e.succeededContentItemIds,failedContentItemInfo:e.failedContentItemInfo.map(e_),createdDate:new Date(e.createdDate),lastModifiedTimestamp:Gr(e.lastModifiedTimestamp)}}function u_(e){return e==null?e:{id:e.id,status:e.status,platformActionId:e.platformActionId,cost:ff(e.cost),sharingBucketId:e.sharingBucketId,succeededContentItemIds:e.succeededContentItemIds,failedContentItemInfo:e.failedContentItemInfo.map(r_),createdDate:e.createdDate.toISOString(),lastModifiedTimestamp:An(e.lastModifiedTimestamp)}}function l_(e){return d_(e)}function d_(e,t){return e==null?e:{documents:e.documents,checkpoint:Gr(e.checkpoint)}}function h_(e){return e==null?e:{assumedMasterState:e.assumedMasterState,newDocumentState:e.newDocumentState}}function f_(e){return e==null?e:{changedDocuments:e.changedDocuments.map(h_)}}function p_(e){return m_(e)}function m_(e,t){return e==null?e:{conflicts:e.conflicts}}function y_(e){return e==null?e:{sharingPassphrase:e.sharingPassphrase,destinationEmails:e.destinationEmails,recaptchaToken:e.recaptchaToken}}function v_(e){return e==null?e:{clientId:e.clientId,url:e.url}}function g_(e){return w_(e)}function w_(e,t){return e==null?e:{sharingBucketsCount:e.sharingBucketsCount}}function b_(e){return S_(e)}function S_(e,t){return e==null?e:{userEncryptionKey:pf(e.userEncryptionKey)}}function E_(e){return __(e)}function __(e,t){return e}function P_(e){return I_(e)}function I_(e,t){return e==null?e:{id:e.id,email:e.email,nick:e.nick,name:e.name==null?void 0:e.name,description:e.description==null?void 0:e.description,userEncryptionKeyType:e.userEncryptionKeyType,totp2faEnabled:e.totp2faEnabled,balance:hf(e.balance),level:e.level==null?void 0:e.level,accountSubscription:e.accountSubscription==null?void 0:aE(e.accountSubscription),verificationStatus:e.verificationStatus==null?void 0:E_(e.verificationStatus),referralCode:e.referralCode==null?void 0:e.referralCode,kycPassed:e.kycPassed==null?void 0:e.kycPassed,planSelectionShown:e.planSelectionShown==null?void 0:e.planSelectionShown,lastModifiedTimestamp:e.lastModifiedTimestamp==null?void 0:Gr(e.lastModifiedTimestamp)}}function C_(e){return e==null?e:{id:e.id,email:e.email,nick:e.nick,name:e.name,description:e.description,userEncryptionKeyType:e.userEncryptionKeyType,totp2faEnabled:e.totp2faEnabled,balance:ff(e.balance),level:e.level,accountSubscription:oE(e.accountSubscription),verificationStatus:e.verificationStatus,referralCode:e.referralCode,kycPassed:e.kycPassed,planSelectionShown:e.planSelectionShown,lastModifiedTimestamp:An(e.lastModifiedTimestamp)}}class k_ extends sd{async getDownloadUrlsRaw(t,r){if(t.sharingBucketId==null)throw new wt("sharingBucketId",'Required parameter "sharingBucketId" was null or undefined when calling getDownloadUrls().');const n={},i={};if(i["Content-Type"]="application/json",t.xTurnstileToken!=null&&(i["X-Turnstile-Token"]=String(t.xTurnstileToken)),this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/download/{sharingBucketId}".replace("{sharingBucketId}",encodeURIComponent(String(t.sharingBucketId))),method:"POST",headers:i,query:n,body:n_(t.generateDownloadUrlsRequest)},r);return new Et(a,o=>GE(o))}async getDownloadUrls(t,r){return await(await this.getDownloadUrlsRaw(t,r)).value(
22)}async getSharingBucketContentRaw(t,r){if(t.sharingBucketId==null)throw new wt("sharingBucketId",'Required parameter "sharingBucketId" was null or undefined when calling getSharingBucketContent().');const n={},i={};if(this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/bucket/{sharingBucketId}/content".replace("{sharingBucketId}",encodeURIComponent(String(t.sharingBucketId))),method:"GET",headers:i,query:n},r);return new Et(a,o=>Dl(o))}async getSharingBucketContent(t,r){return await(await this.getSharingBucketContentRaw(t,r)).value()}async getSharingBucketContentBySharingIdRaw(t,r){if(t.sharingId==null)throw new wt("sharingId",'Required parameter "sharingId" was null or undefined when calling getSharingBucketContentBySharingId().');const n={},i={};if(this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/bucket/{sharingId}/content-by-sharing-id".replace("{sharingId}",encodeURIComponent(String(t.sharingId))),method:"GET",headers:i,query:n},r);return new Et(a,o=>Dl(o))}async getSharingBucketContentBySharingId(t,r){return await(await this.get
22SharingBucketContentBySharingIdRaw(t,r)).value()}}class yf extends sd{async addSharingBucketRaw(t,r){if(t.sharingBucketId==null)throw new wt("sharingBucketId",'Required parameter "sharingBucketId" was null or undefined when calling addSharingBucket().');const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/add-sharing-bucket/{sharingBucketId}".replace("{sharingBucketId}",encodeURIComponent(String(t.sharingBucketId))),method:"POST",headers:i,query:n,body:lE(t.addSharingBucketRequest)},r);return new nn(a)}async addSharingBucket(t,r){await this.addSharingBucketRaw(t,r)}async claimBucketsRaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/claim-buckets",method:"POST",headers:i,query:n,body:SE(t.claimBucketRequest)},r);return new nn(a)}async claimBuckets(t={},r){await this.claimBucketsRaw(t,r)}async claimBucketsLegacyRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/sharing/claim-buckets-legacy",method:"POST",headers:n,query:r},t);return new Et(i,a=>EE(a))}async claimBucketsLegacy(t){return await(await this.claimBucketsLegacyRaw(t)).value()}async claimCrossDomainContentRaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/claim-buckets-external",method:"POST",headers:i,query:n,body:PE(t.claimCrossDomainContentRequest)},r);return new Et(a,o=>IE(o))}async claimCrossDomainContent(t={},r){return await(await this.claimCrossDomainContentRaw(t,r)).value()}async disableE2ERaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/e2e/disable",method:"POST",headers:i,query:n,body:zE(t.disableE2ERequest)},r);return new nn(a)}async disableE2E(t={},r){await this.disableE2ERaw(t,r)}async enableE2ERaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/e2e/enable",method:"POST",headers:i,query:n,body:YE(t.enableE2ERequest)},r);return new nn(a)}async enableE2E(t={},r){await this.enableE2ERaw(t,r)}async enableSharingForBucketRaw(t,r){if(t.sharingBucketId==null)throw new wt("sharingBucketId",'Required parameter "sharingBucketId" was null or undefined when calling enableSharingForBucket().');const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/bucket/{sharingBucketId}/enable-sharing".replace("{sharingBucketId}",encodeURIComponent(String(t.sharingBucketId))),method:"POST",headers:i,query:n,body:QE(t.enableSharingRequest)},r);return new Et(a,o=>XE(o))}async enableSharingForBucket(t,r){return await(await this.enableSharingForBucketRaw(t,r)).value()}async generateSharingInfoRaw(t,r){if(t.sharingBucketId==null)throw new wt("sharingBucketId",'Required parameter "sharingBucketId" was null or undefined when calling generateSharingInfo().');const n={},i={};if(this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/generate-sharing-info/{sharingBucketId}".replace("{sharingBucketId}",encodeURIComponent(String(t.sharingBucketId))),method:"GET",headers:i,query:n},r);return new Et(a,o=>i_(o))}async generateSharingInfo(t,r){return await(await this.generateSharingInfoRaw(t,r)).value(
22)}async getOrCreateUserEncryptionKeyRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/sharing/user-encryption-key",method:"POST",headers:n,query:r},t);return new Et(i,a=>b_(a))}async getOrCreateUserEncryptionKey(t){return await(await this.getOrCreateUserEncryptionKeyRaw(t)).value()}async getSharingInfoMetadataRaw(t){const r={},n={};if(this.configuration&&this.configuration.accessToken){const a=this.configuration.accessToken,o=await a("jwt",[]);o&&(n.Authorization=`Bearer ${o}`)}const i=await this.request({path:"/sharing/sharing-info",method:"GET",headers:n,query:r},t);return new Et(i,a=>g_(a))}async getSharingInfoMetadata(t){return await(await this.getSharingInfoMetadataRaw(t)).value()}async pullCollectionChangesRaw(t,r){if(t.replicatedCollectionName==null)throw new wt("replicatedCollectionName",'Required parameter "replicatedCollectionName" was null or undefined when calling pullCollectionChanges().');if(t.timestampSeconds==null)throw new wt("timestampSeconds",'Required parameter "timestampSeconds" was null or undefined when calling pullCollectionChanges().');if(t.timestampIncrement==null)throw new wt("timestampIncrement",'Required parameter "timestampIncrement" was null or undefined when calling pullCollectionChanges().');if(t.limit==null)throw new wt("limit",'Required parameter "limit" was null or undefined when calling pullCollectionChanges().');const n={};t.timestampSeconds!=null&&(n.timestampSeconds=t.timestampSeconds),t.timestampIncrement!=null&&(n.timestampIncrement=t.timestampIncrement),t.limit!=null&&(n.limit=t.limit),t.clientDeviceId!=null&&(n.clientDeviceId=t.clientDeviceId),t.userId!=null&&(n.userId=t.userId);const i={};if(this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/replication/{replicatedCollectionName}/pull".replace("{replicatedCollectionName}",encodeURIComponent(String(t.replicatedCollectionName))),method:"GET",headers:i,query:n},r);return new Et(a,o=>l_(o))}async pullCollectionChanges(t,r){return await(await this.pullCollectionChangesRaw(t,r)).value()}async pushCollectionChangesRaw(t,r){if(t.replicatedCollectionName==null)throw new wt("replicatedCollectionName",'Required parameter "replicatedCollectionName" was null or undefined when calling pushCollectionChanges().');const n={};t.clientDeviceId!=null&&(n.clientDeviceId=t.clientDeviceId),t.userId!=null&&(n.userId=t.userId);const i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/replication/{replicatedCollectionName}/push".replace("{replicatedCollectionName}",encodeURIComponent(String(t.replicatedCollectionName))),method:"POST",headers:i,query:n,body:f_(t.pushRequest)},r);return new Et(a,o=>p_(o))}async pushCollectionChanges(t,r){return await(await this.pushCollectionChangesRaw(t,r)).value()}async sendShareBucketEmailRaw(t,r){if(t.sharingBucketId==null)throw new wt("sharingBucketId",'Required parameter "sharingBucketId" was null or undefined when calling sendShareBucketEmail().');const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/send-share-bucket-email/{sharingBucketId}".replace("{sharingBucketId}",encodeURIComponent(String(t.sharingBucketId))),method:"POST",headers:i,query:n,body:y_(t.shareBucket
22EmailRequest)},r);return new nn(a)}async sendShareBucketEmail(t,r){await this.sendShareBucketEmailRaw(t,r)}async shareBucketWithClientRaw(t,r){const n={},i={};if(i["Content-Type"]="application/json",this.configuration&&this.configuration.accessToken){const o=this.configuration.accessToken,u=await o("jwt",[]);u&&(i.Authorization=`Bearer ${u}`)}const a=await this.request({path:"/sharing/share-bucket-with-client",method:"POST",headers:i,query:n,body:v_(t.shareBucketWithClientRequest)},r);return new nn(a)}async shareBucketWithClient(t={},r){await this.shareBucketWithClientRaw(t,r)}}const sn={SharingBucket:"SHARING_BUCKET",ContentItem:"CONTENT_ITEM",UserEncryptionKey:"USER_ENCRYPTION_KEY",FileEncryptionKey:"FILE_ENCRYPTION_KEY",User:"USER",PlatformActionHistory:"PLATFORM_ACTION_HISTORY"},R_={type:"object",description:`Represents a content item. 23Some fields are read-only by the client and managed by the server (createdDate, lastModifiedTimestamp). 24`,title:"ContentItem",properties:{id:{type:"string",description:"Unique identifier for the document"},originalSharingBucketId:{type:"string",description:"Original sharing bucket id"},s3Status:{type:"string",enum:["PENDING","IN_PROGRESS","UPLOADED","DELETED"]},itemType:{type:"string",enum:["IMAGE","AUDIO","VIDEO","DOCUMENT","OTHER"]},mediaType:{type:"string",description:"Media type of the content"},size:{type:"number",description:"Size of the content in bytes",format:"int64"},nameEncrypted:{type:"string",description:"AES-GCM base64 representation of the encrypted name of the ContentItem, encrypted by file encryption key (see docs for baseFileEncryptionKeyId)"},sha1Encrypted:{type:"string",description:"AES-GCM base64 representation of the encrypted SHA1 of the content, encrypted by file encryption key (see docs for baseFileEncryptionKeyId)"},baseFileEncryptionKeyId:{type:"string",description:`Base file encryption key id which after derivation will be used to encrypt the content. 25Derivation function deterministicaly derives a new encryption key from the base key and the id of the content item. 26`},ephemeralPublicKey:{type:"string",description:`Base64 representation of the public key of the ephemeral key that was used for deriving the encryption key 27`},metadata:{type:"object",additionalProperties:{type:"object"},description:"Metadata of the content"},previews:{type:"array",items:{type:"object",description:"Represents a preview for a content item.",title:"PreviewItem",properties:{id:{type:"string",description:"Unique identifier for the preview"},mediaType:{type:"string",description:"Media type of the content"},type:{type:"string",enum:["IMAGE","WAVEFORM_JSON"]}},required:["id","type","mediaType"]}},nsfw:{type:"string",enum:["NONE","EXPLICIT"]},createdDate:{type:"string",description:"Date when the document was created",format:"date-time"},lastModifiedTimestamp:{type:"object",description:"Represents a timestamp with a second and increment",title:"Timestamp",properties:{time:{type:"number",description:"Seconds since the Unix epoch"},increment:{type:"number",description:"For operations within a given second."}},required:["time","increment"]},deleted:{type:"boolean",description:"True if the document is deleted (client managed)"}},required:["id","originalSharingBucketId","s3Status","itemType","mediaType","size","baseFileEncryptionKeyId","ephemeralPublicKey","deleted","createdDate"]},D_={type:"object",description:`Represents a file encryption key. 28Some fields are read-only by the client and managed by the server (createdDate, lastModifiedTimestamp). 29`,title:"FileEncryptionKeyRequest",properties:{id:{type:"string",description:"Unique identifier for the document (client managed)"},publicKey:{type:"string",description:"String representation of the raw public key in Base64"},privateKeys:{type:"array",items:{type:"object",title:"PrivateKeyRepresentation",properties:{encryptedPrivateKey:{type:"string",description:'Base64 representation of the AES-KW wrapped private part of the ECDH key ("d" parameter in jwk format)'},encryptedByKeyType:{type:"string"},encryptedByKeyId:{type:"string",description:"Id of the key that was used to encrypt the private-key."}},required:["encryptedPrivateKey","encryptedByKeyType","encryptedByKeyId"]}},encryptedPassphrase:{type:"string",description:"Encrypted passphrase for sharing the sharing bucket"},passphraseWrappedPrivateKey:{type:"string",description:"Passphrase wrapped private key"},deleted:{type:"boolean",description:"True if the document is deleted"},createdDate:{type:"string",description:"Date when the document was created",format:"date-time"},lastModifiedTimestamp:{type:"object",description:"Represents a timestamp with a second and increment",title:"Timestamp",properties:{time:{type:"number",description:"Seconds since the Unix epoch"},increment:{type:"number",description:"For operations within a given second."}},required:["time","increment"]}},required:["id","publicKey","privateKeys","deleted","createdDate"]}
29,x_={type:"object",description:`Represents a bucket that contains a list of content items. 30Some fields are read-only by the client and managed by the server (ownerId, createdDate, lastModifiedTimestamp). 31`,title:"SharingBucket",properties:{id:{type:"string",description:"Unique identifier for the document"},ownerId:{type:"string",description:"User id of the owner (client RO). Can be null in case the bucket was created by an anonymous user"},clientDeviceId:{type:"string",description:"id of the ClientDevice that created this SharingBucket"},ownerNick:{type:"string",description:'Nick of the owner of the bucket (client RO). In case of anonymous users this will be set to "anonymous"'},sharingStatus:{type:"string",enum:["SHARED","NOT_SHARED"]},sharingPermission:{type:"string",enum:["VIEWER","EDITOR"]},sharingId:{type:"string",description:"Sharing id of the bucket (client RO)"},primaryEncryptionKeyId:{type:"string",description:"Primary encryption key id"},contentItemIds:{type:"array",description:"List of content item ids",items:{type:"string"}},totalFileSize:{type:"number",description:"Total size of all files in bytes (Client RO)",format:"int64"},name:{type:"string",description:"Name of the bucket"},createdDate:{type:"string",description:"Date when the document was created",format:"date-time"},lastModifiedTimestamp:{type:"object",description:"Represents a timestamp with a second and increment",title:"Timestamp",properties:{time:{type:"number",description:"Seconds since the Unix epoch"},increment:{type:"number",description:"For operations within a given second."}},required:["time","increment"]},deleted:{type:"boolean",description:"True if the document is deleted (client managed)"},expiresAt:{type:["string","null"],description:`Date when this bucket will expire (client managed). Max value depends on user subscription plan. 32If null, the bucket will never expire (allowed only on some plans) 33`,format:"date-time"},downloadCounter:{type:"number",description:"Counter on how often some ContentItem has been downloaded from this SharingBucket (client RO)"},publicDownloadCounter:{type:"number",description:"Counter on how often some ContentItem has been downloaded from this SharingBucket by users other than the owner (client RO)"},pinned:{type:"boolean",description:"Pinned bucket are shown on top of the list and do not expire"}},required:["id","sharingStatus","sharingPermission","primaryEncryptionKeyId","contentItemIds","name","deleted","pinned","createdDate","expiresAt"]},O_={type:"object",description:`Represents a user's encryption key. 34Some fields are read-only by the client and managed by the server (createdDate, lastModifiedTimestamp). 35`,title:"UserEncryptionKey",properties:{id:{type:"string",description:"Unique identifier for the document (client managed)"},publicKey:{type:"string",description:"String representation of the public key in Base64 encoding"},privateKeys:{type:"array",items:{type:"object",title:"UserPrivateKeyRepresentation",properties:{type:{type:"string"},wrappedKeyWrappingKey:{type:"string",description:"Base64 representation of the encrypted version of the symmetric private key"},wrappedAsymmetricPrivateKey:{type:"string",description:'Base64 representation of the AES-KW wrapped private part of the ECDH key ("d" parameter in jwk format)'},keyWrappingKeyPassphraseSalt:{type:"string",description:"PASSPHRASE_WRAPPED - Base64 representation of the salt that was used to generate the PBKDF key"},asymmetricKeyPassphraseSalt:{type:"string",description:"PASSPHRASE_WRAPPED - Base64 representation of the salt that was used to generate the PBKDF key"},wrappedByKeyId:{type:"string",description:"KEY_WRAPPED - Id of the key that was used to encrypt the private-key."}},required:["type","wrappedKeyWrappingKey","wrappedAsymmetricPrivateKey"]}},deleted:{type:"boolean",description:"True if the document is deleted"},createdDate:{type:"string",description:"Date when the document was created",format:"date-time"},lastModifiedTimestamp:{type:"object",description:"Represents a timestamp with a second and increment",title:"Timestamp",properties:{time:{type:"number",description:"Seconds since the Unix epoch"},increment:{type:"number",description:"For operations within a given second."}},required:["time","increment"]}},required:["id","publicKey","privateKeys","deleted","createdDate"]},T_={type:"object",properties:{id:{type:"string"},email:{type:"string",format:"email"},nick:{type:"string"},name:{type:"string"},description:{type:"string"},userEncryptionKeyType:{type:"string"},totp2faEnabled:{type:"boolean"},balance:{type:"object",title:"BalanceInfo",properties:{lmwr:{type:"number"},credits:{type:"number"}},required:["lmwr","credits"]},level:{type:"string"},accountSubscription:{type:"object",title:"AccountSubscription",properties:{subscription:{type:"object",title:"PlatformSubscription",properties:{status:{type:"string"},purchasePriceUsdcCent:{type:"number",format:"int64"},period:{type:"string",enum:["MONTH","YEAR"]},periodAfterCurrentTerm:{type:"string",enum:["MONTH","YEAR"]},createdAt:{type:"string",format:"date-time"},currentTermStart:{type:"string",format:"date-time"},currentTermEnd:{type:"string",format:"date-time"},trialEnd:{type:"string",format:"date-time"}},required:["purchasePriceUsdcCent","period","createdAt","currentTermStart"]},tier:{type:"string",enum:["FREE","PRO","PRO_PLUS","ADVANCED","LEGACY_PRO","LEGACY_PRO_PLUS","BLUE_WILLOW_SUPPORTER","BLUE_WILLOW_WILLOWER","BLUE_WILLOW_BLUE_ANGEL","BLUE_WILLOW_SAPPHIRE","API_BASIC","API_PRO","API_PRO_PLUS"]},tierAfterCurrentTerm:{type:"string",enum:["FREE","PRO","PRO_PLUS","ADVANCED","LEGACY_PRO","LEGACY_PRO_PLUS","BLUE_WILLOW_SUPPORTER","BLUE_WILLOW_WILLOWER","BLUE_WILLOW_BLUE_ANGEL","BLUE_WILLOW_SAPPHIRE","API_BASIC","API_PRO","API_PRO_PLUS"]},discountedByLimeWireOriginal:{type:"boolean"},discountedByLimeWireOriginalAfterCurrentTerm:{type:"boolean"},nextCreditsForYearlySubscription:{type:"string",format:"date-time"},nextCreditsForTrialingSubscription:{type:"string",format:"date-time"},nextCreditsForBasicLmwoSubscription:{type:"string",format:"date-time"}},required:["subscription","tier","tierAfterCurrentTerm","discountedByLimeWireOriginal","discountedByLimeWireOriginalAfterCurrentTerm"]},verificationStatus:{type:"string",enum:["none","self_verified","staff_verified"]},referralCode:{type:"string"},kycPassed:{type:"boolean"},planSelectionShown:{type:"boolean"},lastModifiedTimestamp:{type:"object",description:"Represents a timestamp with a second and increment",title:"Timestamp",properties:{time:{type:"number",description:"Seconds since the Unix epoch"},increment:{type:"number",description:"For operations within a given second."}},required:["time","increment"]}},required:["id","email","nick","userEncryptionKeyType","totp2faEnabled","balance"]},K_={type:"object",description:`Represents a single platform-action execution. This object will be synced through rx-db from the backend 36to the client to notify it about status updates. All fields are read-only, as this object is only meant to be 37written by the backend. 38`,title:"PlatformActionHistory",properties:{id:{type:"string",description:"Id of the PlatformAction, matches the generationId that is returned when a platform-action is being executed."},status:{type:"string",description:`Current status of the platform action. 39PROCESSING: The action is currently being processed 40FINISHED: The action is finished. Check succeededContentItemIds amd failedContentItemInfo to see if they failed 41`},platformActionId:{type:"string",description:"Identifier of the platform-action itself, which is also part of the URL when an action is exection.\ne.g. `stable-diffusion-xl-10-text-to-image-v1`\n"},cost:{type:"object",title:"BalanceInfo",properties:{lmwr:{type:"number"},credits:{type:"number"}},required:["lmwr","credits"]},sharingBucketId:{type:"string",description:"ID of the sharingBucket this action belongs to"},succeededContentItemIds:{type:"array",description:"contentItemIds that have been successfully processed",items:{type:"string"}},failedContentItemInfo:{type:"array",description:"ContentItemIds where processing failed",items:{type:"object"}},createdDate:{type:"string",description:"Date when the document was created",format:"date-time"},lastModifiedTimestamp:{type:"object",description:"Represents a timestamp with a second and increment",title:"Timestamp",properties:{time:{type:"number",description:"Seconds since the Unix epoch"},increment:{type:"number",description:"For operations within a given second."}},required:["time","increment"]}},required:["id","status","platformActionId","cost","sharingBucketId","succeededContentItemIds","failedContentItemInfo","createdDate","lastModifiedTimestamp"]};var Wc={minimumDeletedTime:1e3*60*60*24*31,minimumCollectionAge:1e3*60,runEach:1e3*60*5,awaitReplicationsInSync:!0,waitForLeadership:!0},Io=xn;async function A_(e){var t=e.database,r=Object.assign({},Wc,t.cleanupPolicy?t.cleanupPolicy:{});await vf(e,r),!e.closed&&(await gf(e,r),await N_(e,r))}async function vf(e,t){await e.promiseWait(t.minimumCollectionAge),!e.closed&&e.database.multiInstance&&t.waitForLeadership&&await e.database.waitForLeadership()}async function gf(e,t){for(var r=e.database,n=e.storageInstance,i=!1;!i&&!e.closed;){if(t.awaitReplicationsInSync){var a=Fc.get(e);a&&await Promise.all(a.map(o=>{if(!o.isStopped())return o.awaitInSync()}))}if(e.closed)return;Io=Io.then(async()=>e.closed?!0:(await r.requestIdlePromise(),n.cleanup(t.minimumDeletedTime))),i=await Io}
41await Gt("postCleanup",{collectionName:e.name,databaseName:r.name})}async function N_(e,t){for(;!e.closed;){if(await Nt(e.eventBulks$).catch(()=>{}),await e.promiseWait(t.runEach),e.closed)return;await gf(e,t)}}var Co=xn;async function M_(e){var t=e.collection,r=t.database,n=Object.assign({},Wc,r.cleanupPolicy?r.cleanupPolicy:{});await vf(t,n),!t.closed&&(await wf(e,n),await B_(e,n))}async function wf(e,t){for(var r=e.collection,n=r.database,i=!1;!i&&!r.closed;){if(t.awaitReplicationsInSync){var a=Fc.get(r);a&&await Promise.all(a.map(o=>{if(!o.isStopped())return o.awaitInSync()}))}if(r.closed)return;Co=Co.then(async()=>r.closed?!0:(await n.requestIdlePromise(),e._cleanup())),i=await Co}}async function B_(e,t){for(var r=e.collection;!r.closed;){if(await Nt(r.eventBulks$).catch(()=>{}),await r.promiseWait(t.runEach),r.closed)return;await wf(e,t)}}var F_={name:"cleanup",rxdb:!0,prototypes:{RxCollection:e=>{e.cleanup=async function(t){var r=Object.assign({},Wc,this.database.cleanupPolicy?this.database.cleanupPolicy:{});typeof t>"u"&&(t=r.minimumDeletedTime);for(var n=!1;!n&&!this.closed;)n=await this.storageInstance.cleanup(t);await Gt("postCleanup",{collectionName:this.name,databaseName:this.database.name})}}},hooks:{createRxCollection:{after:e=>{A_(e.collection)}},createRxState:{after:e=>{M_(e.state)}}}},L_="16.15.0";function U_(){ka.premium="yesIgotRxDBPremiumAccess"}function $c(e){return e.join("||")}var si=["_deleted","_meta.lwt"];$c(si);var W_=gh(),$_=(function(e){function t(r,n,i){var a;return a=e.call(this,null,n)||this,a.id=r,a.parent=i,a}return uc(t,e),t})(W_),oi={get isLocal(){return!0},get allAttachments$(){throw ee("LD1",{document:this})},get primaryPath(){return"id"},get primary(){return this.id},get $(){var e=this,t=Wr(Zo,this.parent),r=this.primary;return e.parent.eventBulks$.pipe(Ce(n=>!!n.isLocal),We(n=>n.events.find(i=>i.documentId===r)),Ce(n=>!!n),We(n=>Xd(Z(n))),Ni(t.docCache.getLatestDocumentData(this.primary)),yi((n,i)=>n._rev===i._rev),We(n=>t.docCache.getCachedRxDocument(n)),Ai(xi))},get $$(){var e=this,t=ko(e),r=t.getReactivityFactory();return r.fromObservable(e.$,e.getLatest()._data,t)},get deleted$$(){var e=this,t=ko(e),r=t.getReactivityFactory();return r.fromObservable(e.deleted$,e.getLatest().deleted,t)},getLatest(){var e=Wr(Zo,this.parent),t=e.docCache.getLatestDocumentData(this.primary);return e.docCache.getCachedRxDocument(t)},get(e){if(e="data."+e,!!this._data){if(typeof e!="string")throw $a("LD2",{objPath:e});var t=vr(this._data,e);return t=xe.deepFreezeWhenDevMode(t),t}},get$(e){if(e="data."+e,xe.isDevMode()){if(e.includes(".item."))throw ee("LD3",{objPath:e});if(e===this.primaryPath)throw ee("LD4")}return this.$.pipe(We(t=>t._data),We(t=>vr(t,e)),yi())},get$$(e){var t=ko(this),r=t.getReactivityFactory();return r.fromObservable(this.get$(e),this.getLatest().get(e),t)},async incrementalModify(e){var t=await ci(this.parent);return t.incrementalWriteQueue.addWrite(this._data,async r=>(r.data=await e(r.data,this),r)).then(r=>t.docCache.getCachedRxDocument(r))},incrementalPatch(e){return this.incrementalModify(t=>(Object.entries(e).forEach(([r,n])=>{t[r]=n}),t))},async _saveData(e){var t=await ci(this.parent),r=this._data;e.id=this.id;var n=[{previous:r,document:e}];return t.storageInstance.bulkWrite(n,"local-document-save-data").then(i=>{if(i.error[0])throw i.error[0];var a=St(this.collection.schema.primaryPath,n,i)[0];e=Oe(e),e._rev=a._rev})},async remove(){var e=await ci(this.parent),t=Oe(this._data);return t._deleted=!0,kn(e.storageInstance,{previous:this._data,document:t},"local-document-remove").then(r=>e.docCache.getCachedRxDocument(r))}},xl=!1,q_=()=>{if(!xl){xl=!0;var e=gs,t=Object.getOwnPropertyNames(e);t.forEach(n=>{var i=Object.getOwnPropertyDescriptor(oi,n);if(!i){var a=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(oi,n,a)}});var r=n=>()=>{throw ee("LD6",{functionName:n})};["populate","update","putAttachment","putAttachmentBase64","getAttachment","allAttachments"].forEach(n=>oi[n]=r(n))}};function H_(e,t){q_();var r=new $_(e.id,e,t);return Object.setPrototypeOf(r,oi),r.prototype=oi,r}function ko(e){var t=e.parent;return Wh(t)?t:t.database}var ts=new WeakMap,Zo=new WeakMap;function Ol(e){var t=e.database?e.database:e,r=e.database?e.name:"",n=(async()=>{var i=await bf(t.token,t.storage,t.name,r,t.instanceCreationOptions,t.multiInstance);i=Ec(t,i,Sf);var a=new Ch("id",t.eventBulks$.pipe(Ce(m=>{var y=!1;return(r===""&&!m.collectionName||r!==""&&m.collectionName===r)&&(y=!0),y&&m.isLocal}),We(m=>m.events)),m=>H_(m,e)),o=new vh(i,"id",()=>{},()=>{}),u=await t.storageToken,d=i.changeStream().subscribe(m=>{for(var y=new Array(m.events.length),g=m.events,w=e.database?e.name:void 0,S=0;S<g.length;S++){var E=g[S];y[S]={documentId:E.documentId,collectionName:w,isLocal:!0,operation:E.operation,documentData:xe.deepFreezeWhenDevMode(E.documentData),previousDocumentData:xe.deepFreezeWhenDevMode(E.previousDocumentData)}}var D={id:m.id,isLocal:!0,internal:!1,collectionName:e.database?e.name:void 0,storageToken:u,events:y,databaseToken:t.token,checkpoint:m.checkpoint,context:m.context};t.$emit(D)});e._subs.push(d);var f={database:t,parent:e,storageInstance:i,docCache:a,incrementalWriteQueue:o};return Zo.set(e,f),f})();ts.set(e,n)}function ci(e){var t=ts.get(e);if(!t){var r=e.database?e.database:e,n=e.database?e.name:"";throw ee("LD8",{database:r.name,collection:n})}return t}function bf(e,t,r,n,i,a){return t.createStorageInstance({databaseInstanceToken:e,databaseName:r,collectionName:J_(n),schema:Sf,options:i,multiInstance:a,devMode:xe.isDevMode()})}function Tl(e){var t=ts.get(e);if(t)return ts.delete(e),t.then(r=>r.storageInstance.close())}async function Kl(e,t,r){var n=Tn(10),i=await bf(n,e,t,r,{},!1);await i.remove()}function J_(e){return"plugin-local-documents-"+e}var Sf=ds({title:"RxLocalDocument",version:0,primaryKey:"id",type:"object",properties:{id:{type:"string",maxLength:128},data:{type:"object",additionalProperties:!0}},required:["id","data"]});async function Al(e,t){var r=await ci(this),n={id:e,data:t,_deleted:!1,_meta:Dn(),_rev:kt(),_attachments:{}}
41;return kn(r.storageInstance,{document:n},"local-document-insert").then(i=>r.docCache.getCachedRxDocument(i))}function Nl(e,t){return this.getLocal(e).then(r=>{if(r)return r.incrementalModify(()=>t);var n=this.insertLocal(e,t);return n})}async function Ml(e){var t=await ci(this),r=t.docCache,n=r.getLatestDocumentDataIfExists(e);return n?Promise.resolve(r.getCachedRxDocument(n)):Kn(t.storageInstance,e).then(i=>i?t.docCache.getCachedRxDocument(i):null)}function Bl(e){return this.$.pipe(Ni(null),Mt(async t=>{if(t)return{changeEvent:t};var r=await this.getLocal(e);return{doc:r}}),Mt(async t=>{if(t.changeEvent){var r=t.changeEvent;if(!r.isLocal||r.documentId!==e)return{use:!1};var n=await this.getLocal(e);return{use:!0,doc:n}}else return{use:!0,doc:t.doc}}),Ce(t=>t.use),We(t=>t.doc))}var Ef={name:"local-documents",rxdb:!0,prototypes:{RxCollection:e=>{e.insertLocal=Al,e.upsertLocal=Nl,e.getLocal=Ml,e.getLocal$=Bl},RxDatabase:e=>{e.insertLocal=Al,e.upsertLocal=Nl,e.getLocal=Ml,e.getLocal$=Bl}},hooks:{createRxDatabase:{before:e=>{e.creator.localDocuments&&Ol(e.database)}},createRxCollection:{before:e=>{e.creator.localDocuments&&Ol(e.collection)}},preCloseRxDatabase:{after:e=>Tl(e)},postCloseRxCollection:{after:e=>Tl(e)},postRemoveRxDatabase:{after:e=>Kl(e.storage,e.databaseName,"")},postRemoveRxCollection:{after:e=>Kl(e.storage,e.databaseName,e.collectionName)}},overwritable:{}};async function _f(e){var t=Dy(e.collection.schema.jsonSchema).map(a=>e.collection.name+"-"+a),r=await e.database.internalStore.findDocumentsById(t.map(a=>Jr(a,mr)),!1),n={};r.forEach(a=>n[a.key]=a);var i=t.find(a=>n[a]);return i?n[i]:void 0}function j_(e,t,r){var n=Oe(r._attachments),i=st(r),a=i._meta;delete i._meta,i._attachments=n;for(var o=t+1,u=Promise.resolve(i),d=function(){var f=o;u=u.then(m=>z_(e,f,m)),o++};o<=e.schema.version;)d();return u.then(f=>f===null?dc:(f._meta=a,f))}function z_(e,t,r){if(r===null)return dc;var n=e.migrationStrategies[t](r,e),i=Pd(n);return i}async function Pf(e){if(e.collection.schema.version===0)return Rt;var t=await _f(e);return!!t}var G_=200,If=new WeakMap;function V_(e){var t=Cf(e.database),r=t.getValue().slice(0);r.push(e),t.next(r)}function Cf(e){return it(If,e,()=>new Kt([]))}function Y_(e){var t=If.get(e);t&&t.complete()}var Q_=(function(){function e(r,n,i=[r.name,"v",r.schema.version].join("-")){this.started=!1,this.canceled=!1,this.updateStatusHandlers=[],this.updateStatusQueue=xn,this.collection=r,this.migrationStrategies=n,this.statusDocKey=i,this.database=r.database,this.oldCollectionMeta=_f(this),this.mustMigrate=Pf(this),this.statusDocId=Jr(this.statusDocKey,Oa),V_(this),this.$=$g(this.database.internalStore,this.statusDocId).pipe(Ce(a=>!!a),We(a=>Z(a).data),Ai(xi))}var t=e.prototype;return t.getStatus=function(){return Nt(this.$)},t.startMigration=async function(n=G_){var i=await this.mustMigrate;if(i){if(this.started)throw ee("DM1");if(this.started=!0,this.database.multiInstance){this.broadcastChannel=new bs(["rx-migration-state",this.database.name,this.collection.name,this.collection.schema.version].join("|"));var a=af(this.broadcastChannel);await a.awaitLeadership()}var o=await this.oldCollectionMeta,u=await this.database.storage.createStorageInstance({databaseName:this.database.name,collectionName:this.collection.name,databaseInstanceToken:this.database.token,multiInstance:this.database.multiInstance,options:{},schema:Z(o).data.schema,password:this.database.password,devMode:xe.isDevMode()}),d=await this.getConnectedStorageInstances(),f=await this.countAllDocuments([u].concat(d.map(y=>y.oldStorage)));await this.updateStatus(y=>(y.count.total=f,y));try{await Promise.all(d.map(async y=>{await Oh(this.collection,y.newStorage.collectionName,y.newStorage.schema),await this.migrateStorage(y.oldStorage,y.newStorage,n),await y.newStorage.close()})),await this.migrateStorage(u,this.collection.storageInstance.originalStorageInstance,n)}catch(y){await u.close(),await this.updateStatus(g=>(g.status="ERROR",g.error=Mo(y),g));return}try{await kn(this.database.internalStore,{previous:o,document:Object.assign({},o,{_deleted:!0}
41)},"rx-migration-remove-collection-meta")}catch(y){var m=Sn(y);if(!(m&&m.documentInDb._deleted))throw y}await this.updateStatus(y=>(y.status="DONE",y)),this.broadcastChannel&&await this.broadcastChannel.close()}},t.updateStatus=function(n){return this.updateStatusHandlers.push(n),this.updateStatusQueue=this.updateStatusQueue.then(async()=>{if(this.updateStatusHandlers.length!==0){var i=this.updateStatusHandlers;for(this.updateStatusHandlers=[];;){var a=await Kn(this.database.internalStore,this.statusDocId),o=st(a);a||(o={id:this.statusDocId,key:this.statusDocKey,context:Oa,data:{collectionName:this.collection.name,status:"RUNNING",count:{total:0,handled:0,percent:0}},_deleted:!1,_meta:Dn(),_rev:kt(),_attachments:{}});var u=Z(o).data;for(var d of i)u=d(u);if(u.count.percent=Math.round(u.count.handled/u.count.total*100),o&&a&&En(o.data,a.data))break;try{await kn(this.database.internalStore,{previous:a,document:Z(o)},Oa);break}catch(f){if(!Sn(f))throw f}}}}),this.updateStatusQueue},t.migrateStorage=async function(n,i,a){this.collection.onClose.push(()=>this.cancel()),this.database.onClose.push(()=>this.cancel());var o=await this.database.storage.createStorageInstance({databaseName:this.database.name,collectionName:"rx-migration-state-meta-"+n.collectionName+"-"+n.schema.version,databaseInstanceToken:this.database.token,multiInstance:this.database.multiInstance,options:{},schema:Vo(n.schema,za(n.schema)),password:this.database.password,devMode:xe.isDevMode()}),u=Ob(i,Va,this.database.token,!0),d=qh({keepMeta:!0,identifier:["rx-migration-state",n.collectionName,n.schema.version,this.collection.schema.version].join("-"),replicationHandler:{masterChangesSince(){return Promise.resolve({checkpoint:null,documents:[]})},masterWrite:async m=>{var y=await Promise.all(m.map(async w=>{var S=w.newDocumentState;if(i.schema.title===Ta&&(S=w.newDocumentState.docData,w.newDocumentState.isCheckpoint==="1"))return{assumedMasterState:void 0,newDocumentState:w.newDocumentState};var E=await j_(this.collection,n.schema.version,S);if(E===null)return null;var D={assumedMasterState:void 0,newDocumentState:i.schema.title===Ta?Object.assign({},w.newDocumentState,{docData:E}):E};return D}));y=y.filter(w=>!!w&&!!w.newDocumentState);var g=await u.masterWrite(y);return g},masterChangeStream$:new He().asObservable()},forkInstance:n,metaInstance:o,pushBatchSize:a,pullBatchSize:0,conflictHandler:Va,hashFunction:this.database.hashFunction}),f=!1;if(d.events.error.subscribe(m=>f=m),d.events.processed.up.subscribe(()=>{this.updateStatus(m=>(m.count.handled=m.count.handled+1,m))}),await Ka(d),await Qo(d),await this.updateStatusQueue,f)throw await o.close(),f;await Promise.all([n.remove(),o.remove()]),await this.cancel()},t.cancel=async function(){this.canceled=!0,this.replicationState&&await Hh(this.replicationState),this.broadcastChannel&&await this.broadcastChannel.close()},t.countAllDocuments=async function(n){var i=0;return await Promise.all(n.map(async a=>{var o=vs(a.schema,mn(a.schema,{selector:{}})),u=await a.count(o);i+=u.count})),i},t.getConnectedStorageInstances=async function(){var n=Z(await this.oldCollectionMeta),i=[];return await Promise.all(await Promise.all(n.data.connectedStorages.map(async a=>{if(a.schema.title!==Ta)throw new Error("unknown migration handling for schema");var o=Vo(st(this.collection.schema.jsonSchema),za(a.schema));o.version=this.collection.schema.version;var[u,d]=await Promise.all([this.database.storage.createStorageInstance({databaseInstanceToken:this.database.token,databaseName:this.database.name,devMode:xe.isDevMode(),multiInstance:this.database.multiInstance,options:{},schema:a.schema,password:this.database.password,collectionName:a.collectionName}),this.database.storage.createStorageInstance({databaseInstanceToken:this.database.token,databaseName:this.database.name,devMode:xe.isDevMode(),multiInstance:this.database.multiInstance,options:{},schema:o,password:this.database.password,collectionName:a.collectionName})]);i.push({oldStorage:u,newStorage:d})}))),i},t.migratePromise=async function(n){this.startMigration(n);var i=await this.mustMigrate;if(!i)return{status:"DONE",collectionName:this.collection.name,count:{handled:0,percent:0,total:0}};var a=await Promise.race([Nt(this.$.pipe(Ce(o=>o.status==="DONE"))),Nt(this.$.pipe(Ce(o=>o.status==="ERROR")))]);if(a.status==="ERROR")throw ee("DM4",{collection:this.collection.name,error:a.error});return a},e})(),X_=new WeakMap,Z_={name:"migration-schema",rxdb:!0,init(){hn(Ef)},hooks:{preCloseRxDatabase:{after:Y_}}
41,prototypes:{RxDatabase:e=>{e.migrationStates=function(){return Cf(this).pipe(Ai(xi))}},RxCollection:e=>{e.getMigrationState=function(){return it(X_,this,()=>new Q_(this.asRxCollection,this.migrationStrategies))},e.migrationNeeded=function(){return this.schema.version===0?Rt:Pf(this.getMigrationState())}}}},eP=Z_;const Nn=(e,t)=>{var u,d;const{primaryKey:r="id",primaryKeyMaxLength:n=48,deletedField:i="deleted",version:a=0}=t||{},o={...e};return delete o.properties[i],{...o,primaryKey:r,properties:{...e.properties,[r]:{...(u=e.properties)==null?void 0:u[r],maxLength:n}},required:(d=e.required)==null?void 0:d.filter(f=>f!==i),version:a}},tP={sharing_bucket:sn.SharingBucket,content_item:sn.ContentItem,file_encryption_key:sn.FileEncryptionKey,user_encryption_key:sn.UserEncryptionKey,user:sn.User,platform_action_history:sn.PlatformActionHistory},kf=1,rP=Nn(R_,{version:kf}),nP={[kf]:e=>({...e,previews:e.previews??[]})},iP=Nn(D_),aP=Nn(x_),sP=Nn(O_),oP=Nn(T_),cP=Nn(K_),uP=4,Fl=async(e,t,r,n)=>{const{response:i}=e;if(!i)return;const{status:a}=i;a<400||a>499||(t.add(e),t.size>uP&&(await r.cancel(),n&&await n(e)))},lP=async(e,t,r,n,i,a,o,u)=>{const{replicationWaitForLeadership:d}=r||{},f=new Set,m=new Set,y=tP[e],g=QS({collection:t,replicationIdentifier:`${y}-http-replication`,deletedField:"deleted",retryTime:3e3,toggleOnDocumentVisible:!0,waitForLeadership:d??!0,push:{async handler(F){const j=await Ba(a.pushCollectionChanges({...n,replicatedCollectionName:y,pushRequest:{changedDocuments:F}}));if(!j.ok)throw await Fl(j.error,f,g,u),j.error;return f.clear(),j.value.conflicts}},pull:{batchSize:1e3,async handler(F,j){const $=await Ba(a.pullCollectionChanges({...n,replicatedCollectionName:y,timestampSeconds:(F==null?void 0:F.time)??0,timestampIncrement:(F==null?void 0:F.increment)??0,limit:j}));if(!$.ok)throw await Fl($.error,m,g,u),$.error;return m.clear(),$.value},stream$:i.asObservable()}});let w=Ke();const S=Ke(),E=Ke();w.resolve();const D=g.active$.subscribe(F=>{F?(S.resolve(),w=Ke()):w.resolve()}),M=g.canceled$.subscribe(F=>{F&&E.resolve()}),U=g.error$.subscribe(F=>{var j,$;console.error(`Replication error on collection "${e}":`,F),!o.aborted&&(($=(j=F.parameters.errors)==null?void 0:j[0])==null?void 0:$.code)==="RC_OUTDATED"&&location.reload()});return{replicationState:g,activePromise:S.promise,canceledPromise:E.promise,awaitActiveReplication:()=>w.promise,dispose:()=>{D.unsubscribe(),M.unsubscribe(),U.unsubscribe(),g.cancel().catch(()=>null),w.resolve()}}},dP=["DB6","DB8"],hP=e=>e,rs=(e,t,r)=>{const n="lmwr-file-sharing",i=t?"-anon":"-user",a=`-${e}`;return`${n}${i}${a}${r?"-memory":""}`},Rf=(e,t,r,n,i)=>{const{multiInstance:a}=n||{},o=hP(r),u=async()=>Kc(t,o),d=async()=>{const S=await Pb({name:t,storage:o,localDocuments:!0,ignoreDuplicate:!1,closeDuplicates:!0,cleanupPolicy:{runEach:9e5},multiInstance:a??!0});f().then(()=>{S.close().catch(()=>null)});const E=await S.addCollections({content_item:{schema:rP,localDocuments:!0,migrationStrategies:nP},file_encryption_key:{schema:iP,localDocuments:!0},sharing_bucket:{schema:aP,localDocuments:!0},user_encryption_key:{schema:sP,localDocuments:!0},user:{schema:oP,localDocuments:!0},platform_action_history:{schema:cP,localDocuments:!0}});return f().then(()=>{Object.values(E).forEach(D=>{D.close().catch(()=>null)})}),{database:S,collections:E}},f=()=>new Promise(S=>{e.aborted?S():e.addEventListener("abort",()=>{S()})}),y=(async()=>d().catch(S=>{if(S instanceof Ao)return console.error("Wiping rxdb due to:",S),u().then(()=>d());throw console.error("RXDB Error",S),S}))(),w=(async()=>{if(!i)return{async awaitActiveReplication(){}};const{collections:S,database:E}=await y,{userId:D,isAnonymous:M,apiOptions:U,onUnrecoverableReplicationError:F}=i,{basePath:j}=U,$=di(yf,U,{init:{signal:e}}),V={userId:M?void 0:D,clientDeviceId:M?D:void 0},W=new URL(j);W.pathname="/sharing/replication/pull-stream",V.clientDeviceId&&W.searchParams.set("clientDeviceId",V.clientDeviceId),V.userId&&W.searchParams.set("userId",V.userId);const ie=Object.fromEntries(Object.entries(S).map(([re])=>[re,new He])),de=us({maxDelay:2e4}),Se=tm(W,{...Bp(W,U,{init:{signal:e}}),retry:(re,{underlyingError:oe,response:ye})=>
41{if(!(Fp(ye)||!ye&&!im(oe)))return de(re)},onMessage({event:re,data:oe}){const[,ye]=Object.entries(ie).find(([Ie])=>re.toLowerCase()===`update-${Ie}`)||[];ye&&ye.next(JSON.parse(oe))}});f().then(()=>{Se.close()});const ue=await Promise.all(Object.keys(S).map(re=>lP(re,S[re],n,V,ie[re],$,e,async oe=>{e.aborted||(await u(),F==null||F(oe))}).then(oe=>(f().then(()=>{oe.dispose()}),oe)))).then(re=>Object.keys(S).reduce((oe,ye)=>{const Ie=re.find(Je=>Je.replicationState.collection.name===ye);return oe[ye]=Ie,oe},{}));return Object.values(ue).forEach(re=>{re.canceledPromise.then(()=>{e.aborted||Se.close()})}),await Promise.all(Object.entries(ue).map(([re,oe])=>{const ye=S[re];return(async()=>{const Me="sync-time";await ye.insertLocal(Me,{[Me]:0}).catch(()=>null);const fe=ye.$.subscribe(({isLocal:ne,documentId:we,operation:_e})=>{!ne||we!==Me||(_e==="INSERT"||_e==="DELETE")&&(fe.unsubscribe(),E.close(),location.reload())}),ve=ye.getLocal$(Me).pipe(Ce(ne=>ne?ne.get(Me)!==0:!1));oe.activePromise.then(async()=>{await oe.replicationState.awaitInSync(),ye.closed||await ye.upsertLocal(Me,{[Me]:Date.now()})}),await Promise.race([Nt(ve).catch(()=>null),f()]),fe.unsubscribe()})()})),{async awaitActiveReplication(){await Promise.all(Object.values(ue).map(re=>re.awaitActiveReplication()))}}})();return y.catch(S=>{i&&S instanceof Ao&&dP.includes(S.code)&&location.reload()}),Promise.all([y,w]).then(([S,E])=>({database:S.database,replication:E}))},CC=()=>{U_(),hn(lf),hn(F_),hn(Ef),hn(eP)};var Aa={exports:{}},fP=Aa.exports,Ll;function pP(){return Ll||(Ll=1,(function(e,t){(function(r,n){e.exports=n()})(fP,function(){var r=function(s,c){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,h){l.__proto__=h}||function(l,h){for(var p in h)Object.prototype.hasOwnProperty.call(h,p)&&(l[p]=h[p])})(s,c)},n=function(){return(n=Object.assign||function(s){for(var c,l=1,h=arguments.length;l<h;l++)for(var p in c=arguments[l])Object.prototype.hasOwnProperty.call(c,p)&&(s[p]=c[p]);return s}).apply(this,arguments)};function i(s,c,l){for(var h,p=0,v=c.length;p<v;p++)!h&&p in c||((h=h||Array.prototype.slice.call(c,0,p))[p]=c[p]);return s.concat(h||Array.prototype.slice.call(c))}var a=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:xp,o=Object.keys,u=Array.isArray;function d(s,c){return typeof c!="object"||o(c).forEach(function(l){s[l]=c[l]}),s}typeof Promise>"u"||a.Promise||(a.Promise=Promise);var f=Object.getPrototypeOf,m={}.hasOwnProperty;function y(s,c){return m.call(s,c)}function g(s,c){typeof c=="function"&&(c=c(f(s))),(typeof Reflect>"u"?o:Reflect.ownKeys)(c).forEach(function(l){S(s,l,c[l])})}var w=Object.defineProperty;function S(s,c,l,h){w(s,c,d(l&&y(l,"get")&&typeof l.get=="function"?{get:l.get,set:l.set,configurable:!0}:{value:l,configurable:!0,writable:!0},h))}function E(s){return{from:function(c){return s.prototype=Object.create(c.prototype),S(s.prototype,"constructor",s),{extend:g.bind(null,s.prototype)}}}}var D=Object.getOwnPropertyDescriptor,M=[].slice;function U(s,c,l){return M.call(s,c,l)}function F(s,c){return c(s)}function j(s){if(!s)throw new Error("Assertion Failed")}function $(s){a.setImmediate?setImmediate(s):setTimeout(s,0)}function V(s,c){if(typeof c=="string"&&y(s,c))return s[c];if(!c)return s;if(typeof c!="string"){for(var l=[],h=0,p=c.length;h<p;++h){var v=V(s,c[h]);l.push(v)}return l}var b=c.indexOf(".");if(b!==-1){var _=s[c.substr(0,b)];return _==null?void 0:V(_,c.substr(b+1))}}function W(s,c,l){if(s&&c!==void 0&&!("isFrozen"in Object&&Object.isFrozen(s)))if(typeof c!="string"&&"length"in c){j(typeof l!="string"&&"length"in l);for(var h=0,p=c.length;h<p;++h)W(s,c[h],l[h])}else{var v,b,_=c.indexOf(".");_!==-1?(v=c.substr(0,_),(b=c.substr(_+1))===""?l===void 0?u(s)&&!isNaN(parseInt(v))?s.splice(v,1):delete s[v]:s[v]=l:W(_=!(_=s[v])||!y(s,v)?s[v]={}:_,b,l)):l===void 0?u(s)&&!isNaN(parseInt(c))?s.splice(c,1):delete s[c]:s[c]=l}}function ie(s){var c,l={};for(c in s)y(s,c)&&(l[c]=s[c]);return l}var de=[].concat;function Se(s){return de.apply([],s)}var Lt="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(Se([8,16,32,64].map(function(s){return["Int","Uint","Float"].map(function(c){return c+s+"Array"})}))).filter(function(s){return a[s]}),ue=new Set(Lt.map(function(s){return a[s]})),re=null;function oe(s){return re=new WeakMap,s=(function c(l){if(!l||typeof l!="object")return l;var h=re.get(l);if(h)return h;if(u(l)){h=[],re.set(l,h);for(var p=0,v=l.length;p<v;++p)h.push(c(l[p]))}else if(ue.has(l.constructor))h=l;else{var b,_=f(l);for(b in h=_===Object.prototype?{}:Object.create(_),re.set(l,h),l)y(l,b)&&(h[b]=c(l[b]))}return h})(s),re=null,s}var ye={}.toString;function Ie(s){return ye.call(s).slice(8,-1)}var Je=typeof Symbol<"u"?Symbol.iterator:"@@iterator",Me=typeof Je=="symbol"?function(s){var c;return s!=null&&(c=s[Je])&&c.apply(s)}:function(){return null};function fe(s,c){return c=s.indexOf(c),0<=c&&s.splice(c,1),0<=c}var ve={};function ne(s){var c,l,h,p;
41if(arguments.length===1){if(u(s))return s.slice();if(this===ve&&typeof s=="string")return[s];if(p=Me(s)){for(l=[];!(h=p.next()).done;)l.push(h.value);return l}if(s==null)return[s];if(typeof(c=s.length)!="number")return[s];for(l=new Array(c);c--;)l[c]=s[c];return l}for(c=arguments.length,l=new Array(c);c--;)l[c]=arguments[c];return l}var we=typeof Symbol<"u"?function(s){return s[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},Ln=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],vt=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(Ln),_e={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 ge(s,c){this.name=s,this.message=c}function qe(s,c){return s+". Errors: "+Object.keys(c).map(function(l){return c[l].toString()}).filter(function(l,h,p){return p.indexOf(l)===h}).join(` 42`)}function yt(s,c,l,h){this.failures=c,this.failedKeys=h,this.successCount=l,this.message=qe(s,c)}function Zt(s,c){this.name="BulkError",this.failures=Object.keys(c).map(function(l){return c[l]}),this.failuresByPos=c,this.message=qe(s,this.failures)}E(ge).from(Error).extend({toString:function(){return this.name+": "+this.message}}),E(yt).from(ge),E(Zt).from(ge);var _s=vt.reduce(function(s,c){return s[c]=c+"Error",s},{}),Qf=ge,se=vt.reduce(function(s,c){var l=c+"Error";function h(p,v){this.name=l,p?typeof p=="string"?(this.message="".concat(p).concat(v?` 43 `+v:""),this.inner=v||null):typeof p=="object"&&(this.message="".concat(p.name," ").concat(p.message),this.inner=p):(this.message=_e[c]||l,this.inner=null)}return E(h).from(Qf),s[c]=h,s},{});se.Syntax=SyntaxError,se.Type=TypeError,se.Range=RangeError;var Yc=Ln.reduce(function(s,c){return s[c+"Error"]=se[c],s},{}),qi=vt.reduce(function(s,c){return["Syntax","Type","Range"].indexOf(c)===-1&&(s[c+"Error"]=se[c]),s},{});function Re(){}function Bn(s){return s}function Xf(s,c){return s==null||s===Bn?c:function(l){return c(s(l))}}function Sr(s,c){return function(){s.apply(this,arguments),c.apply(this,arguments)}}function Zf(s,c){return s===Re?c:function(){var l=s.apply(this,arguments);l!==void 0&&(arguments[0]=l);var h=this.onsuccess,p=this.onerror;this.onsuccess=null,this.onerror=null;var v=c.apply(this,arguments);return h&&(this.onsuccess=this.onsuccess?Sr(h,this.onsuccess):h),p&&(this.onerror=this.onerror?Sr(p,this.onerror):p),v!==void 0?v:l}}function ep(s,c){return s===Re?c:function(){s.apply(this,arguments);var l=this.onsuccess,h=this.onerror;this.onsuccess=this.onerror=null,c.apply(this,arguments),l&&(this.onsuccess=this.onsuccess?Sr(l,this.onsuccess):l),h&&(this.onerror=this.onerror?Sr(h,this.onerror):h)}}function tp(s,c){return s===Re?c:function(l){var h=s.apply(this,arguments);d(l,h);var p=this.onsuccess,v=this.onerror;return this.onsuccess=null,this.onerror=null,l=c.apply(this,arguments),p&&(this.onsuccess=this.onsuccess?Sr(p,this.onsuccess):p),v&&(this.onerror=this.onerror?Sr(v,this.onerror):v),h===void 0?l===void 0?void 0:l:d(h,l)}}function rp(s,c){return s===Re?c:function(){return c.apply(this,arguments)!==!1&&s.apply(this,arguments)}}function Ps(s,c){return s===Re?c:function(){var l=s.apply(this,arguments);if(l&&typeof l.then=="function"){for(var h=this,p=arguments.length,v=new Array(p);p--;)v[p]=arguments[p];return l.then(function(){return c.apply(h,v)})}return c.apply(this,arguments)}}qi.ModifyError=yt,qi.DexieError=ge,qi.BulkError=Zt;var xt=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Qc(s){xt=s}var Fn={},Xc=100,Lt=typeof Promise>"u"?[]:(function(){var s=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[s,f(s),s];var c=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[c,f(c),s]})(),Ln=Lt[0],vt=Lt[1],Lt=Lt[2],vt=vt&&vt.then,Er=Ln&&Ln.constructor,Is=!!Lt,Un=function(s,c){Wn.push([s,c]),Hi&&(queueMicrotask(ip),Hi=!1)},Cs=!0,Hi=!0,_r=[],Ji=[],ks=Bn,er={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Re,pgp:!1,env:{},finalize:Re},ae=er,Wn=[],Pr=0,ji=[];function X(s){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var c=this._PSD=ae;if(typeof s!="function"){if(s!==Fn)throw new TypeError("Not a function");return this._state=arguments[1],this._value=arguments[2],void(this._state===!1&&Ds(this,this._value))}this._state=null,this._value=null,++c.ref,(function l(h,p){try{p(function(v){if(h._state===null){if(v===h)throw new TypeError("A promise cannot be resolved with itself.");var b=h._lib&&Vr();v&&typeof v.then=="function"?l(h,function(_,I){v instanceof X?v._then(_,I):v.then(_,I)}):(h._state=!0,h._value=v,eu(h)),b&&Yr()}},Ds.bind(null,h))}catch(v){Ds(h,v)}})(this,s)}var Rs={get:function(){var s=ae,c=Yi;function l(h,p){var v=this,b=!s.global&&(s!==ae||c!==Yi),_=b&&!rr(),I=new X(function(k,O){xs(v,new Zc(ru(h,s,b,_),ru(p,s,b,_),k,O,s))});return this._consoleTask&&(I._consoleTask=this._consoleTask),I}return l.prototype=Fn,l},set:function(s){S(this,"then",s&&s.prototype===Fn?Rs:{get:function(){return s},set:Rs.set})}};function Zc(s,c,l,h,p){this.onFulfilled=typeof s=="function"?s:null,this.onRejected=typeof c=="function"?c:null,this.resolve=l,this.reject=h,this.psd=p}function Ds(s,c){var l,h;Ji.push(c),s._state===null&&(l=s._lib&&Vr(),c=ks(c),s._state=!1,s._value=c,h=s,_r.s
43ome(function(p){return p._value===h._value})||_r.push(h),eu(s),l&&Yr())}function eu(s){var c=s._listeners;s._listeners=[];for(var l=0,h=c.length;l<h;++l)xs(s,c[l]);var p=s._PSD;--p.ref||p.finalize(),Pr===0&&(++Pr,Un(function(){--Pr==0&&Os()},[]))}function xs(s,c){if(s._state!==null){var l=s._state?c.onFulfilled:c.onRejected;if(l===null)return(s._state?c.resolve:c.reject)(s._value);++c.psd.ref,++Pr,Un(np,[l,s,c])}else s._listeners.push(c)}function np(s,c,l){try{var h,p=c._value;!c._state&&Ji.length&&(Ji=[]),h=xt&&c._consoleTask?c._consoleTask.run(function(){return s(p)}):s(p),c._state||Ji.indexOf(p)!==-1||(function(v){for(var b=_r.length;b;)if(_r[--b]._value===v._value)return _r.splice(b,1)})(c),l.resolve(h)}catch(v){l.reject(v)}finally{--Pr==0&&Os(),--l.psd.ref||l.psd.finalize()}}function ip(){Ir(er,function(){Vr()&&Yr()})}function Vr(){var s=Cs;return Hi=Cs=!1,s}function Yr(){var s,c,l;do for(;0<Wn.length;)for(s=Wn,Wn=[],l=s.length,c=0;c<l;++c){var h=s[c];h[0].apply(null,h[1])}while(0<Wn.length);Hi=Cs=!0}function Os(){var s=_r;_r=[],s.forEach(function(h){h._PSD.onunhandled.call(null,h._value,h)});for(var c=ji.slice(0),l=c.length;l;)c[--l]()}function zi(s){return new X(Fn,!1,s)}function Ae(s,c){var l=ae;return function(){var h=Vr(),p=ae;try{return nr(l,!0),s.apply(this,arguments)}catch(v){c&&c(v)}finally{nr(p,!1),h&&Yr()}}}g(X.prototype,{then:Rs,_then:function(s,c){xs(this,new Zc(null,null,s,c,ae))},catch:function(s){if(arguments.length===1)return this.then(null,s);var c=s,l=arguments[1];return typeof c=="function"?this.then(null,function(h){return(h instanceof c?l:zi)(h)}):this.then(null,function(h){return(h&&h.name===c?l:zi)(h)})},finally:function(s){return this.then(function(c){return X.resolve(s()).then(function(){return c})},function(c){return X.resolve(s()).then(function(){return zi(c)})})},timeout:function(s,c){var l=this;return s<1/0?new X(function(h,p){var v=setTimeout(function(){return p(new se.Timeout(c))},s);l.then(h,p).finally(clearTimeout.bind(null,v))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&S(X.prototype,Symbol.toStringTag,"Dexie.Promise"),er.env=tu(),g(X,{all:function(){var s=ne.apply(null,arguments).map(Qi);return new X(function(c,l){s.length===0&&c([]);var h=s.length;s.forEach(function(p,v){return X.resolve(p).then(function(b){s[v]=b,--h||c(s)},l)})})},resolve:function(s){return s instanceof X?s:s&&typeof s.then=="function"?new X(function(c,l){s.then(c,l)}):new X(Fn,!0,s)},reject:zi,race:function(){var s=ne.apply(null,arguments).map(Qi);return new X(function(c,l){s.map(function(h){return X.resolve(h).then(c,l)})})},PSD:{get:function(){return ae},set:function(s){return ae=s}},totalEchoes:{get:function(){return Yi}},newPSD:tr,usePSD:Ir,scheduler:{get:function(){return Un},set:function(s){Un=s}},rejectionMapper:{get:function(){return ks},set:function(s){ks=s}},follow:function(s,c){return new X(function(l,h){return tr(function(p,v){var b=ae;b.unhandleds=[],b.onunhandled=v,b.finalize=Sr(function(){var _,I=this;_=function(){I.unhandleds.length===0?p():v(I.unhandleds[0])},ji.push(function k(){_(),ji.splice(ji.indexOf(k),1)}),++Pr,Un(function(){--Pr==0&&Os()},[])},b.finalize),s()},c,l,h)})}}),Er&&(Er.allSettled&&S(X,"allSettled",function(){var s=ne.apply(null,arguments).map(Qi);return new X(function(c){s.length===0&&c([]);var l=s.length,h=new Array(l);s.forEach(function(p,v){return X.resolve(p).then(function(b){return h[v]={status:"fulfilled",value:b}},function(b){return h[v]={status:"rejected",reason:b}}).then(function(){return--l||c(h)})})})}),Er.any&&typeof AggregateError<"u"&&S(X,"any",function(){var s=ne.apply(null,arguments).map(Qi);return new X(function(c,l){s.length===0&&l(new AggregateError([]));var h=s.length,p=new Array(h);s.forEach(function(v,b){return X.resolve(v).then(function(_){return c(_)},function(_){p[b]=_,--h||l(new AggregateError(p))})})})}),Er.withResolvers&&(X.withResolvers=Er.withResolvers));var je={awaits:0,echoes:0,id:0},ap=0,Gi=[],Vi=0,Yi=0,sp=0;function tr(s,c,l,h){var p=ae,v=Object.create(p);return v.parent=p,v.ref=0,v.global=!1,v.id=++sp,er.env,v.env=Is?{Promise:X,PromiseProp:{value:X,configurable:!0,writable:!0},all:X.all,race:X.race,allSettled:X.allSettled,any:X.any,resolve:X.resolve,reject:X.reject}:{},c&&d(v,c),++p.ref,v.finalize=function(){--this.parent.ref||this.parent.finalize()},h=Ir(v,s,l,h),v.ref===0&&v.finalize(),h}function Qr(){return je.id||(je.id=++ap),++je.awaits,je.echoes+=Xc,je.id}function rr(){return!!je.awaits&&(--je.awaits==0&&(je.id=0),je.echoes=je.awaits*Xc,!0)}function Qi(s){return je.echoes&&s&&s.constructor===Er?(Qr(),s.then(function(c){return rr(),c},function(c){return rr(),Be(c)})):s}function op(){var s=Gi[Gi.length-1];Gi.pop(),nr(s,!1)}function nr(s,c){var l,h=ae;(c?!je.echoes||Vi++&&s===ae:!Vi||--Vi&&s===ae)||queueMicrotask(c?(function(p){++Yi,je.echoes&&--je.echoes!=0||(je.echoes=je.awaits=je.id=0),Gi.push(ae),nr(p,!0)}).bind(null,s):op),s!==ae&&(ae=s,h===er&&(er.env=tu()),Is&&(l=er.env.Promise,c=s.env,(h.global||s.global)&&(Object.defineProperty(a,"Promise",c.PromiseProp),l.all=c.all,l.race=c.race,l.resolve=c.resolve,l.reject=c.reject,c.allSettled&&(l.allSettled=c.allSettled),c.any&&(l.any=c.any))
43))}function tu(){var s=a.Promise;return Is?{Promise:s,PromiseProp:Object.getOwnPropertyDescriptor(a,"Promise"),all:s.all,race:s.race,allSettled:s.allSettled,any:s.any,resolve:s.resolve,reject:s.reject}:{}}function Ir(s,c,l,h,p){var v=ae;try{return nr(s,!0),c(l,h,p)}finally{nr(v,!1)}}function ru(s,c,l,h){return typeof s!="function"?s:function(){var p=ae;l&&Qr(),nr(c,!0);try{return s.apply(this,arguments)}finally{nr(p,!1),h&&queueMicrotask(rr)}}}function Ts(s){Promise===Er&&je.echoes===0?Vi===0?s():enqueueNativeMicroTask(s):setTimeout(s,0)}(""+vt).indexOf("[native code]")===-1&&(Qr=rr=Re);var Be=X.reject,Cr="ï¿¿",Ft="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",nu="String expected.",Xr=[],Xi="__dbnames",Ks="readonly",As="readwrite";function kr(s,c){return s?c?function(){return s.apply(this,arguments)&&c.apply(this,arguments)}:s:c}var iu={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Zi(s){return typeof s!="string"||/\./.test(s)?function(c){return c}:function(c){return c[s]===void 0&&s in c&&delete(c=oe(c))[s],c}}function au(){throw se.Type()}function be(s,c){try{var l=su(s),h=su(c);if(l!==h)return l==="Array"?1:h==="Array"?-1:l==="binary"?1:h==="binary"?-1:l==="string"?1:h==="string"?-1:l==="Date"?1:h!=="Date"?NaN:-1;switch(l){case"number":case"Date":case"string":return c<s?1:s<c?-1:0;case"binary":return(function(p,v){for(var b=p.length,_=v.length,I=b<_?b:_,k=0;k<I;++k)if(p[k]!==v[k])return p[k]<v[k]?-1:1;return b===_?0:b<_?-1:1})(ou(s),ou(c));case"Array":return(function(p,v){for(var b=p.length,_=v.length,I=b<_?b:_,k=0;k<I;++k){var O=be(p[k],v[k]);if(O!==0)return O}return b===_?0:b<_?-1:1})(s,c)}}catch{}return NaN}function su(s){var c=typeof s;return c!="object"?c:ArrayBuffer.isView(s)?"binary":(s=Ie(s),s==="ArrayBuffer"?"binary":s)}function ou(s){return s instanceof Uint8Array?s:ArrayBuffer.isView(s)?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s)}var cu=(Te.prototype._trans=function(s,c,l){var h=this._tx||ae.trans,p=this.name,v=xt&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(s==="readonly"?"read":"write"," ").concat(this.name));function b(k,O,P){if(!P.schema[p])throw new se.NotFound("Table "+p+" not part of transaction");return c(P.idbtrans,P)}var _=Vr();try{var I=h&&h.db._novip===this.db._novip?h===ae.trans?h._promise(s,b,l):tr(function(){return h._promise(s,b,l)},{trans:h,transless:ae.transless||ae}):(function k(O,P,K,C){if(O.idbdb&&(O._state.openComplete||ae.letThrough||O._vip)){var x=O._createTransaction(P,K,O._dbSchema);try{x.create(),O._state.PR1398_maxLoop=3}catch(T){return T.name===_s.InvalidState&&O.isOpen()&&0<--O._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),O.close({disableAutoOpen:!1}),O.open().then(function(){return k(O,P,K,C)})):Be(T)}return x._promise(P,function(T,R){return tr(function(){return ae.trans=x,C(T,R,x)})}).then(function(T){if(P==="readwrite")try{x.idbtrans.commit()}catch{}return P==="readonly"?T:x._completion.then(function(){return T})})}if(O._state.openComplete)return Be(new se.DatabaseClosed(O._state.dbOpenError));if(!O._state.isBeingOpened){if(!O._state.autoOpen)return Be(new se.DatabaseClosed);O.open().catch(Re)}return O._state.dbReadyPromise.then(function(){return k(O,P,K,C)})})(this.db,s,[this.name],b);return v&&(I._consoleTask=v,I=I.catch(function(k){return console.trace(k),Be(k)})),I}finally{_&&Yr()}},Te.prototype.get=function(s,c){var l=this;return s&&s.constructor===Object?this.where(s).first(c):s==null?Be(new se.Type("Invalid argument to Table.get()")):this._trans("readonly",function(h){return l.core.get({trans:h,key:s}).then(function(p){return l.hook.reading.fire(p)})}).then(c)},Te.prototype.where=function(s){if(typeof s=="string")return new this.db.WhereClause(this,s);if(u(s))return new this.db.WhereClause(this,"[".concat(s.join("+"),"]"));var c=o(s);if(c.length===1)return this.where(c[0]).equals(s[c[0]]);var l=this.schema.indexes.concat(this.schema.primKey).filter(function(_){if(_.compound&&c.every(function(k){return 0<=_.keyPath.indexOf(k)})){for(var I=0;I<c.length;++I)if(c.indexOf(_.keyPath[I])===-1)return!1;return!0}return!1}).sort(function(_,I){return _.keyPath.length-I.keyPath.length}
43)[0];if(l&&this.db._maxKey!==Cr){var v=l.keyPath.slice(0,c.length);return this.where(v).equals(v.map(function(I){return s[I]}))}!l&&xt&&console.warn("The query ".concat(JSON.stringify(s)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(c.join("+"),"]"));var h=this.schema.idxByName;function p(_,I){return be(_,I)===0}var b=c.reduce(function(P,I){var k=P[0],O=P[1],P=h[I],K=s[I];return[k||P,k||!P?kr(O,P&&P.multi?function(C){return C=V(C,I),u(C)&&C.some(function(x){return p(K,x)})}:function(C){return p(K,V(C,I))}):O]},[null,null]),v=b[0],b=b[1];return v?this.where(v.name).equals(s[v.keyPath]).filter(b):l?this.filter(b):this.where(c).equals("")},Te.prototype.filter=function(s){return this.toCollection().and(s)},Te.prototype.count=function(s){return this.toCollection().count(s)},Te.prototype.offset=function(s){return this.toCollection().offset(s)},Te.prototype.limit=function(s){return this.toCollection().limit(s)},Te.prototype.each=function(s){return this.toCollection().each(s)},Te.prototype.toArray=function(s){return this.toCollection().toArray(s)},Te.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Te.prototype.orderBy=function(s){return new this.db.Collection(new this.db.WhereClause(this,u(s)?"[".concat(s.join("+"),"]"):s))},Te.prototype.reverse=function(){return this.toCollection().reverse()},Te.prototype.mapToClass=function(s){var c,l=this.db,h=this.name;function p(){return c!==null&&c.apply(this,arguments)||this}(this.schema.mappedClass=s).prototype instanceof au&&((function(I,k){if(typeof k!="function"&&k!==null)throw new TypeError("Class extends value "+String(k)+" is not a constructor or null");function O(){this.constructor=I}r(I,k),I.prototype=k===null?Object.create(k):(O.prototype=k.prototype,new O)})(p,c=s),Object.defineProperty(p.prototype,"db",{get:function(){return l},enumerable:!1,configurable:!0}),p.prototype.table=function(){return h},s=p);for(var v=new Set,b=s.prototype;b;b=f(b))Object.getOwnPropertyNames(b).forEach(function(I){return v.add(I)});function _(I){if(!I)return I;var k,O=Object.create(s.prototype);for(k in I)if(!v.has(k))try{O[k]=I[k]}catch{}return O}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=_,this.hook("reading",_),s},Te.prototype.defineClass=function(){return this.mapToClass(function(s){d(this,s)})},Te.prototype.add=function(s,c){var l=this,h=this.schema.primKey,p=h.auto,v=h.keyPath,b=s;return v&&p&&(b=Zi(v)(s)),this._trans("readwrite",function(_){return l.core.mutate({trans:_,type:"add",keys:c!=null?[c]:null,values:[b]})}).then(function(_){return _.numFailures?X.reject(_.failures[0]):_.lastResult}).then(function(_){if(v)try{W(s,v,_)}catch{}return _})},Te.prototype.update=function(s,c){return typeof s!="object"||u(s)?this.where(":id").equals(s).modify(c):(s=V(s,this.schema.primKey.keyPath),s===void 0?Be(new se.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(s).modify(c))},Te.prototype.put=function(s,c){var l=this,h=this.schema.primKey,p=h.auto,v=h.keyPath,b=s;return v&&p&&(b=Zi(v)(s)),this._trans("readwrite",function(_){return l.core.mutate({trans:_,type:"put",values:[b],keys:c!=null?[c]:null})}).then(function(_){return _.numFailures?X.reject(_.failures[0]):_.lastResult}).then(function(_){if(v)try{W(s,v,_)}catch{}return _})},Te.prototype.delete=function(s){var c=this;return this._trans("readwrite",function(l){return c.core.mutate({trans:l,type:"delete",keys:[s]})}).then(function(l){return l.numFailures?X.reject(l.failures[0]):void 0})},Te.prototype.clear=function(){var s=this;return this._trans("readwrite",function(c){return s.core.mutate({trans:c,type:"deleteRange",range:iu})}).then(function(c){return c.numFailures?X.reject(c.failures[0]):void 0})},Te.prototype.bulkGet=function(s){var c=this;return this._trans("readonly",function(l){return c.core.getMany({keys:s,trans:l}).then(function(h){return h.map(function(p){return c.hook.reading.fire(p)})})})},Te.prototype.bulkAdd=function(s,c,l){var h=this,p=Array.isArray(c)?c:void 0,v=(l=l||(p?void 0:c))?l.allKeys:void 0;return this._trans("readwrite",function(b){var k=h.schema.primKey,_=k.auto,k=k.keyPath;if(k&&p)throw new se.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbou
43nd keys");if(p&&p.length!==s.length)throw new se.InvalidArgument("Arguments objects and keys must have the same length");var I=s.length,k=k&&_?s.map(Zi(k)):s;return h.core.mutate({trans:b,type:"add",keys:p,values:k,wantResults:v}).then(function(x){var P=x.numFailures,K=x.results,C=x.lastResult,x=x.failures;if(P===0)return v?K:C;throw new Zt("".concat(h.name,".bulkAdd(): ").concat(P," of ").concat(I," operations failed"),x)})})},Te.prototype.bulkPut=function(s,c,l){var h=this,p=Array.isArray(c)?c:void 0,v=(l=l||(p?void 0:c))?l.allKeys:void 0;return this._trans("readwrite",function(b){var k=h.schema.primKey,_=k.auto,k=k.keyPath;if(k&&p)throw new se.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(p&&p.length!==s.length)throw new se.InvalidArgument("Arguments objects and keys must have the same length");var I=s.length,k=k&&_?s.map(Zi(k)):s;return h.core.mutate({trans:b,type:"put",keys:p,values:k,wantResults:v}).then(function(x){var P=x.numFailures,K=x.results,C=x.lastResult,x=x.failures;if(P===0)return v?K:C;throw new Zt("".concat(h.name,".bulkPut(): ").concat(P," of ").concat(I," operations failed"),x)})})},Te.prototype.bulkUpdate=function(s){var c=this,l=this.core,h=s.map(function(b){return b.key}),p=s.map(function(b){return b.changes}),v=[];return this._trans("readwrite",function(b){return l.getMany({trans:b,keys:h,cache:"clone"}).then(function(_){var I=[],k=[];s.forEach(function(P,K){var C=P.key,x=P.changes,T=_[K];if(T){for(var R=0,A=Object.keys(x);R<A.length;R++){var N=A[R],B=x[N];if(N===c.schema.primKey.keyPath){if(be(B,C)!==0)throw new se.Constraint("Cannot update primary key in bulkUpdate()")}else W(T,N,B)}v.push(K),I.push(C),k.push(T)}});var O=I.length;return l.mutate({trans:b,type:"put",keys:I,values:k,updates:{keys:h,changeSpecs:p}}).then(function(P){var K=P.numFailures,C=P.failures;if(K===0)return O;for(var x=0,T=Object.keys(C);x<T.length;x++){var R,A=T[x],N=v[Number(A)];N!=null&&(R=C[A],delete C[A],C[N]=R)}throw new Zt("".concat(c.name,".bulkUpdate(): ").concat(K," of ").concat(O," operations failed"),C)})})})},Te.prototype.bulkDelete=function(s){var c=this,l=s.length;return this._trans("readwrite",function(h){return c.core.mutate({trans:h,type:"delete",keys:s})}).then(function(b){var p=b.numFailures,v=b.lastResult,b=b.failures;if(p===0)return v;throw new Zt("".concat(c.name,".bulkDelete(): ").concat(p," of ").concat(l," operations failed"),b)})},Te);function Te(){}function $n(s){function c(b,_){if(_){for(var I=arguments.length,k=new Array(I-1);--I;)k[I-1]=arguments[I];return l[b].subscribe.apply(null,k),s}if(typeof b=="string")return l[b]}var l={};c.addEventType=v;for(var h=1,p=arguments.length;h<p;++h)v(arguments[h]);return c;function v(b,_,I){if(typeof b!="object"){var k;_=_||rp;var O={subscribers:[],fire:I=I||Re,subscribe:function(P){O.subscribers.indexOf(P)===-1&&(O.subscribers.push(P),O.fire=_(O.fire,P))},unsubscribe:function(P){O.subscribers=O.subscribers.filter(function(K){return K!==P}),O.fire=O.subscribers.reduce(_,I)}};return l[b]=c[b]=O}o(k=b).forEach(function(P){var K=k[P];if(u(K))v(P,k[P][0],k[P][1]);else{if(K!=="asap")throw new se.InvalidArgument("Invalid event config");var C=v(P,Bn,function(){for(var x=arguments.length,T=new Array(x);x--;)T[x]=arguments[x];C.subscribers.forEach(function(R){$(function(){R.apply(null,T)})})})}})}}function qn(s,c){return E(c).from({prototype:s}),c}function Zr(s,c){return!(s.filter||s.algorithm||s.or)&&(c?s.justLimit:!s.replayFilter)}function Ns(s,c){s.filter=kr(s.filter,c)}function Ms(s,c,l){var h=s.replayFilter;s.replayFilter=h?function(){return kr(h(),c())}:c,s.justLimit=l&&!h}function ea(s,c){if(s.isPrimKey)return c.primaryKey;var l=c.getIndexByKeyPath(s.index);if(!l)throw new se.Schema("KeyPath "+s.index+" on object store "+c.name+" is not indexed");return l}function uu(s,c,l){var h=ea(s,c.schema);return c.openCursor({trans:l,values:!s.keysOnly,reverse:s.dir==="prev",unique:!!s.unique,query:{index:h,range:s.range}})}function ta(s,c,l,h){var p=s.replayFilter?kr(s.filter,s.replayFilter()):s.filter;if(s.or){var v={},b=function(_,I,k){var O,P;p&&!p(I,k,function(K){return I.stop(K)},function(K){return I.fail(K)})||((P=""+(O=I.primaryKey))=="[object ArrayBuffer]"&&(P=""+new Uint8Array(O)),y(v,P)||(v[P]=!0,c(_,I,k)))};return Promise.all([s.or._iterate(b,l),lu(uu(s,h,l),s.algorithm,b,!s.keysOnly&&s.valueMapper)])}return lu(uu(s,h,l),kr(s.algorithm,p),c,!s.keysOnly&&s.valueMapper)}function lu(s,c,l,h){var p=Ae(h?function(v,b,_){return l(h(v),b,_)}:l);return s.then(function(v){if(v)return v.start(function(){var b=function(){return v.continue()};c&&!c(v,function(_){return b=_},function(_){v.stop(_),b=Re},function(_){v.fail(_),b=Re})||p(v.value,v,function(_){return b=_}),b()})})}var Lt=Symbol(),Hn=(du.prototype.execute=function(s){if(this.add!==void 0){var c=this.add;if(u(c))return i(i([],u(s)?s:[],!0),c).sort();if(typeof c=="number")return(Number(s)||0)+c;if(typeof c=="bigint")try{return BigInt(s)+c}catch{return BigInt(0)+c}throw new TypeError("Invalid term ".concat(c))}if(this.remove!==void 0){var l=this.remove;if(u(l))return u(s)?s.filter(function(h){return!l.includes(h)}).sort():[];if(typeof l=="number")return Number(s)-l;if(typeof l=="bigint")try{return BigInt(s)-l}catch{return BigInt(0)-l}throw new TypeError("Invalid subtrahend ".concat(l))}return c=(c=this.replacePrefix)===null||c===void 0?void 0:c[0],c&&typeof s=="string"&&s.startsWith(c)?this.replacePrefix[1]+s.substring(c.length):s},du);function du(s){Object.assign(this,s)}var cp=(Ee.prototype._read=function(s,c){var l=this._ctx;return l.error?l.table._trans(null,Be.bind(null,l.error)):l.table._trans("readonly",s).then(c)},Ee.prototype._write=function(s){var c=this._ctx;return c.error?c.table._trans(null,Be.bind(null,c.error)):c.table._trans("readwrite",s,"locked")},Ee.prototype._addAlgorithm=function(s){var c=this._ctx;c.algorithm=kr(c.algorithm,s)},Ee.prototype._iterate=function(s,c){return ta(this._ctx,s,c,this._ctx.table.core)},Ee.prototype.clone=function(s){var c=Object.create(this.constructor.prototype),l=Object.create(this._ctx);return s&&d(l,s),c._ctx=l,c},Ee.prototype.raw=function(){return this._ctx.valueMapper=null,this},Ee.prototype.each=function(s){var c=this._ctx;return this._read(function(l){return ta(c,s,l,c.table.core)})},Ee.prototype.count=function(s){var c=this;return this._read(function(l){var h=c._ctx,p=h.table.core;if(Zr(h,!0))return p.count({trans:l,query:{index:ea(h,p.schema),range:h.range}}).then(function(b){return Math.min(b,h.limit)});var v=0;return ta(h,function(){return++v,!1},l,p).then(function(){return v})}).then(s)},Ee.prototype.sortBy=function(s,c){var l=s.split(".").reverse(),h=l[0],p=l.length-1;function v(I,k){return k?v(I[l[k]],k-1):I[h]}var b=this._ctx.dir==="next"?1:-1;function _(I,k){return be(v(I,p),v(k,p))*b}return this.toArray(function(I){return I.sort(_)}).then(c)},Ee.prototype.toArray=function(s){var c=this;return this._read(function(l){var h=c._ctx;if(h.dir==="next"&&Zr(h,!0)&&0<h.limit){var p=h.valueMapper,v=ea(h,h.table.core.schema);return h.table.core.query({trans:l,limit:h.limit,values:!0,query:{index:v,range:h.range}}).then(function(_){return _=_.result,p?_.map(p):_})}var b=[];return ta(h,function(_){return b.push(_)},l,h.table.core).then(function(){return b})},s)},Ee.prototype.offset=function(s){var c=this._ctx;return s<=0||(c.offset+=s,Zr(c)?Ms(c,function(){var l=s;return function(h,p){return l===0||(l===1?--l:p(function(){h.advance(l),l=0}),!1)}}):Ms(c,function(){var l=s;return function(){return--l<0}})),this},Ee.prototype.limit=function(s){return this._ctx.limit=Math.min(this._ctx.limit,s),Ms(this._ctx,function(){var c=s;return function(l,h,p){return--c<=0&&h(p),0<=c}},!0),this},Ee.prototype.until=function(s,c){return Ns(this._ctx,function(l,h,p){return!s(l.value)||(h(p),c)}),this},Ee.prototype.first=function(s){return this.limit(1).toArray(function(c){return c[0]}).then(s)},Ee.prototype.last=function(s){return this.reverse().first(s)},Ee.prototype.filter=function(s){var c;return Ns(this._ctx,function(l){return s(l.value)}),(c=this._ctx).isMatch=kr(c.isMatch,s),this},Ee.prototype.and=function(s){return this.filter(s)},Ee.prototype.or=function(s){return new this.db.WhereClause(this._ctx.table,s,this)},Ee.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Ee.prototype.desc=function(){return this.reverse()},Ee.prototype.eachKey=function(s){var c=this._ctx;return c.keysOnly=!c.isMatch,this.each(function(l,h){s(h.key,h)})},Ee.prototype.eachUniqueKey=function(s){return this._ctx.unique="unique",this.eachKey(s)},Ee.prototype.eachPrimaryKey=function(s){var c=this._ctx;return c.keysOnly=!c.isMatch,this.each(function(l,h){s(h.primaryKey,h)})},Ee.prototype.keys=function(s){var c=this._ctx;c.keysOnly=!c.isMatch;var l=[];return this.each(function(h,p){l.push(p.key)}).then(function(){return l}).then(s)},Ee.prototype.primaryKeys=function(s){var c=this._ctx;
43if(c.dir==="next"&&Zr(c,!0)&&0<c.limit)return this._read(function(h){var p=ea(c,c.table.core.schema);return c.table.core.query({trans:h,values:!1,limit:c.limit,query:{index:p,range:c.range}})}).then(function(h){return h.result}).then(s);c.keysOnly=!c.isMatch;var l=[];return this.each(function(h,p){l.push(p.primaryKey)}).then(function(){return l}).then(s)},Ee.prototype.uniqueKeys=function(s){return this._ctx.unique="unique",this.keys(s)},Ee.prototype.firstKey=function(s){return this.limit(1).keys(function(c){return c[0]}).then(s)},Ee.prototype.lastKey=function(s){return this.reverse().firstKey(s)},Ee.prototype.distinct=function(){var s=this._ctx,s=s.index&&s.table.schema.idxByName[s.index];if(!s||!s.multi)return this;var c={};return Ns(this._ctx,function(p){var h=p.primaryKey.toString(),p=y(c,h);return c[h]=!0,!p}),this},Ee.prototype.modify=function(s){var c=this,l=this._ctx;return this._write(function(h){var p,v,b;b=typeof s=="function"?s:(p=o(s),v=p.length,function(R){for(var A=!1,N=0;N<v;++N){var B=p[N],L=s[B],q=V(R,B);L instanceof Hn?(W(R,B,L.execute(q)),A=!0):q!==L&&(W(R,B,L),A=!0)}return A});var _=l.table.core,P=_.schema.primaryKey,I=P.outbound,k=P.extractKey,O=200,P=c.db._options.modifyChunkSize;P&&(O=typeof P=="object"?P[_.name]||P["*"]||200:P);function K(R,B){var N=B.failures,B=B.numFailures;x+=R-B;for(var L=0,q=o(N);L<q.length;L++){var G=q[L];C.push(N[G])}}var C=[],x=0,T=[];return c.clone().primaryKeys().then(function(R){function A(B){var L=Math.min(O,R.length-B);return _.getMany({trans:h,keys:R.slice(B,B+L),cache:"immutable"}).then(function(q){for(var G=[],H=[],J=I?[]:null,Y=[],z=0;z<L;++z){var te=q[z],he={value:oe(te),primKey:R[B+z]};b.call(he,he.value,he)!==!1&&(he.value==null?Y.push(R[B+z]):I||be(k(te),k(he.value))===0?(H.push(he.value),I&&J.push(R[B+z])):(Y.push(R[B+z]),G.push(he.value)))}return Promise.resolve(0<G.length&&_.mutate({trans:h,type:"add",values:G}).then(function(pe){for(var me in pe.failures)Y.splice(parseInt(me),1);K(G.length,pe)})).then(function(){return(0<H.length||N&&typeof s=="object")&&_.mutate({trans:h,type:"put",keys:J,values:H,criteria:N,changeSpec:typeof s!="function"&&s,isAdditionalChunk:0<B}).then(function(pe){return K(H.length,pe)})}).then(function(){return(0<Y.length||N&&s===Bs)&&_.mutate({trans:h,type:"delete",keys:Y,criteria:N,isAdditionalChunk:0<B}).then(function(pe){return K(Y.length,pe)})}).then(function(){return R.length>B+L&&A(B+O)})})}var N=Zr(l)&&l.limit===1/0&&(typeof s!="function"||s===Bs)&&{index:l.index,range:l.range};return A(0).then(function(){if(0<C.length)throw new yt("Error modifying one or more objects",C,x,T);return R.length})})})},Ee.prototype.delete=function(){var s=this._ctx,c=s.range;return Zr(s)&&(s.isPrimKey||c.type===3)?this._write(function(l){var h=s.table.core.schema.primaryKey,p=c;return s.table.core.count({trans:l,query:{index:h,range:p}}).then(function(v){return s.table.core.mutate({trans:l,type:"deleteRange",range:p}).then(function(b){var _=b.failures;if(b.lastResult,b.results,b=b.numFailures,b)throw new yt("Could not delete some values",Object.keys(_).map(function(I){return _[I]}),v-b);return v-b})})}):this.modify(Bs)},Ee);function Ee(){}var Bs=function(s,c){return c.value=null};function up(s,c){return s<c?-1:s===c?0:1}function lp(s,c){return c<s?-1:s===c?0:1}function ct(s,c,l){return s=s instanceof fu?new s.Collection(s):s,s._ctx.error=new(l||TypeError)(c),s}function en(s){return new s.Collection(s,function(){return hu("")}).limit(0)}function ra(s,c,l,h){var p,v,b,_,I,k,O,P=l.length;if(!l.every(function(x){return typeof x=="string"}))return ct(s,nu);function K(x){p=x==="next"?function(R){return R.toUpperCase()}:function(R){return R.toLowerCase()},v=x==="next"?function(R){return R.toLowerCase()}:function(R){return R.toUpperCase()},b=x==="next"?up:lp;var T=l.map(function(R){return{lower:v(R),upper:p(R)}}).sort(function(R,A){return b(R.lower,A.lower)});_=T.map(function(R){return R.upper}),I=T.map(function(R){return R.lower}),O=(k=x)==="next"?"":h}K("next"),s=new s.Collection(s,function(){return ir(_[0],I[P-1]+h)}),s._ondirectionchange=function(x){K(x)};
43var C=0;return s._addAlgorithm(function(x,T,R){var A=x.key;if(typeof A!="string")return!1;var N=v(A);if(c(N,I,C))return!0;for(var B=null,L=C;L<P;++L){var q=(function(G,H,J,Y,z,te){for(var he=Math.min(G.length,Y.length),pe=-1,me=0;me<he;++me){var ut=H[me];if(ut!==Y[me])return z(G[me],J[me])<0?G.substr(0,me)+J[me]+J.substr(me+1):z(G[me],Y[me])<0?G.substr(0,me)+Y[me]+J.substr(me+1):0<=pe?G.substr(0,pe)+H[pe]+J.substr(pe+1):null;z(G[me],ut)<0&&(pe=me)}return he<Y.length&&te==="next"?G+J.substr(G.length):he<G.length&&te==="prev"?G.substr(0,J.length):pe<0?null:G.substr(0,pe)+Y[pe]+J.substr(pe+1)})(A,N,_[L],I[L],b,k);q===null&&B===null?C=L+1:(B===null||0<b(B,q))&&(B=q)}return T(B!==null?function(){x.continue(B+O)}:R),!1}),s}function ir(s,c,l,h){return{type:2,lower:s,upper:c,lowerOpen:l,upperOpen:h}}function hu(s){return{type:1,lower:s,upper:s}}var fu=(Object.defineProperty(ze.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),ze.prototype.between=function(s,c,l,h){l=l!==!1,h=h===!0;try{return 0<this._cmp(s,c)||this._cmp(s,c)===0&&(l||h)&&(!l||!h)?en(this):new this.Collection(this,function(){return ir(s,c,!l,!h)})}catch{return ct(this,Ft)}},ze.prototype.equals=function(s){return s==null?ct(this,Ft):new this.Collection(this,function(){return hu(s)})},ze.prototype.above=function(s){return s==null?ct(this,Ft):new this.Collection(this,function(){return ir(s,void 0,!0)})},ze.prototype.aboveOrEqual=function(s){return s==null?ct(this,Ft):new this.Collection(this,function(){return ir(s,void 0,!1)})},ze.prototype.below=function(s){return s==null?ct(this,Ft):new this.Collection(this,function(){return ir(void 0,s,!1,!0)})},ze.prototype.belowOrEqual=function(s){return s==null?ct(this,Ft):new this.Collection(this,function(){return ir(void 0,s)})},ze.prototype.startsWith=function(s){return typeof s!="string"?ct(this,nu):this.between(s,s+Cr,!0,!0)},ze.prototype.startsWithIgnoreCase=function(s){return s===""?this.startsWith(s):ra(this,function(c,l){return c.indexOf(l[0])===0},[s],Cr)},ze.prototype.equalsIgnoreCase=function(s){return ra(this,function(c,l){return c===l[0]},[s],"")},ze.prototype.anyOfIgnoreCase=function(){var s=ne.apply(ve,arguments);return s.length===0?en(this):ra(this,function(c,l){return l.indexOf(c)!==-1},s,"")},ze.prototype.startsWithAnyOfIgnoreCase=function(){var s=ne.apply(ve,arguments);return s.length===0?en(this):ra(this,function(c,l){return l.some(function(h){return c.indexOf(h)===0})},s,Cr)},ze.prototype.anyOf=function(){var s=this,c=ne.apply(ve,arguments),l=this._cmp;try{c.sort(l)}catch{return ct(this,Ft)}if(c.length===0)return en(this);var h=new this.Collection(this,function(){return ir(c[0],c[c.length-1])});h._ondirectionchange=function(v){l=v==="next"?s._ascending:s._descending,c.sort(l)};var p=0;return h._addAlgorithm(function(v,b,_){for(var I=v.key;0<l(I,c[p]);)if(++p===c.length)return b(_),!1;return l(I,c[p])===0||(b(function(){v.continue(c[p])}),!1)}),h},ze.prototype.notEqual=function(s){return this.inAnyRange([[-1/0,s],[s,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},ze.prototype.noneOf=function(){var s=ne.apply(ve,arguments);if(s.length===0)return new this.Collection(this);try{s.sort(this._ascending)}catch{return ct(this,Ft)}var c=s.reduce(function(l,h){return l?l.concat([[l[l.length-1][1],h]]):[[-1/0,h]]},null);return c.push([s[s.length-1],this.db._maxKey]),this.inAnyRange(c,{includeLowers:!1,includeUppers:!1})},ze.prototype.inAnyRange=function(A,c){var l=this,h=this._cmp,p=this._ascending,v=this._descending,b=this._min,_=this._max;if(A.length===0)return en(this);if(!A.every(function(N){return N[0]!==void 0&&N[1]!==void 0&&p(N[0],N[1])<=0}))return ct(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",se.InvalidArgument);var I=!c||c.includeLowers!==!1,k=c&&c.includeUppers===!0,O,P=p;function K(N,B){return P(N[0],B[0])}try{(O=A.reduce(function(N,B){for(var L=0,q=N.length;L<q;++L){var G=N[L];if(h(B[0],G[1])<0&&0<h(B[1],G[0])){G[0]=b(G[0],B[0]),G[1]=_(G[1],B[1]);break}}return L===q&&N.push(B),N},[])).sort(K)}catch{return ct(this,Ft)}var C=0,x=k?function(N){return 0<p(N,O[C][1])}:function(N){return 0<=p(N,O[C][1])},T=I?function(N){return 0<v(N,O[C][0])}:function(N){return 0<=v(N,O[C][0])},R=x,A=new this.Collection(this,function(){return ir(O[0][0],O[O.length-1][1],!I,!k)});return A._ondirectionchange=function(N){P=N==="next"?(R=x,p):(R=T,v),O.sort(K)},A._addAlgorithm(function(N,B,L){for(var q,G=N.key;R(G);)if(++C===O.length)return B(L),!1;return!x(q=G)&&!T(q)||(l._cmp(G,O[C][1])===0||l._cmp(G,O[C][0])===0||B(function(){P===p?N.continue(O[C][0]):N.continue(O[C][1])}),!1)}),A},ze.prototype.startsWithAnyOf=function(){var s=ne.apply(ve,arguments);return s.every(function(c){return typeof c=="string"})?s.length===0?en(this):this.inAnyRange(s.map(function(c){return[c,c+Cr]}
43)):ct(this,"startsWithAnyOf() only works with strings")},ze);function ze(){}function Ot(s){return Ae(function(c){return Jn(c),s(c.target.error),!1})}function Jn(s){s.stopPropagation&&s.stopPropagation(),s.preventDefault&&s.preventDefault()}var jn="storagemutated",Fs="x-storagemutated-1",ar=$n(null,jn),dp=(Tt.prototype._lock=function(){return j(!ae.global),++this._reculock,this._reculock!==1||ae.global||(ae.lockOwnerFor=this),this},Tt.prototype._unlock=function(){if(j(!ae.global),--this._reculock==0)for(ae.global||(ae.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var s=this._blockedFuncs.shift();try{Ir(s[1],s[0])}catch{}}return this},Tt.prototype._locked=function(){return this._reculock&&ae.lockOwnerFor!==this},Tt.prototype.create=function(s){var c=this;if(!this.mode)return this;var l=this.db.idbdb,h=this.db._state.dbOpenError;if(j(!this.idbtrans),!s&&!l)switch(h&&h.name){case"DatabaseClosedError":throw new se.DatabaseClosed(h);case"MissingAPIError":throw new se.MissingAPI(h.message,h);default:throw new se.OpenFailed(h)}if(!this.active)throw new se.TransactionInactive;return j(this._completion._state===null),(s=this.idbtrans=s||(this.db.core||l).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Ae(function(p){Jn(p),c._reject(s.error)}),s.onabort=Ae(function(p){Jn(p),c.active&&c._reject(new se.Abort(s.error)),c.active=!1,c.on("abort").fire(p)}),s.oncomplete=Ae(function(){c.active=!1,c._resolve(),"mutatedParts"in s&&ar.storagemutated.fire(s.mutatedParts)}),this},Tt.prototype._promise=function(s,c,l){var h=this;if(s==="readwrite"&&this.mode!=="readwrite")return Be(new se.ReadOnly("Transaction is readonly"));if(!this.active)return Be(new se.TransactionInactive);if(this._locked())return new X(function(v,b){h._blockedFuncs.push([function(){h._promise(s,c,l).then(v,b)},ae])});if(l)return tr(function(){var v=new X(function(b,_){h._lock();var I=c(b,_,h);I&&I.then&&I.then(b,_)});return v.finally(function(){return h._unlock()}),v._lib=!0,v});var p=new X(function(v,b){var _=c(v,b,h);_&&_.then&&_.then(v,b)});return p._lib=!0,p},Tt.prototype._root=function(){return this.parent?this.parent._root():this},Tt.prototype.waitFor=function(s){var c,l=this._root(),h=X.resolve(s);l._waitingFor?l._waitingFor=l._waitingFor.then(function(){return h}):(l._waitingFor=h,l._waitingQueue=[],c=l.idbtrans.objectStore(l.storeNames[0]),(function v(){for(++l._spinCount;l._waitingQueue.length;)l._waitingQueue.shift()();l._waitingFor&&(c.get(-1/0).onsuccess=v)})());var p=l._waitingFor;return new X(function(v,b){h.then(function(_){return l._waitingQueue.push(Ae(v.bind(null,_)))},function(_){return l._waitingQueue.push(Ae(b.bind(null,_)))}).finally(function(){l._waitingFor===p&&(l._waitingFor=null)})})},Tt.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new se.Abort))},Tt.prototype.table=function(s){var c=this._memoizedTables||(this._memoizedTables={});if(y(c,s))return c[s];var l=this.schema[s];if(!l)throw new se.NotFound("Table "+s+" not part of transaction");return l=new this.db.Table(s,l,this),l.core=this.db.core.table(s),c[s]=l},Tt);function Tt(){}function Ls(s,c,l,h,p,v,b){return{name:s,keyPath:c,unique:l,multi:h,auto:p,compound:v,src:(l&&!b?"&":"")+(h?"*":"")+(p?"++":"")+pu(c)}}function pu(s){return typeof s=="string"?s:s?"["+[].join.call(s,"+")+"]":""}function Us(s,c,l){return{name:s,primKey:c,indexes:l,mappedClass:null,idxByName:(h=function(p){return[p.name,p]},l.reduce(function(p,v,b){return b=h(v,b),b&&(p[b[0]]=b[1]),p},{}))};var h}var zn=function(s){try{return s.only([[]]),zn=function(){return[[]]},[[]]}catch{return zn=function(){return Cr},Cr}};function Ws(s){return s==null?function(){}:typeof s=="string"?(c=s).split(".").length===1?function(l){return l[c]}:function(l){return V(l,c)}:function(l){return V(l,s)};var c}function mu(s){return[].slice.call(s)}var hp=0;function Gn(s){return s==null?":id":typeof s=="string"?s:"[".concat(s.join("+"),"]")}function fp(s,c,I){function h(R){if(R.type===3)return null;if(R.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var C=R.lower,x=R.upper,T=R.lowerOpen,R=R.upperOpen;return C===void 0?x===void 0?null:c.upperBound(x,!!R):x===void 0?c.lowerBound(C,!!T):c.bound(C,x,!!T,!!R)}function p(K){var C,x=K.name;return{name:x,schema:K,mutate:function(T){var R=T.trans,A=T.type,N=T.keys,B=T.values,L=T.range;return new Promise(function(q,G){q=Ae(q);var H=R.objectStore(x),J=H.keyPath==null,Y=A==="put"||A==="add";if(!Y&&A!=="delete"&&A!=="deleteRange")throw new Error("Invalid operation type: "+A);var z,te=(N||B||{length:1}).length;if(N&&B&&N.length!==B.length)throw new Error("Given keys array must have same length as given values array.");if(te===0)return q({numFailures:0,failures:{},results:[],lastResult:void 0});function he(tt){++ut,Jn(tt)}var pe=[],me=[],ut=0;if(A==="deleteRange"){if(L.type===4)return q({numFailures:ut,failures:me,results:[],lastResult:void 0});L.type===3?pe.push(z=H.clear()):pe.push(z=H.delete(h(L)))}else{var J=Y?J?[B,N]:[B,null]:[N,null],le=J[0],Qe=J[1];if(Y)for(var Xe=0;Xe<te;++Xe)pe.push(z=Qe&&Qe[Xe]!==void 0?H[A](le[Xe],Qe[Xe]):H[A](le[Xe])),z.onerror=he;else for(Xe=0;Xe<te;++Xe)pe.push(z=H[A](le[Xe])),z.onerror=he}function ma(tt){tt=tt.target.result,pe.forEach(function(xr,ao){return xr.error!=null&&(me[ao]=xr.error)}),q({numFailures:ut,failures:me,results:A==="delete"?N:pe.map(function(xr){return xr.result}),lastResult:tt})}z.onerror=function(tt){he(tt),ma(tt)},z.onsuccess=ma})},getMany:function(T){var R=T.trans,A=T.keys;return new Promise(function(N,B){N=Ae(N);for(var L,q=R.objectStore(x),G=A.length,H=new Array(G),J=0,Y=0,z=function(pe){pe=pe.target,H[pe._pos]=pe.result,++Y===J&&N(H)},te=Ot(B),he=0;he<G;++he)A[he]!=null&&((L=q.get(A[he]))._pos=he,L.onsuccess=z,L.onerror=te,++J);J===0&&N(H)})},get:function(T){var R=T.trans,A=T.key;return new Promise(function(N,B){N=Ae(N);var L=R.objectStore(x).get(A);L.onsuccess=function(q){return N(q.target.result)},L.onerror=Ot(B)})},query:(C=k,function(T){return new Promise(function(R,A){R=Ae(R);var N,B,L,J=T.trans,q=T.values,G=T.limit,z=T.query,H=G===1/0?void 0:G,Y=z.index,z=z.range,J=J.objectStore(x),Y=Y.isPrimaryKey?J:J.index(Y.n
43ame),z=h(z);if(G===0)return R({result:[]});C?((H=q?Y.getAll(z,H):Y.getAllKeys(z,H)).onsuccess=function(te){return R({result:te.target.result})},H.onerror=Ot(A)):(N=0,B=!q&&"openKeyCursor"in Y?Y.openKeyCursor(z):Y.openCursor(z),L=[],B.onsuccess=function(te){var he=B.result;return he?(L.push(q?he.value:he.primaryKey),++N===G?R({result:L}):void he.continue()):R({result:L})},B.onerror=Ot(A))})}),openCursor:function(T){var R=T.trans,A=T.values,N=T.query,B=T.reverse,L=T.unique;return new Promise(function(q,G){q=Ae(q);var Y=N.index,H=N.range,J=R.objectStore(x),J=Y.isPrimaryKey?J:J.index(Y.name),Y=B?L?"prevunique":"prev":L?"nextunique":"next",z=!A&&"openKeyCursor"in J?J.openKeyCursor(h(H),Y):J.openCursor(h(H),Y);z.onerror=Ot(G),z.onsuccess=Ae(function(te){var he,pe,me,ut,le=z.result;le?(le.___id=++hp,le.done=!1,he=le.continue.bind(le),pe=(pe=le.continuePrimaryKey)&&pe.bind(le),me=le.advance.bind(le),ut=function(){throw new Error("Cursor not stopped")},le.trans=R,le.stop=le.continue=le.continuePrimaryKey=le.advance=function(){throw new Error("Cursor not started")},le.fail=Ae(G),le.next=function(){var Qe=this,Xe=1;return this.start(function(){return Xe--?Qe.continue():Qe.stop()}).then(function(){return Qe})}
43,le.start=function(Qe){function Xe(){if(z.result)try{Qe()}catch(tt){le.fail(tt)}else le.done=!0,le.start=function(){throw new Error("Cursor behind last entry")},le.stop()}var ma=new Promise(function(tt,xr){tt=Ae(tt),z.onerror=Ot(xr),le.fail=xr,le.stop=function(ao){le.stop=le.continue=le.continuePrimaryKey=le.advance=ut,tt(ao)}});return z.onsuccess=Ae(function(tt){z.onsuccess=Xe,Xe()}),le.continue=he,le.continuePrimaryKey=pe,le.advance=me,Xe(),ma},q(le)):q(null)},G)})},count:function(T){var R=T.query,A=T.trans,N=R.index,B=R.range;return new Promise(function(L,q){var G=A.objectStore(x),H=N.isPrimaryKey?G:G.index(N.name),G=h(B),H=G?H.count(G):H.count();H.onsuccess=Ae(function(J){return L(J.target.result)}),H.onerror=Ot(q)})}}}var v,b,_,O=(b=I,_=mu((v=s).objectStoreNames),{schema:{name:v.name,tables:_.map(function(K){return b.objectStore(K)}).map(function(K){var C=K.keyPath,R=K.autoIncrement,x=u(C),T={},R={name:K.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:C==null,compound:x,keyPath:C,autoIncrement:R,unique:!0,extractKey:Ws(C)},indexes:mu(K.indexNames).map(function(A){return K.index(A)}).map(function(L){var N=L.name,B=L.unique,q=L.multiEntry,L=L.keyPath,q={name:N,compound:u(L),keyPath:L,unique:B,multiEntry:q,extractKey:Ws(L)};return T[Gn(L)]=q}),getIndexByKeyPath:function(A){return T[Gn(A)]}};return T[":id"]=R.primaryKey,C!=null&&(T[Gn(C)]=R.primaryKey),R})},hasGetAll:0<_.length&&"getAll"in b.objectStore(_[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}),I=O.schema,k=O.hasGetAll,O=I.tables.map(p),P={};return O.forEach(function(K){return P[K.name]=K}),{stack:"dbcore",transaction:s.transaction.bind(s),table:function(K){if(!P[K])throw new Error("Table '".concat(K,"' not found"));return P[K]},MIN_KEY:-1/0,MAX_KEY:zn(c),schema:I}}function pp(s,c,l,h){var p=l.IDBKeyRange;return l.indexedDB,{dbcore:(h=fp(c,p,h),s.dbcore.reduce(function(v,b){return b=b.create,n(n({},v),b(v))},h))}}function na(s,h){var l=h.db,h=pp(s._middlewares,l,s._deps,h);s.core=h.dbcore,s.tables.forEach(function(p){var v=p.name;s.core.schema.tables.some(function(b){return b.name===v})&&(p.core=s.core.table(v),s[v]instanceof s.Table&&(s[v].core=p.core))})}function ia(s,c,l,h){l.forEach(function(p){var v=h[p];c.forEach(function(b){var _=(function I(k,O){return D(k,O)||(k=f(k))&&I(k,O)})(b,p);(!_||"value"in _&&_.value===void 0)&&(b===s.Transaction.prototype||b instanceof s.Transaction?S(b,p,{get:function(){return this.table(p)},set:function(I){w(this,p,{value:I,writable:!0,configurable:!0,enumerable:!0})}}):b[p]=new s.Table(p,v))})})}function $s(s,c){c.forEach(function(l){for(var h in l)l[h]instanceof s.Table&&delete l[h]})}function mp(s,c){return s._cfg.version-c._cfg.version}function yp(s,c,l,h){var p=s._dbSchema;l.objectStoreNames.contains("$meta")&&!p.$meta&&(p.$meta=Us("$meta",vu("")[0],[]),s._storeNames.push("$meta"));var v=s._createTransaction("readwrite",s._storeNames,p);v.create(l),v._completion.catch(h);var b=v._reject.bind(v),_=ae.transless||ae;tr(function(){return ae.trans=v,ae.transless=_,c!==0?(na(s,l),k=c,((I=v).storeNames.includes("$meta")?I.table("$meta").get("version").then(function(O){return O??k}):X.resolve(k)).then(function(O){return K=O,C=v,x=l,T=[],O=(P=s)._versions,R=P._dbSchema=sa(0,P.idbdb,x),(O=O.filter(function(A){return A._cfg.version>=K})).length!==0?(O.forEach(function(A){T.push(function(){var N=R,B=A._cfg.dbschema;oa(P,N,x),oa(P,B,x),R=P._dbSchema=B;var L=qs(N,B);L.add.forEach(function(Y){Hs(x,Y[0],Y[1].primKey,Y[1].indexes)}),L.change.forEach(function(Y){if(Y.recreate)throw new se.Upgrade("Not yet support for changing primary key");var z=x.objectStore(Y.name);Y.add.forEach(function(te){return aa(z,te)}),Y.change.forEach(function(te){z.deleteIndex(te.name),aa(z,te)}),Y.del.forEach(function(te){return z.deleteIndex(te)})});var q=A._cfg.contentUpgrade;if(q&&A._cfg.version>K){na(P,x),C._memoizedTables={};var G=ie(B);L.del.forEach(function(Y){G[Y]=N[Y]}),$s(P,[P.Transaction.prototype]),ia(P,[P.Transaction.prototype],o(G),G),C.schema=G;var H,J=we(q);return J&&Qr(),L=X.follow(function(){var Y;(H=q(C))&&J&&(Y=rr.bind(null,null),H.then(Y,Y))}),H&&typeof H.then=="function"?X.resolve(H):L.then(function(){return H})}}),T.push(function(N){var B,L,q=A._cfg.dbschema;
43B=q,L=N,[].slice.call(L.db.objectStoreNames).forEach(function(G){return B[G]==null&&L.db.deleteObjectStore(G)}),$s(P,[P.Transaction.prototype]),ia(P,[P.Transaction.prototype],P._storeNames,P._dbSchema),C.schema=P._dbSchema}),T.push(function(N){P.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(P.idbdb.version/10)===A._cfg.version?(P.idbdb.deleteObjectStore("$meta"),delete P._dbSchema.$meta,P._storeNames=P._storeNames.filter(function(B){return B!=="$meta"})):N.objectStore("$meta").put(A._cfg.version,"version"))})}),(function A(){return T.length?X.resolve(T.shift()(C.idbtrans)).then(A):X.resolve()})().then(function(){yu(R,x)})):X.resolve();var P,K,C,x,T,R}).catch(b)):(o(p).forEach(function(O){Hs(l,O,p[O].primKey,p[O].indexes)}),na(s,l),void X.follow(function(){return s.on.populate.fire(v)}).catch(b));var I,k})}function vp(s,c){yu(s._dbSchema,c),c.db.version%10!=0||c.objectStoreNames.contains("$meta")||c.db.createObjectStore("$meta").add(Math.ceil(c.db.version/10-1),"version");var l=sa(0,s.idbdb,c);oa(s,s._dbSchema,c);for(var h=0,p=qs(l,s._dbSchema).change;h<p.length;h++){var v=(function(b){if(b.change.length||b.recreate)return console.warn("Unable to patch indexes of table ".concat(b.name," because it has changes on the type of index or primary key.")),{value:void 0};var _=c.objectStore(b.name);b.add.forEach(function(I){xt&&console.debug("Dexie upgrade patch: Creating missing index ".concat(b.name,".").concat(I.src)),aa(_,I)})})(p[h]);if(typeof v=="object")return v.value}}function qs(s,c){var l,h={del:[],add:[],change:[]};for(l in s)c[l]||h.del.push(l);for(l in c){var p=s[l],v=c[l];if(p){var b={name:l,def:v,recreate:!1,del:[],add:[],change:[]};if(""+(p.primKey.keyPath||"")!=""+(v.primKey.keyPath||"")||p.primKey.auto!==v.primKey.auto)b.recreate=!0,h.change.push(b);else{var _=p.idxByName,I=v.idxByName,k=void 0;for(k in _)I[k]||b.del.push(k);for(k in I){var O=_[k],P=I[k];O?O.src!==P.src&&b.change.push(P):b.add.push(P)}(0<b.del.length||0<b.add.length||0<b.change.length)&&h.change.push(b)}}else h.add.push([l,v])}return h}function Hs(s,c,l,h){var p=s.db.createObjectStore(c,l.keyPath?{keyPath:l.keyPath,autoIncrement:l.auto}:{autoIncrement:l.auto});return h.forEach(function(v){return aa(p,v)}),p}
43function yu(s,c){o(s).forEach(function(l){c.db.objectStoreNames.contains(l)||(xt&&console.debug("Dexie: Creating missing table",l),Hs(c,l,s[l].primKey,s[l].indexes))})}function aa(s,c){s.createIndex(c.name,c.keyPath,{unique:c.unique,multiEntry:c.multi})}function sa(s,c,l){var h={};return U(c.objectStoreNames,0).forEach(function(p){for(var v=l.objectStore(p),b=Ls(pu(k=v.keyPath),k||"",!0,!1,!!v.autoIncrement,k&&typeof k!="string",!0),_=[],I=0;I<v.indexNames.length;++I){var O=v.index(v.indexNames[I]),k=O.keyPath,O=Ls(O.name,k,!!O.unique,!!O.multiEntry,!1,k&&typeof k!="string",!1);_.push(O)}h[p]=Us(p,b,_)}),h}function oa(s,c,l){for(var h=l.db.objectStoreNames,p=0;p<h.length;++p){var v=h[p],b=l.objectStore(v);s._hasGetAll="getAll"in b;for(var _=0;_<b.indexNames.length;++_){var I=b.indexNames[_],k=b.index(I).keyPath,O=typeof k=="string"?k:"["+U(k).join("+")+"]";!c[v]||(k=c[v].idxByName[O])&&(k.name=I,delete c[v].idxByName[O],c[v].idxByName[I]=k)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&a.WorkerGlobalScope&&a instanceof a.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(s._hasGetAll=!1)}function vu(s){return s.split(",").map(function(c,l){var h=(c=c.trim()).replace(/([&*]|\+\+)/g,""),p=/^\[/.test(h)?h.match(/^\[(.*)\]$/)[1].split("+"):h;return Ls(h,p||null,/\&/.test(c),/\*/.test(c),/\+\+/.test(c),u(p),l===0)})}
43var gp=(ca.prototype._parseStoresSpec=function(s,c){o(s).forEach(function(l){if(s[l]!==null){var h=vu(s[l]),p=h.shift();if(p.unique=!0,p.multi)throw new se.Schema("Primary key cannot be multi-valued");h.forEach(function(v){if(v.auto)throw new se.Schema("Only primary key can be marked as autoIncrement (++)");if(!v.keyPath)throw new se.Schema("Index must have a name and cannot be an empty string")}),c[l]=Us(l,p,h)}})},ca.prototype.stores=function(l){var c=this.db;this._cfg.storesSource=this._cfg.storesSource?d(this._cfg.storesSource,l):l;var l=c._versions,h={},p={};return l.forEach(function(v){d(h,v._cfg.storesSource),p=v._cfg.dbschema={},v._parseStoresSpec(h,p)}),c._dbSchema=p,$s(c,[c._allTables,c,c.Transaction.prototype]),ia(c,[c._allTables,c,c.Transaction.prototype,this._cfg.tables],o(p),p),c._storeNames=o(p),this},ca.prototype.upgrade=function(s){return this._cfg.contentUpgrade=Ps(this._cfg.contentUpgrade||Re,s),this},ca);function ca(){}function Js(s,c){var l=s._dbNamesDB;return l||(l=s._dbNamesDB=new Ut(Xi,{addons:[],indexedDB:s,IDBKeyRange:c})).version(1).stores({dbnames:"name"}),l.table("dbnames")}function js(s){return s&&typeof s.databases=="function"}function zs(s){return tr(function(){return ae.letThrough=!0,s()})}function Gs(s){return!("from"in s)}var Ye=function(s,c){if(!this){var l=new Ye;return s&&"d"in s&&d(l,s),l}d(this,arguments.length?{d:1,from:s,to:1<arguments.length?c:s}:{d:0})};function Vn(s,c,l){var h=be(c,l);if(!isNaN(h)){if(0<h)throw RangeError();if(Gs(s))return d(s,{from:c,to:l,d:1});var p=s.l,h=s.r;if(be(l,s.from)<0)return p?Vn(p,c,l):s.l={from:c,to:l,d:1,l:null,r:null},wu(s);if(0<be(c,s.to))return h?Vn(h,c,l):s.r={from:c,to:l,d:1,l:null,r:null},wu(s);be(c,s.from)<0&&(s.from=c,s.l=null,s.d=h?h.d+1:1),0<be(l,s.to)&&(s.to=l,s.r=null,s.d=s.l?s.l.d+1:1),l=!s.r,p&&!s.l&&Yn(s,p),h&&l&&Yn(s,h)}}function Yn(s,c){Gs(c)||(function l(h,I){var v=I.from,b=I.to,_=I.l,I=I.r;Vn(h,v,b),_&&l(h,_),I&&l(h,I)})(s,c)}function gu(s,c){var l=ua(c),h=l.next();if(h.done)return!1;for(var p=h.value,v=ua(s),b=v.next(p.from),_=b.value;!h.done&&!b.done;){if(be(_.from,p.to)<=0&&0<=be(_.to,p.from))return!0;be(p.from,_.from)<0?p=(h=l.next(_.from)).value:_=(b=v.next(p.from)).value}return!1}function ua(s){var c=Gs(s)?null:{s:0,n:s};return{next:function(l){for(var h=0<arguments.length;c;)switch(c.s){case 0:if(c.s=1,h)for(;c.n.l&&be(l,c.n.from)<0;)c={up:c,n:c.n.l,s:1};else for(;c.n.l;)c={up:c,n:c.n.l,s:1};case 1:if(c.s=2,!h||be(l,c.n.to)<=0)return{value:c.n,done:!1};case 2:if(c.n.r){c.s=3,c={up:c,n:c.n.r,s:0};continue}case 3:c=c.up}return{done:!0}}}}function wu(s){var c,l,h=(((c=s.r)===null||c===void 0?void 0:c.d)||0)-(((l=s.l)===null||l===void 0?void 0:l.d)||0),p=1<h?"r":h<-1?"l":"";p&&(c=p=="r"?"l":"r",l=n({},s),h=s[p],s.from=h.from,s.to=h.to,s[p]=h[p],l[p]=h[c],(s[c]=l).d=bu(l)),s.d=bu(s)}function bu(l){var c=l.r,l=l.l;return(c?l?Math.max(c.d,l.d):c.d:l?l.d:0)+1}function la(s,c){return o(c).forEach(function(l){s[l]?Yn(s[l],c[l]):s[l]=(function h(p){var v,b,_={};for(v in p)y(p,v)&&(b=p[v],_[v]=!b||typeof b!="object"||ue.has(b.constructor)?b:h(b));return _})(c[l])}),s}function Vs(s,c){return s.all||c.all||Object.keys(s).some(function(l){return c[l]&&gu(c[l],s[l])})}g(Ye.prototype,((vt={add:function(s){return Yn(this,s),this},addKey:function(s){return Vn(this,s,s),this},addKeys:function(s){var c=this;return s.forEach(function(l){return Vn(c,l,l)}),this},hasKey:function(s){var c=ua(this).next(s).value;return c&&be(c.from,s)<=0&&0<=be(c.to,s)}})[Je]=function(){return ua(this)},vt));var Rr={},Ys={},Qs=!1;function da(s){la(Ys,s),Qs||(Qs=!0,setTimeout(function(){Qs=!1,Xs(Ys,!(Ys={}))},0))}function Xs(s,c){c===void 0&&(c=!1);var l=new Set;if(s.all)for(var h=0,p=Object.values(Rr);h<p.length;h++)Su(b=p[h],s,l,c);else for(var v in s){var b,_=/^idb\:\/\/(.*)\/(.*)\//.exec(v);_&&(v=_[1],_=_[2],(b=Rr["idb://".concat(v,"/").concat(_)])&&Su(b,s,l,c))}l.forEach(function(I){return I()})}function Su(s,c,l,h){for(var p=[],v=0,b=Object.entries(s.queries.query);v<b.length;v++){for(var _=b[v],I=_[0],k=[],O=0,P=_[1];O<P.length;O++){var K=P[O];
43Vs(c,K.obsSet)?K.subscribers.forEach(function(R){return l.add(R)}):h&&k.push(K)}h&&p.push([I,k])}if(h)for(var C=0,x=p;C<x.length;C++){var T=x[C],I=T[0],k=T[1];s.queries.query[I]=k}}function wp(s){var c=s._state,l=s._deps.indexedDB;if(c.isBeingOpened||s.idbdb)return c.dbReadyPromise.then(function(){return c.dbOpenError?Be(c.dbOpenError):s});c.isBeingOpened=!0,c.dbOpenError=null,c.openComplete=!1;var h=c.openCanceller,p=Math.round(10*s.verno),v=!1;function b(){if(c.openCanceller!==h)throw new se.DatabaseClosed("db.open() was cancelled")}function _(){return new X(function(K,C){if(b(),!l)throw new se.MissingAPI;var x=s.name,T=c.autoSchema||!p?l.open(x):l.open(x,p);if(!T)throw new se.MissingAPI;T.onerror=Ot(C),T.onblocked=Ae(s._fireOnBlocked),T.onupgradeneeded=Ae(function(R){var A;O=T.transaction,c.autoSchema&&!s._options.allowEmptyDB?(T.onerror=Jn,O.abort(),T.result.close(),(A=l.deleteDatabase(x)).onsuccess=A.onerror=Ae(function(){C(new se.NoSuchDatabase("Database ".concat(x," doesnt exist")))})):(O.onerror=Ot(C),R=R.oldVersion>Math.pow(2,62)?0:R.oldVersion,P=R<1,s.idbdb=T.result,v&&vp(s,O),yp(s,R/10,O,C))},C),T.onsuccess=Ae(function(){O=null;var R,A,N,B,L,q=s.idbdb=T.result,G=U(q.objectStoreNames);if(0<G.length)try{var H=q.transaction((B=G).length===1?B[0]:B,"readonly");if(c.autoSchema)A=q,N=H,(R=s).verno=A.version/10,N=R._dbSchema=sa(0,A,N),R._storeNames=U(A.objectStoreNames,0),ia(R,[R._allTables],o(N),N);else if(oa(s,s._dbSchema,H),((L=qs(sa(0,(L=s).idbdb,H),L._dbSchema)).add.length||L.change.some(function(J){return J.add.length||J.change.length}))&&!v)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."),q.close(),p=q.version+1,v=!0,K(_());na(s,H)}catch{}Xr.push(s),q.onversionchange=Ae(function(J){c.vcFired=!0,s.on("versionchange").fire(J)}),q.onclose=Ae(function(J){s.on("close").fire(J)}),P&&(L=s._deps,H=x,q=L.indexedDB,L=L.IDBKeyRange,js(q)||H===Xi||Js(q,L).put({name:H}).catch(Re)),K()},C)}).catch(function(K){switch(K==null?void 0:K.name){case"UnknownError":if(0<c.PR1398_maxLoop)return c.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),_();break;case"VersionError":if(0<p)return p=0,_()}return X.reject(K)})}var I,k=c.dbReadyResolve,O=null,P=!1;return X.race([h,(typeof navigator>"u"?X.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(K){function C(){return indexedDB.databases().finally(K)}I=setInterval(C,100),C()}).finally(function(){return clearInterval(I)}):Promise.resolve()).then(_)]).then(function(){return b(),c.onReadyBeingFired=[],X.resolve(zs(function(){return s.on.ready.fire(s.vip)})).then(function K(){if(0<c.onReadyBeingFired.length){var C=c.onReadyBeingFired.reduce(Ps,Re);return c.onReadyBeingFired=[],X.resolve(zs(function(){return C(s.vip)})).then(K)}})}).finally(function(){c.openCanceller===h&&(c.onReadyBeingFired=null,c.isBeingOpened=!1)}).catch(function(K){c.dbOpenError=K;try{O&&O.abort()}catch{}return h===c.openCanceller&&s._close(),Be(K)}).finally(function(){c.openComplete=!0,k()}).then(function(){var K;return P&&(K={},s.tables.forEach(function(C){C.schema.indexes.forEach(function(x){x.name&&(K["idb://".concat(s.name,"/").concat(C.name,"/").concat(x.name)]=new Ye(-1/0,[[[]]]))}),K["idb://".concat(s.name,"/").concat(C.name,"/")]=K["idb://".concat(s.name,"/").concat(C.name,"/:dels")]=new Ye(-1/0,[[[]]])}),ar(jn).fire(K),Xs(K,!0)),s})}function Zs(s){function c(v){return s.next(v)}var l=p(c),h=p(function(v){return s.throw(v)});function p(v){return function(I){var _=v(I),I=_.value;return _.done?I:I&&typeof I.then=="function"?I.then(l,h):u(I)?Promise.all(I).then(l,h):l(I)}}return p(c)()}function ha(s,c,l){for(var h=u(s)?s.slice():[s],p=0;p<l;++p)h.push(c);return h}var bp={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(s){return n(n({},s),{table:function(c){var l=s.table(c),h=l.schema,p={},v=[];function b(P,K,C){var x=Gn(P),T=p[x]=p[x]||[],R=P==null?0:typeof P=="string"?1:P.length,A=0<K,A=n(n({},C),{name:A?"".concat(x,"(virtual-from:").concat(C.name,")"):C.name,lowLevelIndex:C,isVirtual:A,keyTail:K,keyLength:R,extractKey:Ws(P),unique:!A&&C.unique});return T.push(A),A.isPrimaryKey||v.push(A),1<R&&b(R===2?P[0]:P.slice(0,R-1),K+1,C),T.sort(function(N,B){return N.keyTail-B.keyTail}),A}c=b(h.primaryKey.keyPath,0,h.primaryKey),p[":id"]=[c];for(var _=0,I=h.indexes;_<I.length;_++){var k=I[_];b(k.keyPath,0,k)}function O(P){var K,C=P.query.index;return C.isVirtual?n(n({},P),{query:{index:C.lowLevelIndex,range:(K=P.query.range,C=C.keyTail,{type:K.type===1?2:K.type,lower:ha(K.lower,K.lowerOpen?s.MAX_KEY:s.MIN_KEY,C),lowerOpen:!0,upper:ha(K.upper,K.upperOpen?s.MIN_KEY:s.MAX_KEY,C),upperOpen:!0})}}):P}return n(n({},l),{schema:n(n({},h),{primaryKey:c,indexes:v,getIndexByKeyPath:function(P){return(P=p[Gn(P)])&&P[0]}}),count:function(P){return l.count(O(P))},query:function(P){return l.query(O(P))},openCursor:function(P){var K=P.query.index,C=K.keyTail,x=K.isVirtual,T=K.keyLength;return x?l.openCursor(O(P)).then(function(A){return A&&R(A)}):l.openCursor(P);function R(A){return Object.create(A,{continue:{value:function(N){N!=null?A.continue(ha(N,P.reverse?s.MAX_KEY:s.MIN_KEY,C)):P.unique?A.continue(A.key.slice(0,T).concat(P.reverse?s.MIN_KEY:s.MAX_KEY,C)):A.continue()}},continuePrimaryKey:{value:function(N,B){A.continuePrimaryKey(ha(N,s.MAX_KEY,C),B)}},primaryKey:{get:function(){return A.primaryKey}}
43,key:{get:function(){var N=A.key;return T===1?N[0]:N.slice(0,T)}},value:{get:function(){return A.value}}})}}})}})}};function eo(s,c,l,h){return l=l||{},h=h||"",o(s).forEach(function(p){var v,b,_;y(c,p)?(v=s[p],b=c[p],typeof v=="object"&&typeof b=="object"&&v&&b?(_=Ie(v))!==Ie(b)?l[h+p]=c[p]:_==="Object"?eo(v,b,l,h+p+"."):v!==b&&(l[h+p]=c[p]):v!==b&&(l[h+p]=c[p])):l[h+p]=void 0}),o(c).forEach(function(p){y(s,p)||(l[h+p]=c[p])}),l}function to(s,c){return c.type==="delete"?c.keys:c.keys||c.values.map(s.extractKey)}var Sp={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(s){return n(n({},s),{table:function(c){var l=s.table(c),h=l.schema.primaryKey;return n(n({},l),{mutate:function(p){var v=ae.trans,b=v.table(c).hook,_=b.deleting,I=b.creating,k=b.updating;switch(p.type){case"add":if(I.fire===Re)break;return v._promise("readwrite",function(){return O(p)},!0);case"put":if(I.fire===Re&&k.fire===Re)break;return v._promise("readwrite",function(){return O(p)},!0);case"delete":if(_.fire===Re)break;return v._promise("readwrite",function(){return O(p)},!0);case"deleteRange":if(_.fire===Re)break;return v._promise("readwrite",function(){return(function P(K,C,x){return l.query({trans:K,values:!1,query:{index:h,range:C},limit:x}).then(function(T){var R=T.result;return O({type:"delete",keys:R,trans:K}).then(function(A){return 0<A.numFailures?Promise.reject(A.failures[0]):R.length<x?{failures:[],numFailures:0,lastResult:void 0}:P(K,n(n({},C),{lower:R[R.length-1],lowerOpen:!0}),x)})})})(p.trans,p.range,1e4)},!0)}return l.mutate(p);function O(P){var K,C,x,T=ae.trans,R=P.keys||to(h,P);if(!R)throw new Error("Keys missing");return(P=P.type==="add"||P.type==="put"?n(n({},P),{keys:R}):n({},P)).type!=="delete"&&(P.values=i([],P.values)),P.keys&&(P.keys=i([],P.keys)),K=l,x=R,((C=P).type==="add"?Promise.resolve([]):K.getMany({trans:C.trans,keys:x,cache:"immutable"})).then(function(A){var N=R.map(function(B,L){var q,G,H,J=A[L],Y={onerror:null,onsuccess:null};return P.type==="delete"?_.fire.call(Y,B,J,T):P.type==="add"||J===void 0?(q=I.fire.call(Y,B,P.values[L],T),B==null&&q!=null&&(P.keys[L]=B=q,h.outbound||W(P.values[L],h.keyPath,B))):(q=eo(J,P.values[L]),(G=k.fire.call(Y,q,B,J,T))&&(H=P.values[L],Object.keys(G).forEach(function(z){y(H,z)?H[z]=G[z]:W(H,z,G[z])}))),Y});return l.mutate(P).then(function(B){for(var L=B.failures,q=B.results,G=B.numFailures,B=B.lastResult,H=0;H<R.length;++H){var J=(q||R)[H],Y=N[H];J==null?Y.onerror&&Y.onerror(L[H]):Y.onsuccess&&Y.onsuccess(P.type==="put"&&A[H]?P.values[H]:J)}return{failures:L,results:q,numFailures:G,lastResult:B}}).catch(function(B){return N.forEach(function(L){return L.onerror&&L.onerror(B)}),Promise.reject(B)})})}}})}})}};function Eu(s,c,l){try{if(!c||c.keys.length<s.length)return null;for(var h=[],p=0,v=0;p<c.keys.length&&v<s.length;++p)be(c.keys[p],s[v])===0&&(h.push(l?oe(c.values[p]):c.values[p]),++v);return h.length===s.length?h:null}catch{return null}}var Ep={stack:"dbcore",level:-1,create:function(s){return{table:function(c){var l=s.table(c);return n(n({},l),{getMany:function(h){if(!h.cache)return l.getMany(h);var p=Eu(h.keys,h.trans._cache,h.cache==="clone");return p?X.resolve(p):l.getMany(h).then(function(v){return h.trans._cache={keys:h.keys,values:h.cache==="clone"?oe(v):v},v})},mutate:function(h){return h.type!=="add"&&(h.trans._cache=null),l.mutate(h)}})}}}};function _u(s,c){return s.trans.mode==="readonly"&&!!s.subscr&&!s.trans.explicit&&s.trans.db._options.cache!=="disabled"&&!c.schema.primaryKey.outbound}function Pu(s,c){switch(s){case"query":return c.values&&!c.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var _p={stack:"dbcore",level:0,name:"Observability",create:function(s){var c=s.schema.name,l=new Ye(s.MIN_KEY,s.MAX_KEY);return n(n({},s),{transaction:function(h,p,v){if(ae.subscr&&p!=="readonly")throw new se.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(ae.querier));return s.transaction(h,p,v)},table:function(h){var p=s.table(h),v=p.schema,b=v.primaryKey,P=v.indexes,_=b.extractKey,I=b.outbound,k=b.autoIncrement&&P.filter(function(C){return C.compound&&C.keyPath.includes(b.keyPath)}),O=n(n({},p),{mutate:function(C){function x(z){return z="idb://".concat(c,"/").concat(h,"/").concat(z),B[z]||(B[z]=new Ye)}var T,R,A,N=C.trans,B=C.mutatedParts||(C.mutatedParts={}),L=x(""),q=x(":dels"),G=C.type,Y=C.type==="deleteRange"?[C.range]:C.type==="delete"?[C.keys]:C.values.length<50?[to(b,C).filter(function(z){return z}),C.values]:[],H=Y[0],J=Y[1],Y=C.trans._cache;return u(H)?(L.addKeys(H),(Y=G==="delete"||H.length===J.length?Eu(H,Y):null)||q.addKeys(H),(Y||J)&&(T=x,R=Y,A=J,v.indexes.forEac
43h(function(z){var te=T(z.name||"");function he(me){return me!=null?z.extractKey(me):null}function pe(me){return z.multiEntry&&u(me)?me.forEach(function(ut){return te.addKey(ut)}):te.addKey(me)}(R||A).forEach(function(me,Qe){var le=R&&he(R[Qe]),Qe=A&&he(A[Qe]);be(le,Qe)!==0&&(le!=null&&pe(le),Qe!=null&&pe(Qe))})}))):H?(J={from:(J=H.lower)!==null&&J!==void 0?J:s.MIN_KEY,to:(J=H.upper)!==null&&J!==void 0?J:s.MAX_KEY},q.add(J),L.add(J)):(L.add(l),q.add(l),v.indexes.forEach(function(z){return x(z.name).add(l)})),p.mutate(C).then(function(z){return!H||C.type!=="add"&&C.type!=="put"||(L.addKeys(z.results),k&&k.forEach(function(te){for(var he=C.values.map(function(le){return te.extractKey(le)}),pe=te.keyPath.findIndex(function(le){return le===b.keyPath}),me=0,ut=z.results.length;me<ut;++me)he[me][pe]=z.results[me];x(te.name).addKeys(he)})),N.mutatedParts=la(N.mutatedParts||{},B),z})}}),P=function(x){var T=x.query,x=T.index,T=T.range;return[x,new Ye((x=T.lower)!==null&&x!==void 0?x:s.MIN_KEY,(T=T.upper)!==null&&T!==void 0?T:s.MAX_KEY)]},K={get:function(C){return[b,new Ye(C.key)]},getMany:function(C){return[b,new Ye().addKeys(C.keys)]},count:P,query:P,openCursor:P};return o(K).forEach(function(C){O[C]=function(x){var T=ae.subscr,R=!!T,A=_u(ae,p)&&Pu(C,x)?x.obsSet={}:T;if(R){var N=function(J){return J="idb://".concat(c,"/").concat(h,"/").concat(J),A[J]||(A[J]=new Ye)},B=N(""),L=N(":dels"),T=K[C](x),R=T[0],T=T[1];if((C==="query"&&R.isPrimaryKey&&!x.values?L:N(R.name||"")).add(T),!R.isPrimaryKey){if(C!=="count"){var q=C==="query"&&I&&x.values&&p.query(n(n({},x),{values:!1}));return p[C].apply(this,arguments).then(function(J){if(C==="query"){if(I&&x.values)return q.then(function(he){return he=he.result,B.addKeys(he),J});var Y=x.values?J.result.map(_):J.result;(x.values?B:L).addKeys(Y)}else if(C==="openCursor"){var z=J,te=x.values;return z&&Object.create(z,{key:{get:function(){return L.addKey(z.primaryKey),z.key}},primaryKey:{get:function(){var he=z.primaryKey;return L.addKey(he),he}},value:{get:function(){return te&&B.addKey(z.primaryKey),z.value}}})}return J})}L.add(l)}}return p[C].apply(this,arguments)}}),O}})}};function Iu(s,c,l){if(l.numFailures===0)return c;if(c.type==="deleteRange")return null;var h=c.keys?c.keys.length:"values"in c&&c.values?c.values.length:1;return l.numFailures===h?null:(c=n({},c),u(c.keys)&&(c.keys=c.keys.filter(function(p,v){return!(v in l.failures)})),"values"in c&&u(c.values)&&(c.values=c.values.filter(function(p,v){return!(v in l.failures)})),c)}function ro(s,c){return l=s,((h=c).lower===void 0||(h.lowerOpen?0<be(l,h.lower):0<=be(l,h.lower)))&&(s=s,(c=c).upper===void 0||(c.upperOpen?be(s,c.upper)<0:be(s,c.upper)<=0));var l,h}function Cu(s,c,K,h,p,v){if(!K||K.length===0)return s;var b=c.query.index,_=b.multiEntry,I=c.query.range,k=h.schema.primaryKey.extractKey,O=b.extractKey,P=(b.lowLevelIndex||b).extractKey,K=K.reduce(function(C,x){var T=C,R=[];if(x.type==="add"||x.type==="put")for(var A=new Ye,N=x.values.length-1;0<=N;--N){var B,L=x.values[N],q=k(L);A.hasKey(q)||(B=O(L),(_&&u(B)?B.some(function(z){return ro(z,I)}):ro(B,I))&&(A.addKey(q),R.push(L)))}switch(x.type){case"add":var G=new Ye().addKeys(c.values?C.map(function(te){return k(te)}):C),T=C.concat(c.values?R.filter(function(te){return te=k(te),!G.hasKey(te)&&(G.addKey(te),!0)}):R.map(function(te){return k(te)}).filter(function(te){return!G.hasKey(te)&&(G.addKey(te),!0)}));break;case"put":var H=new Ye().addKeys(x.values.map(function(te){return k(te)}));T=C.filter(function(te){return!H.hasKey(c.values?k(te):te)}).concat(c.values?R:R.map(function(te){return k(te)}));break;case"delete":var J=new Ye().addKeys(x.keys);T=C.filter(function(te){return!J.hasKey(c.values?k(te):te)});break;case"deleteRange":var Y=x.range;T=C.filter(function(te){return!ro(k(te),Y)})}return T},s);return K===s?s:(K.sort(function(C,x){return be(P(C),P(x))||be(k(C),k(x))}),c.limit&&c.limit<1/0&&(K.length>c.limit?K.length=c.limit:s.length===c.limit&&K.length<c.limit&&(p.dirty=!0)),v?Object.freeze(K):K)}function ku(s,c){return be(s.lower,c.lower)===0&&be(s.upper,c.upper)===0&&!!s.lowerOpen==!!c.lowerOpen&&!!s.upperOpen==!!c.upperOpen}function Pp(s,c){return(function(l,h,p,v){if(l===void 0)return h!==void 0?-1:0;if(h===void 0)return 1;if((h=be(l,h))===0){if(p&&v)return 0;if(p)return 1;if(v)return-1}return h})(s.lower,c.lower,s.lowerOpen,c.lowerOpen)<=0&&0<=(function(l,h,p,v){if(l===void 0)return h!==void 0?1:0;if(h===void 0)return-1;if((h=be(l,h))===0){if(p&&v)return 0;if(p)return-1;if(v)return 1}return h})(s.upper,c.upper,s.upperOpen,c.upperOpen)}function Ip(s,c,l,h){s.subscribers.add(l),h.addEventListener("abort",function(){var p,v;s.subscribers.delete(l),s.subscribers.size===0&&(p=s,v=c,setTimeout(function(){p.subscribers.size===0&&fe(v,p)},3e3))})}var Cp={stack:"dbcore",level:0,name:"Cache",create:function(s){var c=s.schema.name;return n(n({},s),{transaction:function(l,h,p){var v,b,_=s.transaction(l,h,p);return h==="readwrite"&&(b=(v=new AbortController).signal,p=function(I){return function(){if(v.abort(),h==="readwrite"){for(var k=new Set,O=0,P=l;O<P.length;O++){var K=P[O],C=Rr["idb://".concat(c,"/").concat(K)];if(C){var x=s.table(K),T=C.optimisticOps.filter(function(te){return te.trans===_});if(_._explicit&&I&&_.mutatedParts)for(var R=0,A=Object.values(C.queries.query
43);R<A.length;R++)for(var N=0,B=(G=A[R]).slice();N<B.length;N++)Vs((H=B[N]).obsSet,_.mutatedParts)&&(fe(G,H),H.subscribers.forEach(function(te){return k.add(te)}));else if(0<T.length){C.optimisticOps=C.optimisticOps.filter(function(te){return te.trans!==_});for(var L=0,q=Object.values(C.queries.query);L<q.length;L++)for(var G,H,J,Y=0,z=(G=q[L]).slice();Y<z.length;Y++)(H=z[Y]).res!=null&&_.mutatedParts&&(I&&!H.dirty?(J=Object.isFrozen(H.res),J=Cu(H.res,H.req,T,x,H,J),H.dirty?(fe(G,H),H.subscribers.forEach(function(te){return k.add(te)})):J!==H.res&&(H.res=J,H.promise=X.resolve({result:J}))):(H.dirty&&fe(G,H),H.subscribers.forEach(function(te){return k.add(te)})))}}}k.forEach(function(te){return te()})}}},_.addEventListener("abort",p(!1),{signal:b}),_.addEventListener("error",p(!1),{signal:b}),_.addEventListener("complete",p(!0),{signal:b})),_},table:function(l){var h=s.table(l),p=h.schema.primaryKey;return n(n({},h),{mutate:function(v){var b=ae.trans;if(p.outbound||b.db._options.cache==="disabled"||b.explicit||b.idbtrans.mode!=="readwrite")return h.mutate(v);var _=Rr["idb://".concat(c,"/").concat(l)];return _?(b=h.mutate(v),v.type!=="add"&&v.type!=="put"||!(50<=v.values.length||to(p,v).some(function(I){return I==null}))?(_.optimisticOps.push(v),v.mutatedParts&&da(v.mutatedParts),b.then(function(I){0<I.numFailures&&(fe(_.optimisticOps,v),(I=Iu(0,v,I))&&_.optimisticOps.push(I),v.mutatedParts&&da(v.mutatedParts))}),b.catch(function(){fe(_.optimisticOps,v),v.mutatedParts&&da(v.mutatedParts)})):b.then(function(I){var k=Iu(0,n(n({},v),{values:v.values.map(function(O,P){var K;return I.failures[P]?O:(O=(K=p.keyPath)!==null&&K!==void 0&&K.includes(".")?oe(O):n({},O),W(O,p.keyPath,I.results[P]),O)})}),I);_.optimisticOps.push(k),queueMicrotask(function(){return v.mutatedParts&&da(v.mutatedParts)})}),b):h.mutate(v)},query:function(v){if(!_u(ae,h)||!Pu("query",v))return h.query(v);var b=((k=ae.trans)===null||k===void 0?void 0:k.db._options.cache)==="immutable",P=ae,_=P.requery,I=P.signal,k=(function(x,T,R,A){var N=Rr["idb://".concat(x,"/").concat(T)];if(!N)return[];if(!(T=N.queries[R]))return[null,!1,N,null];var B=T[(A.query?A.query.index.name:null)||""];if(!B)return[null,!1,N,null];switch(R){case"query":var L=B.find(function(q){return q.req.limit===A.limit&&q.req.values===A.values&&ku(q.req.query.range,A.query.range)});return L?[L,!0,N,B]:[B.find(function(q){return("limit"in q.req?q.req.limit:1/0)>=A.limit&&(!A.values||q.req.values)&&Pp(q.req.query.range,A.query.range)}),!1,N,B];case"count":return L=B.find(function(q){return ku(q.req.query.range,A.query.range)}),[L,!!L,N,B]}})(c,l,"query",v),O=k[0],P=k[1],K=k[2],C=k[3];return O&&P?O.obsSet=v.obsSet:(P=h.query(v).then(function(x){var T=x.result;if(O&&(O.res=T),b){for(var R=0,A=T.length;R<A;++R)Object.freeze(T[R]);Object.freeze(T)}else x.result=oe(T);return x}).catch(function(x){return C&&O&&fe(C,O),Promise.reject(x)}),O={obsSet:v.obsSet,promise:P,subscribers:new Set,type:"query",req:v,dirty:!1},C?C.push(O):(C=[O],(K=K||(Rr["idb://".concat(c,"/").concat(l)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[v.query.index.name||""]=C)),Ip(O,C,_,I),O.promise.then(function(x){return{result:Cu(x.result,v,K==null?void 0:K.optimisticOps,h,O,b)}})}})}})}};function fa(s,c){return new Proxy(s,{get:function(l,h,p){return h==="db"?c:Reflect.get(l,h,p)}})}var Ut=(Fe.prototype.version=function(s){if(isNaN(s)||s<.1)throw new se.Type("Given version is not a positive number");if(s=Math.round(10*s)/10,this.idbdb||this._state.isBeingOpened)throw new se.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,s);var c=this._versions,l=c.filter(function(h){return h._cfg.version===s})[0];return l||(l=new this.Version(s),c.push(l),c.sort(mp),l.stores({}),this._state.autoSchema=!1,l)},Fe.prototype._whenReady=function(s){var c=this;return this.idbdb&&(this._state.openComplete||ae.letThrough||this._vip)?s():new X(function(l,h){if(c._state.openComplete)return h(new se.DatabaseClosed(c._state.dbOpenError));if(!c._state.isBeingOpened){if(!c._state.autoOpen)return void h(new se.DatabaseClosed);c.open().catch(Re)}c._state.dbReadyPromise.then(l,h)}).then(s)},Fe.prototype.use=function(s){var c=s.stack,l=s.create,h=s.level,p=s.name;return p&&this.unuse({stack:c,name:p}),s=this._middlewares[c]||(this._middlewares[c]=[]),s.push({stack:c,create:l,level:h??10,name:p}),s.sort(function(v,b){return v.level-b.level}),this},Fe.prototype.unuse=function(s){var c=s.stack,l=s.name,h=s.create;return c&&this._middlewares[c]&&(this._middlewares[c]=this._middlewares[c].filter(function(p){return h?p.create!==h:!!l&&p.name!==l})),this},Fe.prototype.open=function(){var s=this;return Ir(er,function(){return wp(s)})},Fe.prototype._close=function(){var s=this._state,c=Xr.indexOf(this);if(0<=c&&Xr.splice(c,1),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}s.isBeingOpened||(s.dbReadyPromise=new X(function(l){s.dbReadyResolve=l}),s.openCanceller=new X(function(l,h){s.cancelOpen=h}))},Fe.prototype.close=function(l){var c=(l===void 0?{disableAutoOpen:!0}:l).disableAutoOpen,l=this._state;c?(l.isBeingOpened&&l.cancelOpen(new se.DatabaseClosed),this._close(),l.autoOpen=!1,l.dbOpenError=ne
43w se.DatabaseClosed):(this._close(),l.autoOpen=this._options.autoOpen||l.isBeingOpened,l.openComplete=!1,l.dbOpenError=null)},Fe.prototype.delete=function(s){var c=this;s===void 0&&(s={disableAutoOpen:!0});var l=0<arguments.length&&typeof arguments[0]!="object",h=this._state;return new X(function(p,v){function b(){c.close(s);var _=c._deps.indexedDB.deleteDatabase(c.name);_.onsuccess=Ae(function(){var I,k,O;I=c._deps,k=c.name,O=I.indexedDB,I=I.IDBKeyRange,js(O)||k===Xi||Js(O,I).delete(k).catch(Re),p()}),_.onerror=Ot(v),_.onblocked=c._fireOnBlocked}if(l)throw new se.InvalidArgument("Invalid closeOptions argument to db.delete()");h.isBeingOpened?h.dbReadyPromise.then(b):b()})},Fe.prototype.backendDB=function(){return this.idbdb},Fe.prototype.isOpen=function(){return this.idbdb!==null},Fe.prototype.hasBeenClosed=function(){var s=this._state.dbOpenError;return s&&s.name==="DatabaseClosed"},Fe.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Fe.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Fe.prototype,"tables",{get:function(){var s=this;return o(this._allTables).map(function(c){return s._allTables[c]})},enumerable:!1,configurable:!0}),Fe.prototype.transaction=function(){var s=(function(c,l,h){var p=arguments.length;if(p<2)throw new se.InvalidArgument("Too few arguments");for(var v=new Array(p-1);--p;)v[p-1]=arguments[p];return h=v.pop(),[c,Se(v),h]}).apply(this,arguments);return this._transaction.apply(this,s)},Fe.prototype._transaction=function(s,c,l){var h=this,p=ae.trans;p&&p.db===this&&s.indexOf("!")===-1||(p=null);var v,b,_=s.indexOf("?")!==-1;s=s.replace("!","").replace("?","");try{if(b=c.map(function(k){if(k=k instanceof h.Table?k.name:k,typeof k!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return k}),s=="r"||s===Ks)v=Ks;else{if(s!="rw"&&s!=As)throw new se.InvalidArgument("Invalid transaction mode: "+s);v=As}if(p){if(p.mode===Ks&&v===As){if(!_)throw new se.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");p=null}p&&b.forEach(function(k){if(p&&p.storeNames.indexOf(k)===-1){if(!_)throw new se.SubTransaction("Table "+k+" not included in parent transaction.");p=null}}),_&&p&&!p.active&&(p=null)}}catch(k){return p?p._promise(null,function(O,P){P(k)}):Be(k)}var I=(function k(O,P,K,C,x){return X.resolve().then(function(){var T=ae.transless||ae,R=O._createTransaction(P,K,O._dbSchema,C);if(R.explicit=!0,T={trans:R,transless:T},C)R.idbtrans=C.idbtrans;else try{R.create(),R.idbtrans._explicit=!0,O._state.PR1398_maxLoop=3}catch(B){return B.name===_s.InvalidState&&O.isOpen()&&0<--O._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),O.close({disableAutoOpen:!1}),O.open().then(function(){return k(O,P,K,null,x)})):Be(B)}var A,N=we(x);return N&&Qr(),T=X.follow(function(){var B;(A=x.call(R,R))&&(N?(B=rr.bind(null,null),A.then(B,B)):typeof A.next=="function"&&typeof A.throw=="function"&&(A=Zs(A)))},T),(A&&typeof A.then=="function"?X.resolve(A).then(function(B){return R.active?B:Be(new se.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):T.then(function(){return A})).then(function(B){return C&&R._resolve(),R._completion.then(function(){return B})}).catch(function(B){return R._reject(B),Be(B)})})}).bind(null,this,v,b,p,l);return p?p._promise(v,I,"lock"):ae.trans?Ir(ae.transless,function(){return h._whenReady(I)}):this._whenReady(I)},Fe.prototype.table=function(s){if(!y(this._allTables,s))throw new se.InvalidTable("Table ".concat(s," does not exist"));return this._allTables[s]},Fe);function Fe(s,c){var l=this;this._middlewares={},this.verno=0;var h=Fe.dependencies;this._options=c=n({addons:Fe.addons,autoOpen:!0,indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange,cache:"cloned"},c),this._deps={indexedDB:c.indexedDB,IDBKeyRange:c.IDBKeyRange},h=c.addons,this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this;var p,v,b,_,I,k={dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Re,dbReadyPromise:null,cancelOpen:Re,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:c.autoOpen};k.dbReadyPromise=new X(function(P){k.dbReadyResolve=P}),k.openCanceller=new X(function(P,K){k.cancelOpen=K}),this._state=k,this.name=s,this.on=$n(this,"populate","blocked","versionchange","close",{ready:[Ps,Re]}),this.on.ready.subscribe=F(this.on.ready.subscribe,function(P){return function(K,C){Fe.vip(function(){var x,T=l._state;T.openComplete?(T.dbOpenError||X.resolve().then(K),C&&P(K)):T.onReadyBeingFired?(T.onReadyBeingFired.push(K),C&&P(K)):(P(K),x=l,C||P(function R(){x.on.ready.unsubscribe(K),x.on.ready.unsubscribe(R)}
43))})}}),this.Collection=(p=this,qn(cp.prototype,function(A,R){this.db=p;var C=iu,x=null;if(R)try{C=R()}catch(N){x=N}var T=A._ctx,R=T.table,A=R.hook.reading.fire;this._ctx={table:R,index:T.index,isPrimKey:!T.index||R.schema.primKey.keyPath&&T.index===R.schema.primKey.name,range:C,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:x,or:T.or,valueMapper:A!==Bn?A:null}})),this.Table=(v=this,qn(cu.prototype,function(P,K,C){this.db=v,this._tx=C,this.name=P,this.schema=K,this.hook=v._allTables[P]?v._allTables[P].hook:$n(null,{creating:[Zf,Re],reading:[Xf,Bn],updating:[tp,Re],deleting:[ep,Re]})})),this.Transaction=(b=this,qn(dp.prototype,function(P,K,C,x,T){var R=this;this.db=b,this.mode=P,this.storeNames=K,this.schema=C,this.chromeTransactionDurability=x,this.idbtrans=null,this.on=$n(this,"complete","error","abort"),this.parent=T||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 X(function(A,N){R._resolve=A,R._reject=N}),this._completion.then(function(){R.active=!1,R.on.complete.fire()},function(A){var N=R.active;return R.active=!1,R.on.error.fire(A),R.parent?R.parent._reject(A):N&&R.idbtrans&&R.idbtrans.abort(),Be(A)})})),this.Version=(_=this,qn(gp.prototype,function(P){this.db=_,this._cfg={version:P,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(I=this,qn(fu.prototype,function(P,K,C){if(this.db=I,this._ctx={table:P,index:K===":id"?null:K,or:C},this._cmp=this._ascending=be,this._descending=function(x,T){return be(T,x)},this._max=function(x,T){return 0<be(x,T)?x:T},this._min=function(x,T){return be(x,T)<0?x:T},this._IDBKeyRange=I._deps.IDBKeyRange,!this._IDBKeyRange)throw new se.MissingAPI})),this.on("versionchange",function(P){0<P.newVersion?console.warn("Another connection wants to upgrade database '".concat(l.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(l.name,"'. Closing db now to resume the delete request.")),l.close({disableAutoOpen:!1})}),this.on("blocked",function(P){!P.newVersion||P.newVersion<P.oldVersion?console.warn("Dexie.delete('".concat(l.name,"') was blocked")):console.warn("Upgrade '".concat(l.name,"' blocked by other connection holding version ").concat(P.oldVersion/10))}),this._maxKey=zn(c.IDBKeyRange),this._createTransaction=function(P,K,C,x){return new l.Transaction(P,K,C,l._options.chromeTransactionDurability,x)},this._fireOnBlocked=function(P){l.on("blocked").fire(P),Xr.filter(function(K){return K.name===l.name&&K!==l&&!K._state.vcFired}).map(function(K){return K.on("versionchange").fire(P)})},this.use(Ep),this.use(Cp),this.use(_p),this.use(bp),this.use(Sp);var O=new Proxy(this,{get:function(P,K,C){if(K==="_vip")return!0;if(K==="table")return function(T){return fa(l.table(T),O)};var x=Reflect.get(P,K,C);return x instanceof cu?fa(x,O):K==="tables"?x.map(function(T){return fa(T,O)}):K==="_createTransaction"?function(){return fa(x.apply(this,arguments),O)}:x}});this.vip=O,h.forEach(function(P){return P(l)})}var pa,vt=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",kp=(no.prototype.subscribe=function(s,c,l){return this._subscribe(s&&typeof s!="function"?s:{next:s,error:c,complete:l})},no.prototype[vt]=function(){return this},no);function no(s){this._subscribe=s}try{pa={indexedDB:a.indexedDB||a.mozIndexedDB||a.webkitIndexedDB||a.msIndexedDB,IDBKeyRange:a.IDBKeyRange||a.webkitIDBKeyRange}}catch{pa={indexedDB:null,IDBKeyRange:null}}function Ru(s){var c,l=!1,h=new kp(function(p){var v=we(s),b,_=!1,I={},k={},O={get closed(){return _},unsubscribe:function(){_||(_=!0,b&&b.abort(),P&&ar.storagemutated.unsubscribe(C))}};p.start&&p.start(O);var P=!1,K=function(){return Ts(x)},C=function(T){la(I,T),Vs(k,I)&&K()},x=function(){var T,R,A;!_&&pa.indexedDB&&(I={},T={},b&&b.abort(),b=new AbortController,A=(function(N){var B=Vr();try{v&&Qr();var L=tr(s,N);return L=v?L.finally(rr):L}finally{B&&Yr()}})(R={subscr:T,signal:b.signal,requery:K,querier:s,trans:null}
43),Promise.resolve(A).then(function(N){l=!0,c=N,_||R.signal.aborted||(I={},(function(B){for(var L in B)if(y(B,L))return;return 1})(k=T)||P||(ar(jn,C),P=!0),Ts(function(){return!_&&p.next&&p.next(N)}))},function(N){l=!1,["DatabaseClosedError","AbortError"].includes(N==null?void 0:N.name)||_||Ts(function(){_||p.error&&p.error(N)})}))};return setTimeout(K,0),O});return h.hasValue=function(){return l},h.getValue=function(){return c},h}var Dr=Ut;function io(s){var c=sr;try{sr=!0,ar.storagemutated.fire(s),Xs(s,!0)}finally{sr=c}}g(Dr,n(n({},qi),{delete:function(s){return new Dr(s,{addons:[]}).delete()},exists:function(s){return new Dr(s,{addons:[]}).open().then(function(c){return c.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(s){try{return c=Dr.dependencies,l=c.indexedDB,c=c.IDBKeyRange,(js(l)?Promise.resolve(l.databases()).then(function(h){return h.map(function(p){return p.name}).filter(function(p){return p!==Xi})}):Js(l,c).toCollection().primaryKeys()).then(s)}catch{return Be(new se.MissingAPI)}var c,l},defineClass:function(){return function(s){d(this,s)}},ignoreTransaction:function(s){return ae.trans?Ir(ae.transless,s):s()},vip:zs,async:function(s){return function(){try{var c=Zs(s.apply(this,arguments));return c&&typeof c.then=="function"?c:X.resolve(c)}catch(l){return Be(l)}}},spawn:function(s,c,l){try{var h=Zs(s.apply(l,c||[]));return h&&typeof h.then=="function"?h:X.resolve(h)}catch(p){return Be(p)}},currentTransaction:{get:function(){return ae.trans||null}},waitFor:function(s,c){return c=X.resolve(typeof s=="function"?Dr.ignoreTransaction(s):s).timeout(c||6e4),ae.trans?ae.trans.waitFor(c):c},Promise:X,debug:{get:function(){return xt},set:function(s){Qc(s)}},derive:E,extend:d,props:g,override:F,Events:$n,on:ar,liveQuery:Ru,extendObservabilitySet:la,getByKeyPath:V,setByKeyPath:W,delByKeyPath:function(s,c){typeof c=="string"?W(s,c,void 0):"length"in c&&[].map.call(c,function(l){W(s,l,void 0)})},shallowClone:ie,deepClone:oe,getObjectDiff:eo,cmp:be,asap:$,minKey:-1/0,addons:[],connections:Xr,errnames:_s,dependencies:pa,cache:Rr,semVer:"4.0.10",version:"4.0.10".split(".").map(function(s){return parseInt(s)}).reduce(function(s,c,l){return s+c/Math.pow(10,2*l)})})),Dr.maxKey=zn(Dr.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(ar(jn,function(s){sr||(s=new CustomEvent(Fs,{detail:s}),sr=!0,dispatchEvent(s),sr=!1)}),addEventListener(Fs,function(s){s=s.detail,sr||io(s)}));var tn,sr=!1,Du=function(){};return typeof BroadcastChannel<"u"&&((Du=function(){(tn=new BroadcastChannel(Fs)).onmessage=function(s){return s.data&&io(s.data)}})(),typeof tn.unref=="function"&&tn.unref(),ar(jn,function(s){sr||tn.postMessage(s)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(s){if(!Ut.disableBfCache&&s.persisted){xt&&console.debug("Dexie: handling persisted pagehide"),tn!=null&&tn.close();for(var c=0,l=Xr;c<l.length;c++)l[c].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(s){!Ut.disableBfCache&&s.persisted&&(xt&&console.debug("Dexie: handling persisted pageshow"),Du(),io({all:new Ye(-1/0,[[]])}))})),X.rejectionMapper=function(s,c){return!s||s instanceof ge||s instanceof TypeError||s instanceof SyntaxError||!s.name||!Yc[s.name]?s:(c=new Yc[s.name](c||s.message,s),"stack"in s&&S(c,"stack",{get:function(){return this.inner.stack}}),c)},Qc(xt),n(Ut,Object.freeze({__proto__:null,Dexie:Ut,liveQuery:Ru,Entity:au,cmp:be,PropModSymbol:Lt,PropModification:Hn,replacePrefix:function(s,c){return new Hn({replacePrefix:[s,c]})},add:function(s){return new Hn({add:s})},remove:function(s){return new Hn({remove:s})},default:Ut,RangeSet:Ye,mergeRanges:Yn,rangesOverlap:gu}),{default:Ut}),Ut})})(Aa)),Aa.exports}var mP=pP();const ec=Op(mP),Ul=Symbol.for("Dexie"),ns=globalThis[Ul]||(globalThis[Ul]=ec);if(ec.semVer!==ns.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${ec.semVer} and ${ns.semVer}`);const{liveQuery:kC,mergeRanges:RC,rangesOverlap:DC,RangeSet:xC,cmp:OC,Entity:TC,PropModSymbol:KC,PropModification:AC,replacePrefix:NC,add:MC,remove:BC}=ns;var is="docs",yP="changes",Wl="attachments",Df="dexie",$l=new Map,Na=new Map;function vP(e,t,r,n){var i="rxdb-dexie-"+e+"--"+n.version+"--"+t,a=it($l,i,()=>{var o=(async()=>{var u=Oe(r);u.autoOpen=!1;var d=new ns(i,u);r.onCreate&&await r.onCreate(d,i);var f={[is]:bP(n),[yP]:"++sequence, id",[Wl]:"id"};return d.version(1).stores(f),await d.open(),{dexieDb:d,dexieTable:d[is],dexieAttachmentsTable:d[Wl],booleanIndexes:SP(n)}})();return $l.set(i,a),Na.set(a,0),o});return a}
43async function gP(e){var t=await e,r=Na.get(e),n=r-1;n===0?(t.dexieDb.close(),Na.delete(e)):Na.set(e,n)}var tc="__";function Mn(e){var t=e.split(".");if(t.length>1)return t.map(n=>Mn(n)).join(".");if(e.startsWith("|")){var r=e.substring(1);return tc+r}else return e}function xf(e){var t=e.split(".");if(t.length>1)return t.map(n=>xf(n)).join(".");if(e.startsWith(tc)){var r=e.substring(tc.length);return"|"+r}else return e}function wP(e,t){if(!t)return t;var r=Oe(t);return r=rc(r),e.forEach(n=>{var i=vr(t,n),a=i?"1":"0",o=Mn(n);Rd(r,o,a)}),r}function Of(e,t){return t&&(t=Oe(t),t=nc(t),e.forEach(r=>{var n=vr(t,r),i=n==="1";Rd(t,r,i)}),t)}function rc(e){if(!e||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(r=>rc(r));if(typeof e=="object"){var t={};return Object.entries(e).forEach(([r,n])=>{typeof n=="object"&&(n=rc(n)),t[Mn(r)]=n}),t}}function nc(e){if(!e||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(r=>nc(r));if(typeof e=="object"){var t={};return Object.entries(e).forEach(([r,n])=>{(typeof n=="object"||Array.isArray(e))&&(n=nc(n)),t[xf(r)]=n}),t}}function bP(e){var t=[],r=et(e.primaryKey);t.push([r]),t.push(["_deleted",r]),e.indexes&&e.indexes.forEach(a=>{var o=bn(a);t.push(o)}),t.push(["_meta.lwt",r]),t.push(["_meta.lwt"]),t=t.map(a=>a.map(o=>Mn(o)));var n=t.map(a=>a.length===1?a[0]:"["+a.join("+")+"]");n=n.filter((a,o,u)=>u.indexOf(a)===o);var i=n.join(", ");return i}async function ql(e,t){var r=await e,n=await r.dexieTable.bulkGet(t);return n.map(i=>Of(r.booleanIndexes,i))}function Ea(e,t){return e+"||"+t}function SP(e){var t=new Set,r=[];return e.indexes?(e.indexes.forEach(n=>{var i=bn(n);i.forEach(a=>{if(!t.has(a)){t.add(a);var o=Vt(e,a);o.type==="boolean"&&r.push(a)}})}),r.push("_deleted"),ny(r)):r}function Hl(e){return e===It?-1/0:e}function Jl(e,t,r){if(e.includes(t)){var n=r===Pt||r===!0?"1":"0";return n}else return r}function Tf(e,t,r){if(!r){if(typeof window>"u")throw new Error("IDBKeyRange missing");r=window.IDBKeyRange}var n=t.startKeys.map((o,u)=>{var d=t.index[u];return Jl(e,d,o)}).map(Hl),i=t.endKeys.map((o,u)=>{var d=t.index[u];return Jl(e,d,o)}).map(Hl),a=r.bound(n,i,!t.inclusiveStart,!t.inclusiveEnd);return a}async function jl(e,t){var r=await e.internals,n=t.query,i=n.skip?n.skip:0,a=n.limit?n.limit:1/0,o=i+a,u=t.queryPlan,d=!1;u.selectorSatisfiedByIndex||(d=Fi(e.schema,t.query));var f=Tf(r.booleanIndexes,u,r.dexieDb._options.IDBKeyRange),m=u.index,y=[];if(await r.dexieDb.transaction("r",r.dexieTable,async w=>{var S=w.idbtrans,E=S.objectStore(is),D,M;M="["+m.map(F=>Mn(F)).join("+")+"]",D=E.index(M);var U=D.openCursor(f);await new Promise(F=>{U.onsuccess=function(j){var $=j.target.result;if($){var V=Of(r.booleanIndexes,$.value);(!d||d(V))&&y.push(V),u.sortSatisfiedByIndex&&y.length===o?F():$.continue()}else F()}})}),!u.sortSatisfiedByIndex){var g=ys(e.schema,t.query);y=y.sort(g)}return y=y.slice(i,o),{documents:y}}async function EP(e,t){var r=await e.internals,n=t.queryPlan,i=n.index,a=Tf(r.booleanIndexes,n,r.dexieDb._options.IDBKeyRange),o=-1;return await r.dexieDb.transaction("r",r.dexieTable,async u=>{var d=u.idbtrans,f=d.objectStore(is),m,y;y="["+i.map(w=>Mn(w)).join("+")+"]",m=f.index(y);var g=m.count(a);o=await new Promise((w,S)=>{g.onsuccess=function(){w(g.result)},g.onerror=E=>S(E)})}),o}var _P=Ze(),Ro=!1,PP=(function(){function e(r,n,i,a,o,u,d,f){this.changes$=new He,this.instanceId=_P++,this.storage=r,this.databaseName=n,this.collectionName=i,this.schema=a,this.internals=o,this.options=u,this.settings=d,this.devMode=f,this.primaryPath=et(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=async function(n,i){Or(this),!Ro&&!await Dd()&&console.warn(["-------------- RxDB Open Core RxStorage -------------------------------","You are using the free Dexie.js based RxStorage implementation from RxDB https://rxdb.info/rx-storage-dexie.html?console=dexie ","While this is a great option, we want to let you know that there are faster storage solutions available in our premium plugins.","For professional users and production environments, we highly recommend considering these premium options to enhance performance and reliability."," https://rxdb.info/premium/?console=dexie ","If you already purchased premium access you can disable this log by calling the setPremiumFlag() function from rxdb-premium/plugins/shared.","---------------------------------------------------------------------"].join(`
44`)),Ro=!0,n.forEach(m=>{if(!m.document._rev||m.previous&&!m.previous._rev)throw ee("SNH",{args:{row:m}})});var a=await this.internals,o={error:[]};this.devMode&&(n=n.map(m=>{var y=Li(m.document);return{previous:m.previous,document:y}}));var u=n.map(m=>m.document[this.primaryPath]),d;if(await a.dexieDb.transaction("rw",a.dexieTable,a.dexieAttachmentsTable,async()=>{var m=new Map,y=await ql(this.internals,u);y.forEach(S=>{var E=S;return E&&m.set(E[this.primaryPath],E),E}),d=Sc(this,this.primaryPath,m,n,i),o.error=d.errors;var g=[];d.bulkInsertDocs.forEach(S=>{g.push(S.document)}),d.bulkUpdateDocs.forEach(S=>{g.push(S.document)}),g=g.map(S=>wP(a.booleanIndexes,S)),g.length>0&&await a.dexieTable.bulkPut(g);var w=[];d.attachmentsAdd.forEach(S=>{w.push({id:Ea(S.documentId,S.attachmentId),data:S.attachmentData.data})}),d.attachmentsUpdate.forEach(S=>{w.push({id:Ea(S.documentId,S.attachmentId),data:S.attachmentData.data})}),await a.dexieAttachmentsTable.bulkPut(w),await a.dexieAttachmentsTable.bulkDelete(d.attachmentsRemove.map(S=>Ea(S.documentId,S.attachmentId)))}),d=Z(d),d.eventBulk.events.length>0){var f=Z(d.newestRow).document;d.eventBulk.checkpoint={id:f[this.primaryPath],lwt:f._meta.lwt},this.changes$.next(d.eventBulk)}return o},t.findDocumentsById=async function(n,i){Or(this);var a=await this.internals,o=[];return await a.dexieDb.transaction("r",a.dexieTable,async()=>{var u=await ql(this.internals,n);u.forEach(d=>{d&&(!d._deleted||i)&&o.push(d)})}),o},t.query=function(n){return Or(this),jl(this,n)},t.count=async function(n){if(n.queryPlan.selectorSatisfiedByIndex){var i=await EP(this,n);return{count:i,mode:"fast"}}else{var a=await jl(this,n);return{count:a.documents.length,mode:"slow"}}},t.changeStream=function(){return Or(this),this.changes$.asObservable()},t.cleanup=async function(n){Or(this);var i=await this.internals;return await i.dexieDb.transaction("rw",i.dexieTable,async()=>{var a=Ze()-n,o=await i.dexieTable.where("_meta.lwt").below(a).toArray(),u=[];o.forEach(d=>{d._deleted==="1"&&u.push(d[this.primaryPath])}),await i.dexieTable.bulkDelete(u)}),!0},t.getAttachmentData=async function(n,i,a){Or(this);var o=await this.internals,u=Ea(n,i);return await o.dexieDb.transaction("r",o.dexieAttachmentsTable,async()=>{var d=await o.dexieAttachmentsTable.get(u);if(d)return d.data;throw new Error("attachment missing documentId: "+n+" attachmentId: "+i)})},t.remove=async function(){Or(this);var n=await this.internals;return await n.dexieTable.clear(),this.close()},t.close=function(){return this.closed?this.closed:(this.closed=(async()=>{this.changes$.complete(),await gP(this.internals)})(),this.closed)},e})();async function IP(e,t,r){var n=vP(t.databaseName,t.collectionName,r,t.schema),i=new PP(e,t.databaseName,t.collectionName,t.sc
44hema,n,t.options,r,t.devMode);return await of(Df,t,i),Promise.resolve(i)}function Or(e){if(e.closed)throw new Error("RxStorageInstanceDexie is closed "+e.databaseName+"-"+e.collectionName)}var CP=(function(){function e(r){this.name=Df,this.rxdbVersion=hc,this.settings=r}var t=e.prototype;return t.createStorageInstance=function(n){if(_c(n),n.schema.indexes){var i=n.schema.indexes.flat();i.filter(a=>!a.includes(".")).forEach(a=>{if(!n.schema.required||!n.schema.required.includes(a))throw ee("DXE1",{field:a,schema:n.schema})})}return IP(this,n,this.settings)},e})();function kP(e={}){var t=new CP(e);return t}function RP(e,t,r,n,i){for(var a=i+1;n<=i;){var o=n+i>>>1,u=e[o],d=r!==void 0?r(u,t):u-t;d>=0?(a=o,i=o-1):n=o+1}return a}function DP(e,t,r,n,i){for(var a=i+1;n<=i;){var o=n+i>>>1,u=e[o],d=r!==void 0?r(u,t):u-t;d>0?(a=o,i=o-1):n=o+1}return a}function xP(e,t,r,n,i){for(var a=n-1;n<=i;){var o=n+i>>>1,u=e[o],d=r!==void 0?r(u,t):u-t;d<0?(a=o,n=o+1):i=o-1}return a}function OP(e,t,r,n,i){for(var a=n-1;n<=i;){var o=n+i>>>1,u=e[o],d=r!==void 0?r(u,t):u-t;d<=0?(a=o,n=o+1):i=o-1}return a}function TP(e,t,r,n,i){for(;n<=i;){var a=n+i>>>1,o=e[a],u=r!==void 0?r(o,t):o-t;if(u===0)return a;u<=0?n=a+1:i=a-1}return-1}function $i(e,t,r,n,i,a){return a(e,t,r,n===void 0?0:n|0,i===void 0?e.length-1:i|0)}function KP(e,t,r,n,i){return $i(e,t,r,n,i,RP)}function zl(e,t,r,n,i){return $i(e,t,r,n,i,DP)}function AP(e,t,r,n,i){return $i(e,t,r,n,i,xP)}function NP(e,t,r,n,i){return $i(e,t,r,n,i,OP)}function Kf(e,t,r,n,i){return $i(e,t,r,n,i,TP)}function Af(e,t,r){return[e,t,r].join("--memory--")}function _a(e){if(e.internals.removed)throw new Error("removed already "+e.databaseName+" - "+e.collectionName+" - "+e.schema.version)}function Pa(e,t){return e+"||"+t}function MP(e,t){return e[0]<t[0]?-1:1}function Gl(e,t,r,n,i){t.documents.set(e,n);for(var a=0;a<r.length;++a){var o=r[a],u=o.docsWithIndex,d=o.getIndexableString,f=d(n),m=Eh(u,[f,n,e],MP,0);if(i){var y=d(i);if(y===f){var g=u[m-1];if(g&&g[2]===e)u.splice(m-1,1);else{var w=u[m+1];if(w[2]===e)u.splice(m+1,1);else throw ee("SNH",{document:n,args:{byIndex:o}})}}else{var S=Kf(u,[y],ui);u.splice(S,1)}}}}function BP(e,t,r,n){var i=n[e];r.documents.delete(i),Object.values(r.byIndex).forEach(a=>{var o=a.docsWithIndex,u=a.getIndexableString(n),d=Kf(o,[u],ui);o.splice(d,1)})}function ui(e,t){var r=e[0],n=t[0];return r<n?-1:r===n?0:1}function FP(e,t){var r=et(t.primaryKey),n=t.indexes?t.indexes.map(i=>bn(i)):[];n.push(["_deleted","_meta.lwt",r]),n.forEach(i=>{e.byIndex[ic(i)]={index:i,docsWithIndex:[],getIndexableString:cf(t,i)}})}function ic(e){return e.join(",")}var Vl=new Set,LP=(function(){function e(r,n,i,a,o,u,d,f){this.closed=!1,this.categorizedByWriteInput=new WeakMap,this.storage=r,this.databaseName=n,this.collectionName=i,this.schema=a,this.internals=o,this.options=u,this.settings=d,this.devMode=f,Vl.add(this),this.primaryPath=et(this.schema.primaryKey)}var t=e.prototype;return t.bulkWrite=function(n,i){this.ensurePersistence(),_a(this);var a=this.internals,o=this.internals.documents,u=this.primaryPath,d=Sc(this,u,o,n,i),f=d.errors,m=Promise.resolve({error:f});if(this.categorizedByWriteInput.set(n,d),this.internals.ensurePersistenceTask=d,this.internals.ensurePersistenceIdlePromise||(this.internals.ensurePersistenceIdlePromise=On().then(()=>{this.internals.ensurePersistenceIdlePromise=void 0,this.ensurePersistence()})),d.eventBulk.events.length>0){var y=Z(d.newestRow).document;d.eventBulk.checkpoint={id:y[u],lwt:y._meta.lwt},a.changes$.next(d.eventBulk)}return m},t.ensurePersistence=function(){if(this.internals.ensurePersistenceTask){var n=this.internals,i=this.internals.documents,a=this.primaryPath,o=this.internals.ensurePersistenceTask;this.internals.ensurePersistenceTask=void 0;for(var u=Object.values(this.internals.byIndex),d=o.bulkInsertDocs,f=0;f<d.length;++f){var m=d[f],y=m.document,g=y[a];Gl(g,n,u,y,void 0)}for(var w=o.bulkUpdateDocs,S=0;S<w.length;++S){var E=w[S],D=E.document,M=D[a];Gl(M,n,u,D,i.get(M))}if(this.schema.attachments){var U=n.attachments;o.attachmentsAdd.forEach(F=>{U.set(Pa(F.documentId,F.attachmentId),{writeData:F.attachmentData,digest:F.digest})}),this.schema.attachments&&(o.attachmentsUpdate.forEach(F=>{U.set(Pa(F.documentId,F.attachmentId),{writeData:F.attachmentData,digest:F.digest})}),o.attachmentsRemove.forEach(F=>{U.delete(Pa(F.documentId,F.attachmentId))}))}}},t.findDocumentsById=function(n,i){this.ensurePersistence();var a=this.internals.documents,o=[];if(a.size===0)return Promise.resolve(o);for(var u=0;u<n.length;++u){var d=n[u],f=a.get(d);f&&(!f._deleted||i)&&o.push(f)}return Promise.resolve(o)},t.query=function(n){this.ensurePersistence();var i=n.queryPlan,a=n.query,o=a.skip?a.skip:0,u=a.limit?a.limit:1/0,d=o+u,f=!1;i.selectorSatisfiedByIndex||(f=Fi(this.schema,n.query));var m=i.index,y=!i.sortSatisfiedByIndex,g=m,w=i.startKeys,S=Ii(this.schema,g,w),E=i.endKeys;E=E;var D=Ss(this.schema,g,E),M=ic(g);if(!this.internals.byIndex[M])throw new Error("index does not exist "+M);for(var U=this.internals.byIndex[M].docsWithIndex,F=(i.inclusiveStart?KP:zl)(U,[S],ui),j=(i.inclusiveEnd?NP:AP)(U,[D],ui),$=[],V=!1;!V;){var W=U[F];if(!W||F>j)break;var ie=W[1];(!f||f(ie))&&$.push(ie),$.length>=d&&!y&&(V=!0),F++}if(y){var de=ys(this.schema,n.query);$=$.sort(de)}return $=$.slice(o,d),Promise.resolve({documents:$})},t.count=async function(n){this.ensurePersistence();var i=await this.query(n);return{count:i.documents.length,mode:"fast"}},t.cleanup=function(n){this.ensurePersistence();for(var i=Ze()-n,a=["_deleted","_meta.lwt",this.primaryPath],o=ic(a),u=this.internals.byIndex[o].docsWithIndex,d=Ii(this.schema,a,[!0,0,""]),f=zl(u,[d],ui),m=!1;!m;){var y=u[f];!y||y[1]._meta.lwt>i?m=!0:(BP(this.primaryPath,this.schema,this.internals,y[1]),f++)}return xn},t.getAttachmentData=function(n,i,a){this.ensurePersistence(),_a(this);var o=Pa(n,i),u=this.internals.attachments.get(o);if(!a||!u||u.digest!==a)throw new Error("attachment does not exist: "+o);return Promise.resolve(u.writeData.data)},t.changeStream=function(){return _a(this),this.internals.changes$.asObservable()},t.remove=async function(){if(this.closed)throw new Error("closed");this.ensurePersistence(),_a(this),this.internals.removed=!0,this.storage.collectionStates.delete(Af(this.databaseName,this.collectionName,this.schema.version)),await this.close()},t.close=function(){return Vl.delete(this),this.ensurePersistence(),this.closed||(this.closed=!0,this.internals.refCount=this.internals.refCount-1),nt},e})();function UP(e,t,r){var n=Af(t.databaseName,t.collectionName,t.sc
44hema.version),i=e.collectionStates.get(n);if(!i)i={id:Tn(5),schema:t.schema,removed:!1,refCount:1,documents:new Map,attachments:t.schema.attachments?new Map:void 0,byIndex:{},changes$:new He},FP(i,t.schema),e.collectionStates.set(n,i);else{if(t.devMode&&!En(i.schema,t.schema))throw new Error("storage was already created with a different schema");i.refCount=i.refCount+1}var a=new LP(e,t.databaseName,t.collectionName,t.schema,i,t.options,r,t.devMode);return Promise.resolve(a)}var WP=new Map;function Nf(e={}){var t={name:"memory",rxdbVersion:hc,collectionStates:WP,createStorageInstance(r){_c(r);var n=Object.assign({},e,r.options);return UP(this,r,n)}};return t}function as(e,t){var r=$c(t);return Wr(e.indexIdByName,r)}var $P={locale:null,unique:!1};function qP(e,t){t.indexIds.forEach((r=>{e.createIndex(r,r,$P)}))}function HP(e,t,r,n){for(var i={i:r,d:n,i0:void 0,i1:void 0,i2:void 0,i3:void 0,i4:void 0,i5:void 0,i6:void 0,i7:void 0},a=0;a<e;++a){var o=(0,t[a])(n);i["i"+a]=o}return i}function JP(e){var t={},r=e.indexes?e.indexes.map((i=>Array.isArray(i)?i.slice(0):[i])):[];r.push(si);var n=new Map;return r.forEach(((i,a)=>{var o="i"+a,u=$c(i);if(n.has(u))throw new Error("duplicate index "+u+" "+JSON.stringify(e,null,4));n.set(u,o),t[o]=cf(e,i)})),{indexIdByName:n,monadByIndexId:t}}var jP="documents",zP="wal",GP="attachments",VP={durability:"relaxed"},Mf="indexeddb",YP=0;function Ma(e,t){return e+"||"+t}var Yl=new Map;function Bf(e,t){var r=it(Yl,e,(()=>nt));return r=Z(r).then((()=>t())),Yl.set(e,r),r}async function QP(e,t,r){var n=YP++,i=await rI(e,r.indexedDB),a=async()=>(await pi(0),Bf(e.databaseName,(()=>new Promise(((u,d)=>{var f=i.open(e.databaseName);f.onerror=function(m){console.error(n+": OPEN IDB DATABASE "+e.databaseName+" ERROR"),d(m)},f.onsuccess=function(m){var y=f.result;u(y),Ff(o,y)},Uf(o,f)}))))),o={indexedDB:i,debugId:n,closed:!1,storage:t,settings:r,refreshIDBDatabase:a,creationPromise:a(),name:e.databaseName,refCount:0,storesToOpen:[]};return o}function Ff(e,t){t.onversionchange=r=>{e.closed||(t.close(),e.creationPromise=e.refreshIDBDatabase())}}async function XP(e,t,r,n){var i=await it(e.indexedDBStates,r.databaseName,(()=>QP(r,e,t)));return i.storesToOpen=i.storesToOpen.concat(n),i.refCount=i.refCount+1,i.creationPromise.then((()=>Lf(Z(i)))).then((()=>Z(i)))}async function Lf(e){if(e.storesToOpen.length!==0)return e.creationPromise=e.creationPromise.then((async t=>{var r=new Set(Array.from(t.objectStoreNames));if(e.storesToOpen.filter((i=>!r.has(qc(i.collectionName,i.schema).documentStore))).length===0)return t;var n=t.version+1;return t.close(),Bf(e.name,(()=>new Promise(((i,a)=>{var o=e.indexedDB.open(e.name,n);o.onerror=function(u){console.error(e.debugId+": ERROR openStoresOnExistingDatabase() openRequest: error "),a(u)},o.onsuccess=function(u){var d=o.result;Ff(e,d),i(d)},o.onblocked=u=>{},Uf(e,o)}))))})),e.creationPromise}function qc(e,t){var r=t.version;return{documentStore:e+"-"+r+"-"+jP,writeAheadStore:e+"-"+r+"-"+zP,attachmentsStore:e+"-"+r+"-"+GP}}function Uf(e,t){t.onupgradeneeded=function(r){var n=t.result;e.storesToOpen.forEach((i=>{var a=n.objectStoreNames,o=qc(i.collectionName,i.schema);if(!a.contains(o.documentStore)){var u=n.createObjectStore(o.documentStore,{keyPath:"i",autoIncrement:!1});n.createObjectStore(o.writeAheadStore,{keyPath:"i",autoIncrement:!1}),qP(u,i),i.schema.attachments&&n.createObjectStore(o.attachmentsStore,{keyPath:"docIdWithAttachmentId",autoIncrement:!1})}})),e.storesToOpen=[]}}async function ZP(e){if(!e.closed&&(e.refCount=e.refCount-1,e.refCount===0))return e.closed=!0,e.storage.indexedDBStates.delete(e.name),e.creationPromise.then((t=>t.close()))}function ln(e){if(e.closed)throw new Error("RxStorageInstanceIndexedDB is closed "+e.databaseName+"-"+e.collectionName)}async function Wf(e,t){var r=e.primaryPath,n=e.internals.indexIds.length,i=e.internals.getIndexableStringByIndexNumber,a=t.objectStore(e.internals.storeNames.writeAheadStore),o=await new Promise(((w,S)=>{var E=a.get("documents");E.onerror=S,E.onsuccess=D=>{var M=E.result;w(M?JSON.parse(M.docsData):void 0)}}));if(o&&o.length>0){for(var u,d=t.objectStore(e.internals.storeNames.documentStore),f=0;f<o.length;++f){var m=o[f],y=m[r],g=HP(n,i,y,m);u=d.put(g)}await new Promise(((w,S)=>{u.onerror=S,u.onsuccess=()=>w(!0)})),a.delete("documents")}return t}async function Hc(e){var t,r=[e.internals.storeNames.documentStore,e.internals.storeNames.writeAheadStore];e.schema.attachments&&r.push(e.internals.storeNames.attachmentsStore);for(var n=100;n>0;){var i=await e.internals.state.creationPromise;n-=1;try{t=i.transaction(r,"readwrite",VP);break}catch(a){if(a.name!=="InvalidStateError"&&a.name!=="NotFoundError"||!(n>0))throw a;a.name==="NotFoundError"?await Lf(e.internals.state):e.internals.state.creationPromise=e.internals.state.refreshIDBDatabase()}}return await Wf(e,Z(t)),Z(t)}var eI=(function(){function e(t){this.allTasksRuns=[],this.instance=t,this.txPromise=Hc(this.instance).then((r=>Wf(t,r)))}return e.prototype.addTask=function(t){var r=this.txPromise.then((a=>t(a))),n=r.catch((()=>null));this.allTasksRuns.push(n);var i=this.allTasksRuns.length;return n.then((()=>Promise.all(this.allTasksRuns))).then((()=>{this.allTasksRuns.length===i&&(this.instance.openReadonlyTransaction=void 0)})),r.catch((a=>
44{if(a.name==="TransactionInactiveError")return this.instance.openReadonlyTransaction=void 0,hr(this.instance,t);throw a}))},e})();function hr(e,t){return e.openReadonlyTransaction||(e.openReadonlyTransaction=new eI(e)),e.openReadonlyTransaction.addTask(t)}function tI(e,t){var r=(e.settings.IDBKeyRange?e.settings.IDBKeyRange:IDBKeyRange).lowerBound(It,!0),n=t.getKey(r);return new Promise((i=>{n.onsuccess=()=>{i(!!n.result)}}))}function rI(e,t){return typeof t=="function"?t(e):t}async function Ql(e,t){return hr(e,(async r=>{var n=t.queryPlan,i=t.query,a=i.skip?i.skip:0,o=a+(i.limit?i.limit:1/0),u=e.internals.storeNames.documentStore,d=e.settings.batchSize?e.settings.batchSize:50,f=!1;n.selectorSatisfiedByIndex||(f=Fi(e.schema,i));var m=n.index,y=!n.sortSatisfiedByIndex,g=m,w=n.startKeys,S=Ii(e.schema,g,w),E=n.endKeys,D=Ss(e.schema,g,E),M=[],U=r.objectStore(u),F=as(e.internals,g),j=U.index(F);f||t.query.limit||(d=1e5);var $=!1;if(await nI(e,n,j,d,S,D,F,(W=>{for(var ie=0;ie<W.length;ie++){var de=W[ie].d;if($||f&&!f(de)||M.push(de),!y&&M.length===o){$=!0;break}}return!$})),y){var V=ys(e.schema,i);M=M.sort(V)}return{documents:M=M.slice(a,o)}}))}async function nI(e,t,r,n,i,a,o,u){var d=e.settings.IDBKeyRange?e.settings.IDBKeyRange:IDBKeyRange,f=e.internals.getIndexableStringByIndexId[o];if(typeof r.getAll=="function"&&n!==1)for(var m,y=!0,g=!1,w=async function(){m&&(i=f(m.d));var D=d.bound(i,a,!y||!t.inclusiveStart,!t.inclusiveEnd);y=!1;var M=r.getAll(D,n);await new Promise(((U,F)=>{M.onerror=F,M.onsuccess=j=>{var $=j.target.result;m=ls($),$.length!==0&&u($)===!1&&(g=!0),$.length<n&&(g=!0),U()}}))};!g;)await w();else{var S=d.bound(i,a,!t.inclusiveStart,!t.inclusiveEnd),E=r.openCursor(S);await new Promise((D=>{E.onsuccess=function(M){var U=M.target.result;if(U){var F=U.value;u([F])?U.continue():D()}else D()}}))}}async function iI(e,t){return hr(e,(async r=>{var n,i=t.queryPlan,a=e.internals.storeNames.documentStore,o=i.index,u=o,d=i.startKeys,f=Ii(e.schema,u,d),m=i.endKeys,y=Ss(e.schema,u,m),g=r.objectStore(a);n=o.length===1&&o[0]===e.primaryPath?as(e.internals,["_deleted",e.primaryPath]):as(e.internals,u);var w=g.index(n),S=(e.settings.IDBKeyRange?e.settings.IDBKeyRange:IDBKeyRange).bound(f,y,!i.inclusiveStart,!i.inclusiveEnd),E=w.count(S);return{count:await new Promise(((D,M)=>{E.onsuccess=function(){D(E.result)},E.onerror=M})),mode:"fast"}}))}function aI(e,t,r){var n=t.length;if(n===0)return Promise.resolve([]);for(var i=new Array(n),a=0;a<n;a++){var o=t[a];i[a]=e.get(o)}var u=[],d=Z(ls(i));return new Promise(((f,m)=>{d.onerror=m,d.onsuccess=()=>{for(var y=0;y<n;y++){var g=i[y].result;if(g){var w=g.d;!r&&w._deleted||u.push(w)}}f(u)}}))}function sI(e,t,r){var n=r.length,i=new Map;if(n===0)return Promise.resolve(i);for(var a=new Array(n),o=0;o<n;o++){var u=r[o].document[e],d=t.get(u);a[o]=d}var f=Z(ls(a));return new Promise(((m,y)=>{f.onerror=y,f.onsuccess=()=>{for(var g=0;g<n;g++){var w=a[g].result;if(w){var S=w.d,E=S[e];i.set(E,S)}}m(i)}}))}async function oI(e,t,r){var n=e.primaryPath,i=e.internals,a=e.internals.state;await a.creationPromise;var o=[i.storeNames.documentStore,i.storeNames.writeAheadStore];e.schema.attachments&&o.push(i.storeNames.attachmentsStore),ln(e);var u,d=await Hc(e),f=d.objectStore(i.storeNames.documentStore);u=e.internals.minKnownDocsAmount===0&&t.length>30&&!await tI(e,f)?new Map:await sI(n,f,t);for(var m=Sc(e,n,u,t,r),y=m.errors,g=m.bulkInsertDocs,w=new Array(g.length),S=0;S<g.length;++S){var E=g[S].document;w[S]=E}for(var D,M=m.bulkUpdateDocs,U=0;U<M.length;++U){var F=M[U].document;w.push(F)}if(w.length>0){var j=d.objectStore(i.storeNames.writeAheadStore).put({i:"documents",docsData:JSON.stringify(w)});await new Promise(((W,ie)=>{j.onerror=ie,j.onsuccess=W})),e.handleWalIdlePromise||pi(100).then((()=>On())).then((async()=>{e.handleWalIdlePromise=void 0,e.closed||await hr(e,(()=>Rt))}))}if(e.schema.attachments){var $=d.objectStore(e.internals.storeNames.attachmentsStore);m.attachmentsAdd.forEach((W=>{D=$.put({docIdWithAttachmentId:Ma(W.documentId,W.attachmentId),length:W.attachmentData.length,type:W.attachmentData.type,data:W.attachmentData.data})})),m.attachmentsUpdate.forEach((W=>{D=$.put({docIdWithAttachmentId:Ma(W.documentId,W.attachmentId),length:W.attachmentData.length,type:W.attachmentData.type,data:W.attachmentData.data})})),m.attachmentsRemove.forEach((W=>{D=$.delete(Ma(W.documentId,W.attachmentId))}))}if(D&&await new Promise(((W,ie)=>{Z(D).onerror=ie,Z(D).onsuccess=W})),d.commit&&d.commit(),m.eventBulk.events.length>0){var V=Z(m.newestRow).document;m.eventBulk.checkpoint={id:V[n],lwt:V._meta.lwt},e.changes$.next(m.eventBulk)}return{error:y}}var cI=Ze(),uI=(function(){function e(r,n,i,a,o,u,d){this.changes$=new He,this.instanceId=cI++,this.storage=r,this.databaseName=n,this.collectionName=i,this.schema=a,this.internals=o,this.options=u,this.settings=d,this.primaryPath=et(this.schema.primaryKey)}var t=e.prototype;return t.updateMinKnownDocs=function(r){this.internals.minKnownDocsAmount<r&&(this.internals.minKnownDocsAmount=r)},t.bulkWrite=async function(r,n){var i=await oI(this,r,n);return this.updateMinKnownDocs(r.length-i.error.length),i},t.findDocumentsById=async function(r,n){ln(this);var i=await hr(this,(async a=>{var o=a.objectStore(this.internals.storeNames.documentStore);return aI(o,r,n)}));return this.updateMinKnownDocs(i.length),i},t.query=async function(r){await this.internals.state.creationPromise,ln(this);var n=await Ql(this,r);return this.updateMinKnownDocs(n.documents.length),n},t.count=async function(r){if(r.queryPlan.selectorSatisfiedByIndex){var n=await iI(this,r);return this.updateMinKnownDocs(n.count),n}var i=await Ql(this,r);return this.updateMinKnownDocs(i.documents.length),{count:i.documents.length,mode:"slow"}},t.changeStream=function(){return this.changes$.asObservable()},t.cleanup=async function(r){await pi(0),await pi(0);var n=this.internals.state;await n.creationPromise;var i=this.settings.IDBKeyRange;ln(this);var a=(await Hc(this)).objectStore(this.internals.storeNames.documentStore),o=this.settings.batchSize,u=Ze()-r,d=as(this.internals,si),f=a.index(d),m=Ii(this.schema,si,[!0,1]),y=Ss(this.schema,si,[!0,u]),g=i.bound(m,y,!0,!0),w=await new Promise(((S,E)=>{var D=f.getAll(g,o);D.onerror=E,D.onsuccess=function(M){S(M.target.result)}}));return await Promise.all(w.map((S=>new Promise(((E,D)=>{var M=S.i,U=a.delete(M);U.onerror=D,U.onsuccess=()=>E()}))))),w.length<o},t.remove=async function(){var r=this.internals.state;return await r.creationPromise,ln(this),hr(this,(async n=>{var i=[n.objectStore(this.internals.storeNames.documentStore),n.objectStore(this.internals.storeNames.writeAheadStore)];return this.schema.attachments&&i.push(n.objectStore(this.internals.storeNames.attachmentsStore)),await Promise.all(i.map((a=>new Promise(((o,u)=>{var d=a.clear();d.onerror=u,d.onsuccess=o}))))),this.close()}))},t.getAttachmentData=async function(r,n){var i=this.internals.state;return await i.creationPromise,ln(this),hr(this,(a=>{var o=a.objectStore(this.internals.storeNames.attachmentsStore),u=Ma(r,n);return new Promise(((d,f)=>{var m=o.get(u);m.onsuccess=()=>{var y=m.result;y?d(y.data):f("attachment missing documentId: "+r+" attachmentId: "+n)}}))}))},t.close=async function(){return this.closed||(this.closed=(async()=>(await this.internals.state.creationPromise,await hr(this,(async r=>{})),this.changes$.complete(),ZP(this.internals.state)))()),this.closed},e})();async function lI(e,t,r){var n=JP(t.schema),i=Array.from(n.indexIdByName.values()),a=await XP(e,r,t,[{collectionName:t.collectionName,schema:t.schema,indexIds:i}]);await a.creationPromise;
44var o={state:a,storeNames:qc(t.collectionName,t.schema),getIndexableStringByIndexId:n.monadByIndexId,getIndexableStringByIndexNumber:Object.values(n.monadByIndexId),indexIdByName:n.indexIdByName,indexNames:Object.keys(n),indexIds:i,minKnownDocsAmount:0},u=new uI(e,t.databaseName,t.collectionName,t.schema,o,t.options,r);return await of(Mf,t,u),u}var dI=(function(){function e(t){this.name=Mf,this.rxdbVersion=L_,this.indexedDBStates=new Map,this.settings=t}return e.prototype.createStorageInstance=function(t){_c(t);var r=Object.assign({},this.settings,t.options);return lI(this,t,r)},e})();function hI(e={}){var t=e.IDBKeyRange?e.IDBKeyRange:IDBKeyRange,r=e.indexedDB?e.indexedDB:indexedDB,n=Object.assign({batchSize:300,transactionDurability:"relaxed"},e,{IDBKeyRange:t,indexedDB:r});return new dI(n)}const fI=[kP,hI,Nf],pI="lmwrRxdb",ac=`${pI}Registry`,Jc=()=>{try{return localStorage.getItem(ac)}catch{return null}},$f=(e,t)=>{try{e.size>0&&t?localStorage.setItem(ac,t):localStorage.removeItem(ac)}catch{}},mI=e=>{try{const t=JSON.parse(e);if(Array.isArray(t)){const[r]=t;return r||null}return typeof t=="string"&&t||null}catch{return e||null}},jc=e=>{if(!e)return new Set;try{return new Set(JSON.parse(e))}catch{return new Set}},qf=e=>{try{return JSON.stringify(Array.from(e))}catch{return null}},yI=e=>{const t=jc(Jc());t.add(e),$f(t,qf(t))},vI=(e,t)=>{const r=jc(Jc()),n=Array.from(r).filter(i=>e&&i.includes(e));return Promise.all(n.map(i=>Promise.all(fI.map(a=>Kc(e,a()).catch(()=>null).finally(()=>r.delete(i)))).then(()=>{typeof window.indexedDB.databases=="function"&&window.indexedDB.databases().catch(()=>null).then(a=>{if(a)try{a.forEach(o=>{o.name&&o.name.includes(e)&&window.indexedDB.deleteDatabase(o.name)})}catch{}})}))).then(()=>{$f(r,qf(r))})},FC=async(e,t)=>{for(const r of e)await vI(r)},LC=()=>{const e=jc(Jc());return Array.from(e).map(t=>mI(t)).filter(t=>t!==null)},Hf=Pe.createContext(null),Xl=(e=Hf)=>Pe.useContext(e),Zl=e=>{const{openRxdbInstance:t,children:r,context:n=Hf}=e,i=n,[a,o]=Pe.useState(null);if(Pe.useEffect(()=>{const u=new AbortController;return t(u.signal).then(d=>{if(!u.signal.aborted&&Wh(d.database))return o(d),yI(d.database.name),d}).catch(d=>{u.signal.aborted||o(Ct(d,new Error(`Rxdb couldn't be created: ${d}.`)))}),o(null),()=>{u.abort()}},[t]),a instanceof Error)throw a;return ce.jsx(i.Provider,{value:a,children:r})};class gI{constructor(t){this.getContentItemEncryptionKeys=t,this.encryptionKeysCache=new Map}dispose(){this.encryptionKeysCache.clear()}async getEncryptionKeys(t){const r=`${t}`,n=this.encryptionKeysCache.get(r);if(n)return Promise.resolve(n);const i=this.getContentItemEncryptionKeys(t).then(a=>(this.encryptionKeysCache.set(r,a),a));return this.encryptionKeysCache.set(r,i),i}}function wI(e){return new Worker("/build/workers/content-item-decrypter.worker-CKUlJ-H0.js",{name:e==null?void 0:e.name})}function bI(e){return new SharedWorker("/build/workers/content-item-decrypter.worker-CKUlJ-H0.js",{name:e==null?void 0:e.name})}const SI=(e,t,r)=>{let n=!1;const i=[],a=Ke(),o=setTimeout(()=>{const u={contentItems:i};a.resolve([u,Um(d=>Ba(t.getDownloadUrls({sharingBucketId:e,xTurnstileToken:d,generateDownloadUrlsRequest:u}))).then(d=>n?bt(new Br("Canceled","Canceled")):d)])},r);return{requestPromise:a.promise,cancel:()=>{n=!0,clearTimeout(o)},addItems:u=>{const d=Array.isArray(u)?u:[u];i.push(...d)}}},EI=()=>{const e=new Map,t=new Map,r=new Map,n=new Map,i=new Map,a=new Map,o=new Map;return{decryptionKeysCache:e,nameCache:t,fileCache:r,previewCache:n,dataBlobCache:i,exportedPrivateKeyCache:a,blobUrlCache:o,clear:()=>{e.clear(),t.clear(),r.clear(),i.clear(),o.forEach(({url:u})=>{URL.revokeObjectURL(u)}),o.clear()}}},_I=()=>{try{if(typeof SharedWorker=="function"){const t=new bI;return t.port.start(),{worker:t,addMessageEventListener:r=>{t.port.addEventListener("message",r)},removeMessageEventListener:r=>{t.port.removeEventListener("message",r)},postMessage:(...r)=>{t.port.postMessage(...r)},terminate:()=>{t.port.close()}}}}catch{}const e=new wI;return{worker:e,addMessageEventListener:t=>{e.addEventListener("message",t)},removeMessageEventListener:t=>{e.removeEventListener("message",t)},postMessage:(...t)=>{e.postMessage(...t)},terminate:()=>{e.terminate()}}};class PI{constructor(t,r,n,i={}){this.getContentItemDecryptionKeys=t,this.getContentItemExportedPrivateKey=r,this.apiOptions=n,this.store=i,this.events=new Zp,this.localCache=EI(),this.decrypterWorker=_I(),this.previewDownloadInfoBatches=new Map,this.fileDownloadInfoBatches=new Map,this.abortController=new AbortController,this.downloadApi=di(k_,n,{init:{signal:this.abortController.signal}})}dispose(){this.localCache.clear(),this.previewDownloadInfoBatches.forEac
44h(t=>t.cancel()),this.previewDownloadInfoBatches.clear(),this.fileDownloadInfoBatches.forEach(t=>t.cancel()),this.fileDownloadInfoBatches.clear(),this.decrypterWorker.terminate(),this.abortController.abort()}decryptName(t){const r=this.getCachedDecryptedName(t);if(r)return Promise.resolve(r);const{promise:n,resolve:i}=Ke(),a=this.getLocalNameCacheKey(t),o=d=>{var f,m;this.localCache.nameCache.set(a,d),this.events.emit("onNameDecrypted",[d]),(m=(f=this.store).storeDecryptedName)==null||m.call(f,t,d.decryptedName),i(d)};return this.localCache.nameCache.set(a,n),(async()=>{const d=await this.getSharedCachedDecryptedName(t);if(d)return o({contentItem:{...t},decryptedName:d});if(this.store.getDecryptedName){const m=await this.store.getDecryptedName(t);if(m)return o({contentItem:{...t},decryptedName:m})}const f=m=>{const{data:y}=m;if(y.type!=="decryptName"||y.contentItem.id!==t.id||y.contentItem.nameEncrypted!==t.nameEncrypted)return;this.decrypterWorker.removeMessageEventListener(f);const{decryptedName:g}=y;o({decryptedName:g,contentItem:{...t}})};this.decrypterWorker.addMessageEventListener(f),this.decrypterWorker.postMessage({type:"decryptName",contentItem:t,decryptionKeysSerialized:await Ca(await this.getDecryptionKeys(t))})})(),n}decryptPreviews(t,r,n){const i=r.previews||[];return(n?i.filter(({id:o})=>!!n.find(u=>u.id===o)):i).map(o=>{const u=this.getCachedDecryptedPreview(r,o);if(u)return Promise.resolve(u);const{promise:d,resolve:f,reject:m}=Ke(),y=this.getLocalPreviewCacheKey(r,o),g=w=>{this.localCache.previewCache.set(y,w),this.events.emit("onPreviewDecrypted",[w]),this.store.storeDecryptedPreview&&this.getDecryptedDataBlob(w.decryptedData).then(S=>{var E,D;return(D=(E=this.store).storeDecryptedPreview)==null?void 0:D.call(E,r,o,S)}),f(w)};return this.localCache.previewCache.set(y,d),(async()=>
44{const w=await this.getSharedCachedDecryptedData(r,o);if(w)return g({contentItem:{...r},previewItem:{...o},decryptedData:w});if(this.store.getDecryptedPreview){const D=await this.store.getDecryptedPreview(r,o);if(D)return g({contentItem:{...r},previewItem:{...o},decryptedData:this.createContentItemDecryptedData(D,r.id,o.id)})}const S=await this.getDownloadInfo(t,r,o),E=await this.getDownloadServiceWorkerContentItemUrl(t,r,S,o);if(E)g({contentItem:{...r},previewItem:{...o},decryptedData:{url:E}});else{const{decryptedData:D}=await this.downloadAndDecryptData(r,S,o);g({contentItem:{...r},previewItem:{...o},decryptedData:D})}})().catch(w=>{this.localCache.previewCache.delete(y),m(w)}),d})}decryptFile(t,r){const n=this.getCachedDecryptedFile(r);if(n)return Promise.resolve(n);const{promise:i,resolve:a,reject:o}=Ke(),u=this.getLocalFileCacheKey(r),d=f=>{this.localCache.fileCache.set(u,f),this.events.emit("onFileDecrypted",[f]),a(f)};return this.localCache.fileCache.set(u,i),(async()=>{const f=await this.getSharedCachedDecryptedData(r);if(f)return d({contentItem:{...r},decryptedData:f});const m=await this.getDownloadInfo(t,r),y=await this.getDownloadServiceWorkerContentItemUrl(t,r,m);if(y)d({contentItem:{...r},decryptedData:{url:y}});else{const{decryptedData:g}=await this.downloadAndDecryptData(r,m);d({contentItem:{...r},decryptedData:g})}})().catch(f=>{this.localCache.fileCache.delete(u),o(f)}),i}getDecryptionKeys(t){const r=`${t.baseFileEncryptionKeyId}${t.ephemeralPublicKey}`,n=this.localCache.decryptionKeysCache.get(r);if(n)return Promise.resolve(n);const i=this.getContentItemDecryptionKeys(t).then(a=>(this.localCache.decryptionKeysCache.set(r,a),a));return this.localCache.decryptionKeysCache.set(r,i),i}getExportedPrivateKey(t){const r=`${t.baseFileEncryptionKeyId}${t.ephemeralPublicKey}`,n=this.localCache.exportedPrivateKeyCache.get(r);if(n)return Promise.resolve(n);const i=this.getDecryptionKeys(t).then(a=>this.getContentItemExportedPrivateKey(t,a)).then(a=>(this.localCache.exportedPrivateKeyCache.set(r,a),a));return this.localCache.exportedPrivateKeyCache.set(r,i),i}getDecryptedDataBlob(t){const{blob:r,url:n}=t;if(r)return Promise.resolve(r);const i=`${n}`,a=this.localCache.dataBlobCache.get(i);if(a)return Promise.resolve(a);const{promise:o,resolve:u}=Ke();return this.localCache.dataBlobCache.set(i,o),(async()=>{const d=await sc(n,{retry:us({maxDelay:45e3})});if(!d.ok)return;const f=await d.value.blob();this.localCache.dataBlobCache.set(i,f),u(f)})(),o}getDecryptedName(t){const r=this.getCachedDecryptedName(t);if(!(!r||r instanceof Promise))return r}getDecryptedFile(t){const r=this.getCachedDecryptedFile(t);if(!(!r||r instanceof Promise))return r}getDecryptedPreview(t,r){const n=this.getCachedDecryptedPreview(t,r);if(!(!n||n instanceof Promise))return n}getCachedDecryptedName(t){return this.localCache.nameCache.get(this.getLocalNameCacheKey(t))}getCachedDecryptedPreview(t,r){return this.localCache.previewCache.get(this.getLocalPreviewCacheKey(t,r))}getCachedDecryptedFile(t){return this.localCache.fileCache.get(this.getLocalFileCacheKey(t))}getDownloadInfo(t,r,n){const{promise:i,resolve:a,reject:o}=Ke(),u=this.getDownloadInfoBatch(t,!!n),d=n?{id:r.id,metadataId:n.id}:{id:r.id};return u.addItems(d),u.requestPromise.then(([f,m])=>{m.then(y=>{if(!y.ok){o(y.error);return}const{contentItems:g}=y.value,w=g.find(({id:S,metadataId:E})=>S===d.id&&E===d.metadataId);if(!w){o(new Error(`Couldn't get download info for content item: ${d.id}${d.metadataId?` (${d.metadataId})`:""}`));return}a(w)})}),i}getDownloadInfoBatch(t,r){const n=r?this.previewDownloadInfoBatches:this.fileDownloadInfoBatches,i=n.get(t)||SI(t,this.downloadApi,150);return n.set(t,i),{...i,requestPromise:i.requestPromise.then(a=>(n.delete(t),a))}}downloadAndDecryptData(t,r,n){const{promise:i,resolve:a}=Ke();return(async()=>{const{downloadUrl:u}=r,d=f=>{const{data:m}=f;m.type!=="downloadAndDecryptData"||m.downloadUrl!==u||(this.decrypterWorker.removeMessageEventListener(d),a({contentItemDownloadInfo:r,decryptedData:this.createContentItemDecryptedData(m.decryptedData,r.id,r.metadataId)}))};this.decrypterWorker.addMessageEventListener(d),this.decrypterWorker.postMessage({type:"downloadAndDecryptData",contentItem:t,previewItem:n,downloadUrl:u,decryptionKeysSerialized:await Ca(await this.getDecryptionKeys(t))})})(),i}async getDownloadServiceWorkerContentItemUrl(t,r,{downloadUrl:n},i){return Oo.getInstance().createContentItem({sharingBucketId:t,contentItem:r,decryptionKeysSerialized:await Ca(await this.getDecryptionKeys(r)),downloadUrl:n,previewItem:i},this.apiOptions).then(a=>a?(this.abortController.signal.addEventListener("abort",()=>{a.dispose()}),a.getUrl()):null)}getSharedCachedDecryptedName(t){const{promise:r,resolve:n}=Ke(),i=a=>{const{data:o}=a;o.type!=="cachedDecryptedName"||o.contentItem.id!==t.id||(this.decrypterWorker.removeMessageEventListener(i),n(o.decryptedName))};return this.decrypterWorker.addMessageEventListener(i),this.decrypterWorker.postMessage({type:"cachedDecryptedName",contentItem:t}),r}getSharedCachedDecryptedData(t,r){const{promise:n,resolve:i}=Ke(),a=o=>{var d;const{data:u}=o;u.type!=="cachedDecryptedData"||u.contentItem.id!==t.id||((d=u.previewItem)==null?void 0:d.id)!==(r==null?void 0:r.id)||(this.decrypterWorker.removeMessageEventListener(a),i(u.decryptedData&&this.createContentItemDecryptedData(u.decryptedData,t.id,r==null?void 0:r.id)))};return this.decrypterWorker.addMessageEventListener(a),this.decrypterWorker.postMessage({type:"cachedDecryptedData",contentItem:t,previewItem:r}),n}createContentItemDecryptedData(t,r,n){const i=`${r}${n}`,a=this.localCache.blobUrlCache.get(i);if(a)return a;const o={contentItemId:r,previewItemId:n,blob:t,url:URL.createObjectURL(t)};return this.localCache.blobUrlCache.set(i,o),o}getLocalNameCacheKey(t){return`${t.id}${t.nameEncrypted}`}getLocalFileCacheKey(t){return`${t.id}`}getLocalPreviewCacheKey(t,r){return`${t.id}${r.id}`}addEvents(t){return this.events.addEvents(t)}on(t,r){return this.events.on(t,r)}removeEvents(t){return this.events.removeEvents(t)}off(t,r){return this.events.off(t,r)}}const ed=new Map;class II{generateKeyPair(){const{keyProperties:t,keyUsages:r}=rt.getKeyProperties("ASYMMETRIC_PRIVATE_KEY");return crypto.subtle.generateKey(t,!0,r)}deserializeRawPublicKey(t){const r=ed.get(t);if(r)return r;const{keyProperties:n}=rt.getKeyProperties("ASYMMETRIC_PRIVATE_KEY"),i=crypto.subtle.importKey("raw",_t(t),n,!0,[]);return ed.set(t,i),i}async buildEcdhPrivateKey(t,r){return this.doBuild(Ne(await this.exportCryptoKey(t)),r)}async buildEcdhPrivateKeyWithPublicKeyString(t,r){return this.buildEcdhPrivateKeyWithUnwrappedKeys(Ne(await this.exportCryptoKey(t)),r)}async verifyCryptoKeyPair(t){const r="ECDSA",n="SHA-256",a=["sign"],o=["verify"],[u,d]=await Promise.all([crypto.subtle.exportKey("jwk",t.privateKey),crypto.subtle.exportKey("jwk",t.publicKey)]);u.key_ops=a,d.key_ops=o;const[f,m]=await Promise.all([crypto.subtle.importKey("jwk",u,{name:r,namedCurve:u.crv},!1,a),crypto.subtle.importKey("jwk",d,{name:r,namedCurve:d.crv},!1,o)]),y=new TextEncoder().encode(crypto.randomUUID()),g=await crypto.subtle.sign({name:r,hash:{name:n}},f,y);return crypto.subtle.verify({name:r,hash:{name:n}},m,g,y)}async buildEcdhPrivateKeyWithUnwrappedKeys(t,r){return this.doBuild(t,await this.deserializeRawPublicKey(r))}async deriveAesEncryptionKey(t,r,n){const i=rt.getKeyProperties(n);return crypto.subtle.deriveKey({name:"ECDH",public:r},t,i.keyProperties,!0,i.keyUsages)}async exportCryptoKey(t){if(t.type==="private"){const r=await crypto.subtle.exportKey("jwk",t);if(!r.d)throw new Error("Couldn't export private key.");return _t(md(r.d))}return crypto.subtle.exportKey("raw",t)}async doBuild(t,r){const n=await crypto.subtle.exportKey("jwk",r);return n.d=pd(t),n.key_ops=["deriveBits","deriveKey"],crypto.subtle.importKey("jwk",n,{name:"ECDH",namedCurve:"P-256"},!0,["deriveBits","deriveKey"])}}const ei=new Map;class CI{constructor(t,r,n,i,a){this.dataStore=t,this.symmetricKeyService=r,this.asymmetricKeyService=n,this.getPassphraseFn=i,this.createDefaultUserEncryptionKeyFn=a,this.getPassphrasePromise=Ku(),this.createDefaultUserEncryptionKeyPromise=Ku()}async getUserEncryptionKey(t){return this.dataStore.findById(t)}async getOrCreateDefaultEncryptionKey(){const t=await this.dataStore.getLatest();return t||this.createDefaultUserEncryptionKeyPromise.getOrCreate(()=>this.createDefaultUserEncryptionKeyFn())}async getKeyWrappingKey(t){return(await this.resolveEncryptionKeys(t)).symmetricCryptoKey}async hasValidDefaultEncryptionKey(){try{const t=await this.getOrCreateDefaultEncryptionKey();return t?!!await this.getKeyWrappingKey(t):!1}catch{return!1}}async wrapUserEncryptionKeyWithOtherUserEncryptionKey(t,r,n,i){if(t.id===r.id)throw new Error("Can't wrap UserEncryptionKey with itself");n||(n=await this.resolveEncryptionKeys(t)),i||(i=(await this.resolveEncryptionKeys(r)).symmetricCryptoKey);const a=await this.symmetricKeyService.extractPrivateKeyAndWrapWithWrappingKey(i,n.asymmetricCryptoKeyPair.privateKey),o=await this.symmetricKeyService.extractPrivateKeyAndWrapWithWrappingKey(i,n.symmetricCryptoKey);return t.privateKeys=[{type:"KEY_WRAPPED",wrappedKeyWrappingKey:Ne(o),wrappedAsymmetricPrivateKey:Ne(a),wrappedByKeyId:r.id}],t}async derivePassphrase(t,r){const n=new TextEncoder;return Ne(await crypto.subtle.deriveBits({name:"PBKDF2",salt:n.encode(r),iterations:1e5,hash:{name:"SHA-256"}},await crypto.subtle.importKey("raw",n.encode(t),{name:"PBKDF2"},!1,["deriveBits"]),256))}async createUserEncryptionKey(t){const[r,n,i,a]=await Promise.all([this.asymmetricKeyService.generateKeyPair(),this.symmetricKeyService.createKeyWrappingKey(),this.symmetricKeyService.randomSalt(),this.symmetricKeyService.randomSalt()]),[o,u,d]=await Promise.all([this.asymmetricKeyService.exportCryptoKey(r.publicKey),this.symmetricKeyService.extractPrivateKeyAndWrapWithPassphrase(t,i,r.privateKey),this.symmetricKeyService.wrapWithPassphrase(t,a,n)]);return{userEncryptionKey:{id:crypto.randomUUID(),deleted:!1,publicKey:Ne(o),createdDate:new Date,privateKeys:[{type:"PASSPHRASE_WRAPPED",wrappedAsymmetricPrivateKey:Ne(u),wrappedKeyWrappingKey:Ne(d),asymmetricKeyPassphraseSalt:Ne(i),keyWrappingKeyPassphraseSalt:Ne(a)}]},symmetricCryptoKey:n,asymmetricCryptoKeyPair:r,passphrase:t}}async changeDefaultEncryptionKeyPassphrase(t,r){const n=this.symmetricKeyService.randomSalt(),i=this.symmetricKeyService.randomSalt(),{asymmetricCryptoKeyPair:a,symmetricCryptoKey:o,userEncryptionKey:u}=await(r?this.unwrapEncryptionKeyWithPassphrase(await this.getOrCreateDefaultEncryptionKey(),r):this.unwrapDefaultEncryptionKey()),d=await this.symmetricKeyService.extractPrivateKeyAndWrapWithPassphrase(t,n,a.privateKey),f=await this.symmetricKeyService.wrapWithPassphrase(t,i,o);return{userEncryptionKey:{...u,privateKeys:[{type:"PASSPHRASE_WRAPPED",wrappedAsymmetricPrivateKey:Ne(d),wrappedKeyWrappingKey:Ne(f),asymmetricKeyPassphraseSalt:Ne(n),keyWrappingKeyPassphraseSalt:Ne(i)}]},symmetricCryptoKey:o,asymmetricCryptoKeyPair:a,passphrase:t}}async isDefaultEncryptionKeyPassphrase(t){const r=await this.getOrCreateDefaultEncryptionKey();return!!await this.unwrapUserEncryptionKeyWithPassphrase(r,t).catch(()=>null)}async unwrapEncryptionKeyWithPassphrase(t,r){return this.unwrapUserEncryptionKeyWithPassphrase(t,r)}async unwrapDefaultEncryptionKey(){return this.unwrapUserEncryptionKeyWithPassphrase(await this.getOrCreateDefaultEncryptionKey())}async unwrapUserEncryptionKeyWithPassphrase(t,r){const n=typeof r=="string",i=n?r:await this.getPassphrasePromise.getOrCreate(()=>this.getPassphraseFn()).catch(o=>{throw this.getPassphrasePromise.invalidate(),o}),a=async()=>(this.getPassphrasePromise.invalidate(),this.createDefaultUserEncryptionKeyPromise.invalidate(),await this.unwrapUserEncryptionKeyWithPassphrase(await this.getOrCreateDefaultEncryptionKey()));
44if(typeof i!="string")return a();for(const o of t.privateKeys)if(o.type==="PASSPHRASE_WRAPPED"){if(!o.wrappedKeyWrappingKey||!o.wrappedAsymmetricPrivateKey)throw new Error(`UserEncryptionKey "${t.id}" has invalid private keys`);try{const[u,d,f]=await Promise.all([this.symmetricKeyService.unwrapKeyWithPassphrase(i,_t(o.keyWrappingKeyPassphraseSalt),_t(o.wrappedKeyWrappingKey),"WRAPPING_KEY"),this.symmetricKeyService.unwrapKeyWithPassphrase(i,_t(o.asymmetricKeyPassphraseSalt),_t(o.wrappedAsymmetricPrivateKey),"WRAPPED_ASYMMETRIC_PRIVATE_KEY"),this.asymmetricKeyService.deserializeRawPublicKey(t.publicKey)]),y={privateKey:await this.asymmetricKeyService.buildEcdhPrivateKey(d,f),publicKey:f};return ei.set(t.id,{userEncryptionKey:t,symmetricCryptoKey:u,asymmetricCryptoKeyPair:y}),{userEncryptionKey:t,passphrase:i,symmetricCryptoKey:u,asymmetricCryptoKeyPair:y}}catch(u){if(n)throw new Error(`Passphrase decryption of key "${t.id}" failed: "${Ct(u).message}"`);return a()}}throw new Error(`UserEncryptionKey "${t.id}" is not passphrase wrapped`)}async resolveEncryptionKeys(t){var i;const r=await this.resolveEncryptionKeyGraph(t);if(r.length===1)return ei.get(t.id);let n;for(let a=r.length-2;a>=0;a--){const o=r[a],u=r[a+1],d=(i=ei.get(u.id))==null?void 0:i.symmetricCryptoKey;for(const f of o.privateKeys)if(f.wrappedByKeyId===u.id){if(!f.wrappedAsymmetricPrivateKey||!f.wrappedKeyWrappingKey)throw Error(`UserEncryptionKey ${o} contains`);const[m,y,g]=await Promise.all([this.symmetricKeyService.unwrapKeyWithWrappingKey(d,_t(f.wrappedKeyWrappingKey),"WRAPPING_KEY"),this.symmetricKeyService.unwrapKeyWithWrappingKey(d,_t(f.wrappedAsymmetricPrivateKey),"WRAPPED_ASYMMETRIC_PRIVATE_KEY"),this.asymmetricKeyService.deserializeRawPublicKey(o.publicKey)]);n={userEncryptionKey:o,symmetricCryptoKey:m,asymmetricCryptoKeyPair:{publicKey:g,privateKey:y}},ei.set(o.id,n)}}return n}async resolveEncryptionKeyGraph(t){if(ei.has(t.id))return[t];for(const r of t.privateKeys)switch(r.type){case"PASSPHRASE_WRAPPED":{const{userEncryptionKey:n}=await this.unwrapUserEncryptionKeyWithPassphrase(t);return[n]}case"KEY_WRAPPED":{const n=await this.dataStore.findById(r.wrappedByKeyId);if(!n)throw new Error(`UserEncryptionKey ${r.wrappedByKeyId} is referenced but not present in datastore`);return[t,...await this.resolveEncryptionKeyGraph(n)]}}throw new Error(`UserEncryptionKey graph could not be resolved for key ${t.id}`)}}class kI{constructor(t,r,n,i){this.dataStore=t,this.symmetricKeyService=r,this.asymmetricKeyService=n,this.userKeysService=i}async generateFileEncryptionKey(){return this.createFileEncryptionKey({fileEncryptionKeyId:crypto.randomUUID(),keyPair:await this.asymmetricKeyService.generateKeyPair()})}async cryptoKeyPairToFileEncryptionKey({fileEncryptionKeyId:t,keyPair:r}){return this.createFileEncryptionKey({fileEncryptionKeyId:t,keyPair:r})}async getFileEncryptionKey(t){return this.dataStore.findById(t)}async getExportedFileEncryptionCryptoKey(t){return Ne(await this.asymmetricKeyService.exportCryptoKey(t.cryptoKey))}async getFileEncryptionCryptoKey(t,r,n){const i=await this.resolveEncryptionKeyGraph(t);if(!i)throw new Error(`No path found to decrypt FileEncryptionKey: "${t.id}"`);return{aesKeyType:n,cryptoKey:await this.asymmetricKeyService.deriveAesEncryptionKey(i,await this.asymmetricKeyService.deserializeRawPublicKey(r),n)}}async deriveFileEncryptionKeyWrappingKey(t,r){return await crypto.subtle.deriveKey({name:"ECDH",public:r},t,{name:"AES-KW",length:256},!0,["wrapKey","unwrapKey"])}async wrapFileEncryptionKeyWithOtherFileEncryptionKey(t,r){const n=await this.resolveEncryptionKeyGraph(t);if(!n)throw new Error(`Couldn't resolve private key for FileEncryptionKey ${t.id}`);const i=await this.deriveFileEncryptionKeyWrappingKey(n,await this.deserializePublicKey(r.publicKey));return this.symmetricKeyService.extractPrivateKeyAndWrapWithWrappingKey(i,n)}async deriveFileEncryptionCryptoKey(t,r,n){return{aesKeyType:n,cryptoKey:await this.asymmetricKeyService.deriveAesEncryptionKey(t,r,n)}}async wrapPrivateKeyWithUserEncryptionKey(t,r){return{encryptedPrivateKey:Ne(await this.symmetricKeyService.extractPrivateKeyAndWrapWithWrappingKey(await this.userKeysService.getKeyWrappingKey(r),t)),encryptedByKeyId:r.id,encryptedByKeyType:"USER_ENCRYPTION_KEY"}}async importPrivateKey(t,r){return this.asymmetricKeyService.buildEcdhPrivateKeyWithUnwrappedKeys(t,r.publicKey)}async exportPrivateKey(t){const r=await this.resolveEncryptionKeyGraph(t);if(!r)throw new Error(`Unable to resolved file encryption key: "${t.id}"`);return this.asymmetricKeyService.exportCryptoKey(r)}async getFileEncryptionKeyAesCryptoKey(t,r){const n=rt.getKeyProperties(r);return{aesKeyType:r,cryptoKey:await crypto.subtle.importKey("raw",await this.exportPrivateKey(t),n.keyProperties,!0,n.keyUsages)}}async generatePassphraseWrappedPrivateKey(t,r,n){const i=await this.resolveEncryptionKeyGraph(t);if(!i)throw new Error(`Unable to resolved file encryption key: "${t.id}"`);return this.symmetricKeyService.extractPrivateKeyAndWrapWithPassphrase(r,n,i)}async deserializePublicKey(t){return this.asymmetricKeyService.deserializeRawPublicKey(t)}async encryptAesGcm(t,r,n){return{iv:n,encryptedData:(await this.symmetricKeyService.encryptAesGcm(t,r,n)).encryptedData}}async resolveEncryptionKeyGraph(t){for(const r of t.privateKeys){if(r.encryptedByKeyType!=="USER_ENCRYPTION_KEY")continue;const n=await this.userKeysService.getUserEncryptionKey(r.encryptedByKeyId);if(n){const i=await this.symmetricKeyService.unwrapKeyWithWrappingKey(await this.userKeysService.getKeyWrappingKey(n),_t(r.encryptedPrivateKey),"WRAPPED_ASYMMETRIC_PRIVATE_KEY");return this.asymmetricKeyService.buildEcdhPrivateKeyWithPublicKeyString(i,t.publicKey)}}for(const r of t.privateKeys){if(r.encryptedByKeyType!=="FILE_ENCRYPTION_KEY")continue;const n=await this.dataStore.findById(r.encryptedByKeyId);if(n){const i=await this.resolveEncryptionKeyGraph(n);if(i){const a=await this.deriveFileEncryptionKeyWrappingKey(i,await this.deserializePublicKey(t.publicKey)),o=await this.symmetricKeyService.unwrapKeyWithWrappingKey(a,_t(r.encryptedPrivateKey),"WRAPPED_ASYMMETRIC_PRIVATE_KEY");return await this.asymmetricKeyService.buildEcdhPrivateKeyWithPublicKeyString(o,t.publicKey)}}}}async createFileEncryptionKey({fileEncryptionKeyId:t,keyPair:r}){const n=await this.userKeysService.getOrCreateDefaultEncryptionKey();return{id:t,deleted:!1,createdDate:new Date,privateKeys:[await this.wrapPrivateKeyWithUserEncryptionKey(r.privateKey,n)],publicKey:Ne(await this.asymmetricKeyService.exportCryptoKey(r.publicKey))}}}class RI{constructor(t,r){this.asymmetricKeyService=t,this.fileEncryptionKeyService=r}async createEncryptionKeys(t){const r=await this.fileEncryptionKeyService.getFileEncryptionKey(t);if(!r)throw new Error(`Could not find encryption FileEncryptionKey: "${t}"`);const n=await this.asymmetricKeyService.deserializeRawPublicKey(r.publicKey),i=await this.asymmetricKeyService.generateKeyPair(),[a,o,u]=await Promise.all([this.asymmetricKeyService.exportCryptoKey(i.publicKey),this.fileEncryptionKeyService.deriveFileEncryptionCryptoKey(i.privateKey,n,"SYMMETRIC_AES-GCM_KEY"),this.fileEncryptionKeyService.deriveFileEncryptionCryptoKey(i.privateKey,n,"SYMMETRIC_AES-CTR_KEY")]);return{ephemeralPublicKey:Ne(a),aesGcmCryptoKey:o,aesCtrCryptoKey:u}}async getDecryptionKeys({baseFileEncryptionKeyId:t,ephemeralPublicKey:r}){const n=await this.fileEncryptionKeyService.getFileEncryptionKey(t);if(!n)throw new Error(`Could not find decryption FileEncryptionKey: "${t}"`);const[i,a]=await Promise.all([this.fileEncryptionKeyService.getFileEncryptionCryptoKey(n,r,"SYMMETRIC_AES-GCM_KEY"),this.fileEncryptionKeyService.getFileEncryptionCryptoKey(n,r,"SYMMETRIC_AES-CTR_KEY")]);return{aesGcmCryptoKey:i,aesCtrCryptoKey:a}}}class on{constructor(t,r,n){this.collection=t,this.entitiyFromCollectionTypeRaw=r,this.entityToCollectionTypeRaw=n}entitiyFromCollectionType(t){try{return this.entitiyFromCollectionTypeRaw(t)}catch(r){const n=Ct(r);throw console.error(`EntitiyFromCollectionType Error in collection "${this.collection.name}" on document "${this.getDocumentPrimaryKey(t)}
44"`,n),n}}entityToCollectionType(t){try{return this.entityToCollectionTypeRaw(t)}catch(r){const n=Ct(r);throw console.error(`EntityToCollectionType Error in collection "${this.collection.name}" on entity "${this.getDocumentPrimaryKey(t)}"`,n),n}}async insert(t){const r=await this.collection.insert(this.entityToCollectionType(t));return this.entitiyFromCollectionType(this.docToJson(r))}async upsert(t){const r=await this.collection.upsert(this.entityToCollectionType(t));return this.entitiyFromCollectionType(this.docToJson(r))}async incrementalUpsert(t){const r=await this.collection.incrementalUpsert(this.entityToCollectionType(t));return this.entitiyFromCollectionType(this.docToJson(r))}async modify(t,r){const n=await this.collection.findOne(t).modify(async i=>this.entityToCollectionType(await r({...i,...this.entitiyFromCollectionType(i)})));return n&&this.entitiyFromCollectionType(this.docToJson(n))}async incrementalModify(t,r){const n=await this.collection.findOne(t).incrementalModify(async i=>this.entityToCollectionType(await r({...i,...this.entitiyFromCollectionType(i)})));return n&&this.entitiyFromCollectionType(this.docToJson(n))}async patch(t,r){return this.modify(t,n=>({...n,...r}))}async incrementalPatch(t,r){return this.incrementalModify(t,n=>({...n,...r}))}async remove(t){const r=await this.collection.findOne(t).remove();return r&&this.entitiyFromCollectionType(this.docToJson(r))}async incrementalRemove(t){const r=await this.collection.findOne(t).incrementalRemove();return r&&this.entitiyFromCollectionType(this.docToJson(r))}async removeByIds(t){const r=[...await this.collection.findByIds(t).exec()],n=await Promise.all(r.map(async([,i])=>i.remove()));return new Map(r.map(([i],a)=>[i,this.entitiyFromCollectionType(this.docToJson(n[a]))]))}async findOne(t){const r=await this.collection.findOne(t).exec();return r&&this.entitiyFromCollectionType(this.docToJson(r))}async find(t){return(await this.collection.find(t).exec()).map(r=>this.entitiyFromCollectionType(this.docToJson(r)))}async count(t){return await this.collection.count(t).exec()}async findByIds(t){return new Map([...await this.collection.findByIds(t).exec()].map(([r,n])=>[r,this.entitiyFromCollectionType(this.docToJson(n))]))}subscribe(t,r){return this.collection.find(t).$.subscribe(n=>r(n.map(i=>this.entitiyFromCollectionType(this.docToJson(i)))))}subscribeCount(t,r){return this.collection.count(t).$.subscribe(r)}subscribeById(t,r){return this.collection.findOne(t).$.subscribe(n=>r(n?this.entitiyFromCollectionType(this.docToJson(n)):null))}subscribeByIds(t,r){return this.collection.findByIds(t).$.subscribe(n=>r(new Map([...n].map(([i,a])=>[i,this.entitiyFromCollectionType(this.docToJson(a))]))))}docToJson(t){return{...t.toJSON(),deleted:t.deleted}}getDocumentPrimaryKey(t){const r=this.collection.schema.primaryPath,n=t&&typeof t=="object"?t[r]:void 0;return typeof n=="string"||typeof n=="number"?`${n}`:"unknown"}}const zc="lmwrRxdbAnon",UC=()=>{try{return localStorage.getItem(zc)}catch{return null}},DI=e=>{try{localStorage.setItem(zc,e)}catch{}},WC=()=>{try{localStorage.removeItem(zc)}catch{}},Gc={MANAGED:"managed-passphrase",USER_DEFINED:"user-passphrase"},xI=async(e,t)=>{const r=Gc[t],n=await e.getLocal(r).catch(()=>null),i=n==null?void 0:n.get(r);return typeof i=="string"?i:null},Jf=async(e,t,r)=>{const n=Gc[r];await e.upsertLocal(n,{[n]:t}).catch(()=>null)},OI=async(e,t)=>{const r=Gc[t],n=await e.getLocal(r).catch(()=>null);await(n==null?void 0:n.remove())},jf=(e,t)=>{const r=e.rxdbFileEncryptionKeyUtils.collection.$.subscribe(t),n=e.rxdbUserEncryptionKeyUtils.collection.$.subscribe(t);return()=>{r.unsubscribe(),n.unsubscribe()}},TI=(e,t)=>{const r=[e,t].filter(n=>!!n);return{async findById(n){const i={selector:{id:n}};return(await Promise.all(r.map(o=>o.rxdbUserEncryptionKeyUtils.findOne(i)))).find(o=>!!o)||null},async getLatest(){const n={sort:[{createdDate:"desc"}]};return(await Promise.all(r.map(a=>a.rxdbUserEncryptionKeyUtils.find(n)))).flat().find(a=>a!==null&&!!a.privateKeys.find(({type:o})=>o==="PASSPHRASE_WRAPPED"))||null}}},KI=(e,t)=>({async findById(r){const n={selector:{id:r}};return(await Promise.all([e,t].map(a=>a.rxdbFileEncryptionKeyUtils.findOne(n)))).find(a=>!!a)||null}}),AI=e=>({async createContentItem(t,r){await e.rxdbContentItemUtils.insert(t),await e.rxdbSharingBucketUtils.incrementalModify(r,n=>({...n,contentItemIds:[...n.contentItemIds,t.id]}))},async updateContentItem(t){await e.rxdbContentItemUtils.incrementalPatch(t.id,t)},async finishContentItem(t,r){await e.rxdbContentItemUtils.incrementalPatch(t.id,t),await e.rxdbSharingBucketUtils.incrementalModify(r,n=>({...n,totalFileSize:(n.totalFileSize||0)+t.size}))},async removeContentItem(t,r){await e.rxdbContentItemUtils.incrementalRemove(t.id),await e.rxdbSharingBucketUtils.incrementalModify(r,n=>({...n,contentItemIds:n.contentItemIds.filter(i=>i!==t.id)}))}}),NI=(e,t)=>r=>{const{promise:n,resolve:i}=Ke(),a=async()=>{const u=await e.createEncryptionKeys(r).catch(()=>null);
44u&&(o.forEach(d=>d()),i(u))},o=t.map(u=>jf(u,a));return a(),n},MI=(e,t)=>r=>{const{promise:n,resolve:i}=Ke(),a=async()=>{const u=await e.getDecryptionKeys(r).catch(()=>null);u&&(o.forEach(d=>d()),i(u))},o=t.map(u=>jf(u,a));return a(),n},td=e=>{const t=new on(e.sharing_bucket,Lc,HE),r=new on(e.content_item,mf,LE),n=new on(e.file_encryption_key,Uc,jE),i=new on(e.user_encryption_key,pf,Rn),a=new on(e.user,P_,C_),o=new on(e.platform_action_history,o_,u_);return{rxdb:e,rxdbSharingBucketUtils:t,rxdbContentItemUtils:r,rxdbFileEncryptionKeyUtils:n,rxdbUserEncryptionKeyUtils:i,rxdbUserUtils:a,rxdbPlatformActionHistoryUtils:o}},BI={multiInstance:!1,replicationWaitForLeadership:!1},FI=(e,t,r,n,i)=>{const a=rs(e,t);return o=>Rf(o,a,r(),n,i)},LI=(e,t)=>{const r=rs(e,t,!0);return n=>Rf(n,r,Nf(),BI)},UI=async(e,{options:t,userId:r,isAnonymous:n,getRxdbStorage:i,openAuthModal:a,openUpgradeModal:o},u,d,f,m)=>{let y=null;const g=td(f.database),w=td(m.database),S=TI(g,w),E=Lp(t.apiOptions,{init:{signal:e}}),D=us({maxDelay:45e3,maxRetryCount:6}),M=async()=>{const{userEncryptionKey:fe}=await di(yf,{...E,retry:D}).getOrCreateUserEncryptionKey();return fe},U=()=>
44{if(!r)return Promise.resolve("MANAGED");const{promise:fe,resolve:ve}=Ke(),ne=g.rxdbUserUtils.subscribeById(r,we=>{ve(we?we.userEncryptionKeyType:"MANAGED")});return fe.then(we=>(ne.unsubscribe(),we))},F=new rt,j=new II,$=new CI(S,F,j,async()=>{const fe=y,ve=await U(),ne=async _e=>(_e&&await Jf(f.database,_e,ve),_e),we=fe!==ve;if(y=ve,we){const _e=await xI(f.database,ve);if(_e)return _e}return ne(ve===Rm.Managed?(await Up(di(yd,{...E,retry:D}).getPassphrase())).passphrase:await d())},M),V=new kI(KI(g,w),F,j,$),W=new RI(j,V),ie=new gI(NI(W,[g,w])),de=new PI(MI(W,[g,w]),(fe,ve)=>V.getExportedFileEncryptionCryptoKey(ve.aesCtrCryptoKey),E),Se=t.upload.createUploader({apiOptions:E,multipartOptions:t.upload.multipartOptions,contentItemEncrypter:ie,dataStore:AI(g)}),ue=t.download.createDownloader({apiOptions:E,multipartOptions:t.download.multipartOptions,contentItemDecrypter:de});r&&n&&!e.aborted&&DI(r);const re=Ke(),oe=r?g.rxdbUserUtils.subscribeById(r,fe=>{var ne;const ve={userTier:((ne=fe==null?void 0:fe.accountSubscription)==null?void 0:ne.tier)||ZS.Free,userBalance:(fe==null?void 0:fe.balance)||{credits:0,lmwr:0}};re.resolve(ve),e.aborted||u(({userTier:we,userBalance:_e})=>{if(we!==ve.userTier||_e.credits!==ve.userBalance.credits||_e.lmwr!==ve.userBalance.lmwr)return ve})}):re.resolve({userBalance:{credits:0,lmwr:0},userTier:"FREE"}),{userTier:ye,userBalance:Ie}=await re.promise,Je={userId:r,userTier:ye,userBalance:Ie,isAnonymous:n,contentItemEncrypter:ie,contentItemDecrypter:de,uploader:Se,downloader:ue,userKeyService:$,fileEncryptionKeyService:V,apiOptions:E,getRxdbStorage:i,awaitActiveRxdbReplication:async fe=>{const ve=f.replication.awaitActiveReplication();await(typeof fe=="number"?Promise.race([ve,new Promise(ne=>setTimeout(ne,fe))]):ve)},userRxdb:g,memoryRxdb:w,openAuthModal:a,openUpgradeModal:o},Me=()=>{e.removeEventListener("abort",Me),oe==null||oe.unsubscribe(),ie.dispose(),de.dispose(),Se.clear(),ue.clear()};return e.aborted?Me():e.addEventListener("abort",Me),Je},zf="lmwrFileSharingReplicationReloadAttempted",WI=()=>{try{return window.sessionStorage.getItem(zf)==="true"}catch{return!0}},$I=()=>{if(WI())return!1;try{window.sessionStorage.setItem(zf,"true")}catch{return!1}return window.location.reload(),!0},rd="Please enter a passphrase.",qI=od(zp(!0,rd),{emptyMessage:rd}),ss="All my uploaded data will be deleted",nd=`Please enter "${ss}" to continue.`,HI=fd({confirm:od(Vp().trim().toLowerCase().transform((e,t)=>e!==ss.toLowerCase()?(t.addIssue({code:Yp.custom,message:nd}),Qp):e),{emptyMessage:nd})}),JI=({onPassphraseReset:e})=>{const t=Gf(),{closeModal:r}=Gp(),n=Pe.useRef(null),[i,a]=Pe.useState(!1),[o,u]=Pe.useState(null),d=ni(e),f=o&&ce.jsx(Ia,{type:"success",description:"You successfully reset end-to-end encryption for your account.",children:"Success"});return Pe.useEffect(()=>{var m;(m=n.current)==null||m.focus()},[]),Pe.useEffect(()=>{if(o&&o.ok)return()=>{d(o.value)}},[d,o]),ce.jsx(ld,{header:ce.jsx(hd,{danger:!0,children:"Reset End-To-End encryption"}),children:f||ce.jsxs("div",{className:"flex flex-col gap-y-3",children:[ce.jsx(Ia,{type:"warning",description:ce.jsxs(ce.Fragment,{children:["If you forgot your passphrase, there's unfortunately no way to recover your uploaded data. When you proceed with resetting end-to-end encryption,"," ",ce.jsx("strong",{children:"ALL YOUR UPLOADED DATA WILL BE DELETED."})]}),children:"Caution!"}),ce.jsx(Fa,{schema:HI,feedback:o&&!o.ok&&ce.jsx(Ia,{type:"error",description:o.error.message,children:o.error.code}),formIsLoading:i,formOnSubmit:async()=>{const{userRxdb:m,apiOptions:y}=t;a(!0),u(null);try{const g=di(yd,y),w=await Ba(g.resetPassphrase());if(!w.ok)throw w.error;await Promise.all([Jf(m.rxdb,w.value.passphrase,"MANAGED"),OI(m.rxdb,"USER_DEFINED")]),u(w)}catch(g){u(bt(g instanceof Br?g:new Br(Ct(g).message,"Unexpected Error")))}a(!1)},children:({isLoading:m})=>ce.jsxs(ce.Fragment,{children:[ce.jsx(Fa.Input,{name:"confirm",label:"Confirmation",description:ce.jsxs(ce.Fragment,{children:['Enter "',ss,'" to continue.']}),placeholder:ss,ref:n}),ce.jsxs(dd,{children:[ce.jsx(Do,{theme:"danger",type:"submit",loading:m,children:"Reset"}),ce.jsx(Do,{theme:"white",onClick:()=>r(),children:"Close"})]})]})})]})})},jI=({onPassphraseReset:e,...t})=>ce.jsx(ud,{content:ce.jsx(JI,{onPassphraseReset:e}),...t}),zI=fd({passphrase:qI}),GI=({dismissButton:e,onPassphrase:t})=>{const{userKeyService:r,userId:n}=Gf(),[i,a]=Pe.useState(!1),[o,u]=Pe.useState(null),d=Pe.useRef(null);return Pe.useEffect(()=>{var f;
44(f=d.current)==null||f.focus()},[]),ce.jsx(ld,{header:ce.jsx(hd,{hideCloseButton:!0,children:"End-To-End encryption passphrase"}),children:({closeModal:f})=>ce.jsxs("div",{className:"flex flex-col gap-y-3 type-d-75 w-full",children:[ce.jsxs("div",{children:["Please enter the passphrase you chose for the end-to-end encryption."," ",ce.jsx(jI,{onPassphraseReset:()=>{location.reload()},children:({openModal:m})=>ce.jsx(Xp,{className:"inline-flex",paddingless:!0,onClick:()=>m(),children:"I have forgotten my passphrase."})})]}),ce.jsx(Fa,{schema:zI,feedback:o&&!o.ok&&ce.jsx(Ia,{type:"error",description:o.error.message,children:o.error.code}),formIsLoading:i,formOnSubmit:async({values:m})=>{const{passphrase:y}=m;if(n){a(!0),u(null);try{const g=await r.derivePassphrase(y,n);if(!await r.isDefaultEncryptionKeyPassphrase(g))throw new Br("The submitted passphrase is incorrect.","Incorrect Passphrase");t==null||t(g),f()}catch(g){a(!1),u(bt(g instanceof Br?g:new Br(Ct(g).message,"Unexpected Error")))}}},children:({isLoading:m})=>ce.jsxs(ce.Fragment,{children:[ce.jsx(Fa.SecretInput,{name:"passphrase",label:"Passphrase",description:"Enter the passphrase you chose for the end-to-end encryption.",placeholder:"â¢â¢â¢â¢â¢â¢",revealButtonLabelShow:"Show Passphrase",revealButtonLabelHide:"Hide Passphrase",ref:d}),ce.jsxs(dd,{children:[ce.jsx(Do,{type:"submit",loading:m,children:"Submit"}),e]})]})})]})})},VI=e=>{const{dismissButton:t,onPassphrase:r,...n}=e;return ce.jsx(ud,{content:ce.jsx(GI,{dismissButton:t,onPassphrase:r}),...n})},YI=Pe.forwardRef(function(t,r){const[n,i]=Pe.useState(new Set);return Pe.useImperativeHandle(r,()=>({addModal:a=>{i(o=>new Set([...o,a]))},removeModal:a=>{i(o=>(o.delete(a),new Set(o)))}}),[]),ce.jsx(ce.Fragment,{children:n})}),Es=Pe.createContext(null),$C=()=>Pe.useContext(Es),qC=()=>{const e=Pe.useContext(Es),[t,r]=cd(Ke());return Pe.useMemo(()=>{e?t().resolve(e):r(Ke())},[e,t,r]),ni(()=>t().promise)},Gf=()=>{const e=Pe.useContext(Es);if(!e)throw new Error("FileSharing not loaded yet.");return e},Vf=Pe.createContext(null),Yf=Pe.createContext(null),QI=e=>{const{options:t,userId:r,isAnonymous:n,getRxdbStorage:i,openAuthModal:a,openUpgradeModal:o,provideUserPassphraseDismissButton:u,children:d}=e,f=Xl(Vf),m=Xl(Yf),[y,g]=Pe.useState(null),[w,S]=cd(null),E=ni(()=>u),D=ni(a),M=ni(o);if(Pe.useEffect(()=>{if(!f||!m||f.database.name!==rs(r,n)||m.database.name!==rs(r,n,!0)){g(null);return}const U=new AbortController;return UI(U.signal,{options:t,userId:r,isAnonymous:n,getRxdbStorage:i,openAuthModal:D,openUpgradeModal:M},F=>{g(j=>{if(!j||j instanceof Error)return j;const $=F(j);return $?{...j,...$}:j})},async()=>{const F=w();if(!F)throw new Error("FileSharingContextProviderPassphraseModalRoot not found.");const{promise:j,resolve:$}=Ke(),{addModal:V,removeModal:W}=F,ie=ce.jsx(VI,{dismissButton:E(),onPassphrase:de=>{$(de)},onClosed:()=>{$(null),W(ie)},dismissible:!1,defaultOpen:!0},Date.now());return V(ie),j},f,m).then(F=>{U.signal.aborted||g(F)}).catch(F=>{U.signal.aborted||g(Ct(F,new Error(`FileSharing couldn't be created: ${F}.`)))}),g(null),()=>{U.abort()}},[t,n,f,r,m,i,E,w,D,M]),y instanceof Error)throw y;return ce.jsxs(Es.Provider,{value:y,children:[d,y&&ce.jsx(YI,{ref:U=>{S(U)}},y.userId)]})},HC=e=>{const{userId:t,isAnonymous:r,getRxdbStorage:n,options:i}=e,[a,o]=Pe.useState(null),[u,d]=Pe.useState(!1),f=Pe.useMemo(()=>FI(t,r,n,i.rxdb,!!t&&{isAnonymous:r,userId:t,apiOptions:i.apiOptions,onUnrecoverableReplicationError(y){o(y)}}),[t,r,n,i]),m=Pe.useMemo(()=>LI(t,r),[t,r]);if(Pe.useEffect(()=>{a&&($I()||d(!0))},[a]),a&&u)throw new Error(`Data Synchronization Error. Please reload the page. (${a.code})`);return a?null:ce.jsx(Zl,{openRxdbInstance:f,context:Vf,children:ce.jsx(Zl,{openRxdbInstance:m,context:Yf,children:ce.jsx(QI,{...e})})})};export{ZS as A,EC as B,mf as C,k_ as D,Zp as E,jE as F,FI as G,CC as H,WC as I,qI as J,Jf as K,wC as L,vd as M,IC as N,FC as O,vC as P,$C as Q,jI as R,PC as S,Bm as T,Gf as U,qC as V,II as a,_C as b,LE as c,Oo as d,HC as e,$m as f,gC as g,SC as h,yf as i,HE as j,rt as k,dn as l,_t as m,Ne as n,pd as o,md as p,td as q,jf as r,TI as s,BI as t,OI as u,UC as v,rs as w,xI as x,LC as y,hI as z}; 45!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;
45n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="57f337ec-4227-52d1-aacf-4eb4da72ba13")}catch(e){}}() 46//# debugId=57f337ec-4227-52d1-aacf-4eb4da72ba13 47//# sourceMappingURL=file-sharing-provider-DWrH9fGx.js.map
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.