PageSourceSearch

https://www.courseconnectai.com/_next/static/chunks/bc9e92e6-d30da11e70efe6f8.js

js courseconnectai.com collected 2026-10-02 01:26:26 UTC 284,054 bytes, 8 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2992],{6596:(e,t,n)=>{n.d(t,{$$:()=>cC,$1:()=>uK,$c:()=>uG,AB:()=>u$,AM:()=>c5,B:()=>lF,BN:()=>cd,Bh:()=>cJ,C3:()=>c$,CL:()=>cU,Ci:()=>ue,Cq:()=>uO,Cs:()=>lM,Dc:()=>W,EO:()=>uQ,F7:()=>cY,FA:()=>ee,FC:()=>cy,FD:()=>uY,Fs:()=>l9,G8:()=>u3,GA:()=>cO,GG:()=>cu,GV:()=>cK,Gv:()=>uW,H6:()=>lz,H9:()=>lV,HM:()=>uj,He:()=>_,Ix:()=>l3,J_:()=>cH,K$:()=>et,K7:()=>cM,LA:()=>l0,LV:()=>cj,Li:()=>uL,MH:()=>l1,Mh:()=>lB,My:()=>uB,NJ:()=>cr,O5:()=>cB,O8:()=>u7,O_:()=>c_,Os:()=>lZ,P:()=>uV,Q5:()=>lH,Rr:()=>ch,Rw:()=>tB,S0:()=>l7,St:()=>l5,T1:()=>lA,U9:()=>u8,Uo:()=>uq,V7:()=>ut,W6:()=>N,Wc:()=>l4,Wq:()=>ct,Ws:()=>lQ,XK:()=>lk,Y$:()=>$,YQ:()=>cn,YS:()=>lN,Z9:()=>c2,ZX:()=>cP,_7:()=>l$,_A:()=>lK,_M:()=>uF,_e:()=>cl,aQ:()=>cp,aU:()=>lG,bI:()=>k,c4:()=>cq,c8:()=>lv,cY:()=>cR,cm:()=>t1,cz:()=>u6,d_:()=>cI,eQ:()=>V,fS:()=>u2,gS:()=>cg,gT:()=>u9,hq:()=>cz,i1:()=>cG,iB:()=>lX,jy:()=>uU,kA:()=>c4,kL:()=>cS,kU:()=>cc,kd:()=>cm,lN:()=>ci,lo:()=>lT,mT:()=>cX,mZ:()=>cf,mc:()=>ce,me:()=>lJ,nY:()=>co,oN:()=>l6,ol:()=>lW,or:()=>uP,po:()=>l2,qG:()=>tU,qi:()=>E,rJ:()=>lR,rf:()=>uH,ts:()=>cD,uY:()=>l8,vK:()=>ck,vN:()=>lD,wP:()=>cQ,wx:()=>uM,wy:()=>B,x7:()=>cs,xC:()=>uz,yf:()=>cZ,yx:()=>lO,z6:()=>cw});var r,i,s,a,o=n(91398),l=n(22396),u=n(5969),c=n(57176),h=n(90916),d=n(24052),f=n(87358),m=n(81029).hp;let g="@firebase/firestore",p="4.7.17";class y{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}y.UNAUTHENTICATED=new y(null),y.GOOGLE_CREDENTIALS=new y("google-credentials-uid"),y.FIRST_PARTY=new y("first-party-uid"),y.MOCK_USER=new y("mock-user");let w="11.9.0",v=new u.Vy("@firebase/firestore");function I(){return v.logLevel}function _(e){v.setLogLevel(e)}function b(e,...t){if(v.logLevel<=u.$b.DEBUG){let n=t.map(x);v.debug(`Firestore (${w}): ${e}`,...n)}}function T(e,...t){if(v.logLevel<=u.$b.ERROR){let n=t.map(x);v.error(`Firestore (${w}): ${e}`,...n)}}function E(e,...t){if(v.logLevel<=u.$b.WARN){let n=t.map(x);v.warn(`Firestore (${w}): ${e}`,...n)}}function x(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function S(e,t,n){let r="Unexpected state";"string"==typeof t?r=t:n=t,C(e,r,n)}function C(e,t,n){let r=`FIRESTORE (${w}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==n)try{r+=" CONTEXT: "+JSON.stringify(n)}catch(e){r+=" CONTEXT: "+n}throw T(r),Error(r)}function D(e,t,n,r){let i="Unexpected state";"string"==typeof n?i=n:r=n,e||C(t,i,r)}function k(e,t){e||S(57014,t)}let A={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class N extends c.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class R{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class M{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class V{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(y.UNAUTHENTICATED))}shutdown(){}}class O{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class F{constructor(e){this.t=e,this.currentUser=y.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){D(void 0===this.o,42304);let n=this.i,r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve(),i=new R;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new R,e.enqueueRetryable(()=>r(this.currentUser))};let s=()=>{let t=i;e.enqueueRetryable(async()=>{await t.promise,await r(this.currentUser)})},a=e=>{b("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(b("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new R)}},0),s()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(b("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(D("str
1ing"==typeof t.accessToken,31837,{l:t}),new M(t.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){let e=this.auth&&this.auth.getUid();return D(null===e||"string"==typeof e,2055,{h:e}),new y(e)}}class L{constructor(e,t,n){this.P=e,this.T=t,this.I=n,this.type="FirstParty",this.user=y.FIRST_PARTY,this.A=new Map}R(){return this.I?this.I():null}get headers(){this.A.set("X-Goog-AuthUser",this.P);let e=this.R();return e&&this.A.set("Authorization",e),this.T&&this.A.set("X-Goog-Iam-Authorization-Token",this.T),this.A}}class P{constructor(e,t,n){this.P=e,this.T=t,this.I=n}getToken(){return Promise.resolve(new L(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(y.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class q{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class U{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,(0,o.xZ)(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){D(void 0===this.o,3512);let n=e=>{null!=e.error&&b("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let n=e.token!==this.m;return this.m=e.token,b("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>n(t))};let r=e=>{b("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(e=>r(e)),setTimeout(()=>{if(!this.appCheck){let e=this.V.getImmediate({optional:!0});e?r(e):b("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new q(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(D("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new q(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class B{getToken(){return Promise.resolve(new q(""))}invalidateToken(){}start(e,t){}shutdown(){}}function z(){return new TextEncoder}class ${static newId(){let e=62*Math.floor(256/62),t="";for(;t.length<20;){let n=function(e){let t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(40);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let e=0;e<40;e++)n[e]=Math.floor(256*Math.random());return n}(40);for(let r=0;r<n.length;++r)t.length<20&&n[r]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[r]%62))}return t}}function K(e,t){return e<t?-1:+(e>t)}function G(e,t){let n=0;for(;n<e.length&&n<t.length;){let r=e.codePointAt(n),i=t.codePointAt(n);if(r!==i){if(r<128&&i<128)return K(r,i);{let s=z(),a=function(e,t){for(let n=0;n<e.length&&n<t.length;++n)if(e[n]!==t[n])return K(e[n],t[n]);return K(e.length,t.length)}(s.encode(Q(e,n)),s.encode(Q(t,n)));return 0!==a?a:K(r,i)}}n+=r>65535?2:1}return K(e.length,t.length)}function Q(e,t){return e.codePointAt(t)>65535?e.substring(t,t+2):e.substring(t,t+1)}function j(e,t,n){return e.length===t.length&&e.every((e,r)=>n(e,t[r]))}class W{static now(){return W.fromMillis(Date.now())}static fromDate(e){return W.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),n=Math.floor((e-1e3*t)*1e6);return new W(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new N(A.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new N(A.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?K(this.nanoseconds,e.nanoseconds):K(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}
1}class H{static fromTimestamp(e){return new H(e)}static min(){return new H(new W(0,0))}static max(){return new H(new W(0x3afff4417f,0x3b9ac9ff))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}let Y="__name__";class J{constructor(e,t,n){void 0===t?t=0:t>e.length&&S(637,{offset:t,range:e.length}),void 0===n?n=e.length-t:n>e.length-t&&S(1746,{length:n,range:e.length-t}),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===J.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof J?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let n=Math.min(e.length,t.length);for(let r=0;r<n;r++){let n=J.compareSegments(e.get(r),t.get(r));if(0!==n)return n}return K(e.length,t.length)}static compareSegments(e,t){let n=J.isNumericId(e),r=J.isNumericId(t);return n&&!r?-1:!n&&r?1:n&&r?J.extractNumericId(e).compare(J.extractNumericId(t)):G(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return h.jz.fromString(e.substring(4,e.length-2))}}class X extends J{construct(e,t,n){return new X(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let n of e){if(n.indexOf("//")>=0)throw new N(A.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>e.length>0))}return new X(t)}static emptyPath(){return new X([])}}let Z=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ee extends J{construct(e,t,n){return new ee(e,t,n)}static isValidIdentifier(e){return Z.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),ee.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===Y}static keyField(){return new ee([Y])}static fromServerFormat(e){let t=[],n="",r=0,i=()=>{if(0===n.length)throw new N(A.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""},s=!1;for(;r<e.length;){let t=e[r];if("\\"===t){if(r+1===e.length)throw new N(A.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new N(A.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new N(A.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new ee(t)}static emptyPath(){return new ee([])}}class et{constructor(e){this.path=e}static fromPath(e){return new et(X.fromString(e))}static fromName(e){return new et(X.fromString(e).popFirst(5))}static empty(){return new et(X.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===X.comparator(this.path,e.path)}toString(){return this.path.toString()}
1static comparator(e,t){return X.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new et(new X(e.slice()))}}class en{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function er(e){return e.fields.find(e=>2===e.kind)}function ei(e){return e.fields.filter(e=>2!==e.kind)}function es(e,t){let n=K(e.collectionGroup,t.collectionGroup);if(0!==n)return n;for(let r=0;r<Math.min(e.fields.length,t.fields.length);++r)if(0!==(n=function(e,t){let n=ee.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:K(e.kind,t.kind)}(e.fields[r],t.fields[r])))return n;return K(e.fields.length,t.fields.length)}en.UNKNOWN_ID=-1;class ea{constructor(e,t){this.fieldPath=e,this.kind=t}}class eo{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new eo(0,ec.min())}}function el(e,t){let n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1;return new ec(H.fromTimestamp(1e9===r?new W(n+1,0):new W(n,r)),et.empty(),t)}function eu(e){return new ec(e.readTime,e.key,-1)}class ec{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new ec(H.min(),et.empty(),-1)}static max(){return new ec(H.max(),et.empty(),-1)}}function eh(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n||0!==(n=et.comparator(e.documentKey,t.documentKey))?n:K(e.largestBatchId,t.largestBatchId)}let ed="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ef{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function em(e){if(e.code!==A.FAILED_PRECONDITION||e.message!==ed)throw e;b("LocalStore","Unexpectedly lost primary lease")}class eg{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&S(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new eg((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof eg?t:eg.resolve(t)}catch(e){return eg.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):eg.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):eg.reject(t)}static resolve(e){return new eg((t,n)=>{t(e)})}static reject(e){return new eg((t,n)=>{n(e)})}static waitFor(e){return new eg((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=eg.resolve(!1);for(let n of e)t=t.next(e=>e?eg.resolve(e):n());return t}static forEach(e,t){let n=[];return e.forEach((e,r)=>{n.push(t.call(this,e,r))}),this.waitFor(n)}static mapArray(e,t){return new eg((n,r)=>{let i=e.length,s=Array(i),a=0;for(let o=0;o<i;o++){let l=o;t(e[l]).next(e=>{s[l]=e,++a===i&&n(s)},e=>r(e))}})}static doWhile(e,t){return new eg((n,r)=>{let i=()=>{!0===e()?t().next(()=>{i()},r):n()};i()})}}let ep="SimpleDb";class ey{static open(e,t,n,r){try{return new ey(t,e.transaction(r,n))}catch(e){throw new e_(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.S=new R,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{t.error?this.S.reject(new e_(e,t.error)):this.S.resolve()},this.transaction.onerror=t=>{let n=eS(t.target.error);this.S.reject(new e_(e,n))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(b(ep,"Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}v(){let e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){return new eT(this.transaction.objectStore(e))}}class ew{static delete(e){return b(ep,"Removing database:",e),eE((0,c.mS)().indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!(0,c.zW)())return!1;if(ew.F())return!0;let e=(0,c.ZQ)(),t=ew.M(e),n=ev(e);return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||0<t&&t<10||0<n&&n<4.5)}static F(){var e;return void 0!==f&&"YES"===(null==(e=f.__PRIVATE_env)?void 0:e.O)}static N(e,t){return e.store(t)}static M(e){let t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i);return Number(t?t[1].split("_").slice(0,2).join("."):"-1")}constructor(e,t,n){this.name=e,this.version=t,this.B=n,this.L=null,12.2===ew.M((0,c.ZQ)())&&T("Firestore persistence suffers from a bug in 
1iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async k(e){return this.db||(b(ep,"Opening database:",this.name),this.db=await new Promise((t,n)=>{let r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{t(e.target.result)},r.onblocked=()=>{n(new e_(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{let r=t.target.error;"VersionError"===r.name?n(new N(A.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===r.name?n(new N(A.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+r)):n(new e_(e,r))},r.onupgradeneeded=e=>{b(ep,'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);let t=e.target.result;if(null!==this.L&&this.L!==e.oldVersion)throw Error(`refusing to open IndexedDB database due to potential corruption of the IndexedDB database data; this corruption could be caused by clicking the "clear site data" button in a web browser; try reloading the web page to re-initialize the IndexedDB database: lastClosedDbVersion=${this.L}, event.oldVersion=${e.oldVersion}, event.newVersion=${e.newVersion}, db.version=${t.version}`);this.B.q(t,r.transaction,e.oldVersion,this.version).next(()=>{b(ep,"Database upgrade to version "+this.version+" complete")})}}),this.db.addEventListener("close",e=>{let t=e.target;this.L=t.version},{passive:!0})),this.$&&(this.db.onversionchange=e=>this.$(e)),this.db}U(e){this.$=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){let i="readonly"===t,s=0;for(;;){++s;try{this.db=await this.k(e);let t=ey.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next(e=>(t.v(),e)).catch(e=>(t.abort(e),eg.reject(e))).toPromise();return s.catch(()=>{}),await t.D,s}catch(t){let e="FirebaseError"!==t.name&&s<3;
1if(b(ep,"Transaction failed with error:",t.message,"Retrying:",e),this.close(),!e)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function ev(e){let t=e.match(/Android ([\d.]+)/i);return Number(t?t[1].split(".").slice(0,2).join("."):"-1")}class eI{constructor(e){this.K=e,this.W=!1,this.G=null}get isDone(){return this.W}get j(){return this.G}set cursor(e){this.K=e}done(){this.W=!0}H(e){this.G=e}delete(){return eE(this.K.delete())}}class e_ extends N{constructor(e,t){super(A.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function eb(e){return"IndexedDbTransactionError"===e.name}class eT{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(b(ep,"PUT",this.store.name,e,t),n=this.store.put(t,e)):(b(ep,"PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),eE(n)}add(e){return b(ep,"ADD",this.store.name,e,e),eE(this.store.add(e))}get(e){return eE(this.store.get(e)).next(t=>(void 0===t&&(t=null),b(ep,"GET",this.store.name,e,t),t))}delete(e){return b(ep,"DELETE",this.store.name,e),eE(this.store.delete(e))}count(){return b(ep,"COUNT",this.store.name),eE(this.store.count())}J(e,t){let n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){let e=r.getAll(n.range);return new eg((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}})}{let e=this.cursor(n),t=[];return this.Y(e,(e,n)=>{t.push(n)}).next(()=>t)}}Z(e,t){let n=this.store.getAll(e,null===t?void 0:t);return new eg((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}})}X(e,t){b(ep,"DELETE ALL",this.store.name);let n=this.options(e,t);n.ee=!1;let r=this.cursor(n);return this.Y(r,(e,t,n)=>n.delete())}te(e,t){let n;t?n=e:(n={},t=e);let r=this.cursor(n);return this.Y(r,t)}ne(e){let t=this.cursor({});return new eg((n,r)=>{t.onerror=e=>{r(eS(e.target.error))},t.onsuccess=t=>{let r=t.target.result;r?e(r.primaryKey,r.value).next(e=>{e?r.continue():n()}):n()}})}Y(e,t){let n=[];return new eg((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{let i=e.target.result;if(!i)return void r();let s=new eI(i),a=t(i.primaryKey,i.value,s);if(a instanceof eg){let e=a.catch(e=>(s.done(),eg.reject(e)));n.push(e)}s.isDone?r():null===s.j?i.continue():i.continue(s.j)}}).next(()=>eg.waitFor(n))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){let n=this.store.index(e.index);return e.ee?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function eE(e){return new eg((t,n)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{n(eS(e.target.error))}})}let ex=!1;function eS(e){let t=ew.M((0,c.ZQ)());if(t>=12.2&&t<13){let t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){let e=new N("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return ex||(ex=!0,setTimeout(()=>{throw e},0)),e}}return e}let eC="IndexBackfiller";class eD{constructor(e,t){this.asyncQueue=e,this.re=t,this.task=null}start(){this.ie(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}ie(e){b(eC,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{let e=await this.re.se();b(eC,`Documents written: ${e}`)}catch(e){eb(e)?b(eC,"Ignoring IndexedDB error during index backfill: ",e):await em(e)}await this.ie(6e4)})}}class ek{constructor(e,t){this.localStore=e,this.persistence=t}async se(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",t=>this.oe(t,e))}oe(e,t){let n=new Set,r=t,i=!0;return eg.doWhile(()=>!0===i&&r>0,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!n.has(t))return b(eC,`Processing collection: ${t}`),this._e(e,t,r).next(e=>{r-=e,n.add(t)});i=!1})).next(()=>t-r)}_e(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next(r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next(n=>{let i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next(()=>this.ae(r,n)).next(n=>(b(eC,`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n))).next(()=>i.size)}))}ae(e,t){let n=e;
1return t.changes.forEach((e,t)=>{let r=eu(t);eh(r,n)>0&&(n=r)}),new ec(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class eA{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ue(e),this.ce=e=>t.writeSequenceNumber(e))}ue(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ce&&this.ce(e),e}}function eN(e){return null==e}function eR(e){return 0===e&&1/e==-1/0}function eM(e){return"number"==typeof e&&Number.isInteger(e)&&!eR(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function eV(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t+="\x01\x01"),t=function(e,t){let n=t,r=e.length;for(let t=0;t<r;t++){let r=e.charAt(t);switch(r){case"\0":n+="\x01\x10";break;case"\x01":n+="\x01\x11";break;default:n+=r}}return n}(e.get(n),t);return t+"\x01\x01"}eA.le=-1;function eO(e){let t=e.length;if(D(t>=2,64408,{path:e}),2===t)return D("\x01"===e.charAt(0)&&"\x01"===e.charAt(1),56145,{path:e}),X.emptyPath();let n=t-2,r=[],i="";for(let s=0;s<t;){let t=e.indexOf("\x01",s);switch((t<0||t>n)&&S(50515,{path:e}),e.charAt(t+1)){case"\x01":let a,o=e.substring(s,t);0===i.length?a=o:(i+=o,a=i,i=""),r.push(a);break;case"\x10":i+=e.substring(s,t),i+="\0";break;case"\x11":i+=e.substring(s,t+1);break;default:S(61167,{path:e})}s=t+2}return new X(r)}let eF="remoteDocuments",eL="owner",eP="owner",eq="mutationQueues",eU="mutations",eB="batchId",ez="userMutationsIndex",e$=["userId","batchId"],eK={},eG="documentMutations",eQ="remoteDocumentsV14",ej=["prefixPath","collectionGroup","readTime","documentId"],eW="documentKeyIndex",eH=["prefixPath","collectionGroup","documentId"],eY="collectionGroupIndex",eJ=["collectionGroup","readTime","prefixPath","documentId"],eX="remoteDocumentGlobal",eZ="remoteDocumentGlobalKey",e0="targets",e1="queryTargetsIndex",e2=["canonicalId","targetId"],e5="targetDocuments",e4=["targetId","path"],e6="documentTargetsIndex",e3=["path","targetId"],e8="targetGlobalKey",e9="targetGlobal",e7="collectionParents",te=["collectionId","parent"],tt="clientMetadata",tn="bundles",tr="namedQueries",ti="indexConfiguration",ts="collectionGroupIndex",ta="indexState",to=["indexId","uid"],tl="sequenceNumberIndex",tu=["uid","sequenceNumber"],tc="indexEntries",th=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],td="documentKeyIndex",tf=["indexId","uid","orderedDocumentKey"],tm="documentOverlays",tg=["userId","collectionPath","documentId"],tp="collectionPathOverlayIndex",ty=["userId","collectionPath","largestBatchId"],tw="collectionGroupOverlayIndex",tv=["userId","collectionGroup","largestBatchId"],tI="globals",t_=[eq,eU,eG,eF,e0,eL,e9,e5,tt,eX,e7,tn,tr],tb=[...t_,tm],tT=[eq,eU,eG,eQ,e0,eL,e9,e5,tt,eX,e7,tn,tr,tm],tE=[...tT,ti,ta,tc],tx=[...tE,tI];class tS extends ef{constructor(e,t){super(),this.he=e,this.currentSequenceNumber=t}}function tC(e,t){return ew.N(e.he,t)}function tD(e){let t=0;for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function tk(e,t){for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function tA(e,t){let n=[];for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.push(t(e[r],r,e));return n}function tN(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class tR{constructor(e,t){this.comparator=e,this.root=t||tV.EMPTY}insert(e,t){return new tR(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,tV.BLACK,null,null))}remove(e){return new tR(this.comparator,this.root.remove(e,this.comparator).copy(null,null,tV.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){let r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return -1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal((t,n)=>(e(t,n),!1))}toString(){let e=[];return this.inorderTraversal((t,n)=>(e.push(`${t}:${n}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new tM(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new tM(this.root,e,this.comparator,!1)}getReverseIterator(){return new tM(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new tM(this.root,e,this.comparator,!0)}}class tM{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class tV{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:tV.RED,this.left=null!=r?r:tV.EMPTY,this.right=null!=i?i:tV.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new tV(null!=e?e:this.key,null!=t?t:this.value,
1null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this,i=n(e,r.key);return(r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n))).fixUp()}removeMin(){if(this.left.isEmpty())return tV.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),(e=e.copy(null,null,null,e.left.removeMin(),null)).fixUp()}remove(e,t){let n,r=this;if(0>t(e,r.key))r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return tV.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}rotateLeft(){let e=this.copy(null,null,tV.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,tV.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){return Math.pow(2,this.check())<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw S(43730,{key:this.key,value:this.value});if(this.right.isRed())throw S(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw S(27949);return e+ +!this.isRed()}}tV.EMPTY=null,tV.RED=!0,tV.BLACK=!1,tV.EMPTY=new class{constructor(){this.size=0}get key(){throw S(57766)}get value(){throw S(16141)}get color(){throw S(16727)}get left(){throw S(29726)}get right(){throw S(36894)}copy(e,t,n,r,i){return this}insert(e,t,n){return new tV(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class tO{constructor(e){this.comparator=e,this.data=new tR(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal((t,n)=>(e(t),!1))}forEachInRange(e,t){let n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){let r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new tF(this.data.getIterator())}getIteratorFrom(e){return new tF(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof tO)||this.size!==e.size)return!1;let t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new tO(this.comparator);return t.data=e,t}}
1class tF{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function tL(e){return e.hasNext()?e.getNext():void 0}class tP{constructor(e){this.fields=e,e.sort(ee.comparator)}static empty(){return new tP([])}unionWith(e){let t=new tO(ee.comparator);for(let e of this.fields)t=t.add(e);for(let n of e)t=t.add(n);return new tP(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return j(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class tq extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}function tU(){return"undefined"!=typeof atob}class tB{constructor(e){this.binaryString=e}static fromBase64String(e){return new tB(function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new tq("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new tB(function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e))}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return btoa(this.binaryString)}toUint8Array(){var e=this.binaryString;let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return K(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}tB.EMPTY_BYTE_STRING=new tB("");let tz=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function t$(e){if(D(!!e,39018),"string"==typeof e){let t=0,n=tz.exec(e);if(D(!!n,46558,{timestamp:e}),n[1]){let e=n[1];t=Number(e=(e+"000000000").substr(0,9))}return{seconds:Math.floor(new Date(e).getTime()/1e3),nanos:t}}return{seconds:tK(e.seconds),nanos:tK(e.nanos)}}function tK(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function tG(e){return"string"==typeof e?tB.fromBase64String(e):tB.fromUint8Array(e)}let tQ="server_timestamp",tj="__type__",tW="__previous_value__",tH="__local_write_time__";function tY(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[tj])?void 0:n.stringValue)===tQ}function tJ(e){let t=e.mapValue.fields[tW];return tY(t)?tJ(t):t}function tX(e){let t=t$(e.mapValue.fields[tH].timestampValue);return new W(t.seconds,t.nanos)}class tZ{constructor(e,t,n,r,i,s,a,o,l,u){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=u}}let t0="(default)";class t1{constructor(e,t){this.projectId=e,this.database=t||t0}static empty(){return new t1("","")}get isDefaultDatabase(){return this.database===t0}isEqual(e){return e instanceof t1&&e.projectId===this.projectId&&e.database===this.database}}let t2="__type__",t5="__max__",t4={mapValue:{fields:{__type__:{stringValue:t5}}}},t6="__vector__",t3="value",t8={nullValue:"NULL_VALUE"};function t9(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?tY(e)?4:nf(e)?0x1fffffffffffff:nh(e)?10:11:S(28295,{value:e})}function t7(e,t){if(e===t)return!0;let n=t9(e);if(n!==t9(t))return!1;switch(n){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return tX(e).isEqual(tX(t));case 3:if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let r=t$(e.timestampValue),i=t$(t.timestampValue);return r.seconds===i.seconds&&r.nanos===i.nanos;case 5:return e.stringValue===t.stringValue;case 6:return tG(e.bytesValue).isEqual(tG(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return tK(e.geoPointValue.latitude)===tK(t.geoPointValue.latitude)&&tK(e.geoPointValue.longitude)===tK(t.geoPointValue.longitude);case 2:if("integerValue"in e&&"integerValue"in t)return tK(e.integerValue)===tK(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let n=tK(e.doubleValue),r=tK(t.doubleValue);return n===r?eR(n)===eR(r):isNaN(n)&&isNaN(r)}return!1;case 9:return j(e.arrayValue.values||[],t.arrayValue.values||[],t7);case 10:case 11:let s=e.mapValue.fields||{},a=t.mapValue.fields||{};if(tD(s)!==tD(a))return!1;for(let e in s)if(s.hasOwnProperty(e)&&(void 0===a[e]||!t7(s[e],a[e])))return!1;return!0;default:return S(52216,{left:e})}}function ne(e,t){return void 0!==(e.values||[]).find(e=>t7(e,t))}function nt(e,t){if(e===t)return 0;let n=t9(e),r=t9(t);if(n!==r)return K(n,r);switch(n){case 0:case 0x1fffffffffffff:return 0;case 1:return K(e.booleanValue,t.booleanValue);case 2:let i=tK(e.integerValue||e.doubleValue),s=tK(t.integerValue||t.doubleValue);return i<s?-1:i>s?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return nn(e.timestampValue,t.timestampValue);case 4:return nn(tX(e),tX(t));case 5:return G(e.stringValue,t.stringValue);case 6:return function(e,t){let n=tG(e),r=tG(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){let n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){let t=K(n[e],r[e]);if(0!==t)return t}return K(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){let n=K(tK(e.latitude),tK(t.latitude));return 0!==n?n:K(tK(e.longitude),tK(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return nr(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,i,s;let a=e.fields||{},o=t.fields||{},l=null==(n=a[t3])?void 0:n.arrayValue,u=null==(r=o[t3])?void 0:r.arrayValue,c=K((null==(i=null==l?void 0:l.values)?void 0:i.length)||0,(null==(s=null==u?void 0:u.values)?void 0:s.length)||0);return 0!==c?c:nr(l,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===t4.mapValue&&t===t4.mapValue)return 0;if(e===t4.mapValue)return 1;if(t===t4.mapValue)return -1;let n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){let t=G(r[e],s[e]);if(0!==t)return t;let a=nt(n[r[e]],i[s[e]]);if(0!==a)return a}return K(r.length,s.length)}(e.mapValue,t.mapValue);default:throw S(23264,{Pe:n})}}function nn(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return K(e,t);let n=t$(e),r=t$(t),i=K(n.seconds,r.seconds);return 0!==i?i:K(n.nanos,r.nanos)}function nr(e,t){let n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){let t=nt(n[e],r[e]);if(t)return t}return K(n.length,r.length)}function ni(e){var t,n;return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){let t=t$(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?tG(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,et.fromName(t).toString()):"geoPointValue"in e?(n=e.geoPointValue,`geo(${n.latitude},${n.longitude})`):"arrayValue"in e?function(e){let t="[",n=!0;for(let r of e.values||[])n?n=!1:t+=",",t+=ni(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),n="{",r=!0;for(let i of t)r?r=!1:n+=",",n+=`${i}:${ni(e.fields[i])}`;return n+"}"}(e.mapValue):S(61005,{value:e})}function ns(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function na(e){return!!e&&"integerValue"in e}function no(e){return!!e&&"arrayValue"in e}function nl(e){return!!e&&"nullValue"in e}function nu(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function nc(e){return!!e&&"mapValue"in e}function nh(e){var t,n;return(null==(n=((null==(t=null==e?void 0:e.mapValue)?void 0:t.fields)||{})[t2])?void 0:n.stringValue)===t6}
1function nd(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){let t={mapValue:{fields:{}}};return tk(e.mapValue.fields,(e,n)=>t.mapValue.fields[e]=nd(n)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=nd(e.arrayValue.values[n]);return t}return Object.assign({},e)}function nf(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===t5}let nm={mapValue:{fields:{[t2]:{stringValue:t6},[t3]:{arrayValue:{}}}}};function ng(e,t){let n=nt(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function np(e,t){let n=nt(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class ny{constructor(e){this.value=e}static empty(){return new ny({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(!nc(t=(t.mapValue.fields||{})[e.get(n)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=nd(t)}setAll(e){let t=ee.emptyPath(),n={},r=[];e.forEach((e,i)=>{if(!t.isImmediateParentOf(i)){let e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=nd(e):r.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){let t=this.field(e.popLast());nc(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return t7(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];nc(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){for(let r of(tk(t,(t,n)=>e[t]=n),n))delete e[r]}clone(){return new ny(nd(this.value))}}class nw{constructor(e,t,n,r,i,s,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new nw(e,0,H.min(),H.min(),H.min(),ny.empty(),0)}static newFoundDocument(e,t,n,r){return new nw(e,1,t,H.min(),n,r,0)}static newNoDocument(e,t){return new nw(e,2,t,H.min(),H.min(),ny.empty(),0)}static newUnknownDocument(e,t){return new nw(e,3,t,H.min(),H.min(),ny.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(H.min())&&(2===this.documentType||0===this.documentType)&&(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ny.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ny.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=H.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof nw&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new nw(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class nv{constructor(e,t){this.position=e,this.inclusive=t}}function nI(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){let s=t[i],a=e.position[i];if(r=s.field.isKeyField()?et.comparator(et.fromName(a.referenceValue),n.key):nt(a,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function n_(e,t){if(null===e)return null===t;if(null===t||e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!t7(e.position[n],t.position[n]))return!1;return!0}class nb{constructor(e,t="asc"){this.field=e,this.dir=t}}class nT{}class nE extends nT{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new nN(e,t,n):"array-contains"===t?new nO(e,n):"in"===t?new nF(e,n
1):"not-in"===t?new nL(e,n):"array-contains-any"===t?new nP(e,n):new nE(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new nR(e,n):new nM(e,n)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(nt(t,this.value)):null!==t&&t9(this.value)===t9(t)&&this.matchesComparison(nt(t,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return S(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class nx extends nT{constructor(e,t){super(),this.filters=e,this.op=t,this.Te=null}static create(e,t){return new nx(e,t)}matches(e){return nS(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.Te||(this.Te=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Te}getFilters(){return Object.assign([],this.filters)}}function nS(e){return"and"===e.op}function nC(e){return"or"===e.op}function nD(e){return nk(e)&&nS(e)}function nk(e){for(let t of e.filters)if(t instanceof nx)return!1;return!0}function nA(e,t){let n=e.filters.concat(t);return nx.create(n,e.op)}class nN extends nE{constructor(e,t,n){super(e,t,n),this.key=et.fromName(n.referenceValue)}matches(e){let t=et.comparator(e.key,this.key);return this.matchesComparison(t)}}class nR extends nE{constructor(e,t){super(e,"in",t),this.keys=nV("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class nM extends nE{constructor(e,t){super(e,"not-in",t),this.keys=nV("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function nV(e,t){var n;return((null==(n=t.arrayValue)?void 0:n.values)||[]).map(e=>et.fromName(e.referenceValue))}class nO extends nE{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return no(t)&&ne(t.arrayValue,this.value)}}class nF extends nE{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&ne(this.value.arrayValue,t)}}class nL extends nE{constructor(e,t){super(e,"not-in",t)}matches(e){if(ne(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!ne(this.value.arrayValue,t)}}class nP extends nE{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!no(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>ne(this.value.arrayValue,e))}}class nq{constructor(e,t=null,n=[],r=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=a,this.Ie=null}}function nU(e,t=null,n=[],r=[],i=null,s=null,a=null){return new nq(e,t,n,r,i,s,a)}function nB(e){if(null===e.Ie){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(e=>(function e(t){if(t instanceof nE)return t.field.canonicalString()+t.op.toString()+ni(t.value);if(nD(t))return t.filters.map(t=>e(t)).join(",");{let n=t.filters.map(t=>e(t)).join(",");return`${t.op}(${n})`}})(e)).join(","),t+="|ob:",t+=e.orderBy.map(e=>e.field.canonicalString()+e.dir).join(","),eN(e.limit)||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>ni(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>ni(e)).join(",")),e.Ie=t}return e.Ie}function nz(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++){var n,r;if(n=e.orderBy[i],r=t.orderBy[i],!(n.dir===r.dir&&n.field.isEqual(r.field)))return!1}if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!function e(t,n){return t instanceof nE?n instanceof nE&&t.op===n.op&&t.field.isEqual(n.field)&&t7(t.value,n.value):t instanceof nx?n instanceof nx&&t.op===n.op&&t.filters.length===n.filters.length&&t.filters.reduce((t,r,i)=>t&&e(r,n.filters[i]),!0):void S(19439)}(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!n_(e.startAt,t.startAt)&&n_(e.endAt,t.endAt)}function n$(e){return et.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function nK(e,t){return e.filters.filter(e=>e instanceof nE&&e.field.isEqual(t))}function nG(e,t,n){let r=t8,i=!0;for(let n of nK(e,t)){let e=t8,t=!0;switch(n.op){case"<":case"<=":var s;
1e="nullValue"in(s=n.value)?t8:"booleanValue"in s?{booleanValue:!1}:"integerValue"in s||"doubleValue"in s?{doubleValue:NaN}:"timestampValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in s?{stringValue:""}:"bytesValue"in s?{bytesValue:""}:"referenceValue"in s?ns(t1.empty(),et.empty()):"geoPointValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in s?{arrayValue:{}}:"mapValue"in s?nh(s)?nm:{mapValue:{}}:S(35942,{value:s});break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=t8}0>ng({value:r,inclusive:i},{value:e,inclusive:t})&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];0>ng({value:r,inclusive:i},{value:e,inclusive:n.inclusive})&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}function nQ(e,t,n){let r=t4,i=!0;for(let n of nK(e,t)){let e=t4,t=!0;switch(n.op){case">=":case">":var s;e="nullValue"in(s=n.value)?{booleanValue:!1}:"booleanValue"in s?{doubleValue:NaN}:"integerValue"in s||"doubleValue"in s?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in s?{stringValue:""}:"stringValue"in s?{bytesValue:""}:"bytesValue"in s?ns(t1.empty(),et.empty()):"referenceValue"in s?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in s?{arrayValue:{}}:"arrayValue"in s?nm:"mapValue"in s?nh(s)?{mapValue:{}}:t4:S(61959,{value:s}),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=t4}np({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n){for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){let e=n.position[s];np({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}}return{value:r,inclusive:i}}class nj{constructor(e,t=null,n=[],r=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Ee=null,this.de=null,this.Ae=null,this.startAt,this.endAt}}function nW(e){return new nj(e)}function nH(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function nY(e){return null!==e.collectionGroup}function nJ(e){if(null===e.Ee){let t;e.Ee=[];let n=new Set;for(let t of e.explicitOrderBy)e.Ee.push(t),n.add(t.field.canonicalString());let r=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(t=new tO(ee.comparator),e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t).forEach(t=>{n.has(t.canonicalString())||t.isKeyField()||e.Ee.push(new nb(t,r))}),n.has(ee.keyField().canonicalString())||e.Ee.push(new nb(ee.keyField(),r))}return e.Ee}function nX(e){return e.de||(e.de=n0(e,nJ(e))),e.de}function nZ(e){return e.Ae||(e.Ae=n0(e,e.explicitOrderBy)),e.Ae}function n0(e,t){if("F"===e.limitType)return nU(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{let t="desc"===e.dir?"asc":"desc";return new nb(e.field,t)});let n=e.endAt?new nv(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new nv(e.startAt.position,e.startAt.inclusive):null;return nU(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function n1(e,t){let n=e.filters.concat([t]);return new nj(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function n2(e,t,n){return new nj(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function n5(e,t){return nz(nX(e),nX(t))&&e.limitType===t.limitType}function n4(e){return`${nB(nX(e))}|lt:${e.limitType}`}function n6(e){var t;let n;return`Query(target=${n=(t=nX(e)).path.canonicalString(),null!==t.collectionGroup&&(n+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(n+=`, filters: [${t.filters.map(e=>(function e(t){return t instanceof nE?`${t.field.canonicalString()} ${t.op} ${ni(t.value)}`:t instanceof nx?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),eN(t.limit)||(n+=", limit: "+t.limit),t.orderBy.length>0&&(n+=`, orderBy: [${t.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),t.startAt&&(n+=", startAt: ",n+=t.startAt.inclusive?"b:":"a:",n+=t.startAt.position.map(e=>ni(e)).join(",")),t.endAt&&(n+=", endAt: ",n+=t.endAt.inclusive?"a:":"b:",n+=t.endAt.position.map(e=>ni(e)).join(",")),`Target(${n})`}; limitType=${e.limitType})`}function n3(e,t){return t.isFoundDocument()&&function(e,t){let n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):et.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(let n of nJ(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(let n of e.filters)if(!n.matches(t))return!1;return!0}
1(e,t)&&(!e.startAt||!!function(e,t,n){let r=nI(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,nJ(e),t))&&(!e.endAt||!!function(e,t,n){let r=nI(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,nJ(e),t))}function n8(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function n9(e){return(t,n)=>{let r=!1;for(let i of nJ(e)){let e=function(e,t,n){let r=e.field.isKeyField()?et.comparator(t.key,n.key):function(e,t,n){let r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?nt(r,i):S(42886)}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return -1*r;default:return S(19790,{direction:e.dir})}}(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}class n7{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n){for(let[t,r]of n)if(this.equalsFn(t,e))return r}}has(e){return void 0!==this.get(e)}set(e,t){let n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){let t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){tk(this.inner,(t,n)=>{for(let[t,r]of n)e(t,r)})}isEmpty(){return tN(this.inner)}size(){return this.innerSize}}let re=new tR(et.comparator),rt=new tR(et.comparator);function rn(...e){let t=rt;for(let n of e)t=t.insert(n.key,n);return t}function rr(e){let t=rt;return e.forEach((e,n)=>t=t.insert(e,n.overlayedDocument)),t}function ri(){return new n7(e=>e.toString(),(e,t)=>e.isEqual(t))}let rs=new tR(et.comparator),ra=new tO(et.comparator);function ro(...e){let t=ra;for(let n of e)t=t.add(n);return t}let rl=new tO(K);function ru(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:eR(t)?"-0":t}}function rc(e){return{integerValue:""+e}}function rh(e,t){return eM(t)?rc(t):ru(e,t)}class rd{constructor(){this._=void 0}}function rf(e,t){return e instanceof rv?na(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}class rm extends rd{}class rg extends rd{constructor(e){super(),this.elements=e}}function rp(e,t){let n=r_(t);for(let t of e.elements)n.some(e=>t7(e,t))||n.push(t);return{arrayValue:{values:n}}}class ry extends rd{constructor(e){super(),this.elements=e}}function rw(e,t){let n=r_(t);for(let t of e.elements)n=n.filter(e=>!t7(e,t));return{arrayValue:{values:n}}}class rv extends rd{constructor(e,t){super(),this.serializer=e,this.Re=t}}function rI(e){return tK(e.integerValue||e.doubleValue)}function r_(e){return no(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class rb{constructor(e,t){this.field=e,this.transform=t}}class rT{constructor(e,t){this.version=e,this.transformResults=t}}class rE{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new rE}static exists(e){return new rE(void 0,e)}static updateTime(e){return new rE(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function rx(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class rS{}function rC(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new rO(e.key,rE.none()):new rA(e.key,e.data,rE.none());{let n=e.data,r=ny.empty(),i=new tO(ee.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new rN(e.key,r,new tP(i.toArray()),rE.none())}}function rD(e,t,n,r){return e instanceof rA?function(e,t,n,r){if(!rx(e.precondition,t))return n;let i=e.value.clone(),s=rV(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof rN?function(e,t,n,r){if(!rx(e.precondition,t))return n;let i=rV(e.fieldTransforms,r,t),s=t.data;return(s.setAll(rR(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n)?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,n,r):rx(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}function rk(e,t){var n,r;return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||!(!n||!r)&&j(n,r,(e,t)=>{var n,r;return e.field.isEqual(t.field)&&(n=e.transform,r=t.transform,n instanceof rg&&r instanceof rg||n instanceof ry&&r instanceof ry?j(n.elements,r.elements,t7):n instanceof rv&&r instanceof rv?t7(n.Re,r.Re):n instanceof rm&&r instanceof rm)})))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class rA extends rS{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.prec
1ondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class rN extends rS{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function rR(e){let t=new Map;return e.fieldMask.fields.forEach(n=>{if(!n.isEmpty()){let r=e.data.field(n);t.set(n,r)}}),t}function rM(e,t,n){let r=new Map;D(e.length===n.length,32656,{Ve:n.length,me:e.length});for(let s=0;s<n.length;s++){var i;let a=e[s],o=a.transform,l=t.data.field(a.field);r.set(a.field,(i=n[s],o instanceof rg?rp(o,l):o instanceof ry?rw(o,l):i))}return r}function rV(e,t,n){let r=new Map;for(let i of e){let e=i.transform,s=n.data.field(i.field);r.set(i.field,e instanceof rm?function(e,t){let n={fields:{[tj]:{stringValue:tQ},[tH]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&tY(t)&&(t=tJ(t)),t&&(n.fields[tW]=t),{mapValue:n}}(t,s):e instanceof rg?rp(e,s):e instanceof ry?rw(e,s):function(e,t){let n=rf(e,t),r=rI(n)+rI(e.Re);return na(n)&&na(e.Re)?rc(r):ru(e.serializer,r)}(e,s))}return r}class rO extends rS{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class rF extends rS{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class rL{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){let n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let r=this.mutations[t];r.key.isEqual(e.key)&&function(e,t,n){e instanceof rA?function(e,t,n){let r=e.value.clone(),i=rM(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof rN?function(e,t,n){if(!rx(e.precondition,t))return t.convertToUnknownDocument(n.version);let r=rM(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(rR(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}(r,e,n[t])}}applyToLocalView(e,t){for(let n of this.baseMutations)n.key.isEqual(e.key)&&(t=rD(n,e,t,this.localWriteTime));for(let n of this.mutations)n.key.isEqual(e.key)&&(t=rD(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let n=ri();return this.mutations.forEach(r=>{let i=e.get(r.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=rC(s,a=t.has(r.key)?null:a);null!==o&&n.set(r.key,o),s.isValidDocument()||s.convertToNoDocument(H.min())}),n}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),ro())}isEqual(e){return this.batchId===e.batchId&&j(this.mutations,e.mutations,(e,t)=>rk(e,t))&&j(this.baseMutations,e.baseMutations,(e,t)=>rk(e,t))}}class rP{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){D(e.mutations.length===n.length,58842,{fe:e.mutations.length,ge:n.length});let r=rs,i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new rP(e,t,n,r)}}class rq{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{
2      largestBatchId: ${this.largestBatchId},
3      mutation: ${this.mutation.toString()}
4    }`}}class rU{constructor(e,t,n){this.alias=e,this.aggregateType=t,this.fieldPath=n}}class rB{constructor(e,t){this.count=e,this.unchangedNames=t}}function rz(e){switch(e){case A.OK:return S(64938);case A.CANCELLED:case A.UNKNOWN:case A.DEADLINE_EXCEEDED:case A.RESOURCE_EXHAUSTED:case A.INTERNAL:case A.UNAVAILABLE:case A.UNAUTHENTICATED:return!1;case A.INVALID_ARGUMENT:case A.NOT_FOUND:case A.ALREADY_EXISTS:case A.PERMISSION_DENIED:case A.FAILED_PRECONDITION:case A.ABORTED:case A.OUT_OF_RANGE:case A.UNIMPLEMENTED:case A.DATA_LOSS:return!0;default:return S(15467,{code:e})}}function r$(e){if(void 0===e)return T("GRPC error has no .code"),A.UNKNOWN;switch(e){case r.OK:return A.OK;case r.CANCELLED:return A.CANCELLED;case r.UNKNOWN:return A.UNKNOWN;case r.DEADLINE_EXCEEDED:return A.DEADLINE_EXCEEDED;case r.RESOURCE_EXHAUSTED:return A.RESOURCE_EXHAUSTED;case r.INTERNAL:return A.INTERNAL;case r.UNAVAILABLE:return A.UNAVAILABLE;case r.UNAUTHENTICATED:return A.UNAUTHENTICATED;case r.INVALID_ARGUMENT:return A.INVALID_ARGUMENT;case r.NOT_FOUND:return A.NOT_FOUND;case r.ALREADY_EXISTS:return A.ALREADY_EXISTS;case r.PERMISSION_DENIED:return A.PERMISSION_DENIED;case r.FAILED_PRECONDITION:return A.FAILED_PRECONDITION;case r.ABORTED:return A.ABORTED;case r.OUT_OF_RANGE:return A.OUT_OF_RANGE;
4case r.UNIMPLEMENTED:return A.UNIMPLEMENTED;case r.DATA_LOSS:return A.DATA_LOSS;default:return S(39323,{code:e})}}(i=r||(r={}))[i.OK=0]="OK",i[i.CANCELLED=1]="CANCELLED",i[i.UNKNOWN=2]="UNKNOWN",i[i.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",i[i.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",i[i.NOT_FOUND=5]="NOT_FOUND",i[i.ALREADY_EXISTS=6]="ALREADY_EXISTS",i[i.PERMISSION_DENIED=7]="PERMISSION_DENIED",i[i.UNAUTHENTICATED=16]="UNAUTHENTICATED",i[i.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",i[i.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",i[i.ABORTED=10]="ABORTED",i[i.OUT_OF_RANGE=11]="OUT_OF_RANGE",i[i.UNIMPLEMENTED=12]="UNIMPLEMENTED",i[i.INTERNAL=13]="INTERNAL",i[i.UNAVAILABLE=14]="UNAVAILABLE",i[i.DATA_LOSS=15]="DATA_LOSS";let rK=null,rG=new h.jz([0xffffffff,0xffffffff],0);function rQ(e){let t=z().encode(e),n=new h.VV;return n.update(t),new Uint8Array(n.digest())}function rj(e){let t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new h.jz([n,r],0),new h.jz([i,s],0)]}class rW{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new rH(`Invalid padding: ${t}`);if(n<0||e.length>0&&0===this.hashCount)throw new rH(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new rH(`Invalid padding when bitmap length is 0: ${t}`);this.pe=8*e.length-t,this.ye=h.jz.fromNumber(this.pe)}we(e,t,n){let r=e.add(t.multiply(h.jz.fromNumber(n)));return 1===r.compare(rG)&&(r=new h.jz([r.getBits(0),r.getBits(1)],0)),r.modulo(this.ye).toNumber()}be(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.pe)return!1;let[t,n]=rj(rQ(e));for(let e=0;e<this.hashCount;e++){let r=this.we(t,n,e);if(!this.be(r))return!1}return!0}static create(e,t,n){let r=new rW(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);return n.forEach(e=>r.insert(e)),r}insert(e){if(0===this.pe)return;let[t,n]=rj(rQ(e));for(let e=0;e<this.hashCount;e++){let r=this.we(t,n,e);this.Se(r)}}Se(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class rH extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class rY{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){let r=new Map;return r.set(e,rJ.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new rY(H.min(),r,new tR(K),re,ro())}}class rJ{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new rJ(n,t,ro(),ro(),ro())}}class rX{constructor(e,t,n,r){this.De=e,this.removedTargetIds=t,this.key=n,this.ve=r}}class rZ{constructor(e,t){this.targetId=e,this.Ce=t}}class r0{constructor(e,t,n=tB.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class r1{constructor(){this.Fe=0,this.Me=r4(),this.xe=tB.EMPTY_BYTE_STRING,this.Oe=!1,this.Ne=!0}get current(){return this.Oe}get resumeToken(){return this.xe}get Be(){return 0!==this.Fe}get Le(){return this.Ne}ke(e){e.approximateByteSize()>0&&(this.Ne=!0,this.xe=e)}qe(){let e=ro(),t=ro(),n=ro();return this.Me.forEach((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:S(38017,{changeType:i})}}),new rJ(this.xe,this.Oe,e,t,n)}Qe(){this.Ne=!1,this.Me=r4()}$e(e,t){this.Ne=!0,this.Me=this.Me.insert(e,t)}Ue(e){this.Ne=!0,this.Me=this.Me.remove(e)}Ke(){this.Fe+=1}We(){this.Fe-=1,D(this.Fe>=0,3241,{Fe:this.Fe})}Ge(){this.Ne=!0,this.Oe=!0}}class r2{constructor(e){this.ze=e,this.je=new Map,this.He=re,this.Je=r5(),this.Ye=r5(),this.Ze=new tR(K)}Xe(e){for(let t of e.De)e.ve&&e.ve.isFoundDocument()?this.et(t,e.ve):this.tt(t,e.key,e.ve);for(let t of e.removedTargetIds)this.tt(t,e.key,e.ve)}nt(e){this.forEachTarget(e,t=>{let n=this.rt(t);switch(e.state){case 0:this.it(t)&&n.ke(e.resumeToken);break;case 1:n.We(),n.Be||n.Qe(),n.ke(e.resumeToken);break;case 2:n.We(),n.Be||this.removeTarget(t);break;case 3:this.it(t)&&(n.Ge(),n.ke(e.resumeToken));break;case 4:this.it(t)&&(this.st(t),n.ke(e.resumeToken));break;default:S(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.je.forEach((e,n)=>{this.it(n)&&t(n)})}ot(e){let t=e.targetId,n=e.Ce.count,r=this._t(t);if(r){let i=r.target;if(n$(i))if(0===n){let e=new et(i.path);this.tt(t,e,nw.newNoDocument(e,H.min()))}else D(1===n,20013,{expectedCount:n});else{let r=this.ut(t);if(r!==n){let n=this.ct(e),i=n?this.lt(n,e,r):1;0!==i&&(this.st(t),this.Ze=this.Ze.insert(t,2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch")),null==rK||rK.ht(function(e,t,n,r,i){var s,a,o,l,u,c;let h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===i,hashCount:null!=(s=null==d?void 0:d.hashCount)?s:0,bitmapLength:null!=(l=null==(o=null==(a=null==d?void 0:d.bits)?void 0:a.bitmap)?void 0:o.length)?l:0,padding:null!=(c=null==(u=null==d?void 0:d.bits)?void 0:u.padding)?c:0,mightContain:e=>{var t;return null!=(t=null==r?void 0:r.mightContain(e))&&t}}),h}(r,e.Ce,this.ze.Pt(),n,i))}}}}ct(e){let t,n,r=e.Ce.unchangedNames;if(!r||!r.bits)return null;let{bits:{bitmap:i="",padding:s=0},hashCount:a=0}=r;try{t=tG(i).toUint8Array()}catch(e){if(e instanceof tq)return E("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{n=new rW(t,s,a)}catch(e){return E(e instanceof rH?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===n.pe?null:n}lt(e,t,n){return 2*(t.Ce.count!==n-this.Tt(e,t.targetId))}Tt(e,t){let n=this.ze.getRemoteKeysForTarget(t),r=0;
4return n.forEach(n=>{let i=this.ze.Pt(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;e.mightContain(s)||(this.tt(t,n,null),r++)}),r}It(e){let t=new Map;this.je.forEach((n,r)=>{let i=this._t(r);if(i){if(n.current&&n$(i.target)){let t=new et(i.target.path);this.Et(t).has(r)||this.dt(r,t)||this.tt(r,t,nw.newNoDocument(t,e))}n.Le&&(t.set(r,n.qe()),n.Qe())}});let n=ro();this.Ye.forEach((e,t)=>{let r=!0;t.forEachWhile(e=>{let t=this._t(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)}),r&&(n=n.add(e))}),this.He.forEach((t,n)=>n.setReadTime(e));let r=new rY(e,t,this.Ze,this.He,n);return this.He=re,this.Je=r5(),this.Ye=r5(),this.Ze=new tR(K),r}et(e,t){if(!this.it(e))return;let n=2*!!this.dt(e,t.key);this.rt(e).$e(t.key,n),this.He=this.He.insert(t.key,t),this.Je=this.Je.insert(t.key,this.Et(t.key).add(e)),this.Ye=this.Ye.insert(t.key,this.At(t.key).add(e))}tt(e,t,n){if(!this.it(e))return;let r=this.rt(e);this.dt(e,t)?r.$e(t,1):r.Ue(t),this.Ye=this.Ye.insert(t,this.At(t).delete(e)),this.Ye=this.Ye.insert(t,this.At(t).add(e)),n&&(this.He=this.He.insert(t,n))}removeTarget(e){this.je.delete(e)}ut(e){let t=this.rt(e).qe();return this.ze.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Ke(e){this.rt(e).Ke()}rt(e){let t=this.je.get(e);return t||(t=new r1,this.je.set(e,t)),t}At(e){let t=this.Ye.get(e);return t||(t=new tO(K),this.Ye=this.Ye.insert(e,t)),t}Et(e){let t=this.Je.get(e);return t||(t=new tO(K),this.Je=this.Je.insert(e,t)),t}it(e){let t=null!==this._t(e);return t||b("WatchChangeAggregator","Detected inactive target",e),t}_t(e){let t=this.je.get(e);return t&&t.Be?null:this.ze.Rt(e)}st(e){this.je.set(e,new r1),this.ze.getRemoteKeysForTarget(e).forEach(t=>{this.tt(e,t,null)})}dt(e,t){return this.ze.getRemoteKeysForTarget(e).has(t)}}function r5(){return new tR(et.comparator)}function r4(){return new tR(et.comparator)}let r6={asc:"ASCENDING",desc:"DESCENDING"},r3={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"},r8={and:"AND",or:"OR"};class r9{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function r7(e,t){return e.useProto3Json||eN(t)?t:{value:t}}function ie(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function it(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function ir(e){return D(!!e,49232),H.fromTimestamp(function(e){let t=t$(e);return new W(t.seconds,t.nanos)}(e))}function ii(e,t){return is(e,t).canonicalString()}function is(e,t){let n=new X(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?n:n.child(t)}function ia(e){let t=X.fromString(e);return D(iE(t),10190,{key:t.toString()}),t}function io(e,t){return ii(e.databaseId,t.path)}function il(e,t){let n=ia(t);if(n.get(1)!==e.databaseId.projectId)throw new N(A.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new N(A.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new et(id(n))}function iu(e,t){return ii(e.databaseId,t)}function ic(e){let t=ia(e);return 4===t.length?X.emptyPath():id(t)}function ih(e){return new X(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function id(e){return D(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function im(e,t,n){return{name:io(e,t),fields:n.value.mapValue.fields}}function ig(e,t,n){let r=il(e,t.name),i=ir(t.updateTime),s=t.createTime?ir(t.createTime):H.min(),a=new ny({mapValue:{fields:t.fields}}),o=nw.newFoundDocument(r,i,s,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function ip(e,t){var n;let r;if(t instanceof rA)r={update:im(e,t.key,t.value)};else if(t instanceof rO)r={delete:io(e,t.key)};else if(t instanceof rN)r={update:im(e,t.key,t.data),updateMask:function(e){let t=[];
4return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof rF))return S(16599,{ft:t.type});r={verify:io(e,t.key)}}return t.fieldTransforms.length>0&&(r.updateTransforms=t.fieldTransforms.map(e=>(function(e,t){let n=t.transform;if(n instanceof rm)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof rg)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof ry)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof rv)return{fieldPath:t.field.canonicalString(),increment:n.Re};throw S(20930,{transform:t.transform})})(0,e))),t.precondition.isNone||(r.currentDocument=void 0!==(n=t.precondition).updateTime?{updateTime:ie(e,n.updateTime.toTimestamp())}:void 0!==n.exists?{exists:n.exists}:S(27497)),r}function iy(e,t){var n;let r=t.currentDocument?void 0!==(n=t.currentDocument).updateTime?rE.updateTime(ir(n.updateTime)):void 0!==n.exists?rE.exists(n.exists):rE.none():rE.none(),i=t.updateTransforms?t.updateTransforms.map(t=>{let n;return n=null,"setToServerValue"in t?(D("REQUEST_TIME"===t.setToServerValue,16630,{proto:t}),n=new rm):"appendMissingElements"in t?n=new rg(t.appendMissingElements.values||[]):"removeAllFromArray"in t?n=new ry(t.removeAllFromArray.values||[]):"increment"in t?n=new rv(e,t.increment):S(16584,{proto:t}),new rb(ee.fromServerFormat(t.fieldPath),n)}):[];if(t.update){t.update.name;let n=il(e,t.update.name),s=new ny({mapValue:{fields:t.update.fields}});return t.updateMask?new rN(n,s,new tP((t.updateMask.fieldPaths||[]).map(e=>ee.fromServerFormat(e))),r,i):new rA(n,s,r,i)}return t.delete?new rO(il(e,t.delete),r):t.verify?new rF(il(e,t.verify),r):S(1463,{proto:t})}function iw(e,t){return{documents:[iu(e,t.path)]}}function iv(e,t){var n,r;let i,s={structuredQuery:{}},a=t.path;null!==t.collectionGroup?(i=a,s.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=a.popLast(),s.structuredQuery.from=[{collectionId:a.lastSegment()}]),s.parent=iu(e,i);let o=function(e){if(0!==e.length)return function e(t){return t instanceof nE?function(e){if("=="===e.op){if(nu(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NAN"}};if(nl(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(nu(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NOT_NAN"}};if(nl(e.value))return{unaryFilter:{field:ib(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ib(e.field),op:r3[e.op],value:e.value}}}(t):t instanceof nx?function(t){let n=t.getFilters().map(t=>e(t));return 1===n.length?n[0]:{compositeFilter:{op:r8[t.op],filters:n}}}(t):S(54877,{filter:t})}(nx.create(e,"and"))}(t.filters);o&&(s.structuredQuery.where=o);let l=function(e){if(0!==e.length)return e.map(e=>({field:ib(e.field),direction:r6[e.dir]}))}(t.orderBy);l&&(s.structuredQuery.orderBy=l);let u=r7(e,t.limit);return null!==u&&(s.structuredQuery.limit=u),t.startAt&&(s.structuredQuery.startAt={before:(n=t.startAt).inclusive,values:n.position}),t.endAt&&(s.structuredQuery.endAt={before:!(r=t.endAt).inclusive,values:r.position}),{gt:s,parent:i}}function iI(e,t,n,r){let{gt:i,parent:s}=iv(e,t),a={},o=[],l=0;return n.forEach(e=>{let t=r?e.alias:"aggregate_"+l++;a[t]=e.alias,"count"===e.aggregateType?o.push({alias:t,count:{}}):"avg"===e.aggregateType?o.push({alias:t,avg:{field:ib(e.fieldPath)}}):"sum"===e.aggregateType&&o.push({alias:t,sum:{field:ib(e.fieldPath)}})}),{request:{structuredAggregationQuery:{aggregations:o,structuredQuery:i.structuredQuery},parent:i.parent},yt:a,parent:s}}function i_(e){var t;let n,r=ic(e.parent),i=e.structuredQuery,s=i.from?i.from.length:0,a=null;if(s>0){D(1===s,65062);let e=i.from[0];e.allDescendants?a=e.collectionId:r=r.child(e.collectionId)}let o=[];i.where&&(o=function(e){let t=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=iT(e.unaryFilter.field);return nE.create(t,"==",{doubleValue:NaN});case"IS_NULL":let n=iT(e.unaryFilter.field);return nE.create(n,"==",{nullValue:"NULL_VALUE"});
4case"IS_NOT_NAN":let r=iT(e.unaryFilter.field);return nE.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=iT(e.unaryFilter.field);return nE.create(i,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return S(61313);default:return S(60726)}}(t):void 0!==t.fieldFilter?nE.create(iT(t.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return S(58110);default:return S(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?nx.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return S(1026)}}(t.compositeFilter.op)):S(30097,{filter:t})}(e);return t instanceof nx&&nD(t)?t.getFilters():[t]}(i.where));let l=[];i.orderBy&&(l=i.orderBy.map(e=>new nb(iT(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let u=null;i.limit&&(u=eN(n="object"==typeof(t=i.limit)?t.value:t)?null:n);let c=null;i.startAt&&(c=function(e){let t=!!e.before;return new nv(e.values||[],t)}(i.startAt));let h=null;return i.endAt&&(h=function(e){let t=!e.before;return new nv(e.values||[],t)}(i.endAt)),new nj(r,a,l,o,u,"F",c,h)}function ib(e){return{fieldPath:e.canonicalString()}}function iT(e){return ee.fromServerFormat(e.fieldPath)}function iE(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class ix{constructor(e,t,n,r,i=H.min(),s=H.min(),a=tB.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new ix(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new ix(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new ix(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new ix(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class iS{constructor(e){this.wt=e}}function iC(e,t){let n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:iD(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument()){var i;r.document={name:io(i=e.wt,t.key),fields:t.data.value.mapValue.fields,updateTime:ie(i,t.version.toTimestamp()),createTime:ie(i,t.createTime.toTimestamp())}}else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:ik(t.version)};else{if(!t.isUnknownDocument())return S(57904,{document:t});r.unknownDocument={path:n.path.toArray(),version:ik(t.version)}}return r}function iD(e){let t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function ik(e){let t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function iA(e){let t=new W(e.seconds,e.nanoseconds);return H.fromTimestamp(t)}function iN(e,t){let n=(t.baseMutations||[]).map(t=>iy(e.wt,t));for(let e=0;e<t.mutations.length-1;++e){let n=t.mutations[e];e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform&&(n.updateTransforms=t.mutations[e+1].transform.fieldTransforms,t.mutations.splice(e+1,1),++e)}let r=t.mutations.map(t=>iy(e.wt,t)),i=W.fromMillis(t.localWriteTimeMs);return new rL(t.batchId,i,n,r)}function iR(e){let t=iA(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?iA(e.lastLimboFreeSnapshotVersion):H.min();return new ix(void 0!==e.query.documents?function(e){let t=e.documents.length;return D(1===t,1966,{count:t}),nX(nW(ic(e.documents[0])))}(e.query):nX(i_(e.query)),e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,tB.fromBase64String(e.resumeToken))}function iM(e,t){let n,r=ik(t.snapshotVersion),i=ik(t.lastLimboFreeSnapshotVersion);n=n$(t.target)?iw(e.wt,t.target):iv(e.wt,t.target).gt;let s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:nB(t.target),readTime:r,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:i,query:n}}function iV(e){let t=i_({parent:e.parent,structuredQuery:e.structuredQuery});
4return"LAST"===e.limitType?n2(t,t.limit,"L"):t}function iO(e,t){return new rq(t.largestBatchId,iy(e.wt,t.overlayMutation))}function iF(e,t){let n=t.path.lastSegment();return[e,eV(t.path.popLast()),n]}function iL(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:ik(r.readTime),documentKey:eV(r.documentKey.path),largestBatchId:r.largestBatchId}}class iP{getBundleMetadata(e,t){return tC(e,tn).get(t).next(e=>{if(e)return{id:e.bundleId,createTime:iA(e.createTime),version:e.version}})}saveBundleMetadata(e,t){return tC(e,tn).put({bundleId:t.id,createTime:ik(ir(t.createTime)),version:t.version})}getNamedQuery(e,t){return tC(e,tr).get(t).next(e=>{if(e)return{name:e.name,query:iV(e.bundledQuery),readTime:iA(e.readTime)}})}saveNamedQuery(e,t){return tC(e,tr).put({name:t.name,readTime:ik(ir(t.readTime)),bundledQuery:t.bundledQuery})}}class iq{constructor(e,t){this.serializer=e,this.userId=t}static bt(e,t){return new iq(e,t.uid||"")}getOverlay(e,t){return tC(e,tm).get(iF(this.userId,t)).next(e=>e?iO(this.serializer,e):null)}getOverlays(e,t){let n=ri();return eg.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){let r=[];return n.forEach((n,i)=>{let s=new rq(t,i);r.push(this.St(e,s))}),eg.waitFor(r)}removeOverlaysForBatchId(e,t,n){let r=new Set;t.forEach(e=>r.add(eV(e.getCollectionPath())));let i=[];return r.forEach(t=>{let r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(tC(e,tm).X(tp,r))}),eg.waitFor(i)}getOverlaysForCollection(e,t,n){let r=ri(),i=eV(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,1/0],!0);return tC(e,tm).J(tp,s).next(e=>{for(let t of e){let e=iO(this.serializer,t);r.set(e.getKey(),e)}return r})}getOverlaysForCollectionGroup(e,t,n,r){let i,s=ri(),a=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,1/0],!0);return tC(e,tm).te({index:tw,range:a},(e,t,n)=>{let a=iO(this.serializer,t);s.size()<r||a.largestBatchId===i?(s.set(a.getKey(),a),i=a.largestBatchId):n.done()}).next(()=>s)}St(e,t){return tC(e,tm).put(function(e,t,n){let[r,i,s]=iF(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:ip(e.wt,n.mutation)}}(this.serializer,this.userId,t))}}class iU{Dt(e){return tC(e,tI)}getSessionToken(e){return this.Dt(e).get("sessionToken").next(e=>{let t=null==e?void 0:e.value;return t?tB.fromUint8Array(t):tB.EMPTY_BYTE_STRING})}setSessionToken(e,t){return this.Dt(e).put({name:"sessionToken",value:t.toUint8Array()})}}class iB{constructor(){}vt(e,t){this.Ct(e,t),t.Ft()}Ct(e,t){if("nullValue"in e)this.Mt(t,5);else if("booleanValue"in e)this.Mt(t,10),t.xt(+!!e.booleanValue);else if("integerValue"in e)this.Mt(t,15),t.xt(tK(e.integerValue));else if("doubleValue"in e){let n=tK(e.doubleValue);isNaN(n)?this.Mt(t,13):(this.Mt(t,15),eR(n)?t.xt(0):t.xt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Mt(t,20),"string"==typeof n&&(n=t$(n)),t.Ot(`${n.seconds||""}`),t.xt(n.nanos||0)}else if("stringValue"in e)this.Nt(e.stringValue,t),this.Bt(t);else if("bytesValue"in e)this.Mt(t,30),t.Lt(tG(e.bytesValue)),this.Bt(t);else if("referenceValue"in e)this.kt(e.referenceValue,t);else if("geoPointValue"in e){let n=e.geoPointValue;this.Mt(t,45),t.xt(n.latitude||0),t.xt(n.longitude||0)}else"mapValue"in e?nf(e)?this.Mt(t,Number.MAX_SAFE_INTEGER):nh(e)?this.qt(e.mapValue,t):(this.Qt(e.mapValue,t),this.Bt(t)):"arrayValue"in e?(this.$t(e.arrayValue,t),this.Bt(t)):S(19022,{Ut:e})}Nt(e,t){this.Mt(t,25),this.Kt(e,t)}Kt(e,t){t.Ot(e)}Qt(e,t){let n=e.fields||{};for(let e of(this.Mt(t,55),Object.keys(n)))this.Nt(e,t),this.Ct(n[e],t)}qt(e,t){var n,r;let i=e.fields||{};this.Mt(t,53);let s=(null==(r=null==(n=i[t3].arrayValue)?void 0:n.values)?void 0:r.length)||0;this.Mt(t,15),t.xt(tK(s)),this.Nt(t3,t),this.Ct(i[t3],t)}$t(e,t){let n=e.values||[];for(let e of(this.Mt(t,50),n))this.Ct(e,t)}kt(e,t){this.Mt(t,37),et.fromName(e).path.forEach(e=>{this.Mt(t,60),this.Kt(e,t)})}Mt(e,t){e.xt(t)}Bt(e){e.xt(2)}}function iz(e){return Math.ceil((64-function(e){let t=0;for(let n=0;n<8;++n){let r=function(e){if(0===e)return 8;let t=0;return e>>4||(t+=4,e<<=4),e>>6||(t+=2,e<<=2),e>>7||(t+=1),t}(255&e[n]);if(t+=r,8!==r)break}return t}(e))/8)}iB.Wt=new iB;class i${constructor(){this.buffer=new Uint8Array(1024),this.position=0}Gt(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.zt(n.value),n=t.next();this.jt()}Ht(e){let t=e[Symbol.iterator](),n=t.next();for(;!n.done;)this.Jt(n.value),n=t.next();this.Yt()}Zt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.zt(e);else if(e<2048)this.zt(960|e>>>6),this.zt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.zt(480|e>>>12),this.zt(128|63&e>>>6),this.zt(128|63&e);else{let e=t.codePointAt(0);this.zt(240|e>>>18),this.zt(128|63&e>>>12),this.zt(128|63&e>>>6),this.zt(128|63&e)}}this.jt()}Xt(e){for(let t of e){let e=t.charCodeAt(0);if(e<128)this.Jt(e);else if(e<2048)this.Jt(960|e>>>6),this.Jt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Jt(480|e>>>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e);else{let e=t.codePointAt(0);this.Jt(240|e>>>18),this.Jt(128|63&e>>>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e)}}this.Yt()}en(e){let t=this.tn(e),n=iz(t);this.nn(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}rn(e){let t=this.tn(e),n=iz(t);this.nn(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}sn(){this._n(255),this._n(255)}an(){this.un(255),this.un(255)}reset(){this.position=0}seed(e){this.nn(e.length),this.buffer.set(e,this.position),this.position+=e.length}cn(){return this.buffer.slice(0,this.position)}tn(e){let t=function(e){let t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=!!(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=255*!!n;return t}zt(e){let t=255&e;0===t?(this._n(0),this._n(255)):255===t?(this._n(255),this._n(0)):this._n(t)}Jt(e){let t=255&e;0===t?(this.un(0),this.un(255)):255===t?(this.un(255),this.un(0)):this.un(e)}jt(){this._n(0),this._n(1)}Yt(){this.un(0),this.un(1)}_n(e){this.nn(1),this.buffer[this.position++]=e}un(e){this.nn(1),this.buffer[this.position++]=~e}nn(e){let t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);let r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class iK{constructor(e){this.ln=e}Lt(e){this.ln.Gt(e)}Ot(e){this.ln.Zt(e)}xt(e){this.ln.en(e)}Ft(){this.ln.sn()}}class iG{constructor(e){this.ln=e}Lt(e){this.ln.Ht(e)}Ot(e){this.ln.Xt(e)}xt(e){this.ln.rn(e)}Ft(){this.ln.an()}}class iQ{constructor(){this.ln=new i$,this.hn=new iK(this.ln),this.Pn=new iG(this.ln)}seed(e){this.ln.seed(e)}Tn(e){return 0===e?this.hn:this.Pn}cn(){return this.ln.cn()}reset(){this.ln.reset()}}class ij{constructor(e,t,n,r){this.In=e,this.En=t,this.dn=n,this.An=r}Rn(){let e=this.An.length,t=0===e||255===this.An[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.An,0),t!==e?n.set([0],this.An.length):++n[n.length-1],new ij(this.In,this.En,this.dn,n)}Vn(e,t,n){return{indexId:this.In,uid:e,arrayValue:iY(this.dn),directionalValue:iY(this.An),orderedDocumentKey:iY(t),documentKey:n.path.toArray()}}mn(e,t,n){let r=this.Vn(e,t,n);return[r.indexId,r.uid,r.arrayValue,r.directionalValue,r.orderedDocumentKey,r.documentKey]}}function iW(e,t){let n=e.In-t.In;
4return 0!==n||0!==(n=iH(e.dn,t.dn))||0!==(n=iH(e.An,t.An))?n:et.comparator(e.En,t.En)}function iH(e,t){for(let n=0;n<e.length&&n<t.length;++n){let r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}function iY(e){return(0,c.Ov)()?function(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}(e):e}function iJ(e){return"string"!=typeof e?e:function(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(e)}class iX{constructor(e){for(let t of(this.fn=new tO((e,t)=>ee.comparator(e.field,t.field)),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.gn=e.orderBy,this.pn=[],e.filters))t.isInequality()?this.fn=this.fn.add(t):this.pn.push(t)}get yn(){return this.fn.size>1}wn(e){if(D(e.collectionGroup===this.collectionId,49279),this.yn)return!1;let t=er(e);if(void 0!==t&&!this.bn(t))return!1;let n=ei(e),r=new Set,i=0,s=0;for(;i<n.length&&this.bn(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(this.fn.size>0){let e=this.fn.getIterator().getNext();if(!r.has(e.field.canonicalString())){let t=n[i];if(!this.Sn(e,t)||!this.Dn(this.gn[s++],t))return!1}++i}for(;i<n.length;++i){let e=n[i];if(s>=this.gn.length||!this.Dn(this.gn[s++],e))return!1}return!0}vn(){if(this.yn)return null;let e=new tO(ee.comparator),t=[];for(let n of this.pn)if(!n.field.isKeyField())if("array-contains"===n.op||"array-contains-any"===n.op)t.push(new ea(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new ea(n.field,0))}for(let n of this.gn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new ea(n.field,+("asc"!==n.dir))));return new en(en.UNKNOWN_ID,this.collectionId,t,eo.empty())}bn(e){for(let t of this.pn)if(this.Sn(t,e))return!0;return!1}Sn(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;let n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}Dn(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function iZ(e){return e instanceof nE}function i0(e){return e instanceof nx&&nD(e)}function i1(e){return iZ(e)||i0(e)||function(e){if(e instanceof nx&&nC(e)){for(let t of e.getFilters())if(!iZ(t)&&!i0(t))return!1;return!0}return!1}(e)}function i2(e,t){return D(e instanceof nE||e instanceof nx,38388),D(t instanceof nE||t instanceof nx,25473),i4(e instanceof nE?t instanceof nE?nx.create([e,t],"and"):i5(e,t):t instanceof nE?i5(t,e):function(e,t){if(D(e.filters.length>0&&t.filters.length>0,48005),nS(e)&&nS(t))return nA(e,t.getFilters());let n=nC(e)?e:t,r=nC(e)?t:e,i=n.filters.map(e=>i2(e,r));return nx.create(i,"or")}(e,t))}function i5(e,t){if(nS(t))return nA(t,e.getFilters());{let n=t.filters.map(t=>i2(e,t));return nx.create(n,"or")}}function i4(e){if(D(e instanceof nE||e instanceof nx,11850),e instanceof nE)return e;let t=e.getFilters();if(1===t.length)return i4(t[0]);if(nk(e))return e;let n=t.map(e=>i4(e)),r=[];return n.forEach(t=>{t instanceof nE?r.push(t):t instanceof nx&&(t.op===e.op?r.push(...t.filters):r.push(t))}),1===r.length?r[0]:nx.create(r,e.op)}class i6{constructor(){this.Cn=new i3}addToCollectionParentIndex(e,t){return this.Cn.add(t),eg.resolve()}getCollectionParents(e,t){return eg.resolve(this.Cn.getEntries(t))}addFieldIndex(e,t){return eg.resolve()}deleteFieldIndex(e,t){return eg.resolve()}deleteAllFieldIndexes(e){return eg.resolve()}createTargetIndexes(e,t){return eg.resolve()}getDocumentsMatchingTarget(e,t){return eg.resolve(null)}getIndexType(e,t){return eg.resolve(0)}getFieldIndexes(e,t){return eg.resolve([])}getNextCollectionGroupToUpdate(e){return eg.resolve(null)}getMinOffset(e,t){return eg.resolve(ec.min())}getMinOffsetFromCollectionGroup(e,t){return eg.resolve(ec.min())}updateCollectionGroup(e,t,n){return eg.resolve()}updateIndexEntries(e,t){return eg.resolve()}}class i3{constructor(){this.index={}}add(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new tO(X.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){let t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new tO(X.comparator)).toArray()}}let i8="IndexedDbIndexManager",i9=new Uint8Array(0);class i7{constructor(e,t){this.databaseId=t,this.Fn=new i3,this.Mn=new n7(e=>nB(e),(e,t)=>nz(e,t)),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.Fn.has(t)){let n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Fn.add(t)});let i={collectionId:n,parent:eV(r)};return tC(e,e7).put(i)}return eg.resolve()}getCollectionParents(e,t){let n=[],r=IDBKeyRange.bound([t,""],[t+"\0",""],!1,!0);return tC(e,e7).J(r).next(e=>{for(let r of e){if(r.collectionId!==t)break;n.push(eO(r.parent))}return n})}addFieldIndex(e,t){let n=tC(e,ti),r={indexId:t.indexId,collectionGroup:t.collectionGroup,fields:t.fields.map(e=>[e.fieldPath.canonicalString(),e.kind])};delete r.indexId;let i=n.add(r);if(t.indexState){let n=tC(e,ta);return i.next(e=>{n.put(iL(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))})}return i.next()}deleteFieldIndex(e,t){let n=tC(e,ti),r=tC(e,ta),i=tC(e,tc);return n.delete(t.indexId).next(()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))).next(()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))}deleteAllFieldIndexes(e){let t=tC(e,ti),n=tC(e,tc),r=tC(e,ta);return t.X().next(()=>n.X()).next(()=>r.X())}createTargetIndexes(e,t){return eg.forEach(this.xn(t),t=>this.getIndexType(e,t).next(n=>{if(0===n||1===n){let n=new iX(t).vn();if(null!=n)return this.addFieldIndex(e,n)}}))}getDocumentsMatchingTarget(e,t){let n=tC(e,tc),r=!0,i=new Map;return eg.forEach(this.xn(t),t=>this.On(e,t).next(e=>{r&&(r=!!e),i.set(t,e)})).next(()=>{if(r){let e=ro(),r=[];return eg.forEach(i,(i,s)=>{b(i8,`Using index id=${i.indexId}|cg=${i.collectionGroup}|f=${i.fields.map(e=>`${e.fieldPath}:${e.kind}`).join(",")} to execute ${nB(t)}`);let a=function(e,t){let n=er(t);if(void 0===n)return null;for(let t of nK(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),o=function(e,t){let n=new Map;for(let r of ei(t))for(let t of nK(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(s,i),l=function(e,t){let n=[],r=!0;for(let i of ei(t)){let t=0===i.kind?nG(e,i.fieldPath,e.startAt):nQ(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new nv(n,r)}(s,i),u=function(e,t){let n=[],r=!0;for(let i of ei(t)){let t=0===i.kind?nQ(e,i.fieldPath,e.endAt):nG(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new nv(n,r)}(s,i),c=this.Nn(i,s,l),h=this.Nn(i,s,u),d=this.Bn(i,s,o),f=this.Ln(i.indexId,a,c,l.inclusive,h,u.inclusive,d);return eg.forEach(f,i=>n.Z(i,t.limit).next(t=>{t.forEach(t=>{let n=et.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))})}))}).next(()=>r)}return eg.resolve(null)})}xn(e){let t=this.Mn.get(e);return t||(t=0===e.filters.length?[e]:(function(e){if(0===e.getFilters().length)return[];let t=function e(t){if(D(t instanceof nE||t instanceof nx,34018),t instanceof nE)return t;if(1===t.filters.length)return e(t.filters[0]);let n=t.filters.map(t=>e(t)),r=nx.create(n,t.op);return i1(r=i4(r))?r:(D(r instanceof nx,64498),D(nS(r),40251),D(r.filters.length>1,57927),r.filters.reduce((e,t)=>
4i2(e,t)))}(function e(t){var n,r;if(D(t instanceof nE||t instanceof nx,20012),t instanceof nE){if(t instanceof nF){let e=(null==(r=null==(n=t.value.arrayValue)?void 0:n.values)?void 0:r.map(e=>nE.create(t.field,"==",e)))||[];return nx.create(e,"or")}return t}let i=t.filters.map(t=>e(t));return nx.create(i,t.op)}(e));return D(i1(t),7391),iZ(t)||i0(t)?[t]:t.getFilters()})(nx.create(e.filters,"and")).map(t=>nU(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt)),this.Mn.set(e,t)),t}Ln(e,t,n,r,i,s,a){let o=(null!=t?t.length:1)*Math.max(n.length,i.length),l=o/(null!=t?t.length:1),u=[];for(let c=0;c<o;++c){let o=t?this.kn(t[c/l]):i9,h=this.qn(e,o,n[c%l],r),d=this.Qn(e,o,i[c%l],s),f=a.map(t=>this.qn(e,o,t,!0));u.push(...this.createRange(h,d,f))}return u}qn(e,t,n,r){let i=new ij(e,et.empty(),t,n);return r?i:i.Rn()}Qn(e,t,n,r){let i=new ij(e,et.empty(),t,n);return r?i.Rn():i}On(e,t){let n=new iX(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next(e=>{let t=null;for(let r of e)n.wn(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t})}getIndexType(e,t){let n=2,r=this.xn(t);return eg.forEach(r,t=>this.On(e,t).next(e=>{e?0!==n&&e.fields.length<function(e){let t=new tO(ee.comparator),n=!1;for(let r of e.filters)for(let e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(let n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+ +!!n}(t)&&(n=1):n=0})).next(()=>null!==t.limit&&r.length>1&&2===n?1:n)}$n(e,t){let n=new iQ;for(let r of ei(e)){let e=t.data.field(r.fieldPath);if(null==e)return null;let i=n.Tn(r.kind);iB.Wt.vt(e,i)}return n.cn()}kn(e){let t=new iQ;return iB.Wt.vt(e,t.Tn(0)),t.cn()}Un(e,t){let n=new iQ;return iB.Wt.vt(ns(this.databaseId,t),n.Tn(function(e){let t=ei(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.cn()}Bn(e,t,n){if(null===n)return[];let r=[];r.push(new iQ);let i=0;for(let s of ei(e)){let e=n[i++];for(let n of r)if(this.Kn(t,s.fieldPath)&&no(e))r=this.Wn(r,s,e);else{let t=n.Tn(s.kind);iB.Wt.vt(e,t)}}return this.Gn(r)}Nn(e,t,n){return this.Bn(e,t,n.position)}Gn(e){let t=[];for(let n=0;n<e.length;++n)t[n]=e[n].cn();return t}Wn(e,t,n){let r=[...e],i=[];for(let e of n.arrayValue.values||[])for(let n of r){let r=new iQ;r.seed(n.cn()),iB.Wt.vt(e,r.Tn(t.kind)),i.push(r)}return i}Kn(e,t){return!!e.filters.find(e=>e instanceof nE&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op))}getFieldIndexes(e,t){let n=tC(e,ti),r=tC(e,ta);return(t?n.J(ts,IDBKeyRange.bound(t,t)):n.J()).next(e=>{let t=[];return eg.forEach(e,e=>r.get([e.indexId,this.uid]).next(n=>{t.push(function(e,t){let n=t?new eo(t.sequenceNumber,new ec(iA(t.readTime),new et(eO(t.documentKey)),t.largestBatchId)):eo.empty(),r=e.fields.map(([e,t])=>new ea(ee.fromServerFormat(e),t));return new en(e.indexId,e.collectionGroup,r,n)}(e,n))})).next(()=>t)})}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next(e=>0===e.length?null:(e.sort((e,t)=>{let n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:K(e.collectionGroup,t.collectionGroup)}),e[0].collectionGroup))}updateCollectionGroup(e,t,n){let r=tC(e,ti),i=tC(e,ta);return this.zn(e).next(e=>r.J(ts,IDBKeyRange.bound(t,t)).next(t=>eg.forEach(t,t=>i.put(iL(t.indexId,this.uid,e,n)))))}updateIndexEntries(e,t){let n=new Map;return eg.forEach(t,(t,r)=>{let i=n.get(t.collectionGroup);return(i?eg.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next(i=>(n.set(t.collectionGroup,i),eg.forEach(i,n=>this.jn(e,t,n).next(t=>{let i=this.Hn(r,n);return t.isEqual(i)?eg.resolve():this.Jn(e,r,n,t,i)}))))})}Yn(e,t,n,r){return tC(e,tc).put(r.Vn(this.uid,this.Un(n,t.key),t.key))}Zn(e,t,n,r){return tC(e,tc).delete(r.mn(this.uid,this.Un(n,t.key),t.key))}jn(e,t,n){let r=tC(e,tc),i=new tO(iW);return r.te({index:td,range:IDBKeyRange.only([n.indexId,this.uid,iY(this.Un(n,t))])},(e,r)=>{i=i.add(new ij(n.indexId,t,iJ(r.arrayValue),iJ(r.directionalValue)))}).next(()=>i)}Hn(e,t){let n=new tO(iW),r=this.$n(t,e);if(null==r)return n;let i=er(t);if(null!=i){let s=e.data.field(i.fieldPath);if(no(s))for(let i of s.arrayValue.values||[])n=n.add(new ij(t.indexId,e.key,this.kn(i),r))}else n=n.add(new ij(t.indexId,e.key,i9,r));return n}Jn(e,t,n,r,i){b(i8,"Updating index entries for document '%s'",t.key);let s=[];return function(e,t,n,r,i){let s=e.getIterator(),a=t.getIterator(),o=tL(s),l=tL(a);for(;o||l;){let e=!1,t=!1;if(o&&l){let r=n(o,l);r<0?t=!0:r>0&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(l),l=tL(a)):t?(i(o),o=tL(s)):(o=tL(s),l=tL(a))}}(r,i,iW,r=>{s.push(this.Yn(e,t,n,r))},r=>{s.push(this.Zn(e,t,n,r))}),eg.waitFor(s)}zn(e){let t=1;return tC(e,ta).te({index:tl,reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},(e,n,r)=>{r.done(),t=n.sequenceNumber+1}
4).next(()=>t)}createRange(e,t,n){n=n.sort((e,t)=>iW(e,t)).filter((e,t,n)=>!t||0!==iW(e,n[t-1]));let r=[];for(let i of(r.push(e),n)){let n=iW(i,e),s=iW(i,t);if(0===n)r[0]=e.Rn();else if(n>0&&s<0)r.push(i),r.push(i.Rn());else if(s>0)break}r.push(t);let i=[];for(let e=0;e<r.length;e+=2){if(this.Xn(r[e],r[e+1]))return[];let t=r[e].mn(this.uid,i9,et.empty()),n=r[e+1].mn(this.uid,i9,et.empty());i.push(IDBKeyRange.bound(t,n))}return i}Xn(e,t){return iW(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(se)}getMinOffset(e,t){return eg.mapArray(this.xn(t),t=>this.On(e,t).next(e=>e||S(44426))).next(se)}}function se(e){D(0!==e.length,28825);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){let i=e[r].indexState.offset;0>eh(i,t)&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new ec(t.readTime,t.documentKey,n)}let st={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class sn{static withCacheSize(e){return new sn(e,sn.DEFAULT_COLLECTION_PERCENTILE,sn.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function sr(e,t,n){let r=e.store(eU),i=e.store(eG),s=[],a=IDBKeyRange.only(n.batchId),o=0,l=r.te({range:a},(e,t,n)=>(o++,n.delete()));s.push(l.next(()=>{D(1===o,47070,{batchId:n.batchId})}));let u=[];for(let e of n.mutations){var c,h;let r=(c=e.key.path,h=n.batchId,[t,eV(c),h]);s.push(i.delete(r)),u.push(e.key)}return eg.waitFor(s).next(()=>u)}function si(e){let t;if(!e)return 0;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw S(14731);t=e.noDocument}return JSON.stringify(t).length}sn.DEFAULT_COLLECTION_PERCENTILE=10,sn.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,sn.DEFAULT=new sn(0x2800000,sn.DEFAULT_COLLECTION_PERCENTILE,sn.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),sn.DISABLED=new sn(-1,0,0);class ss{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.er={}}static bt(e,t,n,r){return D(""!==e.uid,64387),new ss(e.isAuthenticated()?e.uid:"",t,n,r)}checkEmpty(e){let t=!0,n=IDBKeyRange.bound([this.userId,-1/0],[this.userId,1/0]);return so(e).te({index:ez,range:n},(e,n,r)=>{t=!1,r.done()}).next(()=>t)}addMutationBatch(e,t,n,r){let i=tC(e,eG),s=so(e);return s.add({}).next(a=>{D("number"==typeof a,49019);let o=new rL(a,t,n,r),l=function(e,t,n){let r=n.baseMutations.map(t=>ip(e.wt,t)),i=n.mutations.map(t=>ip(e.wt,t));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,o),u=[],c=new tO((e,t)=>K(e.canonicalString(),t.canonicalString()));for(let e of r){var h,d;let t=(h=this.userId,d=e.key.path,[h,eV(d),a]);c=c.add(e.key.path.popLast()),u.push(s.put(l)),u.push(i.put(t,eK))}return c.forEach(t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))}),e.addOnCommittedListener(()=>{this.er[a]=o.keys()}),eg.waitFor(u).next(()=>o)})}lookupMutationBatch(e,t){return so(e).get(t).next(e=>e?(D(e.userId===this.userId,48,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),iN(this.serializer,e)):null)}tr(e,t){return this.er[t]?eg.resolve(this.er[t]):this.lookupMutationBatch(e,t).next(e=>{if(e){let n=e.keys();return this.er[t]=n,n}return null})}getNextMutationBatchAfterBatchId(e,t){let n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]),i=null;return so(e).te({index:ez,range:r},(e,t,r)=>{t.userId===this.userId&&(D(t.batchId>=n,47524,{nr:n}),i=iN(this.serializer,t)),r.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){let t=IDBKeyRange.upperBound([this.userId,1/0]),n=-1;return so(e).te({index:ez,range:t,reverse:!0},(e,t,r)=>{n=t.batchId,r.done()}).next(()=>n)}getAllMutationBatches(e){let t=IDBKeyRange.bound([this.userId,-1],[this.userId,1/0]);return so(e).J(ez,t).next(e=>e.map(e=>iN(this.serializer,e)))}getAllMutationBatchesAffectingDocumentKey(e,t){let n=[this.userId,eV(t.path)],r=IDBKeyRange.lowerBound(n),i=[];return tC(e,eG).te({range:r},(n,r,s)=>{let[a,o,l]=n,u=eO(o);if(a===this.userId&&t.path.isEqual(u))return so(e).get(l).next(e=>{if(!e)throw S(61480,{rr:n,batchId:l});D(e.userId===this.userId,10503,"Unexpected user for mutation batch",{userId:e.userId,batchId:l}),i.push(iN(this.serializer,e))});s.done()}).next(()=>i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tO(K),r=[];return t.forEach(t=>{let i=[this.userId,eV(t.path)],s=IDBKeyRange.lowerBound(i),a=tC(e,eG).te({range:s},(e,r,i)=>{let[s,a,o]=e,l=eO(a);s===this.userId&&t.path.isEqual(l)?n=n.add(o):i.done()});r.push(a)}),eg.waitFor(r).next(()=>this.ir(e,n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=[this.userId,eV(n)],s=IDBKeyRange.lowerBound(i),a=new tO(K);return tC(e,eG).te({range:s},(e,t,i)=>{let[s,o,l]=e,u=eO(o);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(a=a.add(l)):i.done()}).next(()=>this.ir(e,a))}ir(e,t){let n=[],r=[];return t.forEach(t=>{r.push(so(e).get(t).next(e=>{if(null===e)throw S(35274,{batchId:t});D(e.userId===this.userId,9748,"Unexpected user for mutation batch",{userId:e.userId,batchId:t}),n.push(iN(this.serializer,e))}))}),eg.waitFor(r).next(()=>n)}removeMutationBatch(e,t){return sr(e.he,this.userId,t).next(n=>(e.addOnCommittedListener(()=>{this.sr(t.batchId)}),eg.forEach(n,t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))}sr(e){delete this.er[e]}performConsistencyCheck(e){return this.checkEmpty(e).next(t=>
4{if(!t)return eg.resolve();let n=IDBKeyRange.lowerBound([this.userId]),r=[];return tC(e,eG).te({range:n},(e,t,n)=>{if(e[0]===this.userId){let t=eO(e[1]);r.push(t)}else n.done()}).next(()=>{D(0===r.length,56720,{_r:r.map(e=>e.canonicalString())})})})}containsKey(e,t){return sa(e,this.userId,t)}ar(e){return tC(e,eq).get(this.userId).next(e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""})}}function sa(e,t,n){let r=[t,eV(n.path)],i=r[1],s=IDBKeyRange.lowerBound(r),a=!1;return tC(e,eG).te({range:s,ee:!0},(e,n,r)=>{let[s,o,l]=e;s===t&&o===i&&(a=!0),r.done()}).next(()=>a)}function so(e){return tC(e,eU)}class sl{constructor(e){this.ur=e}next(){return this.ur+=2,this.ur}static cr(){return new sl(0)}static lr(){return new sl(-1)}}class su{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.hr(e).next(t=>{let n=new sl(t.highestTargetId);return t.highestTargetId=n.next(),this.Pr(e,t).next(()=>t.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.hr(e).next(e=>H.fromTimestamp(new W(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.hr(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(e,t,n){return this.hr(e).next(r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.Pr(e,r)))}addTargetData(e,t){return this.Tr(e,t).next(()=>this.hr(e).next(n=>(n.targetCount+=1,this.Ir(t,n),this.Pr(e,n))))}updateTargetData(e,t){return this.Tr(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next(()=>tC(e,e0).delete(t.targetId)).next(()=>this.hr(e)).next(t=>(D(t.targetCount>0,8065),t.targetCount-=1,this.Pr(e,t)))}removeTargets(e,t,n){let r=0,i=[];return tC(e,e0).te((s,a)=>{let o=iR(a);o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r++,i.push(this.removeTargetData(e,o)))}).next(()=>eg.waitFor(i)).next(()=>r)}forEachTarget(e,t){return tC(e,e0).te((e,n)=>{t(iR(n))})}hr(e){return tC(e,e9).get(e8).next(e=>(D(null!==e,2888),e))}Pr(e,t){return tC(e,e9).put(e8,t)}Tr(e,t){return tC(e,e0).put(iM(this.serializer,t))}Ir(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.hr(e).next(e=>e.targetCount)}getTargetData(e,t){let n=nB(t),r=IDBKeyRange.bound([n,-1/0],[n,1/0]),i=null;return tC(e,e0).te({range:r,index:e1},(e,n,r)=>{let s=iR(n);nz(t,s.target)&&(i=s,r.done())}).next(()=>i)}addMatchingKeys(e,t,n){let r=[],i=sc(e);return t.forEach(t=>{let s=eV(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))}),eg.waitFor(r)}removeMatchingKeys(e,t,n){let r=sc(e);return eg.forEach(t,t=>{let i=eV(t.path);return eg.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])})}removeMatchingKeysForTargetId(e,t){let n=sc(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){let n=IDBKeyRange.bound([t],[t+1],!1,!0),r=sc(e),i=ro();return r.te({range:n,ee:!0},(e,t,n)=>{let r=new et(eO(e[1]));i=i.add(r)}).next(()=>i)}containsKey(e,t){let n=eV(t.path),r=IDBKeyRange.bound([n],[n+"\0"],!1,!0),i=0;return sc(e).te({index:e6,ee:!0,range:r},([e,t],n,r)=>{0!==e&&(i++,r.done())}).next(()=>i>0)}Rt(e,t){return tC(e,e0).get(t).next(e=>e?iR(e):null)}}function sc(e){return tC(e,e5)}let sh="LruGarbageCollector";function sd([e,t],[n,r]){let i=K(e,n);return 0===i?K(t,r):i}class sf{constructor(e){this.Er=e,this.buffer=new tO(sd),this.dr=0}Ar(){return++this.dr}Rr(e){let t=[e,this.Ar()];if(this.buffer.size<this.Er)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>sd(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class sm{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Vr=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.mr(6e4)}stop(){this.Vr&&(this.Vr.cancel(),this.Vr=null)}get started(){return null!==this.Vr}mr(e){b(sh,`Garbage collection scheduled in ${e}ms`),this.Vr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Vr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){eb(e)?b(sh,"Ignoring IndexedDB error during garbage collection: ",e):await em(e)}await this.mr(3e5)})}}class sg{constructor(e,t){this.gr=e,this.params=t}calculateTargetCount(e,t){return this.gr.pr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return eg.resolve(eA.le);let n=new sf(t);return this.gr.forEachTarget(e,e=>n.Rr(e.sequenceNumber)).next(()=>this.gr.yr(e,e=>n.Rr(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.gr.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.gr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(b("LruGarbageCollector","Garbage collection skipped; disabled"),eg.resolve(st)):this.getCacheSize(e).next(n=>n<this.params.cacheSizeCollectionThreshold?(b("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),st):this.wr(e,t))}getCacheSize(e){return this.gr.getCacheSize(e)}wr(e,t){let n,r,i,s,a,o,l,c=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(b("LruGarbageCollector",`C
4apping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,s=Date.now(),this.nthSequenceNumber(e,r))).next(r=>(n=r,a=Date.now(),this.removeTargets(e,n,t))).next(t=>(i=t,o=Date.now(),this.removeOrphanedDocuments(e,n))).next(e=>(l=Date.now(),I()<=u.$b.DEBUG&&b("LruGarbageCollector",`LRU Garbage Collection
5	Counted targets in ${s-c}ms
6	Determined least recently used ${r} in `+(a-s)+"ms\n"+`	Removed ${i} targets in `+(o-a)+"ms\n"+`	Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-c}ms`),eg.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e})))}}class sp{constructor(e,t){this.db=e,this.garbageCollector=new sg(this,t)}pr(e){let t=this.br(e);return this.db.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}br(e){let t=0;return this.yr(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}yr(e,t){return this.Sr(e,(e,n)=>t(n))}addReference(e,t,n){return sy(e,n)}removeReference(e,t,n){return sy(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return sy(e,t)}Dr(e,t){let n;return n=!1,tC(e,eq).ne(r=>sa(e,r,t).next(e=>(e&&(n=!0),eg.resolve(!e)))).next(()=>n)}removeOrphanedDocuments(e,t){let n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[],i=0;return this.Sr(e,(s,a)=>{if(a<=t){let t=this.Dr(e,s).next(t=>{if(!t)return i++,n.getEntry(e,s).next(()=>(n.removeEntry(s,H.min()),sc(e).delete([0,eV(s.path)])))});r.push(t)}}).next(()=>eg.waitFor(r)).next(()=>n.apply(e)).next(()=>i)}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return sy(e,t)}Sr(e,t){let n=sc(e),r,i=eA.le;return n.te({index:e6},([e,n],{path:s,sequenceNumber:a})=>{0===e?(i!==eA.le&&t(new et(eO(r)),i),i=a,r=s):i=eA.le}).next(()=>{i!==eA.le&&t(new et(eO(r)),i)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function sy(e,t){var n;return sc(e).put((n=e.currentSequenceNumber,{targetId:0,path:eV(t.path),sequenceNumber:n}))}class sw{constructor(){this.changes=new n7(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,nw.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let n=this.changes.get(t);return void 0!==n?eg.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class sv{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return tC(e,eQ).put(n)}removeEntry(e,t,n){return tC(e,eQ).delete(function(e,t){let n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],iD(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next(n=>(n.byteSize+=t,this.vr(e,n)))}getEntry(e,t){let n=nw.newInvalidDocument(t);return tC(e,eQ).te({index:eW,range:IDBKeyRange.only(s_(t))},(e,r)=>{n=this.Cr(t,r)}).next(()=>n)}Fr(e,t){let n={size:0,document:nw.newInvalidDocument(t)};return tC(e,eQ).te({index:eW,range:IDBKeyRange.only(s_(t))},(e,r)=>{n={document:this.Cr(t,r),size:si(r)}}).next(()=>n)}getEntries(e,t){let n=re;return this.Mr(e,t,(e,t)=>{let r=this.Cr(e,t);n=n.insert(e,r)}).next(()=>n)}Or(e,t){let n=re,r=new tR(et.comparator);return this.Mr(e,t,(e,t)=>{let i=this.Cr(e,t);n=n.insert(e,i),r=r.insert(e,si(t))}).next(()=>({documents:n,Nr:r}))}Mr(e,t,n){if(t.isEmpty())return eg.resolve();let r=new tO(sT);t.forEach(e=>r=r.add(e));let i=IDBKeyRange.bound(s_(r.first()),s_(r.last())),s=r.getIterator(),a=s.getNext();return tC(e,eQ).te({index:eW,range:i},(e,t,r)=>{let i=et.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&0>sT(a,i);)n(a,null),a=s.getNext();a&&a.isEqual(i)&&(n(a,t),a=s.hasNext()?s.getNext():null),a?r.H(s_(a)):r.done()}).next(()=>{for(;a;)n(a,null),a=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,t,n,r,i){let s=t.path,a=[s.popLast().toArray(),s.lastSegment(),iD(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return tC(e,eQ).J(IDBKeyRange.bound(a,o,!0)).next(e=>{null==i||i.incrementDocumentReadCount(e.length);let n=re;for(let i of e){let e=this.Cr(et.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);
6e.isFoundDocument()&&(n3(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n})}getAllFromCollectionGroup(e,t,n,r){let i=re,s=sb(t,n),a=sb(t,ec.max());return tC(e,eQ).te({index:eY,range:IDBKeyRange.bound(s,a,!0)},(e,t,n)=>{let s=this.Cr(et.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);(i=i.insert(s.key,s)).size===r&&n.done()}).next(()=>i)}newChangeBuffer(e){return new sI(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return tC(e,eX).get(eZ).next(e=>(D(!!e,20021),e))}vr(e,t){return tC(e,eX).put(eZ,t)}Cr(e,t){if(t){let e=function(e,t){let n;if(t.document)n=ig(e.wt,t.document,!!t.hasCommittedMutations);else if(t.noDocument){let e=et.fromSegments(t.noDocument.path),r=iA(t.noDocument.readTime);n=nw.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return S(56709);{let e=et.fromSegments(t.unknownDocument.path),r=iA(t.unknownDocument.version);n=nw.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){let t=new W(e[0],e[1]);return H.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!(e.isNoDocument()&&e.version.isEqual(H.min())))return e}return nw.newInvalidDocument(e)}}class sI extends sw{constructor(e,t){super(),this.Br=e,this.trackRemovals=t,this.Lr=new n7(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(e){let t=[],n=0,r=new tO((e,t)=>K(e.canonicalString(),t.canonicalString()));
6return this.changes.forEach((i,s)=>{let a=this.Lr.get(i);if(t.push(this.Br.removeEntry(e,i,a.readTime)),s.isValidDocument()){let o=iC(this.Br.serializer,s);r=r.add(i.path.popLast());let l=si(o);n+=l-a.size,t.push(this.Br.addEntry(e,i,o))}else if(n-=a.size,this.trackRemovals){let n=iC(this.Br.serializer,s.convertToNoDocument(H.min()));t.push(this.Br.addEntry(e,i,n))}}),r.forEach(n=>{t.push(this.Br.indexManager.addToCollectionParentIndex(e,n))}),t.push(this.Br.updateMetadata(e,n)),eg.waitFor(t)}getFromCache(e,t){return this.Br.Fr(e,t).next(e=>(this.Lr.set(t,{size:e.size,readTime:e.document.readTime}),e.document))}getAllFromCache(e,t){return this.Br.Or(e,t).next(({documents:e,Nr:t})=>(t.forEach((t,n)=>{this.Lr.set(t,{size:n,readTime:e.get(t).readTime})}),e))}}function s_(e){let t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function sb(e,t){let n=t.documentKey.path.toArray();return[e,iD(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function sT(e,t){let n=e.path.toArray(),r=t.path.toArray(),i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=K(n[e],r[e]))return i;return(i=K(n.length,r.length))||(i=K(n[n.length-2],r[r.length-2]))||K(n[n.length-1],r[r.length-1])}class sE{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class sx{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next(r=>(n=r,this.remoteDocumentCache.getEntry(e,t))).next(e=>(null!==n&&rD(n.mutation,e,tP.empty(),W.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,ro()).next(()=>t))}getLocalViewOfDocuments(e,t,n=ro()){let r=ri();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,n).next(e=>{let t=rn();return e.forEach((e,n)=>{t=t.insert(e,n.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let n=ri();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,ro()))}populateOverlays(e,t,n){let r=[];return n.forEach(e=>{t.has(e)||r.push(e)}),this.documentOverlayCache.getOverlays(e,r).next(e=>{e.forEach((e,n)=>{t.set(e,n)})})}computeViews(e,t,n,r){let i=re,s=ri(),a=ri();return t.forEach((e,t)=>{let a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof rN)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),rD(a.mutation,t,a.mutation.getFieldMask(),W.now())):s.set(t.key,tP.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>{var n;return a.set(e,new sE(t,null!=(n=s.get(e))?n:null))}),a))}recalculateAndSaveOverlays(e,t){let n=ri(),r=new tR((e,t)=>e-t),i=ro();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let i of e)i.keys().forEach(e=>{let s=t.get(e);if(null===s)return;let a=n.get(e)||tP.empty();a=i.applyToLocalView(s,a),n.set(e,a);let o=(r.get(i.batchId)||ro()).add(e);r=r.insert(i.batchId,o)})}).next(()=>{let s=[],a=r.getReverseIterator();for(;a.hasNext();){let r=a.getNext(),o=r.key,l=r.value,u=ri();l.forEach(e=>{if(!i.has(e)){let r=rC(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}}),s.push(this.documentOverlayCache.saveOverlays(e,o,u))}return eg.waitFor(s)}).next(()=>n)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,n,r){return et.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):nY(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next(i=>{let s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):eg.resolve(ri()),a=-1,o=i;return s.next(t=>eg.forEach(t,(t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),i.get(t)?eg.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,i)).next(()=>this.computeViews(e,o,t,ro())).next(e=>({batchId:a,changes:rr(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new et(t)).next(e=>{let t=rn();
vendor: 4,140 bytes, line 6
6return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){let i=t.collectionGroup,s=rn();return this.indexManager.getCollectionParents(e,i).next(a=>eg.forEach(a,a=>{let o=new nj(a.child(i),null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next(e=>{e.forEach((e,t)=>{s=s.insert(e,t)})})}).next(()=>s))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next(s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r))).next(e=>{i.forEach((t,n)=>{let r=n.getKey();null===e.get(r)&&(e=e.insert(r,nw.newInvalidDocument(r)))});let n=rn();return e.forEach((e,r)=>{let s=i.get(e);void 0!==s&&rD(s.mutation,r,tP.empty(),W.now()),n3(t,r)&&(n=n.insert(e,r))}),n})}}class sS{constructor(e){this.serializer=e,this.kr=new Map,this.qr=new Map}getBundleMetadata(e,t){return eg.resolve(this.kr.get(t))}saveBundleMetadata(e,t){return this.kr.set(t.id,{id:t.id,version:t.version,createTime:ir(t.createTime)}),eg.resolve()}getNamedQuery(e,t){return eg.resolve(this.qr.get(t))}saveNamedQuery(e,t){return this.qr.set(t.name,{name:t.name,query:iV(t.bundledQuery),readTime:ir(t.readTime)}),eg.resolve()}}class sC{constructor(){this.overlays=new tR(et.comparator),this.Qr=new Map}getOverlay(e,t){return eg.resolve(this.overlays.get(t))}getOverlays(e,t){let n=ri();return eg.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&n.set(t,e)})).next(()=>n)}saveOverlays(e,t,n){return n.forEach((n,r)=>{this.St(e,t,r)}),eg.resolve()}removeOverlaysForBatchId(e,t,n){let r=this.Qr.get(n);return void 0!==r&&(r.forEach(e=>this.overlays=this.overlays.remove(e)),this.Qr.delete(n)),eg.resolve()}getOverlaysForCollection(e,t,n){let r=ri(),i=t.length+1,s=new et(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){let e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return eg.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new tR((e,t)=>e-t),s=this.overlays.getIterator();for(;s.hasNext();){let e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=ri(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=ri(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=r)););return eg.resolve(a)}St(e,t,n){let r=this.overlays.get(n.key);if(null!==r){let e=this.Qr.get(r.largestBatchId).delete(n.key);this.Qr.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new rq(t,n));let i=this.Qr.get(t);void 0===i&&(i=ro(),this.Qr.set(t,i)),this.Qr.set(t,i.add(n.key))}}class sD{constructor(){this.sessionToken=tB.EMPTY_BYTE_STRING}getSessionToken(e){return eg.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,eg.resolve()}}class sk{constructor(){this.$r=new tO(sA.Ur),this.Kr=new tO(sA.Wr)}isEmpty(){return this.$r.isEmpty()}addReference(e,t){let n=new sA(e,t);this.$r=this.$r.add(n),this.Kr=this.Kr.add(n)}Gr(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.zr(new sA(e,t))}jr(e,t){e.forEach(e=>this.removeReference(e,t))}Hr(e){let t=new et(new X([])),n=new sA(t,e),r=new sA(t,e+1),i=[];return this.Kr.forEachInRange([n,r],e=>{this.zr(e),i.push(e.key)}),i}Jr(){this.$r.forEach(e=>this.zr(e))}zr(e){this.$r=this.$r.delete(e),this.Kr=this.Kr.delete(e)}Yr(e){let t=new et(new X([])),n=new sA(t,e),r=new sA(t,e+1),i=ro();return this.Kr.forEachInRange([n,r],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new sA(e,0),n=this.$r.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class sA{constructor(e,t){this.key=e,this.Zr=t}static Ur(e,t){return et.comparator(e.key,t.key)||K(e.Zr,t.Zr)}static Wr(e,t){return K(e.Zr,t.Zr)||et.comparator(e.key,t.key)}}class sN{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.nr=1,this.Xr=new tO(sA.Ur)}checkEmpty(e){return eg.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){let i=this.nr;
6this.nr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new rL(i,t,n,r);for(let t of(this.mutationQueue.push(s),r))this.Xr=this.Xr.add(new sA(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return eg.resolve(s)}lookupMutationBatch(e,t){return eg.resolve(this.ei(t))}getNextMutationBatchAfterBatchId(e,t){let n=this.ti(t+1),r=n<0?0:n;return eg.resolve(this.mutationQueue.length>r?this.mutationQueue[r]:null)}getHighestUnacknowledgedBatchId(){return eg.resolve(0===this.mutationQueue.length?-1:this.nr-1)}getAllMutationBatches(e){return eg.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let n=new sA(t,0),r=new sA(t,1/0),i=[];return this.Xr.forEachInRange([n,r],e=>{let t=this.ei(e.Zr);i.push(t)}),eg.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new tO(K);return t.forEach(e=>{let t=new sA(e,0),r=new sA(e,1/0);this.Xr.forEachInRange([t,r],e=>{n=n.add(e.Zr)})}),eg.resolve(this.ni(n))}getAllMutationBatchesAffectingQuery(e,t){let n=t.path,r=n.length+1,i=n;et.isDocumentKey(i)||(i=i.child(""));let s=new sA(new et(i),0),a=new tO(K);return this.Xr.forEachWhile(e=>{let t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.Zr)),!0)},s),eg.resolve(this.ni(a))}ni(e){let t=[];return e.forEach(e=>{let n=this.ei(e);null!==n&&t.push(n)}),t}removeMutationBatch(e,t){D(0===this.ri(t.batchId,"removed"),55003),this.mutationQueue.shift();let n=this.Xr;return eg.forEach(t.mutations,r=>{let i=new sA(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)}).next(()=>{this.Xr=n})}sr(e){}containsKey(e,t){let n=new sA(t,0),r=this.Xr.firstAfterOrEqual(n);return eg.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,eg.resolve()}ri(e,t){return this.ti(e)}ti(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}ei(e){let t=this.ti(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class sR{constructor(e){this.ii=e,this.docs=new tR(et.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.ii(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let n=this.docs.get(t);return eg.resolve(n?n.document.mutableCopy():nw.newInvalidDocument(t))}getEntries(e,t){let n=re;return t.forEach(e=>{let t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():nw.newInvalidDocument(e))}),eg.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=re,s=t.path,a=new et(s.child("__id-9223372036854775808__")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){let{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||0>=eh(eu(a),n)||(r.has(a.key)||n3(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return eg.resolve(i)}getAllFromCollectionGroup(e,t,n,r){S(9500)}si(e,t){return eg.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new sM(this)}getSize(e){return eg.resolve(this.size)}}class sM extends sw{constructor(e){super(),this.Br=e}applyChanges(e){let t=[];
vendor: 4,733 bytes, line 6
6return this.changes.forEach((n,r)=>{r.isValidDocument()?t.push(this.Br.addEntry(e,r)):this.Br.removeEntry(n)}),eg.waitFor(t)}getFromCache(e,t){return this.Br.getEntry(e,t)}getAllFromCache(e,t){return this.Br.getEntries(e,t)}}class sV{constructor(e){this.persistence=e,this.oi=new n7(e=>nB(e),nz),this.lastRemoteSnapshotVersion=H.min(),this.highestTargetId=0,this._i=0,this.ai=new sk,this.targetCount=0,this.ui=sl.cr()}forEachTarget(e,t){return this.oi.forEach((e,n)=>t(n)),eg.resolve()}getLastRemoteSnapshotVersion(e){return eg.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return eg.resolve(this._i)}allocateTargetId(e){return this.highestTargetId=this.ui.next(),eg.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this._i&&(this._i=t),eg.resolve()}Tr(e){this.oi.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.ui=new sl(t),this.highestTargetId=t),e.sequenceNumber>this._i&&(this._i=e.sequenceNumber)}addTargetData(e,t){return this.Tr(t),this.targetCount+=1,eg.resolve()}updateTargetData(e,t){return this.Tr(t),eg.resolve()}removeTargetData(e,t){return this.oi.delete(t.target),this.ai.Hr(t.targetId),this.targetCount-=1,eg.resolve()}removeTargets(e,t,n){let r=0,i=[];return this.oi.forEach((s,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.oi.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)}),eg.waitFor(i).next(()=>r)}getTargetCount(e){return eg.resolve(this.targetCount)}getTargetData(e,t){let n=this.oi.get(t)||null;return eg.resolve(n)}addMatchingKeys(e,t,n){return this.ai.Gr(t,n),eg.resolve()}removeMatchingKeys(e,t,n){this.ai.jr(t,n);let r=this.persistence.referenceDelegate,i=[];return r&&t.forEach(t=>{i.push(r.markPotentiallyOrphaned(e,t))}),eg.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.ai.Hr(t),eg.resolve()}getMatchingKeysForTargetId(e,t){let n=this.ai.Yr(t);return eg.resolve(n)}containsKey(e,t){return eg.resolve(this.ai.containsKey(t))}}class sO{constructor(e,t){this.ci={},this.overlays={},this.li=new eA(0),this.hi=!1,this.hi=!0,this.Pi=new sD,this.referenceDelegate=e(this),this.Ti=new sV(this),this.indexManager=new i6,this.remoteDocumentCache=new sR(e=>this.referenceDelegate.Ii(e)),this.serializer=new iS(t),this.Ei=new sS(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.hi=!1,Promise.resolve()}get started(){return this.hi}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new sC,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.ci[e.toKey()];return n||(n=new sN(t,this.referenceDelegate),this.ci[e.toKey()]=n),n}getGlobalsCache(){return this.Pi}getTargetCache(){return this.Ti}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Ei}runTransaction(e,t,n){b("MemoryPersistence","Starting transaction:",e);let r=new sF(this.li.next());return this.referenceDelegate.di(),n(r).next(e=>this.referenceDelegate.Ai(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ri(e,t){return eg.or(Object.values(this.ci).map(n=>()=>n.containsKey(e,t)))}}class sF extends ef{constructor(e){super(),this.currentSequenceNumber=e}}class sL{constructor(e){this.persistence=e,this.Vi=new sk,this.mi=null}static fi(e){return new sL(e)}get gi(){if(this.mi)return this.mi;throw S(60996)}addReference(e,t,n){return this.Vi.addReference(n,t),this.gi.delete(n.toString()),eg.resolve()}removeReference(e,t,n){return this.Vi.removeReference(n,t),this.gi.add(n.toString()),eg.resolve()}markPotentiallyOrphaned(e,t){return this.gi.add(t.toString()),eg.resolve()}removeTarget(e,t){this.Vi.Hr(t.targetId).forEach(e=>this.gi.add(e.toString()));let n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.gi.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}di(){this.mi=new Set}Ai(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return eg.forEach(this.gi,n=>{let r=et.fromPath(n);return this.pi(e,r).next(e=>{e||t.removeEntry(r,H.min())})}).next(()=>(this.mi=null,t.apply(e)))}updateLimboDocument(e,t){return this.pi(e,t).next(e=>{e?this.gi.delete(t.toString()):this.gi.add(t.toString())})}Ii(e){return 0}pi(e,t){return eg.or([()=>eg.resolve(this.Vi.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ri(e,t)])}}class sP{constructor(e,t){this.persistence=e,this.yi=new n7(e=>eV(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=new sg(this,t)}static fi(e,t){return new sP(e,t)}di(){}Ai(e){return eg.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEac
6hTarget(e,t)}pr(e){let t=this.br(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}br(e){let t=0;return this.yr(e,e=>{t++}).next(()=>t)}yr(e,t){return eg.forEach(this.yi,(n,r)=>this.Dr(e,n,r).next(e=>e?eg.resolve():t(r)))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,t){let n=0,r=this.persistence.getRemoteDocumentCache(),i=r.newChangeBuffer();return r.si(e,r=>this.Dr(e,r,t).next(e=>{e||(n++,i.removeEntry(r,H.min()))})).next(()=>i.apply(e)).next(()=>n)}markPotentiallyOrphaned(e,t){return this.yi.set(t,e.currentSequenceNumber),eg.resolve()}removeTarget(e,t){let n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.yi.set(n,e.currentSequenceNumber),eg.resolve()}removeReference(e,t,n){return this.yi.set(n,e.currentSequenceNumber),eg.resolve()}updateLimboDocument(e,t){return this.yi.set(t,e.currentSequenceNumber),eg.resolve()}Ii(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(t9(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let n=tJ(t);return n?16+e(n):16;case 5:return 2*t.stringValue.length;case 6:return tG(t.bytesValue).approximateByteSize();case 7:return t.referenceValue.length;case 9:return(t.arrayValue.values||[]).reduce((t,n)=>t+e(n),0);case 10:case 11:var r;let i;return r=t.mapValue,i=0,tk(r.fields,(t,n)=>{i+=t.length+e(n)}),i;default:throw S(13486,{value:t})}}(e.data.value)),t}Dr(e,t,n){return eg.or([()=>this.persistence.Ri(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.yi.get(t);return eg.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class sq{constructor(e){this.serializer=e}q(e,t,n,r){let i=new ey("createOrUpgrade",t);n<1&&r>=1&&(e.createObjectStore(eL),e.createObjectStore(eq,{keyPath:"userId"}),e.createObjectStore(eU,{keyPath:eB,autoIncrement:!0}).createIndex(ez,e$,{unique:!0}),e.createObjectStore(eG),sU(e),e.createObjectStore(eF));let s=eg.resolve();return n<3&&r>=3&&(0!==n&&(e.deleteObjectStore(e5),e.deleteObjectStore(e0),e.deleteObjectStore(e9),sU(e)),s=s.next(()=>(function(e){let t=e.store(e9),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:H.min().toTimestamp(),targetCount:0};return t.put(e8,n)})(i))),n<4&&r>=4&&(0!==n&&(s=s.next(()=>i.store(eU).J().next(t=>{e.deleteObjectStore(eU),e.createObjectStore(eU,{keyPath:eB,autoIncrement:!0}).createIndex(ez,e$,{unique:!0});let n=i.store(eU),r=t.map(e=>n.put(e));return eg.waitFor(r)}))),s=s.next(()=>{e.createObjectStore(tt,{keyPath:"clientId"})})),n<5&&r>=5&&(s=s.next(()=>this.wi(i))),n<6&&r>=6&&(s=s.next(()=>(e.createObjectStore(eX),this.bi(i)))),n<7&&r>=7&&(s=s.next(()=>this.Si(i))),n<8&&r>=8&&(s=s.next(()=>this.Di(e,i))),n<9&&r>=9&&(s=s.next(()=>{e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")})),n<10&&r>=10&&(s=s.next(()=>this.Ci(i))),n<11&&r>=11&&(s=s.next(()=>{e.createObjectStore(tn,{keyPath:"bundleId"}),e.createObjectStore(tr,{keyPath:"name"})})),n<12&&r>=12&&(s=s.next(()=>{let t=e.createObjectStore(tm,{keyPath:tg});t.createIndex(tp,ty,{unique:!1}),t.createIndex(tw,tv,{unique:!1})})),n<13&&r>=13&&(s=s.next(()=>(function(e){let t=e.createObjectStore(eQ,{keyPath:ej});t.createIndex(eW,eH),t.createIndex(eY,eJ)})(e)).next(()=>this.Fi(e,i)).next(()=>e.deleteObjectStore(eF))),n<14&&r>=14&&(s=s.next(()=>this.Mi(e,i))),n<15&&r>=15&&(s=s.next(()=>{e.createObjectStore(ti,{keyPath:"indexId",autoIncrement:!0}).createIndex(ts,"collectionGroup",{unique:!1}),e.createObjectStore(ta,{keyPath:to}).createIndex(tl,tu,{unique:!1}),e.createObjectStore(tc,{keyPath:th}).createIndex(td,tf,{unique:!1})})),n<16&&r>=16&&(s=s.next(()=>{t.objectStore(ta).clear()}).next(()=>{t.objectStore(tc).clear()})),n<17&&r>=17&&(s=s.next(()=>{e.createObjectStore(tI,{keyPath:"name"})})),n<18&&r>=18&&(0,c.Ov)()&&(s=s.next(()=>{t.objectStore(ta).clear()}).next(()=>{t.objectStore(tc).clear()})),s}bi(e){let t=0;return e.store(eF).te((e,n)=>{t+=si(n)}).next(()=>{let n={byteSize:t};return e.store(eX).put(eZ,n)})}wi(e){let t=e.store(eq),n=e.store(eU);return t.J().next(t=>eg.forEach(t,t=>{let r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.J(ez,r).next(n=>eg.forEach(n,n=>{D(n.userId===t.userId,18650,"Cannot process batch from unexpected user",{batchId:n.batchId});let r=iN(this.serializer,n);return sr(e,t.userId,r).next(()=>{})}))}))}Si(e){let t=e.store(e5),n=e.store(eF);return e.store(e9).get(e8).next(e=>{let r=[];return n.te((n,i)=>{let s=new X(n),a=[0,eV(s)];r.push(t.get(a).next(n=>n?eg.resolve():t.put({targetId:0,path:eV(s),sequenceNumber:e.highestListenSequenceNumber})))}).next(()=>eg.waitFor(r))})}Di(e,t){e.createObjectStore(e7,{keyPath:te});let n=t.store(e7),r=new i3,i=e=>{if(r.add(e)){let t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:eV(r)})}};return t.store(eF).te({ee:!0},(e,t)=>i(new X(e).popLast())).next(()=>t.store(eG).te({ee:!0},([e,t,n],r)=>
6i(eO(t).popLast())))}Ci(e){let t=e.store(e0);return t.te((e,n)=>{let r=iR(n),i=iM(this.serializer,r);return t.put(i)})}Fi(e,t){let n=t.store(eF),r=[];return n.te((e,n)=>{let i=t.store(eQ),s=(n.document?new et(X.fromString(n.document.name).popFirst(5)):n.noDocument?et.fromSegments(n.noDocument.path):n.unknownDocument?et.fromSegments(n.unknownDocument.path):S(36783)).path.toArray(),a={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(a))}).next(()=>eg.waitFor(r))}Mi(e,t){let n=t.store(eU),r=new sv(this.serializer),i=new sO(sL.fi,this.serializer.wt);return n.J().next(e=>{let n=new Map;return e.forEach(e=>{var t;let r=null!=(t=n.get(e.userId))?t:ro();iN(this.serializer,e).keys().forEach(e=>r=r.add(e)),n.set(e.userId,r)}),eg.forEach(n,(e,n)=>{let s=new y(n),a=iq.bt(this.serializer,s),o=i.getIndexManager(s);return new sx(r,ss.bt(s,this.serializer,o,i.referenceDelegate),a,o).recalculateAndSaveOverlaysForDocumentKeys(new tS(t,eA.le),e).next()})})}}function sU(e){e.createObjectStore(e5,{keyPath:e4}).createIndex(e6,e3,{unique:!0}),e.createObjectStore(e0,{keyPath:"targetId"}).createIndex(e1,e2,{unique:!0}),e.createObjectStore(e9)}let sB="IndexedDbPersistence",sz="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.",s$="main";class sK{constructor(e,t,n,r,i,s,a,o,l,u,c=18){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.xi=i,this.window=s,this.document=a,this.Oi=l,this.Ni=u,this.Bi=c,this.li=null,this.hi=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Li=null,this.inForeground=!1,this.ki=null,this.qi=null,this.Qi=-1/0,this.$i=e=>Promise.resolve(),!sK.C())throw new N(A.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new sp(this,r),this.Ui=t+s$,this.serializer=new iS(o),this.Ki=new ew(this.Ui,this.Bi,new sq(this.serializer)),this.Pi=new iU,this.Ti=new su(this.referenceDelegate,this.serializer),this.remoteDocumentCache=new sv(this.serializer),this.Ei=new iP,this.window&&this.window.localStorage?this.Wi=this.window.localStorage:(this.Wi=null,!1===u&&T(sB,"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.Gi().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new N(A.FAILED_PRECONDITION,sz);return this.zi(),this.ji(),this.Hi(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Ti.getHighestSequenceNumber(e))}).then(e=>{this.li=new eA(e,this.Oi)}).then(()=>{this.hi=!0}).catch(e=>(this.Ki&&this.Ki.close(),Promise.reject(e)))}Ji(e){return this.$i=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.Ki.U(async t=>{null===t.newVersion&&await e()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.xi.enqueueAndForget(async()=>{this.started&&await this.Gi()}))}Gi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",e=>tC(e,tt).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next(()=>{if(this.isPrimary)return this.Yi(e).next(e=>{e||(this.isPrimary=!1,this.xi.enqueueRetryable(()=>this.$i(!1)))})}).next(()=>this.Zi(e)).next(t=>this.isPrimary&&!t?this.Xi(e).next(()=>!1):!!t&&this.es(e).next(()=>!0))).catch(e=>{if(eb(e))return b(sB,"Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return b(sB,"Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.xi.enqueueRetryable(()=>this.$i(e)),this.isPrimary=e})}Yi(e){return tC(e,eL).get(eP).next(e=>eg.resolve(this.ts(e)))}ns(e){return tC(e,tt).delete(this.clientId)}async rs(){if(this.isPrimary&&!this.ss(this.Qi,18e5)){this.Qi=Date.now();let e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{let t=tC(e,tt);return t.J().next(e=>{let n=this._s(e,18e5),r=e.filter(e=>-1===n.indexOf(e));return eg.forEach(r,e=>t.delete(e.clientId)).next(()=>r)})}).catch(()=>[]);if(this.Wi)for(let t of e)this.Wi.removeItem(this.us(t.clientId))}}Hi(){this.qi=this.xi.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Gi().then(()=>this.rs()).then(()=>this.Hi()))}ts(e){return!!e&&e.ownerId===this.clientId}Zi(e){return this.Ni?eg.resolve(!0):tC(e,eL).get(eP).next(t=>
6{if(null!==t&&this.ss(t.leaseTimestampMs,5e3)&&!this.cs(t.ownerId)){if(this.ts(t)&&this.networkEnabled)return!0;if(!this.ts(t)){if(!t.allowTabSynchronization)throw new N(A.FAILED_PRECONDITION,sz);return!1}}return!(!this.networkEnabled||!this.inForeground)||tC(e,tt).J().next(e=>void 0===this._s(e,5e3).find(e=>{if(this.clientId!==e.clientId){let t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&b(sB,`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.hi=!1,this.ls(),this.qi&&(this.qi.cancel(),this.qi=null),this.hs(),this.Ps(),await this.Ki.runTransaction("shutdown","readwrite",[eL,tt],e=>{let t=new tS(e,eA.le);return this.Xi(t).next(()=>this.ns(t))}),this.Ki.close(),this.Ts()}_s(e,t){return e.filter(e=>this.ss(e.updateTimeMs,t)&&!this.cs(e.clientId))}Is(){return this.runTransaction("getActiveClients","readonly",e=>tC(e,tt).J().next(e=>this._s(e,18e5).map(e=>e.clientId)))}get started(){return this.hi}getGlobalsCache(){return this.Pi}getMutationQueue(e,t){return ss.bt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Ti}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new i7(e,this.serializer.wt.databaseId)}getDocumentOverlayCache(e){return iq.bt(this.serializer,e)}getBundleCache(){return this.Ei}runTransaction(e,t,n){var r;let i;b(sB,"Starting transaction:",e);let s=18===(r=this.Bi)||17===r?tx:16===r||15===r?tE:14===r||13===r?tT:12===r?tb:11===r?t_:void S(60245);return this.Ki.runTransaction(e,"readonly"===t?"readonly":"readwrite",s,r=>(i=new tS(r,this.li?this.li.next():eA.le),"readwrite-primary"===t?this.Yi(i).next(e=>!!e||this.Zi(i)).next(t=>{if(!t)throw T(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.xi.enqueueRetryable(()=>this.$i(!1)),new N(A.FAILED_PRECONDITION,ed);return n(i)}).next(e=>this.es(i).next(()=>e)):this.Es(i).next(()=>n(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Es(e){return tC(e,eL).get(eP).next(e=>{if(null!==e&&this.ss(e.leaseTimestampMs,5e3)&&!this.cs(e.ownerId)&&!this.ts(e)&&!(this.Ni||this.allowTabSynchronization&&e.allowTabSynchronization))throw new N(A.FAILED_PRECONDITION,sz)})}es(e){let t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return tC(e,eL).put(eP,t)}static C(){return ew.C()}Xi(e){let t=tC(e,eL);return t.get(eP).next(e=>this.ts(e)?(b(sB,"Releasing primary lease."),t.delete(eP)):eg.resolve())}ss(e,t){let n=Date.now();return!(e<n-t)&&(!(e>n)||(T(`Detected an update time that is in the future: ${e} > ${n}`),!1))}zi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.ki=()=>{this.xi.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Gi()))},this.document.addEventListener("visibilitychange",this.ki),this.inForeground="visible"===this.document.visibilityState)}hs(){this.ki&&(this.document.removeEventListener("visibilitychange",this.ki),this.ki=null)}ji(){var e;"function"==typeof(null==(e=this.window)?void 0:e.addEventListener)&&(this.Li=()=>{this.ls();let e=/(?:Version|Mobile)\/1[456]/;(0,c.nr)()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.xi.enterRestrictedMode(!0),this.xi.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Li))}Ps(){this.Li&&(this.window.removeEventListener("pagehide",this.Li),this.Li=null)}cs(e){var t;try{let n=null!==(null==(t=this.Wi)?void 0:t.getItem(this.us(e)));return b(sB,`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return T(sB,"Failed to get zombied client id.",e),!1}}ls(){if(this.Wi)try{this.Wi.setItem(this.us(this.clientId),String(Date.now()))}catch(e){T("Failed to set zombie client id.",e)}}Ts(){if(this.Wi)try{this.Wi.removeItem(this.us(this.clientId))}catch(e){}}us(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function sG(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class sQ{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.ds=n,this.As=r}static Rs(e,t){let n=ro(),r=ro();for(let e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new sQ(e,t.fromCache,n,r)}}class sj{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class sW{constructor(){this.Vs=!1,this.fs=!1,this.gs=100,this.ps=(0,c.nr)()?8:ev((0,c.ZQ)())>0?6:4}initialize(e,t){this.ys=e,this.indexManager=t,this.Vs=!0}getDocumentsMatchingQuery(e,t,n,r){let i={result:null};return this.ws(e,t).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.bs(e,t,r,n).next(e=>{i.result=e})}).next(()=>{if(i.result)return;let n=new sj;return this.Ss(e,t,n).next(r=>{if(i.result=r,this.fs)return this.Ds(e,t,n,r.size)})}).next(()=>i.result)}Ds(e,t,n,r){return n.documentReadCount<this.gs?(I()<=u.$b.DEBUG&&b("QueryEngine","SDK will not create cache indexes for query:",n6(t),"since it only creates cache indexes for collection contains","more than or equal to",this.gs,"documents"),eg.resolve()):(I()<=u.$b.DEBUG&&b("QueryEngine","Query:",n6(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.ps*r?(I()<=u.$b.DEBUG&&b("QueryEngine","The SDK decides to create cache indexes for query:",n6(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,nX(t))):eg.resolve())}ws(e,t){if(nH(t))return eg.resolve(null);let n=nX(t);return this.indexManager.getIndexType(e,n).next(r=>0===r?null:(null!==t.limit&&1===r&&(n=nX(t=n2(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,n).next(r=>{let i=ro(...r);return this.ys.getDocuments(e,i).next(r=>this.indexManager.getMinOffset(e,n).next(n=>{let s=this.vs(t,r);return this.Cs(t,s,i,n.readTime)?this.ws(e,n2(t,null,"F")):this.Fs(e,s,t,n)}))})))}bs(e,t,n,r){return nH(t)||r.isEqual(H.min())?eg.resolve(null):this.ys.getDocuments(e,n).next(i=>{let s=this.vs(t,i);return this.Cs(t,s,n,r)?eg.resolve(null):(I()<=u.$b.DEBUG&&b("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),n6(t)),this.Fs(e,s,t,el(r,-1)).next(e=>e))})}vs(e,t){let n=new tO(n9(e));return t.forEach((t,r)=>{n3(e,r)&&(n=n.add(r))}),n}Cs(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;let i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}Ss(e,t,n){return I()<=u.$b.DEBUG&&b("QueryEngine","Using full collection scan to execute query:",n6(t)),this.ys.getDocumentsMatchingQuery(e,t,e
6c.min(),n)}Fs(e,t,n,r){return this.ys.getDocumentsMatchingQuery(e,n,r).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let sH="LocalStore";class sY{constructor(e,t,n,r){this.persistence=e,this.Ms=t,this.serializer=r,this.xs=new tR(K),this.Os=new n7(e=>nB(e),nz),this.Ns=new Map,this.Bs=e.getRemoteDocumentCache(),this.Ti=e.getTargetCache(),this.Ei=e.getBundleCache(),this.Ls(n)}Ls(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new sx(this.Bs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Bs.setIndexManager(this.indexManager),this.Ms.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.xs))}}async function sJ(e,t){return await e.persistence.runTransaction("Handle user change","readonly",n=>{let r;return e.mutationQueue.getAllMutationBatches(n).next(i=>(r=i,e.Ls(t),e.mutationQueue.getAllMutationBatches(n))).next(t=>{let i=[],s=[],a=ro();for(let e of r)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(n,a).next(e=>({ks:e,removedBatchIds:i,addedBatchIds:s}))})})}function sX(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.Ti.getLastRemoteSnapshotVersion(t))}function sZ(e,t,n){let r=ro(),i=ro();return n.forEach(e=>r=r.add(e)),t.getEntries(e,r).next(e=>{let r=re;return n.forEach((n,s)=>{let a=e.get(n);s.isFoundDocument()!==a.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(H.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!a.isValidDocument()||s.version.compareTo(a.version)>0||0===s.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):b(sH,"Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",s.version)}),{qs:r,Qs:i}})}function s0(e,t){return e.persistence.runTransaction("Allocate target","readwrite",n=>{let r;return e.Ti.getTargetData(n,t).next(i=>i?(r=i,eg.resolve(r)):e.Ti.allocateTargetId(n).next(i=>(r=new ix(t,i,"TargetPurposeListen",n.currentSequenceNumber),e.Ti.addTargetData(n,r).next(()=>r))))}).then(n=>{let r=e.xs.get(n.targetId);return(null===r||n.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(e.xs=e.xs.insert(n.targetId,n),e.Os.set(t,n.targetId)),n})}async function s1(e,t,n){let r=e.xs.get(t);try{n||await e.persistence.runTransaction("Release target",n?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,r))}catch(e){if(!eb(e))throw e;b(sH,`Failed to update sequence numbers for target ${t}: ${e}`)}e.xs=e.xs.remove(t),e.Os.delete(r.target)}function s2(e,t,n){let r=H.min(),i=ro();return e.persistence.runTransaction("Execute query","readwrite",s=>(function(e,t,n){let r=e.Os.get(n);return void 0!==r?eg.resolve(e.xs.get(r)):e.Ti.getTargetData(t,n)})(e,s,nX(t)).next(t=>{if(t)return r=t.lastLimboFreeSnapshotVersion,e.Ti.getMatchingKeysForTargetId(s,t.targetId).next(e=>{i=e})}).next(()=>e.Ms.getDocumentsMatchingQuery(s,t,n?r:H.min(),n?i:ro())).next(n=>(s6(e,n8(t),n),{documents:n,$s:i})))}function s5(e,t){let n=e.Ti,r=e.xs.get(t);return r?Promise.resolve(r.target):e.persistence.runTransaction("Get target data","readonly",e=>n.Rt(e,t).next(e=>e?e.target:null))}function s4(e,t){let n=e.Ns.get(t)||H.min();return e.persistence.runTransaction("Get new document changes","readonly",r=>e.Bs.getAllFromCollectionGroup(r,t,el(n,-1),Number.MAX_SAFE_INTEGER)).then(n=>(s6(e,t,n),n))}function s6(e,t,n){let r=e.Ns.get(t)||H.min();n.forEach((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)}),e.Ns.set(t,r)}async function s3(e,t,n,r){let i=ro(),s=re;for(let e of n){let n=t.Us(e.metadata.name);e.document&&(i=i.add(n));let r=t.Ks(e);r.setReadTime(t.Ws(e.metadata.readTime)),s=s.insert(n,r)}let a=e.Bs.newChangeBuffer({trackRemovals:!0}),o=await s0(e,nX(nW(X.fromString(`__bundle__/docs/${r}`))));return e.persistence.runTransaction("Apply bundle documents","readwrite",t=>sZ(t,a,s).next(e=>(a.apply(t),e)).next(n=>e.Ti.removeMatchingKeysForTargetId(t,o.targetId).next(()=>e.Ti.addMatchingKeys(t,i,o.targetId)).next(()=>e.localDocuments.getLocalViewOfDocuments(t,n.qs,n.Qs)).next(()=>n.qs)))}async function s8(e,t,n=ro()){let r=await s0(e,nX(iV(t.bundledQuery)));return e.persistence.runTransaction("Save named query","readwrite",i=>{let s=ir(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return e.Ei.saveNamedQuery(i,t);let a=r.withResumeToken(tB.EMPTY_BYTE_STRING,s);return e.xs=e.xs.insert(a.targetId,a),e.Ti.updateTargetData(i,a).next(()=>e.Ti.removeMatchingKeysForTargetId(i,r.targetId)).next(()=>e.Ti.addMatchingKeys(i,n,r.targetId)).next(()=>e.Ei.saveNamedQuery(i,t))})}let s9="firestore_clients";function s7(e,t){return`${s9}_${e}_${t}`}let ae="firestore_mutations";function at(e,t,n){let r=`${ae}_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}let an="firestore_targets";function ar(e,t){return`${an}_${e}_${t}`}
6let ai="SharedClientState";class as{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Gs(e,t,n){let r=JSON.parse(n),i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(i=new N(r.error.code,r.error.message)),s?new as(e,t,r.state,i):(T(ai,`Failed to parse mutation state for ID '${t}': ${n}`),null)}zs(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class aa{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Gs(e,t){let n=JSON.parse(t),r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(r=new N(n.error.code,n.error.message)),i?new aa(e,n.state,r):(T(ai,`Failed to parse target state for ID '${e}': ${t}`),null)}zs(){let e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class ao{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Gs(e,t){let n=JSON.parse(t),r="object"==typeof n&&n.activeTargetIds instanceof Array,i=rl;for(let e=0;r&&e<n.activeTargetIds.length;++e)r=eM(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new ao(e,i):(T(ai,`Failed to parse client data for instance '${e}': ${t}`),null)}}class al{constructor(e,t){this.clientId=e,this.onlineState=t}static Gs(e){let t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new al(t.clientId,t.onlineState):(T(ai,`Failed to parse online state: ${e}`),null)}}class au{constructor(){this.activeTargetIds=rl}js(e){this.activeTargetIds=this.activeTargetIds.add(e)}Hs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}zs(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class ac{constructor(e,t,n,r,i){var s,a,o;this.window=e,this.xi=t,this.persistenceKey=n,this.Js=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Ys=this.Zs.bind(this),this.Xs=new tR(K),this.started=!1,this.eo=[];let l=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.no=s7(this.persistenceKey,this.Js),this.ro=(s=this.persistenceKey,`firestore_sequence_number_${s}`),this.Xs=this.Xs.insert(this.Js,new au),this.io=RegExp(`^${s9}_${l}_([^_]*)$`),this.so=RegExp(`^${ae}_${l}_(\\d+)(?:_(.*))?$`),this.oo=RegExp(`^${an}_${l}_(\\d+)$`),this._o=(a=this.persistenceKey,`firestore_online_state_${a}`),this.ao=(o=this.persistenceKey,`firestore_bundle_loaded_v2_${o}`),this.window.addEventListener("storage",this.Ys)}static C(e){return!(!e||!e.localStorage)}async start(){for(let e of(await this.syncEngine.Is())){if(e===this.Js)continue;let t=this.getItem(s7(this.persistenceKey,e));if(t){let n=ao.Gs(e,t);n&&(this.Xs=this.Xs.insert(n.clientId,n))}}this.uo();let e=this.storage.getItem(this._o);if(e){let t=this.co(e);t&&this.lo(t)}for(let e of this.eo)this.Zs(e);this.eo=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.ro,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ho(this.Xs)}isActiveQueryTarget(e){let t=!1;return this.Xs.forEach((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)}),t}addPendingMutation(e){this.Po(e,"pending")}updateMutationState(e,t,n){this.Po(e,t,n),this.To(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){let t=this.storage.getItem(ar(this.persistenceKey,e));if(t){let r=aa.Gs(e,t);r&&(n=r.state)}}return t&&this.Io.js(e),this.uo(),n}removeLocalQueryTarget(e){this.Io.Hs(e),this.uo()}isLocalQueryTarget(e){return this.Io.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(ar(this.persistenceKey,e))}updateQueryState(e,t,n){this.Eo(e,t,n)}
6handleUserChange(e,t,n){t.forEach(e=>{this.To(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.Ao(e)}notifyBundleLoaded(e){this.Ro(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Ys),this.removeItem(this.no),this.started=!1)}getItem(e){let t=this.storage.getItem(e);return b(ai,"READ",e,t),t}setItem(e,t){b(ai,"SET",e,t),this.storage.setItem(e,t)}removeItem(e){b(ai,"REMOVE",e),this.storage.removeItem(e)}Zs(e){if(e.storageArea===this.storage){if(b(ai,"EVENT",e.key,e.newValue),e.key===this.no)return void T("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.xi.enqueueRetryable(async()=>{if(this.started){if(null!==e.key){if(this.io.test(e.key)){if(null==e.newValue){let t=this.Vo(e.key);return this.mo(t,null)}{let t=this.fo(e.key,e.newValue);if(t)return this.mo(t.clientId,t)}}else if(this.so.test(e.key)){if(null!==e.newValue){let t=this.po(e.key,e.newValue);if(t)return this.yo(t)}}else if(this.oo.test(e.key)){if(null!==e.newValue){let t=this.wo(e.key,e.newValue);if(t)return this.bo(t)}}else if(e.key===this._o){if(null!==e.newValue){let t=this.co(e.newValue);if(t)return this.lo(t)}}else if(e.key===this.ro){let t=function(e){let t=eA.le;if(null!=e)try{let n=JSON.parse(e);D("number"==typeof n,30636,{So:e}),t=n}catch(e){T(ai,"Failed to read sequence number from WebStorage",e)}return t}(e.newValue);t!==eA.le&&this.sequenceNumberHandler(t)}else if(e.key===this.ao){let t=this.Do(e.newValue);await Promise.all(t.map(e=>this.syncEngine.vo(e)))}}}else this.eo.push(e)})}}get Io(){return this.Xs.get(this.Js)}uo(){this.setItem(this.no,this.Io.zs())}Po(e,t,n){let r=new as(this.currentUser,e,t,n),i=at(this.persistenceKey,this.currentUser,e);this.setItem(i,r.zs())}To(e){let t=at(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Ao(e){let t={clientId:this.Js,onlineState:e};this.storage.setItem(this._o,JSON.stringify(t))}Eo(e,t,n){let r=ar(this.persistenceKey,e),i=new aa(e,t,n);this.setItem(r,i.zs())}Ro(e){let t=JSON.stringify(Array.from(e));this.setItem(this.ao,t)}Vo(e){let t=this.io.exec(e);return t?t[1]:null}fo(e,t){let n=this.Vo(e);return ao.Gs(n,t)}po(e,t){let n=this.so.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return as.Gs(new y(i),r,t)}wo(e,t){let n=Number(this.oo.exec(e)[1]);return aa.Gs(n,t)}co(e){return al.Gs(e)}Do(e){return JSON.parse(e)}async yo(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.Co(e.batchId,e.state,e.error);b(ai,`Ignoring mutation for non-active user ${e.user.uid}`)}bo(e){return this.syncEngine.Fo(e.targetId,e.state,e.error)}mo(e,t){let n=t?this.Xs.insert(e,t):this.Xs.remove(e),r=this.ho(this.Xs),i=this.ho(n),s=[],a=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||a.push(e)}),this.syncEngine.Mo(s,a).then(()=>{this.Xs=n})}lo(e){this.Xs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ho(e){let t=rl;return e.forEach((e,n)=>{t=t.unionWith(n.activeTargetIds)}),t}}class ah{constructor(){this.xo=new au,this.Oo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this.xo.js(e),this.Oo[e]||"not-current"}updateQueryState(e,t,n){this.Oo[e]=t}removeLocalQueryTarget(e){this.xo.Hs(e)}isLocalQueryTarget(e){return this.xo.activeTargetIds.has(e)}clearQueryState(e){delete this.Oo[e]}getAllActiveQueryTargets(){return this.xo.activeTargetIds}isActiveQueryTarget(e){return this.xo.activeTargetIds.has(e)}start(){return this.xo=new au,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class ad{No(e){}shutdown(){}}let af="ConnectivityMonitor";class am{constructor(){this.Bo=()=>this.Lo(),this.ko=()=>this.qo(),this.Qo=[],this.$o()}No(e){this.Qo.push(e)}shutdown(){window.removeEventListener("online",this.Bo),window.removeEventListener("offline",this.ko)}$o(){window.addEventListener("online",this.Bo),window.addEventListener("offline",this.ko)}Lo(){for(let e of(b(af,"Network connectivity changed: AVAILABLE"),this.Qo))e(0)}qo(){for(let e of(b(af,"Network connectivity changed: UNAVAILABLE"),this.Qo))e(1)}static C(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let ag=null;function ap(){return null===ag?ag=0x10000000+Math.round(0x80000000*Math.random()):ag++,"0x"+ag.toString(16)}let ay="RestConnection",aw={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregation
6Query:"runAggregationQuery"};class av{get Uo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;let t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.Ko=t+"://"+e.host,this.Wo=`projects/${n}/databases/${r}`,this.Go=this.databaseId.database===t0?`project_id=${n}`:`project_id=${n}&database_id=${r}`}zo(e,t,n,r,i){let s=ap(),a=this.jo(e,t.toUriEncodedString());b(ay,`Sending RPC '${e}' ${s}:`,a,n);let o={"google-cloud-resource-prefix":this.Wo,"x-goog-request-params":this.Go};this.Ho(o,r,i);let{host:l}=new URL(a),u=(0,c.zJ)(l);return this.Jo(e,a,o,n,u).then(t=>(b(ay,`Received RPC '${e}' ${s}: `,t),t),t=>{throw E(ay,`RPC '${e}' ${s} failed with error: `,t,"url: ",a,"request:",n),t})}Yo(e,t,n,r,i,s){return this.zo(e,t,n,r,i)}Ho(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+w,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((t,n)=>e[n]=t),n&&n.headers.forEach((t,n)=>e[n]=t)}jo(e,t){let n=aw[e];return`${this.Ko}/v1/${t}:${n}`}terminate(){}}class aI{constructor(e){this.Zo=e.Zo,this.Xo=e.Xo}e_(e){this.t_=e}n_(e){this.r_=e}i_(e){this.s_=e}onMessage(e){this.o_=e}close(){this.Xo()}send(e){this.Zo(e)}__(){this.t_()}a_(){this.r_()}u_(e){this.s_(e)}c_(e){this.o_(e)}}let a_="WebChannelConnection";class ab extends av{constructor(e){super(e),this.l_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Jo(e,t,n,r,i){let s=ap();return new Promise((i,a)=>{let o=new d.ZS;o.setWithCredentials(!0),o.listenOnce(d.Bx.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case d.O4.NO_ERROR:let t=o.getResponseJson();b(a_,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case d.O4.TIMEOUT:b(a_,`RPC '${e}' ${s} timed out`),a(new N(A.DEADLINE_EXCEEDED,"Request time out"));break;case d.O4.HTTP_ERROR:let n=o.getStatus();if(b(a_,`RPC '${e}' ${s} failed with status:`,n,"response text:",o.getResponseText()),n>0){let e=o.getResponseJson();Array.isArray(e)&&(e=e[0]);let t=null==e?void 0:e.error;if(t&&t.status&&t.message){let e=function(e){let t=e.toLowerCase().replace(/_/g,"-");return Object.values(A).indexOf(t)>=0?t:A.UNKNOWN}(t.status);a(new N(e,t.message))}else a(new N(A.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new N(A.UNAVAILABLE,"Connection failed."));break;default:S(9055,{h_:e,streamId:s,P_:o.getLastErrorCode(),T_:o.getLastError()})}}finally{b(a_,`RPC '${e}' ${s} completed.`)}});let l=JSON.stringify(r);b(a_,`RPC '${e}' ${s} sending request:`,r),o.send(t,"POST",l,n,15)})}I_(e,t,n){let i=ap(),s=[this.Ko,"/","google.firestore.v1.Firestore","/",e,"/channel"],a=(0,d.fF)(),o=(0,d.Ao)(),l={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(l.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(l.useFetchStreams=!0),this.Ho(l.initMessageHeaders,t,n),l.encodeInitMessageHeaders=!0;let c=s.join("");b(a_,`Creating RPC '${e}' stream ${i}: ${c}`,l);let h=a.createWebChannel(c,l);this.E_(h);let f=!1,m=!1,g=new aI({Zo:t=>{m?b(a_,`Not sending because RPC '${e}' stream ${i} is closed:`,t):(f||(b(a_,`Opening RPC '${e}' stream ${i} transport.`),h.open(),f=!0),b(a_,`RPC '${e}' stream ${i} sending:`,t),h.send(t))},Xo:()=>h.close()}),p=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return p(h,d.iO.EventType.OPEN,()=>{m||(b(a_,`RPC '${e}' stream ${i} transport opened.`),g.__())}),p(h,d.iO.EventType.CLOSE,()=>{m||(m=!0,b(a_,`RPC '${e}' stream ${i} transport closed`),g.u_(),this.d_(h))}),p(h,d.iO.EventType.ERROR,t=>{m||(m=!0,E(a_,`RPC '${e}' stream ${i} transport errored. Name:`,t.name,"Message:",t.message),g.u_(new N(A.UNAVAILABLE,"The operation could not be completed")))}),p(h,d.iO.EventType.MESSAGE,t=>{var n;if(!m){let s=t.data[0];D(!!s,16349);let a=(null==s?void 0:s.error)||(null==(n=s[0])?void 0:n.error);if(a){b(a_,`RPC '${e}' stream ${i} received error:`,a);let t=a.status,n=function(e){let t=r[e];if(void 0!==t)return r$(t)}(t),s=a.message;void 0===n&&(n=A.INTERNAL,s="Unknown error status: "+t+" with message "+a.message),m=!0,g.u_(new N(n,s)),h.close()}else b(a_,`RPC '${e}' stream ${i}
6 received:`,s),g.c_(s)}}),p(o,d.Jh.STAT_EVENT,t=>{t.stat===d.ro.PROXY?b(a_,`RPC '${e}' stream ${i} detected buffering proxy`):t.stat===d.ro.NOPROXY&&b(a_,`RPC '${e}' stream ${i} detected no buffering proxy`)}),setTimeout(()=>{g.a_()},0),g}terminate(){this.l_.forEach(e=>e.close()),this.l_=[]}E_(e){this.l_.push(e)}d_(e){this.l_=this.l_.filter(t=>t===e)}}function aT(){return"undefined"!=typeof window?window:null}function aE(){return"undefined"!=typeof document?document:null}function ax(e){return new r9(e,!0)}class aS{constructor(e,t,n=1e3,r=1.5,i=6e4){this.xi=e,this.timerId=t,this.A_=n,this.R_=r,this.V_=i,this.m_=0,this.f_=null,this.g_=Date.now(),this.reset()}reset(){this.m_=0}p_(){this.m_=this.V_}y_(e){this.cancel();let t=Math.floor(this.m_+this.w_()),n=Math.max(0,Date.now()-this.g_),r=Math.max(0,t-n);r>0&&b("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.m_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.f_=this.xi.enqueueAfterDelay(this.timerId,r,()=>(this.g_=Date.now(),e())),this.m_*=this.R_,this.m_<this.A_&&(this.m_=this.A_),this.m_>this.V_&&(this.m_=this.V_)}b_(){null!==this.f_&&(this.f_.skipDelay(),this.f_=null)}cancel(){null!==this.f_&&(this.f_.cancel(),this.f_=null)}w_(){return(Math.random()-.5)*this.m_}}let aC="PersistentStream";class aD{constructor(e,t,n,r,i,s,a,o){this.xi=e,this.S_=n,this.D_=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.v_=0,this.C_=null,this.F_=null,this.stream=null,this.M_=0,this.x_=new aS(e,t)}O_(){return 1===this.state||5===this.state||this.N_()}N_(){return 2===this.state||3===this.state}start(){this.M_=0,4!==this.state?this.auth():this.B_()}async stop(){this.O_()&&await this.close(0)}L_(){this.state=0,this.x_.reset()}k_(){this.N_()&&null===this.C_&&(this.C_=this.xi.enqueueAfterDelay(this.S_,6e4,()=>this.q_()))}Q_(e){this.U_(),this.stream.send(e)}async q_(){if(this.N_())return this.close(0)}U_(){this.C_&&(this.C_.cancel(),this.C_=null)}K_(){this.F_&&(this.F_.cancel(),this.F_=null)}async close(e,t){this.U_(),this.K_(),this.x_.cancel(),this.v_++,4!==e?this.x_.reset():t&&t.code===A.RESOURCE_EXHAUSTED?(T(t.toString()),T("Using maximum backoff delay to prevent overloading the backend."),this.x_.p_()):t&&t.code===A.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.W_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.i_(t)}W_(){}auth(){this.state=1;let e=this.G_(this.v_),t=this.v_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,n])=>{this.v_===t&&this.z_(e,n)},t=>{e(()=>{let e=new N(A.UNKNOWN,"Fetching auth token failed: "+t.message);return this.j_(e)})})}z_(e,t){let n=this.G_(this.v_);this.stream=this.H_(e,t),this.stream.e_(()=>{n(()=>this.listener.e_())}),this.stream.n_(()=>{n(()=>(this.state=2,this.F_=this.xi.enqueueAfterDelay(this.D_,1e4,()=>(this.N_()&&(this.state=3),Promise.resolve())),this.listener.n_()))}),this.stream.i_(e=>{n(()=>this.j_(e))}),this.stream.onMessage(e=>{n(()=>1==++this.M_?this.J_(e):this.onNext(e))})}B_(){this.state=5,this.x_.y_(async()=>{this.state=0,this.start()})}j_(e){return b(aC,`close with error: ${e}`),this.stream=null,this.close(4,e)}G_(e){return t=>{this.xi.enqueueAndForget(()=>this.v_===e?t():(b(aC,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class ak extends aD{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}H_(e,t){return this.connection.I_("Listen",e,t)}J_(e){return this.onNext(e)}onNext(e){this.x_.reset();let t=function(e,t){let n;if("targetChange"in t){var r,i;t.targetChange;let s="NO_CHANGE"===(r=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===r?1:"REMOVE"===r?2:"CURRENT"===r?3:"RESET"===r?4:S(39313,{state:r}),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(D(void 0===i||"string"==typeof i,58123),tB.fromBase64String(i||"")):(D(void 0===i||i instanceof m||i instanceof Uint8Array,16193),tB.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;n=new r0(s,a,o,l&&new N(void 0===l.code?A.UNKNOWN:r$(l.code),l.message||"")||null)}else if("documentChange"in t){t.documentChange;let r=t.documentChange;r.document,r.document.name,r.document.updateTime;let i=il(e,r.document.name),s=ir(r.document.updateTime),a=r.document.createTime?ir(r.document.createTime):H.min(),o=new ny({mapValue:{fields:r.document.fields}}),l=nw.newFoundDocument(i,s,a,o);n=new rX(r.targetIds||[],r.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let r=t.documentDelete;r.document;let i=il(e,r.document),s=r.readTime?ir(r.readTime):H.min(),a=nw.newNoDocument(i,s);n=new rX([],r.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let r=t.documentRemove;r.document;let i=il(e,r.document);n=new rX([],r.removedTargetIds||[],i,null)}else{if(!("filter"in t))return S(11601,{Vt:t});{t.filter;let e=t.filter;e.targetId;
6let{count:r=0,unchangedNames:i}=e,s=new rB(r,i);n=new rZ(e.targetId,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return H.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?H.min():t.readTime?ir(t.readTime):H.min()}(e);return this.listener.Y_(t,n)}Z_(e){let t={};t.database=ih(this.serializer),t.addTarget=function(e,t){let n,r=t.target;if((n=n$(r)?{documents:iw(e,r)}:{query:iv(e,r).gt}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=it(e,t.resumeToken);let r=r7(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(H.min())>0){n.readTime=ie(e,t.snapshotVersion.toTimestamp());let r=r7(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);let n=function(e,t){let n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return S(28987,{purpose:e})}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.Q_(t)}X_(e){let t={};t.database=ih(this.serializer),t.removeTarget=e,this.Q_(t)}}class aA extends aD{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}get ea(){return this.M_>0}start(){this.lastStreamToken=void 0,super.start()}W_(){this.ea&&this.ta([])}H_(e,t){return this.connection.I_("Write",e,t)}J_(e){return D(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,D(!e.writeResults||0===e.writeResults.length,55816),this.listener.na()}onNext(e){var t,n;D(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.x_.reset();let r=(t=e.writeResults,n=e.commitTime,t&&t.length>0?(D(void 0!==n,14353),t.map(e=>{let t;return(t=e.updateTime?ir(e.updateTime):ir(n)).isEqual(H.min())&&(t=ir(n)),new rT(t,e.transformResults||[])})):[]),i=ir(e.commitTime);return this.listener.ra(i,r)}ia(){let e={};e.database=ih(this.serializer),this.Q_(e)}ta(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>ip(this.serializer,e))};this.Q_(t)}}class aN{}class aR extends aN{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.sa=!1}oa(){if(this.sa)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.")}zo(e,t,n,r){return this.oa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.zo(e,is(t,n),r,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}Yo(e,t,n,r,i){return this.oa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,a])=>this.connection.Yo(e,is(t,n),r,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===A.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new N(A.UNKNOWN,e.toString())})}terminate(){this.sa=!0,this.connection.terminate()}}class aM{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this._a=0,this.aa=null,this.ua=!0}ca(){0===this._a&&(this.la("Unknown"),this.aa=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.aa=null,this.ha("Backend didn't respond within 10 seconds."),this.la("Offline"),Promise.resolve())))}Pa(e){"Online"===this.state?this.la("Unknown"):(this._a++,this._a>=1&&(this.Ta(),this.ha(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.la("Offline")))}set(e){this.Ta(),this._a=0,"Online"===e&&(this.ua=!1),this.la(e)}la(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}ha(e){let t=`Could not reach Cloud Firestore backend. ${e}
7This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.ua?(T(t),this.ua=!1):b("OnlineStateTracker",t)}Ta(){null!==this.aa&&(this.aa.cancel(),this.aa=null)}}let aV="RemoteStore";class aO{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Ia=[],this.Ea=new Map,this.da=new Set,this.Aa=[],this.Ra=i,this.Ra.No(e=>{n.enqueueAndForget(async()=>
7{aK(this)&&(b(aV,"Restarting streams for network reachability change."),await async function(e){e.da.add(4),await aL(e),e.Va.set("Unknown"),e.da.delete(4),await aF(e)}(this))})}),this.Va=new aM(n,r)}}async function aF(e){if(aK(e))for(let t of e.Aa)await t(!0)}async function aL(e){for(let t of e.Aa)await t(!1)}function aP(e,t){e.Ea.has(t.targetId)||(e.Ea.set(t.targetId,t),a$(e)?az(e):a3(e).N_()&&aU(e,t))}function aq(e,t){let n=a3(e);e.Ea.delete(t),n.N_()&&aB(e,t),0===e.Ea.size&&(n.N_()?n.k_():aK(e)&&e.Va.set("Unknown"))}function aU(e,t){if(e.ma.Ke(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(H.min())>0){let n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}a3(e).Z_(t)}function aB(e,t){e.ma.Ke(t),a3(e).X_(t)}function az(e){e.ma=new r2({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),Rt:t=>e.Ea.get(t)||null,Pt:()=>e.datastore.serializer.databaseId}),a3(e).start(),e.Va.ca()}function a$(e){return aK(e)&&!a3(e).O_()&&e.Ea.size>0}function aK(e){return 0===e.da.size}async function aG(e){e.Va.set("Online")}async function aQ(e){e.Ea.forEach((t,n)=>{aU(e,t)})}async function aj(e,t){e.ma=void 0,a$(e)?(e.Va.Pa(t),az(e)):e.Va.set("Unknown")}async function aW(e,t,n){if(e.Va.set("Online"),t instanceof r0&&2===t.state&&t.cause)try{await async function(e,t){let n=t.cause;for(let r of t.targetIds)e.Ea.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.Ea.delete(r),e.ma.removeTarget(r))}(e,t)}catch(n){b(aV,"Failed to remove targets %s: %s ",t.targetIds.join(","),n),await aH(e,n)}else if(t instanceof rX?e.ma.Xe(t):t instanceof rZ?e.ma.ot(t):e.ma.nt(t),!n.isEqual(H.min()))try{let t=await sX(e.localStore);n.compareTo(t)>=0&&await function(e,t){let n=e.ma.It(t);
7return n.targetChanges.forEach((n,r)=>{if(n.resumeToken.approximateByteSize()>0){let i=e.Ea.get(r);i&&e.Ea.set(r,i.withResumeToken(n.resumeToken,t))}}),n.targetMismatches.forEach((t,n)=>{let r=e.Ea.get(t);if(!r)return;e.Ea.set(t,r.withResumeToken(tB.EMPTY_BYTE_STRING,r.snapshotVersion)),aB(e,t);let i=new ix(r.target,t,n,r.sequenceNumber);aU(e,i)}),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){b(aV,"Failed to raise snapshot:",t),await aH(e,t)}}async function aH(e,t,n){if(!eb(t))throw t;e.da.add(1),await aL(e),e.Va.set("Offline"),n||(n=()=>sX(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{b(aV,"Retrying IndexedDB access"),await n(),e.da.delete(1),await aF(e)})}function aY(e,t){return t().catch(n=>aH(e,n,t))}async function aJ(e){var t;let n=a8(e),r=e.Ia.length>0?e.Ia[e.Ia.length-1].batchId:-1;for(;aK(t=e)&&t.Ia.length<10;)try{let t=await function(e,t){return e.persistence.runTransaction("Get next mutation batch","readonly",n=>(void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(n,t)))}(e.localStore,r);if(null===t){0===e.Ia.length&&n.k_();break}r=t.batchId,function(e,t){e.Ia.push(t);let n=a8(e);n.N_()&&n.ea&&n.ta(t.mutations)}(e,t)}catch(t){await aH(e,t)}aX(e)&&aZ(e)}function aX(e){return aK(e)&&!a8(e).O_()&&e.Ia.length>0}function aZ(e){a8(e).start()}async function a0(e){a8(e).ia()}async function a1(e){let t=a8(e);for(let n of e.Ia)t.ta(n.mutations)}async function a2(e,t,n){let r=e.Ia.shift(),i=rP.from(r,t,n);await aY(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await aJ(e)}async function a5(e,t){t&&a8(e).ea&&await async function(e,t){var n;if(rz(n=t.code)&&n!==A.ABORTED){let n=e.Ia.shift();a8(e).L_(),await aY(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await aJ(e)}}(e,t),aX(e)&&aZ(e)}async function a4(e,t){e.asyncQueue.verifyOperationInProgress(),b(aV,"RemoteStore received new credentials");let n=aK(e);e.da.add(3),await aL(e),n&&e.Va.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.da.delete(3),await aF(e)}async function a6(e,t){t?(e.da.delete(2),await aF(e)):t||(e.da.add(2),await aL(e),e.Va.set("Unknown"))}function a3(e){var t,n,r;return e.fa||(t=e.datastore,n=e.asyncQueue,r={e_:aG.bind(null,e),n_:aQ.bind(null,e),i_:aj.bind(null,e),Y_:aW.bind(null,e)},t.oa(),e.fa=new ak(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.Aa.push(async t=>{t?(e.fa.L_(),a$(e)?az(e):e.Va.set("Unknown")):(await e.fa.stop(),e.ma=void 0)})),e.fa}function a8(e){var t,n,r;return e.ga||(t=e.datastore,n=e.asyncQueue,r={e_:()=>Promise.resolve(),n_:a0.bind(null,e),i_:a5.bind(null,e),na:a1.bind(null,e),ra:a2.bind(null,e)},t.oa(),e.ga=new aA(n,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,r),e.Aa.push(async t=>{t?(e.ga.L_(),await aJ(e)):(await e.ga.stop(),e.Ia.length>0&&(b(aV,`Stopping write stream with ${e.Ia.length} pending writes`),e.Ia=[]))})),e.ga}class a9{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new R,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){let s=new a9(e,t,Date.now()+n,r,i);return s.start(n),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new N(A.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function a7(e,t){if(T("AsyncQueue",`${t}: ${e}`),eb(e))return new N(A.UNAVAILABLE,`${t}: ${e}`);throw e}class oe{static emptySet(e){return new oe(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||et.comparator(t.key,n.key):(e,t)=>et.comparator(e.key,t.key),this.keyedMap=rn(),this.sortedSet=new tR(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,n)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof oe)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){let e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n  "+e.join("  \n")+"\n)"}copy(e,t){let n=new oe;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}
7class ot{constructor(){this.pa=new tR(et.comparator)}track(e){let t=e.doc.key,n=this.pa.get(t);n?0!==e.type&&3===n.type?this.pa=this.pa.insert(t,e):3===e.type&&1!==n.type?this.pa=this.pa.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.pa=this.pa.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.pa=this.pa.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.pa=this.pa.remove(t):1===e.type&&2===n.type?this.pa=this.pa.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.pa=this.pa.insert(t,{type:2,doc:e.doc}):S(63341,{Vt:e,ya:n}):this.pa=this.pa.insert(t,e)}wa(){let e=[];return this.pa.inorderTraversal((t,n)=>{e.push(n)}),e}}class on{constructor(e,t,n,r,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,r,i){let s=[];return t.forEach(e=>{s.push({type:0,doc:e})}),new on(e,t,oe.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&n5(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}class or{constructor(){this.ba=void 0,this.Sa=[]}Da(){return this.Sa.some(e=>e.va())}}class oi{constructor(){this.queries=os(),this.onlineState="Unknown",this.Ca=new Set}terminate(){!function(e,t){let n=e.queries;e.queries=os(),n.forEach((e,n)=>{for(let e of n.Sa)e.onError(t)})}(this,new N(A.ABORTED,"Firestore shutting down"))}}function os(){return new n7(e=>n4(e),n5)}async function oa(e,t){let n=3,r=t.query,i=e.queries.get(r);i?!i.Da()&&t.va()&&(n=2):(i=new or,n=+!t.va());try{switch(n){case 0:i.ba=await e.onListen(r,!0);break;case 1:i.ba=await e.onListen(r,!1);break;case 2:await e.onFirstRemoteStoreListen(r)}}catch(n){let e=a7(n,`Initialization of query '${n6(t.query)}' failed`);return void t.onError(e)}e.queries.set(r,i),i.Sa.push(t),t.Fa(e.onlineState),i.ba&&t.Ma(i.ba)&&oc(e)}async function oo(e,t){let n=t.query,r=3,i=e.queries.get(n);if(i){let e=i.Sa.indexOf(t);e>=0&&(i.Sa.splice(e,1),0===i.Sa.length?r=+!t.va():!i.Da()&&t.va()&&(r=2))}switch(r){case 0:return e.queries.delete(n),e.onUnlisten(n,!0);case 1:return e.queries.delete(n),e.onUnlisten(n,!1);case 2:return e.onLastRemoteStoreUnlisten(n);default:return}}function ol(e,t){let n=!1;for(let r of t){let t=r.query,i=e.queries.get(t);if(i){for(let e of i.Sa)e.Ma(r)&&(n=!0);i.ba=r}}n&&oc(e)}function ou(e,t,n){let r=e.queries.get(t);if(r)for(let e of r.Sa)e.onError(n);e.queries.delete(t)}function oc(e){e.Ca.forEach(e=>{e.next()})}(a=s||(s={})).xa="default",a.Cache="cache";class oh{constructor(e,t,n){this.query=e,this.Oa=t,this.Na=!1,this.Ba=null,this.onlineState="Unknown",this.options=n||{}}Ma(e){if(!this.options.includeMetadataChanges){let t=[];for(let n of e.docChanges)3!==n.type&&t.push(n);e=new on(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Na?this.La(e)&&(this.Oa.next(e),t=!0):this.ka(e,this.onlineState)&&(this.qa(e),t=!0),this.Ba=e,t}onError(e){this.Oa.error(e)}Fa(e){this.onlineState=e;let t=!1;return this.Ba&&!this.Na&&this.ka(this.Ba,e)&&(this.qa(this.Ba),t=!0),t}ka(e,t){return!(e.fromCache&&this.va())||(!this.options.Qa||"Offline"===t)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}La(e){if(e.docChanges.length>0)return!0;let t=this.Ba&&this.Ba.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}qa(e){e=on.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Na=!0,this.Oa.next(e)}va(){return this.options.source!==s.Cache}}class od{constructor(e,t){this.$a=e,this.byteLength=t}Ua(){return"metadata"in this.$a}}
7class of{constructor(e){this.serializer=e}Us(e){return il(this.serializer,e)}Ks(e){return e.metadata.exists?ig(this.serializer,e.document,!1):nw.newNoDocument(this.Us(e.metadata.name),this.Ws(e.metadata.readTime))}Ws(e){return ir(e)}}class om{constructor(e,t,n){this.Ka=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=og(e)}Wa(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.$a.namedQuery)this.queries.push(e.$a.namedQuery);else if(e.$a.documentMetadata){this.documents.push({metadata:e.$a.documentMetadata}),e.$a.documentMetadata.exists||++t;let n=X.fromString(e.$a.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.$a.document&&(this.documents[this.documents.length-1].document=e.$a.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Ga(e){let t=new Map,n=new of(this.serializer);for(let r of e)if(r.metadata.queries){let e=n.Us(r.metadata.name);for(let n of r.metadata.queries){let r=(t.get(n)||ro()).add(e);t.set(n,r)}}return t}async complete(){let e=await s3(this.localStore,new of(this.serializer),this.documents,this.Ka.id),t=this.Ga(this.documents);for(let e of this.queries)await s8(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,za:this.collectionGroups,ja:e}}}function og(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class op{constructor(e){this.key=e}}class oy{constructor(e){this.key=e}}class ow{constructor(e,t){this.query=e,this.Ha=t,this.Ja=null,this.hasCachedResults=!1,this.current=!1,this.Ya=ro(),this.mutatedKeys=ro(),this.Za=n9(e),this.Xa=new oe(this.Za)}get eu(){return this.Ha}tu(e,t){let n=t?t.nu:new ot,r=t?t.Xa:this.Xa,i=t?t.mutatedKeys:this.mutatedKeys,s=r,a=!1,o="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,l="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal((e,t)=>{let u=r.get(e),c=n3(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!c&&(c.hasLocalMutations||this.mutatedKeys.has(c.key)&&c.hasCommittedMutations),f=!1;u&&c?u.data.isEqual(c.data)?h!==d&&(n.track({type:3,doc:c}),f=!0):this.ru(u,c)||(n.track({type:2,doc:c}),f=!0,(o&&this.Za(c,o)>0||l&&0>this.Za(c,l))&&(a=!0)):!u&&c?(n.track({type:0,doc:c}),f=!0):u&&!c&&(n.track({type:1,doc:u}),f=!0,(o||l)&&(a=!0)),f&&(c?(s=s.add(c),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))}),null!==this.query.limit)for(;s.size>this.query.limit;){let e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{Xa:s,nu:n,Cs:a,mutatedKeys:i}}ru(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){let i=this.Xa;this.Xa=e.Xa,this.mutatedKeys=e.mutatedKeys;let s=e.nu.wa();s.sort((e,t)=>(function(e,t){let n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return S(20277,{Vt:e})}};return n(e)-n(t)})(e.type,t.type)||this.Za(e.doc,t.doc)),this.iu(n),r=null!=r&&r;let a=t&&!r?this.su():[],o=0===this.Ya.size&&this.current&&!r?1:0,l=o!==this.Ja;return(this.Ja=o,0!==s.length||l)?{snapshot:new on(this.query,e.Xa,i,s,e.mutatedKeys,0===o,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),ou:a}:{ou:a}}Fa(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Xa:this.Xa,nu:new ot,mutatedKeys:this.mutatedKeys,Cs:!1},!1)):{ou:[]}}_u(e){return!this.Ha.has(e)&&!!this.Xa.has(e)&&!this.Xa.get(e).hasLocalMutations}iu(e){e&&(e.addedDocuments.forEach(e=>this.Ha=this.Ha.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Ha=this.Ha.delete(e)),this.current=e.current)}su(){if(!this.current)return[];let e=this.Ya;this.Ya=ro(),this.Xa.forEach(e=>{this._u(e.key)&&(this.Ya=this.Ya.add(e.key))});let t=[];return e.forEach(e=>{this.Ya.has(e)||t.push(new oy(e))}),this.Ya.forEach(n=>{e.has(n)||t.push(new op(n))}),t}au(e){this.Ha=e.$s,this.Ya=ro();let t=this.tu(e.documents);return this.applyChanges(t,!0)}uu(){return on.fromInitialDocuments(this.query,this.Xa,this.mutatedKeys,0===this.Ja,this.hasCachedResults)}}let ov="SyncEngine";class oI{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class o_{constructor(e){this.key=e,this.cu=!1}}class ob{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedCl
7ientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.lu={},this.hu=new n7(e=>n4(e),n5),this.Pu=new Map,this.Tu=new Set,this.Iu=new tR(et.comparator),this.Eu=new Map,this.du=new sk,this.Au={},this.Ru=new Map,this.Vu=sl.lr(),this.onlineState="Unknown",this.mu=void 0}get isPrimaryClient(){return!0===this.mu}}async function oT(e,t,n=!0){let r,i=o0(e),s=i.hu.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),r=s.view.uu()):r=await ox(i,t,n,!0),r}async function oE(e,t){let n=o0(e);await ox(n,t,!0,!1)}async function ox(e,t,n,r){let i,s=await s0(e.localStore,nX(t)),a=s.targetId,o=e.sharedClientState.addLocalQueryTarget(a,n);return r&&(i=await oS(e,t,a,"current"===o,s.resumeToken)),e.isPrimaryClient&&n&&aP(e.remoteStore,s),i}async function oS(e,t,n,r,i){e.fu=(t,n,r)=>(async function(e,t,n,r){let i=t.view.tu(n);i.Cs&&(i=await s2(e.localStore,t.query,!1).then(({documents:e})=>t.view.tu(e,i)));let s=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s,a);return oU(e,t.targetId,o.ou),o.snapshot})(e,t,n,r);let s=await s2(e.localStore,t,!0),a=new ow(t,s.$s),o=a.tu(s.documents),l=rJ.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);oU(e,n,u.ou);let c=new oI(t,n,a);return e.hu.set(t,c),e.Pu.has(n)?e.Pu.get(n).push(t):e.Pu.set(n,[t]),u.snapshot}async function oC(e,t,n){let r=e.hu.get(t),i=e.Pu.get(r.targetId);if(i.length>1)return e.Pu.set(r.targetId,i.filter(e=>!n5(e,t))),void e.hu.delete(t);e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(r.targetId),e.sharedClientState.isActiveQueryTarget(r.targetId)||await s1(e.localStore,r.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(r.targetId),n&&aq(e.remoteStore,r.targetId),oP(e,r.targetId)}).catch(em)):(oP(e,r.targetId),await s1(e.localStore,r.targetId,!0))}async function oD(e,t){let n=e.hu.get(t),r=e.Pu.get(n.targetId);e.isPrimaryClient&&1===r.length&&(e.sharedClientState.removeLocalQueryTarget(n.targetId),aq(e.remoteStore,n.targetId))}async function ok(e,t,n){let r=o1(e);try{var i;let e,s=await function(e,t){let n,r,i=W.now(),s=t.reduce((e,t)=>e.add(t.key),ro());return e.persistence.runTransaction("Locally write mutations","readwrite",a=>{let o=re,l=ro();return e.Bs.getEntries(a,s).next(e=>{(o=e).forEach((e,t)=>{t.isValidDocument()||(l=l.add(e))})}).next(()=>e.localDocuments.getOverlayedDocuments(a,o)).next(r=>{n=r;let s=[];for(let e of t){let t=function(e,t){let n=null;for(let r of e.fieldTransforms){let e=t.data.field(r.field),i=rf(r.transform,e||null);null!=i&&(null===n&&(n=ny.empty()),n.set(r.field,i))}return n||null}(e,n.get(e.key).overlayedDocument);null!=t&&s.push(new rN(e.key,t,function e(t){let n=[];return tk(t.fields,(t,r)=>{let i=new ee([t]);if(nc(r)){let t=e(r.mapValue).fields;if(0===t.length)n.push(i);else for(let e of t)n.push(i.child(e))}else n.push(i)}),new tP(n)}(t.value.mapValue),rE.exists(!0)))}return e.mutationQueue.addMutationBatch(a,i,s,t)}).next(t=>{r=t;let i=t.applyToLocalDocumentSet(n,l);return e.documentOverlayCache.saveOverlays(a,t.batchId,i)})}).then(()=>({batchId:r.batchId,changes:rr(n)}))}(r.localStore,t);r.sharedClientState.addPendingMutation(s.batchId),i=s.batchId,(e=r.Au[r.currentUser.toKey()])||(e=new tR(K)),e=e.insert(i,n),r.Au[r.currentUser.toKey()]=e,await oz(r,s.changes),await aJ(r.remoteStore)}catch(t){let e=a7(t,"Failed to persist write");n.reject(e)}}async function oA(e,t){try{let n=await function(e,t){let n=t.snapshotVersion,r=e.xs;return e.persistence.runTransaction("Apply remote event","readwrite-primary",i=>{let s=e.Bs.newChangeBuffer({trackRemovals:!0});r=e.xs;let a=[];
7t.targetChanges.forEach((s,o)=>{var l;let u=r.get(o);if(!u)return;a.push(e.Ti.removeMatchingKeys(i,s.removedDocuments,o).next(()=>e.Ti.addMatchingKeys(i,s.addedDocuments,o)));let c=u.withSequenceNumber(i.currentSequenceNumber);null!==t.targetMismatches.get(o)?c=c.withResumeToken(tB.EMPTY_BYTE_STRING,H.min()).withLastLimboFreeSnapshotVersion(H.min()):s.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(s.resumeToken,n)),r=r.insert(o,c),l=c,(0===u.resumeToken.approximateByteSize()||l.snapshotVersion.toMicroseconds()-u.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)&&a.push(e.Ti.updateTargetData(i,c))});let o=re,l=ro();if(t.documentUpdates.forEach(n=>{t.resolvedLimboDocuments.has(n)&&a.push(e.persistence.referenceDelegate.updateLimboDocument(i,n))}),a.push(sZ(i,s,t.documentUpdates).next(e=>{o=e.qs,l=e.Qs})),!n.isEqual(H.min())){let t=e.Ti.getLastRemoteSnapshotVersion(i).next(t=>e.Ti.setTargetsMetadata(i,i.currentSequenceNumber,n));a.push(t)}return eg.waitFor(a).next(()=>s.apply(i)).next(()=>e.localDocuments.getLocalViewOfDocuments(i,o,l)).next(()=>o)}).then(t=>(e.xs=r,t))}(e.localStore,t);
7t.targetChanges.forEach((t,n)=>{let r=e.Eu.get(n);r&&(D(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?r.cu=!0:t.modifiedDocuments.size>0?D(r.cu,14607):t.removedDocuments.size>0&&(D(r.cu,42227),r.cu=!1))}),await oz(e,n,t)}catch(e){await em(e)}}function oN(e,t,n){var r;if(e.isPrimaryClient&&0===n||!e.isPrimaryClient&&1===n){let n,i=[];e.hu.forEach((e,n)=>{let r=n.view.Fa(t);r.snapshot&&i.push(r.snapshot)}),(r=e.eventManager).onlineState=t,n=!1,r.queries.forEach((e,r)=>{for(let e of r.Sa)e.Fa(t)&&(n=!0)}),n&&oc(r),i.length&&e.lu.Y_(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function oR(e,t,n){e.sharedClientState.updateQueryState(t,"rejected",n);let r=e.Eu.get(t),i=r&&r.key;if(i){let n=new tR(et.comparator);n=n.insert(i,nw.newNoDocument(i,H.min()));let r=ro().add(i),s=new rY(H.min(),new Map,new tR(K),n,r);await oA(e,s),e.Iu=e.Iu.remove(i),e.Eu.delete(t),oB(e)}else await s1(e.localStore,t,!1).then(()=>oP(e,t,n)).catch(em)}async function oM(e,t){var n;let r=t.batch.batchId;try{let i=await (n=e.localStore,n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let r=t.batch.keys(),i=n.Bs.newChangeBuffer({trackRemovals:!0});return(function(e,t,n,r){let i=n.batch,s=i.keys(),a=eg.resolve();return s.forEach(e=>{a=a.next(()=>r.getEntry(t,e)).next(t=>{let s=n.docVersions.get(e);D(null!==s,48541),0>t.version.compareTo(s)&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))})}),a.next(()=>e.mutationQueue.removeMutationBatch(t,i))})(n,e,t,i).next(()=>i.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=ro();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t))).next(()=>n.localDocuments.getDocuments(e,r))}));oL(e,r,null),oF(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await oz(e,i)}catch(e){await em(e)}}async function oV(e,t,n){var r;try{let i=await (r=e.localStore,r.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let n;return r.mutationQueue.lookupMutationBatch(e,t).next(t=>(D(null!==t,37113),n=t.keys(),r.mutationQueue.removeMutationBatch(e,t))).next(()=>r.mutationQueue.performConsistencyCheck(e)).next(()=>r.documentOverlayCache.removeOverlaysForBatchId(e,n,t)).next(()=>r.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,n)).next(()=>r.localDocuments.getDocuments(e,n))}));oL(e,t,n),oF(e,t),e.sharedClientState.updateMutationState(t,"rejected",n),await oz(e,i)}catch(e){await em(e)}}async function oO(e,t){var n;aK(e.remoteStore)||b(ov,"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{let r=await (n=e.localStore).persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>n.mutationQueue.getHighestUnacknowledgedBatchId(e));if(-1===r)return void t.resolve();let i=e.Ru.get(r)||[];i.push(t),e.Ru.set(r,i)}catch(n){let e=a7(n,"Initialization of waitForPendingWrites() operation failed");t.reject(e)}}function oF(e,t){(e.Ru.get(t)||[]).forEach(e=>{e.resolve()}),e.Ru.delete(t)}function oL(e,t,n){let r=e.Au[e.currentUser.toKey()];if(r){let i=r.get(t);i&&(n?i.reject(n):i.resolve(),r=r.remove(t)),e.Au[e.currentUser.toKey()]=r}}function oP(e,t,n=null){for(let r of(e.sharedClientState.removeLocalQueryTarget(t),e.Pu.get(t)))e.hu.delete(r),n&&e.lu.gu(r,n);e.Pu.delete(t),e.isPrimaryClient&&e.du.Hr(t).forEach(t=>{e.du.containsKey(t)||oq(e,t)})}function oq(e,t){e.Tu.delete(t.path.canonicalString());let n=e.Iu.get(t);null!==n&&(aq(e.remoteStore,n),e.Iu=e.Iu.remove(t),e.Eu.delete(n),oB(e))}function oU(e,t,n){for(let r of n)r instanceof op?(e.du.addReference(r.key,t),function(e,t){let n=t.key,r=n.path.canonicalString();e.Iu.get(n)||e.Tu.has(r)||(b(ov,"New document in limbo: "+n),e.Tu.add(r),oB(e))}(e,r)):r instanceof oy?(b(ov,"Document no longer in limbo: "+r.key),e.du.removeReference(r.key,t),e.du.containsKey(r.key)||oq(e,r.key)):S(19791,{pu:r})}function oB(e){for(;e.Tu.size>0&&e.Iu.size<e.maxConcurrentLimboResolutions;){let t=e.Tu.values().next().value;e.Tu.delete(t);let n=new et(X.fromString(t)),r=e.Vu.next();e.Eu.set(r,new o_(n)),e.Iu=e.Iu.insert(n,r),aP(e.remoteStore,new ix(nX(nW(n.path)),r,"TargetPurposeLimboResolution",eA.le))}}async function oz(e,t,n){let r=[],i=[],s=[];e.hu.isEmpty()||(e.hu.forEach((a,o)=>{s.push(e.fu(o,t,n).then(t=>{var s;if((t||n)&&e.isPrimaryClient){let r=t?!t.fromCache:null==(s=null==n?void 0:n.targetChanges.get(o.targetId))?void 0:s.current;
7e.sharedClientState.updateQueryState(o.targetId,r?"current":"not-current")}if(t){r.push(t);let e=sQ.Rs(o.targetId,t);i.push(e)}}))}),await Promise.all(s),e.lu.Y_(r),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>eg.forEach(t,t=>eg.forEach(t.ds,r=>e.persistence.referenceDelegate.addReference(n,t.targetId,r)).next(()=>eg.forEach(t.As,r=>e.persistence.referenceDelegate.removeReference(n,t.targetId,r)))))}catch(e){if(!eb(e))throw e;b(sH,"Failed to update sequence numbers: "+e)}for(let n of t){let t=n.targetId;if(!n.fromCache){let n=e.xs.get(t),r=n.snapshotVersion,i=n.withLastLimboFreeSnapshotVersion(r);e.xs=e.xs.insert(t,i)}}}(e.localStore,i))}async function o$(e,t){if(!e.currentUser.isEqual(t)){b(ov,"User change. New user:",t.toKey());let n=await sJ(e.localStore,t);e.currentUser=t,e.Ru.forEach(e=>{e.forEach(e=>{e.reject(new N(A.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Ru.clear(),e.sharedClientState.handleUserChange(t,n.removedBatchIds,n.addedBatchIds),await oz(e,n.ks)}}function oK(e,t){let n=e.Eu.get(t);if(n&&n.cu)return ro().add(n.key);{let n=ro(),r=e.Pu.get(t);if(!r)return n;for(let t of r){let r=e.hu.get(t);n=n.unionWith(r.view.eu)}return n}}async function oG(e,t){let n=await s2(e.localStore,t.query,!0),r=t.view.au(n);return e.isPrimaryClient&&oU(e,t.targetId,r.ou),r}async function oQ(e,t){return s4(e.localStore,t).then(t=>oz(e,t))}async function oj(e,t,n,r){var i;let s=await function(e,t){let n=e.mutationQueue;return e.persistence.runTransaction("Lookup mutation documents","readonly",r=>n.tr(r,t).next(t=>t?e.localDocuments.getDocuments(r,t):eg.resolve(null)))}(e.localStore,t);null!==s?("pending"===n?await aJ(e.remoteStore):"acknowledged"===n||"rejected"===n?(oL(e,t,r||null),oF(e,t),i=e.localStore,i.mutationQueue.sr(t)):S(6720,"Unknown batchState",{yu:n}),await oz(e,s)):b(ov,"Cannot apply mutation batch with id: "+t)}async function oW(e,t){if(o0(e),o1(e),!0===t&&!0!==e.mu){let t=e.sharedClientState.getAllActiveQueryTargets(),n=await oH(e,t.toArray());for(let t of(e.mu=!0,await a6(e.remoteStore,!0),n))aP(e.remoteStore,t)}else if(!1===t&&!1!==e.mu){let t=[],n=Promise.resolve();e.Pu.forEach((r,i)=>{e.sharedClientState.isLocalQueryTarget(i)?t.push(i):n=n.then(()=>(oP(e,i),s1(e.localStore,i,!0))),aq(e.remoteStore,i)}),await n,await oH(e,t),e.Eu.forEach((t,n)=>{aq(e.remoteStore,n)}),e.du.Jr(),e.Eu=new Map,e.Iu=new tR(et.comparator),e.mu=!1,await a6(e.remoteStore,!1)}}async function oH(e,t,n){let r=[],i=[];for(let n of t){let t,s=e.Pu.get(n);if(s&&0!==s.length)for(let n of(t=await s0(e.localStore,nX(s[0])),s)){let t=e.hu.get(n),r=await oG(e,t);r.snapshot&&i.push(r.snapshot)}else{let r=await s5(e.localStore,n);t=await s0(e.localStore,r),await oS(e,oY(r),n,!1,t.resumeToken)}r.push(t)}return e.lu.Y_(i),r}function oY(e){var t,n,r,i,s;return t=e.path,n=e.collectionGroup,r=e.orderBy,i=e.filters,s=e.limit,new nj(t,n,r,i,s,"F",e.startAt,e.endAt)}function oJ(e){return e.localStore.persistence.Is()}async function oX(e,t,n,r){if(e.mu)return void b(ov,"Ignoring unexpected query state notification.");let i=e.Pu.get(t);if(i&&i.length>0)switch(n){case"current":case"not-current":{let r=await s4(e.localStore,n8(i[0])),s=rY.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,tB.EMPTY_BYTE_STRING);await oz(e,r,s);break}case"rejected":await s1(e.localStore,t,!0),oP(e,t,r);break;default:S(64155,n)}}async function oZ(e,t,n){let r=o0(e);if(r.mu){for(let e of t){if(r.Pu.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){b(ov,"Adding an already active target "+e);continue}let t=await s5(r.localStore,e),n=await s0(r.localStore,t);await oS(r,oY(t),n.targetId,!1,n.resumeToken),aP(r.remoteStore,n)}for(let e of n)r.Pu.has(e)&&await s1(r.localStore,e,!1).then(()=>{aq(r.remoteStore,e),oP(r,e)}).catch(em)}}function o0(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=oA.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=oK.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=oR.bind(null,e),e.lu.Y_=ol.bind(null,e.eventManager),e.lu.gu=ou.bind(null,e.eventManager),e}function o1(e){return e.remoteStore.remoteSyncer.applySuccessfulWrite=oM.bind(null,e),e.remoteStore.remoteSyncer.rejectFailedWrite=oV.bind(null,e),e}class o2{constructor(){this.kind="memory",this.synchronizeTabs=!1}
7async initialize(e){this.serializer=ax(e.databaseInfo.databaseId),this.sharedClientState=this.bu(e),this.persistence=this.Su(e),await this.persistence.start(),this.localStore=this.Du(e),this.gcScheduler=this.vu(e,this.localStore),this.indexBackfillerScheduler=this.Cu(e,this.localStore)}vu(e,t){return null}Cu(e,t){return null}Du(e){var t,n;return t=this.persistence,n=new sW,new sY(t,n,e.initialUser,this.serializer)}Su(e){return new sO(sL.fi,this.serializer)}bu(e){return new ah}async terminate(){var e,t;null==(e=this.gcScheduler)||e.stop(),null==(t=this.indexBackfillerScheduler)||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}o2.provider={build:()=>new o2};class o5 extends o2{constructor(e){super(),this.cacheSizeBytes=e}vu(e,t){return D(this.persistence.referenceDelegate instanceof sP,46915),new sm(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Su(e){let t=void 0!==this.cacheSizeBytes?sn.withCacheSize(this.cacheSizeBytes):sn.DEFAULT;return new sO(e=>sP.fi(e,t),this.serializer)}}class o4 extends o2{constructor(e,t,n){super(),this.Fu=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Fu.initialize(this,e),await o1(this.Fu.syncEngine),await aJ(this.Fu.remoteStore),await this.persistence.Ji(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve()))}Du(e){var t,n;return t=this.persistence,n=new sW,new sY(t,n,e.initialUser,this.serializer)}vu(e,t){return new sm(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Cu(e,t){let n=new ek(t,this.persistence);return new eD(e.asyncQueue,n)}Su(e){let t=sG(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?sn.withCacheSize(this.cacheSizeBytes):sn.DEFAULT;return new sK(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,aT(),aE(),this.serializer,this.sharedClientState,!!this.forceOwnership)}bu(e){return new ah}}class o6 extends o4{constructor(e,t){super(e,t,!1),this.Fu=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);let t=this.Fu.syncEngine;this.sharedClientState instanceof ac&&(this.sharedClientState.syncEngine={Co:oj.bind(null,t),Fo:oX.bind(null,t),Mo:oZ.bind(null,t),Is:oJ.bind(null,t),vo:oQ.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Ji(async e=>{await oW(this.Fu.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())})}bu(e){let t=aT();if(!ac.C(t))throw new N(A.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");let n=sG(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new ac(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class o3{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>oN(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=o$.bind(null,this.syncEngine),await a6(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new oi}createDatastore(e){var t;let n=ax(e.databaseInfo.databaseId),r=new ab(e.databaseInfo);return t=e.authCredentials,new aR(t,e.appCheckCredentials,r,n)}createRemoteStore(e){var t,n;return t=this.localStore,n=this.datastore,new aO(t,n,e.asyncQueue,e=>oN(this.syncEngine,e,0),am.C()?new am:new ad)}createSyncEngine(e,t){return function(e,t,n,r,i,s,a){let o=new ob(e,t,n,r,i,s);return a&&(o.mu=!0),o}(this.localStore,this.remoteStore,this.eventManager,this.sharedCl
7ientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){b(aV,"RemoteStore shutting down."),e.da.add(5),await aL(e),e.Ra.shutdown(),e.Va.set("Unknown")}(this.remoteStore),null==(e=this.datastore)||e.terminate(),null==(t=this.eventManager)||t.terminate()}}function o8(e,t=10240){let n=0;return{async read(){if(n<e.byteLength){let r={value:e.slice(n,n+t),done:!1};return n+=t,r}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}o3.provider={build:()=>new o3};class o9{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Mu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Mu(this.observer.error,e):T("Uncaught Error in snapshot listener:",e.toString()))}xu(){this.muted=!0}Mu(e,t){setTimeout(()=>{this.muted||e(t)},0)}}class o7{constructor(e,t){this.Ou=e,this.serializer=t,this.metadata=new R,this.buffer=new Uint8Array,this.Nu=new TextDecoder("utf-8"),this.Bu().then(e=>{e&&e.Ua()?this.metadata.resolve(e.$a.metadata):this.metadata.reject(Error(`The first element of the bundle is not a metadata, it is
8             ${JSON.stringify(null==e?void 0:e.$a)}`))},e=>this.metadata.reject(e))}close(){return this.Ou.cancel()}async getMetadata(){return this.metadata.promise}async wu(){return await this.getMetadata(),this.Bu()}async Bu(){let e=await this.Lu();if(null===e)return null;let t=this.Nu.decode(e),n=Number(t);return isNaN(n)&&this.ku(`length string (${t}) is not valid number`),new od(JSON.parse(await this.qu(n)),e.length+n)}Qu(){return this.buffer.findIndex(e=>123===e)}async Lu(){for(;0>this.Qu()&&!await this.$u(););if(0===this.buffer.length)return null;let e=this.Qu();e<0&&this.ku("Reached the end of bundle when a length string is expected.");let t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async qu(e){for(;this.buffer.length<e;)await this.$u()&&this.ku("Reached the end of bundle when more is expected.");let t=this.Nu.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}ku(e){throw this.Ou.cancel(),Error(`Invalid bundle format: ${e}`)}async $u(){let e=await this.Ou.read();if(!e.done){let t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class le{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new N(A.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;let t=await async function(e,t){let n={documents:t.map(t=>io(e.serializer,t))},r=await e.Yo("BatchGetDocuments",e.serializer.databaseId,X.emptyPath(),n,t.length),i=new Map;r.forEach(t=>{var n;let r=(n=e.serializer,"found"in t?function(e,t){D(!!t.found,43571),t.found.name,t.found.updateTime;let n=il(e,t.found.name),r=ir(t.found.updateTime),i=t.found.createTime?ir(t.found.createTime):H.min(),s=new ny({mapValue:{fields:t.found.fields}});return nw.newFoundDocument(n,r,i,s)}(n,t):"missing"in t?function(e,t){D(!!t.missing,3894),D(!!t.readTime,22933);let n=il(e,t.missing),r=ir(t.readTime);return nw.newNoDocument(n,r)}(n,t):S(7234,{result:t}));i.set(r.key.toString(),r)});let s=[];return t.forEach(e=>{let t=i.get(e.toString());D(!!t,55234,{key:e}),s.push(t)}),s}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new rO(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;let e=this.readVersions;this.mutations.forEach(t=>{e.delete(t.key.toString())}),e.forEach((e,t)=>{let n=et.fromPath(t);
8this.mutations.push(new rF(n,this.precondition(n)))}),await async function(e,t){let n={writes:t.map(t=>ip(e.serializer,t))};await e.zo("Commit",e.serializer.databaseId,X.emptyPath(),n)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw S(50498,{Uu:e.constructor.name});t=H.min()}let n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new N(A.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){let t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(H.min())?rE.exists(!1):rE.updateTime(t):rE.none()}preconditionForUpdate(e){let t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(H.min()))throw new N(A.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return rE.updateTime(t)}return rE.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class lt{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.Ku=n.maxAttempts,this.x_=new aS(this.asyncQueue,"transaction_retry")}Wu(){this.Ku-=1,this.Gu()}Gu(){this.x_.y_(async()=>{let e=new le(this.datastore),t=this.zu(e);t&&t.then(t=>{this.asyncQueue.enqueueAndForget(()=>e.commit().then(()=>{this.deferred.resolve(t)}).catch(e=>{this.ju(e)}))}).catch(e=>{this.ju(e)})})}zu(e){try{let t=this.updateFunction(e);return!eN(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}ju(e){this.Ku>0&&this.Hu(e)?(this.Ku-=1,this.asyncQueue.enqueueAndForget(()=>(this.Gu(),Promise.resolve()))):this.deferred.reject(e)}Hu(e){if("FirebaseError"===e.name){let t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!rz(t)}return!1}}let ln="FirestoreClient";class lr{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=y.UNAUTHENTICATED,this.clientId=$.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,async e=>{b(ln,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(b(ln,"Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();let e=new R;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(n){let t=a7(n,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function li(e,t){e.asyncQueue.verifyOperationInProgress(),b(ln,"Initializing OfflineComponentProvider");let n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await sJ(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function ls(e,t){e.asyncQueue.verifyOperationInProgress();let n=await la(e);b(ln,"Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener(e=>a4(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,n)=>a4(t.remoteStore,n)),e._onlineComponents=t}async function la(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){b(ln,"Using user provided OfflineComponentProvider");try{await li(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===A.FAILED_PRECONDITION||t.code===A.UNIMPLEMENT
8ED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code))throw t;E("Error using user provided cache. Falling back to memory cache: "+t),await li(e,new o2)}}else b(ln,"Using default OfflineComponentProvider"),await li(e,new o5(void 0));return e._offlineComponents}async function lo(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(b(ln,"Using user provided OnlineComponentProvider"),await ls(e,e._uninitializedComponentsProvider._online)):(b(ln,"Using default OnlineComponentProvider"),await ls(e,new o3))),e._onlineComponents}function ll(e){return la(e).then(e=>e.persistence)}function lu(e){return la(e).then(e=>e.localStore)}function lc(e){return lo(e).then(e=>e.remoteStore)}function lh(e){return lo(e).then(e=>e.syncEngine)}function ld(e){return lo(e).then(e=>e.datastore)}async function lf(e){let t=await lo(e),n=t.eventManager;return n.onListen=oT.bind(null,t.syncEngine),n.onUnlisten=oC.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=oE.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=oD.bind(null,t.syncEngine),n}function lm(e,t,n={}){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,i){let s=new o9({next:o=>{s.xu(),t.enqueueAndForget(()=>oo(e,a));let l=o.docs.has(n);!l&&o.fromCache?i.reject(new N(A.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&o.fromCache&&r&&"server"===r.source?i.reject(new N(A.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):i.resolve(o)},error:e=>i.reject(e)}),a=new oh(nW(n.path),s,{includeMetadataChanges:!0,Qa:!0});return oa(e,a)})(await lf(e),e.asyncQueue,t,n,r)),r.promise}function lg(e,t,n={}){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>(function(e,t,n,r,i){let s=new o9({next:n=>{s.xu(),t.enqueueAndForget(()=>oo(e,a)),n.fromCache&&"server"===r.source?i.reject(new N(A.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(n)},error:e=>i.reject(e)}),a=new oh(n,s,{includeMetadataChanges:!0,Qa:!0});return oa(e,a)})(await lf(e),e.asyncQueue,t,n,r)),r.promise}function lp(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let ly=new Map;function lw(e,t,n){if(!n)throw new N(A.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function lv(e,t,n,r){if(!0===t&&!0===r)throw new N(A.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function lI(e){if(!et.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function l_(e){if(et.isDocumentKey(e))throw new N(A.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function lb(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{var t;let n=(t=e).constructor?t.constructor.name:null;return n?`a custom ${n} object`:"an object"}}return"function"==typeof e?"a function":S(12329,{type:typeof e})}function lT(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new N(A.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let n=lb(e);throw new N(A.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function lE(e,t){if(t<=0)throw new N(A.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}let lx="firestore.googleapis.com";class lS{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new N(A.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=lx,this.ssl=!0}else this.host=e.host,this.ssl=null==(t=e.ssl)||t;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=0x2800000;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new N(A.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}lv("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=lp(null!=(n=e.experimentalLongPollingOptions)?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new N(A.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){var t,n;return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,n=e.experimentalLongPollingOptions,t.timeoutSeconds===n.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class lC{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new lS({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new N(A.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new N(A.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new lS(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new V;switch(e.type){case"firstParty":return new P(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new N(A.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
8d credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){let t=ly.get(e);t&&(b("ComponentProvider","Removing Datastore"),ly.delete(e),t.terminate())}(this),Promise.resolve()}}function lD(e,t,n,r={}){var i;e=lT(e,lC);let s=(0,c.zJ)(t),a=e._getSettings(),o=Object.assign(Object.assign({},a),{emulatorOptions:e._getEmulatorOptions()}),l=`${t}:${n}`;s&&((0,c.gE)(`https://${l}`),(0,c.P1)("Firestore",!0)),a.host!==lx&&a.host!==l&&E("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let u=Object.assign(Object.assign({},a),{host:l,ssl:s,emulatorOptions:r});if(!(0,c.bD)(u,o)&&(e._setSettings(u),r.mockUserToken)){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=y.MOCK_USER;else{t=(0,c.Fy)(r.mockUserToken,null==(i=e._app)?void 0:i.options.projectId);let s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new N(A.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new y(s)}e._authCredentials=new O(new M(t,n))}}class lk{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new lk(this.firestore,e,this._query)}}class lA{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new lN(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new lA(this.firestore,e,this._key)}}class lN extends lk{constructor(e,t,n){super(e,t,nW(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new lA(this.firestore,null,new et(e))}withConverter(e){return new lN(this.firestore,e,this._path)}}function lR(e,t,...n){if(e=(0,c.Ku)(e),lw("collection","path",t),e instanceof lC){let r=X.fromString(t,...n);return l_(r),new lN(e,null,r)}{if(!(e instanceof lA||e instanceof lN))throw new N(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(X.fromString(t,...n));return l_(r),new lN(e.firestore,null,r)}}function lM(e,t){if(e=lT(e,lC),lw("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new N(A.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new lk(e,null,new nj(X.emptyPath(),t))}function lV(e,t,...n){if(e=(0,c.Ku)(e),1==arguments.length&&(t=$.newId()),lw("doc","path",t),e instanceof lC){let r=X.fromString(t,...n);return lI(r),new lA(e,null,new et(r))}{if(!(e instanceof lA||e instanceof lN))throw new N(A.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let r=e._path.child(X.fromString(t,...n));return lI(r),new lA(e.firestore,e instanceof lN?e.converter:null,new et(r))}}function lO(e,t){return e=(0,c.Ku)(e),t=(0,c.Ku)(t),(e instanceof lA||e instanceof lN)&&(t instanceof lA||t instanceof lN)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function lF(e,t){return e=(0,c.Ku)(e),t=(0,c.Ku)(t),e instanceof lk&&t instanceof lk&&e.firestore===t.firestore&&n5(e._query,t._query)&&e.converter===t.converter}let lL="AsyncQueue";class lP{constructor(e=Promise.resolve()){this.Ju=[],this.Yu=!1,this.Zu=[],this.Xu=null,this.ec=!1,this.tc=!1,this.nc=[],this.x_=new aS(this,"async_queue_retry"),this.rc=()=>{let e=aE();e&&b(lL,"Visibility state changed to "+e.visibilityState),this.x_.b_()},this.sc=e;let t=aE();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.rc)}get isShuttingDown(){return this.Yu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.oc(),this._c(e)}enterRestrictedMode(e){if(!this.Yu){this.Yu=!0,this.tc=e||!1;let t=aE();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.rc)}}enqueue(e){if(this.oc(),this.Yu)return new Promise(()=>{});let t=new R;return this._c(()=>this.Yu&&this.tc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Ju.push(e),this.ac()))}async ac(){if(0!==this.Ju.length){try{await this.Ju[0](),this.Ju.shift(),this.x_.reset()}catch(e){if(!eb(e))throw e;b(lL,"Operation failed with retryable error: "+e)}this.Ju.length>0&&this.x_.y_(()=>this.ac())}}_c(e){let t=this.sc.then(()=>
8(this.ec=!0,e().catch(e=>{throw this.Xu=e,this.ec=!1,T("INTERNAL UNHANDLED ERROR: ",lq(e)),e}).then(e=>(this.ec=!1,e))));return this.sc=t,t}enqueueAfterDelay(e,t,n){this.oc(),this.nc.indexOf(e)>-1&&(t=0);let r=a9.createAndSchedule(this,e,t,n,e=>this.uc(e));return this.Zu.push(r),r}oc(){this.Xu&&S(47125,{cc:lq(this.Xu)})}verifyOperationInProgress(){}async lc(){let e;do e=this.sc,await e;while(e!==this.sc)}hc(e){for(let t of this.Zu)if(t.timerId===e)return!0;return!1}Pc(e){return this.lc().then(()=>{for(let t of(this.Zu.sort((e,t)=>e.targetTimeMs-t.targetTimeMs),this.Zu))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.lc()})}Tc(e){this.nc.push(e)}uc(e){let t=this.Zu.indexOf(e);this.Zu.splice(t,1)}}function lq(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}function lU(e){if("object"!=typeof e||null===e)return!1;for(let t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}class lB{constructor(){this._progressObserver={},this._taskCompletionResolver=new R,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}let lz=-1;class l$ extends lC{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new lP,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new lP(e),this._firestoreClient=void 0,await e}}}function lK(e,t,n){n||(n=t0);let r=(0,o.j6)(e,"firestore");if(r.isInitialized(n)){let e=r.getImmediate({identifier:n}),i=r.getOptions(n);if((0,c.bD)(i,t))return e;throw new N(A.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&void 0!==t.localCache)throw new N(A.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new N(A.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return t.host&&(0,c.zJ)(t.host)&&(0,c.gE)(t.host),r.initialize({options:t,instanceIdentifier:n})}function lG(e,t){let n="object"==typeof e?e:(0,o.Sx)(),r="string"==typeof e?e:t||t0,i=(0,o.j6)(n,"firestore").getImmediate({identifier:r});if(!i._initialized){let e=(0,c.yU)("firestore");e&&lD(i,...e)}return i}function lQ(e){if(e._terminated)throw new N(A.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||lj(e),e._firestoreClient}function lj(e){var t,n,r,i,s;let a=e._freezeSettings(),o=(i=e._databaseId,s=(null==(t=e._app)?void 0:t.options.appId)||"",new tZ(i,s,e._persistenceKey,a.host,a.ssl,a.experimentalForceLongPolling,a.experimentalAutoDetectLongPolling,lp(a.experimentalLongPollingOptions),a.useFetchStreams,a.isUsingEmulator));e._componentsProvider||(null==(n=a.localCache)?void 0:n._offlineComponentProvider)&&(null==(r=a.localCache)?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:a.localCache._offlineComponentProvider,_online:a.localCache._onlineComponentProvider}),e._firestoreClient=new lr(e._authCredentials,e._appCheckCredentials,e._queue,o,e._componentsProvider&&function(e){let t=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(t),_online:t}}(e._componentsProvider))}function lW(e,t){E("enableIndexedDbPersistence() will be deprecated 
8in the future, you can use `FirestoreSettings.cache` instead.");let n=e._freezeSettings();return lY(e,o3.provider,{build:e=>new o4(e,n.cacheSizeBytes,null==t?void 0:t.forceOwnership)}),Promise.resolve()}async function lH(e){E("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");let t=e._freezeSettings();lY(e,o3.provider,{build:e=>new o6(e,t.cacheSizeBytes)})}function lY(e,t,n){if((e=lT(e,l$))._firestoreClient||e._terminated)throw new N(A.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new N(A.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:n},lj(e)}function lJ(e){if(e._initialized&&!e._terminated)throw new N(A.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");let t=new R;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!ew.C())return Promise.resolve();await ew.delete(e+s$)}(sG(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}function lX(e){var t=lQ(e=lT(e,l$));let n=new R;return t.asyncQueue.enqueueAndForget(async()=>oO(await lh(t),n)),n.promise}function lZ(e){var t;return(t=lQ(e=lT(e,l$))).asyncQueue.enqueue(async()=>{let e=await ll(t),n=await lc(t);return e.setNetworkEnabled(!0),n.da.delete(0),aF(n)})}function l0(e){var t;return(t=lQ(e=lT(e,l$))).asyncQueue.enqueue(async()=>{let e=await ll(t),n=await lc(t);return e.setNetworkEnabled(!1),async function(e){e.da.add(0),await aL(e),e.Va.set("Offline")}(n)})}function l1(e){return(0,o.Us)(e.app,"firestore",e._databaseId.database),e._delete()}function l2(e,t){let n=lQ(e=lT(e,l$)),r=new lB;return function(e,t,n,r){var i;let s=(i=ax(t),new o7(function(e,t){if(e instanceof Uint8Array)return o8(e,void 0);if(e instanceof ArrayBuffer)return o8(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}("string"==typeof n?z().encode(n):n),i));e.asyncQueue.enqueueAndForget(async()=>{var t;(async function(e,t,n){try{var r;let i=await t.getMetadata();if(await function(e,t){let n=ir(t.createTime);return e.persistence.runTransaction("hasNewerBundle","readonly",n=>e.Ei.getBundleMetadata(n,t.id)).then(e=>!!e&&e.createTime.compareTo(n)>=0)}(e.localStore,i))return await t.close(),n._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes}),Promise.resolve(new Set);n._updateProgress(og(i));let s=new om(i,e.localStore,t.serializer),a=await t.wu();for(;a;){let e=await s.Wa(a);e&&n._updateProgress(e),a=await t.wu()}let o=await s.complete();return await oz(e,o.ja,void 0),await (r=e.localStore,r.persistence.runTransaction("Save bundle","readwrite",e=>r.Ei.saveBundleMetadata(e,i))),n._completeWith(o.progress),Promise.resolve(o.za)}catch(e){return E(ov,`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(t=await lh(e),s,r).then(e=>{t.sharedClientState.notifyBundleLoaded(e)})})}(n,e._databaseId,t,r),r}function l5(e,t){var n;return(n=lQ(e=lT(e,l$)),n.asyncQueue.enqueue(async()=>{var e;return e=await lu(n),e.persistence.runTransaction("Get named query","readonly",n=>e.Ei.getNamedQuery(n,t))})).then(t=>t?new lk(e,null,t.query):null)}class l4{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class l6{constructor(e,t,n){this._userDataWriter=t,this._data=n,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class l3{constructor(e){this._byteString=e}static fromBase64String(e){try{return new l3(tB.fromBase64String(e))}catch(e){throw new N(A.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new l3(tB.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class l8{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new N(A.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new ee(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}function l9(){return new l8(Y)}class l7{constructor(e){this._methodName=e}}class ue{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new N(A.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new N(A.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return K(this._lat,e._lat)||K(this._long,e._long)}}class ut{constructor(e){this._values=(e||[]).map(e=>e)}toArray(){return this._values.map(e=>e)}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}(this._values,e._values)}}let un=/^__.*__$/;class ur{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new rN(e,this.data,this.fieldMask,t,this.fieldTransforms):new rA(e,this.data,t,this.fieldTransforms)}}class ui{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new rN(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function us(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw S(40011,{Ic:e})}}class ua{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer
8=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Ec(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Ic(){return this.settings.Ic}dc(e){return new ua(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Ac(e){var t;let n=null==(t=this.path)?void 0:t.child(e),r=this.dc({path:n,Rc:!1});return r.Vc(e),r}mc(e){var t;let n=null==(t=this.path)?void 0:t.child(e),r=this.dc({path:n,Rc:!1});return r.Ec(),r}fc(e){return this.dc({path:void 0,Rc:!0})}gc(e){return uS(e,this.settings.methodName,this.settings.yc||!1,this.path,this.settings.wc)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}Ec(){if(this.path)for(let e=0;e<this.path.length;e++)this.Vc(this.path.get(e))}Vc(e){if(0===e.length)throw this.gc("Document fields must not be empty");if(us(this.Ic)&&un.test(e))throw this.gc('Document fields cannot begin and end with "__"')}}class uo{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||ax(e)}bc(e,t,n,r=!1){return new ua({Ic:e,methodName:t,wc:n,path:ee.emptyPath(),Rc:!1,yc:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ul(e){let t=e._freezeSettings(),n=ax(e._databaseId);return new uo(e._databaseId,!!t.ignoreUndefinedProperties,n)}function uu(e,t,n,r,i,s={}){let a,o,l=e.bc(s.merge||s.mergeFields?2:0,t,n,i);ub("Data must be an object, but it was:",l,r);let u=uI(r,l);if(s.merge)a=new tP(l.fieldMask),o=l.fieldTransforms;else if(s.mergeFields){let e=[];for(let r of s.mergeFields){let i=uT(t,r,n);if(!l.contains(i))throw new N(A.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);uC(e,i)||e.push(i)}a=new tP(e),o=l.fieldTransforms.filter(e=>a.covers(e.field))}else a=null,o=l.fieldTransforms;return new ur(new ny(u),a,o)}class uc extends l7{_toFieldTransform(e){if(2!==e.Ic)throw 1===e.Ic?e.gc(`${this._methodName}() can only appear at the top level of your update data`):e.gc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof uc}}function uh(e,t,n){return new ua({Ic:3,wc:t.settings.wc,methodName:e._methodName,Rc:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class ud extends l7{_toFieldTransform(e){return new rb(e.path,new rm)}isEqual(e){return e instanceof ud}}class uf extends l7{constructor(e,t){super(e),this.Sc=t}_toFieldTransform(e){let t=uh(this,e,!0),n=new rg(this.Sc.map(e=>uv(e,t)));return new rb(e.path,n)}isEqual(e){return e instanceof uf&&(0,c.bD)(this.Sc,e.Sc)}}class um extends l7{constructor(e,t){super(e),this.Sc=t}_toFieldTransform(e){let t=uh(this,e,!0),n=new ry(this.Sc.map(e=>uv(e,t)));return new rb(e.path,n)}isEqual(e){return e instanceof um&&(0,c.bD)(this.Sc,e.Sc)}}class ug extends l7{constructor(e,t){super(e),this.Dc=t}_toFieldTransform(e){let t=new rv(e.serializer,rh(e.serializer,this.Dc));return new rb(e.path,t)}isEqual(e){return e instanceof ug&&this.Dc===e.Dc}}function up(e,t,n,r){let i=e.bc(1,t,n);ub("Data must be an object, but it was:",i,r);let s=[],a=ny.empty();return tk(r,(e,r)=>{let o=ux(t,e,n);r=(0,c.Ku)(r);let l=i.mc(o);if(r instanceof uc)s.push(o);else{let e=uv(r,l);null!=e&&(s.push(o),a.set(o,e))}}),new ui(a,new tP(s),i.fieldTransforms)}function uy(e,t,n,r,i,s){let a=e.bc(1,t,n),o=[uT(t,r,n)],l=[i];if(s.length%2!=0)throw new N(A.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)o.push(uT(t,s[e])),l.push(s[e+1]);let u=[],h=ny.empty();for(let e=o.length-1;e>=0;--e)if(!uC(u,o[e])){let t=o[e],n=l[e];n=(0,c.Ku)(n);let r=a.mc(t);if(n instanceof uc)u.push(t);else{let e=uv(n,r);null!=e&&(u.push(t),h.set(t,e))}}return new ui(h,new tP(u),a.fieldTransforms)}function uw(e,t,n,r=!1){return uv(n,e.bc(r?4:3,t))}function uv(e,t){if(u_(e=(0,c.Ku)(e)))return ub("Unsupported field value:",t,e),uI(e,t);if(e instanceof l7)return function(e,t){if(!us(t.Ic))throw t.gc(`${e._methodName}
8() can only be used with update() and set()`);if(!t.path)throw t.gc(`${e._methodName}() is not currently supported inside arrays`);let n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Rc&&4!==t.Ic)throw t.gc("Nested arrays are not supported");let n=[],r=0;for(let i of e){let e=uv(i,t.fc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}return function(e,t){if(null===(e=(0,c.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return rh(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let n=W.fromDate(e);return{timestampValue:ie(t.serializer,n)}}if(e instanceof W){let n=new W(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:ie(t.serializer,n)}}if(e instanceof ue)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof l3)return{bytesValue:it(t.serializer,e._byteString)};if(e instanceof lA){let n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.gc(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:ii(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof ut)return{mapValue:{fields:{[t2]:{stringValue:t6},[t3]:{arrayValue:{values:e.toArray().map(e=>{if("number"!=typeof e)throw t.gc("VectorValues must only contain numeric values.");return ru(t.serializer,e)})}}}}};throw t.gc(`Unsupported field value: ${lb(e)}`)}(e,t)}function uI(e,t){let n={};return tN(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):tk(e,(e,r)=>{let i=uv(r,t.Ac(e));null!=i&&(n[e]=i)}),{mapValue:{fields:n}}}function u_(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof W||e instanceof ue||e instanceof l3||e instanceof lA||e instanceof l7||e instanceof ut)}function ub(e,t,n){if(!u_(n)||"object"!=typeof n||null===n||Object.getPrototypeOf(n)!==Object.prototype&&null!==Object.getPrototypeOf(n)){let r=lb(n);throw"an object"===r?t.gc(e+" a custom object"):t.gc(e+" "+r)}}function uT(e,t,n){if((t=(0,c.Ku)(t))instanceof l8)return t._internalPath;if("string"==typeof t)return ux(e,t);throw uS("Field path arguments must be of type string or ",e,!1,void 0,n)}let uE=RegExp("[~\\*/\\[\\]]");function ux(e,t,n){if(t.search(uE)>=0)throw uS(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new l8(...t.split("."))._internalPath}catch(r){throw uS(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function uS(e,t,n,r,i){let s=r&&!r.isEmpty(),a=void 0!==i,o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=` in field ${r}`),a&&(l+=` in document ${i}`),l+=")"),new N(A.INVALID_ARGUMENT,o+e+l)}function uC(e,t){return e.some(e=>e.isEqual(t))}class uD{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new lA(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new uk(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){let t=this._document.data.field(uA("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class uk extends uD{data(){return super.data()}}function uA(e,t){return"string"==typeof t?ux(e,t):t instanceof l8?t._internalPath:t._delegate._internalPath}function uN(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new N(A.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class uR{}class uM extends uR{}function uV(e,t,...n){let r=[];for(let i of(t instanceof uR&&r.push(t),function(e){let t=e.filter(e=>e instanceof uL).length,n=e.filter(e=>e instanceof uO).length;if(t>1||t>0&&n>0)throw new N(A.INVALID_ARGUMENT,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(r=r.concat(n)),r))e=i._apply(e);return e}class uO extends uM{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new uO(e,t,n)}_apply(e){let t=this._parse(e);return u0(e._query,t),new lk(e.firestore,e.converter,n1(e._query,t))}_parse(e){let t=ul(e.firestore);return function(e,t,n,r,i,s,a){let o;
8if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new N(A.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){uZ(a,s);let t=[];for(let n of a)t.push(uX(r,e,n));o={arrayValue:{values:t}}}else o=uX(r,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||uZ(a,s),o=uw(n,t,a,"in"===s||"not-in"===s);return nE.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function uF(e,t,n){let r=uA("where",e);return uO._create(r,t,n)}class uL extends uR{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new uL(e,t)}_parse(e){let t=this._queryConstraints.map(t=>t._parse(e)).filter(e=>e.getFilters().length>0);return 1===t.length?t[0]:nx.create(t,this._getOperator())}_apply(e){let t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;for(let e of t.getFlattenedFilters())u0(n,e),n=n1(n,e)}(e._query,t),new lk(e.firestore,e.converter,n1(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function uP(...e){return e.forEach(e=>u1("or",e)),uL._create("or",e)}function uq(...e){return e.forEach(e=>u1("and",e)),uL._create("and",e)}class uU extends uM{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new uU(e,t)}_apply(e){let t=function(e,t,n){if(null!==e.startAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new N(A.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new nb(t,n)}(e._query,this._field,this._direction);return new lk(e.firestore,e.converter,function(e,t){let n=e.explicitOrderBy.concat([t]);return new nj(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}function uB(e,t="asc"){let n=uA("orderBy",e);return uU._create(n,t)}class uz extends uM{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new uz(e,t,n)}_apply(e){return new lk(e.firestore,e.converter,n2(e._query,this._limit,this._limitType))}}function u$(e){return lE("limit",e),uz._create("limit",e,"F")}function uK(e){return lE("limitToLast",e),uz._create("limitToLast",e,"L")}class uG extends uM{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new uG(e,t,n)}_apply(e){var t;let n=uJ(e,this.type,this._docOrFields,this._inclusive);return new lk(e.firestore,e.converter,(t=e._query,new nj(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,n,t.endAt)))}}function uQ(...e){return uG._create("startAt",e,!0)}function uj(...e){return uG._create("startAfter",e,!1)}class uW extends uM{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new uW(e,t,n)}_apply(e){var t;let n=uJ(e,this.type,this._docOrFields,this._inclusive);return new lk(e.firestore,e.converter,(t=e._query,new nj(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,n)))}}function uH(...e){return uW._create("endBefore",e,!1)}function uY(...e){return uW._create("endAt",e,!0)}function uJ(e,t,n,r){if(n[0]=(0,c.Ku)(n[0]),n[0]instanceof uD)return function(e,t,n,r,i){if(!r)throw new N(A.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);let s=[];for(let n of nJ(e))if(n.field.isKeyField())s.push(ns(t,r.key));else{let e=r.data.field(n.field);if(tY(e))throw new N(A.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){let e=n.field.canonicalString();throw new N(A.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new nv(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{let i=ul(e.firestore);return function(e,t,n,r,i,s){let a=e.explicitOrderBy;if(i.length>a.length)throw new N(A.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);let o=[];for(let s=0;s<i.length;s++){let l=i[s];
8if(a[s].field.isKeyField()){if("string"!=typeof l)throw new N(A.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!nY(e)&&-1!==l.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);let n=e.path.child(X.fromString(l));if(!et.isDocumentKey(n))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);let i=new et(n);o.push(ns(t,i))}else{let e=uw(n,r,l);o.push(e)}}return new nv(o,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function uX(e,t,n){if("string"==typeof(n=(0,c.Ku)(n))){if(""===n)throw new N(A.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!nY(t)&&-1!==n.indexOf("/"))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);let r=t.path.child(X.fromString(n));if(!et.isDocumentKey(r))throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return ns(e,new et(r))}if(n instanceof lA)return ns(e,n._key);throw new N(A.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${lb(n)}.`)}function uZ(e,t){if(!Array.isArray(e)||0===e.length)throw new N(A.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function u0(e,t){let n=function(e,t){for(let n of e)for(let e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(t.op));if(null!==n)throw n===t.op?new N(A.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new N(A.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function u1(e,t){if(!(t instanceof uO||t instanceof uL))throw new N(A.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class u2{convertValue(e,t="none"){switch(t9(e)){case 0:return null;case 1:return e.booleanValue;case 2:return tK(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(tG(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw S(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let n={};return tk(e,(e,r)=>{n[e]=this.convertValue(r,t)}),n}convertVectorValue(e){var t,n,r;return new ut(null==(r=null==(n=null==(t=e.fields)?void 0:t[t3].arrayValue)?void 0:n.values)?void 0:r.map(e=>tK(e.doubleValue)))}convertGeoPoint(e){return new ue(tK(e.latitude),tK(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let n=tJ(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(tX(e));default:return null}}convertTimestamp(e){let t=t$(e);return new W(t.seconds,t.nanos)}convertDocumentKey(e,t){let n=X.fromString(e);D(iE(n),9688,{name:e});let r=new t1(n.get(1),n.get(3)),i=new et(n.popFirst(5));return r.isEqual(t)||T(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function u5(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class u4 extends u2{constructor(e){super(),this.firestore=e}convertBytes(e){return new l3(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);
8return new lA(this.firestore,null,t)}}function u6(e){return new l4("sum",uT("sum",e))}function u3(e){return new l4("avg",uT("average",e))}function u8(){return new l4("count")}function u9(e,t){var n,r;return e instanceof l4&&t instanceof l4&&e.aggregateType===t.aggregateType&&(null==(n=e._internalFieldPath)?void 0:n.canonicalString())===(null==(r=t._internalFieldPath)?void 0:r.canonicalString())}function u7(e,t){return lF(e.query,t.query)&&(0,c.bD)(e.data(),t.data())}class ce{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class ct extends uD{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new cn(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){let n=this._document.data.field(uA("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class cn extends ct{data(e={}){return super.data(e)}}class cr{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new ce(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){let e=[];return this.forEach(t=>e.push(t)),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach(n=>{e.call(t,new cn(this._firestore,this._userDataWriter,n.key,n,new ce(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new N(A.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map(n=>{let r=new cn(e._firestore,e._userDataWriter,n.doc.key,n.doc,new ce(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}})}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(e=>t||3!==e.type).map(t=>{let r=new cn(e._firestore,e._userDataWriter,t.doc.key,t.doc,new ce(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(s=(n=n.add(t.doc)).indexOf(t.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return S(61501,{type:e})}}(t.type),doc:r,oldIndex:i,newIndex:s}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function ci(e,t){return e instanceof ct&&t instanceof ct?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof cr&&t instanceof cr&&e._firestore===t._firestore&&lF(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function cs(e){e=lT(e,lA);let t=lT(e.firestore,l$);return lm(lQ(t),e._key).then(n=>cv(t,e,n))}class ca extends u2{constructor(e){super(),this.firestore=e}convertBytes(e){return new l3(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new lA(this.firestore,null,t)}}function co(e){e=lT(e,lA);let t=lT(e.firestore,l$),n=lQ(t),r=new ca(t);return(function(e,t){let n=new R;return e.asyncQueue.enqueueAndForget(async()=>(async function(e,t,n){try{let r=await e.persistence.runTransaction("read document","readonly",n=>e.localDocuments.getDocument(n,t));r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new N(A.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(r){let e=a7(r,`Failed to get document '${t} from cache`);n.reject(e)}})(await lu(e),t,n)),n.promise})(n,e._key).then(n=>new ct(t,r,e._key,n,new ce(null!==n&&n.hasLocalMutations,!0),e.converter))}function cl(e){e=lT(e,lA);let t=lT(e.firestore,l$);return lm(lQ(t),e._key,{source:"server"}).then(n=>cv(t,e,n))}function cu(e){e=lT(e,lk);let t=lT(e.firestore,l$),n=lQ(t),r=new ca(t);return uN(e._query),lg(n,e._query).then(n=>new cr(t,r,e,n))}function cc(e){e=lT(e,lk);let t=lT(e.firestore,l$),n=lQ(t),r=new ca(t);return(function(e,t){let n=new R;return e.asyncQueue.enqueueAndForget(async()=>(async function(e,t,n){try{let r=await s2(e,t,!0),i=new ow(t,r.$s),s=i.tu(r.documents),a=i.applyChanges(s,
8!1);n.resolve(a.snapshot)}catch(r){let e=a7(r,`Failed to execute query '${t} against cache`);n.reject(e)}})(await lu(e),t,n)),n.promise})(n,e._query).then(n=>new cr(t,r,e,n))}function ch(e){e=lT(e,lk);let t=lT(e.firestore,l$),n=lQ(t),r=new ca(t);return lg(n,e._query,{source:"server"}).then(n=>new cr(t,r,e,n))}function cd(e,t,n){e=lT(e,lA);let r=lT(e.firestore,l$),i=u5(e.converter,t,n);return cw(r,[uu(ul(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,rE.none())])}function cf(e,t,n,...r){e=lT(e,lA);let i=lT(e.firestore,l$),s=ul(i);return cw(i,[("string"==typeof(t=(0,c.Ku)(t))||t instanceof l8?uy(s,"updateDoc",e._key,t,n,r):up(s,"updateDoc",e._key,t)).toMutation(e._key,rE.exists(!0))])}function cm(e){return cw(lT(e.firestore,l$),[new rO(e._key,rE.none())])}function cg(e,t){let n=lT(e.firestore,l$),r=lV(e),i=u5(e.converter,t);return cw(n,[uu(ul(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,rE.exists(!1))]).then(()=>r)}function cp(e,...t){let n,r,i;e=(0,c.Ku)(e);let s={includeMetadataChanges:!1,source:"default"},a=0;"object"!=typeof t[0]||lU(t[a])||(s=t[a],a++);let o={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(lU(t[a])){let e=t[a];t[a]=null==(l=e.next)?void 0:l.bind(e),t[a+1]=null==(u=e.error)?void 0:u.bind(e),t[a+2]=null==(h=e.complete)?void 0:h.bind(e)}if(e instanceof lA)r=lT(e.firestore,l$),i=nW(e._key.path),n={next:n=>{t[a]&&t[a](cv(r,e,n))},error:t[a+1],complete:t[a+2]};else{let s=lT(e,lk);r=lT(s.firestore,l$),i=s._query;let o=new ca(r);n={next:e=>{t[a]&&t[a](new cr(r,o,s,e))},error:t[a+1],complete:t[a+2]},uN(e._query)}var l,u,h,d=lQ(r),f=i;let m=new o9(n),g=new oh(f,m,o);return d.asyncQueue.enqueueAndForget(async()=>oa(await lf(d),g)),()=>{m.xu(),d.asyncQueue.enqueueAndForget(async()=>oo(await lf(d),g))}}function cy(e,t){return function(e,t){let n=new o9(t);return e.asyncQueue.enqueueAndForget(async()=>{var t;return t=await lf(e),void(t.Ca.add(n),n.next())}),()=>{n.xu(),e.asyncQueue.enqueueAndForget(async()=>{var t;return t=await lf(e),void t.Ca.delete(n)})}}(lQ(e=lT(e,l$)),lU(t)?t:{next:t})}function cw(e,t){var n=lQ(e);let r=new R;return n.asyncQueue.enqueueAndForget(async()=>ok(await lh(n),t,r)),r.promise}function cv(e,t,n){let r=n.docs.get(t._key),i=new ca(e);return new ct(e,i,t._key,r,new ce(n.hasPendingWrites,n.fromCache),t.converter)}function cI(e){return c_(e,{count:u8()})}function c_(e,t){let n=lT(e.firestore,l$),r=lQ(n),i=tA(t,(e,t)=>new rU(t,e.aggregateType,e._internalFieldPath));return(function(e,t,n){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>{try{let i=await ld(e);r.resolve(async function(e,t,n){var r;let{request:i,yt:s,parent:a}=iI(e.serializer,nZ(t),n);e.connection.Uo||delete i.parent;let o=(await e.Yo("RunAggregationQuery",e.serializer.databaseId,a,i,1)).filter(e=>!!e.result);D(1===o.length,64727);let l=null==(r=o[0].result)?void 0:r.aggregateFields;return Object.keys(l).reduce((e,t)=>(e[s[t]]=l[t],e),{})}(i,t,n))}catch(e){r.reject(e)}}),r.promise})(r,e._query,i).then(t=>new l6(e,new ca(n),t))}class cb{constructor(e){this.kind="memory",this._onlineComponentProvider=o3.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new o5(void 0)}}toJSON(){return{kind:this.kind}}}class cT{constructor(e){let t;this.kind="persistent",(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),t=e.tabManager):(t=cR(void 0))._initialize(e),this._onlineComponentProvider=t._onlineComponentProvider,this._offlineComponentProvider=t._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class cE{constructor(){this.kind="memoryEager",this._offlineComponentProvider=o2.provider}toJSON(){return{kind:this.kind}}}class cx{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new o5(e)}}toJSON(){return{kind:this.kind}}}function cS(){return new cE}function cC(e){return new cx(null==e?void 0:e.cacheSizeBytes)}function cD(e){return new cb(e)}function ck(e){return new cT(e)}class cA{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=o3.provider,this._offlineComponentProvider={build:t=>new o4(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class cN{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=o3.provider,this._offlineComponentProvider={build:t=>new o6(t,null==e?void 0:e.cacheSizeBytes)}}}function cR(e){return new cA(null==e?void 0:e.forceOwnership)}function cM(){return new cN}let cV={maxAttempts:5};class cO{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ul(e)}set(e,t,n){this._verifyNotCommitted();let r=cF(e,this._firestore),i=u5(r.converter,t,n),s=uu(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,rE.none())),this}update(e,t,n,...r){let i;this._verifyNotCommitted();let s=cF(e,this._firestore);return i="string"==typeof(t=(0,c.Ku)(t))||t instanceof l8?uy(this._dataReader,"WriteBatch.update",s._key,t,n,r):up(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,rE.exists(!0))),this}delete(e){this._verifyNotCommitted();let t=cF(e,this._firestore);return this._mutations=this._mutations.concat(new rO(t._key,rE.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new N(A.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function cF(e,t){if((e=(0,c.Ku)(e)).firestore!==t)throw new N(A.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class cL{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=ul(e)}get(e){let t=cF(e,this._firestore),n=new u4(this._firestore);return this._transaction.lookup([t._key]).then(e=>{if(!e||1!==e.length)return S(24041);let r=e[0];
8if(r.isFoundDocument())return new uD(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new uD(this._firestore,n,t._key,null,t.converter);throw S(18433,{doc:r})})}set(e,t,n){let r=cF(e,this._firestore),i=u5(r.converter,t,n),s=uu(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){let i,s=cF(e,this._firestore);return i="string"==typeof(t=(0,c.Ku)(t))||t instanceof l8?uy(this._dataReader,"Transaction.update",s._key,t,n,r):up(this._dataReader,"Transaction.update",s._key,t),this._transaction.update(s._key,i),this}delete(e){let t=cF(e,this._firestore);return this._transaction.delete(t._key),this}}class cP extends cL{constructor(e,t){super(e,t),this._firestore=e}get(e){let t=cF(e,this._firestore),n=new ca(this._firestore);return super.get(e).then(e=>new ct(this._firestore,n,t._key,e._document,new ce(!1,!1),t.converter))}}function cq(e,t,n){e=lT(e,l$);let r=Object.assign(Object.assign({},cV),n);if(r.maxAttempts<1)throw new N(A.INVALID_ARGUMENT,"Max attempts must be at least 1");return function(e,t,n){let r=new R;return e.asyncQueue.enqueueAndForget(async()=>{let i=await ld(e);new lt(e.asyncQueue,i,n,t,r).Wu()}),r.promise}(lQ(e),n=>t(new cP(e,n)),r)}function cU(){return new uc("deleteField")}function cB(){return new ud("serverTimestamp")}function cz(...e){return new uf("arrayUnion",e)}function c$(...e){return new um("arrayRemove",e)}function cK(e){return new ug("increment",e)}function cG(e){return new ut(e)}function cQ(e){return lQ(e=lT(e,l$)),new cO(e,t=>cw(e,t))}function cj(e,t){let n=lQ(e=lT(e,l$));if(!n._uninitializedComponentsProvider||"memory"===n._uninitializedComponentsProvider._offline.kind)return E("Cannot enable indexes when persistence is disabled"),Promise.resolve();let r=function(e){let t="string"==typeof e?function(e){try{return JSON.parse(e)}catch(e){throw new N(A.INVALID_ARGUMENT,"Failed to parse JSON: "+(null==e?void 0:e.message))}}(e):e,n=[];if(Array.isArray(t.indexes))for(let e of t.indexes){let t=cW(e,"collectionGroup"),r=[];if(Array.isArray(e.fields))for(let t of e.fields){let e=ux("setIndexConfiguration",cW(t,"fieldPath"));"CONTAINS"===t.arrayConfig?r.push(new ea(e,2)):"ASCENDING"===t.order?r.push(new ea(e,0)):"DESCENDING"===t.order&&r.push(new ea(e,1))}n.push(new en(en.UNKNOWN_ID,t,r,eo.empty()))}return n}(t);return n.asyncQueue.enqueue(async()=>(async function(e,t){let n=e.indexManager,r=[];return e.persistence.runTransaction("Configure indexes","readwrite",e=>n.getFieldIndexes(e).next(i=>(function(e,t,n,r,i){t=[...t],(e=[...e]).sort(n),t.sort(n);let s=e.length,a=t.length,o=0,l=0;for(;o<a&&l<s;){let s=n(e[l],t[o]);s<0?i(e[l++]):s>0?r(t[o++]):(o++,l++)}for(;o<a;)r(t[o++]);for(;l<s;)i(e[l++])})(i,t,es,t=>{r.push(n.addFieldIndex(e,t))},t=>{r.push(n.deleteFieldIndex(e,t))})).next(()=>eg.waitFor(r)))})(await lu(n),r))}function cW(e,t){if("string"!=typeof e[t])throw new N(A.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}class cH{constructor(e){this._firestore=e,this.type="PersistentCacheIndexManager"}}function cY(e){var t;e=lT(e,l$);let n=c1.get(e);if(n)return n;if("persistent"!==(null==(t=lQ(e)._uninitializedComponentsProvider)?void 0:t._offline.kind))return null;let r=new cH(e);return c1.set(e,r),r}function cJ(e){c0(e,!0)}function cX(e){c0(e,!1)}function cZ(e){var t;(t=lQ(e._firestore)).asyncQueue.enqueue(async()=>(function(e){let t=e.indexManager;return e.persistence.runTransaction("Delete All Indexes","readwrite",e=>t.deleteAllFieldIndexes(e))})(await lu(t))).then(e=>b("deleting all persistent cache indexes succeeded")).catch(e=>E("deleting all persistent cache indexes failed",e))}function c0(e,t){var n;(n=lQ(e._firestore),n.asyncQueue.enqueue(async()=>{var e;return e=await lu(n),void(e.Ms.fs=t)})).then(e=>b(`setting persistent cache index auto creation isEnabled=${t} succeeded`)).catch(e=>E(`setting persistent cache index auto creation isEnabled=${t} failed`,e))}let c1=new WeakMap;function c2(e){var t;let n=null==(t=lQ(lT(e.firestore,l$))._onlineComponents)?void 0:t.datastore.serializer;return void 0===n?null:iv(n,nX(e._query)).gt}function c5(e,t){var n;let r=tA(t,(e,t)=>new rU(t,e.aggregateType,e._internalFieldPath)),i=null==(n=lQ(lT(e.firestore,l$))._onlineComponents)?void 0:n.datastore.serializer;return void 0===i?null:iI(i,nZ(e._query),r,!0).request}class c4{constructor(){throw Error("instances of this class should not be created")}static onExistenceFilterMismatch(e){return c6.instance.onExistenceFilterMismatch(e)}}class c6{constructor(){this.vc=new Map}static get instance(){return c3||function(e){if(rK)throw Error("a TestingHooksSpi instance is already set");rK=e}(c3=new c6),c3}
8ht(e){this.vc.forEach(t=>t(e))}onExistenceFilterMismatch(e){let t=Symbol(),n=this.vc;return n.set(t,e),()=>n.delete(t)}}let c3=null;!function(e,t=!0){w=o.MF,(0,o.om)(new l.uA("firestore",(e,{instanceIdentifier:n,options:r})=>{let i=e.getProvider("app").getImmediate(),s=new l$(new F(e.getProvider("auth-internal")),new U(i,e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new N(A.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new t1(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:t},r),s._setSettings(r),s},"PUBLIC").setMultipleInstances(!0)),(0,o.KO)(g,p,void 0),(0,o.KO)(g,p,"esm2017")}()}}]);

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.