{"version":3,"sources":["webpack:///./node_modules/@firebase/firestore/dist/index.esm2017.js","webpack:///./node_modules/tslib/tslib.es6.js","webpack:///./node_modules/@firebase/auth/dist/esm2017/index-7078a255.js","webpack:///./node_modules/@firebase/auth/dist/esm2017/internal.js","webpack:///./node_modules/firebase/compat/auth/dist/index.esm.js","webpack:///./node_modules/@firebase/installations/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/analytics/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/analytics-compat/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/app-check/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/app-check-compat/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/database-compat/dist/index.esm2017.js","webpack:///./node_modules/@firebase/firestore-compat/dist/index.esm2017.js","webpack:///./node_modules/@firebase/functions/dist/index.esm2017.js","webpack:///./node_modules/@firebase/functions-compat/dist/index.esm2017.js","webpack:///./node_modules/@firebase/messaging/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/messaging/dist/index.sw.esm2017.js","webpack:///./node_modules/@firebase/messaging-compat/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/storage/dist/index.esm2017.js","webpack:///./node_modules/@firebase/storage-compat/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/performance/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/performance-compat/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/remote-config/dist/esm/index.esm2017.js","webpack:///./node_modules/@firebase/remote-config-compat/dist/esm/index.esm2017.js","webpack:///./node_modules/firebase/compat/dist/index.esm.js","webpack:///./node_modules/@firebase/database/dist/index.esm2017.js","webpack:///./node_modules/@firebase/auth-compat/dist/index.esm2017.js","webpack:///./node_modules/@firebase/webchannel-wrapper/dist/index.esm2017.js"],"names":["D","C","t","this","uid","isAuthenticated","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","x","N","k","logLevel","M","setLogLevel","O","e","DEBUG","n","map","B","debug","F","ERROR","error","$","WARN","warn","JSON","stringify","L","Error","U","q","K","G","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","Q","super","code","message","toString","name","j","promise","Promise","resolve","reject","W","user","type","headers","Map","set","z","enqueueRetryable","H","token","changeListener","J","currentUser","i","forceRefresh","auth","s","o","u","r","addAuthTokenListener","onInit","setTimeout","getImmediate","optional","getToken","then","accessToken","removeAuthTokenListener","getUid","Y","getAuthHeaderValueForFirstParty","X","h","l","m","Z","value","length","tt","g","appCheck","p","addTokenListener","removeTokenListener","nt","previousValue","sequenceNumberHandler","I","T","writeSequenceNumber","Math","max","st","self","crypto","msCrypto","Uint8Array","getRandomValues","floor","random","A","it","charAt","rt","ot","every","ut","at","seconds","nanoseconds","fromMillis","Date","now","getTime","toMillis","String","padStart","ct","timestamp","_compareTo","isEqual","ht","Object","prototype","hasOwnProperty","call","lt","ft","dt","segments","offset","len","comparator","slice","limit","forEach","push","construct","get","min","_t","toArray","join","canonicalString","indexOf","split","filter","wt","mt","test","replace","isValidIdentifier","gt","fields","sort","isPrefixOf","yt","atob","pt","binaryString","fromCharCode","Symbol","iterator","next","charCodeAt","done","btoa","EMPTY_BYTE_STRING","It","RegExp","Tt","exec","substr","Number","nanos","Et","At","fromBase64String","fromUint8Array","Rt","mapValue","__type__","stringValue","Pt","__previous_value__","bt","__local_write_time__","timestampValue","Vt","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","useFetchStreams","vt","projectId","database","St","Dt","Ct","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","xt","path","fromString","popFirst","emptyPath","popLast","lastSegment","Nt","kt","nullValue","Mt","Ht","Ot","booleanValue","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","doubleValue","isNaN","arrayValue","values","Ft","find","$t","Bt","compareTo","keys","Lt","Ut","toBase64","fromName","qt","Kt","Gt","Qt","jt","Wt","zt","assign","Jt","NaN","empty","Yt","Xt","Zt","te","isEmpty","getFieldsMap","isImmediateParentOf","applyChanges","field","ee","child","ne","key","documentType","version","readTime","data","documentState","hasLocalMutations","hasCommittedMutations","clone","se","indexId","collectionGroup","indexState","ie","kind","re","UNKNOWN_ID","oe","fieldPath","ue","sequenceNumber","he","ae","toTimestamp","fromTimestamp","ce","documentKey","largestBatchId","le","fe","orderBy","filters","startAt","endAt","P","de","_e","op","dir","inclusive","position","we","me","xe","ke","ge","isDocumentKey","ye","Te","pe","Ie","isKeyField","V","Ee","be","Ve","ve","Se","Ae","Re","v","Pe","some","De","Ce","Ne","Me","explicitOrderBy","limitType","Oe","Fe","$e","Be","Le","Ue","S","qe","Ke","keyField","Ge","Qe","je","We","ze","He","isFoundDocument","hasCollectionId","matches","Je","Ye","Xe","Ze","tn","en","nn","_","sn","un","an","cn","hn","ln","on","dn","rn","fn","elements","_n","wn","transform","mn","gn","transformResults","yn","updateTime","exists","pn","In","Tn","bn","Sn","fieldTransforms","setAll","convertToFoundDocument","setHasCommittedMutations","Vn","precondition","convertToUnknownDocument","vn","convertToNoDocument","En","Dn","Pn","setHasLocalMutations","An","Rn","fieldMask","Cn","xn","Nn","count","kn","Mn","On","Fn","$n","mapKeyFn","equalsFn","inner","innerSize","splice","Bn","root","Un","EMPTY","insert","copy","BLACK","remove","left","right","size","minKey","maxKey","inorderTraversal","reverseTraversal","Ln","isReverse","nodeStack","pop","color","RED","fixUp","isRed","moveRedLeft","removeMin","rotateRight","moveRedRight","rotateLeft","colorFlip","check","pow","qn","getIteratorFrom","hasNext","getNext","getIterator","Kn","has","add","iter","Gn","Qn","jn","Wn","zn","Hn","Jn","Yn","Xn","Zn","ts","es","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","ns","createSynthesizedTargetChangeForCurrentChange","resumeToken","current","addedDocuments","modifiedDocuments","removedDocuments","ss","removedTargetIds","is","targetId","rs","state","targetIds","cause","os","cs","approximateByteSize","us","as","forEachTarget","removeTarget","et","target","newNoDocument","forEachWhile","purpose","setReadTime","delete","getRemoteKeysForTarget","hs","asc","desc","ls","in","fs","ds","toISOString","_s","toUint8Array","ws","ms","gs","ys","Gs","ps","Is","Rs","Ts","Es","As","Ps","bs","newFoundDocument","Vs","found","missing","vs","targetChange","targetChangeType","documentChange","document","a","c","documentDelete","documentRemove","Ss","update","updateMask","Ks","verify","updateTransforms","setToServerValue","appendMissingElements","removeAllFromArray","increment","isNone","currentDocument","Ds","none","fromServerFormat","fieldPaths","Cs","xs","documents","Ns","structuredQuery","parent","from","collectionId","allDescendants","unaryFilter","Bs","fieldFilter","$s","compositeFilter","where","direction","Fs","before","ks","Os","Ls","Ms","qs","Us","reduce","concat","create","Qs","Ws","js","zs","substring","Hs","Js","Ys","Xs","Zs","ti","ei","ni","si","ii","ri","oi","ui","ai","ci","hi","li","fi","di","_i","wi","mi","gi","yi","onCommittedListeners","pi","nextCallback","catchCallback","result","isDone","callbackAttached","wrapFailure","wrapSuccess","wrapUserFunction","waitFor","Ii","action","transaction","aborted","oncomplete","onabort","Ai","onerror","vi","abort","commit","objectStore","Pi","Ti","bi","window","indexedDB","deleteDatabase","toPromise","process","store","match","db","open","onsuccess","onblocked","onupgradeneeded","oldVersion","onversionchange","catch","close","Ei","Ri","put","options","index","getAll","cursor","range","primaryKey","continue","reverse","openKeyCursor","openCursor","Vi","Si","currentSequenceNumber","Di","Ci","batchId","localWriteTime","baseMutations","mutations","mutationResults","applyToLocalView","isValidDocument","xi","batch","commitVersion","docVersions","Ni","mutation","ki","lastLimboFreeSnapshotVersion","Mi","Oi","noDocument","fromSegments","Li","unknownDocument","newUnknownDocument","Fi","prefixPath","getCollectionPath","documentId","$i","isNoDocument","Bi","isUnknownDocument","Ui","localWriteTimeMs","qi","query","lastListenSequenceNumber","Ki","canonicalId","Gi","Qi","overlayMutation","ji","Wi","zi","id","bundleId","createTime","Hi","bundledQuery","Ji","userId","Yi","Set","IDBKeyRange","bound","POSITIVE_INFINITY","getKey","collectionPath","getCollectionGroup","Xi","Zi","tr","ceil","er","buffer","codePointAt","DataView","ArrayBuffer","setFloat64","nr","sr","ir","seed","reset","rr","directionalValue","or","ur","ar","cr","hr","getEntries","lr","fr","addOnCommittedListener","dr","wr","mr","_r","getFieldIndex","Array","f","d","createRange","getFieldIndexes","orderedDocumentKey","only","upperBound","gr","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","yr","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","pr","Ir","DEFAULT","DISABLED","Tr","indexManager","referenceDelegate","NEGATIVE_INFINITY","Ar","Rr","addToCollectionParentIndex","lookupMutationBatch","lowerBound","markPotentiallyOrphaned","checkEmpty","Er","Pr","lastAcknowledgedBatchId","lastStreamToken","br","Vr","highestTargetId","lastRemoteSnapshotVersion","highestListenSequenceNumber","targetCount","removeMatchingKeysForTargetId","vr","removeTargetData","Sr","Dr","addReference","removeReference","async","Cr","xr","Nr","last","kr","garbageCollector","asyncQueue","params","cancel","enqueueAfterDelay","collectGarbage","Mr","maxValue","removeTargets","removeOrphanedDocuments","getCacheSize","calculateTargetCount","nthSequenceNumber","Or","getTargetCache","getTargetCount","Fr","getRemoteDocumentCache","newChangeBuffer","getEntry","removeEntry","apply","withSequenceNumber","updateTargetData","getSize","$r","changes","changesApplied","assertNotApplied","newInvalidDocument","getFromCache","getAllFromCache","Br","qr","getMetadata","byteSize","Kr","Qr","first","Gr","Lr","trackRemovals","Ur","addEntry","updateMetadata","jr","createObjectStore","keyPath","autoIncrement","createIndex","unique","Wr","deleteObjectStore","objectStoreNames","contains","zr","Hr","allowTabSynchronization","clientId","isPrimary","networkEnabled","inForeground","localStorage","runTransaction","getHighestSequenceNumber","started","newVersion","enqueueAndForget","Yr","updateTimeMs","Jr","removeItem","ownerId","leaseTimestampMs","raiseOnCommittedEvent","addEventListener","visibilityState","removeEventListener","navigator","appVersion","enterRestrictedMode","shutdown","getItem","setItem","Xr","isDefaultDatabase","Zr","getAllMutationBatchesAffectingDocumentKey","getAllMutationBatchesAffectingDocumentKeys","getCollectionParents","getAllFromCollection","getAllMutationBatchesAffectingQuery","to","fromCache","docChanges","doc","eo","hasPendingWrites","no","persistence","getBundleCache","getIndexManager","getMutationQueue","setIndexManager","collect","so","io","getAllMutationBatches","removedBatchIds","addedBatchIds","ro","applyToRemoteDocument","removeMutationBatch","performConsistencyCheck","oo","getLastRemoteSnapshotVersion","uo","removeMatchingKeys","addMatchingKeys","withResumeToken","withLastLimboFreeSnapshotVersion","toMicroseconds","updateLimboDocument","ao","setTargetsMetadata","co","getNextMutationBatchAfterBatchId","ho","getTargetData","allocateTargetId","addTargetData","lo","fo","getMatchingKeysForTargetId","mo","_o","wo","getAllFromCollectionGroup","go","metadata","yo","saveNamedQuery","po","Io","overlays","To","Eo","forEachInRange","firstAfterOrEqual","Ao","shift","Ro","docs","mutableCopy","Po","bo","containsKey","Vo","toKey","vo","So","fromPath","Do","Co","xo","No","parse","ko","Mo","activeTargetIds","Oo","onlineState","Fo","$o","syncEngine","onlineStateHandler","bind","storage","isActiveQueryTarget","addPendingMutation","storageArea","newValue","all","unionWith","Bo","Lo","Uo","qo","BatchGetDocuments","Commit","RunQuery","Ko","Go","databaseInfo","listenOnce","COMPLETE","getLastErrorCode","NO_ERROR","getResponseJson","TIMEOUT","HTTP_ERROR","getStatus","getResponseText","status","toLowerCase","send","httpSessionIdParam","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","detectBufferingProxy","xmlHttpFactory","httpHeadersOverwriteParam","createWebChannel","y","listen","EventType","OPEN","CLOSE","MESSAGE","STAT_EVENT","stat","PROXY","NOPROXY","Qo","jo","Wo","zo","timerId","skipDelay","Ho","authCredentialsProvider","appCheckCredentialsProvider","listener","stream","invalidateToken","onMessage","start","Jo","addTarget","labels","Yo","streamToken","writeResults","commitTime","Xo","writes","authCredentials","appCheckCredentials","tu","eu","Zo","nu","su","iu","ou","uu","cu","localStore","datastore","remoteSyncer","hu","lu","fu","du","_u","wu","au","Vu","ru","mu","rejectListen","applyRemoteEvent","vu","gu","yu","pu","Iu","Tu","Eu","Au","applySuccessfulWrite","Ru","rejectFailedWrite","Pu","verifyOperationInProgress","handleCredentialChange","bu","stop","Su","targetTimeMs","removalCallback","deferred","timerHandle","handleDelayElapsed","clearTimeout","Du","Cu","keyedMap","sortedSet","xu","Nu","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","emptySet","ku","listeners","Mu","queries","Ou","onListen","onError","Lu","Fu","onUnlisten","$u","Bu","Uu","includeMetadataChanges","fromInitialDocuments","qu","payload","byteLength","Ku","Gu","collectionGroups","progress","Qu","bytesLoaded","documentsLoaded","namedQuery","documentMetadata","taskState","totalDocuments","totalBytes","ju","Wu","zu","track","snapshot","Hu","Ju","view","Zu","Yu","remoteStore","eventManager","sharedClientState","maxConcurrentLimboResolutions","ta","ea","na","sa","ia","ra","oa","ua","aa","ca","ha","Xu","Va","addLocalQueryTarget","isPrimaryClient","la","fa","removeLocalQueryTarget","clearQueryState","va","addMutationBatch","applyToLocalDocumentSet","wa","setOnlineState","updateQueryState","_a","updateMutationState","getHighestUnacknowledgedBatchId","da","ma","clear","handleUserChange","ga","ya","pa","Ia","Ta","getAllActiveQueryTargets","Ea","isLocalQueryTarget","Aa","Ra","Pa","createSynthesizedRemoteEventForCurrentChange","ba","Sa","getBundleMetadata","_completeWith","_updateProgress","complete","saveBundleMetadata","_failWith","notifyBundleLoaded","Da","synchronizeTabs","gcScheduler","initialUser","Ca","cacheSizeBytes","forceOwnership","initialize","withCacheSize","xa","Na","createDatastore","createRemoteStore","createEventManager","createSyncEngine","ka","closed","Ma","observer","muted","console","Oa","TextDecoder","decode","findIndex","read","Fa","readVersions","committed","lastWriteError","writtenDocs","ensureCommitNotCalled","recordVersion","write","toMutation","preconditionForUpdate","$a","updateFunction","Ba","R","authCredentialListener","appCheckCredentialListener","isShuttingDown","enqueueAndForgetEvenWhileRestricted","onlineComponents","terminate","offlineComponents","La","getConfiguration","setCredentialChangeListener","setDatabaseDeletedListener","Ua","qa","setAppCheckTokenChangeListener","Ka","Ga","Qa","ja","Wa","za","Ha","enqueue","setNetworkEnabled","Ja","Ya","Xa","source","Za","tc","ec","nc","run","sc","TextEncoder","encode","ReadableStream","getReader","ic","getNamedQuery","rc","oc","uc","ac","cc","hc","constructor","lc","_delegate","fc","dc","credentials","ignoreUndefinedProperties","experimentalForceLongPolling","experimentalAutoDetectLongPolling","_c","_authCredentials","_appCheckCredentials","_persistenceKey","_settings","_settingsFrozen","_databaseId","_app","_terminateTask","client","sessionIndex","iamToken","_terminate","app","settings","wc","_getSettings","_setSettings","mockUserToken","sub","user_id","mc","converter","_key","firestore","yc","gc","_query","_path","pc","Ic","Tc","arguments","Ec","Ac","Rc","stack","includes","createAndSchedule","Pc","bc","_progressObserver","_taskCompletionResolver","_lastProgress","Vc","vc","_queue","_firestoreClient","xc","Cc","verifyNotTerminated","_freezeSettings","Nc","Kc","Mc","kc","DOMException","Oc","_initialized","_terminated","Fc","$c","Bc","Uc","qc","Gc","_internalPath","jc","_byteString","Wc","_methodName","zc","isFinite","_lat","_long","Hc","Jc","Yc","Xc","Zc","ph","methodName","th","eh","nh","merge","mergeFields","wh","dh","mh","Ih","covers","sh","ih","rh","oh","fh","uh","ah","ch","yh","hh","lh","_h","_toFieldTransform","fromDate","getPrototypeOf","gh","search","Th","_firestore","_userDataWriter","_document","_converter","Eh","fromFirestore","convertValue","Ah","Rh","Ph","_firestoreImpl","bh","serverTimestamps","Vh","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","oldIndex","newIndex","vh","Sh","Dh","Ch","xh","_apply","Nh","zh","Wh","Hh","kh","Mh","Oh","Fh","$h","Bh","Lh","jh","Uh","qh","Kh","Gh","Qh","isArray","Jh","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","Yh","toFirestore","Xh","convertDocumentKey","Zh","_commitHandler","_mutations","_committed","_dataReader","_verifyNotCommitted","tl","el","wl","nl","sl","il","rl","ol","ul","al","_l","cl","hl","ll","fl","dl","ml","_transaction","lookup","gl","yl","pl","Il","Tl","El","getProvider","__rest","getOwnPropertySymbols","propertyIsEnumerable","ProviderId","FACEBOOK","GITHUB","GOOGLE","PASSWORD","PHONE","TWITTER","ActionCodeOperation","EMAIL_SIGNIN","PASSWORD_RESET","RECOVER_EMAIL","REVERT_SECOND_FACTOR_ADDITION","VERIFY_AND_CHANGE_EMAIL","VERIFY_EMAIL","_debugErrorMap","_prodErrorMap","debugErrorMap","prodErrorMap","_DEFAULT_AUTH_ERROR_FACTORY","logClient","_logError","msg","args","_fail","authOrCode","rest","createErrorInternal","_createError","_errorWithCustomMessage","errorMap","factory","appName","_assertInstanceOf","object","instance","constructorInstance","fullParams","_errorFactory","_assert","assertion","debugFail","failure","debugAssert","instanceCache","_getInstance","cls","Function","_initializeAuthInstance","deps","hierarchy","_updateErrorMap","_initializeWithPersistence","popupRedirectResolver","_getCurrentUrl","location","href","_isHttpOrHttps","_getCurrentScheme","protocol","_isOnline","onLine","_getUserLanguage","navigatorLanguage","languages","language","shortDelay","longDelay","isMobile","_emulatorUrl","config","emulator","url","startsWith","FetchProvider","fetchImpl","headersImpl","responseImpl","fetch","Headers","Response","SERVER_ERROR_MAP","DEFAULT_API_TIMEOUT_MS","_addTidIfNecessary","request","tenantId","_performApiRequest","method","customErrorMap","_performFetchWithErrorHandling","body","apiKey","_getAdditionalHeaders","languageCode","_getFinalTarget","apiHost","referrerPolicy","fetchFn","_canInitEmulator","networkTimeout","NetworkTimeout","response","race","clearNetworkTimeout","json","_makeTaggedError","ok","errorMessage","serverErrorCode","serverErrorMessage","authError","_performSignInRequest","serverResponse","_serverResponse","base","apiScheme","timer","errorParams","email","phoneNumber","customData","_tokenResponse","deleteAccount","deleteLinkedAccounts","getAccountInfo","utcTimestampToDateString","utcTimestamp","date","toUTCString","getIdTokenResult","userInternal","getIdToken","claims","_parseToken","exp","auth_time","iat","firebase","undefined","signInProvider","authTime","secondsStringToMilliseconds","issuedAtTime","expirationTime","signInSecondFactor","algorithm","signature","decoded","_tokenExpiresIn","parsedToken","_logoutIfInvalidated","bypassAuthState","isUserInvalidated","signOut","ProactiveRefresh","isRunning","errorBackoff","schedule","wasError","interval","expTime","stsTokenManager","getInterval","iteration","UserMetadata","createdAt","lastLoginAt","_initializeTime","lastSignInTime","creationTime","_reloadWithoutSaving","idToken","users","coreAccount","_notifyReloadListener","newProviderData","providerUserInfo","extractProviderData","providerData","mergeProviderData","oldIsAnonymous","isAnonymous","newIsAnonymous","passwordHash","updates","localId","displayName","photoURL","photoUrl","emailVerified","reload","_persistUserIfCurrent","_notifyListenersIfCurrent","original","newData","deduped","providerId","providers","provider","rawId","requestStsToken","refreshToken","tokenApiHost","access_token","expiresIn","expires_in","refresh_token","StsTokenManager","updateTokensAndExpiration","isExpired","refresh","oldToken","expiresInSec","manager","toJSON","assertStringOrUndefined","opt","proactiveRefresh","reloadUserInfo","reloadListener","userInfo","_copy","_assign","_clone","callback","_start","_stop","tokensRefreshed","updateFromServerResponse","clearRefreshToken","_redirectEventId","_b","_d","_f","_g","plainObjectTokenManager","fromJSON","idTokenResponse","InMemoryPersistence","_listener","inMemoryPersistence","_persistenceKeyName","PersistenceUserManager","userKey","fullUserKey","fullPersistenceKey","boundEventHandler","_onStorageEvent","_addListener","_set","blob","_get","_fromJSON","_remove","newPersistence","getCurrentUser","removeCurrentUser","setCurrentUser","_removeListener","persistenceHierarchy","availablePersistences","_isAvailable","selectedPersistence","userToMigrate","migrationHierarchy","_shouldAllowMigration","_getBrowserName","userAgent","_isIEMobile","_isFirefox","_isBlackBerry","_isWebOS","_isSafari","_isChromeIOS","_isAndroid","_isIOS","_isIOS7Or8","_isIOSStandalone","standalone","_isIE10","documentMode","_isMobileBrowser","_isIframe","top","_getClientVersion","clientPlatform","frameworks","reportedPlatform","reportedFrameworks","heartbeatServiceProvider","emulatorConfig","operations","authStateSubscription","idTokenSubscription","redirectUser","isProactiveRefreshEnabled","_isInitialized","_deleted","_initializationPromise","_popupRedirectResolver","lastNotifiedUid","appVerificationDisabledForTesting","clientVersion","sdkClientVersion","queue","persistenceManager","_shouldInitProactively","_initialize","initializeCurrentUser","assertedPersistence","_currentUser","_updateCurrentUser","storedUser","authDomain","getOrInitRedirectPersistenceManager","redirectUserEventId","storedUserEventId","tryRedirectSignIn","directlySetCurrentUser","reloadAndSetCurrentUserOrClear","redirectResolver","_completeRedirectFn","_setRedirectUser","userExtern","notifyAuthListeners","redirectPersistenceManager","setPersistence","nextOrObserver","completed","registerStateListener","redirectManager","resolver","_redirectPersistence","_startProactiveRefresh","_stopProactiveRefresh","currentUid","subscription","cb","addObserver","framework","_getFrameworks","heartbeatsHeader","getHeartbeatsHeader","_castAuth","connectAuthEmulator","authInternal","disableWarnings","extractProtocol","port","extractHostAndPort","portStr","freeze","emitEmulatorWarning","protocolEnd","authority","hostAndPort","bracketedIPv6","parsePort","attachBanner","createElement","sty","style","innerText","width","backgroundColor","border","bottom","margin","zIndex","textAlign","classList","appendChild","info","readyState","AuthCredential","signInMethod","_auth","_idToken","resetPassword","updateEmailPassword","applyActionCode$1","signInWithPassword","sendOobCode","sendEmailVerification$1","sendPasswordResetEmail$1","sendSignInLinkToEmail$1","verifyAndChangeEmail","signInWithEmailLink$1","signInWithEmailLinkForLinking","EmailAuthCredential","_email","_password","_tenantId","password","oobCode","obj","_fromEmailAndPassword","_fromEmailAndCode","returnSecureToken","_getIdTokenResponse","signInWithIdp","IDP_REQUEST_URI$1","pendingToken","cred","nonce","oauthToken","oauthTokenSecret","secret","buildRequest","autoCreate","requestUri","postBody","sendPhoneVerificationCode","signInWithPhoneNumber$1","linkWithPhoneNumber$1","temporaryProof","VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_","verifyPhoneNumberForExisting","apiRequest","operation","PhoneAuthCredential","verificationId","verificationCode","_makeVerificationRequest","sessionInfo","parseMode","mode","parseDeepLink","link","doubleDeepLink","iOSDeepLink","iOSDoubleDeepLink","actionLink","searchParams","continueUrl","EmailAuthProvider","PROVIDER_ID","emailLink","actionCodeUrl","parseLink","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_LINK_SIGN_IN_METHOD","FederatedAuthProvider","defaultLanguageCode","customParameters","customOAuthParameters","BaseOAuthProvider","scopes","scope","OAuthProvider","_fromParams","_credential","rawNonce","userCredential","oauthCredentialFromTaggedObject","tokenResponse","oauthIdToken","oauthAccessToken","FacebookAuthProvider","FACEBOOK_SIGN_IN_METHOD","credentialFromTaggedObject","credential","GoogleAuthProvider","addScope","GOOGLE_SIGN_IN_METHOD","GithubAuthProvider","GITHUB_SIGN_IN_METHOD","IDP_REQUEST_URI","SAMLAuthCredential","SAML_PROVIDER_PREFIX","SAMLAuthProvider","samlCredentialFromTaggedObject","_create","TwitterAuthProvider","TWITTER_SIGN_IN_METHOD","signUp","UserCredentialImpl","operationType","_fromIdTokenResponse","providerIdForResponse","userCred","_updateTokensIfNecessary","signInAnonymously","setPrototypeOf","_processCredentialSavingMfaContextIfNecessary","idTokenProvider","_getReauthenticationResolver","_fromErrorAndOperation","providerDataAsNames","pid","unlink","_assertLinkedStatus","deleteProvider","providersLeft","pd","_link$1","_linkToIdToken","_forOperation","expected","providerIds","_reauthenticate","parsed","_signInWithCredential","signInWithCredential","linkWithCredential","reauthenticateWithCredential","signInWithCustomToken$1","signInWithCustomToken","customToken","MultiFactorInfoImpl","factorId","mfaEnrollmentId","enrollmentTime","enrolledAt","enrollment","PhoneMultiFactorInfoImpl","_fromServerResponse","phoneInfo","_setActionCodeSettingsOnRequest","actionCodeSettings","dynamicLinkDomain","canHandleCodeInApp","handleCodeInApp","iOS","iOSBundleId","android","packageName","androidInstallApp","installApp","androidMinimumVersionCode","minimumVersion","androidPackageName","sendPasswordResetEmail","authModular","requestType","confirmPasswordReset","newPassword","applyActionCode","checkActionCode","newEmail","mfaInfo","multiFactorInfo","previousEmail","verifyPasswordResetCode","createUserWithEmailAndPassword","signInWithEmailAndPassword","sendSignInLinkToEmail","isSignInWithEmailLink","signInWithEmailLink","credentialWithLink","createAuthUri","fetchSignInMethodsForEmail","continueUri","identifier","signinMethods","sendEmailVerification","verifyBeforeUpdateEmail","updateProfile$1","updateProfile","profileRequest","passwordProvider","updateEmail","updateEmailOrPassword","updatePassword","profile","rawUserInfo","isNewUser","filteredProviderId","GenericAdditionalUserInfo","FacebookAdditionalUserInfo","GithubAdditionalUserInfo","GoogleAdditionalUserInfo","TwitterAdditionalUserInfo","screenName","FederatedAdditionalUserInfoWithUsername","username","login","getAdditionalUserInfo","MultiFactorSessionImpl","mfaPendingCredential","multiFactorSession","pendingCredential","_fromMfaPendingCredential","_fromIdtoken","MultiFactorResolverImpl","session","hints","signInResolver","authExtern","mfaResponse","_process","assertionExtern","getMultiFactorResolver","errorInternal","_fromError","startEnrollPhoneMfa","finalizeEnrollPhoneMfa","withdrawMfa","MultiFactorUserImpl","enrolledFactors","_onReload","getSession","finalizeMfaResponse","infoOrUid","multiFactorUserCache","WeakMap","multiFactor","userModular","_fromUser","STORAGE_AVAILABLE_KEY","BrowserPersistenceClass","storageRetriever","_iframeCannotSyncWebStorage","_POLLING_INTERVAL_MS$1","IE10_LOCAL_STORAGE_SYNC_DELAY","BrowserLocalPersistence","event","poll","onStorageEvent","localCache","pollTimer","safariLocalStorageNotSynced","fallbackToPolling","oldValue","forAllChangedKeys","_oldValue","notifyListeners","detachListener","stopPolling","storedValue","triggerListeners","setInterval","StorageEvent","clearInterval","startPolling","attachListener","browserLocalPersistence","BrowserSessionPersistence","sessionStorage","browserSessionPersistence","_allSettled","promises","fulfilled","reason","Receiver","eventTarget","handlersMap","handleEvent","existingInstance","receivers","receiver","isListeningto","newInstance","messageEvent","eventId","eventType","handlers","ports","postMessage","handler","origin","eventHandler","_generateEventId","prefix","digits","Sender","messageChannel","port1","timeout","MessageChannel","completionTimer","ackTimer","port2","finally","removeMessageHandler","_window","_setWindowLocation","_isWorker","_getActiveServiceWorker","serviceWorker","registration","ready","active","_getServiceWorkerController","controller","_getWorkerGlobalScope","DB_NAME","DB_VERSION","DB_OBJECTSTORE_NAME","DB_DATA_KEYPATH","DBPromise","getObjectStore","isReadWrite","_deleteDatabase","_openDatabase","_putObject","getObject","_deleteObject","_POLLING_INTERVAL_MS","_TRANSACTION_RETRY_COUNT","IndexedDBLocalPersistence","pendingWrites","sender","serviceWorkerReceiverAvailable","activeServiceWorker","_workerInitializationPromise","initializeServiceWorkerMessaging","numAttempts","_openDb","initializeReceiver","initializeSender","_subscribe","_origin","_poll","keyProcessed","_data","results","_send","_withPendingWrite","_withRetries","notifyServiceWorker","getAllRequest","keysInResult","fbase_key","localKey","indexedDBLocalPersistence","startSignInPhoneMfa","finalizeSignInPhoneMfa","getRecaptchaParams","recaptchaSiteKey","getScriptParentElement","getElementsByTagName","_loadJS","setAttribute","onload","charset","_generateCallbackName","_SOLVE_TIME_MS","_EXPIRATION_TIME_MS","_WIDGET_ID_START","MockReCaptcha","counter","_widgets","container","parameters","MockWidget","optWidgetId","getResponse","execute","containerOrId","deleted","responseToken","clickHandler","getElementById","isVisible","checkIfDeleted","generateRandomAlphaNumericString","expiredCallback","chars","allowedChars","_JSLOAD_CALLBACK","NETWORK_TIMEOUT_DELAY","RECAPTCHA_BASE","hostLanguage","librarySeparatelyLoaded","grecaptcha","isHostLanguageValid","shouldResolveImmediately","recaptcha","render","widgetId","MockReCaptchaLoaderImpl","RECAPTCHA_VERIFIER_TYPE","DEFAULT_PARAMS","theme","RecaptchaVerifier","destroyed","tokenChangeListeners","renderPromise","isInvisible","makeTokenCallback","_recaptchaLoader","validateStartingState","assertNotDestroyed","getAssertedRecaptcha","tokenChange","makeRenderPromise","clearedOneInstance","childNodes","node","removeChild","sitekey","hasChildNodes","existing","globalFunc","init","guaranteedEmpty","domReady","load","siteKey","ConfirmationResultImpl","onConfirmation","authCredential","_fromVerification","signInWithPhoneNumber","appVerifier","_verifyPhoneNumber","linkWithPhoneNumber","reauthenticateWithPhoneNumber","verifier","recaptchaToken","phoneInfoOptions","phoneEnrollmentInfo","phoneSessionInfo","multiFactorHint","multiFactorUid","phoneSignInInfo","phoneResponseInfo","_reset","updatePhoneNumber","phoneOptions","applicationVerifier","_fromTokenResponse","_withDefaultResolver","resolverOverride","PHONE_SIGN_IN_METHOD","IdpCredential","_buildIdpRequest","sessionId","returnIdpCredential","_signIn","_reauth","_link","AbstractPopupRedirectOperation","pendingPromise","onExecution","registerConsumer","urlResponse","getIdpTask","unregisterAndCleanUp","unregisterConsumer","cleanUp","_POLL_WINDOW_CLOSE_TIMEOUT","signInWithPopup","resolverInternal","PopupOperation","executeNotNull","reauthenticateWithPopup","linkWithPopup","authWindow","pollId","currentPopupAction","_openPopup","associatedEvent","_originValidation","_isIframeWebStorageSupported","isSupported","pollUserCancellation","PENDING_REDIRECT_KEY","redirectOutcomeMap","RedirectAction","readyOutcome","hasPendingRedirect","_getAndClearPendingRedirectStatus","onAuthEvent","_redirectUserForId","pendingRedirectKey","resolverPersistence","_setPendingRedirectStatus","_clearRedirectOutcomes","signInWithRedirect","_signInWithRedirect","_openRedirect","reauthenticateWithRedirect","_reauthenticateWithRedirect","prepareUserForRedirect","linkWithRedirect","_linkWithRedirect","getRedirectResult","_getRedirectResult","resolverExtern","EVENT_DUPLICATION_CACHE_DURATION_MS","AuthEventManager","cachedEventUids","consumers","queuedRedirectEvent","hasHandledPotentialRedirect","lastProcessedEventTime","authEventConsumer","isEventForConsumer","sendToConsumer","saveEventToCache","hasEventBeenHandled","handled","consumer","isRedirectEvent","isNullRedirectEvent","eventIdMatches","eventUid","_getProjectConfig","IP_ADDRESS_REGEX","HTTP_REGEX","_validateOrigin","authorizedDomains","domain","matchDomain","currentUrl","hostname","URL","ceUrl","escapedDomainPattern","NETWORK_TIMEOUT","resetUnloadedGapiModules","beacon","___jsl","hint","CP","loadGapi","loadGapiIframe","gapi","iframes","getContext","ontimeout","Iframe","cbName","cachedGApiLoader","_loadGapi","PING_TIMEOUT","IFRAME_PATH","EMULATED_IFRAME_PATH","IFRAME_ATTRIBUTES","height","tabindex","EID_FROM_APIHOST","getIframeUrl","eid","fw","_openIframe","context","messageHandlersFilter","CROSS_ORIGIN_IFRAMES_FILTER","attributes","dontclear","iframe","restyle","setHideOnLeave","networkError","networkErrorTimer","clearTimerAndResolve","ping","BASE_POPUP_OPTIONS","resizable","statusbar","toolbar","DEFAULT_WIDTH","DEFAULT_HEIGHT","TARGET_BLANK","FIREFOX_EMPTY_URL","AuthPopup","_open","screen","availHeight","availWidth","scrollbars","optionsString","entries","accum","openAsNewWindowIOS","newWin","focus","click","createEvent","initMouseEvent","dispatchEvent","WIDGET_PATH","EMULATOR_WIDGET_PATH","_getRedirectUrl","authType","redirectUrl","additionalParams","setDefaultLanguage","getCustomParameters","getScopes","tid","paramsDict","getHandlerBase","WEB_STORAGE_SUPPORT_KEY","BrowserPopupRedirectResolver","eventManagers","originValidationPromises","initAndGetManager","register","iframeEvent","authEvent","onEvent","browserPopupRedirectResolver","MultiFactorAssertionImpl","_finalizeEnroll","_finalizeSignIn","PhoneMultiFactorAssertionImpl","phoneVerificationInfo","PhoneMultiFactorGenerator","_fromCredential","FACTOR_ID","AuthInterop","internalListeners","assertAuthConfigured","unsubscribe","onIdTokenChanged","updateProactiveRefresh","getVersionForPlatform","registerAuth","authInstance","setInstantiationMode","setInstanceCreatedCallback","_instanceIdentifier","_instance","authInternalProvider","_cordovaWindow","REDIRECT_TIMEOUT_MS","_generateHandlerUrl","BuildInfo","sessionDigest","computeSha256","iosBundleId","_performRedirect","handlerUrl","cordova","plugins","browsertab","isAvailable","browserTabIsAvailable","iabRef","openUrl","InAppBrowser","_waitForAppResume","eventListener","cleanup","onCloseTimer","authEventSeen","closeBrowserTab","resumed","visibilityChanged","addPassiveListener","removePassiveListener","_checkCordovaConfiguration","_j","_k","win","universalLinks","subscribe","missingPlugin","bytes","stringToArrayBuffer","buf","subtle","digest","arr","num","str","buff","SESSION_ID_LENGTH","passiveListeners","initPromise","resolveInialized","_generateNewEvent","generateSessionId","_savePartialEvent","_getAndRemoveEvent","_eventFromPartialAndUrl","partialEvent","callbackUrl","_getDeepLinkFromCallback","searchParamsOrEmpty","errorObject","parseJsonOrNull","decodeURIComponent","idx","INITIAL_EVENT_TIMEOUT_MS","attachCallbackListeners","initialized","resetRedirect","_cb","handleOpenURL","noEventTimeout","generateNoEvent","universalLinksCb","eventData","finalEvent","existingHandleOpenURL","packagePrefix","cordovaPopupRedirectResolver","addFrameworkForLogging","_logFramework","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","SERVICE","SERVICE_NAME","ERROR_DESCRIPTION_MAP","ERROR_FACTORY","isServerError","getInstallationsEndpoint","extractAuthTokenInfoFromResponse","requestStatus","getExpiresInFromResponseExpiresIn","getErrorFromResponse","requestName","responseJson","errorData","serverCode","serverMessage","serverStatus","getHeaders","Accept","getHeadersWithAuth","appConfig","append","getAuthorizationHeader","retryIfServerError","responseExpiresIn","createInstallationRequest","fid","endpoint","heartbeatService","authVersion","sdkVersion","responseValue","registeredInstallationEntry","registrationStatus","authToken","sleep","bufferToBase64UrlSafe","array","b64","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","b64String","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","broadcastFidChange","callbacks","channel","getBroadcastChannel","closeBroadcastChannel","broadcastChannel","BroadcastChannel","onmessage","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","dbPromise","getDbPromise","tx","updateFn","getInstallationEntry","installations","registrationPromise","installationEntry","oldEntry","updateOrCreateInstallationEntry","entryWithPromise","triggerRegistrationIfNecessary","entry","clearTimedOutRequest","registrationPromiseWithError","inProgressEntry","registrationTime","registerInstallation","waitUntilFidRegistration","updateInstallationRequest","hasInstallationRequestTimedOut","generateAuthTokenRequest","getGenerateAuthTokenEndpoint","installation","completedAuthToken","refreshAuthToken","tokenPromise","isEntryRegistered","oldAuthToken","isAuthTokenValid","waitUntilAuthTokenRequest","makeAuthTokenRequestInProgressEntry","fetchAuthTokenFromServer","updateAuthTokenRequest","hasAuthTokenRequestTimedOut","updatedInstallationEntry","isAuthTokenExpired","inProgressAuthToken","requestTime","getId","installationsImpl","completeInstallationRegistration","extractAppConfig","getMissingValueError","configKeys","keyName","valueName","INSTALLATIONS_NAME","INSTALLATIONS_NAME_INTERNAL","publicFactory","_delete","installationsInternal","registerInstallations","ANALYTICS_TYPE","GA_FID_KEY","ORIGIN_KEY","FETCH_TIMEOUT_MILLIS","DYNAMIC_CONFIG_URL","GTAG_URL","promiseAllSettled","insertScriptTag","dataLayerName","measurementId","script","src","head","getOrCreateDataLayer","dataLayer","gtagOnConfig","gtagCore","initializationPromisesMap","dynamicConfigPromisesList","measurementIdToAppId","gtagParams","correspondingAppId","dynamicConfigResults","foundConfig","gtagOnEvent","initializationPromisesToWaitFor","gaSendToList","sendToId","initializationPromise","wrapGtag","gtagWrapper","command","idOrNameOrParams","wrapOrCreateGtag","gtagFunctionName","_args","wrappedGtag","findGtagScriptOnPage","scriptTags","tag","ERRORS","LONG_RETRY_FACTOR","BASE_INTERVAL_MILLIS","RetryData","throttleMetadata","intervalMillis","defaultRetryData","fetchDynamicConfig","appFields","appUrl","jsonResponse","_ignored","httpStatus","responseMessage","fetchDynamicConfigWithRetry","retryData","timeoutMillis","getThrottleMetadata","backoffCount","throttleEndTimeMillis","signal","AnalyticsAbortSignal","attemptFetchDynamicConfigWithRetry","setAbortableTimeout","deleteThrottleMetadata","isRetriableError","backoffMillis","setThrottleMetadata","validateIndexedDB","errorInfo","_initializeAnalytics","dynamicConfigPromise","fidPromise","envIsValid","dynamicConfig","configProperties","gtagCoreFunction","wrappedGtagFunction","gtagName","globalInitDone","warnOnBrowserContextMismatch","mismatchedEnvMessages","details","err","analyticsInstance","logEvent$1","gtagFunction","eventName","eventParams","global","setCurrentScreen$1","setUserId$1","setUserProperties$1","properties","flatProperties","setAnalyticsCollectionEnabled$1","enabled","isDBOpenable","setCurrentScreen","setUserId","setUserProperties","setAnalyticsCollectionEnabled","logEvent","registerAnalytics","internalFactory","analytics","analyticsOptions","EventName","analyticsServiceExp","namespaceExports","Analytics","registerComponent","setServiceProps","setMultipleInstances","registerVersion","APP_CHECK_STATES","DEFAULT_STATE","activated","tokenObservers","DEBUG_STATE","getState","setState","getDebugState","BASE_ENDPOINT","EXCHANGE_RECAPTCHA_TOKEN_METHOD","EXCHANGE_RECAPTCHA_ENTERPRISE_TOKEN_METHOD","EXCHANGE_DEBUG_TOKEN_METHOD","TOKEN_REFRESH_TIME","OFFSET_DURATION","RETRIAL_MIN_WAIT","RETRIAL_MAX_WAIT","ONE_DAY","retryPolicy","getWaitDuration","pending","nextErrorWaitInterval","hasSucceeded","getNextRun","currentErrorWaitInterval","getRecaptcha","isEnterprise","enterprise","ensureActivated","uuidv4","getDurationString","durationInMillis","totalSeconds","round","days","hours","minutes","pad","exchangeToken","responseBody","originalError","originalErrorMessage","ttl","timeToLiveAsNumber","attestationToken","expireTimeMillis","issuedAtTimeMillis","getExchangeRecaptchaV3TokenRequest","reCAPTCHAToken","getExchangeRecaptchaEnterpriseTokenRequest","getExchangeDebugTokenRequest","debugToken","debug_token","STORE_NAME","DEBUG_TOKEN_KEY","getDBPromise","readTokenFromIndexedDB","computeKey","writeTokenToIndexedDB","writeDebugTokenToIndexedDB","readDebugTokenFromIndexedDB","compositeKey","_event","readTokenFromStorage","writeTokenToStorage","readOrCreateDebugTokenFromStorage","existingDebugToken","newToken","isDebugMode","debugState","getDebugToken","initializeDebugMode","globals","FIREBASE_APPCHECK_DEBUG_TOKEN","deferredToken","defaultTokenErrorData","formatDummyToken","tokenErrorData","encodeString","getToken$2","cachedToken","cachedTokenPromise","isValid","interopTokenResult","shouldCallListeners","exchangeTokenPromise","tokenFromDebugExchange","makeDummyTokenResult","notifyTokenListeners","tokenObserver","validToken","initTokenRefresher","newObservers","tokenRefresher","refresher","createTokenRefresher","isTokenAutoRefreshEnabled","nextRefreshTimeMillis","latestAllowableRefresh","observers","RECAPTCHA_URL","RECAPTCHA_ENTERPRISE_URL","initializeV3","reCAPTCHAState","divId","makeDiv","queueWidgetRender","loadReCAPTCHAV3Script","initializeEnterprise","loadReCAPTCHAEnterpriseScript","renderInvisibleWidget","invisibleDiv","display","getToken$1","_reject","_siteKey","_throttleData","throwIfThrottled","attestedClaimsToken","_heartbeatServiceProvider","setBackoff","time","allowRequestsAfter","otherProvider","_customProviderOptions","issuedAtTimeSeconds","throttleData","initializeAppCheck","log","isInitialized","initialOptions","getOptions","_activate","newState","automaticDataCollectionEnabled","setTokenAutoRefreshEnabled","appCheckInstance","onTokenChanged","onNextOrObserver","onCompletion","nextFn","errorFn","APP_CHECK_NAME","APP_CHECK_NAME_INTERNAL","registerAppCheck","_identifier","_appcheckService","siteKeyOrProvider","ReCaptchaEnterpriseProvider","ReCaptchaV3Provider","CustomProvider","validateBoolean","fnName","argumentName","bool","validateEventType","onComplete","priority","setWithPriority","objectToMerge","newObjectToMerge","_database","val","exportVal","hasChild","expDataSnapshot","hasChildren","ref","getRef","cancelCallbackOrContext","ret","getCancelAndContextArgs_","valueCallback","expSnapshot","previousChildName","userCallback","cancelCallback","failureCallbackOrContext","onlyOnce","other","cancelOrContext","_repo","pathString","newVal","newPriority","transactionUpdate","applyLocally","transactionResult","expPromise","expRef","getParent","getRoot","childRef","apiName","initStandalone","customAuthImpl","namespace","nodeAdmin","authProvider","setComponent","ServerValue","TIMESTAMP","delta","__proto__","registerDatabase","instanceIdentifier","databaseExp","Reference","Query","Database","DataSnapshot","enableLogging","validateSetOptions","assertUint8ArrayAvailable","assertBase64Available","base64","isPartialObserver","implementsAnyMethods","methods","databaseIdOrApp","_persistenceProvider","_appCompat","settingsLiteral","currentSettings","experimentalForceOwningTab","enableMultiTabIndexedDbPersistence","enableIndexedDbPersistence","clearIndexedDbPersistence","_removeServiceInstance","arg","replaceFunctionName","WriteBatch","bundleData","expQuery","forKey","level","documentRef","castReference","dataOrField","moreFieldsAndValues","modelObject","converterMapByFirestore","INSTANCES","untypedConverterByConverter","fieldOrUpdateData","extractSnapshotOptions","wrapObserver","snap","withConverter","getInstance","updated","wrapper","userObserver","opStr","directionStr","DocumentChange","docChange","thisArg","docRef","documentPath","fieldNames","delegate","firestoreNamespace","Firestore","GeoPoint","Timestamp","Blob","Transaction","DocumentReference","DocumentSnapshot","QueryDocumentSnapshot","QuerySnapshot","CollectionReference","FieldPath","FieldValue","CACHE_SIZE_UNLIMITED","configureForFirebase","firestoreFactory","firestoreExp","registerFirestore","LONG_TYPE","UNSIGNED_LONG_TYPE","mapValues","valueOf","FUNCTIONS_TYPE","errorCodeMap","codeForHTTPStatus","_errorForResponse","bodyJSON","description","errorJSON","ContextProvider","messagingProvider","appCheckProvider","messaging","Notification","permission","getAuthToken","messagingToken","getMessagingToken","appCheckToken","getAppCheckToken","DEFAULT_REGION","failAfter","millis","regionOrCustomDomain","emulatorOrigin","contextProvider","cancelAllRequests","deleteService","customDomain","region","connectFunctionsEmulator$1","functionsInstance","httpsCallable$1","postJSON","_url","failAfterHandle","responseData","decodedData","AUTH_INTERNAL_NAME","APP_CHECK_INTERNAL_NAME","MESSAGING_INTERNAL_NAME","registerFunctions","variant","connectFunctionsEmulator","httpsCallable","_region","_customDomain","functionsServiceExp","Functions","DEFAULT_SW_PATH","DEFAULT_SW_SCOPE","DEFAULT_VAPID_KEY","ENDPOINT","CONSOLE_CAMPAIGN_ID","CONSOLE_CAMPAIGN_NAME","CONSOLE_CAMPAIGN_TIME","CONSOLE_CAMPAIGN_ANALYTICS_ENABLED","MessageType$1","MessageType","arrayToBase64","uint8Array","base64String","base64ToArray","padding","repeat","rawData","outputArray","OLD_DB_NAME","OLD_DB_VERSION","OLD_OBJECT_STORE_NAME","migrateOldDatabase","senderId","databases","dbNames","tokenDetails","upgradeTransaction","oldDetails","p256dh","fcmToken","subscriptionOptions","swScope","vapidKey","checkTokenDetails","upgradeDb","dbGet","firebaseDependencies","oldTokenDetails","dbSet","dbRemove","ERROR_MAP","requestGetToken","getBody","subscribeOptions","getEndpoint","requestUpdateToken","updateOptions","requestDeleteToken","unsubscribeOptions","web","applicationPubKey","TOKEN_EXPIRATION_MS","getTokenInternal","pushSubscription","getPushSubscription","swRegistration","isTokenValid","updateToken","getNewToken","deleteTokenInternal","pushManager","getSubscription","updatedToken","updatedTokenDetails","userVisibleOnly","applicationServerKey","dbOptions","currentOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","externalizePayload","internalPayload","collapseKey","collapse_key","messageId","fcmMessageId","propagateNotificationPayload","propagateDataPayload","propagateFcmOptions","messagePayloadInternal","notification","title","image","fcmOptions","analyticsLabel","analytics_label","isConsoleMessage","_mergeStrings","s1","s2","resultArray","messagingSenderId","MessagingService","analyticsProvider","deliveryMetricsExportedToBigQueryEnabled","onBackgroundMessageHandler","onMessageHandler","logEvents","isLogServiceStarted","registerDefaultSw","browserErrorMessage","updateSwReg","ServiceWorkerRegistration","updateVapidKey","requestPermission","serviceWorkerRegistration","logToScion","messageType","getEventType","message_id","message_name","message_time","message_device_time","NOTIFICATION_CLICKED","PUSH_RECEIVED","messageEventListener","isFirebaseMessaging","dataPayload","WindowMessagingFactory","WindowMessagingInternalFactory","messagingInternal","registerMessagingInWindow","deleteToken$1","onMessage$1","deleteToken","FCM_MSG","SDK_PLATFORM_WEB","EVENT_MESSAGE_DELIVERED","stageLog","fcmEvent","createFcmEvent","createAndEnqueueLogEvent","project_number","instance_id","message_type","DISPLAY_NOTIFICATION","DATA_MESSAGE","sdk_platform","package_name","event_time_ms","source_extension_json_proto3","onSubChange","newSubscription","onPush","getMessagePayloadInternal","clientList","getClientList","hasVisibleClients","sendMessagePayloadInternalToWindows","showNotification","wrapInternalPayload","onNotificationClick","stopImmediatePropagation","getLink","originUrl","getWindowClient","clients","openWindow","wrappedInternalPayload","clientUrl","matchAll","includeUncontrolled","notificationPayloadInternal","actions","maxActions","click_action","SwMessagingFactory","waitUntil","registerMessagingInSw","onBackgroundMessage$1","onBackgroundMessage","PushSubscription","messagingCompatFactory","NAMESPACE_EXPORTS","registerMessagingCompat","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","DEFAULT_MAX_OPERATION_RETRY_TIME","DEFAULT_MAX_UPLOAD_RETRY_TIME","prependCode","_baseMessage","unknown","objectNotFound","quotaExceeded","bucket","unauthenticated","unauthorizedApp","unauthorized","retryLimitExceeded","canceled","invalidUrl","invalidDefaultBucket","noDefaultBucket","cannotSliceBlob","serverFileWrongSize","noDownloadURL","invalidArgument","appDeleted","invalidRootOperation","invalidFormat","format","internalError","Location","path_","encodeURIComponent","bucketString","bucketLocation","makeFromUrl","bucketDomain","gsModify","loc","gsPath","gsRegex","gsIndices","httpModify","firebaseStorageHost","firebaseStoragePath","firebaseStorageRegExp","firebaseStorageIndices","cloudStorageHost","cloudStoragePath","cloudStorageRegExp","cloudStorageIndices","groups","regex","indices","postModify","group","captures","bucketValue","pathValue","FailRequest","promise_","_appDelete","waitSeconds","retryTimeoutId","globalTimeoutId","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","clearGlobalTimeout","success","mustStop","waitMillis","stopped","wasTimeout","isJustDef","isFunction","isNonArrayObject","isString","isNativeBlob","isNativeBlobDefined","validateNumber","argument","minValue","makeUrl","urlPart","makeQueryString","queryPart","nextPart","ErrorCode","NetworkRequest","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","callback_","errorCallback_","timeout_","progressCallback_","connectionFactory_","pendingConnection_","backoffId_","canceled_","appDelete_","resolve_","reject_","start_","doTheRequest","backoffCallback","RequestEndStatus","connection","progressListener","progressEvent","loaded","total","lengthComputable","addUploadProgressListener","removeUploadProgressListener","hitServer","getErrorCode","isRetryStatusCode_","wasCanceled","ABORT","successCode","backoffDone","requestWentThrough","wasSuccessCode","getErrorText","appDelete","isFiveHundredCode","extraRetryCodes","isExtraRetryCode","isRequestSpecificRetryCode","addAuthHeader_","addVersionHeader_","firebaseVersion","addGmpidHeader_","addAppCheckHeader_","makeRequest","requestInfo","requestFactory","urlParams","successCodes","additionalRetryCodes","errorHandler","progressCallback","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob$1","bb","getBlob","sliceBlob","end","webkitSlice","mozSlice","decodeBase64","encoded","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","StringData","contentType","dataFromString","stringData","utf8Bytes_","base64Bytes_","dataURLBytes_","dataURLContentType_","b","valid","percentEncodedBytes_","hasMinus","hasUnder","invalidChar","hasPlus","hasSlash","DataURLParts","dataURL","middle","endsWith","dataUrl","parts","longEnough","FbsBlob","elideCopy","blobType","data_","size_","type_","startByte","endByte","realBlob","sliced","blobby","uint8Arrays","finalLength","merged","jsonObjectOrNull","lastIndexOf","newPath","childPath","canonicalChildPath","component","lastComponent","noXform_","Mapping","server","local","writable","xform","mappings_","xformPath","fullPath","getMappings","mappings","mappingsXformPath","_metadata","nameMapping","xformSize","sizeMapping","addRef","service","generateRef","_makeStorageReference","defineProperty","fromResource","resource","mapping","fromResourceString","resourceString","downloadUrlFromResourceString","tokens","tokensList","urls","queryString","alt","toResourceString","PREFIXES_KEY","ITEMS_KEY","fromBackendResponse","listResult","prefixes","items","nextPageToken","pathWithoutTrailingSlash","reference","item","fromResponseString","RequestInfo","handlerCheck","cndn","metadataHandler","xhr","text","listHandler","downloadUrlHandler","_protocol","sharedErrorHandler","newErr","objectErrorHandler","shared","getMetadata$2","fullServerUrl","maxOperationRetryTime","list$2","delimiter","pageToken","maxResults","isRoot","bucketOnlyServerUrl","getDownloadUrl","updateMetadata$2","deleteObject$2","_xhr","_text","determineContentType_","metadataForUpload_","metadataClone","multipartUpload","genBoundary","boundary","metadata_","metadataString","preBlobPart","postBlobPart","maxUploadRetryTime","uploadData","ResumableUploadStatus","finalized","checkResumeHeader_","allowed","getResponseHeader","allowedStatus","createResumableUpload","metadataForUpload","getResumableUploadStatus","sizeString","RESUMABLE_UPLOAD_CHUNK_SIZE","continueResumableUpload","chunkSize","status_","bytesLeft","bytesToUpload","uploadCommand","uploadStatus","newCurrent","TaskEvent","STATE_CHANGED","TaskState","RUNNING","PAUSED","SUCCESS","CANCELED","taskStateFromInternalTaskState","Observer","asFunctions","argsToForward","textFactoryOverride","XhrConnection","sent_","xhr_","XMLHttpRequest","initXhr","errorCode_","sendPromise_","NETWORK_ERROR","setRequestHeader","statusText","header","upload","XhrTextConnection","responseType","newTextConnection","UploadTask","_transferred","_needToFetchStatus","_needToFetchMetadata","_observers","_error","_uploadUrl","_request","_chunkMultiplier","_resolve","_ref","_blob","_mappings","_resumable","_shouldDoResumable","_state","_errorHandler","_codeEquals","completeTransitions_","_transition","_metadataErrorHandler","_promise","sizeBefore","_createResumable","_fetchStatus","_fetchMetadata","_continueUpload","_oneShotUpload","_getAuthToken","_getAppCheckToken","_resolveToken","_location","createRequest","_makeRequest","getPromise","statusRequest","_makeProgressCallback","uploadRequest","newStatus","_increaseMultiplier","currentSize","metadataRequest","multipartRequest","transferred","old","_notifyObservers","wasPaused","externalState","bytesTransferred","task","_addObserver","_removeObserver","onFulfilled","onRejected","_notifyObserver","_finishPromise","triggered","toCall","_service","_newRef","uploadBytesResumable$1","_throwIfRoot","listAll$1","accumulator","listAllHelper","nextPage","list$1","makeRequestWithTokens","getMetadata$1","updateMetadata$1","getDownloadURL$1","deleteObject$1","_getChild$1","isUrl","refFromURL","refFromPath","FirebaseStorageImpl","_bucket","ref$1","serviceOrRef","pathOrUrl","extractBucket","makeFromBucketSpec","connectStorageEmulator$1","_overrideAuthToken","_authProvider","_appCheckProvider","_firebaseVersion","_host","_appId","_maxOperationRetryTime","_maxUploadRetryTime","_requests","tokenData","STORAGE_TYPE","uploadBytesResumable","list","listAll","getDownloadURL","deleteObject","_getChild","connectStorageEmulator","registerStorage","UploadTaskSnapshotCompat","UploadTaskCompat","pause","resume","wrappedNextOrObserver","taskSnapshot","ListResultCompat","storageExp","storageServiceCompat","Storage","SDK_VERSION","TRACE_START_MARK_PREFIX","TRACE_STOP_MARK_PREFIX","TRACE_MEASURE_PREFIX","OOB_TRACE_PAGE_LOAD_PREFIX","FIRST_PAINT_COUNTER_NAME","FIRST_CONTENTFUL_PAINT_COUNTER_NAME","FIRST_INPUT_DELAY_COUNTER_NAME","CONFIG_LOCAL_STORAGE_KEY","CONFIG_EXPIRY_LOCAL_STORAGE_KEY","consoleLogger","apiInstance","windowInstance","iid","settingsServiceInstance","INFO","performance","PerformanceObserver","windowLocation","cookieEnabled","perfMetrics","onFirstInputDelay","mark","measureName","mark1","mark2","measure","getEntriesByType","getEntriesByName","timeOrigin","timing","navigationStart","entryType","observe","entryTypes","setupApi","getIidPromise","installationsService","iidPromise","iidVal","getIid","getAuthTokenPromise","authTokenPromise","authTokenVal","mergeStrings","part1","part2","sizeDiff","SettingsService","instrumentationEnabled","dataCollectionEnabled","loggingEnabled","tracesSamplingRate","networkRequestsSamplingRate","logEndPointUrl","flTransportEndpointUrl","transportKey","logSource","logTraceAfterSampling","logNetworkAfterSampling","configTimeToLive","VisibilityState","RESERVED_ATTRIBUTE_PREFIXES","ATTRIBUTE_FORMAT_REGEX","MAX_ATTRIBUTE_NAME_LENGTH","MAX_ATTRIBUTE_VALUE_LENGTH","getServiceWorkerStatus","getVisibilityState","VISIBLE","HIDDEN","getEffectiveConnectionType","navigatorConnection","effectiveType","isValidCustomAttributeName","matchesReservedPrefix","isValidCustomAttributeValue","getAppId","firebaseApp","getProjectId","getApiKey","REMOTE_CONFIG_SDK_VERSION","DEFAULT_CONFIGS","FIS_AUTH_PREFIX","getConfig","performanceController","getStoredConfig","processConfig","getRemoteConfig","storeConfig","expiryString","configValid","configStringified","configResponse","COULD_NOT_GET_CONFIG_MSG","configEndPoint","Request","Authorization","app_instance_id","app_instance_id_token","app_id","app_version","sdk_version","fpr_enabled","fpr_log_source","fpr_log_endpoint_url","fpr_log_transport_key","fpr_vc_network_request_sampling_rate","fpr_vc_trace_sampling_rate","shouldLogAfterSampling","expiry","samplingRate","initializationStatus","getInitializationPromise","initializePerf","isPerfInitialized","getDocumentReadyComplete","changeInitializationStatus","DEFAULT_SEND_INTERVAL_MS","INITIAL_SEND_TIME_DELAY_MS","DEFAULT_REMAINING_TRIES","MAX_EVENT_COUNT_PER_REQUEST","remainingTries","isTransportSetup","setupTransportService","processQueue","timeOffset","dispatchQueueEvents","staged","log_event","evt","eventTime","request_time_ms","client_info","client_type","js_client_info","log_source","sendEventsToFl","postToFlEndpoint","res","transportWait","nextRequestWaitMillis","requestOffset","logResponseDetails","responseAction","flTransportFullUrl","getFlTransportFullUrl","addToQueue","transportHandler","serializer","sendLog","resourceType","logTrace","trace","settingsService","isAuto","requiredApisAvailable","sendTraceLog","logNetworkRequest","networkRequest","networkRequestUrl","logEndpointUrl","flEndpointUrl","serializeNetworkRequest","serializeTrace","networkRequestMetric","http_method","httpMethod","http_response_code","response_payload_bytes","responsePayloadBytes","client_start_time_us","startTimeUs","time_to_response_initiated_us","timeToResponseInitiatedUs","time_to_response_completed_us","timeToResponseCompletedUs","perfMetric","application_info","getApplicationInfo","network_request_metric","traceMetric","is_auto","duration_us","durationUs","counters","customAttributes","getAttributes","custom_attributes","trace_metric","google_app_id","web_app_info","page_url","getUrl","service_worker_status","visibility_state","effective_connection_type","application_process_state","MAX_METRIC_NAME_LENGTH","RESERVED_AUTO_PREFIX","oobMetrics","isValidMetricName","traceName","convertMetricValueToInteger","providedValue","valueAsInteger","Trace","traceMeasureName","api","randomId","traceStartMark","traceStopMark","traceMeasure","calculateTraceMetrics","startTime","duration","metrics","metricName","numAsInteger","putMetric","customMetricName","attr","isValidName","isValidValue","attributeName","attributeValue","perfMeasureEntries","perfMeasureEntry","getTimeOrigin","navigationTimings","paintTimings","firstInputDelay","route","timeOriginUs","setStartTime","setDuration","domInteractive","domContentLoadedEventEnd","loadEventEnd","FIRST_PAINT","FIRST_CONTENTFUL_PAINT","firstPaint","paintObject","firstContentfulPaint","createNetworkRequestEntry","performanceEntry","responseStart","responseEnd","transferSize","FID_WAIT_TIME_MS","setupOobResources","setupOobTraces","setupNetworkRequests","setupUserTimingTraces","resources","setupObserver","timeoutId","createOobTrace","measures","createUserTimingTrace","DEFAULT_ENTRY_NAME","perfInstance","_init","registerPerformance","registerPerformanceCompat","firebaseInstance","performanceFactory","RemoteConfigAbortSignal","RC_COMPONENT_NAME","hasErrorCode","errorCode","DEFAULT_VALUE_FOR_BOOLEAN","DEFAULT_VALUE_FOR_STRING","DEFAULT_VALUE_FOR_NUMBER","BOOLEAN_TRUTHY_VALUES","Value","_source","_value","activate","remoteConfig","lastSuccessfulFetchResponse","activeConfigEtag","_storage","getLastSuccessfulFetchResponse","getActiveConfigEtag","eTag","_storageCache","setActiveConfig","setActiveConfigEtag","ensureInitialized","_initializePromise","loadFromStorage","_isInitializationComplete","fetchConfig","abortSignal","fetchTimeoutMillis","_client","cacheMaxAgeMillis","minimumFetchIntervalMillis","setLastFetchStatus","lastFetchStatus","getAllKeys","getActiveConfig","defaultConfig","allConfigs","getValue","getBoolean","asBoolean","getNumber","asNumber","getString","asString","_logger","activeConfig","SILENT","obj1","obj2","CachingClient","storageCache","logger","lastSuccessfulFetchTimestampMillis","cacheAgeMillis","isCachedDataFresh","getLastSuccessfulFetchTimestampMillis","storageOperations","setLastSuccessfulFetchTimestampMillis","setLastSuccessfulFetchResponse","getUserLanguage","RestClient","firebaseInstallations","installationId","installationToken","urlBase","FIREBASE_REMOTE_CONFIG_URL_BASE","requestBody","language_code","fetchPromise","timeoutPromise","responseEtag","attemptFetch","DEFAULT_FETCH_TIMEOUT_MILLIS","DEFAULT_CACHE_MAX_AGE_MILLIS","RemoteConfig","getLastFetchStatus","toFirebaseError","APP_NAMESPACE_STORE","openDatabase","openDbPromise","etag","createCompositeKey","StorageCache","lastFetchStatusPromise","lastSuccessfulFetchTimestampMillisPromise","activeConfigPromise","timestampMillis","registerRemoteConfig","remoteConfigFactory","restClient","retryingClient","cachingClient","remoteConfigInstance","fetchAndActivate","fetchTimeMillis","registerRemoteConfigCompat","name$1","version$1","setSDKVersion","DOMStorageWrapper","domStorage_","prefix_","prefixedName_","storedVal","MemoryStorage","cache_","isInMemoryStorage","createStoragefor","domStorageName","domStorage","PersistentStorage","SessionStorage","LUIDGenerator","sha1","utf8Bytes","sha1Bytes","encodeByteArray","buildLogMessage_","varArgs","firstLog_","enableLogging$1","logger_","persistent","VERBOSE","logWrapper","fatal","warnIfPageIsSecure","isInvalidJSONNumber","executeWhenDOMReady","called","wrappedFn","attachEvent","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","ObjectToUniqueKey","splitStringBySize","segsize","dataSegs","each","doubleToIEEE754String","ebits","fbits","bias","Infinity","abs","LN2","bits","hexByteString","hexByte","parseInt","isChromeExtensionContentScript","isWindowsStoreApp","Windows","UI","errorForServerCode","toUpperCase","INTEGER_REGEXP_","INTEGER_32_MIN","INTEGER_32_MAX","intVal","exceptionGuard","beingCrawled","setTimeoutNonBlocking","AppCheckTokenProvider","appName_","FirebaseAuthTokenProvider","firebaseOptions_","authProvider_","auth_","EmulatorTokenProvider","OWNER","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN_RE","LAST_SESSION_PARAM","APPLICATION_ID_PARAM","APP_CHECK_TOKEN_PARAM","WEBSOCKET","LONG_POLLING","RepoInfo","secure","webSocketOnly","includeNamespaceInQueryParams","_domain","internalHost","newHost","isCacheableHost","toURLString","repoInfoNeedsQueryParam","repoInfo","isCustomHost","repoInfoConnectionURL","connURL","pairs","StatsCollection","counters_","amount","collections","reporters","statsManagerGetCollection","hashString","statsManagerGetOrCreateReporter","creatorFunction","PacketReceiver","onMessage_","pendingResponses","currentResponseNum","closeAfterResponse","onClose","responseNum","requestNum","toProcess","FIREBASE_LONGPOLL_START_PARAM","FIREBASE_LONGPOLL_CLOSE_COMMAND","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","FIREBASE_LONGPOLL_ID_PARAM","FIREBASE_LONGPOLL_PW_PARAM","FIREBASE_LONGPOLL_SERIAL_PARAM","FIREBASE_LONGPOLL_CALLBACK_ID_PARAM","FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM","FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET","FIREBASE_LONGPOLL_DATA_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","MAX_URL_DATA_SIZE","SEG_HEADER_SIZE","MAX_PAYLOAD_SIZE","KEEPALIVE_REQUEST_INTERVAL","LP_CONNECT_TIMEOUT","BrowserPollConnection","connId","applicationId","transportSessionId","lastSessionId","bytesSent","bytesReceived","everConnected_","log_","stats_","urlFn","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","FirebaseIFrameScriptHolder","arg1","arg2","arg3","arg4","incrementIncomingBytes_","sendNewPolls","closeAfter","pN","handleResponse","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow_","forceDisallow_","myDisconnFrame","shutdown_","dataStr","incrementCounter","base64data","enqueueSegment","pw","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","currentDomain","iframeContents","contentWindow","contentDocument","alive","innerHTML","myID","myPW","newRequest_","theURL","curDataString","nextSeg","theSeg","seg","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript","onreadystatechange","rstate","parentNode","WEBSOCKET_MAX_FRAME_SIZE","WEBSOCKET_KEEPALIVE_INTERVAL","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","platform","env","proxy","mySock","onopen","onclose","handleIncomingFrame","isOldAndroid","oldAndroidRegex","oldAndroidMatch","parseFloat","fullMess","jsonMess","frameCount","handleNewFrameCount_","mess","resetKeepAlive","appendFrame_","remainingData","extractFrameCount_","sendString_","responsesRequiredToBeHealthy","healthyTimeout","TransportManager","initTransports_","isWebSocketsAvailable","isSkipPollConnection","previouslyFailed","transports_","transports","transport","ALL_TRANSPORTS","UPGRADE_TIMEOUT","DELAY_BEFORE_SENDING_EXTRA_REQUESTS","BYTES_SENT_HEALTHY_OVERRIDE","BYTES_RECEIVED_HEALTHY_OVERRIDE","MESSAGE_TYPE","MESSAGE_DATA","CONTROL_SHUTDOWN","CONTROL_RESET","CONTROL_ERROR","CONTROL_PONG","SWITCH_ACK","END_TRANSMISSION","PING","SERVER_HELLO","Connection","repoInfo_","applicationId_","appCheckToken_","authToken_","onReady_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","conn","initialTransport","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeoutMS","healthyTimeout_","markConnectionHealthy","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","sendData_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","onSecondaryControl_","proceedWithUpgrade_","tryCleanupConnection","onControl_","onDataMessage_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","onConnectionEstablished_","tryStartUpgrade_","upgradeTransport","startUpgrade_","closeConnections_","ServerActions","hash","stats","EventEmitter","allowedEvents_","listeners_","validateEventType_","getInitialEvent","OnlineMonitor","online_","trigger","MAX_PATH_DEPTH","MAX_PATH_LENGTH_BYTES","Path","pathOrString","pieceNum","pieces_","copyTo","pieceNum_","newEmptyPath","pathGetFront","pathGetLength","pathPopFront","pathGetBack","pathToUrlEncodedString","pathSlice","begin","pathParent","pieces","pathChild","childPathObj","childPieces","pathIsEmpty","newRelativePath","outerPath","innerPath","outer","pathCompare","leftKeys","rightKeys","cmp","pathEquals","pathContains","ValidationPath","errorPrefix_","parts_","byteLength_","validationPathCheckValid","validationPathPush","validationPath","validationPathPop","validationPathToErrorString","VisibilityMonitor","hidden","visibilityChange","visible_","visible","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","GET_CONNECT_TIMEOUT","RECONNECT_MAX_DELAY_FOR_ADMINS","RECONNECT_DELAY_MULTIPLIER","RECONNECT_DELAY_RESET_TIMEOUT","SERVER_KILL_INTERRUPT_REASON","INVALID_TOKEN_THRESHOLD","PersistentConnection","onDataUpdate_","onConnectStatus_","onServerInfoUpdate_","authTokenProvider_","appCheckTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens","outstandingPuts_","outstandingGets_","outstandingPutCount_","outstandingGetCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","forceTokenRefresh_","invalidAuthTokenCount_","invalidAppCheckTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","onVisible_","onOnline_","onResponse","curReqNum","sendRequest","initConnection_","_queryObject","outstandingGet","sendGet_","currentHashFn","queryId","_queryIdentifier","_queryParams","isDefault","loadsAllData","listenSpec","hashFn","sendListen_","req","warnOnListenWarnings_","currentListenSpec","removeListen_","warnings","indexSpec","getIndex","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","isFirebaseSecret","tryAppCheck","authMethod","requestData","onAuthRevoked_","onAppCheckRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","putInternal","sendPut_","queued","errorReason","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","handleTimestamp_","sendConnectStats_","restoreState_","establishConnection_","scheduleConnect_","online","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage","onReady","onRealtimeDisconnect_","nextConnectionId_","closeFn","sendRequestFn","interrupt","serverTimeOffset","normalizedPathString","statusCode","explanation","notifyForInvalidToken","clientName","reportStats","currentlyOnline","NamedNode","Index","compare","oldNode","newNode","oldWrapped","newWrapped","MIN","__EMPTY_NODE","KeyIndex","indexValue","KEY_INDEX","SortedMapIterator","startKey","isReverse_","resultGenerator_","nodeStack_","LLRBNode","SortedMap","EMPTY_NODE","min_","fixUp_","isRed_","moveRedLeft_","removeMin_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","blackDepth","check_","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","MAX_NODE$2","setMaxNode$1","priorityHashText","validatePriorityNode","priorityNode","isLeafNode","getPriority","__childrenNodeConstructor","nodeFromJSON$1","MAX_NODE$1","LeafNode","value_","priorityNode_","lazyHash_","newPriorityNode","childName","childNode","newChildNode","updatePriority","updateImmediateChild","front","updateChild","exportFormat","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","equals","setNodeFromJSON","setMaxNode","PriorityIndex","aPriority","bPriority","indexCmp","PRIORITY_INDEX","LOG_2","Base12Num","logBase2","bitMask","current_","mask","bits_","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","low","high","namedNode","buildFrom12Array","base12","buildPennant","childTree","attachPennant","pennant","isOne","nextBitIsOne","_defaultIndexMap","fallbackObject","IndexMap","indexes_","indexSet_","indexKey","sortedMap","indexDefinition","existingChildren","sawIndexedValue","Wrap","isDefinedOn","getCompare","indexName","newIndexSet","newIndexes","indexedChildren","existingSnap","newChildren","ChildrenNode","children_","indexMap_","Default","getImmediateChild","getChild","newIndexMap","removeFromIndexes","addToIndexes","newImmediateChild","numKeys","allIntegerKeys","forEachChild","childHash","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","getLastChildName","wrappedNode","minPost","startPost","peek","getReverseIteratorFrom","maxPost","endPost","MAX_NODE","hasIndex","addIndex","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","defineProperties","MAX","USE_HINZE","nodeFromJSON","jsonLeaf","childData","children","childrenHavePriority","hinzeJsonObj","childSet","sortedChildSet","PathIndex","indexPath_","aChild","extractChild","bChild","valueNode","ValueIndex","VALUE_INDEX","PUSH_CHARS","MIN_PUSH_CHAR","MAX_PUSH_CHAR","MAX_KEY_LEN","nextPushId","lastPushTime","lastRandChars","duplicateTime","timeStampChars","successor","keyAsInt","sourcePlusOne","changeValue","snapshotNode","changeChildAdded","changeChildRemoved","changeChildChanged","oldSnap","changeChildMoved","IndexedFilter","index_","newChild","affectedPath","optChangeAccumulator","isIndexed","oldChild","trackChildChange","withIndex","newSnap","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","filtered","updateFullNode","hasStart","startName","getIndexStartName","makePost","getIndexStartValue","hasEnd","endName","getIndexEndName","getIndexEndValue","LimitedFilter","rangedFilter_","limit_","getLimit","reverse_","isViewFromLeft","numChildren","getIndexedFilter","fullLimitUpdateChild_","inRange","getReverseIterator","indexCompare","foundStartPost","childKey","childSnap","changeAccumulator","oldEventCache","newChildNamedNode","windowBoundary","getFirstChild","getLastChild","oldChildSnap","nextChild","getChildAfterChild","compareNext","remainsInWindow","newEventCache","nextChildInRange","QueryParams","limitSet_","startSet_","startNameSet_","startAfterSet_","endSet_","endNameSet_","endBeforeSet_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","queryParamsGetNodeFilter","queryParams","hasLimit","queryParamsLimitToFirst","newLimit","newParams","queryParamsLimitToLast","queryParamsStartAt","queryParamsStartAfter","queryParamsEndAt","queryParamsEndBefore","queryParamsOrderBy","queryParamsToRestQueryStringParameters","queryParamsGetQueryObject","viewFrom","ReadonlyRestClient","listens_","listenId","getListenId_","thisListen","queryStringParameters","restRequest_","responseText","SnapshotHolder","rootNode_","newSnapshotNode","newSparseSnapshotTree","sparseSnapshotTreeRemember","sparseSnapshotTree","sparseSnapshotTreeForget","tree","safeToRemove","sparseSnapshotTreeForEachTree","func","sparseSnapshotTreeForEachChild","StatsListener","collection_","last_","newStats","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","REPORT_STATS_INTERVAL","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","reportedStats","haveStatsToReport","OperationType","newOperationSourceUser","fromUser","fromServer","tagged","newOperationSourceServer","newOperationSourceServerTaggedQuery","AckUserWrite","affectedTree","revert","ACK_USER_WRITE","subtree","ListenComplete","LISTEN_COMPLETE","Overwrite","OVERWRITE","Merge","MERGE","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isCompleteForChild","EventGenerator","query_","eventGeneratorGenerateEventsForChanges","eventGenerator","eventCache","eventRegistrations","events","moves","change","indexedValueChanged","eventGeneratorGenerateEventsForType","registrations","filteredChanges","eventGeneratorCompareChanges","materializedChange","eventGeneratorMaterializeSingleChange","respondsTo","prevName","getPredecessorChildName","aWrapped","bWrapped","newViewCache","serverCache","viewCacheUpdateEventSnap","viewCache","eventSnap","viewCacheUpdateServerSnap","serverSnap","viewCacheGetCompleteEventSnap","getNode","viewCacheGetCompleteServerSnap","emptyChildrenSingleton","EmptyChildren","ImmutableTree","relativePath","predicate","childExistingPathAndValue","findRootMostMatchingPathAndValue","toSet","newTree","setTree","fold_","pathSoFar","findOnPath_","pathToFollow","foreachOnPath_","currentRelativePath","foreach_","CompoundWrite","writeTree_","compoundWriteAddWrite","compoundWrite","rootmost","findRootMostValueAndPath","rootMostPath","newWriteTree","compoundWriteAddWrites","newWrite","compoundWriteRemoveWrite","compoundWriteHasCompleteWrite","compoundWriteGetCompleteNode","compoundWriteGetCompleteChildren","compoundWriteChildCompoundWrite","shadowingNode","compoundWriteIsEmpty","compoundWriteApply","applySubtreeWrite","writeTree","priorityWrite","writeTreeChildWrites","newWriteTreeRef","writeTreeAddOverwrite","writeId","lastWriteId","allWrites","visibleWrites","writeTreeAddMerge","changedChildren","writeTreeGetWrite","record","writeTreeRemoveWrite","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","writeTreeRecordContainsPath_","writeTreeResetTree_","writeRecord","writeTreeLayerTree_","writeTreeDefaultFilter_","treeRoot","writePath","deepNode","writeTreeCalcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","mergeAtPath","layeredCache","subMerge","writeTreeCalcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","writeTreeCalcEventCacheAfterServerOverwrite","existingEventSnap","existingServerSnap","childMerge","writeTreeCalcCompleteChild","writeTreeShadowingWrite","writeTreeCalcIndexedSlice","completeServerData","toIterate","nodes","writeTreeRefCalcCompleteEventCache","writeTreeRef","writeTreeRefCalcCompleteEventChildren","writeTreeRefCalcEventCacheAfterServerOverwrite","writeTreeRefShadowingWrite","writeTreeRefCalcIndexedSlice","writeTreeRefCalcCompleteChild","existingServerCache","writeTreeRefChild","ChildChangeAccumulator","changeMap","oldChange","oldType","NoCompleteChildSource_","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","newViewProcessor","viewProcessorAssertIndexed","viewProcessor","viewProcessorApplyOperation","oldViewCache","writesCache","completeCache","filterServerNode","overwrite","viewProcessorApplyUserOverwrite","isFiltered","viewProcessorApplyServerOverwrite","viewProcessorApplyUserMerge","viewProcessorApplyServerMerge","ackUserWrite","viewProcessorRevertUserWrite","viewProcessorAckUserWrite","viewProcessorListenComplete","getChanges","viewProcessorMaybeAddValueEvent","isLeafOrEmpty","oldCompleteSnap","viewProcessorGenerateEventCacheAfterServerEvent","changePath","oldEventSnap","completeEventChildren","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","filtersNodes","changedSnap","oldServerSnap","newServerCache","serverFilter","newServerNode","isCompleteForPath","getCompleteChild","newEventSnap","viewProcessorCacheHasChild","curViewCache","foreach","viewProcessorApplyMerge","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","mergePath","serverCachePath","oldServerNode","serverChildren","View","initialViewCache","eventRegistrations_","indexFilter","processor_","initialServerCache","initialEventCache","eventGenerator_","viewGetServerCache","viewGetCompleteNode","viewGetCompleteServerCache","cache","viewIsEmpty","viewAddEventRegistration","eventRegistration","viewRemoveEventRegistration","cancelError","cancelEvents","maybeEvent","createCancelEvent","remaining","hasAnyCallback","viewApplyOperation","viewGenerateEventsForChanges_","viewGetInitialEvents","initialChanges","eventNode","referenceConstructor$1","referenceConstructor","SyncPoint","views","syncPointSetReferenceConstructor","syncPointGetReferenceConstructor","syncPointIsEmpty","syncPoint","syncPointApplyOperation","optCompleteServerCache","syncPointGetView","serverCacheComplete","eventCacheComplete","syncPointAddEventRegistration","syncPointRemoveEventRegistration","removed","hadCompleteView","syncPointHasCompleteView","viewQueryId","syncPointGetQueryViews","syncPointGetCompleteServerCache","syncPointViewForQuery","syncPointGetCompleteView","syncPointViewExistsForQuery","syncTreeSetReferenceConstructor","syncTreeGetReferenceConstructor","syncTreeNextQueryTag_","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","tagToQueryMap","queryToTagMap","syncTreeApplyUserOverwrite","syncTree","syncTreeApplyOperationToSyncPoints_","syncTreeApplyUserMerge","changeTree","fromObject","syncTreeAckUserWrite","needToReevaluate","syncTreeApplyServerOverwrite","syncTreeApplyServerMerge","syncTreeApplyListenComplete","syncTreeApplyTaggedListenComplete","queryKey","syncTreeQueryKeyForTag_","syncTreeParseQueryKey_","queryPath","syncTreeApplyTaggedOperation_","syncTreeRemoveEventRegistration","maybeSyncPoint","removedAndEvents","removingDefault","covered","findOnPath","parentSyncPoint","newViews","syncTreeCollectDistinctViewsForSubTree_","newQuery","syncTreeCreateListenerForView_","startListening","syncTreeQueryForListening_","syncTreeTagForQuery_","defaultTag","stopListening","queryToRemove","tagToRemove","syncTreeMakeQueryKey_","syncTreeRemoveTags_","syncTreeApplyTaggedQueryOverwrite","syncTreeApplyTaggedQueryMerge","syncTreeAddEventRegistration","foundAncestorDefaultView","foreachOnPath","pathToSyncPoint","sp","foreachChild","childSyncPoint","viewAlreadyExists","syncTreeGetNextQueryTag_","syncTreeSetupListener_","syncTreeCalcCompleteEventCache","includeHiddenSets","syncTreeGetServerValue","serverCacheNode","syncTreeApplyOperationHelper_","syncPointTree","syncTreeApplyOperationDescendantsHelper_","childOperation","operationForChild","childServerCache","childWritesCache","splitIndex","fold","maybeChildSyncPoint","childMap","completeView","childViews","removedQuery","removedQueryKey","removedQueryTag","queriesToStop","childQueries","queryToStop","ExistingValueProvider","DeferredValueProvider","syncTree_","generateWithValues","resolveDeferredLeafValue","existingVal","serverValues","resolveScalarDeferredValue","resolveComplexDeferredValue","unused","existingNode","leaf","resolveDeferredValueTree","resolveDeferredValue","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","Tree","childCount","treeSubTree","pathObj","treeGetValue","treeSetValue","treeUpdateParents","treeHasChildren","treeIsEmpty","treeForEachChild","treeForEachDescendant","includeSelf","childrenFirst","treeForEachAncestor","treeGetPath","treeUpdateChild","childEmpty","childExists","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidRootPathString","isValidPriority","validateFirebaseDataArg","validateFirebaseData","errorPrefix","hasDotValue","hasActualChild","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","errorPrefix$1","validatePriority","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","EventQueue","eventLists_","recursionDepth_","eventQueueQueueEvents","eventQueue","eventDataList","currList","getPath","eventQueueRaiseEventsAtPath","eventQueueRaiseQueuedEventsMatchingPredicate","eventPath","eventQueueRaiseEventsForChangedPath","changedPath","sentAll","eventList","eventListRaise","eventFn","getEventRunner","INTERRUPT_REASON","MAX_TRANSACTION_RETRIES","Repo","forceRestClient_","appCheckProvider_","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","transactionQueueTree_","persistentConnection_","repoStart","repo","authOverride","isMerge","repoOnDataUpdate","repoOnConnectStatus","connectStatus","repoOnServerInfoUpdate","addTokenChangeListener","refreshAppCheckToken","statsReporter_","infoData_","infoSyncTree_","infoEvents","repoUpdateInfo","serverSyncTree_","unlisten","repoServerTime","offsetNode","repoGenerateServerValues","taggedChildren","raw","taggedSnap","repoRerunTransactions","repoRunOnDisconnectEvents","updateSnapshot","repoGetNextWriteId","repoGetValue","cached","repoLog","repoSetWithPriority","newNodeUnresolved","clearEvents","repoCallOnCompleteCallback","repoAbortTransactions","repoUpdate","childrenToMerge","changedKey","changedValue","resolvedOnDisconnectTree","resolved","repoOnDisconnectCancel","onDisconnectCancel","repoOnDisconnectSet","onDisconnectPut","repoOnDisconnectSetWithPriority","repoOnDisconnectUpdate","onDisconnectMerge","repoAddEventCallbackForQuery","repoRemoveEventCallbackForQuery","repoInterrupt","repoResume","repoStartTransaction","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","repoGetLatestState","queueNode","nodeQueue","priorityForNode","currentNode","repoSendReadyTransactions","excludeSets","repoPruneCompletedTransactionsBelowNode","repoBuildTransactionQueue","allRun","repoSendTransactionQueue","setsToIgnore","txn","latestState","snapToSend","latestHash","dataToSend","pathToSend","rootMostTransactionNode","repoGetAncestorTransactionNode","repoRerunTransactionQueue","txnsToRerun","abortTransaction","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","transactionNode","transactionQueue","repoAggregateTransactionQueuesForNode","repoAbortTransactionsOnNode","lastSent","decodePath","pathStringDecoded","piece","decodeQuery","segment","kv","parseRepoInfo","parseDatabaseURL","scheme","subdomain","colonInd","slashInd","questionMarkInd","hostWithoutPort","dotInd","DataEvent","CancelEvent","CallbackContext","snapshotCallback","hasCancelCallback","OnDisconnect","wrapCallback","QueryImpl","_orderByCalled","ReferenceImpl","sameRepo","samePath","sameQueryIdentifier","validateNoPreviousOrderByCall","validateQueryEndpoints","startNode","endNode","tooManyArgsError","wrongArgTypeError","validateLimit","hasAnchoredLimit","parentPath","_node","_index","_checkNotDeleted","_root","parsedURL","thennablePushRef","pushRef","setPriority","ValueEventRegistration","callbackContext","onCancel","onValue","ChildEventRegistration","eventToCheck","cancelCallbackOrListenOptions","onceCallback","dataSnapshot","onChildAdded","onChildChanged","onChildMoved","onChildRemoved","off","expCallback","QueryConstraint","QueryEndAtConstraint","QueryEndBeforeConstraint","endBefore","QueryStartAtConstraint","QueryStartAfterConstraint","startAfter","QueryLimitToFirstConstraint","_limit","limitToFirst","QueryLimitToLastConstraint","limitToLast","QueryOrderByChildConstraint","parsedPath","orderByChild","QueryOrderByKeyConstraint","orderByKey","QueryOrderByPriorityConstraint","orderByPriority","QueryOrderByValueConstraint","orderByValue","QueryEqualToValueConstraint","equalTo","queryConstraints","queryImpl","constraint","FIREBASE_DATABASE_EMULATOR_HOST_VAR","repos","useRestClient","repoManagerApplyEmulatorSettings","tokenProvider","repoManagerDatabaseFromApp","dbUrl","databaseURL","isEmulator","dbEmulatorHost","authTokenProvider","repoManagerCreateRepo","repoManagerDeleteRepo","appRepos","_repoInternal","_instanceStarted","_rootInternal","connectDatabaseEmulator","goOffline","goOnline","SERVER_TIMESTAMP","serverTimestamp","TransactionResult","promiseComplete","simpleListen","echo","onEcho","CORDOVA_ONDEVICEREADY_TIMEOUT_MS","_isAndroidOrIosCordovaScheme","_isNativeEnvironment","_isIe11","_isEdge","_isLocalStorageNotSynchronized","_isWebStorageSupported","_isPopupRedirectSupported","_isLikelyCordova","_isCordova","_getSelfWindow","Persistence","LOCAL","NONE","SESSION","_assert$3","PERSISTENCE_KEY","_validatePersistenceArgument","_savePersistenceForRedirect","getSessionStorageIfAvailable","_getPersistence","_getPersistencesFromRedirect","_assert$2","CompatPopupRedirectResolver","browserResolver","cordovaResolver","underlyingResolver","selectUnderlyingResolver","assertedUnderlyingResolver","isCordova","unwrap","wrapped","credentialFromResponse","credentialFromObject","attachExtraErrorFields","mfaErr","MultiFactorResolver","credErr","credentialFromResult","credentialFromError","convertCredential","credentialPromise","additionalUserInfo","User","getOrCreate","convertConfirmationResult","confirmationResultPromise","confirmationResultExp","confirm","resolveSignIn","USER_MAP","phoneCredential","_assert$1","Auth","linkUnderlyingAuth","buildPersistenceHierarchy","useDeviceLanguage","wrapObservers","onAuthStateChanged","converted","isIndexedDBFullySupported","updateCurrentUser","oldNext","newNext","persistences","PhoneAuthProvider","verifyPhoneNumber","AUTH_TYPE","registerAuthCompat","ActionCodeInfo","Operation","commonjsGlobal","globalThis","esm","goog","unshift","Vb","trim","w","defaultPrevented","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","pointerId","pointerType","changedTouches","srcElement","nodeName","fromElement","toElement","pageX","pageY","2","3","4","preventDefault","returnValue","capture","ab","fb","once","gb","hb","ib","jb","kb","lb","addListener","removeListener","mb","nb","ob","detachEvent","pb","qb","rb","sb","tb","ub","vb","Ab","wb","yb","zb","Bb","Cb","Db","Eb","Fb","Gb","Hb","Ib","E","Jb","Kb","Lb","Mb","Nb","Ob","Pb","Qb","Rb","Sb","Tb","Ub","Wb","xb","Xb","Yb","Zb","$b","eb","Dc","Lc","Qc","Sc","ad","bd","decodeURI","encodeURI","cd","dd","ed","fd","gd","hd","PerformanceNavigationTiming","nextHopProtocol","jd","kd","ld","md","nd","Image","od","qd","rd","ud","td","sd","arrayBuffer","getAllResponseHeaders","vd","wd","xd","yd","Bd","zd","Cd","Dd","Ed","Ad","mozResponseArrayBuffer","Fd","Gd","Hd","Id","concurrentRequestLimit","fastHandshake","Jd","Kd","sendBeacon","Ld","Md","Nd","Od","Qd","Pd","Rd","Sd","Td","messageHeaders","clientProtocolHeaderRequired","messageContentType","Ud","__sm__","Vd","FormData","withCredentials","__data__","getLastError","createWebChannelTransport","getStatEventTarget","Event","Stat","FetchXmlHttpFactory","WebChannel","XhrIo"],"mappings":"mHAAA,qzEAMA,MAAMA,EAAI;;;;;;;;;;;;;;;;GAsBV,MAAMC,EACF,YAAYC,GACRC,KAAKC,IAAMF,EAEf,kBACI,OAAO,MAAQC,KAAKC,IAKjB,QACH,OAAOD,KAAKE,kBAAoB,OAASF,KAAKC,IAAM,iBAExD,QAAQF,GACJ,OAAOA,EAAEE,MAAQD,KAAKC,KAICH,EAAEK,gBAAkB,IAAIL,EAAE,MAGzDA,EAAEM,mBAAqB,IAAIN,EAAE,0BAA2BA,EAAEO,YAAc,IAAIP,EAAE,mBAC9EA,EAAEQ,UAAY,IAAIR,EAAE;;;;;;;;;;;;;;;;;AAkBpB,IAAIS,EAAI;;;;;;;;;;;;;;;;GAkBR,MAAMC,EAAI,IAAI,OAAO,uBAGrB,SAASC,IACL,OAAOD,EAAEE,SAeT,SAASC,EAAEZ,GACXS,EAAEI,YAAYb,GAGlB,SAASc,EAAEd,KAAMe,GACb,GAAIN,EAAEE,UAAY,OAASK,MAAO,CAC9B,MAAMC,EAAIF,EAAEG,IAAIC,GAChBV,EAAEW,MAAM,cAAcZ,OAAOR,OAAQiB,IAI7C,SAASI,EAAErB,KAAMe,GACb,GAAIN,EAAEE,UAAY,OAASW,MAAO,CAC9B,MAAML,EAAIF,EAAEG,IAAIC,GAChBV,EAAEc,MAAM,cAAcf,OAAOR,OAAQiB,IAMzC,SAASO,EAAExB,KAAMe,GACjB,GAAIN,EAAEE,UAAY,OAASc,KAAM,CAC7B,MAAMR,EAAIF,EAAEG,IAAIC,GAChBV,EAAEiB,KAAK,cAAclB,OAAOR,OAAQiB,IAMxC,SAASE,EAAEnB,GACX,GAAI,iBAAmBA,EAAG,OAAOA,EACjC,IACI,OAAOe,EAAIf,EAAG2B,KAAKC,UAAUb,GAC/B,MAAOA,GAEL,OAAOf;;;;;;;;;;;;;;;;GAmBX,IAAIe;;;;;;;;;;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G,EAAEF,GAAG,EAAEF,GAAG,EAAEK,GAAG,EAAE/mJ,MAAM,GAAGC,QAAQ,GAAGumJ,GAAG,GAAGL,GAAG,GAAGC,GAAG,GAAGF,GAAG,GAAGI,GAAG,GAAGC,GAAG,GAAGxB,GAAG,GAAGD,GAAG,GAAGE,GAAG,IAAQkH,GAAsB/J,EAAI+J,oBAAoBzvH,GAAO0vH,GAAahK,EAAIgK,WAAW5E,GACxiB6E,GAAQjK,EAAIiK,MAAM7oL,K","file":"js/chunk-361113c6.05f80b00.js","sourcesContent":["import { _registerComponent, registerVersion, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { FirebaseError, createMockUserToken, getModularInstance, deepEqual, getUA, isIndexedDBAvailable, isSafari, isMobileCordova, isReactNative, isElectron, isIE, isUWP, isBrowserExtension } from '@firebase/util';\nimport { XhrIo, EventType, ErrorCode, createWebChannelTransport, getStatEventTarget, FetchXmlHttpFactory, WebChannel, Event, Stat } from '@firebase/webchannel-wrapper';\n\nconst D = \"@firebase/firestore\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nclass C {\n constructor(t) {\n this.uid = t;\n }\n isAuthenticated() {\n return null != this.uid;\n }\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */ toKey() {\n return this.isAuthenticated() ? \"uid:\" + this.uid : \"anonymous-user\";\n }\n isEqual(t) {\n return t.uid === this.uid;\n }\n}\n\n/** A user with a null UID. */ C.UNAUTHENTICATED = new C(null), \n// TODO(mikelehen): Look into getting a proper uid-equivalent for\n// non-FirebaseAuth providers.\nC.GOOGLE_CREDENTIALS = new C(\"google-credentials-uid\"), C.FIRST_PARTY = new C(\"first-party-uid\"), \nC.MOCK_USER = new C(\"mock-user\");\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet x = \"9.6.11\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst N = new Logger(\"@firebase/firestore\");\n\n// Helper methods are needed because variables can't be exported as read/write\nfunction k() {\n return N.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * \n */ function M(t) {\n N.setLogLevel(t);\n}\n\nfunction O(t, ...e) {\n if (N.logLevel <= LogLevel.DEBUG) {\n const n = e.map(B);\n N.debug(`Firestore (${x}): ${t}`, ...n);\n }\n}\n\nfunction F(t, ...e) {\n if (N.logLevel <= LogLevel.ERROR) {\n const n = e.map(B);\n N.error(`Firestore (${x}): ${t}`, ...n);\n }\n}\n\n/**\n * @internal\n */ function $(t, ...e) {\n if (N.logLevel <= LogLevel.WARN) {\n const n = e.map(B);\n N.warn(`Firestore (${x}): ${t}`, ...n);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */ function B(t) {\n if (\"string\" == typeof t) return t;\n try {\n return e = t, JSON.stringify(e);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return t;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /** Formats an object as a JSON string, suitable for logging. */\n var e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */ function L(t = \"Unexpected state\") {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const e = `FIRESTORE (${x}) INTERNAL ASSERTION FAILED: ` + t;\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw F(e), new Error(e);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */ function U(t, e) {\n t || L();\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */ function q(t, e) {\n t || L();\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */ function K(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n return t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const G = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: \"ok\",\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: \"cancelled\",\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: \"unknown\",\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: \"invalid-argument\",\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: \"deadline-exceeded\",\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: \"not-found\",\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: \"already-exists\",\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: \"permission-denied\",\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: \"unauthenticated\",\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: \"resource-exhausted\",\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: \"failed-precondition\",\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: \"aborted\",\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: \"out-of-range\",\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: \"unimplemented\",\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: \"internal\",\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: \"unavailable\",\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: \"data-loss\"\n};\n\n/** An error returned by a Firestore operation. */ class Q extends FirebaseError {\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n t, \n /**\n * A custom error description.\n */\n e) {\n super(t, e), this.code = t, this.message = e, \n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class j {\n constructor() {\n this.promise = new Promise(((t, e) => {\n this.resolve = t, this.reject = e;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class W {\n constructor(t, e) {\n this.user = e, this.type = \"OAuth\", this.headers = new Map, this.headers.set(\"Authorization\", `Bearer ${t}`);\n }\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */ class z {\n getToken() {\n return Promise.resolve(null);\n }\n invalidateToken() {}\n start(t, e) {\n // Fire with initial user.\n t.enqueueRetryable((() => e(C.UNAUTHENTICATED)));\n }\n shutdown() {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */ class H {\n constructor(t) {\n this.token = t, \n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.changeListener = null;\n }\n getToken() {\n return Promise.resolve(this.token);\n }\n invalidateToken() {}\n start(t, e) {\n this.changeListener = e, \n // Fire with initial user.\n t.enqueueRetryable((() => e(this.token.user)));\n }\n shutdown() {\n this.changeListener = null;\n }\n}\n\nclass J {\n constructor(t) {\n this.t = t, \n /** Tracks the current User. */\n this.currentUser = C.UNAUTHENTICATED, \n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n this.i = 0, this.forceRefresh = !1, this.auth = null;\n }\n start(t, e) {\n let n = this.i;\n // A change listener that prevents double-firing for the same token change.\n const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let i = new j;\n this.o = () => {\n this.i++, this.currentUser = this.u(), i.resolve(), i = new j, t.enqueueRetryable((() => s(this.currentUser)));\n };\n const r = () => {\n const e = i;\n t.enqueueRetryable((async () => {\n await e.promise, await s(this.currentUser);\n }));\n }, o = t => {\n O(\"FirebaseAuthCredentialsProvider\", \"Auth detected\"), this.auth = t, this.auth.addAuthTokenListener(this.o), \n r();\n };\n this.t.onInit((t => o(t))), \n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout((() => {\n if (!this.auth) {\n const t = this.t.getImmediate({\n optional: !0\n });\n t ? o(t) : (\n // If auth is still not available, proceed with `null` user\n O(\"FirebaseAuthCredentialsProvider\", \"Auth not yet detected\"), i.resolve(), i = new j);\n }\n }), 0), r();\n }\n getToken() {\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const t = this.i, e = this.forceRefresh;\n return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e => \n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n this.i !== t ? (O(\"FirebaseAuthCredentialsProvider\", \"getToken aborted due to token change.\"), \n this.getToken()) : e ? (U(\"string\" == typeof e.accessToken), new W(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.auth && this.auth.removeAuthTokenListener(this.o);\n }\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n u() {\n const t = this.auth && this.auth.getUid();\n return U(null === t || \"string\" == typeof t), new C(t);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */ class Y {\n constructor(t, e, n) {\n this.type = \"FirstParty\", this.user = C.FIRST_PARTY, this.headers = new Map, this.headers.set(\"X-Goog-AuthUser\", e);\n const s = t.auth.getAuthHeaderValueForFirstParty([]);\n s && this.headers.set(\"Authorization\", s), n && this.headers.set(\"X-Goog-Iam-Authorization-Token\", n);\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */ class X {\n constructor(t, e, n) {\n this.h = t, this.l = e, this.m = n;\n }\n getToken() {\n return Promise.resolve(new Y(this.h, this.l, this.m));\n }\n start(t, e) {\n // Fire with initial uid.\n t.enqueueRetryable((() => e(C.FIRST_PARTY)));\n }\n shutdown() {}\n invalidateToken() {}\n}\n\nclass Z {\n constructor(t) {\n this.value = t, this.type = \"AppCheck\", this.headers = new Map, t && t.length > 0 && this.headers.set(\"x-firebase-appcheck\", this.value);\n }\n}\n\nclass tt {\n constructor(t) {\n this.g = t, this.forceRefresh = !1, this.appCheck = null, this.p = null;\n }\n start(t, e) {\n const n = t => {\n null != t.error && O(\"FirebaseAppCheckTokenProvider\", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);\n const n = t.token !== this.p;\n return this.p = t.token, O(\"FirebaseAppCheckTokenProvider\", `Received ${n ? \"new\" : \"existing\"} token.`), \n n ? e(t.token) : Promise.resolve();\n };\n this.o = e => {\n t.enqueueRetryable((() => n(e)));\n };\n const s = t => {\n O(\"FirebaseAppCheckTokenProvider\", \"AppCheck detected\"), this.appCheck = t, this.appCheck.addTokenListener(this.o);\n };\n this.g.onInit((t => s(t))), \n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout((() => {\n if (!this.appCheck) {\n const t = this.g.getImmediate({\n optional: !0\n });\n t ? s(t) : \n // If AppCheck is still not available, proceed without it.\n O(\"FirebaseAppCheckTokenProvider\", \"AppCheck not yet detected\");\n }\n }), 0);\n }\n getToken() {\n const t = this.forceRefresh;\n return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (U(\"string\" == typeof t.token), \n this.p = t.token, new Z(t.token)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.appCheck && this.appCheck.removeTokenListener(this.o);\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */ class et {\n getToken() {\n return Promise.resolve(new Z(\"\"));\n }\n invalidateToken() {}\n start(t, e) {}\n shutdown() {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nclass nt {\n constructor(t, e) {\n this.previousValue = t, e && (e.sequenceNumberHandler = t => this.I(t), this.T = t => e.writeSequenceNumber(t));\n }\n I(t) {\n return this.previousValue = Math.max(t, this.previousValue), this.previousValue;\n }\n next() {\n const t = ++this.previousValue;\n return this.T && this.T(t), t;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nfunction st(t) {\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const e = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n \"undefined\" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);\n if (e && \"function\" == typeof e.getRandomValues) e.getRandomValues(n); else \n // Falls back to Math.random\n for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());\n return n;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ nt.A = -1;\n\nclass it {\n static R() {\n // Alphanumeric characters\n const t = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", e = Math.floor(256 / t.length) * t.length;\n // The largest byte value that is a multiple of `char.length`.\n let n = \"\";\n for (;n.length < 20; ) {\n const s = st(40);\n for (let i = 0; i < s.length; ++i) \n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));\n }\n return n;\n }\n}\n\nfunction rt(t, e) {\n return t < e ? -1 : t > e ? 1 : 0;\n}\n\n/** Helper to compare arrays using isEqual(). */ function ot(t, e, n) {\n return t.length === e.length && t.every(((t, s) => n(t, e[s])));\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */ function ut(t) {\n // Return the input string, with an additional NUL byte appended.\n return t + \"\\0\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nclass at {\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n t, \n /**\n * The fractions of a second at nanosecond resolution.*\n */\n e) {\n if (this.seconds = t, this.nanoseconds = e, e < 0) throw new Q(G.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (e >= 1e9) throw new Q(G.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (t < -62135596800) throw new Q(G.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n // This will break in the year 10,000.\n if (t >= 253402300800) throw new Q(G.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n }\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */ static now() {\n return at.fromMillis(Date.now());\n }\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */ static fromDate(t) {\n return at.fromMillis(t.getTime());\n }\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */ static fromMillis(t) {\n const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));\n return new at(e, n);\n }\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */ toDate() {\n return new Date(this.toMillis());\n }\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */ toMillis() {\n return 1e3 * this.seconds + this.nanoseconds / 1e6;\n }\n _compareTo(t) {\n return this.seconds === t.seconds ? rt(this.nanoseconds, t.nanoseconds) : rt(this.seconds, t.seconds);\n }\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */ isEqual(t) {\n return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;\n }\n /** Returns a textual representation of this `Timestamp`. */ toString() {\n return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n }\n /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {\n return {\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */ valueOf() {\n // This method returns a string of the form . where\n // is translated to have a non-negative value and both \n // and are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const t = this.seconds - -62135596800;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n return String(t).padStart(12, \"0\") + \".\" + String(this.nanoseconds).padStart(9, \"0\");\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */ class ct {\n constructor(t) {\n this.timestamp = t;\n }\n static fromTimestamp(t) {\n return new ct(t);\n }\n static min() {\n return new ct(new at(0, 0));\n }\n static max() {\n return new ct(new at(253402300799, 999999999));\n }\n compareTo(t) {\n return this.timestamp._compareTo(t.timestamp);\n }\n isEqual(t) {\n return this.timestamp.isEqual(t.timestamp);\n }\n /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {\n // Convert to microseconds.\n return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;\n }\n toString() {\n return \"SnapshotVersion(\" + this.timestamp.toString() + \")\";\n }\n toTimestamp() {\n return this.timestamp;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function ht(t) {\n let e = 0;\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;\n return e;\n}\n\nfunction lt(t, e) {\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);\n}\n\nfunction ft(t) {\n for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;\n return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Path represents an ordered sequence of string segments.\n */\nclass dt {\n constructor(t, e, n) {\n void 0 === e ? e = 0 : e > t.length && L(), void 0 === n ? n = t.length - e : n > t.length - e && L(), \n this.segments = t, this.offset = e, this.len = n;\n }\n get length() {\n return this.len;\n }\n isEqual(t) {\n return 0 === dt.comparator(this, t);\n }\n child(t) {\n const e = this.segments.slice(this.offset, this.limit());\n return t instanceof dt ? t.forEach((t => {\n e.push(t);\n })) : e.push(t), this.construct(e);\n }\n /** The index of one past the last segment of the path. */ limit() {\n return this.offset + this.length;\n }\n popFirst(t) {\n return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);\n }\n popLast() {\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n firstSegment() {\n return this.segments[this.offset];\n }\n lastSegment() {\n return this.get(this.length - 1);\n }\n get(t) {\n return this.segments[this.offset + t];\n }\n isEmpty() {\n return 0 === this.length;\n }\n isPrefixOf(t) {\n if (t.length < this.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n isImmediateParentOf(t) {\n if (this.length + 1 !== t.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n forEach(t) {\n for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);\n }\n toArray() {\n return this.segments.slice(this.offset, this.limit());\n }\n static comparator(t, e) {\n const n = Math.min(t.length, e.length);\n for (let s = 0; s < n; s++) {\n const n = t.get(s), i = e.get(s);\n if (n < i) return -1;\n if (n > i) return 1;\n }\n return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */ class _t extends dt {\n construct(t, e, n) {\n return new _t(t, e, n);\n }\n canonicalString() {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join(\"/\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */ static fromString(...t) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n const e = [];\n for (const n of t) {\n if (n.indexOf(\"//\") >= 0) throw new Q(G.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);\n // Strip leading and traling slashed.\n e.push(...n.split(\"/\").filter((t => t.length > 0)));\n }\n return new _t(e);\n }\n static emptyPath() {\n return new _t([]);\n }\n}\n\nconst wt = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */ class mt extends dt {\n construct(t, e, n) {\n return new mt(t, e, n);\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */ static isValidIdentifier(t) {\n return wt.test(t);\n }\n canonicalString() {\n return this.toArray().map((t => (t = t.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\"), \n mt.isValidIdentifier(t) || (t = \"`\" + t + \"`\"), t))).join(\".\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns true if this field references the key of a document.\n */ isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }\n /**\n * The field designating the key of a document.\n */ static keyField() {\n return new mt([ \"__name__\" ]);\n }\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */ static fromServerFormat(t) {\n const e = [];\n let n = \"\", s = 0;\n const i = () => {\n if (0 === n.length) throw new Q(G.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);\n e.push(n), n = \"\";\n };\n let r = !1;\n for (;s < t.length; ) {\n const e = t[s];\n if (\"\\\\\" === e) {\n if (s + 1 === t.length) throw new Q(G.INVALID_ARGUMENT, \"Path has trailing escape character: \" + t);\n const e = t[s + 1];\n if (\"\\\\\" !== e && \".\" !== e && \"`\" !== e) throw new Q(G.INVALID_ARGUMENT, \"Path has invalid escape sequence: \" + t);\n n += e, s += 2;\n } else \"`\" === e ? (r = !r, s++) : \".\" !== e || r ? (n += e, s++) : (i(), s++);\n }\n if (i(), r) throw new Q(G.INVALID_ARGUMENT, \"Unterminated ` in path: \" + t);\n return new mt(e);\n }\n static emptyPath() {\n return new mt([]);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */ class gt {\n constructor(t) {\n this.fields = t, \n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n t.sort(mt.comparator);\n }\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */ covers(t) {\n for (const e of this.fields) if (e.isPrefixOf(t)) return !0;\n return !1;\n }\n isEqual(t) {\n return ot(this.fields, t.fields, ((t, e) => t.isEqual(e)));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Converts a Base64 encoded string to a binary string. */\n/** True if and only if the Base64 conversion functions are available. */\nfunction yt() {\n return \"undefined\" != typeof atob;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */ class pt {\n constructor(t) {\n this.binaryString = t;\n }\n static fromBase64String(t) {\n const e = atob(t);\n return new pt(e);\n }\n static fromUint8Array(t) {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const e = \n /**\n * Helper function to convert an Uint8array to a binary string.\n */\n function(t) {\n let e = \"\";\n for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);\n return e;\n }\n /**\n * Helper function to convert a binary string to an Uint8Array.\n */ (t);\n return new pt(e);\n }\n [Symbol.iterator]() {\n let t = 0;\n return {\n next: () => t < this.binaryString.length ? {\n value: this.binaryString.charCodeAt(t++),\n done: !1\n } : {\n value: void 0,\n done: !0\n }\n };\n }\n toBase64() {\n return t = this.binaryString, btoa(t);\n /** Converts a binary string to a Base64 encoded string. */\n var t;\n }\n toUint8Array() {\n return function(t) {\n const e = new Uint8Array(t.length);\n for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);\n return e;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n (this.binaryString);\n }\n approximateByteSize() {\n return 2 * this.binaryString.length;\n }\n compareTo(t) {\n return rt(this.binaryString, t.binaryString);\n }\n isEqual(t) {\n return this.binaryString === t.binaryString;\n }\n}\n\npt.EMPTY_BYTE_STRING = new pt(\"\");\n\nconst It = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */ function Tt(t) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (U(!!t), \"string\" == typeof t) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n let e = 0;\n const n = It.exec(t);\n if (U(!!n), n[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let t = n[1];\n t = (t + \"000000000\").substr(0, 9), e = Number(t);\n }\n // Parse the date to get the seconds.\n const s = new Date(t);\n return {\n seconds: Math.floor(s.getTime() / 1e3),\n nanos: e\n };\n }\n return {\n seconds: Et(t.seconds),\n nanos: Et(t.nanos)\n };\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */ function Et(t) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n return \"number\" == typeof t ? t : \"string\" == typeof t ? Number(t) : 0;\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */ function At(t) {\n return \"string\" == typeof t ? pt.fromBase64String(t) : pt.fromUint8Array(t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */ function Rt(t) {\n var e, n;\n return \"server_timestamp\" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nfunction Pt(t) {\n const e = t.mapValue.fields.__previous_value__;\n return Rt(e) ? Pt(e) : e;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */ function bt(t) {\n const e = Tt(t.mapValue.fields.__local_write_time__.timestampValue);\n return new at(e.seconds, e.nanos);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Vt {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(t, e, n, s, i, r, o, u) {\n this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i, \n this.forceLongPolling = r, this.autoDetectLongPolling = o, this.useFetchStreams = u;\n }\n}\n\n/** The default database name for a project. */\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nclass vt {\n constructor(t, e) {\n this.projectId = t, this.database = e || \"(default)\";\n }\n static empty() {\n return new vt(\"\", \"\");\n }\n get isDefaultDatabase() {\n return \"(default)\" === this.database;\n }\n isEqual(t) {\n return t instanceof vt && t.projectId === this.projectId && t.database === this.database;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Sentinel value that sorts before any Mutation Batch ID. */\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction St(t) {\n return null == t;\n}\n\n/** Returns whether the value represents -0. */ function Dt(t) {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return 0 === t && 1 / t == -1 / 0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */ function Ct(t) {\n return \"number\" == typeof t && Number.isInteger(t) && !Dt(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */ class xt {\n constructor(t) {\n this.path = t;\n }\n static fromPath(t) {\n return new xt(_t.fromString(t));\n }\n static fromName(t) {\n return new xt(_t.fromString(t).popFirst(5));\n }\n static empty() {\n return new xt(_t.emptyPath());\n }\n get collectionGroup() {\n return this.path.popLast().lastSegment();\n }\n /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {\n return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;\n }\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {\n return this.path.get(this.path.length - 2);\n }\n /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {\n return this.path.popLast();\n }\n isEqual(t) {\n return null !== t && 0 === _t.comparator(this.path, t.path);\n }\n toString() {\n return this.path.toString();\n }\n static comparator(t, e) {\n return _t.comparator(t.path, e.path);\n }\n static isDocumentKey(t) {\n return t.length % 2 == 0;\n }\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */ static fromSegments(t) {\n return new xt(new _t(t.slice()));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Nt = {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__max__\"\n }\n }\n }\n}, kt = {\n nullValue: \"NULL_VALUE\"\n};\n\n/** Extracts the backend's type order for the provided value. */\nfunction Mt(t) {\n return \"nullValue\" in t ? 0 /* NullValue */ : \"booleanValue\" in t ? 1 /* BooleanValue */ : \"integerValue\" in t || \"doubleValue\" in t ? 2 /* NumberValue */ : \"timestampValue\" in t ? 3 /* TimestampValue */ : \"stringValue\" in t ? 5 /* StringValue */ : \"bytesValue\" in t ? 6 /* BlobValue */ : \"referenceValue\" in t ? 7 /* RefValue */ : \"geoPointValue\" in t ? 8 /* GeoPointValue */ : \"arrayValue\" in t ? 9 /* ArrayValue */ : \"mapValue\" in t ? Rt(t) ? 4 /* ServerTimestampValue */ : Ht(t) ? 9 /* ArrayValue */ : 10 /* ObjectValue */ : L();\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */ function Ot(t, e) {\n if (t === e) return !0;\n const n = Mt(t);\n if (n !== Mt(e)) return !1;\n switch (n) {\n case 0 /* NullValue */ :\n case 9007199254740991 /* MaxValue */ :\n return !0;\n\n case 1 /* BooleanValue */ :\n return t.booleanValue === e.booleanValue;\n\n case 4 /* ServerTimestampValue */ :\n return bt(t).isEqual(bt(e));\n\n case 3 /* TimestampValue */ :\n return function(t, e) {\n if (\"string\" == typeof t.timestampValue && \"string\" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) \n // Use string equality for ISO 8601 timestamps\n return t.timestampValue === e.timestampValue;\n const n = Tt(t.timestampValue), s = Tt(e.timestampValue);\n return n.seconds === s.seconds && n.nanos === s.nanos;\n }(t, e);\n\n case 5 /* StringValue */ :\n return t.stringValue === e.stringValue;\n\n case 6 /* BlobValue */ :\n return function(t, e) {\n return At(t.bytesValue).isEqual(At(e.bytesValue));\n }(t, e);\n\n case 7 /* RefValue */ :\n return t.referenceValue === e.referenceValue;\n\n case 8 /* GeoPointValue */ :\n return function(t, e) {\n return Et(t.geoPointValue.latitude) === Et(e.geoPointValue.latitude) && Et(t.geoPointValue.longitude) === Et(e.geoPointValue.longitude);\n }(t, e);\n\n case 2 /* NumberValue */ :\n return function(t, e) {\n if (\"integerValue\" in t && \"integerValue\" in e) return Et(t.integerValue) === Et(e.integerValue);\n if (\"doubleValue\" in t && \"doubleValue\" in e) {\n const n = Et(t.doubleValue), s = Et(e.doubleValue);\n return n === s ? Dt(n) === Dt(s) : isNaN(n) && isNaN(s);\n }\n return !1;\n }(t, e);\n\n case 9 /* ArrayValue */ :\n return ot(t.arrayValue.values || [], e.arrayValue.values || [], Ot);\n\n case 10 /* ObjectValue */ :\n return function(t, e) {\n const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};\n if (ht(n) !== ht(s)) return !1;\n for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !Ot(n[t], s[t]))) return !1;\n return !0;\n }\n /** Returns true if the ArrayValue contains the specified element. */ (t, e);\n\n default:\n return L();\n }\n}\n\nfunction Ft(t, e) {\n return void 0 !== (t.values || []).find((t => Ot(t, e)));\n}\n\nfunction $t(t, e) {\n if (t === e) return 0;\n const n = Mt(t), s = Mt(e);\n if (n !== s) return rt(n, s);\n switch (n) {\n case 0 /* NullValue */ :\n case 9007199254740991 /* MaxValue */ :\n return 0;\n\n case 1 /* BooleanValue */ :\n return rt(t.booleanValue, e.booleanValue);\n\n case 2 /* NumberValue */ :\n return function(t, e) {\n const n = Et(t.integerValue || t.doubleValue), s = Et(e.integerValue || e.doubleValue);\n return n < s ? -1 : n > s ? 1 : n === s ? 0 : \n // one or both are NaN.\n isNaN(n) ? isNaN(s) ? 0 : -1 : 1;\n }(t, e);\n\n case 3 /* TimestampValue */ :\n return Bt(t.timestampValue, e.timestampValue);\n\n case 4 /* ServerTimestampValue */ :\n return Bt(bt(t), bt(e));\n\n case 5 /* StringValue */ :\n return rt(t.stringValue, e.stringValue);\n\n case 6 /* BlobValue */ :\n return function(t, e) {\n const n = At(t), s = At(e);\n return n.compareTo(s);\n }(t.bytesValue, e.bytesValue);\n\n case 7 /* RefValue */ :\n return function(t, e) {\n const n = t.split(\"/\"), s = e.split(\"/\");\n for (let t = 0; t < n.length && t < s.length; t++) {\n const e = rt(n[t], s[t]);\n if (0 !== e) return e;\n }\n return rt(n.length, s.length);\n }(t.referenceValue, e.referenceValue);\n\n case 8 /* GeoPointValue */ :\n return function(t, e) {\n const n = rt(Et(t.latitude), Et(e.latitude));\n if (0 !== n) return n;\n return rt(Et(t.longitude), Et(e.longitude));\n }(t.geoPointValue, e.geoPointValue);\n\n case 9 /* ArrayValue */ :\n return function(t, e) {\n const n = t.values || [], s = e.values || [];\n for (let t = 0; t < n.length && t < s.length; ++t) {\n const e = $t(n[t], s[t]);\n if (e) return e;\n }\n return rt(n.length, s.length);\n }(t.arrayValue, e.arrayValue);\n\n case 10 /* ObjectValue */ :\n return function(t, e) {\n const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n s.sort(), r.sort();\n for (let t = 0; t < s.length && t < r.length; ++t) {\n const e = rt(s[t], r[t]);\n if (0 !== e) return e;\n const o = $t(n[s[t]], i[r[t]]);\n if (0 !== o) return o;\n }\n return rt(s.length, r.length);\n }\n /**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */ (t.mapValue, e.mapValue);\n\n default:\n throw L();\n }\n}\n\nfunction Bt(t, e) {\n if (\"string\" == typeof t && \"string\" == typeof e && t.length === e.length) return rt(t, e);\n const n = Tt(t), s = Tt(e), i = rt(n.seconds, s.seconds);\n return 0 !== i ? i : rt(n.nanos, s.nanos);\n}\n\nfunction Lt(t) {\n return Ut(t);\n}\n\nfunction Ut(t) {\n return \"nullValue\" in t ? \"null\" : \"booleanValue\" in t ? \"\" + t.booleanValue : \"integerValue\" in t ? \"\" + t.integerValue : \"doubleValue\" in t ? \"\" + t.doubleValue : \"timestampValue\" in t ? function(t) {\n const e = Tt(t);\n return `time(${e.seconds},${e.nanos})`;\n }(t.timestampValue) : \"stringValue\" in t ? t.stringValue : \"bytesValue\" in t ? At(t.bytesValue).toBase64() : \"referenceValue\" in t ? (n = t.referenceValue, \n xt.fromName(n).toString()) : \"geoPointValue\" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : \"arrayValue\" in t ? function(t) {\n let e = \"[\", n = !0;\n for (const s of t.values || []) n ? n = !1 : e += \",\", e += Ut(s);\n return e + \"]\";\n }\n /** Returns a reference value for the provided database and key. */ (t.arrayValue) : \"mapValue\" in t ? function(t) {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const e = Object.keys(t.fields || {}).sort();\n let n = \"{\", s = !0;\n for (const i of e) s ? s = !1 : n += \",\", n += `${i}:${Ut(t.fields[i])}`;\n return n + \"}\";\n }(t.mapValue) : L();\n var e, n;\n}\n\nfunction qt(t, e) {\n return {\n referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */ function Kt(t) {\n return !!t && \"integerValue\" in t;\n}\n\n/** Returns true if `value` is a DoubleValue. */\n/** Returns true if `value` is an ArrayValue. */\nfunction Gt(t) {\n return !!t && \"arrayValue\" in t;\n}\n\n/** Returns true if `value` is a NullValue. */ function Qt(t) {\n return !!t && \"nullValue\" in t;\n}\n\n/** Returns true if `value` is NaN. */ function jt(t) {\n return !!t && \"doubleValue\" in t && isNaN(Number(t.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */ function Wt(t) {\n return !!t && \"mapValue\" in t;\n}\n\n/** Creates a deep copy of `source`. */ function zt(t) {\n if (t.geoPointValue) return {\n geoPointValue: Object.assign({}, t.geoPointValue)\n };\n if (t.timestampValue && \"object\" == typeof t.timestampValue) return {\n timestampValue: Object.assign({}, t.timestampValue)\n };\n if (t.mapValue) {\n const e = {\n mapValue: {\n fields: {}\n }\n };\n return lt(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = zt(n))), e;\n }\n if (t.arrayValue) {\n const e = {\n arrayValue: {\n values: []\n }\n };\n for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = zt(t.arrayValue.values[n]);\n return e;\n }\n return Object.assign({}, t);\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function Ht(t) {\n return \"__max__\" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;\n}\n\n/** Returns the lowest value for the given value type (inclusive). */ function Jt(t) {\n return \"nullValue\" in t ? kt : \"booleanValue\" in t ? {\n booleanValue: !1\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n doubleValue: NaN\n } : \"timestampValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"stringValue\" in t ? {\n stringValue: \"\"\n } : \"bytesValue\" in t ? {\n bytesValue: \"\"\n } : \"referenceValue\" in t ? qt(vt.empty(), xt.empty()) : \"geoPointValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"arrayValue\" in t ? {\n arrayValue: {}\n } : \"mapValue\" in t ? {\n mapValue: {}\n } : L();\n}\n\n/** Returns the largest value for the given value type (exclusive). */ function Yt(t) {\n return \"nullValue\" in t ? {\n booleanValue: !1\n } : \"booleanValue\" in t ? {\n doubleValue: NaN\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"timestampValue\" in t ? {\n stringValue: \"\"\n } : \"stringValue\" in t ? {\n bytesValue: \"\"\n } : \"bytesValue\" in t ? qt(vt.empty(), xt.empty()) : \"referenceValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"geoPointValue\" in t ? {\n arrayValue: {}\n } : \"arrayValue\" in t ? {\n mapValue: {}\n } : \"mapValue\" in t ? Nt : L();\n}\n\nfunction Xt(t, e) {\n return void 0 === t ? e : void 0 === e || $t(t, e) > 0 ? t : e;\n}\n\nfunction Zt(t, e) {\n return void 0 === t ? e : void 0 === e || $t(t, e) < 0 ? t : e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */ class te {\n constructor(t) {\n this.value = t;\n }\n static empty() {\n return new te({\n mapValue: {}\n });\n }\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */ field(t) {\n if (t.isEmpty()) return this.value;\n {\n let e = this.value;\n for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)], \n !Wt(e)) return null;\n return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;\n }\n }\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */ set(t, e) {\n this.getFieldsMap(t.popLast())[t.lastSegment()] = zt(e);\n }\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */ setAll(t) {\n let e = mt.emptyPath(), n = {}, s = [];\n t.forEach(((t, i) => {\n if (!e.isImmediateParentOf(i)) {\n // Insert the accumulated changes at this parent location\n const t = this.getFieldsMap(e);\n this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();\n }\n t ? n[i.lastSegment()] = zt(t) : s.push(i.lastSegment());\n }));\n const i = this.getFieldsMap(e);\n this.applyChanges(i, n, s);\n }\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */ delete(t) {\n const e = this.field(t.popLast());\n Wt(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];\n }\n isEqual(t) {\n return Ot(this.value, t.value);\n }\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */ getFieldsMap(t) {\n let e = this.value;\n e.mapValue.fields || (e.mapValue = {\n fields: {}\n });\n for (let n = 0; n < t.length; ++n) {\n let s = e.mapValue.fields[t.get(n)];\n Wt(s) && s.mapValue.fields || (s = {\n mapValue: {\n fields: {}\n }\n }, e.mapValue.fields[t.get(n)] = s), e = s;\n }\n return e.mapValue.fields;\n }\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */ applyChanges(t, e, n) {\n lt(e, ((e, n) => t[e] = n));\n for (const e of n) delete t[e];\n }\n clone() {\n return new te(zt(this.value));\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */ function ee(t) {\n const e = [];\n return lt(t.fields, ((t, n) => {\n const s = new mt([ t ]);\n if (Wt(n)) {\n const t = ee(n.mapValue).fields;\n if (0 === t.length) \n // Preserve the empty map by adding it to the FieldMask.\n e.push(s); else \n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const n of t) e.push(s.child(n));\n } else \n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n e.push(s);\n })), new gt(e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */ class ne {\n constructor(t, e, n, s, i, r) {\n this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.data = i, \n this.documentState = r;\n }\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */ static newInvalidDocument(t) {\n return new ne(t, 0 /* INVALID */ , ct.min(), ct.min(), te.empty(), 0 /* SYNCED */);\n }\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */ static newFoundDocument(t, e, n) {\n return new ne(t, 1 /* FOUND_DOCUMENT */ , e, ct.min(), n, 0 /* SYNCED */);\n }\n /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {\n return new ne(t, 2 /* NO_DOCUMENT */ , e, ct.min(), te.empty(), 0 /* SYNCED */);\n }\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */ static newUnknownDocument(t, e) {\n return new ne(t, 3 /* UNKNOWN_DOCUMENT */ , e, ct.min(), te.empty(), 2 /* HAS_COMMITTED_MUTATIONS */);\n }\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */ convertToFoundDocument(t, e) {\n return this.version = t, this.documentType = 1 /* FOUND_DOCUMENT */ , this.data = e, \n this.documentState = 0 /* SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */ convertToNoDocument(t) {\n return this.version = t, this.documentType = 2 /* NO_DOCUMENT */ , this.data = te.empty(), \n this.documentState = 0 /* SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */ convertToUnknownDocument(t) {\n return this.version = t, this.documentType = 3 /* UNKNOWN_DOCUMENT */ , this.data = te.empty(), \n this.documentState = 2 /* HAS_COMMITTED_MUTATIONS */ , this;\n }\n setHasCommittedMutations() {\n return this.documentState = 2 /* HAS_COMMITTED_MUTATIONS */ , this;\n }\n setHasLocalMutations() {\n return this.documentState = 1 /* HAS_LOCAL_MUTATIONS */ , this;\n }\n setReadTime(t) {\n return this.readTime = t, this;\n }\n get hasLocalMutations() {\n return 1 /* HAS_LOCAL_MUTATIONS */ === this.documentState;\n }\n get hasCommittedMutations() {\n return 2 /* HAS_COMMITTED_MUTATIONS */ === this.documentState;\n }\n get hasPendingWrites() {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n isValidDocument() {\n return 0 /* INVALID */ !== this.documentType;\n }\n isFoundDocument() {\n return 1 /* FOUND_DOCUMENT */ === this.documentType;\n }\n isNoDocument() {\n return 2 /* NO_DOCUMENT */ === this.documentType;\n }\n isUnknownDocument() {\n return 3 /* UNKNOWN_DOCUMENT */ === this.documentType;\n }\n isEqual(t) {\n return t instanceof ne && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);\n }\n mutableCopy() {\n return new ne(this.key, this.documentType, this.version, this.readTime, this.data.clone(), this.documentState);\n }\n toString() {\n return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nclass se {\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n t, \n /** The collection ID this index applies to. */\n e, \n /** The field segments for this index. */\n n, \n /** Shows how up-to-date the index is for the current user. */\n s) {\n this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;\n }\n}\n\n/** An ID for an index that has not yet been added to persistence. */\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nfunction ie(t) {\n return t.fields.find((t => 2 /* CONTAINS */ === t.kind));\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */ function re(t) {\n return t.fields.filter((t => 2 /* CONTAINS */ !== t.kind));\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */ se.UNKNOWN_ID = -1;\n\n/** An index component consisting of field path and index type. */\nclass oe {\n constructor(\n /** The field path of the component. */\n t, \n /** The fields sorting order. */\n e) {\n this.fieldPath = t, this.kind = e;\n }\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */ class ue {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n t, \n /** The the latest indexed read time, document and batch id. */\n e) {\n this.sequenceNumber = t, this.offset = e;\n }\n /** The state of an index that has not yet been backfilled. */ static empty() {\n return new ue(0, he.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */ function ae(t, e) {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = ct.fromTimestamp(1e9 === s ? new at(n + 1, 0) : new at(n, s));\n return new he(i, xt.empty(), e);\n}\n\n/** Creates a new offset based on the provided document. */ function ce(t) {\n return new he(t.readTime, t.key, -1);\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */ class he {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n t, \n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n e, \n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n n) {\n this.readTime = t, this.documentKey = e, this.largestBatchId = n;\n }\n /** Returns an offset that sorts before all regular offsets. */ static min() {\n return new he(ct.min(), xt.empty(), -1);\n }\n /** Returns an offset that sorts after all regular offsets. */ static max() {\n return new he(ct.max(), xt.empty(), -1);\n }\n}\n\nfunction le(t, e) {\n let n = t.readTime.compareTo(e.readTime);\n return 0 !== n ? n : (n = xt.comparator(t.documentKey, e.documentKey), 0 !== n ? n : rt(t.largestBatchId, e.largestBatchId));\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Visible for testing\nclass fe {\n constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i, \n this.startAt = r, this.endAt = o, this.P = null;\n }\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */ function de(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n return new fe(t, e, n, s, i, r, o);\n}\n\nfunction _e(t) {\n const e = K(t);\n if (null === e.P) {\n let t = e.path.canonicalString();\n null !== e.collectionGroup && (t += \"|cg:\" + e.collectionGroup), t += \"|f:\", t += e.filters.map((t => {\n return (e = t).field.canonicalString() + e.op.toString() + Lt(e.value);\n var e;\n })).join(\",\"), t += \"|ob:\", t += e.orderBy.map((t => function(t) {\n // TODO(b/29183165): Make this collision robust.\n return t.field.canonicalString() + t.dir;\n }(t))).join(\",\"), St(e.limit) || (t += \"|l:\", t += e.limit), e.startAt && (t += \"|lb:\", \n t += e.startAt.inclusive ? \"b:\" : \"a:\", t += e.startAt.position.map((t => Lt(t))).join(\",\")), \n e.endAt && (t += \"|ub:\", t += e.endAt.inclusive ? \"a:\" : \"b:\", t += e.endAt.position.map((t => Lt(t))).join(\",\")), \n e.P = t;\n }\n return e.P;\n}\n\nfunction we(t) {\n let e = t.path.canonicalString();\n return null !== t.collectionGroup && (e += \" collectionGroup=\" + t.collectionGroup), \n t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => {\n return `${(e = t).field.canonicalString()} ${e.op} ${Lt(e.value)}`;\n /** Returns a debug description for `filter`. */\n var e;\n /** Filter that matches on key fields (i.e. '__name__'). */ })).join(\", \")}]`), \n St(t.limit) || (e += \", limit: \" + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {\n return `${t.field.canonicalString()} (${t.dir})`;\n }(t))).join(\", \")}]`), t.startAt && (e += \", startAt: \", e += t.startAt.inclusive ? \"b:\" : \"a:\", \n e += t.startAt.position.map((t => Lt(t))).join(\",\")), t.endAt && (e += \", endAt: \", \n e += t.endAt.inclusive ? \"a:\" : \"b:\", e += t.endAt.position.map((t => Lt(t))).join(\",\")), \n `Target(${e})`;\n}\n\nfunction me(t, e) {\n if (t.limit !== e.limit) return !1;\n if (t.orderBy.length !== e.orderBy.length) return !1;\n for (let n = 0; n < t.orderBy.length; n++) if (!xe(t.orderBy[n], e.orderBy[n])) return !1;\n if (t.filters.length !== e.filters.length) return !1;\n for (let i = 0; i < t.filters.length; i++) if (n = t.filters[i], s = e.filters[i], \n n.op !== s.op || !n.field.isEqual(s.field) || !Ot(n.value, s.value)) return !1;\n var n, s;\n return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!ke(t.startAt, e.startAt) && ke(t.endAt, e.endAt)));\n}\n\nfunction ge(t) {\n return xt.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n}\n\n/** Returns the field filters that target the given field path. */ function ye(t, e) {\n return t.filters.filter((t => t instanceof Te && t.field.isEqual(e)));\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction pe(t, e, n) {\n let s, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of ye(t, e)) {\n let t, e = !0;\n switch (n.op) {\n case \"<\" /* LESS_THAN */ :\n case \"<=\" /* LESS_THAN_OR_EQUAL */ :\n t = Jt(n.value);\n break;\n\n case \"==\" /* EQUAL */ :\n case \"in\" /* IN */ :\n case \">=\" /* GREATER_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \">\" /* GREATER_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* NOT_EQUAL */ :\n case \"not-in\" /* NOT_IN */ :\n t = kt;\n // Remaining filters cannot be used as lower bounds.\n }\n Xt(s, t) === t && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n Xt(s, t) === t && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for an descending segment).\n */ function Ie(t, e, n) {\n let s, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of ye(t, e)) {\n let t, e = !0;\n switch (n.op) {\n case \">=\" /* GREATER_THAN_OR_EQUAL */ :\n case \">\" /* GREATER_THAN */ :\n t = Yt(n.value), e = !1;\n break;\n\n case \"==\" /* EQUAL */ :\n case \"in\" /* IN */ :\n case \"<=\" /* LESS_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \"<\" /* LESS_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* NOT_EQUAL */ :\n case \"not-in\" /* NOT_IN */ :\n t = Nt;\n // Remaining filters cannot be used as upper bounds.\n }\n Zt(s, t) === t && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n Zt(s, t) === t && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\nclass Te extends class {} {\n constructor(t, e, n) {\n super(), this.field = t, this.op = e, this.value = n;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(t, e, n) {\n return t.isKeyField() ? \"in\" /* IN */ === e || \"not-in\" /* NOT_IN */ === e ? this.V(t, e, n) : new Ee(t, e, n) : \"array-contains\" /* ARRAY_CONTAINS */ === e ? new be(t, n) : \"in\" /* IN */ === e ? new Ve(t, n) : \"not-in\" /* NOT_IN */ === e ? new ve(t, n) : \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ === e ? new Se(t, n) : new Te(t, e, n);\n }\n static V(t, e, n) {\n return \"in\" /* IN */ === e ? new Ae(t, n) : new Re(t, n);\n }\n matches(t) {\n const e = t.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n return \"!=\" /* NOT_EQUAL */ === this.op ? null !== e && this.v($t(e, this.value)) : null !== e && Mt(this.value) === Mt(e) && this.v($t(e, this.value));\n // Only compare types with matching backend order (such as double and int).\n }\n v(t) {\n switch (this.op) {\n case \"<\" /* LESS_THAN */ :\n return t < 0;\n\n case \"<=\" /* LESS_THAN_OR_EQUAL */ :\n return t <= 0;\n\n case \"==\" /* EQUAL */ :\n return 0 === t;\n\n case \"!=\" /* NOT_EQUAL */ :\n return 0 !== t;\n\n case \">\" /* GREATER_THAN */ :\n return t > 0;\n\n case \">=\" /* GREATER_THAN_OR_EQUAL */ :\n return t >= 0;\n\n default:\n return L();\n }\n }\n S() {\n return [ \"<\" /* LESS_THAN */ , \"<=\" /* LESS_THAN_OR_EQUAL */ , \">\" /* GREATER_THAN */ , \">=\" /* GREATER_THAN_OR_EQUAL */ , \"!=\" /* NOT_EQUAL */ , \"not-in\" /* NOT_IN */ ].indexOf(this.op) >= 0;\n }\n}\n\nclass Ee extends Te {\n constructor(t, e, n) {\n super(t, e, n), this.key = xt.fromName(n.referenceValue);\n }\n matches(t) {\n const e = xt.comparator(t.key, this.key);\n return this.v(e);\n }\n}\n\n/** Filter that matches on key fields within an array. */ class Ae extends Te {\n constructor(t, e) {\n super(t, \"in\" /* IN */ , e), this.keys = Pe(\"in\" /* IN */ , e);\n }\n matches(t) {\n return this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */ class Re extends Te {\n constructor(t, e) {\n super(t, \"not-in\" /* NOT_IN */ , e), this.keys = Pe(\"not-in\" /* NOT_IN */ , e);\n }\n matches(t) {\n return !this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\nfunction Pe(t, e) {\n var n;\n return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => xt.fromName(t.referenceValue)));\n}\n\n/** A Filter that implements the array-contains operator. */ class be extends Te {\n constructor(t, e) {\n super(t, \"array-contains\" /* ARRAY_CONTAINS */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return Gt(e) && Ft(e.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */ class Ve extends Te {\n constructor(t, e) {\n super(t, \"in\" /* IN */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return null !== e && Ft(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the not-in operator. */ class ve extends Te {\n constructor(t, e) {\n super(t, \"not-in\" /* NOT_IN */ , e);\n }\n matches(t) {\n if (Ft(this.value.arrayValue, {\n nullValue: \"NULL_VALUE\"\n })) return !1;\n const e = t.data.field(this.field);\n return null !== e && !Ft(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */ class Se extends Te {\n constructor(t, e) {\n super(t, \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return !(!Gt(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => Ft(this.value.arrayValue, t)));\n }\n}\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */ class De {\n constructor(t, e) {\n this.position = t, this.inclusive = e;\n }\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */ class Ce {\n constructor(t, e = \"asc\" /* ASCENDING */) {\n this.field = t, this.dir = e;\n }\n}\n\nfunction xe(t, e) {\n return t.dir === e.dir && t.field.isEqual(e.field);\n}\n\nfunction Ne(t, e, n) {\n let s = 0;\n for (let i = 0; i < t.position.length; i++) {\n const r = e[i], o = t.position[i];\n if (r.field.isKeyField()) s = xt.comparator(xt.fromName(o.referenceValue), n.key); else {\n s = $t(o, n.data.field(r.field));\n }\n if (\"desc\" /* DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;\n }\n return s;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */ function ke(t, e) {\n if (null === t) return null === e;\n if (null === e) return !1;\n if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;\n for (let n = 0; n < t.position.length; n++) {\n if (!Ot(t.position[n], e.position[n])) return !1;\n }\n return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */ class Me {\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(t, e = null, n = [], s = [], i = null, r = \"F\" /* First */ , o = null, u = null) {\n this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s, \n this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.D = null, \n // The corresponding `Target` of this `Query` instance.\n this.C = null, this.startAt, this.endAt;\n }\n}\n\n/** Creates a new Query instance with the options provided. */ function Oe(t, e, n, s, i, r, o, u) {\n return new Me(t, e, n, s, i, r, o, u);\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */ function Fe(t) {\n return new Me(t);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */ function $e(t) {\n return !St(t.limit) && \"F\" /* First */ === t.limitType;\n}\n\nfunction Be(t) {\n return !St(t.limit) && \"L\" /* Last */ === t.limitType;\n}\n\nfunction Le(t) {\n return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;\n}\n\nfunction Ue(t) {\n for (const e of t.filters) if (e.S()) return e.field;\n return null;\n}\n\n/**\n * Checks if any of the provided Operators are included in the query and\n * returns the first one that is, or null if none are.\n */\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nfunction qe(t) {\n return null !== t.collectionGroup;\n}\n\n/**\n * Returns the implicit order by constraint that is used to execute the Query,\n * which can be different from the order by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`).\n */ function Ke(t) {\n const e = K(t);\n if (null === e.D) {\n e.D = [];\n const t = Ue(e), n = Le(e);\n if (null !== t && null === n) \n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n t.isKeyField() || e.D.push(new Ce(t)), e.D.push(new Ce(mt.keyField(), \"asc\" /* ASCENDING */)); else {\n let t = !1;\n for (const n of e.explicitOrderBy) e.D.push(n), n.field.isKeyField() && (t = !0);\n if (!t) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : \"asc\" /* ASCENDING */;\n e.D.push(new Ce(mt.keyField(), t));\n }\n }\n }\n return e.D;\n}\n\n/**\n * Converts this `Query` instance to it's corresponding `Target` representation.\n */ function Ge(t) {\n const e = K(t);\n if (!e.C) if (\"F\" /* First */ === e.limitType) e.C = de(e.path, e.collectionGroup, Ke(e), e.filters, e.limit, e.startAt, e.endAt); else {\n // Flip the orderBy directions since we want the last results\n const t = [];\n for (const n of Ke(e)) {\n const e = \"desc\" /* DESCENDING */ === n.dir ? \"asc\" /* ASCENDING */ : \"desc\" /* DESCENDING */;\n t.push(new Ce(n.field, e));\n }\n // We need to swap the cursors to match the now-flipped query ordering.\n const n = e.endAt ? new De(e.endAt.position, !e.endAt.inclusive) : null, s = e.startAt ? new De(e.startAt.position, !e.startAt.inclusive) : null;\n // Now return as a LimitType.First query.\n e.C = de(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);\n }\n return e.C;\n}\n\nfunction Qe(t, e, n) {\n return new Me(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);\n}\n\nfunction je(t, e) {\n return me(Ge(t), Ge(e)) && t.limitType === e.limitType;\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nfunction We(t) {\n return `${_e(Ge(t))}|lt:${t.limitType}`;\n}\n\nfunction ze(t) {\n return `Query(target=${we(Ge(t))}; limitType=${t.limitType})`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */ function He(t, e) {\n return e.isFoundDocument() && function(t, e) {\n const n = e.key.path;\n return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : xt.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);\n }\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */ (t, e) && function(t, e) {\n for (const n of t.explicitOrderBy) \n // order by key always matches\n if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;\n return !0;\n }(t, e) && function(t, e) {\n for (const n of t.filters) if (!n.matches(e)) return !1;\n return !0;\n }\n /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {\n if (t.startAt && !\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n function(t, e, n) {\n const s = Ne(t, e, n);\n return t.inclusive ? s <= 0 : s < 0;\n }(t.startAt, Ke(t), e)) return !1;\n if (t.endAt && !function(t, e, n) {\n const s = Ne(t, e, n);\n return t.inclusive ? s >= 0 : s > 0;\n }(t.endAt, Ke(t), e)) return !1;\n return !0;\n }\n /**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */ (t, e);\n}\n\nfunction Je(t) {\n return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */ function Ye(t) {\n return (e, n) => {\n let s = !1;\n for (const i of Ke(t)) {\n const t = Xe(i, e, n);\n if (0 !== t) return t;\n s = s || i.field.isKeyField();\n }\n return 0;\n };\n}\n\nfunction Xe(t, e, n) {\n const s = t.field.isKeyField() ? xt.comparator(e.key, n.key) : function(t, e, n) {\n const s = e.data.field(t), i = n.data.field(t);\n return null !== s && null !== i ? $t(s, i) : L();\n }\n /**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */ (t.field, e, n);\n switch (t.dir) {\n case \"asc\" /* ASCENDING */ :\n return s;\n\n case \"desc\" /* DESCENDING */ :\n return -1 * s;\n\n default:\n return L();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */ function Ze(t, e) {\n if (t.N) {\n if (isNaN(e)) return {\n doubleValue: \"NaN\"\n };\n if (e === 1 / 0) return {\n doubleValue: \"Infinity\"\n };\n if (e === -1 / 0) return {\n doubleValue: \"-Infinity\"\n };\n }\n return {\n doubleValue: Dt(e) ? \"-0\" : e\n };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */ function tn(t) {\n return {\n integerValue: \"\" + t\n };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */ function en(t, e) {\n return Ct(e) ? tn(e) : Ze(t, e);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Used to represent a field transform on a mutation. */ class nn {\n constructor() {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n this._ = void 0;\n }\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */ function sn(t, e, n) {\n return t instanceof un ? function(t, e) {\n const n = {\n fields: {\n __type__: {\n stringValue: \"server_timestamp\"\n },\n __local_write_time__: {\n timestampValue: {\n seconds: t.seconds,\n nanos: t.nanoseconds\n }\n }\n }\n };\n return e && (n.fields.__previous_value__ = e), {\n mapValue: n\n };\n }(n, e) : t instanceof an ? cn(t, e) : t instanceof hn ? ln(t, e) : function(t, e) {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const n = on(t, e), s = dn(n) + dn(t.k);\n return Kt(n) && Kt(t.k) ? tn(s) : Ze(t.M, s);\n }(t, e);\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */ function rn(t, e, n) {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return t instanceof an ? cn(t, e) : t instanceof hn ? ln(t, e) : n;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */ function on(t, e) {\n return t instanceof fn ? Kt(n = e) || function(t) {\n return !!t && \"doubleValue\" in t;\n }\n /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {\n integerValue: 0\n } : null;\n var n;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nclass un extends nn {}\n\n/** Transforms an array value via a union operation. */ class an extends nn {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction cn(t, e) {\n const n = _n(e);\n for (const e of t.elements) n.some((t => Ot(t, e))) || n.push(e);\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/** Transforms an array value via a remove operation. */ class hn extends nn {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction ln(t, e) {\n let n = _n(e);\n for (const e of t.elements) n = n.filter((t => !Ot(t, e)));\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */ class fn extends nn {\n constructor(t, e) {\n super(), this.M = t, this.k = e;\n }\n}\n\nfunction dn(t) {\n return Et(t.integerValue || t.doubleValue);\n}\n\nfunction _n(t) {\n return Gt(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A field path and the TransformOperation to perform upon it. */ class wn {\n constructor(t, e) {\n this.field = t, this.transform = e;\n }\n}\n\nfunction mn(t, e) {\n return t.field.isEqual(e.field) && function(t, e) {\n return t instanceof an && e instanceof an || t instanceof hn && e instanceof hn ? ot(t.elements, e.elements, Ot) : t instanceof fn && e instanceof fn ? Ot(t.k, e.k) : t instanceof un && e instanceof un;\n }(t.transform, e.transform);\n}\n\n/** The result of successfully applying a mutation to the backend. */\nclass gn {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n t, \n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n e) {\n this.version = t, this.transformResults = e;\n }\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */ class yn {\n constructor(t, e) {\n this.updateTime = t, this.exists = e;\n }\n /** Creates a new empty Precondition. */ static none() {\n return new yn;\n }\n /** Creates a new Precondition with an exists flag. */ static exists(t) {\n return new yn(void 0, t);\n }\n /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {\n return new yn(t);\n }\n /** Returns whether this Precondition is empty. */ get isNone() {\n return void 0 === this.updateTime && void 0 === this.exists;\n }\n isEqual(t) {\n return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */ function pn(t, e) {\n return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */ class In {}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */ function Tn(t, e, n) {\n t instanceof bn ? function(t, e, n) {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const s = t.value.clone(), i = Sn(t.fieldTransforms, e, n.transformResults);\n s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();\n }(t, e, n) : t instanceof Vn ? function(t, e, n) {\n if (!pn(t.precondition, e)) \n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n return void e.convertToUnknownDocument(n.version);\n const s = Sn(t.fieldTransforms, e, n.transformResults), i = e.data;\n i.setAll(vn(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();\n }(t, e, n) : function(t, e, n) {\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n e.convertToNoDocument(n.version).setHasCommittedMutations();\n }(0, e, n);\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n */ function En(t, e, n) {\n t instanceof bn ? function(t, e, n) {\n if (!pn(t.precondition, e)) \n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return;\n const s = t.value.clone(), i = Dn(t.fieldTransforms, n, e);\n s.setAll(i), e.convertToFoundDocument(Pn(e), s).setHasLocalMutations();\n }\n /**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */ (t, e, n) : t instanceof Vn ? function(t, e, n) {\n if (!pn(t.precondition, e)) return;\n const s = Dn(t.fieldTransforms, n, e), i = e.data;\n i.setAll(vn(t)), i.setAll(s), e.convertToFoundDocument(Pn(e), i).setHasLocalMutations();\n }\n /**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */ (t, e, n) : function(t, e) {\n pn(t.precondition, e) && \n // We don't call `setHasLocalMutations()` since we want to be backwards\n // compatible with the existing SDK behavior.\n e.convertToNoDocument(ct.min());\n }\n /**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */ (t, e);\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */ function An(t, e) {\n let n = null;\n for (const s of t.fieldTransforms) {\n const t = e.data.field(s.field), i = on(s.transform, t || null);\n null != i && (null == n && (n = te.empty()), n.set(s.field, i));\n }\n return n || null;\n}\n\nfunction Rn(t, e) {\n return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {\n return void 0 === t && void 0 === e || !(!t || !e) && ot(t, e, ((t, e) => mn(t, e)));\n }(t.fieldTransforms, e.fieldTransforms) && (0 /* Set */ === t.type ? t.value.isEqual(e.value) : 1 /* Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask)))));\n}\n\n/**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.min().\n */ function Pn(t) {\n return t.isFoundDocument() ? t.version : ct.min();\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */ class bn extends In {\n constructor(t, e, n, s = []) {\n super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s, \n this.type = 0 /* Set */;\n }\n}\n\nclass Vn extends In {\n constructor(t, e, n, s, i = []) {\n super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s, \n this.fieldTransforms = i, this.type = 1 /* Patch */;\n }\n}\n\nfunction vn(t) {\n const e = new Map;\n return t.fieldMask.fields.forEach((n => {\n if (!n.isEmpty()) {\n const s = t.data.field(n);\n e.set(n, s);\n }\n })), e;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */ function Sn(t, e, n) {\n const s = new Map;\n U(t.length === n.length);\n for (let i = 0; i < n.length; i++) {\n const r = t[i], o = r.transform, u = e.data.field(r.field);\n s.set(r.field, rn(o, u, n[i]));\n }\n return s;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @returns The transform results list.\n */ function Dn(t, e, n) {\n const s = new Map;\n for (const i of t) {\n const t = i.transform, r = n.data.field(i.field);\n s.set(i.field, sn(t, r, e));\n }\n return s;\n}\n\n/** A mutation that deletes the document at the given key. */ class Cn extends In {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 2 /* Delete */ , this.fieldTransforms = [];\n }\n}\n\nclass xn extends In {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 3 /* Verify */ , this.fieldTransforms = [];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Nn {\n // TODO(b/33078163): just use simplest form of existence filter for now\n constructor(t) {\n this.count = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */ var kn, Mn;\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nfunction On(t) {\n switch (t) {\n default:\n return L();\n\n case G.CANCELLED:\n case G.UNKNOWN:\n case G.DEADLINE_EXCEEDED:\n case G.RESOURCE_EXHAUSTED:\n case G.INTERNAL:\n case G.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case G.UNAUTHENTICATED:\n return !1;\n\n case G.INVALID_ARGUMENT:\n case G.NOT_FOUND:\n case G.ALREADY_EXISTS:\n case G.PERMISSION_DENIED:\n case G.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case G.ABORTED:\n case G.OUT_OF_RANGE:\n case G.UNIMPLEMENTED:\n case G.DATA_LOSS:\n return !0;\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nfunction Fn(t) {\n if (void 0 === t) \n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n return F(\"GRPC error has no .code\"), G.UNKNOWN;\n switch (t) {\n case kn.OK:\n return G.OK;\n\n case kn.CANCELLED:\n return G.CANCELLED;\n\n case kn.UNKNOWN:\n return G.UNKNOWN;\n\n case kn.DEADLINE_EXCEEDED:\n return G.DEADLINE_EXCEEDED;\n\n case kn.RESOURCE_EXHAUSTED:\n return G.RESOURCE_EXHAUSTED;\n\n case kn.INTERNAL:\n return G.INTERNAL;\n\n case kn.UNAVAILABLE:\n return G.UNAVAILABLE;\n\n case kn.UNAUTHENTICATED:\n return G.UNAUTHENTICATED;\n\n case kn.INVALID_ARGUMENT:\n return G.INVALID_ARGUMENT;\n\n case kn.NOT_FOUND:\n return G.NOT_FOUND;\n\n case kn.ALREADY_EXISTS:\n return G.ALREADY_EXISTS;\n\n case kn.PERMISSION_DENIED:\n return G.PERMISSION_DENIED;\n\n case kn.FAILED_PRECONDITION:\n return G.FAILED_PRECONDITION;\n\n case kn.ABORTED:\n return G.ABORTED;\n\n case kn.OUT_OF_RANGE:\n return G.OUT_OF_RANGE;\n\n case kn.UNIMPLEMENTED:\n return G.UNIMPLEMENTED;\n\n case kn.DATA_LOSS:\n return G.DATA_LOSS;\n\n default:\n return L();\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */ (Mn = kn || (kn = {}))[Mn.OK = 0] = \"OK\", Mn[Mn.CANCELLED = 1] = \"CANCELLED\", \nMn[Mn.UNKNOWN = 2] = \"UNKNOWN\", Mn[Mn.INVALID_ARGUMENT = 3] = \"INVALID_ARGUMENT\", \nMn[Mn.DEADLINE_EXCEEDED = 4] = \"DEADLINE_EXCEEDED\", Mn[Mn.NOT_FOUND = 5] = \"NOT_FOUND\", \nMn[Mn.ALREADY_EXISTS = 6] = \"ALREADY_EXISTS\", Mn[Mn.PERMISSION_DENIED = 7] = \"PERMISSION_DENIED\", \nMn[Mn.UNAUTHENTICATED = 16] = \"UNAUTHENTICATED\", Mn[Mn.RESOURCE_EXHAUSTED = 8] = \"RESOURCE_EXHAUSTED\", \nMn[Mn.FAILED_PRECONDITION = 9] = \"FAILED_PRECONDITION\", Mn[Mn.ABORTED = 10] = \"ABORTED\", \nMn[Mn.OUT_OF_RANGE = 11] = \"OUT_OF_RANGE\", Mn[Mn.UNIMPLEMENTED = 12] = \"UNIMPLEMENTED\", \nMn[Mn.INTERNAL = 13] = \"INTERNAL\", Mn[Mn.UNAVAILABLE = 14] = \"UNAVAILABLE\", Mn[Mn.DATA_LOSS = 15] = \"DATA_LOSS\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nclass $n {\n constructor(t, e) {\n this.mapKeyFn = t, this.equalsFn = e, \n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n this.inner = {}, \n /** The number of entries stored in the map */\n this.innerSize = 0;\n }\n /** Get a value for this key, or undefined if it does not exist. */ get(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;\n }\n has(t) {\n return void 0 !== this.get(t);\n }\n /** Put this key and value in the map. */ set(t, e) {\n const n = this.mapKeyFn(t), s = this.inner[n];\n if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;\n for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t)) \n // This is updating an existing entry and does not increase `innerSize`.\n return void (s[n] = [ t, e ]);\n s.push([ t, e ]), this.innerSize++;\n }\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */ delete(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 === n) return !1;\n for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1), \n this.innerSize--, !0;\n return !1;\n }\n forEach(t) {\n lt(this.inner, ((e, n) => {\n for (const [e, s] of n) t(e, s);\n }));\n }\n isEmpty() {\n return ft(this.inner);\n }\n size() {\n return this.innerSize;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nclass Bn {\n constructor(t, e) {\n this.comparator = t, this.root = e || Un.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(t, e) {\n return new Bn(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, Un.BLACK, null, null));\n }\n // Returns a copy of the map, with the specified key removed.\n remove(t) {\n return new Bn(this.comparator, this.root.remove(t, this.comparator).copy(null, null, Un.BLACK, null, null));\n }\n // Returns the value of the node with the given key, or null.\n get(t) {\n let e = this.root;\n for (;!e.isEmpty(); ) {\n const n = this.comparator(t, e.key);\n if (0 === n) return e.value;\n n < 0 ? e = e.left : n > 0 && (e = e.right);\n }\n return null;\n }\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(t) {\n // Number of nodes that were pruned when descending right\n let e = 0, n = this.root;\n for (;!n.isEmpty(); ) {\n const s = this.comparator(t, n.key);\n if (0 === s) return e + n.left.size;\n s < 0 ? n = n.left : (\n // Count all nodes left of the node plus the node itself\n e += n.left.size + 1, n = n.right);\n }\n // Node not found\n return -1;\n }\n isEmpty() {\n return this.root.isEmpty();\n }\n // Returns the total number of nodes in the map.\n get size() {\n return this.root.size;\n }\n // Returns the minimum key in the map.\n minKey() {\n return this.root.minKey();\n }\n // Returns the maximum key in the map.\n maxKey() {\n return this.root.maxKey();\n }\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.root.inorderTraversal(t);\n }\n forEach(t) {\n this.inorderTraversal(((e, n) => (t(e, n), !1)));\n }\n toString() {\n const t = [];\n return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(\", \")}}`;\n }\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.root.reverseTraversal(t);\n }\n // Returns an iterator over the SortedMap.\n getIterator() {\n return new Ln(this.root, null, this.comparator, !1);\n }\n getIteratorFrom(t) {\n return new Ln(this.root, t, this.comparator, !1);\n }\n getReverseIterator() {\n return new Ln(this.root, null, this.comparator, !0);\n }\n getReverseIteratorFrom(t) {\n return new Ln(this.root, t, this.comparator, !0);\n }\n}\n\n // end SortedMap\n// An iterator over an LLRBNode.\nclass Ln {\n constructor(t, e, n, s) {\n this.isReverse = s, this.nodeStack = [];\n let i = 1;\n for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1, \n // flip the comparison if we're going in reverse\n e && s && (i *= -1), i < 0) \n // This node is less than our start key. ignore it\n t = this.isReverse ? t.left : t.right; else {\n if (0 === i) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(t);\n break;\n }\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;\n }\n }\n getNext() {\n let t = this.nodeStack.pop();\n const e = {\n key: t.key,\n value: t.value\n };\n if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), \n t = t.left;\n return e;\n }\n hasNext() {\n return this.nodeStack.length > 0;\n }\n peek() {\n if (0 === this.nodeStack.length) return null;\n const t = this.nodeStack[this.nodeStack.length - 1];\n return {\n key: t.key,\n value: t.value\n };\n }\n}\n\n // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\nclass Un {\n constructor(t, e, n, s, i) {\n this.key = t, this.value = e, this.color = null != n ? n : Un.RED, this.left = null != s ? s : Un.EMPTY, \n this.right = null != i ? i : Un.EMPTY, this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(t, e, n, s, i) {\n return new Un(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);\n }\n isEmpty() {\n return !1;\n }\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);\n }\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);\n }\n // Returns the minimum node in the tree.\n min() {\n return this.left.isEmpty() ? this : this.left.min();\n }\n // Returns the maximum key in the tree.\n minKey() {\n return this.min().key;\n }\n // Returns the maximum key in the tree.\n maxKey() {\n return this.right.isEmpty() ? this.key : this.right.maxKey();\n }\n // Returns new tree, with the key/value added.\n insert(t, e, n) {\n let s = this;\n const i = n(t, s.key);\n return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)), \n s.fixUp();\n }\n removeMin() {\n if (this.left.isEmpty()) return Un.EMPTY;\n let t = this;\n return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), \n t.fixUp();\n }\n // Returns new tree, with the specified item removed.\n remove(t, e) {\n let n, s = this;\n if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()), \n s = s.copy(null, null, null, s.left.remove(t, e), null); else {\n if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()), \n 0 === e(t, s.key)) {\n if (s.right.isEmpty()) return Un.EMPTY;\n n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());\n }\n s = s.copy(null, null, null, null, s.right.remove(t, e));\n }\n return s.fixUp();\n }\n isRed() {\n return this.color;\n }\n // Returns new tree after performing any needed rotations.\n fixUp() {\n let t = this;\n return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), \n t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;\n }\n moveRedLeft() {\n let t = this.colorFlip();\n return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), \n t = t.rotateLeft(), t = t.colorFlip()), t;\n }\n moveRedRight() {\n let t = this.colorFlip();\n return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;\n }\n rotateLeft() {\n const t = this.copy(null, null, Un.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, t, null);\n }\n rotateRight() {\n const t = this.copy(null, null, Un.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, t);\n }\n colorFlip() {\n const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, t, e);\n }\n // For testing.\n checkMaxDepth() {\n const t = this.check();\n return Math.pow(2, t) <= this.size + 1;\n }\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n check() {\n if (this.isRed() && this.left.isRed()) throw L();\n if (this.right.isRed()) throw L();\n const t = this.left.check();\n if (t !== this.right.check()) throw L();\n return t + (this.isRed() ? 0 : 1);\n }\n}\n\n // end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nUn.EMPTY = null, Un.RED = !0, Un.BLACK = !1;\n\n// end LLRBEmptyNode\nUn.EMPTY = new \n// Represents an empty node (a leaf node in the Red-Black Tree).\nclass {\n constructor() {\n this.size = 0;\n }\n get key() {\n throw L();\n }\n get value() {\n throw L();\n }\n get color() {\n throw L();\n }\n get left() {\n throw L();\n }\n get right() {\n throw L();\n }\n // Returns a copy of the current node.\n copy(t, e, n, s, i) {\n return this;\n }\n // Returns a copy of the tree, with the specified key/value added.\n insert(t, e, n) {\n return new Un(t, e);\n }\n // Returns a copy of the tree, with the specified key removed.\n remove(t, e) {\n return this;\n }\n isEmpty() {\n return !0;\n }\n inorderTraversal(t) {\n return !1;\n }\n reverseTraversal(t) {\n return !1;\n }\n minKey() {\n return null;\n }\n maxKey() {\n return null;\n }\n isRed() {\n return !1;\n }\n // For testing.\n checkMaxDepth() {\n return !0;\n }\n check() {\n return 0;\n }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nclass qn {\n constructor(t) {\n this.comparator = t, this.data = new Bn(this.comparator);\n }\n has(t) {\n return null !== this.data.get(t);\n }\n first() {\n return this.data.minKey();\n }\n last() {\n return this.data.maxKey();\n }\n get size() {\n return this.data.size;\n }\n indexOf(t) {\n return this.data.indexOf(t);\n }\n /** Iterates elements in order defined by \"comparator\" */ forEach(t) {\n this.data.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) {\n const n = this.data.getIteratorFrom(t[0]);\n for (;n.hasNext(); ) {\n const s = n.getNext();\n if (this.comparator(s.key, t[1]) >= 0) return;\n e(s.key);\n }\n }\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */ forEachWhile(t, e) {\n let n;\n for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {\n if (!t(n.getNext().key)) return;\n }\n }\n /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {\n const e = this.data.getIteratorFrom(t);\n return e.hasNext() ? e.getNext().key : null;\n }\n getIterator() {\n return new Kn(this.data.getIterator());\n }\n getIteratorFrom(t) {\n return new Kn(this.data.getIteratorFrom(t));\n }\n /** Inserts or updates an element */ add(t) {\n return this.copy(this.data.remove(t).insert(t, !0));\n }\n /** Deletes an element */ delete(t) {\n return this.has(t) ? this.copy(this.data.remove(t)) : this;\n }\n isEmpty() {\n return this.data.isEmpty();\n }\n unionWith(t) {\n let e = this;\n // Make sure `result` always refers to the larger one of the two sets.\n return e.size < t.size && (e = t, t = this), t.forEach((t => {\n e = e.add(t);\n })), e;\n }\n isEqual(t) {\n if (!(t instanceof qn)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.data.getIterator(), n = t.data.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (0 !== this.comparator(t, s)) return !1;\n }\n return !0;\n }\n toArray() {\n const t = [];\n return this.forEach((e => {\n t.push(e);\n })), t;\n }\n toString() {\n const t = [];\n return this.forEach((e => t.push(e))), \"SortedSet(\" + t.toString() + \")\";\n }\n copy(t) {\n const e = new qn(this.comparator);\n return e.data = t, e;\n }\n}\n\nclass Kn {\n constructor(t) {\n this.iter = t;\n }\n getNext() {\n return this.iter.getNext().key;\n }\n hasNext() {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction Gn(t) {\n return t.hasNext() ? t.getNext() : void 0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Qn = new Bn(xt.comparator);\n\nfunction jn() {\n return Qn;\n}\n\nconst Wn = new Bn(xt.comparator);\n\nfunction zn() {\n return Wn;\n}\n\nfunction Hn() {\n return new $n((t => t.toString()), ((t, e) => t.isEqual(e)));\n}\n\nconst Jn = new Bn(xt.comparator);\n\nconst Yn = new qn(xt.comparator);\n\nfunction Xn(...t) {\n let e = Yn;\n for (const n of t) e = e.add(n);\n return e;\n}\n\nconst Zn = new qn(rt);\n\nfunction ts() {\n return Zn;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */ class es {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n t, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n e, \n /**\n * A set of targets that is known to be inconsistent. Listens for these\n * targets should be re-established without resume tokens.\n */\n n, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n s, \n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n i) {\n this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s, \n this.resolvedLimboDocuments = i;\n }\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(t, e) {\n const n = new Map;\n return n.set(t, ns.createSynthesizedTargetChangeForCurrentChange(t, e)), new es(ct.min(), n, ts(), jn(), Xn());\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */ class ns {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n t, \n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n e, \n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n n, \n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n s, \n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n i) {\n this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s, \n this.removedDocuments = i;\n }\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */ static createSynthesizedTargetChangeForCurrentChange(t, e) {\n return new ns(pt.EMPTY_BYTE_STRING, e, Xn(), Xn(), Xn());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */ class ss {\n constructor(\n /** The new document applies to all of these targets. */\n t, \n /** The new document is removed from all of these targets. */\n e, \n /** The key of the document for this change. */\n n, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n s) {\n this.O = t, this.removedTargetIds = e, this.key = n, this.F = s;\n }\n}\n\nclass is {\n constructor(t, e) {\n this.targetId = t, this.$ = e;\n }\n}\n\nclass rs {\n constructor(\n /** What kind of change occurred to the watch target. */\n t, \n /** The target IDs that were added/removed/set. */\n e, \n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n n = pt.EMPTY_BYTE_STRING\n /** An RPC error indicating why the watch failed. */ , s = null) {\n this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;\n }\n}\n\n/** Tracks the internal state of a Watch target. */ class os {\n constructor() {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n this.B = 0, \n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n this.L = cs(), \n /** See public getters for explanations of these fields. */\n this.U = pt.EMPTY_BYTE_STRING, this.q = !1, \n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n this.K = !0;\n }\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */ get current() {\n return this.q;\n }\n /** The last resume token sent to us for this target. */ get resumeToken() {\n return this.U;\n }\n /** Whether this target has pending target adds or target removes. */ get G() {\n return 0 !== this.B;\n }\n /** Whether we have modified any state that should trigger a snapshot. */ get j() {\n return this.K;\n }\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */ W(t) {\n t.approximateByteSize() > 0 && (this.K = !0, this.U = t);\n }\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */ H() {\n let t = Xn(), e = Xn(), n = Xn();\n return this.L.forEach(((s, i) => {\n switch (i) {\n case 0 /* Added */ :\n t = t.add(s);\n break;\n\n case 2 /* Modified */ :\n e = e.add(s);\n break;\n\n case 1 /* Removed */ :\n n = n.add(s);\n break;\n\n default:\n L();\n }\n })), new ns(this.U, this.q, t, e, n);\n }\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */ J() {\n this.K = !1, this.L = cs();\n }\n Y(t, e) {\n this.K = !0, this.L = this.L.insert(t, e);\n }\n X(t) {\n this.K = !0, this.L = this.L.remove(t);\n }\n Z() {\n this.B += 1;\n }\n tt() {\n this.B -= 1;\n }\n et() {\n this.K = !0, this.q = !0;\n }\n}\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nclass us {\n constructor(t) {\n this.nt = t, \n /** The internal state of all tracked targets. */\n this.st = new Map, \n /** Keeps track of the documents to update since the last raised snapshot. */\n this.it = jn(), \n /** A mapping of document keys to their set of target IDs. */\n this.rt = as(), \n /**\n * A list of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n this.ot = new qn(rt);\n }\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */ ut(t) {\n for (const e of t.O) t.F && t.F.isFoundDocument() ? this.at(e, t.F) : this.ct(e, t.key, t.F);\n for (const e of t.removedTargetIds) this.ct(e, t.key, t.F);\n }\n /** Processes and adds the WatchTargetChange to the current set of changes. */ ht(t) {\n this.forEachTarget(t, (e => {\n const n = this.lt(e);\n switch (t.state) {\n case 0 /* NoChange */ :\n this.ft(e) && n.W(t.resumeToken);\n break;\n\n case 1 /* Added */ :\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.tt(), n.G || \n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n n.J(), n.W(t.resumeToken);\n break;\n\n case 2 /* Removed */ :\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.tt(), n.G || this.removeTarget(e);\n break;\n\n case 3 /* Current */ :\n this.ft(e) && (n.et(), n.W(t.resumeToken));\n break;\n\n case 4 /* Reset */ :\n this.ft(e) && (\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.dt(e), n.W(t.resumeToken));\n break;\n\n default:\n L();\n }\n }));\n }\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */ forEachTarget(t, e) {\n t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.st.forEach(((t, n) => {\n this.ft(n) && e(n);\n }));\n }\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */ _t(t) {\n const e = t.targetId, n = t.$.count, s = this.wt(e);\n if (s) {\n const t = s.target;\n if (ge(t)) if (0 === n) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const n = new xt(t.path);\n this.ct(e, n, ne.newNoDocument(n, ct.min()));\n } else U(1 === n); else {\n this.gt(e) !== n && (\n // Existence filter mismatch: We reset the mapping and raise a new\n // snapshot with `isFromCache:true`.\n this.dt(e), this.ot = this.ot.add(e));\n }\n }\n }\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */ yt(t) {\n const e = new Map;\n this.st.forEach(((n, s) => {\n const i = this.wt(s);\n if (i) {\n if (n.current && ge(i.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const e = new xt(i.target.path);\n null !== this.it.get(e) || this.It(s, e) || this.ct(s, e, ne.newNoDocument(e, t));\n }\n n.j && (e.set(s, n.H()), n.J());\n }\n }));\n let n = Xn();\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n \n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.rt.forEach(((t, e) => {\n let s = !0;\n e.forEachWhile((t => {\n const e = this.wt(t);\n return !e || 2 /* LimboResolution */ === e.purpose || (s = !1, !1);\n })), s && (n = n.add(t));\n })), this.it.forEach(((e, n) => n.setReadTime(t)));\n const s = new es(t, e, this.ot, this.it, n);\n return this.it = jn(), this.rt = as(), this.ot = new qn(rt), s;\n }\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n at(t, e) {\n if (!this.ft(t)) return;\n const n = this.It(t, e.key) ? 2 /* Modified */ : 0 /* Added */;\n this.lt(t).Y(e.key, n), this.it = this.it.insert(e.key, e), this.rt = this.rt.insert(e.key, this.Tt(e.key).add(t));\n }\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n ct(t, e, n) {\n if (!this.ft(t)) return;\n const s = this.lt(t);\n this.It(t, e) ? s.Y(e, 1 /* Removed */) : \n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n s.X(e), this.rt = this.rt.insert(e, this.Tt(e).delete(t)), n && (this.it = this.it.insert(e, n));\n }\n removeTarget(t) {\n this.st.delete(t);\n }\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */ gt(t) {\n const e = this.lt(t).H();\n return this.nt.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;\n }\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */ Z(t) {\n this.lt(t).Z();\n }\n lt(t) {\n let e = this.st.get(t);\n return e || (e = new os, this.st.set(t, e)), e;\n }\n Tt(t) {\n let e = this.rt.get(t);\n return e || (e = new qn(rt), this.rt = this.rt.insert(t, e)), e;\n }\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */ ft(t) {\n const e = null !== this.wt(t);\n return e || O(\"WatchChangeAggregator\", \"Detected inactive target\", t), e;\n }\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */ wt(t) {\n const e = this.st.get(t);\n return e && e.G ? null : this.nt.Et(t);\n }\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */ dt(t) {\n this.st.set(t, new os);\n this.nt.getRemoteKeysForTarget(t).forEach((e => {\n this.ct(t, e, /*updatedDocument=*/ null);\n }));\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */ It(t, e) {\n return this.nt.getRemoteKeysForTarget(t).has(e);\n }\n}\n\nfunction as() {\n return new Bn(xt.comparator);\n}\n\nfunction cs() {\n return new Bn(xt.comparator);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const hs = (() => {\n const t = {\n asc: \"ASCENDING\",\n desc: \"DESCENDING\"\n };\n return t;\n})(), ls = (() => {\n const t = {\n \"<\": \"LESS_THAN\",\n \"<=\": \"LESS_THAN_OR_EQUAL\",\n \">\": \"GREATER_THAN\",\n \">=\": \"GREATER_THAN_OR_EQUAL\",\n \"==\": \"EQUAL\",\n \"!=\": \"NOT_EQUAL\",\n \"array-contains\": \"ARRAY_CONTAINS\",\n in: \"IN\",\n \"not-in\": \"NOT_IN\",\n \"array-contains-any\": \"ARRAY_CONTAINS_ANY\"\n };\n return t;\n})();\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nclass fs {\n constructor(t, e) {\n this.databaseId = t, this.N = e;\n }\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nfunction ds(t, e) {\n if (t.N) {\n return `${new Date(1e3 * e.seconds).toISOString().replace(/\\.\\d*/, \"\").replace(\"Z\", \"\")}.${(\"000000000\" + e.nanoseconds).slice(-9)}Z`;\n }\n return {\n seconds: \"\" + e.seconds,\n nanos: e.nanoseconds\n };\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nfunction _s(t, e) {\n return t.N ? e.toBase64() : e.toUint8Array();\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */ function ws(t, e) {\n return ds(t, e.toTimestamp());\n}\n\nfunction ms(t) {\n return U(!!t), ct.fromTimestamp(function(t) {\n const e = Tt(t);\n return new at(e.seconds, e.nanos);\n }(t));\n}\n\nfunction gs(t, e) {\n return function(t) {\n return new _t([ \"projects\", t.projectId, \"databases\", t.database ]);\n }(t).child(\"documents\").child(e).canonicalString();\n}\n\nfunction ys(t) {\n const e = _t.fromString(t);\n return U(Gs(e)), e;\n}\n\nfunction ps(t, e) {\n return gs(t.databaseId, e.path);\n}\n\nfunction Is(t, e) {\n const n = ys(e);\n if (n.get(1) !== t.databaseId.projectId) throw new Q(G.INVALID_ARGUMENT, \"Tried to deserialize key from different project: \" + n.get(1) + \" vs \" + t.databaseId.projectId);\n if (n.get(3) !== t.databaseId.database) throw new Q(G.INVALID_ARGUMENT, \"Tried to deserialize key from different database: \" + n.get(3) + \" vs \" + t.databaseId.database);\n return new xt(Rs(n));\n}\n\nfunction Ts(t, e) {\n return gs(t.databaseId, e);\n}\n\nfunction Es(t) {\n const e = ys(t);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n return 4 === e.length ? _t.emptyPath() : Rs(e);\n}\n\nfunction As(t) {\n return new _t([ \"projects\", t.databaseId.projectId, \"databases\", t.databaseId.database ]).canonicalString();\n}\n\nfunction Rs(t) {\n return U(t.length > 4 && \"documents\" === t.get(4)), t.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */ function Ps(t, e, n) {\n return {\n name: ps(t, e),\n fields: n.value.mapValue.fields\n };\n}\n\nfunction bs(t, e, n) {\n const s = Is(t, e.name), i = ms(e.updateTime), r = new te({\n mapValue: {\n fields: e.fields\n }\n }), o = ne.newFoundDocument(s, i, r);\n return n && o.setHasCommittedMutations(), n ? o.setHasCommittedMutations() : o;\n}\n\nfunction Vs(t, e) {\n return \"found\" in e ? function(t, e) {\n U(!!e.found), e.found.name, e.found.updateTime;\n const n = Is(t, e.found.name), s = ms(e.found.updateTime), i = new te({\n mapValue: {\n fields: e.found.fields\n }\n });\n return ne.newFoundDocument(n, s, i);\n }(t, e) : \"missing\" in e ? function(t, e) {\n U(!!e.missing), U(!!e.readTime);\n const n = Is(t, e.missing), s = ms(e.readTime);\n return ne.newNoDocument(n, s);\n }(t, e) : L();\n}\n\nfunction vs(t, e) {\n let n;\n if (\"targetChange\" in e) {\n e.targetChange;\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const s = function(t) {\n return \"NO_CHANGE\" === t ? 0 /* NoChange */ : \"ADD\" === t ? 1 /* Added */ : \"REMOVE\" === t ? 2 /* Removed */ : \"CURRENT\" === t ? 3 /* Current */ : \"RESET\" === t ? 4 /* Reset */ : L();\n }(e.targetChange.targetChangeType || \"NO_CHANGE\"), i = e.targetChange.targetIds || [], r = function(t, e) {\n return t.N ? (U(void 0 === e || \"string\" == typeof e), pt.fromBase64String(e || \"\")) : (U(void 0 === e || e instanceof Uint8Array), \n pt.fromUint8Array(e || new Uint8Array));\n }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {\n const e = void 0 === t.code ? G.UNKNOWN : Fn(t.code);\n return new Q(e, t.message || \"\");\n }\n /**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: } struct.\n */ (o);\n n = new rs(s, i, r, u || null);\n } else if (\"documentChange\" in e) {\n e.documentChange;\n const s = e.documentChange;\n s.document, s.document.name, s.document.updateTime;\n const i = Is(t, s.document.name), r = ms(s.document.updateTime), o = new te({\n mapValue: {\n fields: s.document.fields\n }\n }), u = ne.newFoundDocument(i, r, o), a = s.targetIds || [], c = s.removedTargetIds || [];\n n = new ss(a, c, u.key, u);\n } else if (\"documentDelete\" in e) {\n e.documentDelete;\n const s = e.documentDelete;\n s.document;\n const i = Is(t, s.document), r = s.readTime ? ms(s.readTime) : ct.min(), o = ne.newNoDocument(i, r), u = s.removedTargetIds || [];\n n = new ss([], u, o.key, o);\n } else if (\"documentRemove\" in e) {\n e.documentRemove;\n const s = e.documentRemove;\n s.document;\n const i = Is(t, s.document), r = s.removedTargetIds || [];\n n = new ss([], r, i, null);\n } else {\n if (!(\"filter\" in e)) return L();\n {\n e.filter;\n const t = e.filter;\n t.targetId;\n const s = t.count || 0, i = new Nn(s), r = t.targetId;\n n = new is(r, i);\n }\n }\n return n;\n}\n\nfunction Ss(t, e) {\n let n;\n if (e instanceof bn) n = {\n update: Ps(t, e.key, e.value)\n }; else if (e instanceof Cn) n = {\n delete: ps(t, e.key)\n }; else if (e instanceof Vn) n = {\n update: Ps(t, e.key, e.data),\n updateMask: Ks(e.fieldMask)\n }; else {\n if (!(e instanceof xn)) return L();\n n = {\n verify: ps(t, e.key)\n };\n }\n return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {\n const n = e.transform;\n if (n instanceof un) return {\n fieldPath: e.field.canonicalString(),\n setToServerValue: \"REQUEST_TIME\"\n };\n if (n instanceof an) return {\n fieldPath: e.field.canonicalString(),\n appendMissingElements: {\n values: n.elements\n }\n };\n if (n instanceof hn) return {\n fieldPath: e.field.canonicalString(),\n removeAllFromArray: {\n values: n.elements\n }\n };\n if (n instanceof fn) return {\n fieldPath: e.field.canonicalString(),\n increment: n.k\n };\n throw L();\n }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {\n return void 0 !== e.updateTime ? {\n updateTime: ws(t, e.updateTime)\n } : void 0 !== e.exists ? {\n exists: e.exists\n } : L();\n }(t, e.precondition)), n;\n}\n\nfunction Ds(t, e) {\n const n = e.currentDocument ? function(t) {\n return void 0 !== t.updateTime ? yn.updateTime(ms(t.updateTime)) : void 0 !== t.exists ? yn.exists(t.exists) : yn.none();\n }(e.currentDocument) : yn.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {\n let n = null;\n if (\"setToServerValue\" in e) U(\"REQUEST_TIME\" === e.setToServerValue), n = new un; else if (\"appendMissingElements\" in e) {\n const t = e.appendMissingElements.values || [];\n n = new an(t);\n } else if (\"removeAllFromArray\" in e) {\n const t = e.removeAllFromArray.values || [];\n n = new hn(t);\n } else \"increment\" in e ? n = new fn(t, e.increment) : L();\n const s = mt.fromServerFormat(e.fieldPath);\n return new wn(s, n);\n }(t, e))) : [];\n if (e.update) {\n e.update.name;\n const i = Is(t, e.update.name), r = new te({\n mapValue: {\n fields: e.update.fields\n }\n });\n if (e.updateMask) {\n const t = function(t) {\n const e = t.fieldPaths || [];\n return new gt(e.map((t => mt.fromServerFormat(t))));\n }(e.updateMask);\n return new Vn(i, r, t, n, s);\n }\n return new bn(i, r, n, s);\n }\n if (e.delete) {\n const s = Is(t, e.delete);\n return new Cn(s, n);\n }\n if (e.verify) {\n const s = Is(t, e.verify);\n return new xn(s, n);\n }\n return L();\n}\n\nfunction Cs(t, e) {\n return t && t.length > 0 ? (U(void 0 !== e), t.map((t => function(t, e) {\n // NOTE: Deletes don't have an updateTime.\n let n = t.updateTime ? ms(t.updateTime) : ms(e);\n return n.isEqual(ct.min()) && (\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n n = ms(e)), new gn(n, t.transformResults || []);\n }(t, e)))) : [];\n}\n\nfunction xs(t, e) {\n return {\n documents: [ Ts(t, e.path) ]\n };\n}\n\nfunction Ns(t, e) {\n // Dissect the path into parent, collectionId, and optional key filter.\n const n = {\n structuredQuery: {}\n }, s = e.path;\n null !== e.collectionGroup ? (n.parent = Ts(t, s), n.structuredQuery.from = [ {\n collectionId: e.collectionGroup,\n allDescendants: !0\n } ]) : (n.parent = Ts(t, s.popLast()), n.structuredQuery.from = [ {\n collectionId: s.lastSegment()\n } ]);\n const i = function(t) {\n if (0 === t.length) return;\n const e = t.map((t => \n // visible for testing\n function(t) {\n if (\"==\" /* EQUAL */ === t.op) {\n if (jt(t.value)) return {\n unaryFilter: {\n field: Bs(t.field),\n op: \"IS_NAN\"\n }\n };\n if (Qt(t.value)) return {\n unaryFilter: {\n field: Bs(t.field),\n op: \"IS_NULL\"\n }\n };\n } else if (\"!=\" /* NOT_EQUAL */ === t.op) {\n if (jt(t.value)) return {\n unaryFilter: {\n field: Bs(t.field),\n op: \"IS_NOT_NAN\"\n }\n };\n if (Qt(t.value)) return {\n unaryFilter: {\n field: Bs(t.field),\n op: \"IS_NOT_NULL\"\n }\n };\n }\n return {\n fieldFilter: {\n field: Bs(t.field),\n op: $s(t.op),\n value: t.value\n }\n };\n }(t)));\n if (1 === e.length) return e[0];\n return {\n compositeFilter: {\n op: \"AND\",\n filters: e\n }\n };\n }(e.filters);\n i && (n.structuredQuery.where = i);\n const r = function(t) {\n if (0 === t.length) return;\n return t.map((t => \n // visible for testing\n function(t) {\n return {\n field: Bs(t.field),\n direction: Fs(t.dir)\n };\n }(t)));\n }(e.orderBy);\n r && (n.structuredQuery.orderBy = r);\n const o = function(t, e) {\n return t.N || St(e) ? e : {\n value: e\n };\n }\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */ (t, e.limit);\n var u;\n return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {\n before: (u = e.startAt).inclusive,\n values: u.position\n }), e.endAt && (n.structuredQuery.endAt = function(t) {\n return {\n before: !t.inclusive,\n values: t.position\n };\n }(e.endAt)), n;\n}\n\nfunction ks(t) {\n let e = Es(t.parent);\n const n = t.structuredQuery, s = n.from ? n.from.length : 0;\n let i = null;\n if (s > 0) {\n U(1 === s);\n const t = n.from[0];\n t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);\n }\n let r = [];\n n.where && (r = Os(n.where));\n let o = [];\n n.orderBy && (o = n.orderBy.map((t => function(t) {\n return new Ce(Ls(t.field), \n // visible for testing\n function(t) {\n switch (t) {\n case \"ASCENDING\":\n return \"asc\" /* ASCENDING */;\n\n case \"DESCENDING\":\n return \"desc\" /* DESCENDING */;\n\n default:\n return;\n }\n }\n // visible for testing\n (t.direction));\n }(t))));\n let u = null;\n n.limit && (u = function(t) {\n let e;\n return e = \"object\" == typeof t ? t.value : t, St(e) ? null : e;\n }(n.limit));\n let a = null;\n n.startAt && (a = function(t) {\n const e = !!t.before, n = t.values || [];\n return new De(n, e);\n }(n.startAt));\n let c = null;\n return n.endAt && (c = function(t) {\n const e = !t.before, n = t.values || [];\n return new De(n, e);\n }\n // visible for testing\n (n.endAt)), Oe(e, i, o, r, u, \"F\" /* First */ , a, c);\n}\n\nfunction Ms(t, e) {\n const n = function(t, e) {\n switch (e) {\n case 0 /* Listen */ :\n return null;\n\n case 1 /* ExistenceFilterMismatch */ :\n return \"existence-filter-mismatch\";\n\n case 2 /* LimboResolution */ :\n return \"limbo-document\";\n\n default:\n return L();\n }\n }(0, e.purpose);\n return null == n ? null : {\n \"goog-listen-tags\": n\n };\n}\n\nfunction Os(t) {\n return t ? void 0 !== t.unaryFilter ? [ qs(t) ] : void 0 !== t.fieldFilter ? [ Us(t) ] : void 0 !== t.compositeFilter ? t.compositeFilter.filters.map((t => Os(t))).reduce(((t, e) => t.concat(e))) : L() : [];\n}\n\nfunction Fs(t) {\n return hs[t];\n}\n\nfunction $s(t) {\n return ls[t];\n}\n\nfunction Bs(t) {\n return {\n fieldPath: t.canonicalString()\n };\n}\n\nfunction Ls(t) {\n return mt.fromServerFormat(t.fieldPath);\n}\n\nfunction Us(t) {\n return Te.create(Ls(t.fieldFilter.field), function(t) {\n switch (t) {\n case \"EQUAL\":\n return \"==\" /* EQUAL */;\n\n case \"NOT_EQUAL\":\n return \"!=\" /* NOT_EQUAL */;\n\n case \"GREATER_THAN\":\n return \">\" /* GREATER_THAN */;\n\n case \"GREATER_THAN_OR_EQUAL\":\n return \">=\" /* GREATER_THAN_OR_EQUAL */;\n\n case \"LESS_THAN\":\n return \"<\" /* LESS_THAN */;\n\n case \"LESS_THAN_OR_EQUAL\":\n return \"<=\" /* LESS_THAN_OR_EQUAL */;\n\n case \"ARRAY_CONTAINS\":\n return \"array-contains\" /* ARRAY_CONTAINS */;\n\n case \"IN\":\n return \"in\" /* IN */;\n\n case \"NOT_IN\":\n return \"not-in\" /* NOT_IN */;\n\n case \"ARRAY_CONTAINS_ANY\":\n return \"array-contains-any\" /* ARRAY_CONTAINS_ANY */;\n\n default:\n return L();\n }\n }(t.fieldFilter.op), t.fieldFilter.value);\n}\n\nfunction qs(t) {\n switch (t.unaryFilter.op) {\n case \"IS_NAN\":\n const e = Ls(t.unaryFilter.field);\n return Te.create(e, \"==\" /* EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NULL\":\n const n = Ls(t.unaryFilter.field);\n return Te.create(n, \"==\" /* EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n case \"IS_NOT_NAN\":\n const s = Ls(t.unaryFilter.field);\n return Te.create(s, \"!=\" /* NOT_EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NOT_NULL\":\n const i = Ls(t.unaryFilter.field);\n return Te.create(i, \"!=\" /* NOT_EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n default:\n return L();\n }\n}\n\nfunction Ks(t) {\n const e = [];\n return t.fields.forEach((t => e.push(t.canonicalString()))), {\n fieldPaths: e\n };\n}\n\nfunction Gs(t) {\n // Resource names have at least 4 components (project ID, database ID)\n return t.length >= 4 && \"projects\" === t.get(0) && \"databases\" === t.get(2);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction Qs(t) {\n let e = \"\";\n for (let n = 0; n < t.length; n++) e.length > 0 && (e = Ws(e)), e = js(t.get(n), e);\n return Ws(e);\n}\n\n/** Encodes a single segment of a resource path into the given result */ function js(t, e) {\n let n = e;\n const s = t.length;\n for (let e = 0; e < s; e++) {\n const s = t.charAt(e);\n switch (s) {\n case \"\\0\":\n n += \"\u0001\u0010\";\n break;\n\n case \"\u0001\":\n n += \"\u0001\u0011\";\n break;\n\n default:\n n += s;\n }\n }\n return n;\n}\n\n/** Encodes a path separator into the given result */ function Ws(t) {\n return t + \"\u0001\u0001\";\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */ function zs(t) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const e = t.length;\n if (U(e >= 2), 2 === e) return U(\"\u0001\" === t.charAt(0) && \"\u0001\" === t.charAt(1)), _t.emptyPath();\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const n = e - 2, s = [];\n let i = \"\";\n for (let r = 0; r < e; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const e = t.indexOf(\"\u0001\", r);\n (e < 0 || e > n) && L();\n switch (t.charAt(e + 1)) {\n case \"\u0001\":\n const n = t.substring(r, e);\n let o;\n 0 === i.length ? \n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n o = n : (i += n, o = i, i = \"\"), s.push(o);\n break;\n\n case \"\u0010\":\n i += t.substring(r, e), i += \"\\0\";\n break;\n\n case \"\u0011\":\n // The escape character can be used in the output to encode itself.\n i += t.substring(r, e + 1);\n break;\n\n default:\n L();\n }\n r = e + 2;\n }\n return new _t(s);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Hs = [ \"userId\", \"batchId\" ];\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nfunction Js(t, e) {\n return [ t, Qs(e) ];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */ function Ys(t, e, n) {\n return [ t, Qs(e), n ];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */ const Xs = {}, Zs = [ \"prefixPath\", \"collectionGroup\", \"readTime\", \"documentId\" ], ti = [ \"prefixPath\", \"collectionGroup\", \"documentId\" ], ei = [ \"collectionGroup\", \"readTime\", \"prefixPath\", \"documentId\" ], ni = [ \"canonicalId\", \"targetId\" ], si = [ \"targetId\", \"path\" ], ii = [ \"path\", \"targetId\" ], ri = [ \"collectionId\", \"parent\" ], oi = [ \"indexId\", \"uid\" ], ui = [ \"uid\", \"sequenceNumber\" ], ai = [ \"indexId\", \"uid\", \"arrayValue\", \"directionalValue\", \"orderedDocumentKey\", \"documentKey\" ], ci = [ \"indexId\", \"uid\", \"orderedDocumentKey\" ], hi = [ \"userId\", \"collectionPath\", \"documentId\" ], li = [ \"userId\", \"collectionPath\", \"largestBatchId\" ], fi = [ \"userId\", \"collectionGroup\", \"largestBatchId\" ], di = [ ...[ ...[ ...[ ...[ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocuments\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\" ], \"clientMetadata\" ], \"remoteDocumentGlobal\" ], \"collectionParents\" ], \"bundles\", \"namedQueries\" ], _i = [ ...di, \"documentOverlays\" ], wi = [ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocumentsV14\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\", \"clientMetadata\", \"remoteDocumentGlobal\", \"collectionParents\", \"bundles\", \"namedQueries\", \"documentOverlays\" ], mi = [ ...wi, \"indexConfiguration\", \"indexState\", \"indexEntries\" ];\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst gi = \"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.\";\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */ class yi {\n constructor() {\n this.onCommittedListeners = [];\n }\n addOnCommittedListener(t) {\n this.onCommittedListeners.push(t);\n }\n raiseOnCommittedEvent() {\n this.onCommittedListeners.forEach((t => t()));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */ class pi {\n constructor(t) {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n this.nextCallback = null, this.catchCallback = null, \n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = void 0, this.error = void 0, this.isDone = !1, \n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = !1, t((t => {\n this.isDone = !0, this.result = t, this.nextCallback && \n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(t);\n }), (t => {\n this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);\n }));\n }\n catch(t) {\n return this.next(void 0, t);\n }\n next(t, e) {\n return this.callbackAttached && L(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new pi(((n, s) => {\n this.nextCallback = e => {\n this.wrapSuccess(t, e).next(n, s);\n }, this.catchCallback = t => {\n this.wrapFailure(e, t).next(n, s);\n };\n }));\n }\n toPromise() {\n return new Promise(((t, e) => {\n this.next(t, e);\n }));\n }\n wrapUserFunction(t) {\n try {\n const e = t();\n return e instanceof pi ? e : pi.resolve(e);\n } catch (t) {\n return pi.reject(t);\n }\n }\n wrapSuccess(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : pi.resolve(e);\n }\n wrapFailure(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : pi.reject(e);\n }\n static resolve(t) {\n return new pi(((e, n) => {\n e(t);\n }));\n }\n static reject(t) {\n return new pi(((e, n) => {\n n(t);\n }));\n }\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t) {\n return new pi(((e, n) => {\n let s = 0, i = 0, r = !1;\n t.forEach((t => {\n ++s, t.next((() => {\n ++i, r && i === s && e();\n }), (t => n(t)));\n })), r = !0, i === s && e();\n }));\n }\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */ static or(t) {\n let e = pi.resolve(!1);\n for (const n of t) e = e.next((t => t ? pi.resolve(t) : n()));\n return e;\n }\n static forEach(t, e) {\n const n = [];\n return t.forEach(((t, s) => {\n n.push(e.call(this, t, s));\n })), this.waitFor(n);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nclass Ii {\n constructor(t, e) {\n this.action = t, this.transaction = e, this.aborted = !1, \n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n this.At = new j, this.transaction.oncomplete = () => {\n this.At.resolve();\n }, this.transaction.onabort = () => {\n e.error ? this.At.reject(new Ai(t, e.error)) : this.At.resolve();\n }, this.transaction.onerror = e => {\n const n = vi(e.target.error);\n this.At.reject(new Ai(t, n));\n };\n }\n static open(t, e, n, s) {\n try {\n return new Ii(e, t.transaction(s, n));\n } catch (t) {\n throw new Ai(e, t);\n }\n }\n get Rt() {\n return this.At.promise;\n }\n abort(t) {\n t && this.At.reject(t), this.aborted || (O(\"SimpleDb\", \"Aborting transaction:\", t ? t.message : \"Client-initiated abort\"), \n this.aborted = !0, this.transaction.abort());\n }\n Pt() {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const t = this.transaction;\n this.aborted || \"function\" != typeof t.commit || t.commit();\n }\n /**\n * Returns a SimpleDbStore for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */ store(t) {\n const e = this.transaction.objectStore(t);\n return new Pi(e);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */ class Ti {\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(t, e, n) {\n this.name = t, this.version = e, this.bt = n;\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n 12.2 === Ti.Vt(getUA()) && F(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");\n }\n /** Deletes the specified database. */ static delete(t) {\n return O(\"SimpleDb\", \"Removing database:\", t), bi(window.indexedDB.deleteDatabase(t)).toPromise();\n }\n /** Returns true if IndexedDB is available in the current environment. */ static vt() {\n if (!isIndexedDBAvailable()) return !1;\n if (Ti.St()) return !0;\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n const t = getUA(), e = Ti.Vt(t), n = 0 < e && e < 10, s = Ti.Dt(t), i = 0 < s && s < 4.5;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n // iOS Safari: Disable for users running iOS version < 10.\n return !(t.indexOf(\"MSIE \") > 0 || t.indexOf(\"Trident/\") > 0 || t.indexOf(\"Edge/\") > 0 || n || i);\n }\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */ static St() {\n var t;\n return \"undefined\" != typeof process && \"YES\" === (null === (t = process.env) || void 0 === t ? void 0 : t.Ct);\n }\n /** Helper to get a typed SimpleDbStore from a transaction. */ static xt(t, e) {\n return t.store(e);\n }\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static Vt(t) {\n const e = t.match(/i(?:phone|pad|pod) os ([\\d_]+)/i), n = e ? e[1].split(\"_\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static Dt(t) {\n const e = t.match(/Android ([\\d.]+)/i), n = e ? e[1].split(\".\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */ async Nt(t) {\n return this.db || (O(\"SimpleDb\", \"Opening database:\", this.name), this.db = await new Promise(((e, n) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const s = indexedDB.open(this.name, this.version);\n s.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, s.onblocked = () => {\n n(new Ai(t, \"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));\n }, s.onerror = e => {\n const s = e.target.error;\n \"VersionError\" === s.name ? n(new Q(G.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\" === s.name ? n(new Q(G.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: \" + s)) : n(new Ai(t, s));\n }, s.onupgradeneeded = t => {\n O(\"SimpleDb\", 'Database \"' + this.name + '\" requires upgrade from version:', t.oldVersion);\n const e = t.target.result;\n this.bt.kt(e, s.transaction, t.oldVersion, this.version).next((() => {\n O(\"SimpleDb\", \"Database upgrade to version \" + this.version + \" complete\");\n }));\n };\n }))), this.Mt && (this.db.onversionchange = t => this.Mt(t)), this.db;\n }\n Ot(t) {\n this.Mt = t, this.db && (this.db.onversionchange = e => t(e));\n }\n async runTransaction(t, e, n, s) {\n const i = \"readonly\" === e;\n let r = 0;\n for (;;) {\n ++r;\n try {\n this.db = await this.Nt(t);\n const e = Ii.open(this.db, t, i ? \"readonly\" : \"readwrite\", n), r = s(e).next((t => (e.Pt(), \n t))).catch((t => (\n // Abort the transaction if there was an error.\n e.abort(t), pi.reject(t)))).toPromise();\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n return r.catch((() => {})), \n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await e.Rt, r;\n } catch (t) {\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const e = \"FirebaseError\" !== t.name && r < 3;\n if (O(\"SimpleDb\", \"Transaction failed with error:\", t.message, \"Retrying:\", e), \n this.close(), !e) return Promise.reject(t);\n }\n }\n }\n close() {\n this.db && this.db.close(), this.db = void 0;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */ class Ei {\n constructor(t) {\n this.Ft = t, this.$t = !1, this.Bt = null;\n }\n get isDone() {\n return this.$t;\n }\n get Lt() {\n return this.Bt;\n }\n set cursor(t) {\n this.Ft = t;\n }\n /**\n * This function can be called to stop iteration at any point.\n */ done() {\n this.$t = !0;\n }\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */ Ut(t) {\n this.Bt = t;\n }\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */ delete() {\n return bi(this.Ft.delete());\n }\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */ class Ai extends Q {\n constructor(t, e) {\n super(G.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = \"IndexedDbTransactionError\";\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */ function Ri(t) {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return \"IndexedDbTransactionError\" === t.name;\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ class Pi {\n constructor(t) {\n this.store = t;\n }\n put(t, e) {\n let n;\n return void 0 !== e ? (O(\"SimpleDb\", \"PUT\", this.store.name, t, e), n = this.store.put(e, t)) : (O(\"SimpleDb\", \"PUT\", this.store.name, \"\", t), \n n = this.store.put(t)), bi(n);\n }\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */ add(t) {\n O(\"SimpleDb\", \"ADD\", this.store.name, t, t);\n return bi(this.store.add(t));\n }\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */ get(t) {\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return bi(this.store.get(t)).next((e => (\n // Normalize nonexistence to null.\n void 0 === e && (e = null), O(\"SimpleDb\", \"GET\", this.store.name, t, e), e)));\n }\n delete(t) {\n O(\"SimpleDb\", \"DELETE\", this.store.name, t);\n return bi(this.store.delete(t));\n }\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */ count() {\n O(\"SimpleDb\", \"COUNT\", this.store.name);\n return bi(this.store.count());\n }\n qt(t, e) {\n const n = this.options(t, e);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster. Unfortunately, getAll() does not support custom indices.\n if (n.index || \"function\" != typeof this.store.getAll) {\n const t = this.cursor(n), e = [];\n return this.Kt(t, ((t, n) => {\n e.push(n);\n })).next((() => e));\n }\n {\n const t = this.store.getAll(n.range);\n return new pi(((e, n) => {\n t.onerror = t => {\n n(t.target.error);\n }, t.onsuccess = t => {\n e(t.target.result);\n };\n }));\n }\n }\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */ Gt(t, e) {\n const n = this.store.getAll(t, null === e ? void 0 : e);\n return new pi(((t, e) => {\n n.onerror = t => {\n e(t.target.error);\n }, n.onsuccess = e => {\n t(e.target.result);\n };\n }));\n }\n Qt(t, e) {\n O(\"SimpleDb\", \"DELETE ALL\", this.store.name);\n const n = this.options(t, e);\n n.jt = !1;\n const s = this.cursor(n);\n return this.Kt(s, ((t, e, n) => n.delete()));\n }\n Wt(t, e) {\n let n;\n e ? n = t : (n = {}, e = t);\n const s = this.cursor(n);\n return this.Kt(s, e);\n }\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */ zt(t) {\n const e = this.cursor({});\n return new pi(((n, s) => {\n e.onerror = t => {\n const e = vi(t.target.error);\n s(e);\n }, e.onsuccess = e => {\n const s = e.target.result;\n s ? t(s.primaryKey, s.value).next((t => {\n t ? s.continue() : n();\n })) : n();\n };\n }));\n }\n Kt(t, e) {\n const n = [];\n return new pi(((s, i) => {\n t.onerror = t => {\n i(t.target.error);\n }, t.onsuccess = t => {\n const i = t.target.result;\n if (!i) return void s();\n const r = new Ei(i), o = e(i.primaryKey, i.value, r);\n if (o instanceof pi) {\n const t = o.catch((t => (r.done(), pi.reject(t))));\n n.push(t);\n }\n r.isDone ? s() : null === r.Lt ? i.continue() : i.continue(r.Lt);\n };\n })).next((() => pi.waitFor(n)));\n }\n options(t, e) {\n let n;\n return void 0 !== t && (\"string\" == typeof t ? n = t : e = t), {\n index: n,\n range: e\n };\n }\n cursor(t) {\n let e = \"next\";\n if (t.reverse && (e = \"prev\"), t.index) {\n const n = this.store.index(t.index);\n return t.jt ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);\n }\n return this.store.openCursor(t.range, e);\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */ function bi(t) {\n return new pi(((e, n) => {\n t.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, t.onerror = t => {\n const e = vi(t.target.error);\n n(e);\n };\n }));\n}\n\n// Guard so we only report the error once.\nlet Vi = !1;\n\nfunction vi(t) {\n const e = Ti.Vt(getUA());\n if (e >= 12.2 && e < 13) {\n const e = \"An internal error was encountered in the Indexed Database server\";\n if (t.message.indexOf(e) >= 0) {\n // Wrap error in a more descriptive one.\n const t = new Q(\"internal\", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);\n return Vi || (Vi = !0, \n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout((() => {\n throw t;\n }), 0)), t;\n }\n }\n return t;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Si extends yi {\n constructor(t, e) {\n super(), this.Ht = t, this.currentSequenceNumber = e;\n }\n}\n\nfunction Di(t, e) {\n const n = K(t);\n return Ti.xt(n.Ht, e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */ class Ci {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(t, e, n, s) {\n this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */ applyToRemoteDocument(t, e) {\n const n = e.mutationResults;\n for (let e = 0; e < this.mutations.length; e++) {\n const s = this.mutations[e];\n if (s.key.isEqual(t.key)) {\n Tn(s, t, n[e]);\n }\n }\n }\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n */ applyToLocalView(t) {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const e of this.baseMutations) e.key.isEqual(t.key) && En(e, t, this.localWriteTime);\n // Second, apply all user-provided mutations.\n for (const e of this.mutations) e.key.isEqual(t.key) && En(e, t, this.localWriteTime);\n }\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch.\n */ applyToLocalDocumentSet(t) {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n this.mutations.forEach((e => {\n const n = t.get(e.key), s = n;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n this.applyToLocalView(s), n.isValidDocument() || s.convertToNoDocument(ct.min());\n }));\n }\n keys() {\n return this.mutations.reduce(((t, e) => t.add(e.key)), Xn());\n }\n isEqual(t) {\n return this.batchId === t.batchId && ot(this.mutations, t.mutations, ((t, e) => Rn(t, e))) && ot(this.baseMutations, t.baseMutations, ((t, e) => Rn(t, e)));\n }\n}\n\n/** The result of applying a mutation batch to the backend. */ class xi {\n constructor(t, e, n, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n s) {\n this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */ static from(t, e, n) {\n U(t.mutations.length === n.length);\n let s = Jn;\n const i = t.mutations;\n for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);\n return new xi(t, e, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */ class Ni {\n constructor(t, e) {\n this.largestBatchId = t, this.mutation = e;\n }\n getKey() {\n return this.mutation.key;\n }\n isEqual(t) {\n return null !== t && this.mutation === t.mutation;\n }\n toString() {\n return `Overlay{\\n largestBatchId: ${this.largestBatchId},\\n mutation: ${this.mutation.toString()}\\n }`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */ class ki {\n constructor(\n /** The target being listened to. */\n t, \n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n e, \n /** The purpose of the target. */\n n, \n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n s, \n /** The latest snapshot version seen for this target. */\n i = ct.min()\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */ , r = ct.min()\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */ , o = pt.EMPTY_BYTE_STRING) {\n this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i, \n this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o;\n }\n /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {\n return new ki(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);\n }\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */ withResumeToken(t, e) {\n return new ki(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);\n }\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */ withLastLimboFreeSnapshotVersion(t) {\n return new ki(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Serializer for values stored in the LocalStore. */ class Mi {\n constructor(t) {\n this.Jt = t;\n }\n}\n\n/** Decodes a remote document from storage locally to a Document. */ function Oi(t, e) {\n let n;\n if (e.document) n = bs(t.Jt, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {\n const t = xt.fromSegments(e.noDocument.path), s = Li(e.noDocument.readTime);\n n = ne.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();\n } else {\n if (!e.unknownDocument) return L();\n {\n const t = xt.fromSegments(e.unknownDocument.path), s = Li(e.unknownDocument.version);\n n = ne.newUnknownDocument(t, s);\n }\n }\n return e.readTime && n.setReadTime(function(t) {\n const e = new at(t[0], t[1]);\n return ct.fromTimestamp(e);\n }(e.readTime)), n;\n}\n\n/** Encodes a document for storage locally. */ function Fi(t, e) {\n const n = e.key, s = {\n prefixPath: n.getCollectionPath().popLast().toArray(),\n collectionGroup: n.collectionGroup,\n documentId: n.path.lastSegment(),\n readTime: $i(e.readTime),\n hasCommittedMutations: e.hasCommittedMutations\n };\n if (e.isFoundDocument()) s.document = function(t, e) {\n return {\n name: ps(t, e.key),\n fields: e.data.value.mapValue.fields,\n updateTime: ds(t, e.version.toTimestamp())\n };\n }(t.Jt, e); else if (e.isNoDocument()) s.noDocument = {\n path: n.path.toArray(),\n readTime: Bi(e.version)\n }; else {\n if (!e.isUnknownDocument()) return L();\n s.unknownDocument = {\n path: n.path.toArray(),\n version: Bi(e.version)\n };\n }\n return s;\n}\n\nfunction $i(t) {\n const e = t.toTimestamp();\n return [ e.seconds, e.nanoseconds ];\n}\n\nfunction Bi(t) {\n const e = t.toTimestamp();\n return {\n seconds: e.seconds,\n nanoseconds: e.nanoseconds\n };\n}\n\nfunction Li(t) {\n const e = new at(t.seconds, t.nanoseconds);\n return ct.fromTimestamp(e);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n/** Decodes a DbMutationBatch into a MutationBatch */\nfunction Ui(t, e) {\n const n = (e.baseMutations || []).map((e => Ds(t.Jt, e)));\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let t = 0; t < e.mutations.length - 1; ++t) {\n const n = e.mutations[t];\n if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {\n const s = e.mutations[t + 1];\n n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1), \n ++t;\n }\n }\n const s = e.mutations.map((e => Ds(t.Jt, e))), i = at.fromMillis(e.localWriteTimeMs);\n return new Ci(e.batchId, i, n, s);\n}\n\n/** Decodes a DbTarget into TargetData */ function qi(t) {\n const e = Li(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? Li(t.lastLimboFreeSnapshotVersion) : ct.min();\n let s;\n var i;\n return void 0 !== t.query.documents ? (U(1 === (i = t.query).documents.length), \n s = Ge(Fe(Es(i.documents[0])))) : s = function(t) {\n return Ge(ks(t));\n }(t.query), new ki(s, t.targetId, 0 /* Listen */ , t.lastListenSequenceNumber, e, n, pt.fromBase64String(t.resumeToken));\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */ function Ki(t, e) {\n const n = Bi(e.snapshotVersion), s = Bi(e.lastLimboFreeSnapshotVersion);\n let i;\n i = ge(e.target) ? xs(t.Jt, e.target) : Ns(t.Jt, e.target);\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const r = e.resumeToken.toBase64();\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: e.targetId,\n canonicalId: _e(e.target),\n readTime: n,\n resumeToken: r,\n lastListenSequenceNumber: e.sequenceNumber,\n lastLimboFreeSnapshotVersion: s,\n query: i\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nfunction Gi(t) {\n const e = ks({\n parent: t.parent,\n structuredQuery: t.structuredQuery\n });\n return \"LAST\" === t.limitType ? Qe(e, e.limit, \"L\" /* Last */) : e;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nfunction Qi(t, e) {\n return new Ni(e.largestBatchId, Ds(t.Jt, e.overlayMutation));\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nfunction ji(t, e) {\n const n = e.path.lastSegment();\n return [ t, Qs(e.path.popLast()), n ];\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Wi {\n getBundleMetadata(t, e) {\n return zi(t).get(e).next((t => {\n if (t) return {\n id: (e = t).bundleId,\n createTime: Li(e.createTime),\n version: e.version\n };\n /** Encodes a DbBundle to a BundleMetadata object. */\n var e;\n /** Encodes a BundleMetadata to a DbBundle. */ }));\n }\n saveBundleMetadata(t, e) {\n return zi(t).put({\n bundleId: (n = e).id,\n createTime: Bi(ms(n.createTime)),\n version: n.version\n });\n var n;\n /** Encodes a DbNamedQuery to a NamedQuery. */ }\n getNamedQuery(t, e) {\n return Hi(t).get(e).next((t => {\n if (t) return {\n name: (e = t).name,\n query: Gi(e.bundledQuery),\n readTime: Li(e.readTime)\n };\n var e;\n /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));\n }\n saveNamedQuery(t, e) {\n return Hi(t).put(function(t) {\n return {\n name: t.name,\n readTime: Bi(ms(t.readTime)),\n bundledQuery: t.bundledQuery\n };\n }(e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */ function zi(t) {\n return Di(t, \"bundles\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */ function Hi(t) {\n return Di(t, \"namedQueries\");\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */ class Ji {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(t, e) {\n this.M = t, this.userId = e;\n }\n static Yt(t, e) {\n const n = e.uid || \"\";\n return new Ji(t, n);\n }\n getOverlay(t, e) {\n return Yi(t).get(ji(this.userId, e)).next((t => t ? Qi(this.M, t) : null));\n }\n saveOverlays(t, e, n) {\n const s = [];\n return n.forEach(((n, i) => {\n const r = new Ni(e, i);\n s.push(this.Xt(t, r));\n })), pi.waitFor(s);\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = new Set;\n // Get the set of unique collection paths.\n e.forEach((t => s.add(Qs(t.getCollectionPath()))));\n const i = [];\n return s.forEach((e => {\n const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n i.push(Yi(t).Qt(\"collectionPathOverlayIndex\", s));\n })), pi.waitFor(i);\n }\n getOverlaysForCollection(t, e, n) {\n const s = Hn(), i = Qs(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return Yi(t).qt(\"collectionPathOverlayIndex\", r).next((t => {\n for (const e of t) {\n const t = Qi(this.M, e);\n s.set(t.getKey(), t);\n }\n return s;\n }));\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n const i = Hn();\n let r;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return Yi(t).Wt({\n index: \"collectionGroupOverlayIndex\",\n range: o\n }, ((t, e, n) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const o = Qi(this.M, e);\n i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();\n })).next((() => i));\n }\n Xt(t, e) {\n return Yi(t).put(function(t, e, n) {\n const [s, i, r] = ji(e, n.mutation.key);\n return {\n userId: e,\n collectionPath: i,\n documentId: r,\n collectionGroup: n.mutation.key.getCollectionGroup(),\n largestBatchId: n.largestBatchId,\n overlayMutation: Ss(t.Jt, n.mutation)\n };\n }(this.M, this.userId, e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */ function Yi(t) {\n return Di(t, \"documentOverlays\");\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n/** Firestore index value writer. */\nclass Xi {\n constructor() {}\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n // As an example, consider the resulting encoding for:\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n /** Writes an index value. */\n Zt(t, e) {\n this.te(t, e), \n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n e.ee();\n }\n te(t, e) {\n if (\"nullValue\" in t) this.ne(e, 5); else if (\"booleanValue\" in t) this.ne(e, 10), \n e.se(t.booleanValue ? 1 : 0); else if (\"integerValue\" in t) this.ne(e, 15), e.se(Et(t.integerValue)); else if (\"doubleValue\" in t) {\n const n = Et(t.doubleValue);\n isNaN(n) ? this.ne(e, 13) : (this.ne(e, 15), Dt(n) ? \n // -0.0, 0 and 0.0 are all considered the same\n e.se(0) : e.se(n));\n } else if (\"timestampValue\" in t) {\n const n = t.timestampValue;\n this.ne(e, 20), \"string\" == typeof n ? e.ie(n) : (e.ie(`${n.seconds || \"\"}`), e.se(n.nanos || 0));\n } else if (\"stringValue\" in t) this.re(t.stringValue, e), this.oe(e); else if (\"bytesValue\" in t) this.ne(e, 30), \n e.ue(At(t.bytesValue)), this.oe(e); else if (\"referenceValue\" in t) this.ae(t.referenceValue, e); else if (\"geoPointValue\" in t) {\n const n = t.geoPointValue;\n this.ne(e, 45), e.se(n.latitude || 0), e.se(n.longitude || 0);\n } else \"mapValue\" in t ? Ht(t) ? this.ne(e, Number.MAX_SAFE_INTEGER) : (this.ce(t.mapValue, e), \n this.oe(e)) : \"arrayValue\" in t ? (this.he(t.arrayValue, e), this.oe(e)) : L();\n }\n re(t, e) {\n this.ne(e, 25), this.le(t, e);\n }\n le(t, e) {\n e.ie(t);\n }\n ce(t, e) {\n const n = t.fields || {};\n this.ne(e, 55);\n for (const t of Object.keys(n)) this.re(t, e), this.te(n[t], e);\n }\n he(t, e) {\n const n = t.values || [];\n this.ne(e, 50);\n for (const t of n) this.te(t, e);\n }\n ae(t, e) {\n this.ne(e, 37);\n xt.fromName(t).path.forEach((t => {\n this.ne(e, 60), this.le(t, e);\n }));\n }\n ne(t, e) {\n t.se(e);\n }\n oe(t) {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n t.se(2);\n }\n}\n\nXi.fe = new Xi;\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nfunction Zi(t) {\n if (0 === t) return 8;\n let e = 0;\n return t >> 4 == 0 && (\n // Test if the first four bits are zero.\n e += 4, t <<= 4), t >> 6 == 0 && (\n // Test if the first two (or next two) bits are zero.\n e += 2, t <<= 2), t >> 7 == 0 && (\n // Test if the remaining bit is zero.\n e += 1), e;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction tr(t) {\n // This is just the number of bytes for the unsigned representation of the number.\n const e = 64 - function(t) {\n let e = 0;\n for (let n = 0; n < 8; ++n) {\n const s = Zi(255 & t[n]);\n if (e += s, 8 !== s) break;\n }\n return e;\n }(t);\n return Math.ceil(e / 8);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */ class er {\n constructor() {\n this.buffer = new Uint8Array(1024), this.position = 0;\n }\n de(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this._e(n.value), n = e.next();\n this.we();\n }\n me(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this.ge(n.value), n = e.next();\n this.ye();\n }\n /** Writes utf8 bytes into this byte sequence, ascending. */ pe(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this._e(t); else if (t < 2048) this._e(960 | t >>> 6), this._e(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this._e(480 | t >>> 12), \n this._e(128 | 63 & t >>> 6), this._e(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this._e(240 | t >>> 18), this._e(128 | 63 & t >>> 12), this._e(128 | 63 & t >>> 6), \n this._e(128 | 63 & t);\n }\n }\n this.we();\n }\n /** Writes utf8 bytes into this byte sequence, descending */ Ie(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this.ge(t); else if (t < 2048) this.ge(960 | t >>> 6), this.ge(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this.ge(480 | t >>> 12), \n this.ge(128 | 63 & t >>> 6), this.ge(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this.ge(240 | t >>> 18), this.ge(128 | 63 & t >>> 12), this.ge(128 | 63 & t >>> 6), \n this.ge(128 | 63 & t);\n }\n }\n this.ye();\n }\n Te(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const e = this.Ee(t), n = tr(e);\n this.Ae(1 + n), this.buffer[this.position++] = 255 & n;\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];\n }\n Re(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const e = this.Ee(t), n = tr(e);\n this.Ae(1 + n), this.buffer[this.position++] = ~(255 & n);\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */ Pe() {\n this.be(255), this.be(255);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */ Ve() {\n this.ve(255), this.ve(255);\n }\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */ reset() {\n this.position = 0;\n }\n seed(t) {\n this.Ae(t.length), this.buffer.set(t, this.position), this.position += t.length;\n }\n /** Makes a copy of the encoded bytes in this buffer. */ Se() {\n return this.buffer.slice(0, this.position);\n }\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */ Ee(t) {\n const e = \n /** Converts a JavaScript number to a byte array (using big endian encoding). */\n function(t) {\n const e = new DataView(new ArrayBuffer(8));\n return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);\n }(t), n = 0 != (128 & e[0]);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n // Revert the two complement to get natural ordering\n e[0] ^= n ? 255 : 128;\n for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;\n return e;\n }\n /** Writes a single byte ascending to the buffer. */ _e(t) {\n const e = 255 & t;\n 0 === e ? (this.be(0), this.be(255)) : 255 === e ? (this.be(255), this.be(0)) : this.be(e);\n }\n /** Writes a single byte descending to the buffer. */ ge(t) {\n const e = 255 & t;\n 0 === e ? (this.ve(0), this.ve(255)) : 255 === e ? (this.ve(255), this.ve(0)) : this.ve(t);\n }\n we() {\n this.be(0), this.be(1);\n }\n ye() {\n this.ve(0), this.ve(1);\n }\n be(t) {\n this.Ae(1), this.buffer[this.position++] = t;\n }\n ve(t) {\n this.Ae(1), this.buffer[this.position++] = ~t;\n }\n Ae(t) {\n const e = t + this.position;\n if (e <= this.buffer.length) return;\n // Try doubling.\n let n = 2 * this.buffer.length;\n // Still not big enough? Just allocate the right size.\n n < e && (n = e);\n // Create the new buffer.\n const s = new Uint8Array(n);\n s.set(this.buffer), // copy old data\n this.buffer = s;\n }\n}\n\nclass nr {\n constructor(t) {\n this.De = t;\n }\n ue(t) {\n this.De.de(t);\n }\n ie(t) {\n this.De.pe(t);\n }\n se(t) {\n this.De.Te(t);\n }\n ee() {\n this.De.Pe();\n }\n}\n\nclass sr {\n constructor(t) {\n this.De = t;\n }\n ue(t) {\n this.De.me(t);\n }\n ie(t) {\n this.De.Ie(t);\n }\n se(t) {\n this.De.Re(t);\n }\n ee() {\n this.De.Ve();\n }\n}\n\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */ class ir {\n constructor() {\n this.De = new er, this.Ce = new nr(this.De), this.xe = new sr(this.De);\n }\n seed(t) {\n this.De.seed(t);\n }\n Ne(t) {\n return 0 /* ASCENDING */ === t ? this.Ce : this.xe;\n }\n Se() {\n return this.De.Se();\n }\n reset() {\n this.De.reset();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Represents an index entry saved by the SDK in persisted storage. */ class rr {\n constructor(t, e, n, s) {\n this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;\n }\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */ ke() {\n const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);\n return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1], \n new rr(this.indexId, this.documentKey, this.arrayValue, n);\n }\n}\n\nfunction or(t, e) {\n let n = t.indexId - e.indexId;\n return 0 !== n ? n : (n = ur(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = ur(t.directionalValue, e.directionalValue), \n 0 !== n ? n : xt.comparator(t.documentKey, e.documentKey)));\n}\n\nfunction ur(t, e) {\n for (let n = 0; n < t.length && n < e.length; ++n) {\n const s = t[n] - e[n];\n if (0 !== s) return s;\n }\n return t.length - e.length;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */ class ar {\n constructor(t) {\n this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(), \n this.Me = t.orderBy, this.Oe = [];\n for (const e of t.filters) {\n const t = e;\n t.S() ? this.Fe = t : this.Oe.push(t);\n }\n }\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */ $e(t) {\n // If there is an array element, find a matching filter.\n const e = ie(t);\n if (void 0 !== e && !this.Be(e)) return !1;\n const n = re(t);\n let s = 0, i = 0;\n // Process all equalities first. Equalities can appear out of order.\n for (;s < n.length && this.Be(n[s]); ++s) ;\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (s === n.length) return !0;\n // If there is an inequality filter, the next segment must match both the\n // filter and the first orderBy clause.\n if (void 0 !== this.Fe) {\n const t = n[s];\n if (!this.Le(this.Fe, t) || !this.Ue(this.Me[i++], t)) return !1;\n ++s;\n }\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (;s < n.length; ++s) {\n const t = n[s];\n if (i >= this.Me.length || !this.Ue(this.Me[i++], t)) return !1;\n }\n return !0;\n }\n Be(t) {\n for (const e of this.Oe) if (this.Le(e, t)) return !0;\n return !1;\n }\n Le(t, e) {\n if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;\n const n = \"array-contains\" /* ARRAY_CONTAINS */ === t.op || \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ === t.op;\n return 2 /* CONTAINS */ === e.kind === n;\n }\n Ue(t, e) {\n return !!t.field.isEqual(e.fieldPath) && (0 /* ASCENDING */ === e.kind && \"asc\" /* ASCENDING */ === t.dir || 1 /* DESCENDING */ === e.kind && \"desc\" /* DESCENDING */ === t.dir);\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of IndexManager.\n */ class cr {\n constructor() {\n this.qe = new hr;\n }\n addToCollectionParentIndex(t, e) {\n return this.qe.add(e), pi.resolve();\n }\n getCollectionParents(t, e) {\n return pi.resolve(this.qe.getEntries(e));\n }\n addFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return pi.resolve();\n }\n deleteFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return pi.resolve();\n }\n getDocumentsMatchingTarget(t, e) {\n // Field indices are not supported with memory persistence.\n return pi.resolve(null);\n }\n getFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return pi.resolve(null);\n }\n getFieldIndexes(t, e) {\n // Field indices are not supported with memory persistence.\n return pi.resolve([]);\n }\n getNextCollectionGroupToUpdate(t) {\n // Field indices are not supported with memory persistence.\n return pi.resolve(null);\n }\n updateCollectionGroup(t, e, n) {\n // Field indices are not supported with memory persistence.\n return pi.resolve();\n }\n updateIndexEntries(t, e) {\n // Field indices are not supported with memory persistence.\n return pi.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ class hr {\n constructor() {\n this.index = {};\n }\n // Returns false if the entry already existed.\n add(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new qn(_t.comparator), i = !s.has(n);\n return this.index[e] = s.add(n), i;\n }\n has(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e];\n return s && s.has(n);\n }\n getEntries(t) {\n return (this.index[t] || new qn(_t.comparator)).toArray();\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const lr = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nclass fr {\n constructor(t, e) {\n this.user = t, this.databaseId = e, \n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n this.Ke = new hr, \n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n this.Ge = new $n((t => _e(t)), ((t, e) => me(t, e))), this.uid = t.uid || \"\";\n }\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */ addToCollectionParentIndex(t, e) {\n if (!this.Ke.has(e)) {\n const n = e.lastSegment(), s = e.popLast();\n t.addOnCommittedListener((() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.Ke.add(e);\n }));\n const i = {\n collectionId: n,\n parent: Qs(s)\n };\n return dr(t).put(i);\n }\n return pi.resolve();\n }\n getCollectionParents(t, e) {\n const n = [], s = IDBKeyRange.bound([ e, \"\" ], [ ut(e), \"\" ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return dr(t).qt(s).next((t => {\n for (const s of t) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (s.collectionId !== e) break;\n n.push(zs(s.parent));\n }\n return n;\n }));\n }\n addFieldIndex(t, e) {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const n = wr(t), s = function(t) {\n return {\n indexId: t.indexId,\n collectionGroup: t.collectionGroup,\n fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))\n };\n }(e);\n // `indexId` is auto-populated by IndexedDb\n return delete s.indexId, n.add(s).next();\n }\n deleteFieldIndex(t, e) {\n const n = wr(t), s = mr(t), i = _r(t);\n return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0))));\n }\n getDocumentsMatchingTarget(t, e) {\n const n = _r(t);\n let s = !0;\n const i = new Map;\n return pi.forEach(this.Qe(e), (e => this.getFieldIndex(t, e).next((t => {\n s && (s = !!t), i.set(e, t);\n })))).next((() => {\n if (s) {\n let t = Xn();\n const s = [];\n return pi.forEach(i, ((i, r) => {\n /** Returns a debug representation of the field index */\n var o;\n O(\"IndexedDbIndexManager\", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(\",\")}`} to execute ${_e(e)}`);\n const u = function(t, e) {\n const n = ie(e);\n if (void 0 === n) return null;\n for (const e of ye(t, n.fieldPath)) switch (e.op) {\n case \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ :\n return e.value.arrayValue.values || [];\n\n case \"array-contains\" /* ARRAY_CONTAINS */ :\n return [ e.value ];\n // Remaining filters are not array filters.\n }\n return null;\n }\n /**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */ (r, i), a = function(t, e) {\n const n = new Map;\n for (const s of re(e)) for (const e of ye(t, s.fieldPath)) switch (e.op) {\n case \"==\" /* EQUAL */ :\n case \"in\" /* IN */ :\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n n.set(s.fieldPath.canonicalString(), e.value);\n break;\n\n case \"not-in\" /* NOT_IN */ :\n case \"!=\" /* NOT_EQUAL */ :\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());\n // Remaining filters cannot be used as notIn bounds.\n }\n return null;\n }\n /**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `null` if no lower bound\n * exists.\n */ (r, i), c = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const i of re(e)) {\n const e = 0 /* ASCENDING */ === i.kind ? pe(t, i.fieldPath, t.startAt) : Ie(t, i.fieldPath, t.startAt);\n if (!e.value) \n // No lower bound exists\n return null;\n n.push(e.value), s && (s = e.inclusive);\n }\n return new De(n, s);\n }\n /**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `null` if no\n * upper bound exists.\n */ (r, i), h = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const i of re(e)) {\n const e = 0 /* ASCENDING */ === i.kind ? Ie(t, i.fieldPath, t.endAt) : pe(t, i.fieldPath, t.endAt);\n if (!e.value) \n // No upper bound exists\n return null;\n n.push(e.value), s && (s = e.inclusive);\n }\n return new De(n, s);\n }(r, i), l = this.je(i, r, c), f = this.je(i, r, h), d = this.We(i, r, a), _ = this.ze(i.indexId, u, l, !!c && c.inclusive, f, !!h && h.inclusive, d);\n return pi.forEach(_, (i => n.Gt(i, e.limit).next((e => {\n e.forEach((e => {\n const n = xt.fromSegments(e.documentKey);\n t.has(n) || (t = t.add(n), s.push(n));\n }));\n }))));\n })).next((() => s));\n }\n return pi.resolve(null);\n }));\n }\n Qe(t) {\n let e = this.Ge.get(t);\n return e || (\n // TODO(orquery): Implement DNF transform\n e = [ t ], this.Ge.set(t, e), e);\n }\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */ ze(t, e, n, s, i, r, o) {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const u = (null != e ? e.length : 1) * Math.max(null != n ? n.length : 1, null != i ? i.length : 1), a = u / (null != e ? e.length : 1), c = [];\n for (let h = 0; h < u; ++h) {\n const u = e ? this.He(e[h / a]) : lr, l = n ? this.Je(t, u, n[h % a], s) : this.Ye(t), f = i ? this.Xe(t, u, i[h % a], r) : this.Ye(t + 1);\n c.push(...this.createRange(l, f, o.map((e => this.Je(t, u, e, \n /* inclusive= */ !0)))));\n }\n return c;\n }\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */ Je(t, e, n, s) {\n const i = new rr(t, xt.empty(), e, n);\n return s ? i : i.ke();\n }\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */ Xe(t, e, n, s) {\n const i = new rr(t, xt.empty(), e, n);\n return s ? i.ke() : i;\n }\n /**\n * Generates an empty bound that scopes the index scan to the current index\n * and user.\n */ Ye(t) {\n return new rr(t, xt.empty(), lr, lr);\n }\n getFieldIndex(t, e) {\n const n = new ar(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();\n return this.getFieldIndexes(t, s).next((t => {\n const e = t.filter((t => n.$e(t)));\n // Return the index that matches the most number of segments.\n return e.sort(((t, e) => e.fields.length - t.fields.length)), e.length > 0 ? e[0] : null;\n }));\n }\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */ Ze(t, e) {\n const n = new ir;\n for (const s of re(t)) {\n const t = e.data.field(s.fieldPath);\n if (null == t) return null;\n const i = n.Ne(s.kind);\n Xi.fe.Zt(t, i);\n }\n return n.Se();\n }\n /** Encodes a single value to the ascending index format. */ He(t) {\n const e = new ir;\n return Xi.fe.Zt(t, e.Ne(0 /* ASCENDING */)), e.Se();\n }\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */ tn(t, e) {\n const n = new ir;\n return Xi.fe.Zt(qt(this.databaseId, e), n.Ne(function(t) {\n const e = re(t);\n return 0 === e.length ? 0 /* ASCENDING */ : e[e.length - 1].kind;\n }(t))), n.Se();\n }\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */ We(t, e, n) {\n if (null === n) return [];\n let s = [];\n s.push(new ir);\n let i = 0;\n for (const r of re(t)) {\n const t = n[i++];\n for (const n of s) if (this.en(e, r.fieldPath) && Gt(t)) s = this.nn(s, r, t); else {\n const e = n.Ne(r.kind);\n Xi.fe.Zt(t, e);\n }\n }\n return this.sn(s);\n }\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */ je(t, e, n) {\n return null == n ? null : this.We(t, e, n.position);\n }\n /** Returns the byte representation for the provided encoders. */ sn(t) {\n const e = [];\n for (let n = 0; n < t.length; ++n) e[n] = t[n].Se();\n return e;\n }\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */ nn(t, e, n) {\n const s = [ ...t ], i = [];\n for (const t of n.arrayValue.values || []) for (const n of s) {\n const s = new ir;\n s.seed(n.Se()), Xi.fe.Zt(t, s.Ne(e.kind)), i.push(s);\n }\n return i;\n }\n en(t, e) {\n return !!t.filters.find((t => t instanceof Te && t.field.isEqual(e) && (\"in\" /* IN */ === t.op || \"not-in\" /* NOT_IN */ === t.op)));\n }\n getFieldIndexes(t, e) {\n const n = wr(t), s = mr(t);\n return (e ? n.qt(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)) : n.qt()).next((t => {\n const e = [];\n return pi.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {\n e.push(function(t, e) {\n const n = e ? new ue(e.sequenceNumber, new he(Li(e.readTime), new xt(zs(e.documentKey)), e.largestBatchId)) : ue.empty(), s = t.fields.map((([t, e]) => new oe(mt.fromServerFormat(t), e)));\n return new se(t.indexId, t.collectionGroup, s, n);\n }(t, n));\n })))).next((() => e));\n }));\n }\n getNextCollectionGroupToUpdate(t) {\n return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {\n const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;\n return 0 !== n ? n : rt(t.collectionGroup, e.collectionGroup);\n })), t[0].collectionGroup)));\n }\n updateCollectionGroup(t, e, n) {\n const s = wr(t), i = mr(t);\n return this.rn(t).next((t => s.qt(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)).next((e => pi.forEach(e, (e => i.put(function(t, e, n, s) {\n return {\n indexId: t,\n uid: e.uid || \"\",\n sequenceNumber: n,\n readTime: Bi(s.readTime),\n documentKey: Qs(s.documentKey.path),\n largestBatchId: s.largestBatchId\n };\n }(e.indexId, this.user, t, n))))))));\n }\n updateIndexEntries(t, e) {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const n = new Map;\n return pi.forEach(e, ((e, s) => {\n const i = n.get(e.collectionGroup);\n return (i ? pi.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i), \n pi.forEach(i, (n => this.on(t, e, n).next((e => {\n const i = this.un(s, n);\n return e.isEqual(i) ? pi.resolve() : this.an(t, s, n, e, i);\n })))))));\n }));\n }\n cn(t, e, n, s) {\n return _r(t).put({\n indexId: s.indexId,\n uid: this.uid,\n arrayValue: s.arrayValue,\n directionalValue: s.directionalValue,\n orderedDocumentKey: this.tn(n, e.key),\n documentKey: e.key.path.toArray()\n });\n }\n hn(t, e, n, s) {\n return _r(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.tn(n, e.key), e.key.path.toArray() ]);\n }\n on(t, e, n) {\n const s = _r(t);\n let i = new qn(or);\n return s.Wt({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only([ n.indexId, this.uid, this.tn(n, e) ])\n }, ((t, s) => {\n i = i.add(new rr(n.indexId, e, s.arrayValue, s.directionalValue));\n })).next((() => i));\n }\n /** Creates the index entries for the given document. */ un(t, e) {\n let n = new qn(or);\n const s = this.Ze(e, t);\n if (null == s) return n;\n const i = ie(e);\n if (null != i) {\n const r = t.data.field(i.fieldPath);\n if (Gt(r)) for (const i of r.arrayValue.values || []) n = n.add(new rr(e.indexId, t.key, this.He(i), s));\n } else n = n.add(new rr(e.indexId, t.key, lr, s));\n return n;\n }\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */ an(t, e, n, s, i) {\n O(\"IndexedDbIndexManager\", \"Updating index entries for document '%s'\", e.key);\n const r = [];\n return function(t, e, n, s, i) {\n const r = t.getIterator(), o = e.getIterator();\n let u = Gn(r), a = Gn(o);\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n for (;u || a; ) {\n let t = !1, e = !1;\n if (u && a) {\n const s = n(u, a);\n s < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n e = !0 : s > 0 && (\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n t = !0);\n } else null != u ? e = !0 : t = !0;\n t ? (s(a), a = Gn(o)) : e ? (i(u), u = Gn(r)) : (u = Gn(r), a = Gn(o));\n }\n }(s, i, or, (\n /* onAdd= */ s => {\n r.push(this.cn(t, e, n, s));\n }), (\n /* onRemove= */ s => {\n r.push(this.hn(t, e, n, s));\n })), pi.waitFor(r);\n }\n rn(t) {\n let e = 1;\n return mr(t).Wt({\n index: \"sequenceNumberIndex\",\n reverse: !0,\n range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])\n }, ((t, n, s) => {\n s.done(), e = n.sequenceNumber + 1;\n })).next((() => e));\n }\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */ createRange(t, e, n) {\n // The notIb values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n n = n.sort(((t, e) => or(t, e))).filter(((t, e, n) => !e || 0 !== or(t, n[e - 1])));\n const s = [];\n s.push(t);\n for (const i of n) {\n const n = or(i, t), r = or(i, e);\n if (0 === n) \n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n s[0] = t.ke(); else if (n > 0 && r < 0) \n // `notInValue` is in the middle of the range\n s.push(i), s.push(i.ke()); else if (r > 0) \n // `notInValue` (and all following values) are out of the range\n break;\n }\n s.push(e);\n const i = [];\n for (let t = 0; t < s.length; t += 2) i.push(IDBKeyRange.bound([ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, lr, [] ], [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, lr, [] ]));\n return i;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */ function dr(t) {\n return Di(t, \"collectionParents\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */ function _r(t) {\n return Di(t, \"indexEntries\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */ function wr(t) {\n return Di(t, \"indexConfiguration\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */ function mr(t) {\n return Di(t, \"indexState\");\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const gr = {\n didRun: !1,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nclass yr {\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n t, \n // The percentage of sequence numbers that we will attempt to collect\n e, \n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n n) {\n this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;\n }\n static withCacheSize(t) {\n return new yr(t, yr.DEFAULT_COLLECTION_PERCENTILE, yr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nfunction pr(t, e, n) {\n const s = t.store(\"mutations\"), i = t.store(\"documentMutations\"), r = [], o = IDBKeyRange.only(n.batchId);\n let u = 0;\n const a = s.Wt({\n range: o\n }, ((t, e, n) => (u++, n.delete())));\n r.push(a.next((() => {\n U(1 === u);\n })));\n const c = [];\n for (const t of n.mutations) {\n const s = Ys(e, t.key.path, n.batchId);\n r.push(i.delete(s)), c.push(t.key);\n }\n return pi.waitFor(r).next((() => c));\n}\n\n/**\n * Returns an approximate size for the given document.\n */ function Ir(t) {\n if (!t) return 0;\n let e;\n if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {\n if (!t.noDocument) throw L();\n e = t.noDocument;\n }\n return JSON.stringify(e).length;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A mutation queue for a specific user, backed by IndexedDB. */ yr.DEFAULT_COLLECTION_PERCENTILE = 10, \nyr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, yr.DEFAULT = new yr(41943040, yr.DEFAULT_COLLECTION_PERCENTILE, yr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), \nyr.DISABLED = new yr(-1, 0, 0);\n\nclass Tr {\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n t, e, n, s) {\n this.userId = t, this.M = e, this.indexManager = n, this.referenceDelegate = s, \n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n this.ln = {};\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */ static Yt(t, e, n, s) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n U(\"\" !== t.uid);\n const i = t.isAuthenticated() ? t.uid : \"\";\n return new Tr(i, e, n, s);\n }\n checkEmpty(t) {\n let e = !0;\n const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return Ar(t).Wt({\n index: \"userMutationsIndex\",\n range: n\n }, ((t, n, s) => {\n e = !1, s.done();\n })).next((() => e));\n }\n addMutationBatch(t, e, n, s) {\n const i = Rr(t), r = Ar(t);\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return r.add({}).next((o => {\n U(\"number\" == typeof o);\n const u = new Ci(o, e, n, s), a = function(t, e, n) {\n const s = n.baseMutations.map((e => Ss(t.Jt, e))), i = n.mutations.map((e => Ss(t.Jt, e)));\n return {\n userId: e,\n batchId: n.batchId,\n localWriteTimeMs: n.localWriteTime.toMillis(),\n baseMutations: s,\n mutations: i\n };\n }(this.M, this.userId, u), c = [];\n let h = new qn(((t, e) => rt(t.canonicalString(), e.canonicalString())));\n for (const t of s) {\n const e = Ys(this.userId, t.key.path, o);\n h = h.add(t.key.path.popLast()), c.push(r.put(a)), c.push(i.put(e, Xs));\n }\n return h.forEach((e => {\n c.push(this.indexManager.addToCollectionParentIndex(t, e));\n })), t.addOnCommittedListener((() => {\n this.ln[o] = u.keys();\n })), pi.waitFor(c).next((() => u));\n }));\n }\n lookupMutationBatch(t, e) {\n return Ar(t).get(e).next((t => t ? (U(t.userId === this.userId), Ui(this.M, t)) : null));\n }\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n fn(t, e) {\n return this.ln[e] ? pi.resolve(this.ln[e]) : this.lookupMutationBatch(t, e).next((t => {\n if (t) {\n const n = t.keys();\n return this.ln[e] = n, n;\n }\n return null;\n }));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);\n let i = null;\n return Ar(t).Wt({\n index: \"userMutationsIndex\",\n range: s\n }, ((t, e, s) => {\n e.userId === this.userId && (U(e.batchId >= n), i = Ui(this.M, e)), s.done();\n })).next((() => i));\n }\n getHighestUnacknowledgedBatchId(t) {\n const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);\n let n = -1;\n return Ar(t).Wt({\n index: \"userMutationsIndex\",\n range: e,\n reverse: !0\n }, ((t, e, s) => {\n n = e.batchId, s.done();\n })).next((() => n));\n }\n getAllMutationBatches(t) {\n const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return Ar(t).qt(\"userMutationsIndex\", e).next((t => t.map((t => Ui(this.M, t)))));\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const n = Js(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];\n return Rr(t).Wt({\n range: s\n }, ((n, s, r) => {\n const [o, u, a] = n, c = zs(u);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n if (o === this.userId && e.path.isEqual(c)) \n // Look up the mutation batch in the store.\n return Ar(t).get(a).next((t => {\n if (!t) throw L();\n U(t.userId === this.userId), i.push(Ui(this.M, t));\n }));\n r.done();\n })).next((() => i));\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new qn(rt);\n const s = [];\n return e.forEach((e => {\n const i = Js(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = Rr(t).Wt({\n range: r\n }, ((t, s, i) => {\n const [r, o, u] = t, a = zs(o);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n r === this.userId && e.path.isEqual(a) ? n = n.add(u) : i.done();\n }));\n s.push(o);\n })), pi.waitFor(s).next((() => this.dn(t, n)));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n const n = e.path, s = n.length + 1, i = Js(this.userId, n), r = IDBKeyRange.lowerBound(i);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let o = new qn(rt);\n return Rr(t).Wt({\n range: r\n }, ((t, e, i) => {\n const [r, u, a] = t, c = zs(u);\n r === this.userId && n.isPrefixOf(c) ? \n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n c.length === s && (o = o.add(a)) : i.done();\n })).next((() => this.dn(t, o)));\n }\n dn(t, e) {\n const n = [], s = [];\n // TODO(rockwood): Implement this using iterate.\n return e.forEach((e => {\n s.push(Ar(t).get(e).next((t => {\n if (null === t) throw L();\n U(t.userId === this.userId), n.push(Ui(this.M, t));\n })));\n })), pi.waitFor(s).next((() => n));\n }\n removeMutationBatch(t, e) {\n return pr(t.Ht, this.userId, e).next((n => (t.addOnCommittedListener((() => {\n this._n(e.batchId);\n })), pi.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));\n }\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n _n(t) {\n delete this.ln[t];\n }\n performConsistencyCheck(t) {\n return this.checkEmpty(t).next((e => {\n if (!e) return pi.resolve();\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const n = IDBKeyRange.lowerBound([ this.userId ]);\n const s = [];\n return Rr(t).Wt({\n range: n\n }, ((t, e, n) => {\n if (t[0] === this.userId) {\n const e = zs(t[1]);\n s.push(e);\n } else n.done();\n })).next((() => {\n U(0 === s.length);\n }));\n }));\n }\n containsKey(t, e) {\n return Er(t, this.userId, e);\n }\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n wn(t) {\n return Pr(t).get(this.userId).next((t => t || {\n userId: this.userId,\n lastAcknowledgedBatchId: -1,\n lastStreamToken: \"\"\n }));\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */ function Er(t, e, n) {\n const s = Js(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);\n let o = !1;\n return Rr(t).Wt({\n range: r,\n jt: !0\n }, ((t, n, s) => {\n const [r, u, /*batchID*/ a] = t;\n r === e && u === i && (o = !0), s.done();\n })).next((() => o));\n}\n\n/** Returns true if any mutation queue contains the given document. */\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction Ar(t) {\n return Di(t, \"mutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function Rr(t) {\n return Di(t, \"documentMutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function Pr(t) {\n return Di(t, \"mutationQueues\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Offset to ensure non-overlapping target ids. */\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nclass br {\n constructor(t) {\n this.mn = t;\n }\n next() {\n return this.mn += 2, this.mn;\n }\n static gn() {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new br(0);\n }\n static yn() {\n // Sync engine assigns target IDs for limbo document detection.\n return new br(-1);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Vr {\n constructor(t, e) {\n this.referenceDelegate = t, this.M = e;\n }\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n allocateTargetId(t) {\n return this.pn(t).next((e => {\n const n = new br(e.highestTargetId);\n return e.highestTargetId = n.next(), this.In(t, e).next((() => e.highestTargetId));\n }));\n }\n getLastRemoteSnapshotVersion(t) {\n return this.pn(t).next((t => ct.fromTimestamp(new at(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));\n }\n getHighestSequenceNumber(t) {\n return this.pn(t).next((t => t.highestListenSequenceNumber));\n }\n setTargetsMetadata(t, e, n) {\n return this.pn(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()), \n e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.In(t, s))));\n }\n addTargetData(t, e) {\n return this.Tn(t, e).next((() => this.pn(t).next((n => (n.targetCount += 1, this.En(e, n), \n this.In(t, n))))));\n }\n updateTargetData(t, e) {\n return this.Tn(t, e);\n }\n removeTargetData(t, e) {\n return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => vr(t).delete(e.targetId))).next((() => this.pn(t))).next((e => (U(e.targetCount > 0), \n e.targetCount -= 1, this.In(t, e))));\n }\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */ removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return vr(t).Wt(((r, o) => {\n const u = qi(o);\n u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));\n })).next((() => pi.waitFor(i))).next((() => s));\n }\n /**\n * Call provided function with each `TargetData` that we have cached.\n */ forEachTarget(t, e) {\n return vr(t).Wt(((t, n) => {\n const s = qi(n);\n e(s);\n }));\n }\n pn(t) {\n return Sr(t).get(\"targetGlobalKey\").next((t => (U(null !== t), t)));\n }\n In(t, e) {\n return Sr(t).put(\"targetGlobalKey\", e);\n }\n Tn(t, e) {\n return vr(t).put(Ki(this.M, e));\n }\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */ En(t, e) {\n let n = !1;\n return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0), \n t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber, \n n = !0), n;\n }\n getTargetCount(t) {\n return this.pn(t).next((t => t.targetCount));\n }\n getTargetData(t, e) {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const n = _e(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);\n let i = null;\n return vr(t).Wt({\n range: s,\n index: \"queryTargetsIndex\"\n }, ((t, n, s) => {\n const r = qi(n);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n me(e, r.target) && (i = r, s.done());\n })).next((() => i));\n }\n addMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = [], i = Dr(t);\n return e.forEach((e => {\n const r = Qs(e.path);\n s.push(i.put({\n targetId: n,\n path: r\n })), s.push(this.referenceDelegate.addReference(t, n, e));\n })), pi.waitFor(s);\n }\n removeMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = Dr(t);\n return pi.forEach(e, (e => {\n const i = Qs(e.path);\n return pi.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);\n }));\n }\n removeMatchingKeysForTargetId(t, e) {\n const n = Dr(t), s = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return n.delete(s);\n }\n getMatchingKeysForTargetId(t, e) {\n const n = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0), s = Dr(t);\n let i = Xn();\n return s.Wt({\n range: n,\n jt: !0\n }, ((t, e, n) => {\n const s = zs(t[1]), r = new xt(s);\n i = i.add(r);\n })).next((() => i));\n }\n containsKey(t, e) {\n const n = Qs(e.path), s = IDBKeyRange.bound([ n ], [ ut(n) ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n let i = 0;\n return Dr(t).Wt({\n index: \"documentTargetsIndex\",\n jt: !0,\n range: s\n }, (([t, e], n, s) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n 0 !== t && (i++, s.done());\n })).next((() => i > 0));\n }\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n Et(t, e) {\n return vr(t).get(e).next((t => t ? qi(t) : null));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */ function vr(t) {\n return Di(t, \"targets\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */ function Sr(t) {\n return Di(t, \"targetGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */ function Dr(t) {\n return Di(t, \"targetDocuments\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */ async function Cr(t) {\n if (t.code !== G.FAILED_PRECONDITION || t.message !== gi) throw t;\n O(\"LocalStore\", \"Unexpectedly lost primary lease\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function xr([t, e], [n, s]) {\n const i = rt(t, n);\n return 0 === i ? rt(e, s) : i;\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */ class Nr {\n constructor(t) {\n this.An = t, this.buffer = new qn(xr), this.Rn = 0;\n }\n Pn() {\n return ++this.Rn;\n }\n bn(t) {\n const e = [ t, this.Pn() ];\n if (this.buffer.size < this.An) this.buffer = this.buffer.add(e); else {\n const t = this.buffer.last();\n xr(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));\n }\n }\n get maxValue() {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()[0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */ class kr {\n constructor(t, e) {\n this.garbageCollector = t, this.asyncQueue = e, this.Vn = !1, this.vn = null;\n }\n start(t) {\n -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Sn(t);\n }\n stop() {\n this.vn && (this.vn.cancel(), this.vn = null);\n }\n get started() {\n return null !== this.vn;\n }\n Sn(t) {\n const e = this.Vn ? 3e5 : 6e4;\n O(\"LruGarbageCollector\", `Garbage collection scheduled in ${e}ms`), this.vn = this.asyncQueue.enqueueAfterDelay(\"lru_garbage_collection\" /* LruGarbageCollection */ , e, (async () => {\n this.vn = null, this.Vn = !0;\n try {\n await t.collectGarbage(this.garbageCollector);\n } catch (t) {\n Ri(t) ? O(\"LruGarbageCollector\", \"Ignoring IndexedDB error during garbage collection: \", t) : await Cr(t);\n }\n await this.Sn(t);\n }));\n }\n}\n\n/** Implements the steps for LRU garbage collection. */ class Mr {\n constructor(t, e) {\n this.Dn = t, this.params = e;\n }\n calculateTargetCount(t, e) {\n return this.Dn.Cn(t).next((t => Math.floor(e / 100 * t)));\n }\n nthSequenceNumber(t, e) {\n if (0 === e) return pi.resolve(nt.A);\n const n = new Nr(e);\n return this.Dn.forEachTarget(t, (t => n.bn(t.sequenceNumber))).next((() => this.Dn.xn(t, (t => n.bn(t))))).next((() => n.maxValue));\n }\n removeTargets(t, e, n) {\n return this.Dn.removeTargets(t, e, n);\n }\n removeOrphanedDocuments(t, e) {\n return this.Dn.removeOrphanedDocuments(t, e);\n }\n collect(t, e) {\n return -1 === this.params.cacheSizeCollectionThreshold ? (O(\"LruGarbageCollector\", \"Garbage collection skipped; disabled\"), \n pi.resolve(gr)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (O(\"LruGarbageCollector\", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), \n gr) : this.Nn(t, e)));\n }\n getCacheSize(t) {\n return this.Dn.getCacheSize(t);\n }\n Nn(t, e) {\n let n, s, i, r, o, a, c;\n const h = Date.now();\n return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (\n // Cap at the configured max\n e > this.params.maximumSequenceNumbersToCollect ? (O(\"LruGarbageCollector\", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`), \n s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s, \n o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, a = Date.now(), \n this.removeOrphanedDocuments(t, n)))).next((t => {\n if (c = Date.now(), k() <= LogLevel.DEBUG) {\n O(\"LruGarbageCollector\", `LRU Garbage Collection\\n\\tCounted targets in ${r - h}ms\\n\\tDetermined least recently used ${s} in ` + (o - r) + \"ms\\n\" + `\\tRemoved ${i} targets in ` + (a - o) + \"ms\\n\" + `\\tRemoved ${t} documents in ` + (c - a) + \"ms\\n\" + `Total Duration: ${c - h}ms`);\n }\n return pi.resolve({\n didRun: !0,\n sequenceNumbersCollected: s,\n targetsRemoved: i,\n documentsRemoved: t\n });\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Provides LRU functionality for IndexedDB persistence. */\nclass Or {\n constructor(t, e) {\n this.db = t, this.garbageCollector = function(t, e) {\n return new Mr(t, e);\n }(this, e);\n }\n Cn(t) {\n const e = this.kn(t);\n return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));\n }\n kn(t) {\n let e = 0;\n return this.xn(t, (t => {\n e++;\n })).next((() => e));\n }\n forEachTarget(t, e) {\n return this.db.getTargetCache().forEachTarget(t, e);\n }\n xn(t, e) {\n return this.Mn(t, ((t, n) => e(n)));\n }\n addReference(t, e, n) {\n return Fr(t, n);\n }\n removeReference(t, e, n) {\n return Fr(t, n);\n }\n removeTargets(t, e, n) {\n return this.db.getTargetCache().removeTargets(t, e, n);\n }\n markPotentiallyOrphaned(t, e) {\n return Fr(t, e);\n }\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */ On(t, e) {\n return function(t, e) {\n let n = !1;\n return Pr(t).zt((s => Er(t, s, e).next((t => (t && (n = !0), pi.resolve(!t)))))).next((() => n));\n }(t, e);\n }\n removeOrphanedDocuments(t, e) {\n const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];\n let i = 0;\n return this.Mn(t, ((r, o) => {\n if (o <= e) {\n const e = this.On(t, r).next((e => {\n if (!e) \n // Our size accounting requires us to read all documents before\n // removing them.\n return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, ct.min()), Dr(t).delete([ 0, Qs(r.path) ]))));\n }));\n s.push(e);\n }\n })).next((() => pi.waitFor(s))).next((() => n.apply(t))).next((() => i));\n }\n removeTarget(t, e) {\n const n = e.withSequenceNumber(t.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(t, n);\n }\n updateLimboDocument(t, e) {\n return Fr(t, e);\n }\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */ Mn(t, e) {\n const n = Dr(t);\n let s, i = nt.A;\n return n.Wt({\n index: \"documentTargetsIndex\"\n }, (([t, n], {path: r, sequenceNumber: o}) => {\n 0 === t ? (\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n i !== nt.A && e(new xt(zs(s)), i), \n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n i = o, s = r) : \n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n i = nt.A;\n })).next((() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n i !== nt.A && e(new xt(zs(s)), i);\n }));\n }\n getCacheSize(t) {\n return this.db.getRemoteDocumentCache().getSize(t);\n }\n}\n\nfunction Fr(t, e) {\n return Dr(t).put(\n /**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\n function(t, e) {\n return {\n targetId: 0,\n path: Qs(t.path),\n sequenceNumber: e\n };\n }(e, t.currentSequenceNumber));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */ class $r {\n constructor() {\n // A mapping of document key to the new cache entry that should be written.\n this.changes = new $n((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;\n }\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ addEntry(t) {\n this.assertNotApplied(), this.changes.set(t.key, t);\n }\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ removeEntry(t, e) {\n this.assertNotApplied(), this.changes.set(t, ne.newInvalidDocument(t).setReadTime(e));\n }\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */ getEntry(t, e) {\n this.assertNotApplied();\n const n = this.changes.get(e);\n return void 0 !== n ? pi.resolve(n) : this.getFromCache(t, e);\n }\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */ getEntries(t, e) {\n return this.getAllFromCache(t, e);\n }\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */ apply(t) {\n return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);\n }\n /** Helper to assert this.changes is not null */ assertNotApplied() {}\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */ class Br {\n constructor(t) {\n this.M = t;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ addEntry(t, e, n) {\n return qr(t).put(n);\n }\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ removeEntry(t, e, n) {\n return qr(t).delete(\n /**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\n function(t, e) {\n const n = t.path.toArray();\n return [ \n /* prefix path */ n.slice(0, n.length - 2), \n /* collection id */ n[n.length - 2], $i(e), \n /* document id */ n[n.length - 1] ];\n }\n /**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */ (e, n));\n }\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */ updateMetadata(t, e) {\n return this.getMetadata(t).next((n => (n.byteSize += e, this.Fn(t, n))));\n }\n getEntry(t, e) {\n let n = ne.newInvalidDocument(e);\n return qr(t).Wt({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(Kr(e))\n }, ((t, s) => {\n n = this.$n(e, s);\n })).next((() => n));\n }\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */ Bn(t, e) {\n let n = {\n size: 0,\n document: ne.newInvalidDocument(e)\n };\n return qr(t).Wt({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(Kr(e))\n }, ((t, s) => {\n n = {\n document: this.$n(e, s),\n size: Ir(s)\n };\n })).next((() => n));\n }\n getEntries(t, e) {\n let n = jn();\n return this.Ln(t, e, ((t, e) => {\n const s = this.$n(t, e);\n n = n.insert(t, s);\n })).next((() => n));\n }\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */ Un(t, e) {\n let n = jn(), s = new Bn(xt.comparator);\n return this.Ln(t, e, ((t, e) => {\n const i = this.$n(t, e);\n n = n.insert(t, i), s = s.insert(t, Ir(e));\n })).next((() => ({\n documents: n,\n qn: s\n })));\n }\n Ln(t, e, n) {\n if (e.isEmpty()) return pi.resolve();\n let s = new qn(Qr);\n e.forEach((t => s = s.add(t)));\n const i = IDBKeyRange.bound(Kr(s.first()), Kr(s.last())), r = s.getIterator();\n let o = r.getNext();\n return qr(t).Wt({\n index: \"documentKeyIndex\",\n range: i\n }, ((t, e, s) => {\n const i = xt.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);\n // Go through keys not found in cache.\n for (;o && Qr(o, i) < 0; ) n(o, null), o = r.getNext();\n o && o.isEqual(i) && (\n // Key found in cache.\n n(o, e), o = r.hasNext() ? r.getNext() : null), \n // Skip to the next key (if there is one).\n o ? s.Ut(Kr(o)) : s.done();\n })).next((() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;\n }));\n }\n getAllFromCollection(t, e, n) {\n const s = [ e.popLast().toArray(), e.lastSegment(), $i(n.readTime), n.documentKey.path.isEmpty() ? \"\" : n.documentKey.path.lastSegment() ], i = [ e.popLast().toArray(), e.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], \"\" ];\n return qr(t).qt(IDBKeyRange.bound(s, i, !0)).next((t => {\n let e = jn();\n for (const n of t) {\n const t = this.$n(xt.fromSegments(n.prefixPath.concat(n.collectionGroup, n.documentId)), n);\n e = e.insert(t.key, t);\n }\n return e;\n }));\n }\n getAllFromCollectionGroup(t, e, n, s) {\n let i = jn();\n const r = Gr(e, n), o = Gr(e, he.max());\n return qr(t).Wt({\n index: \"collectionGroupIndex\",\n range: IDBKeyRange.bound(r, o, !0)\n }, ((t, e, n) => {\n const r = this.$n(xt.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);\n i = i.insert(r.key, r), i.size === s && n.done();\n })).next((() => i));\n }\n newChangeBuffer(t) {\n return new Lr(this, !!t && t.trackRemovals);\n }\n getSize(t) {\n return this.getMetadata(t).next((t => t.byteSize));\n }\n getMetadata(t) {\n return Ur(t).get(\"remoteDocumentGlobalKey\").next((t => (U(!!t), t)));\n }\n Fn(t, e) {\n return Ur(t).put(\"remoteDocumentGlobalKey\", e);\n }\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */ $n(t, e) {\n if (e) {\n const t = Oi(this.M, e);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n if (!(t.isNoDocument() && t.version.isEqual(ct.min()))) return t;\n }\n return ne.newInvalidDocument(t);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass Lr extends $r {\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(t, e) {\n super(), this.Kn = t, this.trackRemovals = e, \n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n this.Gn = new $n((t => t.toString()), ((t, e) => t.isEqual(e)));\n }\n applyChanges(t) {\n const e = [];\n let n = 0, s = new qn(((t, e) => rt(t.canonicalString(), e.canonicalString())));\n return this.changes.forEach(((i, r) => {\n const o = this.Gn.get(i);\n if (e.push(this.Kn.removeEntry(t, i, o.readTime)), r.isValidDocument()) {\n const u = Fi(this.Kn.M, r);\n s = s.add(i.path.popLast());\n const a = Ir(u);\n n += a - o.size, e.push(this.Kn.addEntry(t, i, u));\n } else if (n -= o.size, this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const n = Fi(this.Kn.M, r.convertToNoDocument(ct.min()));\n e.push(this.Kn.addEntry(t, i, n));\n }\n })), s.forEach((n => {\n e.push(this.Kn.indexManager.addToCollectionParentIndex(t, n));\n })), e.push(this.Kn.updateMetadata(t, n)), pi.waitFor(e);\n }\n getFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.Kn.Bn(t, e).next((t => (this.Gn.set(e, {\n size: t.size,\n readTime: t.document.readTime\n }), t.document)));\n }\n getAllFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.Kn.Un(t, e).next((({documents: t, qn: e}) => (\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n e.forEach(((e, n) => {\n this.Gn.set(e, {\n size: n,\n readTime: t.get(e).readTime\n });\n })), t)));\n }\n}\n\nfunction Ur(t) {\n return Di(t, \"remoteDocumentGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */ function qr(t) {\n return Di(t, \"remoteDocumentsV14\");\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */ function Kr(t) {\n const e = t.path.toArray();\n return [ \n /* prefix path */ e.slice(0, e.length - 2), \n /* collection id */ e[e.length - 2], \n /* document id */ e[e.length - 1] ];\n}\n\nfunction Gr(t, e) {\n const n = e.documentKey.path.toArray();\n return [ \n /* collection id */ t, $i(e.readTime), \n /* prefix path */ n.slice(0, n.length - 2), \n /* document id */ n.length > 0 ? n[n.length - 1] : \"\" ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */ function Qr(t, e) {\n const n = t.path.toArray(), s = e.path.toArray();\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let i = 0;\n for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = rt(n[t], s[t]), \n i) return i;\n return i = rt(n.length, s.length), i || (i = rt(n[n.length - 2], s[s.length - 2]), \n i || rt(n[n.length - 1], s[s.length - 1]));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO(indexing): Remove this constant\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Performs database creation and schema upgrades. */\nclass jr {\n constructor(t) {\n this.M = t;\n }\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */ kt(t, e, n, s) {\n const i = new Ii(\"createOrUpgrade\", e);\n n < 1 && s >= 1 && (function(t) {\n t.createObjectStore(\"owner\");\n }(t), function(t) {\n t.createObjectStore(\"mutationQueues\", {\n keyPath: \"userId\"\n });\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Hs, {\n unique: !0\n }), t.createObjectStore(\"documentMutations\");\n }\n /**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */ (t), Wr(t), function(t) {\n t.createObjectStore(\"remoteDocuments\");\n }(t));\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n let r = pi.resolve();\n return n < 3 && s >= 3 && (\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n 0 !== n && (!function(t) {\n t.deleteObjectStore(\"targetDocuments\"), t.deleteObjectStore(\"targets\"), t.deleteObjectStore(\"targetGlobal\");\n }(t), Wr(t)), r = r.next((() => \n /**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\n function(t) {\n const e = t.store(\"targetGlobal\"), n = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: ct.min().toTimestamp(),\n targetCount: 0\n };\n return e.put(\"targetGlobalKey\", n);\n }(i)))), n < 4 && s >= 4 && (0 !== n && (\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n r = r.next((() => function(t, e) {\n return e.store(\"mutations\").qt().next((n => {\n t.deleteObjectStore(\"mutations\");\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Hs, {\n unique: !0\n });\n const s = e.store(\"mutations\"), i = n.map((t => s.put(t)));\n return pi.waitFor(i);\n }));\n }(t, i)))), r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"clientMetadata\", {\n keyPath: \"clientId\"\n });\n }(t);\n }))), n < 5 && s >= 5 && (r = r.next((() => this.Qn(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {\n t.createObjectStore(\"remoteDocumentGlobal\");\n }(t), this.jn(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Wn(i)))), n < 8 && s >= 8 && (r = r.next((() => this.zn(t, i)))), \n n < 9 && s >= 9 && (r = r.next((() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n !function(t) {\n t.objectStoreNames.contains(\"remoteDocumentChanges\") && t.deleteObjectStore(\"remoteDocumentChanges\");\n }(t);\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n }))), n < 10 && s >= 10 && (r = r.next((() => this.Hn(i)))), n < 11 && s >= 11 && (r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"bundles\", {\n keyPath: \"bundleId\"\n });\n }(t), function(t) {\n t.createObjectStore(\"namedQueries\", {\n keyPath: \"name\"\n });\n }(t);\n }))), n < 12 && s >= 12 && (r = r.next((() => {\n !function(t) {\n const e = t.createObjectStore(\"documentOverlays\", {\n keyPath: hi\n });\n e.createIndex(\"collectionPathOverlayIndex\", li, {\n unique: !1\n }), e.createIndex(\"collectionGroupOverlayIndex\", fi, {\n unique: !1\n });\n }(t);\n }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {\n const e = t.createObjectStore(\"remoteDocumentsV14\", {\n keyPath: Zs\n });\n e.createIndex(\"documentKeyIndex\", ti), e.createIndex(\"collectionGroupIndex\", ei);\n }(t))).next((() => this.Jn(t, i))).next((() => t.deleteObjectStore(\"remoteDocuments\")))), \n n < 14 && s >= 14 && (r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"indexConfiguration\", {\n keyPath: \"indexId\",\n autoIncrement: !0\n }).createIndex(\"collectionGroupIndex\", \"collectionGroup\", {\n unique: !1\n });\n t.createObjectStore(\"indexState\", {\n keyPath: oi\n }).createIndex(\"sequenceNumberIndex\", ui, {\n unique: !1\n });\n t.createObjectStore(\"indexEntries\", {\n keyPath: ai\n }).createIndex(\"documentKeyIndex\", ci, {\n unique: !1\n });\n }(t);\n }))), r;\n }\n jn(t) {\n let e = 0;\n return t.store(\"remoteDocuments\").Wt(((t, n) => {\n e += Ir(n);\n })).next((() => {\n const n = {\n byteSize: e\n };\n return t.store(\"remoteDocumentGlobal\").put(\"remoteDocumentGlobalKey\", n);\n }));\n }\n Qn(t) {\n const e = t.store(\"mutationQueues\"), n = t.store(\"mutations\");\n return e.qt().next((e => pi.forEach(e, (e => {\n const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);\n return n.qt(\"userMutationsIndex\", s).next((n => pi.forEach(n, (n => {\n U(n.userId === e.userId);\n const s = Ui(this.M, n);\n return pr(t, e.userId, s).next((() => {}));\n }))));\n }))));\n }\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */ Wn(t) {\n const e = t.store(\"targetDocuments\"), n = t.store(\"remoteDocuments\");\n return t.store(\"targetGlobal\").get(\"targetGlobalKey\").next((t => {\n const s = [];\n return n.Wt(((n, i) => {\n const r = new _t(n), o = function(t) {\n return [ 0, Qs(t) ];\n }(r);\n s.push(e.get(o).next((n => n ? pi.resolve() : (n => e.put({\n targetId: 0,\n path: Qs(n),\n sequenceNumber: t.highestListenSequenceNumber\n }))(r))));\n })).next((() => pi.waitFor(s)));\n }));\n }\n zn(t, e) {\n // Create the index.\n t.createObjectStore(\"collectionParents\", {\n keyPath: ri\n });\n const n = e.store(\"collectionParents\"), s = new hr, i = t => {\n if (s.add(t)) {\n const e = t.lastSegment(), s = t.popLast();\n return n.put({\n collectionId: e,\n parent: Qs(s)\n });\n }\n };\n // Helper to add an index entry iff we haven't already written it.\n // Index existing remote documents.\n return e.store(\"remoteDocuments\").Wt({\n jt: !0\n }, ((t, e) => {\n const n = new _t(t);\n return i(n.popLast());\n })).next((() => e.store(\"documentMutations\").Wt({\n jt: !0\n }, (([t, e, n], s) => {\n const r = zs(e);\n return i(r.popLast());\n }))));\n }\n Hn(t) {\n const e = t.store(\"targets\");\n return e.Wt(((t, n) => {\n const s = qi(n), i = Ki(this.M, s);\n return e.put(i);\n }));\n }\n Jn(t, e) {\n const n = e.store(\"remoteDocuments\"), s = [];\n return n.Wt(((t, n) => {\n const i = e.store(\"remoteDocumentsV14\"), r = (o = n, o.document ? new xt(_t.fromString(o.document.name).popFirst(5)) : o.noDocument ? xt.fromSegments(o.noDocument.path) : o.unknownDocument ? xt.fromSegments(o.unknownDocument.path) : L()).path.toArray();\n var o;\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const u = {\n prefixPath: r.slice(0, r.length - 2),\n collectionGroup: r[r.length - 2],\n documentId: r[r.length - 1],\n readTime: n.readTime || [ 0, 0 ],\n unknownDocument: n.unknownDocument,\n noDocument: n.noDocument,\n document: n.document,\n hasCommittedMutations: !!n.hasCommittedMutations\n };\n s.push(i.put(u));\n })).next((() => pi.waitFor(s)));\n }\n}\n\nfunction Wr(t) {\n t.createObjectStore(\"targetDocuments\", {\n keyPath: si\n }).createIndex(\"documentTargetsIndex\", ii, {\n unique: !0\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n t.createObjectStore(\"targets\", {\n keyPath: \"targetId\"\n }).createIndex(\"queryTargetsIndex\", ni, {\n unique: !0\n }), t.createObjectStore(\"targetGlobal\");\n}\n\nconst zr = \"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.\";\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nclass Hr {\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n t, e, n, s, i, r, o, u, a, \n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n c, h = 13) {\n if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n, \n this.Yn = i, this.window = r, this.document = o, this.Xn = a, this.Zn = c, this.ts = h, \n this.es = null, this.ns = !1, this.isPrimary = !1, this.networkEnabled = !0, \n /** Our window.unload handler, if registered. */\n this.ss = null, this.inForeground = !1, \n /** Our 'visibilitychange' listener if registered. */\n this.rs = null, \n /** The client metadata refresh task. */\n this.os = null, \n /** The last time we garbage collected the client metadata object store. */\n this.us = Number.NEGATIVE_INFINITY, \n /** A listener to notify on primary state changes. */\n this.cs = t => Promise.resolve(), !Hr.vt()) throw new Q(G.UNIMPLEMENTED, \"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");\n this.referenceDelegate = new Or(this, s), this.hs = e + \"main\", this.M = new Mi(u), \n this.ls = new Ti(this.hs, this.ts, new jr(this.M)), this.fs = new Vr(this.referenceDelegate, this.M), \n this.ds = function(t) {\n return new Br(t);\n }(this.M), this._s = new Wi, this.window && this.window.localStorage ? this.ws = this.window.localStorage : (this.ws = null, \n !1 === c && F(\"IndexedDbPersistence\", \"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));\n }\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */ start() {\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.gs().then((() => {\n if (!this.isPrimary && !this.allowTabSynchronization) \n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new Q(G.FAILED_PRECONDITION, zr);\n return this.ys(), this.ps(), this.Is(), this.runTransaction(\"getHighestListenSequenceNumber\", \"readonly\", (t => this.fs.getHighestSequenceNumber(t)));\n })).then((t => {\n this.es = new nt(t, this.Xn);\n })).then((() => {\n this.ns = !0;\n })).catch((t => (this.ls && this.ls.close(), Promise.reject(t))));\n }\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ Ts(t) {\n return this.cs = async e => {\n if (this.started) return t(e);\n }, t(this.isPrimary);\n }\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setDatabaseDeletedListener(t) {\n this.ls.Ot((async e => {\n // Check if an attempt is made to delete IndexedDB.\n null === e.newVersion && await t();\n }));\n }\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setNetworkEnabled(t) {\n this.networkEnabled !== t && (this.networkEnabled = t, \n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.Yn.enqueueAndForget((async () => {\n this.started && await this.gs();\n })));\n }\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */ gs() {\n return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", (t => Yr(t).put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n }).next((() => {\n if (this.isPrimary) return this.Es(t).next((t => {\n t || (this.isPrimary = !1, this.Yn.enqueueRetryable((() => this.cs(!1))));\n }));\n })).next((() => this.As(t))).next((e => this.isPrimary && !e ? this.Rs(t).next((() => !1)) : !!e && this.Ps(t).next((() => !0)))))).catch((t => {\n if (Ri(t)) \n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return O(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", t), this.isPrimary;\n if (!this.allowTabSynchronization) throw t;\n return O(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", t), \n /* isPrimary= */ !1;\n })).then((t => {\n this.isPrimary !== t && this.Yn.enqueueRetryable((() => this.cs(t))), this.isPrimary = t;\n }));\n }\n Es(t) {\n return Jr(t).get(\"owner\").next((t => pi.resolve(this.bs(t))));\n }\n Vs(t) {\n return Yr(t).delete(this.clientId);\n }\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */ async vs() {\n if (this.isPrimary && !this.Ss(this.us, 18e5)) {\n this.us = Date.now();\n const t = await this.runTransaction(\"maybeGarbageCollectMultiClientState\", \"readwrite-primary\", (t => {\n const e = Di(t, \"clientMetadata\");\n return e.qt().next((t => {\n const n = this.Ds(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));\n // Delete metadata for clients that are no longer considered active.\n return pi.forEach(s, (t => e.delete(t.clientId))).next((() => s));\n }));\n })).catch((() => []));\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.ws) for (const e of t) this.ws.removeItem(this.Cs(e.clientId));\n }\n }\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */ Is() {\n this.os = this.Yn.enqueueAfterDelay(\"client_metadata_refresh\" /* ClientMetadataRefresh */ , 4e3, (() => this.gs().then((() => this.vs())).then((() => this.Is()))));\n }\n /** Checks whether `client` is the local client. */ bs(t) {\n return !!t && t.ownerId === this.clientId;\n }\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */ As(t) {\n if (this.Zn) return pi.resolve(!0);\n return Jr(t).get(\"owner\").next((e => {\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (null !== e && this.Ss(e.leaseTimestampMs, 5e3) && !this.xs(e.ownerId)) {\n if (this.bs(e) && this.networkEnabled) return !0;\n if (!this.bs(e)) {\n if (!e.allowTabSynchronization) \n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new Q(G.FAILED_PRECONDITION, zr);\n return !1;\n }\n }\n return !(!this.networkEnabled || !this.inForeground) || Yr(t).qt().next((t => void 0 === this.Ds(t, 5e3).find((t => {\n if (this.clientId !== t.clientId) {\n const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;\n if (e || n && s) return !0;\n }\n return !1;\n }))));\n })).next((t => (this.isPrimary !== t && O(\"IndexedDbPersistence\", `Client ${t ? \"is\" : \"is not\"} eligible for a primary lease.`), \n t)));\n }\n async shutdown() {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this.ns = !1, this.Ns(), this.os && (this.os.cancel(), this.os = null), this.ks(), \n this.Ms(), \n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.ls.runTransaction(\"shutdown\", \"readwrite\", [ \"owner\", \"clientMetadata\" ], (t => {\n const e = new Si(t, nt.A);\n return this.Rs(e).next((() => this.Vs(e)));\n })), this.ls.close(), \n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.Os();\n }\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */ Ds(t, e) {\n return t.filter((t => this.Ss(t.updateTimeMs, e) && !this.xs(t.clientId)));\n }\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ Fs() {\n return this.runTransaction(\"getActiveClients\", \"readonly\", (t => Yr(t).qt().next((t => this.Ds(t, 18e5).map((t => t.clientId))))));\n }\n get started() {\n return this.ns;\n }\n getMutationQueue(t, e) {\n return Tr.Yt(t, this.M, e, this.referenceDelegate);\n }\n getTargetCache() {\n return this.fs;\n }\n getRemoteDocumentCache() {\n return this.ds;\n }\n getIndexManager(t) {\n return new fr(t, this.M.Jt.databaseId);\n }\n getDocumentOverlayCache(t) {\n return Ji.Yt(this.M, t);\n }\n getBundleCache() {\n return this._s;\n }\n runTransaction(t, e, n) {\n O(\"IndexedDbPersistence\", \"Starting transaction:\", t);\n const s = \"readonly\" === e ? \"readonly\" : \"readwrite\", i = 14 === (r = this.ts) ? mi : 13 === r ? wi : 12 === r ? _i : 11 === r ? di : void L();\n /** Returns the object stores for the provided schema. */\n var r;\n let o;\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.ls.runTransaction(t, s, i, (s => (o = new Si(s, this.es ? this.es.next() : nt.A), \n \"readwrite-primary\" === e ? this.Es(o).next((t => !!t || this.As(o))).next((e => {\n if (!e) throw F(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1, \n this.Yn.enqueueRetryable((() => this.cs(!1))), new Q(G.FAILED_PRECONDITION, gi);\n return n(o);\n })).next((t => this.Ps(o).next((() => t)))) : this.$s(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(), \n t)));\n }\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n $s(t) {\n return Jr(t).get(\"owner\").next((t => {\n if (null !== t && this.Ss(t.leaseTimestampMs, 5e3) && !this.xs(t.ownerId) && !this.bs(t) && !(this.Zn || this.allowTabSynchronization && t.allowTabSynchronization)) throw new Q(G.FAILED_PRECONDITION, zr);\n }));\n }\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */ Ps(t) {\n const e = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return Jr(t).put(\"owner\", e);\n }\n static vt() {\n return Ti.vt();\n }\n /** Checks the primary lease and removes it if we are the current primary. */ Rs(t) {\n const e = Jr(t);\n return e.get(\"owner\").next((t => this.bs(t) ? (O(\"IndexedDbPersistence\", \"Releasing primary lease.\"), \n e.delete(\"owner\")) : pi.resolve()));\n }\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ Ss(t, e) {\n const n = Date.now();\n return !(t < n - e) && (!(t > n) || (F(`Detected an update time that is in the future: ${t} > ${n}`), \n !1));\n }\n ys() {\n null !== this.document && \"function\" == typeof this.document.addEventListener && (this.rs = () => {\n this.Yn.enqueueAndForget((() => (this.inForeground = \"visible\" === this.document.visibilityState, \n this.gs())));\n }, this.document.addEventListener(\"visibilitychange\", this.rs), this.inForeground = \"visible\" === this.document.visibilityState);\n }\n ks() {\n this.rs && (this.document.removeEventListener(\"visibilitychange\", this.rs), this.rs = null);\n }\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */ ps() {\n var t;\n \"function\" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.ss = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.Ns(), isSafari() && navigator.appVersion.match(/Version\\/1[45]/) && \n // On Safari 14 and 15, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.Yn.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Yn.enqueueAndForget((() => this.shutdown()));\n }, this.window.addEventListener(\"pagehide\", this.ss));\n }\n Ms() {\n this.ss && (this.window.removeEventListener(\"pagehide\", this.ss), this.ss = null);\n }\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */ xs(t) {\n var e;\n try {\n const n = null !== (null === (e = this.ws) || void 0 === e ? void 0 : e.getItem(this.Cs(t)));\n return O(\"IndexedDbPersistence\", `Client '${t}' ${n ? \"is\" : \"is not\"} zombied in LocalStorage`), \n n;\n } catch (t) {\n // Gracefully handle if LocalStorage isn't working.\n return F(\"IndexedDbPersistence\", \"Failed to get zombied client id.\", t), !1;\n }\n }\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */ Ns() {\n if (this.ws) try {\n this.ws.setItem(this.Cs(this.clientId), String(Date.now()));\n } catch (t) {\n // Gracefully handle if LocalStorage isn't available / working.\n F(\"Failed to set zombie client id.\", t);\n }\n }\n /** Removes the zombied client entry if it exists. */ Os() {\n if (this.ws) try {\n this.ws.removeItem(this.Cs(this.clientId));\n } catch (t) {\n // Ignore\n }\n }\n Cs(t) {\n return `firestore_zombie_${this.persistenceKey}_${t}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */ function Jr(t) {\n return Di(t, \"owner\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */ function Yr(t) {\n return Di(t, \"clientMetadata\");\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */ function Xr(t, e) {\n // Use two different prefix formats:\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let n = t.projectId;\n return t.isDefaultDatabase || (n += \".\" + t.database), \"firestore/\" + e + \"/\" + n + \"/\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nclass Zr {\n constructor(t, e, n) {\n this.ds = t, this.Bs = e, this.indexManager = n;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */ Ls(t, e) {\n return this.Bs.getAllMutationBatchesAffectingDocumentKey(t, e).next((n => this.Us(t, e, n)));\n }\n /** Internal version of `getDocument` that allows reusing batches. */ Us(t, e, n) {\n return this.ds.getEntry(t, e).next((t => {\n for (const e of n) e.applyToLocalView(t);\n return t;\n }));\n }\n // Returns the view of the given `docs` as they would appear after applying\n // all mutations in the given `batches`.\n qs(t, e) {\n t.forEach(((t, n) => {\n for (const t of e) t.applyToLocalView(n);\n }));\n }\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */ Ks(t, e) {\n return this.ds.getEntries(t, e).next((e => this.Gs(t, e).next((() => e))));\n }\n /**\n * Applies the local view the given `baseDocs` without retrieving documents\n * from the local store.\n */ Gs(t, e) {\n return this.Bs.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => this.qs(e, t)));\n }\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n */ Qs(t, e, n) {\n /**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\n return function(t) {\n return xt.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n }(e) ? this.js(t, e.path) : qe(e) ? this.Ws(t, e, n) : this.zs(t, e, n);\n }\n js(t, e) {\n // Just do a simple document lookup.\n return this.Ls(t, new xt(e)).next((t => {\n let e = zn();\n return t.isFoundDocument() && (e = e.insert(t.key, t)), e;\n }));\n }\n Ws(t, e, n) {\n const s = e.collectionGroup;\n let i = zn();\n return this.indexManager.getCollectionParents(t, s).next((r => pi.forEach(r, (r => {\n const o = function(t, e) {\n return new Me(e, \n /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }\n /**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */ (e, r.child(s));\n return this.zs(t, o, n).next((t => {\n t.forEach(((t, e) => {\n i = i.insert(t, e);\n }));\n }));\n })).next((() => i))));\n }\n zs(t, e, n) {\n // Query the remote documents and overlay mutations.\n let s;\n return this.ds.getAllFromCollection(t, e.path, n).next((n => (s = n, this.Bs.getAllMutationBatchesAffectingQuery(t, e)))).next((t => {\n for (const e of t) for (const t of e.mutations) {\n const n = t.key;\n let i = s.get(n);\n null == i && (\n // Create invalid document to apply mutations on top of\n i = ne.newInvalidDocument(n), s = s.insert(n, i)), En(t, i, e.localWriteTime), i.isFoundDocument() || (s = s.remove(n));\n }\n })).next((() => (\n // Finally, filter out any documents that don't actually match\n // the query.\n s.forEach(((t, n) => {\n He(e, n) || (s = s.remove(t));\n })), s)));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */ class to {\n constructor(t, e, n, s) {\n this.targetId = t, this.fromCache = e, this.Hs = n, this.Js = s;\n }\n static Ys(t, e) {\n let n = Xn(), s = Xn();\n for (const t of e.docChanges) switch (t.type) {\n case 0 /* Added */ :\n n = n.add(t.doc.key);\n break;\n\n case 1 /* Removed */ :\n s = s.add(t.doc.key);\n // do nothing\n }\n return new to(t, e.fromCache, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A query engine that takes advantage of the target document mapping in the\n * QueryCache. Query execution is optimized by only reading the documents that\n * previously matched a query plus any documents that were edited after the\n * query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */ class eo {\n /** Sets the document view to query against. */\n Xs(t) {\n this.Zs = t;\n }\n /** Returns all local documents matching the specified query. */ Qs(t, e, n, s) {\n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return function(t) {\n return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());\n }(e) || n.isEqual(ct.min()) ? this.ti(t, e) : this.Zs.Ks(t, s).next((i => {\n const r = this.ei(e, i);\n return ($e(e) || Be(e)) && this.ni(e.limitType, r, s, n) ? this.ti(t, e) : (k() <= LogLevel.DEBUG && O(\"QueryEngine\", \"Re-using previous result from %s to execute query: %s\", n.toString(), ze(e)), \n this.Zs.Qs(t, e, ae(n, -1)).next((t => (\n // We merge `previousResults` into `updateResults`, since\n // `updateResults` is already a DocumentMap. If a document is\n // contained in both lists, then its contents are the same.\n r.forEach((e => {\n t = t.insert(e.key, e);\n })), t))));\n }));\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n }\n /** Applies the query filter and sorting to the provided documents. */ ei(t, e) {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let n = new qn(Ye(t));\n return e.forEach(((e, s) => {\n He(t, s) && (n = n.add(s));\n })), n;\n }\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */ ni(t, e, n, s) {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n if (n.size !== e.size) return !0;\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const i = \"F\" /* First */ === t ? e.last() : e.first();\n return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);\n }\n ti(t, e) {\n return k() <= LogLevel.DEBUG && O(\"QueryEngine\", \"Using full collection scan to execute query:\", ze(e)), \n this.Zs.Qs(t, e, he.min());\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass no {\n constructor(\n /** Manages our in-memory or durable persistence. */\n t, e, n, s) {\n this.persistence = t, this.si = e, this.M = s, \n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n this.ii = new Bn(rt), \n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n this.ri = new $n((t => _e(t)), me), \n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n this.oi = new Map, this.ui = t.getRemoteDocumentCache(), this.fs = t.getTargetCache(), \n this._s = t.getBundleCache(), this.ai(n);\n }\n ai(t) {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.indexManager = this.persistence.getIndexManager(t), this.Bs = this.persistence.getMutationQueue(t, this.indexManager), \n this.ci = new Zr(this.ui, this.Bs, this.indexManager), this.ui.setIndexManager(this.indexManager), \n this.si.Xs(this.ci);\n }\n collectGarbage(t) {\n return this.persistence.runTransaction(\"Collect garbage\", \"readwrite-primary\", (e => t.collect(e, this.ii)));\n }\n}\n\nfunction so(\n/** Manages our in-memory or durable persistence. */\nt, e, n, s) {\n return new no(t, e, n, s);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nasync function io(t, e) {\n const n = K(t);\n return await n.persistence.runTransaction(\"Handle user change\", \"readonly\", (t => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let s;\n return n.Bs.getAllMutationBatches(t).next((i => (s = i, n.ai(e), n.Bs.getAllMutationBatches(t)))).next((e => {\n const i = [], r = [];\n // Union the old/new changed keys.\n let o = Xn();\n for (const t of s) {\n i.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n for (const t of e) {\n r.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return n.ci.Ks(t, o).next((t => ({\n hi: t,\n removedBatchIds: i,\n addedBatchIds: r\n })));\n }));\n }));\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nfunction ro(t, e) {\n const n = K(t);\n return n.persistence.runTransaction(\"Acknowledge batch\", \"readwrite-primary\", (t => {\n const s = e.batch.keys(), i = n.ui.newChangeBuffer({\n trackRemovals: !0\n });\n return function(t, e, n, s) {\n const i = n.batch, r = i.keys();\n let o = pi.resolve();\n return r.forEach((t => {\n o = o.next((() => s.getEntry(e, t))).next((e => {\n const r = n.docVersions.get(t);\n U(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n e.setReadTime(n.commitVersion), s.addEntry(e)));\n }));\n })), o.next((() => t.Bs.removeMutationBatch(e, i)));\n }\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-Tab only.\n (n, t, e, i).next((() => i.apply(t))).next((() => n.Bs.performConsistencyCheck(t))).next((() => n.ci.Ks(t, s)));\n }));\n}\n\n/**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nfunction oo(t) {\n const e = K(t);\n return e.persistence.runTransaction(\"Get last remote snapshot version\", \"readonly\", (t => e.fs.getLastRemoteSnapshotVersion(t)));\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */ function uo(t, e) {\n const n = K(t), s = e.snapshotVersion;\n let i = n.ii;\n return n.persistence.runTransaction(\"Apply remote event\", \"readwrite-primary\", (t => {\n const r = n.ui.newChangeBuffer({\n trackRemovals: !0\n });\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n i = n.ii;\n const o = [];\n e.targetChanges.forEach(((r, u) => {\n const a = i.get(u);\n if (!a) return;\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n o.push(n.fs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.fs.addMatchingKeys(t, r.addedDocuments, u))));\n let c = a.withSequenceNumber(t.currentSequenceNumber);\n e.targetMismatches.has(u) ? c = c.withResumeToken(pt.EMPTY_BYTE_STRING, ct.min()).withLastLimboFreeSnapshotVersion(ct.min()) : r.resumeToken.approximateByteSize() > 0 && (c = c.withResumeToken(r.resumeToken, s)), \n i = i.insert(u, c), \n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n function(t, e, n) {\n // Always persist target data if we don't already have a resume token.\n if (0 === t.resumeToken.approximateByteSize()) return !0;\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;\n }\n /**\n * Notifies local store of the changed views to locally pin documents.\n */ (a, c, r) && o.push(n.fs.updateTargetData(t, c));\n }));\n let u = jn();\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (e.documentUpdates.forEach((s => {\n e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));\n })), \n // Each loop iteration only affects its \"own\" doc, so it's safe to get all the remote\n // documents in advance in a single call.\n o.push(ao(t, r, e.documentUpdates).next((t => {\n u = t;\n }))), !s.isEqual(ct.min())) {\n const e = n.fs.getLastRemoteSnapshotVersion(t).next((e => n.fs.setTargetsMetadata(t, t.currentSequenceNumber, s)));\n o.push(e);\n }\n return pi.waitFor(o).next((() => r.apply(t))).next((() => n.ci.Gs(t, u))).next((() => u));\n })).then((t => (n.ii = i, t)));\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n * @param globalVersion - A `SnapshotVersion` representing the read time if all\n * documents have the same read time.\n * @param documentVersions - A DocumentKey-to-SnapshotVersion map if documents\n * have their own read time.\n *\n * Note: this function will use `documentVersions` if it is defined;\n * when it is not defined, resorts to `globalVersion`.\n */ function ao(t, e, n) {\n let s = Xn();\n return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {\n let s = jn();\n return n.forEach(((n, i) => {\n const r = t.get(n);\n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n i.isNoDocument() && i.version.isEqual(ct.min()) ? (\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n e.removeEntry(n, i.readTime), s = s.insert(n, i)) : !r.isValidDocument() || i.version.compareTo(r.version) > 0 || 0 === i.version.compareTo(r.version) && r.hasPendingWrites ? (e.addEntry(i), \n s = s.insert(n, i)) : O(\"LocalStore\", \"Ignoring outdated watch update for \", n, \". Current version:\", r.version, \" Watch version:\", i.version);\n })), s;\n }));\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nfunction co(t, e) {\n const n = K(t);\n return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", (t => (void 0 === e && (e = -1), \n n.Bs.getNextMutationBatchAfterBatchId(t, e))));\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nfunction ho(t, e) {\n const n = K(t);\n return n.persistence.runTransaction(\"Allocate target\", \"readwrite\", (t => {\n let s;\n return n.fs.getTargetData(t, e).next((i => i ? (\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n s = i, pi.resolve(s)) : n.fs.allocateTargetId(t).next((i => (s = new ki(e, i, 0 /* Listen */ , t.currentSequenceNumber), \n n.fs.addTargetData(t, s).next((() => s)))))));\n })).then((t => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const s = n.ii.get(t.targetId);\n return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.ii = n.ii.insert(t.targetId, t), \n n.ri.set(e, t.targetId)), t;\n }));\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nasync function lo(t, e, n) {\n const s = K(t), i = s.ii.get(e), r = n ? \"readwrite\" : \"readwrite-primary\";\n try {\n n || await s.persistence.runTransaction(\"Release target\", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));\n } catch (t) {\n if (!Ri(t)) throw t;\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n O(\"LocalStore\", `Failed to update sequence numbers for target ${e}: ${t}`);\n }\n s.ii = s.ii.remove(e), s.ri.delete(i.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */ function fo(t, e, n) {\n const s = K(t);\n let i = ct.min(), r = Xn();\n return s.persistence.runTransaction(\"Execute query\", \"readonly\", (t => function(t, e, n) {\n const s = K(t), i = s.ri.get(n);\n return void 0 !== i ? pi.resolve(s.ii.get(i)) : s.fs.getTargetData(e, n);\n }(s, t, Ge(e)).next((e => {\n if (e) return i = e.lastLimboFreeSnapshotVersion, s.fs.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n r = t;\n }));\n })).next((() => s.si.Qs(t, e, n ? i : ct.min(), n ? r : Xn()))).next((t => (mo(s, Je(e), t), \n {\n documents: t,\n li: r\n })))));\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction _o(t, e) {\n const n = K(t), s = K(n.fs), i = n.ii.get(e);\n return i ? Promise.resolve(i.target) : n.persistence.runTransaction(\"Get target data\", \"readonly\", (t => s.Et(t, e).next((t => t ? t.target : null))));\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction wo(t, e) {\n const n = K(t), s = n.oi.get(e) || ct.min();\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n return n.persistence.runTransaction(\"Get new document changes\", \"readonly\", (t => n.ui.getAllFromCollectionGroup(t, e, ae(s, -1), \n /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (mo(n, e, t), t)));\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction mo(t, e, n) {\n let s = ct.min();\n n.forEach(((t, e) => {\n e.readTime.compareTo(s) > 0 && (s = e.readTime);\n })), t.oi.set(e, s);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nasync function go(t, e, n, s) {\n const i = K(t);\n let r = Xn(), o = jn();\n for (const t of n) {\n const n = e.fi(t.metadata.name);\n t.document && (r = r.add(n));\n const s = e.di(t);\n s.setReadTime(e._i(t.metadata.readTime)), o = o.insert(n, s);\n }\n const u = i.ui.newChangeBuffer({\n trackRemovals: !0\n }), a = await ho(i, function(t) {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return Ge(Fe(_t.fromString(`__bundle__/docs/${t}`)));\n }(s));\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n return i.persistence.runTransaction(\"Apply bundle documents\", \"readwrite\", (t => ao(t, u, o).next((e => (u.apply(t), \n e))).next((e => i.fs.removeMatchingKeysForTargetId(t, a.targetId).next((() => i.fs.addMatchingKeys(t, r, a.targetId))).next((() => i.ci.Gs(t, e))).next((() => e))))));\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nasync function yo(t, e, n = Xn()) {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const s = await ho(t, Ge(Gi(e.bundledQuery))), i = K(t);\n return i.persistence.runTransaction(\"Save named query\", \"readwrite\", (t => {\n const r = ms(e.readTime);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (s.snapshotVersion.compareTo(r) >= 0) return i._s.saveNamedQuery(t, e);\n // Update existing target data because the query from the bundle is newer.\n const o = s.withResumeToken(pt.EMPTY_BYTE_STRING, r);\n return i.ii = i.ii.insert(o.targetId, o), i.fs.updateTargetData(t, o).next((() => i.fs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.fs.addMatchingKeys(t, n, s.targetId))).next((() => i._s.saveNamedQuery(t, e)));\n }));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class po {\n constructor(t) {\n this.M = t, this.wi = new Map, this.mi = new Map;\n }\n getBundleMetadata(t, e) {\n return pi.resolve(this.wi.get(e));\n }\n saveBundleMetadata(t, e) {\n /** Decodes a BundleMetadata proto into a BundleMetadata object. */\n var n;\n return this.wi.set(e.id, {\n id: (n = e).id,\n version: n.version,\n createTime: ms(n.createTime)\n }), pi.resolve();\n }\n getNamedQuery(t, e) {\n return pi.resolve(this.mi.get(e));\n }\n saveNamedQuery(t, e) {\n return this.mi.set(e.name, function(t) {\n return {\n name: t.name,\n query: Gi(t.bundledQuery),\n readTime: ms(t.readTime)\n };\n }(e)), pi.resolve();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */ class Io {\n constructor() {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n this.overlays = new Bn(xt.comparator), this.gi = new Map;\n }\n getOverlay(t, e) {\n return pi.resolve(this.overlays.get(e));\n }\n saveOverlays(t, e, n) {\n return n.forEach(((n, s) => {\n this.Xt(t, e, s);\n })), pi.resolve();\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = this.gi.get(n);\n return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))), \n this.gi.delete(n)), pi.resolve();\n }\n getOverlaysForCollection(t, e, n) {\n const s = Hn(), i = e.length + 1, r = new xt(e.child(\"\")), o = this.overlays.getIteratorFrom(r);\n for (;o.hasNext(); ) {\n const t = o.getNext().value, r = t.getKey();\n if (!e.isPrefixOf(r.path)) break;\n // Documents from sub-collections\n r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));\n }\n return pi.resolve(s);\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n let i = new Bn(((t, e) => t - e));\n const r = this.overlays.getIterator();\n for (;r.hasNext(); ) {\n const t = r.getNext().value;\n if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {\n let e = i.get(t.largestBatchId);\n null === e && (e = Hn(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);\n }\n }\n const o = Hn(), u = i.getIterator();\n for (;u.hasNext(); ) {\n if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;\n }\n return pi.resolve(o);\n }\n Xt(t, e, n) {\n if (null === n) return;\n // Remove the association of the overlay to its batch id.\n const s = this.overlays.get(n.key);\n if (null !== s) {\n const t = this.gi.get(s.largestBatchId).delete(n.key);\n this.gi.set(s.largestBatchId, t);\n }\n this.overlays = this.overlays.insert(n.key, new Ni(e, n));\n // Create the association of this overlay to the given largestBatchId.\n let i = this.gi.get(e);\n void 0 === i && (i = Xn(), this.gi.set(e, i)), this.gi.set(e, i.add(n.key));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */ class To {\n constructor() {\n // A set of outstanding references to a document sorted by key.\n this.yi = new qn(Eo.pi), \n // A set of outstanding references to a document sorted by target id.\n this.Ii = new qn(Eo.Ti);\n }\n /** Returns true if the reference set contains no references. */ isEmpty() {\n return this.yi.isEmpty();\n }\n /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {\n const n = new Eo(t, e);\n this.yi = this.yi.add(n), this.Ii = this.Ii.add(n);\n }\n /** Add references to the given document keys for the given ID. */ Ei(t, e) {\n t.forEach((t => this.addReference(t, e)));\n }\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */ removeReference(t, e) {\n this.Ai(new Eo(t, e));\n }\n Ri(t, e) {\n t.forEach((t => this.removeReference(t, e)));\n }\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */ Pi(t) {\n const e = new xt(new _t([])), n = new Eo(e, t), s = new Eo(e, t + 1), i = [];\n return this.Ii.forEachInRange([ n, s ], (t => {\n this.Ai(t), i.push(t.key);\n })), i;\n }\n bi() {\n this.yi.forEach((t => this.Ai(t)));\n }\n Ai(t) {\n this.yi = this.yi.delete(t), this.Ii = this.Ii.delete(t);\n }\n Vi(t) {\n const e = new xt(new _t([])), n = new Eo(e, t), s = new Eo(e, t + 1);\n let i = Xn();\n return this.Ii.forEachInRange([ n, s ], (t => {\n i = i.add(t.key);\n })), i;\n }\n containsKey(t) {\n const e = new Eo(t, 0), n = this.yi.firstAfterOrEqual(e);\n return null !== n && t.isEqual(n.key);\n }\n}\n\nclass Eo {\n constructor(t, e) {\n this.key = t, this.vi = e;\n }\n /** Compare by key then by ID */ static pi(t, e) {\n return xt.comparator(t.key, e.key) || rt(t.vi, e.vi);\n }\n /** Compare by ID then by key */ static Ti(t, e) {\n return rt(t.vi, e.vi) || xt.comparator(t.key, e.key);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Ao {\n constructor(t, e) {\n this.indexManager = t, this.referenceDelegate = e, \n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.Bs = [], \n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.Si = 1, \n /** An ordered mapping between documents and the mutations batch IDs. */\n this.Di = new qn(Eo.pi);\n }\n checkEmpty(t) {\n return pi.resolve(0 === this.Bs.length);\n }\n addMutationBatch(t, e, n, s) {\n const i = this.Si;\n this.Si++, this.Bs.length > 0 && this.Bs[this.Bs.length - 1];\n const r = new Ci(i, e, n, s);\n this.Bs.push(r);\n // Track references by document key and index collection parents.\n for (const e of s) this.Di = this.Di.add(new Eo(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());\n return pi.resolve(r);\n }\n lookupMutationBatch(t, e) {\n return pi.resolve(this.Ci(e));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = this.xi(n), i = s < 0 ? 0 : s;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n return pi.resolve(this.Bs.length > i ? this.Bs[i] : null);\n }\n getHighestUnacknowledgedBatchId() {\n return pi.resolve(0 === this.Bs.length ? -1 : this.Si - 1);\n }\n getAllMutationBatches(t) {\n return pi.resolve(this.Bs.slice());\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n const n = new Eo(e, 0), s = new Eo(e, Number.POSITIVE_INFINITY), i = [];\n return this.Di.forEachInRange([ n, s ], (t => {\n const e = this.Ci(t.vi);\n i.push(e);\n })), pi.resolve(i);\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new qn(rt);\n return e.forEach((t => {\n const e = new Eo(t, 0), s = new Eo(t, Number.POSITIVE_INFINITY);\n this.Di.forEachInRange([ e, s ], (t => {\n n = n.add(t.vi);\n }));\n })), pi.resolve(this.Ni(n));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const n = e.path, s = n.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let i = n;\n xt.isDocumentKey(i) || (i = i.child(\"\"));\n const r = new Eo(new xt(i), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let o = new qn(rt);\n return this.Di.forEachWhile((t => {\n const e = t.key.path;\n return !!n.isPrefixOf(e) && (\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n e.length === s && (o = o.add(t.vi)), !0);\n }), r), pi.resolve(this.Ni(o));\n }\n Ni(t) {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const e = [];\n return t.forEach((t => {\n const n = this.Ci(t);\n null !== n && e.push(n);\n })), e;\n }\n removeMutationBatch(t, e) {\n U(0 === this.ki(e.batchId, \"removed\")), this.Bs.shift();\n let n = this.Di;\n return pi.forEach(e.mutations, (s => {\n const i = new Eo(s.key, e.batchId);\n return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);\n })).next((() => {\n this.Di = n;\n }));\n }\n _n(t) {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n containsKey(t, e) {\n const n = new Eo(e, 0), s = this.Di.firstAfterOrEqual(n);\n return pi.resolve(e.isEqual(s && s.key));\n }\n performConsistencyCheck(t) {\n return this.Bs.length, pi.resolve();\n }\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */ ki(t, e) {\n return this.xi(t);\n }\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */ xi(t) {\n if (0 === this.Bs.length) \n // As an index this is past the end of the queue\n return 0;\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n return t - this.Bs[0].batchId;\n }\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */ Ci(t) {\n const e = this.xi(t);\n if (e < 0 || e >= this.Bs.length) return null;\n return this.Bs[e];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass Ro {\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(t) {\n this.Mi = t, \n /** Underlying cache of documents and their read times. */\n this.docs = new Bn(xt.comparator), \n /** Size of all cached documents. */\n this.size = 0;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ addEntry(t, e) {\n const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Mi(e);\n return this.docs = this.docs.insert(n, {\n document: e.mutableCopy(),\n size: r\n }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());\n }\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ removeEntry(t) {\n const e = this.docs.get(t);\n e && (this.docs = this.docs.remove(t), this.size -= e.size);\n }\n getEntry(t, e) {\n const n = this.docs.get(e);\n return pi.resolve(n ? n.document.mutableCopy() : ne.newInvalidDocument(e));\n }\n getEntries(t, e) {\n let n = jn();\n return e.forEach((t => {\n const e = this.docs.get(t);\n n = n.insert(t, e ? e.document.mutableCopy() : ne.newInvalidDocument(t));\n })), pi.resolve(n);\n }\n getAllFromCollection(t, e, n) {\n let s = jn();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const i = new xt(e.child(\"\")), r = this.docs.getIteratorFrom(i);\n for (;r.hasNext(); ) {\n const {key: t, value: {document: i}} = r.getNext();\n if (!e.isPrefixOf(t.path)) break;\n t.path.length > e.length + 1 || (le(ce(i), n) <= 0 || (s = s.insert(i.key, i.mutableCopy())));\n }\n return pi.resolve(s);\n }\n getAllFromCollectionGroup(t, e, n, s) {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n L();\n }\n Oi(t, e) {\n return pi.forEach(this.docs, (t => e(t)));\n }\n newChangeBuffer(t) {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new Po(this);\n }\n getSize(t) {\n return pi.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass Po extends $r {\n constructor(t) {\n super(), this.Kn = t;\n }\n applyChanges(t) {\n const e = [];\n return this.changes.forEach(((n, s) => {\n s.isValidDocument() ? e.push(this.Kn.addEntry(t, s)) : this.Kn.removeEntry(n);\n })), pi.waitFor(e);\n }\n getFromCache(t, e) {\n return this.Kn.getEntry(t, e);\n }\n getAllFromCache(t, e) {\n return this.Kn.getEntries(t, e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class bo {\n constructor(t) {\n this.persistence = t, \n /**\n * Maps a target to the data about that target\n */\n this.Fi = new $n((t => _e(t)), me), \n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = ct.min(), \n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0, \n /** The highest sequence number encountered. */\n this.$i = 0, \n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.Bi = new To, this.targetCount = 0, this.Li = br.gn();\n }\n forEachTarget(t, e) {\n return this.Fi.forEach(((t, n) => e(n))), pi.resolve();\n }\n getLastRemoteSnapshotVersion(t) {\n return pi.resolve(this.lastRemoteSnapshotVersion);\n }\n getHighestSequenceNumber(t) {\n return pi.resolve(this.$i);\n }\n allocateTargetId(t) {\n return this.highestTargetId = this.Li.next(), pi.resolve(this.highestTargetId);\n }\n setTargetsMetadata(t, e, n) {\n return n && (this.lastRemoteSnapshotVersion = n), e > this.$i && (this.$i = e), \n pi.resolve();\n }\n Tn(t) {\n this.Fi.set(t.target, t);\n const e = t.targetId;\n e > this.highestTargetId && (this.Li = new br(e), this.highestTargetId = e), t.sequenceNumber > this.$i && (this.$i = t.sequenceNumber);\n }\n addTargetData(t, e) {\n return this.Tn(e), this.targetCount += 1, pi.resolve();\n }\n updateTargetData(t, e) {\n return this.Tn(e), pi.resolve();\n }\n removeTargetData(t, e) {\n return this.Fi.delete(e.target), this.Bi.Pi(e.targetId), this.targetCount -= 1, \n pi.resolve();\n }\n removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return this.Fi.forEach(((r, o) => {\n o.sequenceNumber <= e && null === n.get(o.targetId) && (this.Fi.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)), \n s++);\n })), pi.waitFor(i).next((() => s));\n }\n getTargetCount(t) {\n return pi.resolve(this.targetCount);\n }\n getTargetData(t, e) {\n const n = this.Fi.get(e) || null;\n return pi.resolve(n);\n }\n addMatchingKeys(t, e, n) {\n return this.Bi.Ei(e, n), pi.resolve();\n }\n removeMatchingKeys(t, e, n) {\n this.Bi.Ri(e, n);\n const s = this.persistence.referenceDelegate, i = [];\n return s && e.forEach((e => {\n i.push(s.markPotentiallyOrphaned(t, e));\n })), pi.waitFor(i);\n }\n removeMatchingKeysForTargetId(t, e) {\n return this.Bi.Pi(e), pi.resolve();\n }\n getMatchingKeysForTargetId(t, e) {\n const n = this.Bi.Vi(e);\n return pi.resolve(n);\n }\n containsKey(t, e) {\n return pi.resolve(this.Bi.containsKey(e));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nclass Vo {\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(t, e) {\n this.Ui = {}, this.overlays = {}, this.es = new nt(0), this.ns = !1, this.ns = !0, \n this.referenceDelegate = t(this), this.fs = new bo(this);\n this.indexManager = new cr, this.ds = function(t) {\n return new Ro(t);\n }((t => this.referenceDelegate.qi(t))), this.M = new Mi(e), this._s = new po(this.M);\n }\n start() {\n return Promise.resolve();\n }\n shutdown() {\n // No durable state to ensure is closed on shutdown.\n return this.ns = !1, Promise.resolve();\n }\n get started() {\n return this.ns;\n }\n setDatabaseDeletedListener() {\n // No op.\n }\n setNetworkEnabled() {\n // No op.\n }\n getIndexManager(t) {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n getDocumentOverlayCache(t) {\n let e = this.overlays[t.toKey()];\n return e || (e = new Io, this.overlays[t.toKey()] = e), e;\n }\n getMutationQueue(t, e) {\n let n = this.Ui[t.toKey()];\n return n || (n = new Ao(e, this.referenceDelegate), this.Ui[t.toKey()] = n), n;\n }\n getTargetCache() {\n return this.fs;\n }\n getRemoteDocumentCache() {\n return this.ds;\n }\n getBundleCache() {\n return this._s;\n }\n runTransaction(t, e, n) {\n O(\"MemoryPersistence\", \"Starting transaction:\", t);\n const s = new vo(this.es.next());\n return this.referenceDelegate.Ki(), n(s).next((t => this.referenceDelegate.Gi(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(), \n t)));\n }\n Qi(t, e) {\n return pi.or(Object.values(this.Ui).map((n => () => n.containsKey(t, e))));\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */ class vo extends yi {\n constructor(t) {\n super(), this.currentSequenceNumber = t;\n }\n}\n\nclass So {\n constructor(t) {\n this.persistence = t, \n /** Tracks all documents that are active in Query views. */\n this.ji = new To, \n /** The list of documents that are potentially GCed after each transaction. */\n this.Wi = null;\n }\n static zi(t) {\n return new So(t);\n }\n get Hi() {\n if (this.Wi) return this.Wi;\n throw L();\n }\n addReference(t, e, n) {\n return this.ji.addReference(n, e), this.Hi.delete(n.toString()), pi.resolve();\n }\n removeReference(t, e, n) {\n return this.ji.removeReference(n, e), this.Hi.add(n.toString()), pi.resolve();\n }\n markPotentiallyOrphaned(t, e) {\n return this.Hi.add(e.toString()), pi.resolve();\n }\n removeTarget(t, e) {\n this.ji.Pi(e.targetId).forEach((t => this.Hi.add(t.toString())));\n const n = this.persistence.getTargetCache();\n return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n t.forEach((t => this.Hi.add(t.toString())));\n })).next((() => n.removeTargetData(t, e)));\n }\n Ki() {\n this.Wi = new Set;\n }\n Gi(t) {\n // Remove newly orphaned documents.\n const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();\n return pi.forEach(this.Hi, (n => {\n const s = xt.fromPath(n);\n return this.Ji(t, s).next((t => {\n t || e.removeEntry(s, ct.min());\n }));\n })).next((() => (this.Wi = null, e.apply(t))));\n }\n updateLimboDocument(t, e) {\n return this.Ji(t, e).next((t => {\n t ? this.Hi.delete(e.toString()) : this.Hi.add(e.toString());\n }));\n }\n qi(t) {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n Ji(t, e) {\n return pi.or([ () => pi.resolve(this.ji.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Qi(t, e) ]);\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\n/** Assembles the key for a client state in WebStorage */\nfunction Do(t, e) {\n return `firestore_clients_${t}_${e}`;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */\nfunction Co(t, e, n) {\n let s = `firestore_mutations_${t}_${n}`;\n return e.isAuthenticated() && (s += `_${e.uid}`), s;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\n/** Assembles the key for a query state in WebStorage */\nfunction xo(t, e) {\n return `firestore_targets_${t}_${e}`;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nclass No {\n constructor(t, e, n, s) {\n this.user = t, this.batchId = e, this.state = n, this.error = s;\n }\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Yi(t, e, n) {\n const s = JSON.parse(n);\n let i, r = \"object\" == typeof s && -1 !== [ \"pending\", \"acknowledged\", \"rejected\" ].indexOf(s.state) && (void 0 === s.error || \"object\" == typeof s.error);\n return r && s.error && (r = \"string\" == typeof s.error.message && \"string\" == typeof s.error.code, \n r && (i = new Q(s.error.code, s.error.message))), r ? new No(t, e, s.state, i) : (F(\"SharedClientState\", `Failed to parse mutation state for ID '${e}': ${n}`), \n null);\n }\n Xi() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nclass ko {\n constructor(t, e, n) {\n this.targetId = t, this.state = e, this.error = n;\n }\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Yi(t, e) {\n const n = JSON.parse(e);\n let s, i = \"object\" == typeof n && -1 !== [ \"not-current\", \"current\", \"rejected\" ].indexOf(n.state) && (void 0 === n.error || \"object\" == typeof n.error);\n return i && n.error && (i = \"string\" == typeof n.error.message && \"string\" == typeof n.error.code, \n i && (s = new Q(n.error.code, n.error.message))), i ? new ko(t, n.state, s) : (F(\"SharedClientState\", `Failed to parse target state for ID '${t}': ${e}`), \n null);\n }\n Xi() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */ class Mo {\n constructor(t, e) {\n this.clientId = t, this.activeTargetIds = e;\n }\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Yi(t, e) {\n const n = JSON.parse(e);\n let s = \"object\" == typeof n && n.activeTargetIds instanceof Array, i = ts();\n for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Ct(n.activeTargetIds[t]), \n i = i.add(n.activeTargetIds[t]);\n return s ? new Mo(t, i) : (F(\"SharedClientState\", `Failed to parse client data for instance '${t}': ${e}`), \n null);\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */ class Oo {\n constructor(t, e) {\n this.clientId = t, this.onlineState = e;\n }\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Yi(t) {\n const e = JSON.parse(t);\n return \"object\" == typeof e && -1 !== [ \"Unknown\", \"Online\", \"Offline\" ].indexOf(e.onlineState) && \"string\" == typeof e.clientId ? new Oo(e.clientId, e.onlineState) : (F(\"SharedClientState\", `Failed to parse online state: ${t}`), \n null);\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nclass Fo {\n constructor() {\n this.activeTargetIds = ts();\n }\n Zi(t) {\n this.activeTargetIds = this.activeTargetIds.add(t);\n }\n tr(t) {\n this.activeTargetIds = this.activeTargetIds.delete(t);\n }\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */ Xi() {\n const t = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now()\n };\n return JSON.stringify(t);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */ class $o {\n constructor(t, e, n, s, i) {\n this.window = t, this.Yn = e, this.persistenceKey = n, this.er = s, this.syncEngine = null, \n this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.nr = this.sr.bind(this), \n this.ir = new Bn(rt), this.started = !1, \n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n this.rr = [];\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const r = n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n this.storage = this.window.localStorage, this.currentUser = i, this.ur = Do(this.persistenceKey, this.er), \n this.ar = \n /** Assembles the key for the current sequence number. */\n function(t) {\n return `firestore_sequence_number_${t}`;\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (this.persistenceKey), this.ir = this.ir.insert(this.er, new Fo), this.cr = new RegExp(`^firestore_clients_${r}_([^_]*)$`), \n this.hr = new RegExp(`^firestore_mutations_${r}_(\\\\d+)(?:_(.*))?$`), this.lr = new RegExp(`^firestore_targets_${r}_(\\\\d+)$`), \n this.dr = \n /** Assembles the key for the online state of the primary tab. */\n function(t) {\n return `firestore_online_state_${t}`;\n }\n // The WebStorage prefix that plays as a event to indicate the remote documents\n // might have changed due to some secondary tabs loading a bundle.\n // format of the key is:\n // firestore_bundle_loaded_v2_\n // The version ending with \"v2\" stores the list of modified collection groups.\n (this.persistenceKey), this._r = function(t) {\n return `firestore_bundle_loaded_v2_${t}`;\n }\n // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n // looks like 'firestore_sequence_number_'.\n (this.persistenceKey), \n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener(\"storage\", this.nr);\n }\n /** Returns 'true' if WebStorage is available in the current environment. */ static vt(t) {\n return !(!t || !t.localStorage);\n }\n async start() {\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const t = await this.syncEngine.Fs();\n for (const e of t) {\n if (e === this.er) continue;\n const t = this.getItem(Do(this.persistenceKey, e));\n if (t) {\n const n = Mo.Yi(e, t);\n n && (this.ir = this.ir.insert(n.clientId, n));\n }\n }\n this.wr();\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const e = this.storage.getItem(this.dr);\n if (e) {\n const t = this.mr(e);\n t && this.gr(t);\n }\n for (const t of this.rr) this.sr(t);\n this.rr = [], \n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener(\"pagehide\", (() => this.shutdown())), this.started = !0;\n }\n writeSequenceNumber(t) {\n this.setItem(this.ar, JSON.stringify(t));\n }\n getAllActiveQueryTargets() {\n return this.yr(this.ir);\n }\n isActiveQueryTarget(t) {\n let e = !1;\n return this.ir.forEach(((n, s) => {\n s.activeTargetIds.has(t) && (e = !0);\n })), e;\n }\n addPendingMutation(t) {\n this.pr(t, \"pending\");\n }\n updateMutationState(t, e, n) {\n this.pr(t, e, n), \n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.Ir(t);\n }\n addLocalQueryTarget(t) {\n let e = \"not-current\";\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(t)) {\n const n = this.storage.getItem(xo(this.persistenceKey, t));\n if (n) {\n const s = ko.Yi(t, n);\n s && (e = s.state);\n }\n }\n return this.Tr.Zi(t), this.wr(), e;\n }\n removeLocalQueryTarget(t) {\n this.Tr.tr(t), this.wr();\n }\n isLocalQueryTarget(t) {\n return this.Tr.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n this.removeItem(xo(this.persistenceKey, t));\n }\n updateQueryState(t, e, n) {\n this.Er(t, e, n);\n }\n handleUserChange(t, e, n) {\n e.forEach((t => {\n this.Ir(t);\n })), this.currentUser = t, n.forEach((t => {\n this.addPendingMutation(t);\n }));\n }\n setOnlineState(t) {\n this.Ar(t);\n }\n notifyBundleLoaded(t) {\n this.Rr(t);\n }\n shutdown() {\n this.started && (this.window.removeEventListener(\"storage\", this.nr), this.removeItem(this.ur), \n this.started = !1);\n }\n getItem(t) {\n const e = this.storage.getItem(t);\n return O(\"SharedClientState\", \"READ\", t, e), e;\n }\n setItem(t, e) {\n O(\"SharedClientState\", \"SET\", t, e), this.storage.setItem(t, e);\n }\n removeItem(t) {\n O(\"SharedClientState\", \"REMOVE\", t), this.storage.removeItem(t);\n }\n sr(t) {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const e = t;\n if (e.storageArea === this.storage) {\n if (O(\"SharedClientState\", \"EVENT\", e.key, e.newValue), e.key === this.ur) return void F(\"Received WebStorage notification for local change. Another client might have garbage-collected our state\");\n this.Yn.enqueueRetryable((async () => {\n if (this.started) {\n if (null !== e.key) if (this.cr.test(e.key)) {\n if (null == e.newValue) {\n const t = this.Pr(e.key);\n return this.br(t, null);\n }\n {\n const t = this.Vr(e.key, e.newValue);\n if (t) return this.br(t.clientId, t);\n }\n } else if (this.hr.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.vr(e.key, e.newValue);\n if (t) return this.Sr(t);\n }\n } else if (this.lr.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.Dr(e.key, e.newValue);\n if (t) return this.Cr(t);\n }\n } else if (e.key === this.dr) {\n if (null !== e.newValue) {\n const t = this.mr(e.newValue);\n if (t) return this.gr(t);\n }\n } else if (e.key === this.ar) {\n const t = function(t) {\n let e = nt.A;\n if (null != t) try {\n const n = JSON.parse(t);\n U(\"number\" == typeof n), e = n;\n } catch (t) {\n F(\"SharedClientState\", \"Failed to read sequence number from WebStorage\", t);\n }\n return e;\n }\n /**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */ (e.newValue);\n t !== nt.A && this.sequenceNumberHandler(t);\n } else if (e.key === this._r) {\n const t = this.Nr(e.newValue);\n await Promise.all(t.map((t => this.syncEngine.kr(t))));\n }\n } else this.rr.push(e);\n }));\n }\n }\n get Tr() {\n return this.ir.get(this.er);\n }\n wr() {\n this.setItem(this.ur, this.Tr.Xi());\n }\n pr(t, e, n) {\n const s = new No(this.currentUser, t, e, n), i = Co(this.persistenceKey, this.currentUser, t);\n this.setItem(i, s.Xi());\n }\n Ir(t) {\n const e = Co(this.persistenceKey, this.currentUser, t);\n this.removeItem(e);\n }\n Ar(t) {\n const e = {\n clientId: this.er,\n onlineState: t\n };\n this.storage.setItem(this.dr, JSON.stringify(e));\n }\n Er(t, e, n) {\n const s = xo(this.persistenceKey, t), i = new ko(t, e, n);\n this.setItem(s, i.Xi());\n }\n Rr(t) {\n const e = JSON.stringify(Array.from(t));\n this.setItem(this._r, e);\n }\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */ Pr(t) {\n const e = this.cr.exec(t);\n return e ? e[1] : null;\n }\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */ Vr(t, e) {\n const n = this.Pr(t);\n return Mo.Yi(n, e);\n }\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ vr(t, e) {\n const n = this.hr.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;\n return No.Yi(new C(i), s, e);\n }\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Dr(t, e) {\n const n = this.lr.exec(t), s = Number(n[1]);\n return ko.Yi(s, e);\n }\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ mr(t) {\n return Oo.Yi(t);\n }\n Nr(t) {\n return JSON.parse(t);\n }\n async Sr(t) {\n if (t.user.uid === this.currentUser.uid) return this.syncEngine.Mr(t.batchId, t.state, t.error);\n O(\"SharedClientState\", `Ignoring mutation for non-active user ${t.user.uid}`);\n }\n Cr(t) {\n return this.syncEngine.Or(t.targetId, t.state, t.error);\n }\n br(t, e) {\n const n = e ? this.ir.insert(t, e) : this.ir.remove(t), s = this.yr(this.ir), i = this.yr(n), r = [], o = [];\n return i.forEach((t => {\n s.has(t) || r.push(t);\n })), s.forEach((t => {\n i.has(t) || o.push(t);\n })), this.syncEngine.Fr(r, o).then((() => {\n this.ir = n;\n }));\n }\n gr(t) {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n this.ir.get(t.clientId) && this.onlineStateHandler(t.onlineState);\n }\n yr(t) {\n let e = ts();\n return t.forEach(((t, n) => {\n e = e.unionWith(n.activeTargetIds);\n })), e;\n }\n}\n\nclass Bo {\n constructor() {\n this.$r = new Fo, this.Br = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;\n }\n addPendingMutation(t) {\n // No op.\n }\n updateMutationState(t, e, n) {\n // No op.\n }\n addLocalQueryTarget(t) {\n return this.$r.Zi(t), this.Br[t] || \"not-current\";\n }\n updateQueryState(t, e, n) {\n this.Br[t] = e;\n }\n removeLocalQueryTarget(t) {\n this.$r.tr(t);\n }\n isLocalQueryTarget(t) {\n return this.$r.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n delete this.Br[t];\n }\n getAllActiveQueryTargets() {\n return this.$r.activeTargetIds;\n }\n isActiveQueryTarget(t) {\n return this.$r.activeTargetIds.has(t);\n }\n start() {\n return this.$r = new Fo, Promise.resolve();\n }\n handleUserChange(t, e, n) {\n // No op.\n }\n setOnlineState(t) {\n // No op.\n }\n shutdown() {}\n writeSequenceNumber(t) {}\n notifyBundleLoaded(t) {\n // No op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Lo {\n Lr(t) {\n // No-op.\n }\n shutdown() {\n // No-op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nclass Uo {\n constructor() {\n this.Ur = () => this.qr(), this.Kr = () => this.Gr(), this.Qr = [], this.jr();\n }\n Lr(t) {\n this.Qr.push(t);\n }\n shutdown() {\n window.removeEventListener(\"online\", this.Ur), window.removeEventListener(\"offline\", this.Kr);\n }\n jr() {\n window.addEventListener(\"online\", this.Ur), window.addEventListener(\"offline\", this.Kr);\n }\n qr() {\n O(\"ConnectivityMonitor\", \"Network connectivity changed: AVAILABLE\");\n for (const t of this.Qr) t(0 /* AVAILABLE */);\n }\n Gr() {\n O(\"ConnectivityMonitor\", \"Network connectivity changed: UNAVAILABLE\");\n for (const t of this.Qr) t(1 /* UNAVAILABLE */);\n }\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static vt() {\n return \"undefined\" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const qo = {\n BatchGetDocuments: \"batchGet\",\n Commit: \"commit\",\n RunQuery: \"runQuery\"\n};\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nclass Ko {\n constructor(t) {\n this.Wr = t.Wr, this.zr = t.zr;\n }\n Hr(t) {\n this.Jr = t;\n }\n Yr(t) {\n this.Xr = t;\n }\n onMessage(t) {\n this.Zr = t;\n }\n close() {\n this.zr();\n }\n send(t) {\n this.Wr(t);\n }\n eo() {\n this.Jr();\n }\n no(t) {\n this.Xr(t);\n }\n so(t) {\n this.Zr(t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Go extends \n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nclass {\n constructor(t) {\n this.databaseInfo = t, this.databaseId = t.databaseId;\n const e = t.ssl ? \"https\" : \"http\";\n this.io = e + \"://\" + t.host, this.ro = \"projects/\" + this.databaseId.projectId + \"/databases/\" + this.databaseId.database + \"/documents\";\n }\n oo(t, e, n, s, i) {\n const r = this.uo(t, e);\n O(\"RestConnection\", \"Sending: \", r, n);\n const o = {};\n return this.ao(o, s, i), this.co(t, r, o, n).then((t => (O(\"RestConnection\", \"Received: \", t), \n t)), (e => {\n throw $(\"RestConnection\", `${t} failed with error: `, e, \"url: \", r, \"request:\", n), \n e;\n }));\n }\n ho(t, e, n, s, i) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.oo(t, e, n, s, i);\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */ ao(t, e, n) {\n t[\"X-Goog-Api-Client\"] = \"gl-js/ fire/\" + x, \n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n t[\"Content-Type\"] = \"text/plain\", this.databaseInfo.appId && (t[\"X-Firebase-GMPID\"] = this.databaseInfo.appId), \n e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));\n }\n uo(t, e) {\n const n = qo[t];\n return `${this.io}/v1/${e}:${n}`;\n }\n} {\n constructor(t) {\n super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling, \n this.useFetchStreams = t.useFetchStreams;\n }\n co(t, e, n, s) {\n return new Promise(((i, r) => {\n const o = new XhrIo;\n o.listenOnce(EventType.COMPLETE, (() => {\n try {\n switch (o.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const e = o.getResponseJson();\n O(\"Connection\", \"XHR received:\", JSON.stringify(e)), i(e);\n break;\n\n case ErrorCode.TIMEOUT:\n O(\"Connection\", 'RPC \"' + t + '\" timed out'), r(new Q(G.DEADLINE_EXCEEDED, \"Request time out\"));\n break;\n\n case ErrorCode.HTTP_ERROR:\n const n = o.getStatus();\n if (O(\"Connection\", 'RPC \"' + t + '\" failed with status:', n, \"response text:\", o.getResponseText()), \n n > 0) {\n const t = o.getResponseJson().error;\n if (t && t.status && t.message) {\n const e = function(t) {\n const e = t.toLowerCase().replace(/_/g, \"-\");\n return Object.values(G).indexOf(e) >= 0 ? e : G.UNKNOWN;\n }(t.status);\n r(new Q(e, t.message));\n } else r(new Q(G.UNKNOWN, \"Server responded with status \" + o.getStatus()));\n } else \n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n r(new Q(G.UNAVAILABLE, \"Connection failed.\"));\n break;\n\n default:\n L();\n }\n } finally {\n O(\"Connection\", 'RPC \"' + t + '\" completed.');\n }\n }));\n const u = JSON.stringify(s);\n o.send(e, \"POST\", u, n, 15);\n }));\n }\n lo(t, e, n) {\n const s = [ this.io, \"/\", \"google.firestore.v1.Firestore\", \"/\", t, \"/channel\" ], i = createWebChannelTransport(), r = getStatEventTarget(), o = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: \"gsessionid\",\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: !0,\n supportsCrossDomainXhr: !0,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 6e5\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n this.useFetchStreams && (o.xmlHttpFactory = new FetchXmlHttpFactory({})), this.ao(o.initMessageHeaders, e, n), \n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the httpHeadersOverwriteParam option to specify that\n // the headers should instead be encoded into a special \"$httpHeaders\" query\n // parameter, which is recognized by the webchannel backend. This is\n // formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32\n // TODO(b/145624756): There is a backend bug where $httpHeaders isn't respected if the request\n // doesn't have an Origin header. So we have to exclude a few browser environments that are\n // known to (sometimes) not include an Origin. See\n // https://github.com/firebase/firebase-js-sdk/issues/1491.\n isMobileCordova() || isReactNative() || isElectron() || isIE() || isUWP() || isBrowserExtension() || (o.httpHeadersOverwriteParam = \"$httpHeaders\");\n const u = s.join(\"\");\n O(\"Connection\", \"Creating WebChannel: \" + u, o);\n const a = i.createWebChannel(u, o);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let c = !1, h = !1;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n const l = new Ko({\n Wr: t => {\n h ? O(\"Connection\", \"Not sending because WebChannel is closed:\", t) : (c || (O(\"Connection\", \"Opening WebChannel transport.\"), \n a.open(), c = !0), O(\"Connection\", \"WebChannel sending:\", t), a.send(t));\n },\n zr: () => a.close()\n }), y = (t, e, n) => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n t.listen(e, (t => {\n try {\n n(t);\n } catch (t) {\n setTimeout((() => {\n throw t;\n }), 0);\n }\n }));\n };\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n return y(a, WebChannel.EventType.OPEN, (() => {\n h || O(\"Connection\", \"WebChannel transport opened.\");\n })), y(a, WebChannel.EventType.CLOSE, (() => {\n h || (h = !0, O(\"Connection\", \"WebChannel transport closed\"), l.no());\n })), y(a, WebChannel.EventType.ERROR, (t => {\n h || (h = !0, $(\"Connection\", \"WebChannel transport errored:\", t), l.no(new Q(G.UNAVAILABLE, \"The operation could not be completed\")));\n })), y(a, WebChannel.EventType.MESSAGE, (t => {\n var e;\n if (!h) {\n const n = t.data[0];\n U(!!n);\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const s = n, i = s.error || (null === (e = s[0]) || void 0 === e ? void 0 : e.error);\n if (i) {\n O(\"Connection\", \"WebChannel received error:\", i);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const t = i.status;\n let e = \n /**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\n function(t) {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = kn[t];\n if (void 0 !== e) return Fn(e);\n }(t), n = i.message;\n void 0 === e && (e = G.INTERNAL, n = \"Unknown error status: \" + t + \" with message \" + i.message), \n // Mark closed so no further events are propagated\n h = !0, l.no(new Q(e, n)), a.close();\n } else O(\"Connection\", \"WebChannel received:\", n), l.so(n);\n }\n })), y(r, Event.STAT_EVENT, (t => {\n t.stat === Stat.PROXY ? O(\"Connection\", \"Detected buffering proxy\") : t.stat === Stat.NOPROXY && O(\"Connection\", \"Detected no buffering proxy\");\n })), setTimeout((() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n l.eo();\n }), 0), l;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Initializes the WebChannelConnection for the browser. */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** The Platform's 'window' implementation or null if not available. */\nfunction Qo() {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof window ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */ function jo() {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof document ? document : null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function Wo(t) {\n return new fs(t, /* useProto3Json= */ !0);\n}\n\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nclass zo {\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n t, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n e, \n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n n = 1e3\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */ , s = 1.5\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */ , i = 6e4) {\n this.Yn = t, this.timerId = e, this.fo = n, this._o = s, this.wo = i, this.mo = 0, \n this.yo = null, \n /** The last backoff attempt, as epoch milliseconds. */\n this.po = Date.now(), this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */ reset() {\n this.mo = 0;\n }\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */ Io() {\n this.mo = this.wo;\n }\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */ To(t) {\n // Cancel any pending backoff operation.\n this.cancel();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const e = Math.floor(this.mo + this.Eo()), n = Math.max(0, Date.now() - this.po), s = Math.max(0, e - n);\n // Guard against lastAttemptTime being in the future due to a clock change.\n s > 0 && O(\"ExponentialBackoff\", `Backing off for ${s} ms (base delay: ${this.mo} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`), \n this.yo = this.Yn.enqueueAfterDelay(this.timerId, s, (() => (this.po = Date.now(), \n t()))), \n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.mo *= this._o, this.mo < this.fo && (this.mo = this.fo), this.mo > this.wo && (this.mo = this.wo);\n }\n Ao() {\n null !== this.yo && (this.yo.skipDelay(), this.yo = null);\n }\n cancel() {\n null !== this.yo && (this.yo.cancel(), this.yo = null);\n }\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ Eo() {\n return (Math.random() - .5) * this.mo;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nclass Ho {\n constructor(t, e, n, s, i, r, o, u) {\n this.Yn = t, this.Ro = n, this.Po = s, this.bo = i, this.authCredentialsProvider = r, \n this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* Initial */ , \n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n this.Vo = 0, this.vo = null, this.So = null, this.stream = null, this.Do = new zo(t, e);\n }\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */ Co() {\n return 1 /* Starting */ === this.state || 5 /* Backoff */ === this.state || this.xo();\n }\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */ xo() {\n return 2 /* Open */ === this.state || 3 /* Healthy */ === this.state;\n }\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */ start() {\n 4 /* Error */ !== this.state ? this.auth() : this.No();\n }\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */ async stop() {\n this.Co() && await this.close(0 /* Initial */);\n }\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */ ko() {\n this.state = 0 /* Initial */ , this.Do.reset();\n }\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */ Mo() {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n this.xo() && null === this.vo && (this.vo = this.Yn.enqueueAfterDelay(this.Ro, 6e4, (() => this.Oo())));\n }\n /** Sends a message to the underlying stream. */ Fo(t) {\n this.$o(), this.stream.send(t);\n }\n /** Called by the idle timer when the stream should close due to inactivity. */ async Oo() {\n if (this.xo()) \n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(0 /* Initial */);\n }\n /** Marks the stream as active again. */ $o() {\n this.vo && (this.vo.cancel(), this.vo = null);\n }\n /** Cancels the health check delayed operation. */ Bo() {\n this.So && (this.So.cancel(), this.So = null);\n }\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */ async close(t, e) {\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.$o(), this.Bo(), this.Do.cancel(), \n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.Vo++, 4 /* Error */ !== t ? \n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.Do.reset() : e && e.code === G.RESOURCE_EXHAUSTED ? (\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n F(e.toString()), F(\"Using maximum backoff delay to prevent overloading the backend.\"), \n this.Do.Io()) : e && e.code === G.UNAUTHENTICATED && 3 /* Healthy */ !== this.state && (\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), \n // Clean up the underlying stream because we are no longer interested in events.\n null !== this.stream && (this.Lo(), this.stream.close(), this.stream = null), \n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = t, \n // Notify the listener that the stream closed.\n await this.listener.Yr(e);\n }\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */ Lo() {}\n auth() {\n this.state = 1 /* Starting */;\n const t = this.Uo(this.Vo), e = this.Vo;\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n this.Vo === e && \n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.qo(t, n);\n }), (e => {\n t((() => {\n const t = new Q(G.UNKNOWN, \"Fetching auth token failed: \" + e.message);\n return this.Ko(t);\n }));\n }));\n }\n qo(t, e) {\n const n = this.Uo(this.Vo);\n this.stream = this.Go(t, e), this.stream.Hr((() => {\n n((() => (this.state = 2 /* Open */ , this.So = this.Yn.enqueueAfterDelay(this.Po, 1e4, (() => (this.xo() && (this.state = 3 /* Healthy */), \n Promise.resolve()))), this.listener.Hr())));\n })), this.stream.Yr((t => {\n n((() => this.Ko(t)));\n })), this.stream.onMessage((t => {\n n((() => this.onMessage(t)));\n }));\n }\n No() {\n this.state = 5 /* Backoff */ , this.Do.To((async () => {\n this.state = 0 /* Initial */ , this.start();\n }));\n }\n // Visible for tests\n Ko(t) {\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return O(\"PersistentStream\", `close with error: ${t}`), this.stream = null, this.close(4 /* Error */ , t);\n }\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */ Uo(t) {\n return e => {\n this.Yn.enqueueAndForget((() => this.Vo === t ? e() : (O(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), \n Promise.resolve())));\n };\n }\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */ class Jo extends Ho {\n constructor(t, e, n, s, i, r) {\n super(t, \"listen_stream_connection_backoff\" /* ListenStreamConnectionBackoff */ , \"listen_stream_idle\" /* ListenStreamIdle */ , \"health_check_timeout\" /* HealthCheckTimeout */ , e, n, s, r), \n this.M = i;\n }\n Go(t, e) {\n return this.bo.lo(\"Listen\", t, e);\n }\n onMessage(t) {\n // A successful response means the stream is healthy\n this.Do.reset();\n const e = vs(this.M, t), n = function(t) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!(\"targetChange\" in t)) return ct.min();\n const e = t.targetChange;\n return e.targetIds && e.targetIds.length ? ct.min() : e.readTime ? ms(e.readTime) : ct.min();\n }(t);\n return this.listener.Qo(e, n);\n }\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */ jo(t) {\n const e = {};\n e.database = As(this.M), e.addTarget = function(t, e) {\n let n;\n const s = e.target;\n return n = ge(s) ? {\n documents: xs(t, s)\n } : {\n query: Ns(t, s)\n }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0 ? n.resumeToken = _s(t, e.resumeToken) : e.snapshotVersion.compareTo(ct.min()) > 0 && (\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n n.readTime = ds(t, e.snapshotVersion.toTimestamp())), n;\n }(this.M, t);\n const n = Ms(this.M, t);\n n && (e.labels = n), this.Fo(e);\n }\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */ Wo(t) {\n const e = {};\n e.database = As(this.M), e.removeTarget = t, this.Fo(e);\n }\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */ class Yo extends Ho {\n constructor(t, e, n, s, i, r) {\n super(t, \"write_stream_connection_backoff\" /* WriteStreamConnectionBackoff */ , \"write_stream_idle\" /* WriteStreamIdle */ , \"health_check_timeout\" /* HealthCheckTimeout */ , e, n, s, r), \n this.M = i, this.zo = !1;\n }\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */ get Ho() {\n return this.zo;\n }\n // Override of PersistentStream.start\n start() {\n this.zo = !1, this.lastStreamToken = void 0, super.start();\n }\n Lo() {\n this.zo && this.Jo([]);\n }\n Go(t, e) {\n return this.bo.lo(\"Write\", t, e);\n }\n onMessage(t) {\n if (\n // Always capture the last stream token.\n U(!!t.streamToken), this.lastStreamToken = t.streamToken, this.zo) {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.Do.reset();\n const e = Cs(t.writeResults, t.commitTime), n = ms(t.commitTime);\n return this.listener.Yo(n, e);\n }\n // The first response is always the handshake response\n return U(!t.writeResults || 0 === t.writeResults.length), this.zo = !0, this.listener.Xo();\n }\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */ Zo() {\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const t = {};\n t.database = As(this.M), this.Fo(t);\n }\n /** Sends a group of mutations to the Firestore backend to apply. */ Jo(t) {\n const e = {\n streamToken: this.lastStreamToken,\n writes: t.map((t => Ss(this.M, t)))\n };\n this.Fo(e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass Xo extends class {} {\n constructor(t, e, n, s) {\n super(), this.authCredentials = t, this.appCheckCredentials = e, this.bo = n, this.M = s, \n this.tu = !1;\n }\n eu() {\n if (this.tu) throw new Q(G.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n /** Invokes the provided RPC with auth and AppCheck tokens. */ oo(t, e, n) {\n return this.eu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.bo.oo(t, e, n, s, i))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === G.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new Q(G.UNKNOWN, t.toString());\n }));\n }\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ ho(t, e, n) {\n return this.eu(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.bo.ho(t, e, n, s, i))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === G.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new Q(G.UNKNOWN, t.toString());\n }));\n }\n terminate() {\n this.tu = !0;\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nclass Zo {\n constructor(t, e) {\n this.asyncQueue = t, this.onlineStateHandler = e, \n /** The current OnlineState. */\n this.state = \"Unknown\" /* Unknown */ , \n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n this.nu = 0, \n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n this.su = null, \n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n this.iu = !0;\n }\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */ ru() {\n 0 === this.nu && (this.ou(\"Unknown\" /* Unknown */), this.su = this.asyncQueue.enqueueAfterDelay(\"online_state_timeout\" /* OnlineStateTimeout */ , 1e4, (() => (this.su = null, \n this.uu(\"Backend didn't respond within 10 seconds.\"), this.ou(\"Offline\" /* Offline */), \n Promise.resolve()))));\n }\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */ au(t) {\n \"Online\" /* Online */ === this.state ? this.ou(\"Unknown\" /* Unknown */) : (this.nu++, \n this.nu >= 1 && (this.cu(), this.uu(`Connection failed 1 times. Most recent error: ${t.toString()}`), \n this.ou(\"Offline\" /* Offline */)));\n }\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */ set(t) {\n this.cu(), this.nu = 0, \"Online\" /* Online */ === t && (\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.iu = !1), this.ou(t);\n }\n ou(t) {\n t !== this.state && (this.state = t, this.onlineStateHandler(t));\n }\n uu(t) {\n const e = `Could not reach Cloud Firestore backend. ${t}\\nThis 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.`;\n this.iu ? (F(e), this.iu = !1) : O(\"OnlineStateTracker\", e);\n }\n cu() {\n null !== this.su && (this.su.cancel(), this.su = null);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class tu {\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n t, \n /** The client-side proxy for interacting with the backend. */\n e, n, s, i) {\n this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {}, \n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n this.hu = [], \n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.lu = new Map, \n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n this.fu = new Set, \n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n this.du = [], this._u = i, this._u.Lr((t => {\n n.enqueueAndForget((async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n cu(this) && (O(\"RemoteStore\", \"Restarting streams for network reachability change.\"), \n await async function(t) {\n const e = K(t);\n e.fu.add(4 /* ConnectivityChange */), await nu(e), e.wu.set(\"Unknown\" /* Unknown */), \n e.fu.delete(4 /* ConnectivityChange */), await eu(e);\n }(this));\n }));\n })), this.wu = new Zo(n, s);\n }\n}\n\nasync function eu(t) {\n if (cu(t)) for (const e of t.du) await e(/* enabled= */ !0);\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */ async function nu(t) {\n for (const e of t.du) await e(/* enabled= */ !1);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nfunction su(t, e) {\n const n = K(t);\n n.lu.has(e.targetId) || (\n // Mark this as something the client is currently listening for.\n n.lu.set(e.targetId, e), au(n) ? \n // The listen will be sent in onWatchStreamOpen\n uu(n) : Vu(n).xo() && ru(n, e));\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */ function iu(t, e) {\n const n = K(t), s = Vu(n);\n n.lu.delete(e), s.xo() && ou(n, e), 0 === n.lu.size && (s.xo() ? s.Mo() : cu(n) && \n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n n.wu.set(\"Unknown\" /* Unknown */));\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */ function ru(t, e) {\n t.mu.Z(e.targetId), Vu(t).jo(e);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */ function ou(t, e) {\n t.mu.Z(e), Vu(t).Wo(e);\n}\n\nfunction uu(t) {\n t.mu = new us({\n getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),\n Et: e => t.lu.get(e) || null\n }), Vu(t).start(), t.wu.ru();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */ function au(t) {\n return cu(t) && !Vu(t).Co() && t.lu.size > 0;\n}\n\nfunction cu(t) {\n return 0 === K(t).fu.size;\n}\n\nfunction hu(t) {\n t.mu = void 0;\n}\n\nasync function lu(t) {\n t.lu.forEach(((e, n) => {\n ru(t, e);\n }));\n}\n\nasync function fu(t, e) {\n hu(t), \n // If we still need the watch stream, retry the connection.\n au(t) ? (t.wu.au(e), uu(t)) : \n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n t.wu.set(\"Unknown\" /* Unknown */);\n}\n\nasync function du(t, e, n) {\n if (\n // Mark the client as online since we got a message from the server\n t.wu.set(\"Online\" /* Online */), e instanceof rs && 2 /* Removed */ === e.state && e.cause) \n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await \n /** Handles an error on a target */\n async function(t, e) {\n const n = e.cause;\n for (const s of e.targetIds) \n // A watched target might have been removed already.\n t.lu.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.lu.delete(s), t.mu.removeTarget(s));\n }\n /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */ (t, e);\n } catch (n) {\n O(\"RemoteStore\", \"Failed to remove targets %s: %s \", e.targetIds.join(\",\"), n), \n await _u(t, n);\n } else if (e instanceof ss ? t.mu.ut(e) : e instanceof is ? t.mu._t(e) : t.mu.ht(e), \n !n.isEqual(ct.min())) try {\n const e = await oo(t.localStore);\n n.compareTo(e) >= 0 && \n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await \n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n function(t, e) {\n const n = t.mu.yt(e);\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n return n.targetChanges.forEach(((n, s) => {\n if (n.resumeToken.approximateByteSize() > 0) {\n const i = t.lu.get(s);\n // A watched target might have been removed already.\n i && t.lu.set(s, i.withResumeToken(n.resumeToken, e));\n }\n })), \n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n n.targetMismatches.forEach((e => {\n const n = t.lu.get(e);\n if (!n) \n // A watched target might have been removed already.\n return;\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n t.lu.set(e, n.withResumeToken(pt.EMPTY_BYTE_STRING, n.snapshotVersion)), \n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n ou(t, e);\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const s = new ki(n.target, e, 1 /* ExistenceFilterMismatch */ , n.sequenceNumber);\n ru(t, s);\n })), t.remoteSyncer.applyRemoteEvent(n);\n }(t, n);\n } catch (e) {\n O(\"RemoteStore\", \"Failed to raise snapshot:\", e), await _u(t, e);\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */ async function _u(t, e, n) {\n if (!Ri(e)) throw e;\n t.fu.add(1 /* IndexedDbFailed */), \n // Disable network and raise offline snapshots\n await nu(t), t.wu.set(\"Offline\" /* Offline */), n || (\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n n = () => oo(t.localStore)), \n // Probe IndexedDB periodically and re-enable network\n t.asyncQueue.enqueueRetryable((async () => {\n O(\"RemoteStore\", \"Retrying IndexedDB access\"), await n(), t.fu.delete(1 /* IndexedDbFailed */), \n await eu(t);\n }));\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */ function wu(t, e) {\n return e().catch((n => _u(t, n, e)));\n}\n\nasync function mu(t) {\n const e = K(t), n = vu(e);\n let s = e.hu.length > 0 ? e.hu[e.hu.length - 1].batchId : -1;\n for (;gu(e); ) try {\n const t = await co(e.localStore, s);\n if (null === t) {\n 0 === e.hu.length && n.Mo();\n break;\n }\n s = t.batchId, yu(e, t);\n } catch (t) {\n await _u(e, t);\n }\n pu(e) && Iu(e);\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */ function gu(t) {\n return cu(t) && t.hu.length < 10;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */ function yu(t, e) {\n t.hu.push(e);\n const n = vu(t);\n n.xo() && n.Ho && n.Jo(e.mutations);\n}\n\nfunction pu(t) {\n return cu(t) && !vu(t).Co() && t.hu.length > 0;\n}\n\nfunction Iu(t) {\n vu(t).start();\n}\n\nasync function Tu(t) {\n vu(t).Zo();\n}\n\nasync function Eu(t) {\n const e = vu(t);\n // Send the write pipeline now that the stream is established.\n for (const n of t.hu) e.Jo(n.mutations);\n}\n\nasync function Au(t, e, n) {\n const s = t.hu.shift(), i = xi.from(s, e, n);\n await wu(t, (() => t.remoteSyncer.applySuccessfulWrite(i))), \n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await mu(t);\n}\n\nasync function Ru(t, e) {\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n e && vu(t).Ho && \n // This error affects the actual write.\n await async function(t, e) {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (n = e.code, On(n) && n !== G.ABORTED) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const n = t.hu.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n vu(t).ko(), await wu(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))), \n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await mu(t);\n }\n var n;\n }(t, e), \n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n pu(t) && Iu(t);\n}\n\nasync function Pu(t, e) {\n const n = K(t);\n n.asyncQueue.verifyOperationInProgress(), O(\"RemoteStore\", \"RemoteStore received new credentials\");\n const s = cu(n);\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n n.fu.add(3 /* CredentialChange */), await nu(n), s && \n // Don't set the network status to Unknown if we are offline.\n n.wu.set(\"Unknown\" /* Unknown */), await n.remoteSyncer.handleCredentialChange(e), \n n.fu.delete(3 /* CredentialChange */), await eu(n);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */ async function bu(t, e) {\n const n = K(t);\n e ? (n.fu.delete(2 /* IsSecondary */), await eu(n)) : e || (n.fu.add(2 /* IsSecondary */), \n await nu(n), n.wu.set(\"Unknown\" /* Unknown */));\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function Vu(t) {\n return t.gu || (\n // Create stream (but note that it is not started yet).\n t.gu = function(t, e, n) {\n const s = K(t);\n return s.eu(), new Jo(e, s.bo, s.authCredentials, s.appCheckCredentials, s.M, n);\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.datastore, t.asyncQueue, {\n Hr: lu.bind(null, t),\n Yr: fu.bind(null, t),\n Qo: du.bind(null, t)\n }), t.du.push((async e => {\n e ? (t.gu.ko(), au(t) ? uu(t) : t.wu.set(\"Unknown\" /* Unknown */)) : (await t.gu.stop(), \n hu(t));\n }))), t.gu;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function vu(t) {\n return t.yu || (\n // Create stream (but note that it is not started yet).\n t.yu = function(t, e, n) {\n const s = K(t);\n return s.eu(), new Yo(e, s.bo, s.authCredentials, s.appCheckCredentials, s.M, n);\n }(t.datastore, t.asyncQueue, {\n Hr: Tu.bind(null, t),\n Yr: Ru.bind(null, t),\n Xo: Eu.bind(null, t),\n Yo: Au.bind(null, t)\n }), t.du.push((async e => {\n e ? (t.yu.ko(), \n // This will start the write stream if necessary.\n await mu(t)) : (await t.yu.stop(), t.hu.length > 0 && (O(\"RemoteStore\", `Stopping write stream with ${t.hu.length} pending writes`), \n t.hu = []));\n }))), t.yu;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nclass Su {\n constructor(t, e, n, s, i) {\n this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i, \n this.deferred = new j, this.then = this.deferred.promise.then.bind(this.deferred.promise), \n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch((t => {}));\n }\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */ static createAndSchedule(t, e, n, s, i) {\n const r = Date.now() + n, o = new Su(t, e, r, s, i);\n return o.start(n), o;\n }\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */ start(t) {\n this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);\n }\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */ skipDelay() {\n return this.handleDelayElapsed();\n }\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */ cancel(t) {\n null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new Q(G.CANCELLED, \"Operation cancelled\" + (t ? \": \" + t : \"\"))));\n }\n handleDelayElapsed() {\n this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), \n this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));\n }\n clearTimeout() {\n null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), \n this.timerHandle = null);\n }\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */ function Du(t, e) {\n if (F(\"AsyncQueue\", `${e}: ${t}`), Ri(t)) return new Q(G.UNAVAILABLE, `${e}: ${t}`);\n throw t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */ class Cu {\n /** The default ordering is by key if the comparator is omitted */\n constructor(t) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n this.comparator = t ? (e, n) => t(e, n) || xt.comparator(e.key, n.key) : (t, e) => xt.comparator(t.key, e.key), \n this.keyedMap = zn(), this.sortedSet = new Bn(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */ static emptySet(t) {\n return new Cu(t.comparator);\n }\n has(t) {\n return null != this.keyedMap.get(t);\n }\n get(t) {\n return this.keyedMap.get(t);\n }\n first() {\n return this.sortedSet.minKey();\n }\n last() {\n return this.sortedSet.maxKey();\n }\n isEmpty() {\n return this.sortedSet.isEmpty();\n }\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */ indexOf(t) {\n const e = this.keyedMap.get(t);\n return e ? this.sortedSet.indexOf(e) : -1;\n }\n get size() {\n return this.sortedSet.size;\n }\n /** Iterates documents in order defined by \"comparator\" */ forEach(t) {\n this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Inserts or updates a document with the same key */ add(t) {\n // First remove the element if we have it.\n const e = this.delete(t.key);\n return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));\n }\n /** Deletes a document with a given key */ delete(t) {\n const e = this.get(t);\n return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;\n }\n isEqual(t) {\n if (!(t instanceof Cu)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (!t.isEqual(s)) return !1;\n }\n return !0;\n }\n toString() {\n const t = [];\n return this.forEach((e => {\n t.push(e.toString());\n })), 0 === t.length ? \"DocumentSet ()\" : \"DocumentSet (\\n \" + t.join(\" \\n\") + \"\\n)\";\n }\n copy(t, e) {\n const n = new Cu;\n return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */ class xu {\n constructor() {\n this.pu = new Bn(xt.comparator);\n }\n track(t) {\n const e = t.doc.key, n = this.pu.get(e);\n n ? \n // Merge the new change with the existing change.\n 0 /* Added */ !== t.type && 3 /* Metadata */ === n.type ? this.pu = this.pu.insert(e, t) : 3 /* Metadata */ === t.type && 1 /* Removed */ !== n.type ? this.pu = this.pu.insert(e, {\n type: n.type,\n doc: t.doc\n }) : 2 /* Modified */ === t.type && 2 /* Modified */ === n.type ? this.pu = this.pu.insert(e, {\n type: 2 /* Modified */ ,\n doc: t.doc\n }) : 2 /* Modified */ === t.type && 0 /* Added */ === n.type ? this.pu = this.pu.insert(e, {\n type: 0 /* Added */ ,\n doc: t.doc\n }) : 1 /* Removed */ === t.type && 0 /* Added */ === n.type ? this.pu = this.pu.remove(e) : 1 /* Removed */ === t.type && 2 /* Modified */ === n.type ? this.pu = this.pu.insert(e, {\n type: 1 /* Removed */ ,\n doc: n.doc\n }) : 0 /* Added */ === t.type && 1 /* Removed */ === n.type ? this.pu = this.pu.insert(e, {\n type: 2 /* Modified */ ,\n doc: t.doc\n }) : \n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n L() : this.pu = this.pu.insert(e, t);\n }\n Iu() {\n const t = [];\n return this.pu.inorderTraversal(((e, n) => {\n t.push(n);\n })), t;\n }\n}\n\nclass Nu {\n constructor(t, e, n, s, i, r, o, u) {\n this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i, \n this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u;\n }\n /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s) {\n const i = [];\n return e.forEach((t => {\n i.push({\n type: 0 /* Added */ ,\n doc: t\n });\n })), new Nu(t, e, Cu.emptySet(e), i, n, s, \n /* syncStateChanged= */ !0, \n /* excludesMetadataChanges= */ !1);\n }\n get hasPendingWrites() {\n return !this.mutatedKeys.isEmpty();\n }\n isEqual(t) {\n if (!(this.fromCache === t.fromCache && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && je(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;\n const e = this.docChanges, n = t.docChanges;\n if (e.length !== n.length) return !1;\n for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;\n return !0;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */ class ku {\n constructor() {\n this.Tu = void 0, this.listeners = [];\n }\n}\n\nclass Mu {\n constructor() {\n this.queries = new $n((t => We(t)), je), this.onlineState = \"Unknown\" /* Unknown */ , \n this.Eu = new Set;\n }\n}\n\nasync function Ou(t, e) {\n const n = K(t), s = e.query;\n let i = !1, r = n.queries.get(s);\n if (r || (i = !0, r = new ku), i) try {\n r.Tu = await n.onListen(s);\n } catch (t) {\n const n = Du(t, `Initialization of query '${ze(e.query)}' failed`);\n return void e.onError(n);\n }\n if (n.queries.set(s, r), r.listeners.push(e), \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n e.Au(n.onlineState), r.Tu) {\n e.Ru(r.Tu) && Lu(n);\n }\n}\n\nasync function Fu(t, e) {\n const n = K(t), s = e.query;\n let i = !1;\n const r = n.queries.get(s);\n if (r) {\n const t = r.listeners.indexOf(e);\n t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);\n }\n if (i) return n.queries.delete(s), n.onUnlisten(s);\n}\n\nfunction $u(t, e) {\n const n = K(t);\n let s = !1;\n for (const t of e) {\n const e = t.query, i = n.queries.get(e);\n if (i) {\n for (const e of i.listeners) e.Ru(t) && (s = !0);\n i.Tu = t;\n }\n }\n s && Lu(n);\n}\n\nfunction Bu(t, e, n) {\n const s = K(t), i = s.queries.get(e);\n if (i) for (const t of i.listeners) t.onError(n);\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n s.queries.delete(e);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction Lu(t) {\n t.Eu.forEach((t => {\n t.next();\n }));\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */ class Uu {\n constructor(t, e, n) {\n this.query = t, this.Pu = e, \n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.bu = !1, this.Vu = null, this.onlineState = \"Unknown\" /* Unknown */ , this.options = n || {};\n }\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */ Ru(t) {\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const e = [];\n for (const n of t.docChanges) 3 /* Metadata */ !== n.type && e.push(n);\n t = new Nu(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged, \n /* excludesMetadataChanges= */ !0);\n }\n let e = !1;\n return this.bu ? this.vu(t) && (this.Pu.next(t), e = !0) : this.Su(t, this.onlineState) && (this.Du(t), \n e = !0), this.Vu = t, e;\n }\n onError(t) {\n this.Pu.error(t);\n }\n /** Returns whether a snapshot was raised. */ Au(t) {\n this.onlineState = t;\n let e = !1;\n return this.Vu && !this.bu && this.Su(this.Vu, t) && (this.Du(this.Vu), e = !0), \n e;\n }\n Su(t, e) {\n // Always raise the first event when we're synced\n if (!t.fromCache) return !0;\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const n = \"Offline\" /* Offline */ !== e;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n return (!this.options.Cu || !n) && (!t.docs.isEmpty() || \"Offline\" /* Offline */ === e);\n // Raise data from cache if we have any documents or we are offline\n }\n vu(t) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (t.docChanges.length > 0) return !0;\n const e = this.Vu && this.Vu.hasPendingWrites !== t.hasPendingWrites;\n return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n }\n Du(t) {\n t = Nu.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache), this.bu = !0, \n this.Pu.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */ class qu {\n constructor(t, \n // How many bytes this element takes to store in the bundle.\n e) {\n this.payload = t, this.byteLength = e;\n }\n xu() {\n return \"metadata\" in this.payload;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */ class Ku {\n constructor(t) {\n this.M = t;\n }\n fi(t) {\n return Is(this.M, t);\n }\n /**\n * Converts a BundleDocument to a MutableDocument.\n */ di(t) {\n return t.metadata.exists ? bs(this.M, t.document, !1) : ne.newNoDocument(this.fi(t.metadata.name), this._i(t.metadata.readTime));\n }\n _i(t) {\n return ms(t);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */ class Gu {\n constructor(t, e, n) {\n this.Nu = t, this.localStore = e, this.M = n, \n /** Batched queries to be saved into storage */\n this.queries = [], \n /** Batched documents to be saved into storage */\n this.documents = [], \n /** The collection groups affected by this bundle. */\n this.collectionGroups = new Set, this.progress = Qu(t);\n }\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */ ku(t) {\n this.progress.bytesLoaded += t.byteLength;\n let e = this.progress.documentsLoaded;\n if (t.payload.namedQuery) this.queries.push(t.payload.namedQuery); else if (t.payload.documentMetadata) {\n this.documents.push({\n metadata: t.payload.documentMetadata\n }), t.payload.documentMetadata.exists || ++e;\n const n = _t.fromString(t.payload.documentMetadata.name);\n this.collectionGroups.add(n.get(n.length - 2));\n } else t.payload.document && (this.documents[this.documents.length - 1].document = t.payload.document, \n ++e);\n return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e, \n Object.assign({}, this.progress)) : null;\n }\n Mu(t) {\n const e = new Map, n = new Ku(this.M);\n for (const s of t) if (s.metadata.queries) {\n const t = n.fi(s.metadata.name);\n for (const n of s.metadata.queries) {\n const s = (e.get(n) || Xn()).add(t);\n e.set(n, s);\n }\n }\n return e;\n }\n /**\n * Update the progress to 'Success' and return the updated progress.\n */ async complete() {\n const t = await go(this.localStore, new Ku(this.M), this.documents, this.Nu.id), e = this.Mu(this.documents);\n for (const t of this.queries) await yo(this.localStore, t, e.get(t.name));\n return this.progress.taskState = \"Success\", {\n progress: this.progress,\n Ou: this.collectionGroups,\n Fu: t\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */ function Qu(t) {\n return {\n taskState: \"Running\",\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass ju {\n constructor(t) {\n this.key = t;\n }\n}\n\nclass Wu {\n constructor(t) {\n this.key = t;\n }\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */ class zu {\n constructor(t, \n /** Documents included in the remote target */\n e) {\n this.query = t, this.$u = e, this.Bu = null, \n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = !1, \n /** Documents in the view but not in the remote target */\n this.Lu = Xn(), \n /** Document Keys that have local changes */\n this.mutatedKeys = Xn(), this.Uu = Ye(t), this.qu = new Cu(this.Uu);\n }\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */ get Ku() {\n return this.$u;\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */ Gu(t, e) {\n const n = e ? e.Qu : new xu, s = e ? e.qu : this.qu;\n let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const u = $e(this.query) && s.size === this.query.limit ? s.last() : null, a = Be(this.query) && s.size === this.query.limit ? s.first() : null;\n // Drop documents out to meet limit/limitToLast requirement.\n if (t.inorderTraversal(((t, e) => {\n const c = s.get(t), h = He(this.query, e) ? e : null, l = !!c && this.mutatedKeys.has(c.key), f = !!h && (h.hasLocalMutations || \n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n this.mutatedKeys.has(h.key) && h.hasCommittedMutations);\n let d = !1;\n // Calculate change\n if (c && h) {\n c.data.isEqual(h.data) ? l !== f && (n.track({\n type: 3 /* Metadata */ ,\n doc: h\n }), d = !0) : this.ju(c, h) || (n.track({\n type: 2 /* Modified */ ,\n doc: h\n }), d = !0, (u && this.Uu(h, u) > 0 || a && this.Uu(h, a) < 0) && (\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n o = !0));\n } else !c && h ? (n.track({\n type: 0 /* Added */ ,\n doc: h\n }), d = !0) : c && !h && (n.track({\n type: 1 /* Removed */ ,\n doc: c\n }), d = !0, (u || a) && (\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n o = !0));\n d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));\n })), $e(this.query) || Be(this.query)) for (;r.size > this.query.limit; ) {\n const t = $e(this.query) ? r.last() : r.first();\n r = r.delete(t.key), i = i.delete(t.key), n.track({\n type: 1 /* Removed */ ,\n doc: t\n });\n }\n return {\n qu: r,\n Qu: n,\n ni: o,\n mutatedKeys: i\n };\n }\n ju(t, e) {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;\n }\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param updateLimboDocuments - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(t, e, n) {\n const s = this.qu;\n this.qu = t.qu, this.mutatedKeys = t.mutatedKeys;\n // Sort changes based on type and query comparator\n const i = t.Qu.Iu();\n i.sort(((t, e) => function(t, e) {\n const n = t => {\n switch (t) {\n case 0 /* Added */ :\n return 1;\n\n case 2 /* Modified */ :\n case 3 /* Metadata */ :\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n\n case 1 /* Removed */ :\n return 0;\n\n default:\n return L();\n }\n };\n return n(t) - n(e);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.type, e.type) || this.Uu(t.doc, e.doc))), this.Wu(n);\n const r = e ? this.zu() : [], o = 0 === this.Lu.size && this.current ? 1 /* Synced */ : 0 /* Local */ , u = o !== this.Bu;\n if (this.Bu = o, 0 !== i.length || u) {\n return {\n snapshot: new Nu(this.query, t.qu, s, i, t.mutatedKeys, 0 /* Local */ === o, u, \n /* excludesMetadataChanges= */ !1),\n Hu: r\n };\n }\n // no changes\n return {\n Hu: r\n };\n }\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */ Au(t) {\n return this.current && \"Offline\" /* Offline */ === t ? (\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = !1, this.applyChanges({\n qu: this.qu,\n Qu: new xu,\n mutatedKeys: this.mutatedKeys,\n ni: !1\n }, \n /* updateLimboDocuments= */ !1)) : {\n Hu: []\n };\n }\n /**\n * Returns whether the doc for the given key should be in limbo.\n */ Ju(t) {\n // If the remote end says it's part of this query, it's not in limbo.\n return !this.$u.has(t) && (\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n !!this.qu.has(t) && !this.qu.get(t).hasLocalMutations);\n }\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */ Wu(t) {\n t && (t.addedDocuments.forEach((t => this.$u = this.$u.add(t))), t.modifiedDocuments.forEach((t => {})), \n t.removedDocuments.forEach((t => this.$u = this.$u.delete(t))), this.current = t.current);\n }\n zu() {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) return [];\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const t = this.Lu;\n this.Lu = Xn(), this.qu.forEach((t => {\n this.Ju(t.key) && (this.Lu = this.Lu.add(t.key));\n }));\n // Diff the new limbo docs with the old limbo docs.\n const e = [];\n return t.forEach((t => {\n this.Lu.has(t) || e.push(new Wu(t));\n })), this.Lu.forEach((n => {\n t.has(n) || e.push(new ju(n));\n })), e;\n }\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n Yu(t) {\n this.$u = t.li, this.Lu = Xn();\n const e = this.Gu(t.documents);\n return this.applyChanges(e, /*updateLimboDocuments=*/ !0);\n }\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n Xu() {\n return Nu.fromInitialDocuments(this.query, this.qu, this.mutatedKeys, 0 /* Local */ === this.Bu);\n }\n}\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass Hu {\n constructor(\n /**\n * The query itself.\n */\n t, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n e, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n n) {\n this.query = t, this.targetId = e, this.view = n;\n }\n}\n\n/** Tracks a limbo resolution. */ class Ju {\n constructor(t) {\n this.key = t, \n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n this.Zu = !1;\n }\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */ class Yu {\n constructor(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r) {\n this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s, \n this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.ta = {}, this.ea = new $n((t => We(t)), je), \n this.na = new Map, \n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n this.sa = new Set, \n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n this.ia = new Bn(xt.comparator), \n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n this.ra = new Map, this.oa = new To, \n /** Stores user completion handlers, indexed by User and BatchId. */\n this.ua = {}, \n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n this.aa = new Map, this.ca = br.yn(), this.onlineState = \"Unknown\" /* Unknown */ , \n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n this.ha = void 0;\n }\n get isPrimaryClient() {\n return !0 === this.ha;\n }\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nasync function Xu(t, e) {\n const n = Va(t);\n let s, i;\n const r = n.ea.get(e);\n if (r) \n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.Xu(); else {\n const t = await ho(n.localStore, Ge(e));\n n.isPrimaryClient && su(n.remoteStore, t);\n const r = n.sharedClientState.addLocalQueryTarget(t.targetId);\n s = t.targetId, i = await Zu(n, e, s, \"current\" === r);\n }\n return i;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */ async function Zu(t, e, n, s) {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n t.la = (e, n, s) => async function(t, e, n, s) {\n let i = e.view.Gu(n);\n i.ni && (\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n i = await fo(t.localStore, e.query, \n /* usePreviousResults= */ !1).then((({documents: t}) => e.view.Gu(t, i))));\n const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i, \n /* updateLimboDocuments= */ t.isPrimaryClient, r);\n return fa(t, e.targetId, o.Hu), o.snapshot;\n }(t, e, n, s);\n const i = await fo(t.localStore, e, \n /* usePreviousResults= */ !0), r = new zu(e, i.li), o = r.Gu(i.documents), u = ns.createSynthesizedTargetChangeForCurrentChange(n, s && \"Offline\" /* Offline */ !== t.onlineState), a = r.applyChanges(o, \n /* updateLimboDocuments= */ t.isPrimaryClient, u);\n fa(t, n, a.Hu);\n const c = new Hu(e, n, r);\n return t.ea.set(e, c), t.na.has(n) ? t.na.get(n).push(e) : t.na.set(n, [ e ]), a.snapshot;\n}\n\n/** Stops listening to the query. */ async function ta(t, e) {\n const n = K(t), s = n.ea.get(e), i = n.na.get(s.targetId);\n if (i.length > 1) return n.na.set(s.targetId, i.filter((t => !je(t, e)))), void n.ea.delete(e);\n // No other queries are mapped to the target, clean up the query and the target.\n if (n.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n n.sharedClientState.removeLocalQueryTarget(s.targetId);\n n.sharedClientState.isActiveQueryTarget(s.targetId) || await lo(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !1).then((() => {\n n.sharedClientState.clearQueryState(s.targetId), iu(n.remoteStore, s.targetId), \n ha(n, s.targetId);\n })).catch(Cr);\n } else ha(n, s.targetId), await lo(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !0);\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ async function ea(t, e, n) {\n const s = va(t);\n try {\n const t = await function(t, e) {\n const n = K(t), s = at.now(), i = e.reduce(((t, e) => t.add(e.key)), Xn());\n let r;\n return n.persistence.runTransaction(\"Locally write mutations\", \"readwrite\", (t => n.ci.Ks(t, i).next((i => {\n r = i;\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const o = [];\n for (const t of e) {\n const e = An(t, r.get(t.key));\n null != e && \n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n o.push(new Vn(t.key, e, ee(e.value.mapValue), yn.exists(!0)));\n }\n return n.Bs.addMutationBatch(t, s, o, e);\n })))).then((t => (t.applyToLocalDocumentSet(r), {\n batchId: t.batchId,\n changes: r\n })));\n }(s.localStore, e);\n s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {\n let s = t.ua[t.currentUser.toKey()];\n s || (s = new Bn(rt));\n s = s.insert(e, n), t.ua[t.currentUser.toKey()] = s;\n }\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */ (s, t.batchId, n), await wa(s, t.changes), await mu(s.remoteStore);\n } catch (t) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const e = Du(t, \"Failed to persist write\");\n n.reject(e);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */ async function na(t, e) {\n const n = K(t);\n try {\n const t = await uo(n.localStore, e);\n // Update `receivedDocument` as appropriate for any limbo targets.\n e.targetChanges.forEach(((t, e) => {\n const s = n.ra.get(e);\n s && (\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n U(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1), \n t.addedDocuments.size > 0 ? s.Zu = !0 : t.modifiedDocuments.size > 0 ? U(s.Zu) : t.removedDocuments.size > 0 && (U(s.Zu), \n s.Zu = !1));\n })), await wa(n, t, e);\n } catch (t) {\n await Cr(t);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */ function sa(t, e, n) {\n const s = K(t);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (s.isPrimaryClient && 0 /* RemoteStore */ === n || !s.isPrimaryClient && 1 /* SharedClientState */ === n) {\n const t = [];\n s.ea.forEach(((n, s) => {\n const i = s.view.Au(e);\n i.snapshot && t.push(i.snapshot);\n })), function(t, e) {\n const n = K(t);\n n.onlineState = e;\n let s = !1;\n n.queries.forEach(((t, n) => {\n for (const t of n.listeners) \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n t.Au(e) && (s = !0);\n })), s && Lu(n);\n }(s.eventManager, e), t.length && s.ta.Qo(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */ async function ia(t, e, n) {\n const s = K(t);\n // PORTING NOTE: Multi-tab only.\n s.sharedClientState.updateQueryState(e, \"rejected\", n);\n const i = s.ra.get(e), r = i && i.key;\n if (r) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let t = new Bn(xt.comparator);\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n t = t.insert(r, ne.newNoDocument(r, ct.min()));\n const n = Xn().add(r), i = new es(ct.min(), \n /* targetChanges= */ new Map, \n /* targetMismatches= */ new qn(rt), t, n);\n await na(s, i), \n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n s.ia = s.ia.remove(r), s.ra.delete(e), _a(s);\n } else await lo(s.localStore, e, \n /* keepPersistedTargetData */ !1).then((() => ha(s, e, n))).catch(Cr);\n}\n\nasync function ra(t, e) {\n const n = K(t), s = e.batch.batchId;\n try {\n const t = await ro(n.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n ca(n, s, /*error=*/ null), aa(n, s), n.sharedClientState.updateMutationState(s, \"acknowledged\"), \n await wa(n, t);\n } catch (t) {\n await Cr(t);\n }\n}\n\nasync function oa(t, e, n) {\n const s = K(t);\n try {\n const t = await function(t, e) {\n const n = K(t);\n return n.persistence.runTransaction(\"Reject batch\", \"readwrite-primary\", (t => {\n let s;\n return n.Bs.lookupMutationBatch(t, e).next((e => (U(null !== e), s = e.keys(), n.Bs.removeMutationBatch(t, e)))).next((() => n.Bs.performConsistencyCheck(t))).next((() => n.ci.Ks(t, s)));\n }));\n }\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */ (s.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n ca(s, e, n), aa(s, e), s.sharedClientState.updateMutationState(e, \"rejected\", n), \n await wa(s, t);\n } catch (n) {\n await Cr(n);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */ async function ua(t, e) {\n const n = K(t);\n cu(n.remoteStore) || O(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\");\n try {\n const t = await function(t) {\n const e = K(t);\n return e.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (t => e.Bs.getHighestUnacknowledgedBatchId(t)));\n }(n.localStore);\n if (-1 === t) \n // Trigger the callback right away if there is no pending writes at the moment.\n return void e.resolve();\n const s = n.aa.get(t) || [];\n s.push(e), n.aa.set(t, s);\n } catch (t) {\n const n = Du(t, \"Initialization of waitForPendingWrites() operation failed\");\n e.reject(n);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */ function aa(t, e) {\n (t.aa.get(e) || []).forEach((t => {\n t.resolve();\n })), t.aa.delete(e);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */ function ca(t, e, n) {\n const s = K(t);\n let i = s.ua[s.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (i) {\n const t = i.get(e);\n t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.ua[s.currentUser.toKey()] = i;\n }\n}\n\nfunction ha(t, e, n = null) {\n t.sharedClientState.removeLocalQueryTarget(e);\n for (const s of t.na.get(e)) t.ea.delete(s), n && t.ta.fa(s, n);\n if (t.na.delete(e), t.isPrimaryClient) {\n t.oa.Pi(e).forEach((e => {\n t.oa.containsKey(e) || \n // We removed the last reference for this key\n la(t, e);\n }));\n }\n}\n\nfunction la(t, e) {\n t.sa.delete(e.path.canonicalString());\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const n = t.ia.get(e);\n null !== n && (iu(t.remoteStore, n), t.ia = t.ia.remove(e), t.ra.delete(n), _a(t));\n}\n\nfunction fa(t, e, n) {\n for (const s of n) if (s instanceof ju) t.oa.addReference(s.key, e), da(t, s); else if (s instanceof Wu) {\n O(\"SyncEngine\", \"Document no longer in limbo: \" + s.key), t.oa.removeReference(s.key, e);\n t.oa.containsKey(s.key) || \n // We removed the last reference for this key\n la(t, s.key);\n } else L();\n}\n\nfunction da(t, e) {\n const n = e.key, s = n.path.canonicalString();\n t.ia.get(n) || t.sa.has(s) || (O(\"SyncEngine\", \"New document in limbo: \" + n), t.sa.add(s), \n _a(t));\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */ function _a(t) {\n for (;t.sa.size > 0 && t.ia.size < t.maxConcurrentLimboResolutions; ) {\n const e = t.sa.values().next().value;\n t.sa.delete(e);\n const n = new xt(_t.fromString(e)), s = t.ca.next();\n t.ra.set(s, new Ju(n)), t.ia = t.ia.insert(n, s), su(t.remoteStore, new ki(Ge(Fe(n.path)), s, 2 /* LimboResolution */ , nt.A));\n }\n}\n\nasync function wa(t, e, n) {\n const s = K(t), i = [], r = [], o = [];\n s.ea.isEmpty() || (s.ea.forEach(((t, u) => {\n o.push(s.la(u, e, n).then((t => {\n if (t) {\n s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, t.fromCache ? \"not-current\" : \"current\"), \n i.push(t);\n const e = to.Ys(u.targetId, t);\n r.push(e);\n }\n })));\n })), await Promise.all(o), s.ta.Qo(i), await async function(t, e) {\n const n = K(t);\n try {\n await n.persistence.runTransaction(\"notifyLocalViewChanges\", \"readwrite\", (t => pi.forEach(e, (e => pi.forEach(e.Hs, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => pi.forEach(e.Js, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));\n } catch (t) {\n if (!Ri(t)) throw t;\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n O(\"LocalStore\", \"Failed to update sequence numbers: \" + t);\n }\n for (const t of e) {\n const e = t.targetId;\n if (!t.fromCache) {\n const t = n.ii.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);\n // Advance the last limbo free snapshot version\n n.ii = n.ii.insert(e, i);\n }\n }\n }(s.localStore, r));\n}\n\nasync function ma(t, e) {\n const n = K(t);\n if (!n.currentUser.isEqual(e)) {\n O(\"SyncEngine\", \"User change. New user:\", e.toKey());\n const t = await io(n.localStore, e);\n n.currentUser = e, \n // Fails tasks waiting for pending writes requested by previous user.\n function(t, e) {\n t.aa.forEach((t => {\n t.forEach((t => {\n t.reject(new Q(G.CANCELLED, e));\n }));\n })), t.aa.clear();\n }(n, \"'waitForPendingWrites' promise is rejected due to a user change.\"), \n // TODO(b/114226417): Consider calling this only in the primary tab.\n n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await wa(n, t.hi);\n }\n}\n\nfunction ga(t, e) {\n const n = K(t), s = n.ra.get(e);\n if (s && s.Zu) return Xn().add(s.key);\n {\n let t = Xn();\n const s = n.na.get(e);\n if (!s) return t;\n for (const e of s) {\n const s = n.ea.get(e);\n t = t.unionWith(s.view.Ku);\n }\n return t;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */ async function ya(t, e) {\n const n = K(t), s = await fo(n.localStore, e.query, \n /* usePreviousResults= */ !0), i = e.view.Yu(s);\n return n.isPrimaryClient && fa(n, e.targetId, i.Hu), i;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nasync function pa(t, e) {\n const n = K(t);\n return wo(n.localStore, e).then((t => wa(n, t)));\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nasync function Ia(t, e, n, s) {\n const i = K(t), r = await function(t, e) {\n const n = K(t), s = K(n.Bs);\n return n.persistence.runTransaction(\"Lookup mutation documents\", \"readonly\", (t => s.fn(t, e).next((e => e ? n.ci.Ks(t, e) : pi.resolve(null)))));\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e);\n null !== r ? (\"pending\" === n ? \n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await mu(i.remoteStore) : \"acknowledged\" === n || \"rejected\" === n ? (\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n ca(i, e, s || null), aa(i, e), function(t, e) {\n K(K(t).Bs)._n(e);\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e)) : L(), await wa(i, r)) : \n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n O(\"SyncEngine\", \"Cannot apply mutation batch with id: \" + e);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function Ta(t, e) {\n const n = K(t);\n if (Va(n), va(n), !0 === e && !0 !== n.ha) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const t = n.sharedClientState.getAllActiveQueryTargets(), e = await Ea(n, t.toArray());\n n.ha = !0, await bu(n.remoteStore, !0);\n for (const t of e) su(n.remoteStore, t);\n } else if (!1 === e && !1 !== n.ha) {\n const t = [];\n let e = Promise.resolve();\n n.na.forEach(((s, i) => {\n n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (ha(n, i), \n lo(n.localStore, i, \n /*keepPersistedTargetData=*/ !0)))), iu(n.remoteStore, i);\n })), await e, await Ea(n, t), \n // PORTING NOTE: Multi-Tab only.\n function(t) {\n const e = K(t);\n e.ra.forEach(((t, n) => {\n iu(e.remoteStore, n);\n })), e.oa.bi(), e.ra = new Map, e.ia = new Bn(xt.comparator);\n }\n /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n // PORTING NOTE: Multi-Tab only.\n (n), n.ha = !1, await bu(n.remoteStore, !1);\n }\n}\n\nasync function Ea(t, e, n) {\n const s = K(t), i = [], r = [];\n for (const t of e) {\n let e;\n const n = s.na.get(t);\n if (n && 0 !== n.length) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n e = await ho(s.localStore, Ge(n[0]));\n for (const t of n) {\n const e = s.ea.get(t), n = await ya(s, e);\n n.snapshot && r.push(n.snapshot);\n }\n } else {\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const n = await _o(s.localStore, t);\n e = await ho(s.localStore, n), await Zu(s, Aa(n), t, \n /*current=*/ !1);\n }\n i.push(e);\n }\n return s.ta.Qo(r), i;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction Aa(t) {\n return Oe(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, \"F\" /* First */ , t.startAt, t.endAt);\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nfunction Ra(t) {\n const e = K(t);\n return K(K(e.localStore).persistence).Fs();\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function Pa(t, e, n, s) {\n const i = K(t);\n if (i.ha) \n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n return void O(\"SyncEngine\", \"Ignoring unexpected query state notification.\");\n const r = i.na.get(e);\n if (r && r.length > 0) switch (n) {\n case \"current\":\n case \"not-current\":\n {\n const t = await wo(i.localStore, Je(r[0])), s = es.createSynthesizedRemoteEventForCurrentChange(e, \"current\" === n);\n await wa(i, t, s);\n break;\n }\n\n case \"rejected\":\n await lo(i.localStore, e, \n /* keepPersistedTargetData */ !0), ha(i, e, s);\n break;\n\n default:\n L();\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */ async function ba(t, e, n) {\n const s = Va(t);\n if (s.ha) {\n for (const t of e) {\n if (s.na.has(t)) {\n // A target might have been added in a previous attempt\n O(\"SyncEngine\", \"Adding an already active target \" + t);\n continue;\n }\n const e = await _o(s.localStore, t), n = await ho(s.localStore, e);\n await Zu(s, Aa(e), n.targetId, \n /*current=*/ !1), su(s.remoteStore, n);\n }\n for (const t of n) \n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n s.na.has(t) && \n // Release queries that are still active.\n await lo(s.localStore, t, \n /* keepPersistedTargetData */ !1).then((() => {\n iu(s.remoteStore, t), ha(s, t);\n })).catch(Cr);\n }\n}\n\nfunction Va(t) {\n const e = K(t);\n return e.remoteStore.remoteSyncer.applyRemoteEvent = na.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = ga.bind(null, e), \n e.remoteStore.remoteSyncer.rejectListen = ia.bind(null, e), e.ta.Qo = $u.bind(null, e.eventManager), \n e.ta.fa = Bu.bind(null, e.eventManager), e;\n}\n\nfunction va(t) {\n const e = K(t);\n return e.remoteStore.remoteSyncer.applySuccessfulWrite = ra.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = oa.bind(null, e), \n e;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */ function Sa(t, e, n) {\n const s = K(t);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (\n /** Loads a bundle and returns the list of affected collection groups. */\n async function(t, e, n) {\n try {\n const s = await e.getMetadata();\n if (await function(t, e) {\n const n = K(t), s = ms(e.createTime);\n return n.persistence.runTransaction(\"hasNewerBundle\", \"readonly\", (t => n._s.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));\n }\n /**\n * Saves the given `BundleMetadata` to local persistence.\n */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {\n return {\n taskState: \"Success\",\n documentsLoaded: t.totalDocuments,\n bytesLoaded: t.totalBytes,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n }(s)), Promise.resolve(new Set);\n n._updateProgress(Qu(s));\n const i = new Gu(s, t.localStore, e.M);\n let r = await e.da();\n for (;r; ) {\n const t = await i.ku(r);\n t && n._updateProgress(t), r = await e.da();\n }\n const o = await i.complete();\n return await wa(t, o.Fu, \n /* remoteEvent */ void 0), \n // Save metadata, so loading the same bundle will skip.\n await function(t, e) {\n const n = K(t);\n return n.persistence.runTransaction(\"Save bundle\", \"readwrite\", (t => n._s.saveBundleMetadata(t, e)));\n }\n /**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Ou);\n } catch (t) {\n return $(\"SyncEngine\", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);\n }\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */)(s, e, n).then((t => {\n s.sharedClientState.notifyBundleLoaded(t);\n }));\n}\n\nclass Da {\n constructor() {\n this.synchronizeTabs = !1;\n }\n async initialize(t) {\n this.M = Wo(t.databaseInfo.databaseId), this.sharedClientState = this._a(t), this.persistence = this.wa(t), \n await this.persistence.start(), this.gcScheduler = this.ma(t), this.localStore = this.ga(t);\n }\n ma(t) {\n return null;\n }\n ga(t) {\n return so(this.persistence, new eo, t.initialUser, this.M);\n }\n wa(t) {\n return new Vo(So.zi, this.M);\n }\n _a(t) {\n return new Bo;\n }\n async terminate() {\n this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(), \n await this.persistence.shutdown();\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */ class Ca extends Da {\n constructor(t, e, n) {\n super(), this.ya = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;\n }\n async initialize(t) {\n await super.initialize(t), await this.ya.initialize(this, t), \n // Enqueue writes from a previous session\n await va(this.ya.syncEngine), await mu(this.ya.remoteStore), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.Ts((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(this.localStore), \n Promise.resolve())));\n }\n ga(t) {\n return so(this.persistence, new eo, t.initialUser, this.M);\n }\n ma(t) {\n const e = this.persistence.referenceDelegate.garbageCollector;\n return new kr(e, t.asyncQueue);\n }\n wa(t) {\n const e = Xr(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? yr.withCacheSize(this.cacheSizeBytes) : yr.DEFAULT;\n return new Hr(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, Qo(), jo(), this.M, this.sharedClientState, !!this.forceOwnership);\n }\n _a(t) {\n return new Bo;\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */ class xa extends Ca {\n constructor(t, e) {\n super(t, e, /* forceOwnership= */ !1), this.ya = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;\n }\n async initialize(t) {\n await super.initialize(t);\n const e = this.ya.syncEngine;\n this.sharedClientState instanceof $o && (this.sharedClientState.syncEngine = {\n Mr: Ia.bind(null, e),\n Or: Pa.bind(null, e),\n Fr: ba.bind(null, e),\n Fs: Ra.bind(null, e),\n kr: pa.bind(null, e)\n }, await this.sharedClientState.start()), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.Ts((async t => {\n await Ta(this.ya.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start(this.localStore) : t || this.gcScheduler.stop());\n }));\n }\n _a(t) {\n const e = Qo();\n if (!$o.vt(e)) throw new Q(G.UNIMPLEMENTED, \"IndexedDB persistence is only available on platforms that support LocalStorage.\");\n const n = Xr(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);\n return new $o(e, t.asyncQueue, n, t.clientId, t.initialUser);\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */ class Na {\n async initialize(t, e) {\n this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState, \n this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e), \n this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e, \n /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => sa(this.syncEngine, t, 1 /* SharedClientState */), \n this.remoteStore.remoteSyncer.handleCredentialChange = ma.bind(null, this.syncEngine), \n await bu(this.remoteStore, this.syncEngine.isPrimaryClient));\n }\n createEventManager(t) {\n return new Mu;\n }\n createDatastore(t) {\n const e = Wo(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new Go(s));\n var s;\n /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {\n return new Xo(t, e, n, s);\n }(t.authCredentials, t.appCheckCredentials, n, e);\n }\n createRemoteStore(t) {\n return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => sa(this.syncEngine, t, 0 /* RemoteStore */), \n r = Uo.vt() ? new Uo : new Lo, new tu(e, n, s, i, r);\n var e, n, s, i, r;\n /** Re-enables the network. Idempotent. */ }\n createSyncEngine(t, e) {\n return function(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r, o) {\n const u = new Yu(t, e, n, s, i, r);\n return o && (u.ha = !0), u;\n }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);\n }\n terminate() {\n return async function(t) {\n const e = K(t);\n O(\"RemoteStore\", \"RemoteStore shutting down.\"), e.fu.add(5 /* Shutdown */), await nu(e), \n e._u.shutdown(), \n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n e.wu.set(\"Unknown\" /* Unknown */);\n }(this.remoteStore);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nfunction ka(t, e = 10240) {\n let n = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read() {\n if (n < t.byteLength) {\n const s = {\n value: t.slice(n, n + e),\n done: !1\n };\n return n += e, s;\n }\n return {\n done: !0\n };\n },\n async cancel() {},\n releaseLock() {},\n closed: Promise.reject(\"unimplemented\")\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nclass Ma {\n constructor(t) {\n this.observer = t, \n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = !1;\n }\n next(t) {\n this.observer.next && this.pa(this.observer.next, t);\n }\n error(t) {\n this.observer.error ? this.pa(this.observer.error, t) : console.error(\"Uncaught Error in snapshot listener:\", t);\n }\n Ia() {\n this.muted = !0;\n }\n pa(t, e) {\n this.muted || setTimeout((() => {\n this.muted || t(e);\n }), 0);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */ class Oa {\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n t, e) {\n this.Ta = t, this.M = e, \n /** Cached bundle metadata. */\n this.metadata = new j, \n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n this.buffer = new Uint8Array, this.Ea = new TextDecoder(\"utf-8\"), \n // Read the metadata (which is the first element).\n this.Aa().then((t => {\n t && t.xu() ? this.metadata.resolve(t.payload.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\\n ${JSON.stringify(null == t ? void 0 : t.payload)}`));\n }), (t => this.metadata.reject(t)));\n }\n close() {\n return this.Ta.cancel();\n }\n async getMetadata() {\n return this.metadata.promise;\n }\n async da() {\n // Makes sure metadata is read before proceeding.\n return await this.getMetadata(), this.Aa();\n }\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */ async Aa() {\n const t = await this.Ra();\n if (null === t) return null;\n const e = this.Ea.decode(t), n = Number(e);\n isNaN(n) && this.Pa(`length string (${e}) is not valid number`);\n const s = await this.ba(n);\n return new qu(JSON.parse(s), t.length + n);\n }\n /** First index of '{' from the underlying buffer. */ Va() {\n return this.buffer.findIndex((t => t === \"{\".charCodeAt(0)));\n }\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */ async Ra() {\n for (;this.Va() < 0; ) {\n if (await this.va()) break;\n }\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (0 === this.buffer.length) return null;\n const t = this.Va();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n t < 0 && this.Pa(\"Reached the end of bundle when a length string is expected.\");\n const e = this.buffer.slice(0, t);\n // Update the internal buffer to drop the read length.\n return this.buffer = this.buffer.slice(t), e;\n }\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */ async ba(t) {\n for (;this.buffer.length < t; ) {\n await this.va() && this.Pa(\"Reached the end of bundle when more is expected.\");\n }\n const e = this.Ea.decode(this.buffer.slice(0, t));\n // Update the internal buffer to drop the read json string.\n return this.buffer = this.buffer.slice(t), e;\n }\n Pa(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n throw this.Ta.cancel(), new Error(`Invalid bundle format: ${t}`);\n }\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */ async va() {\n const t = await this.Ta.read();\n if (!t.done) {\n const e = new Uint8Array(this.buffer.length + t.value.length);\n e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;\n }\n return t.done;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nclass Fa {\n constructor(t) {\n this.datastore = t, \n // The version of each document that was read during this transaction.\n this.readVersions = new Map, this.mutations = [], this.committed = !1, \n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n this.lastWriteError = null, \n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n this.writtenDocs = new Set;\n }\n async lookup(t) {\n if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new Q(G.INVALID_ARGUMENT, \"Firestore transactions require all reads to be executed before all writes.\");\n const e = await async function(t, e) {\n const n = K(t), s = As(n.M) + \"/documents\", i = {\n documents: e.map((t => ps(n.M, t)))\n }, r = await n.ho(\"BatchGetDocuments\", s, i), o = new Map;\n r.forEach((t => {\n const e = Vs(n.M, t);\n o.set(e.key.toString(), e);\n }));\n const u = [];\n return e.forEach((t => {\n const e = o.get(t.toString());\n U(!!e), u.push(e);\n })), u;\n }(this.datastore, t);\n return e.forEach((t => this.recordVersion(t))), e;\n }\n set(t, e) {\n this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n update(t, e) {\n try {\n this.write(e.toMutation(t, this.preconditionForUpdate(t)));\n } catch (t) {\n this.lastWriteError = t;\n }\n this.writtenDocs.add(t.toString());\n }\n delete(t) {\n this.write(new Cn(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n async commit() {\n if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;\n const t = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach((e => {\n t.delete(e.key.toString());\n })), \n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n t.forEach(((t, e) => {\n const n = xt.fromPath(e);\n this.mutations.push(new xn(n, this.precondition(n)));\n })), await async function(t, e) {\n const n = K(t), s = As(n.M) + \"/documents\", i = {\n writes: e.map((t => Ss(n.M, t)))\n };\n await n.oo(\"Commit\", s, i);\n }(this.datastore, this.mutations), this.committed = !0;\n }\n recordVersion(t) {\n let e;\n if (t.isFoundDocument()) e = t.version; else {\n if (!t.isNoDocument()) throw L();\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n e = ct.min();\n }\n const n = this.readVersions.get(t.key.toString());\n if (n) {\n if (!e.isEqual(n)) \n // This transaction will fail no matter what.\n throw new Q(G.ABORTED, \"Document version changed between two reads.\");\n } else this.readVersions.set(t.key.toString(), e);\n }\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */ precondition(t) {\n const e = this.readVersions.get(t.toString());\n return !this.writtenDocs.has(t.toString()) && e ? yn.updateTime(e) : yn.none();\n }\n /**\n * Returns the precondition for a document if the operation is an update.\n */ preconditionForUpdate(t) {\n const e = this.readVersions.get(t.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(t.toString()) && e) {\n if (e.isEqual(ct.min())) \n // The document doesn't exist, so fail the transaction.\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new Q(G.INVALID_ARGUMENT, \"Can't update a document that doesn't exist.\");\n // Document exists, base precondition on document update time.\n return yn.updateTime(e);\n }\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return yn.exists(!0);\n }\n write(t) {\n this.ensureCommitNotCalled(), this.mutations.push(t);\n }\n ensureCommitNotCalled() {}\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nclass $a {\n constructor(t, e, n, s) {\n this.asyncQueue = t, this.datastore = e, this.updateFunction = n, this.deferred = s, \n this.Sa = 5, this.Do = new zo(this.asyncQueue, \"transaction_retry\" /* TransactionRetry */);\n }\n /** Runs the transaction and sets the result on deferred. */ run() {\n this.Sa -= 1, this.Da();\n }\n Da() {\n this.Do.To((async () => {\n const t = new Fa(this.datastore), e = this.Ca(t);\n e && e.then((e => {\n this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {\n this.deferred.resolve(e);\n })).catch((t => {\n this.xa(t);\n }))));\n })).catch((t => {\n this.xa(t);\n }));\n }));\n }\n Ca(t) {\n try {\n const e = this.updateFunction(t);\n return !St(e) && e.catch && e.then ? e : (this.deferred.reject(Error(\"Transaction callback must return a Promise\")), \n null);\n } catch (t) {\n // Do not retry errors thrown by user provided updateFunction.\n return this.deferred.reject(t), null;\n }\n }\n xa(t) {\n this.Sa > 0 && this.Na(t) ? (this.Sa -= 1, this.asyncQueue.enqueueAndForget((() => (this.Da(), \n Promise.resolve())))) : this.deferred.reject(t);\n }\n Na(t) {\n if (\"FirebaseError\" === t.name) {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const e = t.code;\n return \"aborted\" === e || \"failed-precondition\" === e || !On(e);\n }\n return !1;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the\n * pieces of the client SDK architecture. It is responsible for creating the\n * async queue that is shared by all of the other components in the system.\n */\nclass Ba {\n constructor(t, e, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n n, s) {\n this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s, \n this.user = C.UNAUTHENTICATED, this.clientId = it.R(), this.authCredentialListener = () => Promise.resolve(), \n this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {\n O(\"FirestoreClient\", \"Received user=\", t.uid), await this.authCredentialListener(t), \n this.user = t;\n })), this.appCheckCredentials.start(n, (t => (O(\"FirestoreClient\", \"Received new app check token=\", t), \n this.appCheckCredentialListener(t, this.user))));\n }\n async getConfiguration() {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: 100\n };\n }\n setCredentialChangeListener(t) {\n this.authCredentialListener = t;\n }\n setAppCheckTokenChangeListener(t) {\n this.appCheckCredentialListener = t;\n }\n /**\n * Checks that the client has not been terminated. Ensures that other methods on\n * this class cannot be called after the client is terminated.\n */ verifyNotTerminated() {\n if (this.asyncQueue.isShuttingDown) throw new Q(G.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n terminate() {\n this.asyncQueue.enterRestrictedMode();\n const t = new j;\n return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n this.onlineComponents && await this.onlineComponents.terminate(), this.offlineComponents && await this.offlineComponents.terminate(), \n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();\n } catch (e) {\n const n = Du(e, \"Failed to shutdown persistence\");\n t.reject(n);\n }\n })), t.promise;\n }\n}\n\nasync function La(t, e) {\n t.asyncQueue.verifyOperationInProgress(), O(\"FirestoreClient\", \"Initializing OfflineComponentProvider\");\n const n = await t.getConfiguration();\n await e.initialize(n);\n let s = n.initialUser;\n t.setCredentialChangeListener((async t => {\n s.isEqual(t) || (await io(e.localStore, t), s = t);\n })), \n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n e.persistence.setDatabaseDeletedListener((() => t.terminate())), t.offlineComponents = e;\n}\n\nasync function Ua(t, e) {\n t.asyncQueue.verifyOperationInProgress();\n const n = await qa(t);\n O(\"FirestoreClient\", \"Initializing OnlineComponentProvider\");\n const s = await t.getConfiguration();\n await e.initialize(n, s), \n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n t.setCredentialChangeListener((t => Pu(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => Pu(e.remoteStore, n))), \n t.onlineComponents = e;\n}\n\nasync function qa(t) {\n return t.offlineComponents || (O(\"FirestoreClient\", \"Using default OfflineComponentProvider\"), \n await La(t, new Da)), t.offlineComponents;\n}\n\nasync function Ka(t) {\n return t.onlineComponents || (O(\"FirestoreClient\", \"Using default OnlineComponentProvider\"), \n await Ua(t, new Na)), t.onlineComponents;\n}\n\nfunction Ga(t) {\n return qa(t).then((t => t.persistence));\n}\n\nfunction Qa(t) {\n return qa(t).then((t => t.localStore));\n}\n\nfunction ja(t) {\n return Ka(t).then((t => t.remoteStore));\n}\n\nfunction Wa(t) {\n return Ka(t).then((t => t.syncEngine));\n}\n\nasync function za(t) {\n const e = await Ka(t), n = e.eventManager;\n return n.onListen = Xu.bind(null, e.syncEngine), n.onUnlisten = ta.bind(null, e.syncEngine), \n n;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */ function Ha(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Ga(t), n = await ja(t);\n return e.setNetworkEnabled(!0), function(t) {\n const e = K(t);\n return e.fu.delete(0 /* UserDisabled */), eu(e);\n }(n);\n }));\n}\n\n/** Disables the network connection. Pending operations will not complete. */ function Ja(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Ga(t), n = await ja(t);\n return e.setNetworkEnabled(!1), async function(t) {\n const e = K(t);\n e.fu.add(0 /* UserDisabled */), await nu(e), \n // Set the OnlineState to Offline so get()s return from cache, etc.\n e.wu.set(\"Offline\" /* Offline */);\n }(n);\n }));\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */ function Ya(t, e) {\n const n = new j;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await function(t, e) {\n const n = K(t);\n return n.persistence.runTransaction(\"read document\", \"readonly\", (t => n.ci.Ls(t, e)));\n }(t, e);\n s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new Q(G.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.)\"));\n } catch (t) {\n const s = Du(t, `Failed to get document '${e} from cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */ (await Qa(t), e, n))), n.promise;\n}\n\nfunction Xa(t, e, n = {}) {\n const s = new j;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new Ma({\n next: r => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => Fu(t, o)));\n const u = r.docs.has(n);\n !u && r.fromCache ? \n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n i.reject(new Q(G.UNAVAILABLE, \"Failed to get document because the client is offline.\")) : u && r.fromCache && s && \"server\" === s.source ? i.reject(new Q(G.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(r);\n },\n error: t => i.reject(t)\n }), o = new Uu(Fe(n.path), r, {\n includeMetadataChanges: !0,\n Cu: !0\n });\n return Ou(t, o);\n }(await za(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction Za(t, e) {\n const n = new j;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await fo(t, e, \n /* usePreviousResults= */ !0), i = new zu(e, s.li), r = i.Gu(s.documents), o = i.applyChanges(r, \n /* updateLimboDocuments= */ !1);\n n.resolve(o.snapshot);\n } catch (t) {\n const s = Du(t, `Failed to execute query '${e} against cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */ (await Qa(t), e, n))), n.promise;\n}\n\nfunction tc(t, e, n = {}) {\n const s = new j;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new Ma({\n next: n => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => Fu(t, o))), n.fromCache && \"server\" === s.source ? i.reject(new Q(G.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);\n },\n error: t => i.reject(t)\n }), o = new Uu(n, r, {\n includeMetadataChanges: !0,\n Cu: !0\n });\n return Ou(t, o);\n }(await za(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction ec(t, e) {\n const n = new Ma(e);\n return t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n K(t).Eu.add(e), \n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n e.next();\n }(await za(t), n))), () => {\n n.Ia(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n K(t).Eu.delete(e);\n }(await za(t), n)));\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */ function nc(t, e) {\n const n = new j;\n return t.asyncQueue.enqueueAndForget((async () => {\n const s = await function(t) {\n return Ka(t).then((t => t.datastore));\n }(t);\n new $a(t.asyncQueue, s, e, n).run();\n })), n.promise;\n}\n\nfunction sc(t, e, n, s) {\n const i = function(t, e) {\n let n;\n n = \"string\" == typeof t ? (new TextEncoder).encode(t) : t;\n return function(t, e) {\n return new Oa(t, e);\n }(function(t, e) {\n if (t instanceof Uint8Array) return ka(t, e);\n if (t instanceof ArrayBuffer) return ka(new Uint8Array(t), e);\n if (t instanceof ReadableStream) return t.getReader();\n throw new Error(\"Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream\");\n }(n), e);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n, Wo(e));\n t.asyncQueue.enqueueAndForget((async () => {\n Sa(await Wa(t), i, s);\n }));\n}\n\nfunction ic(t, e) {\n return t.asyncQueue.enqueue((async () => function(t, e) {\n const n = K(t);\n return n.persistence.runTransaction(\"Get named query\", \"readonly\", (t => n._s.getNamedQuery(t, e)));\n }(await Qa(t), e)));\n}\n\nconst rc = new Map;\n\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction oc(t, e, n) {\n if (!n) throw new Q(G.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */ function uc(t, e, n, s) {\n if (!0 === e && !0 === s) throw new Q(G.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */ function ac(t) {\n if (!xt.isDocumentKey(t)) throw new Q(G.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */ function cc(t) {\n if (xt.isDocumentKey(t)) throw new Q(G.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\n/** Returns a string describing the type / value of the provided input. */\nfunction hc(t) {\n if (void 0 === t) return \"undefined\";\n if (null === t) return \"null\";\n if (\"string\" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), \n JSON.stringify(t);\n if (\"number\" == typeof t || \"boolean\" == typeof t) return \"\" + t;\n if (\"object\" == typeof t) {\n if (t instanceof Array) return \"an array\";\n {\n const e = \n /** try to get the constructor name for an object. */\n function(t) {\n if (t.constructor) return t.constructor.name;\n return null;\n }\n /**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */ (t);\n return e ? `a custom ${e} object` : \"an object\";\n }\n }\n return \"function\" == typeof t ? \"a function\" : L();\n}\n\nfunction lc(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n if (\"_delegate\" in t && (\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t = t._delegate), !(t instanceof e)) {\n if (e.name === t.constructor.name) throw new Q(G.INVALID_ARGUMENT, \"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?\");\n {\n const n = hc(t);\n throw new Q(G.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);\n }\n }\n return t;\n}\n\nfunction fc(t, e) {\n if (e <= 0) throw new Q(G.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// settings() defaults:\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass dc {\n constructor(t) {\n var e;\n if (void 0 === t.host) {\n if (void 0 !== t.ssl) throw new Q(G.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n this.host = \"firestore.googleapis.com\", this.ssl = true;\n } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;\n if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, \n void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {\n if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new Q(G.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n this.cacheSizeBytes = t.cacheSizeBytes;\n }\n this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, \n this.useFetchStreams = !!t.useFetchStreams, uc(\"experimentalForceLongPolling\", t.experimentalForceLongPolling, \"experimentalAutoDetectLongPolling\", t.experimentalAutoDetectLongPolling);\n }\n isEqual(t) {\n return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link getFirestore}.\n */ class _c {\n /** @hideconstructor */\n constructor(t, e, n) {\n this._authCredentials = e, this._appCheckCredentials = n, \n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n this.type = \"firestore-lite\", this._persistenceKey = \"(lite)\", this._settings = new dc({}), \n this._settingsFrozen = !1, t instanceof vt ? this._databaseId = t : (this._app = t, \n this._databaseId = function(t) {\n if (!Object.prototype.hasOwnProperty.apply(t.options, [ \"projectId\" ])) throw new Q(G.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n return new vt(t.options.projectId);\n }\n /**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */ (t));\n }\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */ get app() {\n if (!this._app) throw new Q(G.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is not available\");\n return this._app;\n }\n get _initialized() {\n return this._settingsFrozen;\n }\n get _terminated() {\n return void 0 !== this._terminateTask;\n }\n _setSettings(t) {\n if (this._settingsFrozen) throw new Q(G.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.\");\n this._settings = new dc(t), void 0 !== t.credentials && (this._authCredentials = function(t) {\n if (!t) return new z;\n switch (t.type) {\n case \"gapi\":\n const e = t.client;\n // Make sure this really is a Gapi client.\n return U(!(\"object\" != typeof e || null === e || !e.auth || !e.auth.getAuthHeaderValueForFirstParty)), \n new X(e, t.sessionIndex || \"0\", t.iamToken || null);\n\n case \"provider\":\n return t.client;\n\n default:\n throw new Q(G.INVALID_ARGUMENT, \"makeAuthCredentialsProvider failed due to invalid credential type\");\n }\n }(t.credentials));\n }\n _getSettings() {\n return this._settings;\n }\n _freezeSettings() {\n return this._settingsFrozen = !0, this._settings;\n }\n _delete() {\n return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;\n }\n /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */ _terminate() {\n /**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\n return function(t) {\n const e = rc.get(t);\n e && (O(\"ComponentProvider\", \"Removing Datastore\"), rc.delete(t), e.terminate());\n }(this), Promise.resolve();\n }\n}\n\nfunction wc(t, e, n, s = {}) {\n var i;\n const r = (t = lc(t, _c))._getSettings();\n if (\"firestore.googleapis.com\" !== r.host && r.host !== e && $(\"Host has been set in both settings() and useEmulator(), emulator host will be used\"), \n t._setSettings(Object.assign(Object.assign({}, r), {\n host: `${e}:${n}`,\n ssl: !1\n })), s.mockUserToken) {\n let e, n;\n if (\"string\" == typeof s.mockUserToken) e = s.mockUserToken, n = C.MOCK_USER; else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n e = createMockUserToken(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);\n const r = s.mockUserToken.sub || s.mockUserToken.user_id;\n if (!r) throw new Q(G.INVALID_ARGUMENT, \"mockUserToken must contain 'sub' or 'user_id' field!\");\n n = new C(r);\n }\n t._authCredentials = new H(new W(e, n));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */ class mc {\n /** @hideconstructor */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._key = n, \n /** The type of this Firestore reference. */\n this.type = \"document\", this.firestore = t;\n }\n get _path() {\n return this._key.path;\n }\n /**\n * The document's identifier within its collection.\n */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */ get path() {\n return this._key.path.canonicalString();\n }\n /**\n * The collection this `DocumentReference` belongs to.\n */ get parent() {\n return new yc(this.firestore, this.converter, this._key.path.popLast());\n }\n withConverter(t) {\n return new mc(this.firestore, t, this._key);\n }\n}\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */ class gc {\n // This is the lite version of the Query class in the main SDK.\n /** @hideconstructor protected */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._query = n, \n /** The type of this Firestore reference. */\n this.type = \"query\", this.firestore = t;\n }\n withConverter(t) {\n return new gc(this.firestore, t, this._query);\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link query}).\n */ class yc extends gc {\n /** @hideconstructor */\n constructor(t, e, n) {\n super(t, e, Fe(n)), this._path = n, \n /** The type of this Firestore reference. */\n this.type = \"collection\";\n }\n /** The collection's identifier. */ get id() {\n return this._query.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */ get path() {\n return this._query.path.canonicalString();\n }\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */ get parent() {\n const t = this._path.popLast();\n return t.isEmpty() ? null : new mc(this.firestore, \n /* converter= */ null, new xt(t));\n }\n withConverter(t) {\n return new yc(this.firestore, t, this._path);\n }\n}\n\nfunction pc(t, e, ...n) {\n if (t = getModularInstance(t), oc(\"collection\", \"path\", e), t instanceof _c) {\n const s = _t.fromString(e, ...n);\n return cc(s), new yc(t, /* converter= */ null, s);\n }\n {\n if (!(t instanceof mc || t instanceof yc)) throw new Q(G.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(_t.fromString(e, ...n));\n return cc(s), new yc(t.firestore, \n /* converter= */ null, s);\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */ function Ic(t, e) {\n if (t = lc(t, _c), oc(\"collectionGroup\", \"collection id\", e), e.indexOf(\"/\") >= 0) throw new Q(G.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);\n return new gc(t, \n /* converter= */ null, \n /**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\n function(t) {\n return new Me(_t.emptyPath(), t);\n }(e));\n}\n\nfunction Tc(t, e, ...n) {\n if (t = getModularInstance(t), \n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n 1 === arguments.length && (e = it.R()), oc(\"doc\", \"path\", e), t instanceof _c) {\n const s = _t.fromString(e, ...n);\n return ac(s), new mc(t, \n /* converter= */ null, new xt(s));\n }\n {\n if (!(t instanceof mc || t instanceof yc)) throw new Q(G.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(_t.fromString(e, ...n));\n return ac(s), new mc(t.firestore, t instanceof yc ? t.converter : null, new xt(s));\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function Ec(t, e) {\n return t = getModularInstance(t), e = getModularInstance(e), (t instanceof mc || t instanceof yc) && (e instanceof mc || e instanceof yc) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function Ac(t, e) {\n return t = getModularInstance(t), e = getModularInstance(e), t instanceof gc && e instanceof gc && (t.firestore === e.firestore && je(t._query, e._query) && t.converter === e.converter);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Rc {\n constructor() {\n // The last promise in the queue.\n this.ka = Promise.resolve(), \n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n this.Ma = [], \n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n this.Oa = !1, \n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.Fa = [], \n // visible for testing\n this.$a = null, \n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.Ba = !1, \n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n this.La = !1, \n // List of TimerIds to fast-forward delays for.\n this.Ua = [], \n // Backoff timer used to schedule retries for retryable operations\n this.Do = new zo(this, \"async_queue_retry\" /* AsyncQueueRetry */), \n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n this.qa = () => {\n const t = jo();\n t && O(\"AsyncQueue\", \"Visibility state changed to \" + t.visibilityState), this.Do.Ao();\n };\n const t = jo();\n t && \"function\" == typeof t.addEventListener && t.addEventListener(\"visibilitychange\", this.qa);\n }\n get isShuttingDown() {\n return this.Oa;\n }\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */ enqueueAndForget(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(t);\n }\n enqueueAndForgetEvenWhileRestricted(t) {\n this.Ka(), \n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.Ga(t);\n }\n enterRestrictedMode(t) {\n if (!this.Oa) {\n this.Oa = !0, this.La = t || !1;\n const e = jo();\n e && \"function\" == typeof e.removeEventListener && e.removeEventListener(\"visibilitychange\", this.qa);\n }\n }\n enqueue(t) {\n if (this.Ka(), this.Oa) \n // Return a Promise which never resolves.\n return new Promise((() => {}));\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const e = new j;\n return this.Ga((() => this.Oa && this.La ? Promise.resolve() : (t().then(e.resolve, e.reject), \n e.promise))).then((() => e.promise));\n }\n enqueueRetryable(t) {\n this.enqueueAndForget((() => (this.Ma.push(t), this.Qa())));\n }\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */ async Qa() {\n if (0 !== this.Ma.length) {\n try {\n await this.Ma[0](), this.Ma.shift(), this.Do.reset();\n } catch (t) {\n if (!Ri(t)) throw t;\n // Failure will be handled by AsyncQueue\n O(\"AsyncQueue\", \"Operation failed with retryable error: \" + t);\n }\n this.Ma.length > 0 && \n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.Do.To((() => this.Qa()));\n }\n }\n Ga(t) {\n const e = this.ka.then((() => (this.Ba = !0, t().catch((t => {\n this.$a = t, this.Ba = !1;\n const e = \n /**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\n function(t) {\n let e = t.message || \"\";\n t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + \"\\n\" + t.stack);\n return e;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t);\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw F(\"INTERNAL UNHANDLED ERROR: \", e), t;\n })).then((t => (this.Ba = !1, t))))));\n return this.ka = e, e;\n }\n enqueueAfterDelay(t, e, n) {\n this.Ka(), \n // Fast-forward delays for timerIds that have been overriden.\n this.Ua.indexOf(t) > -1 && (e = 0);\n const s = Su.createAndSchedule(this, t, e, n, (t => this.ja(t)));\n return this.Fa.push(s), s;\n }\n Ka() {\n this.$a && L();\n }\n verifyOperationInProgress() {}\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */ async Wa() {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let t;\n do {\n t = this.ka, await t;\n } while (t !== this.ka);\n }\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */ za(t) {\n for (const e of this.Fa) if (e.timerId === t) return !0;\n return !1;\n }\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */ Ha(t) {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.Wa().then((() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.Fa.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));\n for (const e of this.Fa) if (e.skipDelay(), \"all\" /* All */ !== t && e.timerId === t) break;\n return this.Wa();\n }));\n }\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */ Ja(t) {\n this.Ua.push(t);\n }\n /** Called once a DelayedOperation is run or canceled. */ ja(t) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const e = this.Fa.indexOf(t);\n this.Fa.splice(e, 1);\n }\n}\n\nfunction Pc(t) {\n /**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\n return function(t, e) {\n if (\"object\" != typeof t || null === t) return !1;\n const n = t;\n for (const t of e) if (t in n && \"function\" == typeof n[t]) return !0;\n return !1;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */ (t, [ \"next\", \"error\", \"complete\" ]);\n}\n\nclass bc {\n constructor() {\n this._progressObserver = {}, this._taskCompletionResolver = new j, this._lastProgress = {\n taskState: \"Running\",\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n }\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */ onProgress(t, e, n) {\n this._progressObserver = {\n next: t,\n error: e,\n complete: n\n };\n }\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */ catch(t) {\n return this._taskCompletionResolver.promise.catch(t);\n }\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */ then(t, e) {\n return this._taskCompletionResolver.promise.then(t, e);\n }\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */ _completeWith(t) {\n this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(), \n this._taskCompletionResolver.resolve(t);\n }\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */ _failWith(t) {\n this._lastProgress.taskState = \"Error\", this._progressObserver.next && this._progressObserver.next(this._lastProgress), \n this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);\n }\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */ _updateProgress(t) {\n this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** DOMException error code constants. */ const Vc = -1;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link getFirestore}.\n */\nclass vc extends _c {\n /** @hideconstructor */\n constructor(t, e, n) {\n super(t, e, n), \n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n this.type = \"firestore\", this._queue = new Rc, this._persistenceKey = \"name\" in t ? t.name : \"[DEFAULT]\";\n }\n _terminate() {\n return this._firestoreClient || \n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n xc(this), this._firestoreClient.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link getFirestore}. If the custom settings are empty, this function is\n * equivalent to calling {@link getFirestore}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @returns A newly initialized {@link Firestore} instance.\n */ function Sc(t, e) {\n const n = _getProvider(t, \"firestore\");\n if (n.isInitialized()) {\n const t = n.getImmediate(), s = n.getOptions();\n if (deepEqual(s, e)) return t;\n throw new Q(G.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.\");\n }\n if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new Q(G.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n return n.initialize({\n options: e\n });\n}\n\n/**\n * Returns the existing {@link Firestore} instance that is associated with the\n * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new\n * instance with default settings.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore}\n * instance is associated with.\n * @returns The {@link Firestore} instance of the provided app.\n */ function Dc(e = getApp()) {\n return _getProvider(e, \"firestore\").getImmediate();\n}\n\n/**\n * @internal\n */ function Cc(t) {\n return t._firestoreClient || xc(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;\n}\n\nfunction xc(t) {\n var e;\n const n = t._freezeSettings(), s = function(t, e, n, s) {\n return new Vt(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, s.useFetchStreams);\n }(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || \"\", t._persistenceKey, n);\n t._firestoreClient = new Ba(t._authCredentials, t._appCheckCredentials, t._queue, s);\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * Must be called before any other functions (other than\n * {@link initializeFirestore}, {@link getFirestore} or\n * {@link clearIndexedDbPersistence}.\n *\n * If this fails, `enableIndexedDbPersistence()` will reject the promise it\n * returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n */ function Nc(t, e) {\n Kc(t = lc(t, vc));\n const n = Cc(t), s = t._freezeSettings(), i = new Na;\n return Mc(n, i, new Ca(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise\n * it returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n */ function kc(t) {\n Kc(t = lc(t, vc));\n const e = Cc(t), n = t._freezeSettings(), s = new Na;\n return Mc(e, s, new xa(s, n.cacheSizeBytes));\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */ function Mc(t, e, n) {\n const s = new j;\n return t.asyncQueue.enqueue((async () => {\n try {\n await La(t, n), await Ua(t, e), s.resolve();\n } catch (t) {\n if (!\n /**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\n function(t) {\n if (\"FirebaseError\" === t.name) return t.code === G.FAILED_PRECONDITION || t.code === G.UNIMPLEMENTED;\n if (\"undefined\" != typeof DOMException && t instanceof DOMException) \n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n return 22 === t.code || 20 === t.code || \n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n 11 === t.code;\n return !0;\n }\n /**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link getFirestore})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */ (t)) throw t;\n console.warn(\"Error enabling offline persistence. Falling back to persistence disabled: \" + t), \n s.reject(t);\n }\n })).then((() => s.promise));\n}\n\nfunction Oc(t) {\n if (t._initialized && !t._terminated) throw new Q(G.FAILED_PRECONDITION, \"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.\");\n const e = new j;\n return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n await async function(t) {\n if (!Ti.vt()) return Promise.resolve();\n const e = t + \"main\";\n await Ti.delete(e);\n }(Xr(t._databaseId, t._persistenceKey)), e.resolve();\n } catch (t) {\n e.reject(t);\n }\n })), e.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */ function Fc(t) {\n return function(t) {\n const e = new j;\n return t.asyncQueue.enqueueAndForget((async () => ua(await Wa(t), e))), e.promise;\n }(Cc(t = lc(t, vc)));\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */ function $c(t) {\n return Ha(Cc(t = lc(t, vc)));\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */ function Bc(t) {\n return Ja(Cc(t = lc(t, vc)));\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link getFirestore}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */ function Lc(t) {\n return _removeServiceInstance(t.app, \"firestore\"), t._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise`.\n */ function Uc(t, e) {\n const n = Cc(t = lc(t, vc)), s = new bc;\n return sc(n, t._databaseId, e, s), s;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */ function qc(t, e) {\n return ic(Cc(t = lc(t, vc)), e).then((e => e ? new gc(t, null, e.query) : null));\n}\n\nfunction Kc(t) {\n if (t._initialized || t._terminated) throw new Q(G.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.\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */\nclass Gc {\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...t) {\n for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new Q(G.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). Field names must not be empty.\");\n this._internalPath = new mt(t);\n }\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */ isEqual(t) {\n return this._internalPath.isEqual(t._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */ function Qc() {\n return new Gc(\"__name__\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing an array of bytes.\n */ class jc {\n /** @hideconstructor */\n constructor(t) {\n this._byteString = t;\n }\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */ static fromBase64String(t) {\n try {\n return new jc(pt.fromBase64String(t));\n } catch (t) {\n throw new Q(G.INVALID_ARGUMENT, \"Failed to construct data from Base64 string: \" + t);\n }\n }\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */ static fromUint8Array(t) {\n return new jc(pt.fromUint8Array(t));\n }\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */ toBase64() {\n return this._byteString.toBase64();\n }\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */ toUint8Array() {\n return this._byteString.toUint8Array();\n }\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */ toString() {\n return \"Bytes(base64: \" + this.toBase64() + \")\";\n }\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */ isEqual(t) {\n return this._byteString.isEqual(t._byteString);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */ class Wc {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(t) {\n this._methodName = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */ class zc {\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(t, e) {\n if (!isFinite(t) || t < -90 || t > 90) throw new Q(G.INVALID_ARGUMENT, \"Latitude must be a number between -90 and 90, but was: \" + t);\n if (!isFinite(e) || e < -180 || e > 180) throw new Q(G.INVALID_ARGUMENT, \"Longitude must be a number between -180 and 180, but was: \" + e);\n this._lat = t, this._long = e;\n }\n /**\n * The latitude of this `GeoPoint` instance.\n */ get latitude() {\n return this._lat;\n }\n /**\n * The longitude of this `GeoPoint` instance.\n */ get longitude() {\n return this._long;\n }\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */ isEqual(t) {\n return this._lat === t._lat && this._long === t._long;\n }\n /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */ _compareTo(t) {\n return rt(this._lat, t._lat) || rt(this._long, t._long);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Hc = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */ class Jc {\n constructor(t, e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return null !== this.fieldMask ? new Vn(t, this.data, this.fieldMask, e, this.fieldTransforms) : new bn(t, this.data, e, this.fieldTransforms);\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */ class Yc {\n constructor(t, \n // The fieldMask does not include document transforms.\n e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return new Vn(t, this.data, this.fieldMask, e, this.fieldTransforms);\n }\n}\n\nfunction Xc(t) {\n switch (t) {\n case 0 /* Set */ :\n // fall through\n case 2 /* MergeSet */ :\n // fall through\n case 1 /* Update */ :\n return !0;\n\n case 3 /* Argument */ :\n case 4 /* ArrayArgument */ :\n return !1;\n\n default:\n throw L();\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */ class Zc {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(t, e, n, s, i, r) {\n this.settings = t, this.databaseId = e, this.M = n, this.ignoreUndefinedProperties = s, \n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n void 0 === i && this.Ya(), this.fieldTransforms = i || [], this.fieldMask = r || [];\n }\n get path() {\n return this.settings.path;\n }\n get Xa() {\n return this.settings.Xa;\n }\n /** Returns a new context with the specified settings overwritten. */ Za(t) {\n return new Zc(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.M, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);\n }\n tc(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.Za({\n path: n,\n ec: !1\n });\n return s.nc(t), s;\n }\n sc(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.Za({\n path: n,\n ec: !1\n });\n return s.Ya(), s;\n }\n ic(t) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.Za({\n path: void 0,\n ec: !0\n });\n }\n rc(t) {\n return ph(t, this.settings.methodName, this.settings.oc || !1, this.path, this.settings.uc);\n }\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {\n return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));\n }\n Ya() {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path) for (let t = 0; t < this.path.length; t++) this.nc(this.path.get(t));\n }\n nc(t) {\n if (0 === t.length) throw this.rc(\"Document fields must not be empty\");\n if (Xc(this.Xa) && Hc.test(t)) throw this.rc('Document fields cannot begin and end with \"__\"');\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */ class th {\n constructor(t, e, n) {\n this.databaseId = t, this.ignoreUndefinedProperties = e, this.M = n || Wo(t);\n }\n /** Creates a new top-level parse context. */ ac(t, e, n, s = !1) {\n return new Zc({\n Xa: t,\n methodName: e,\n uc: n,\n path: mt.emptyPath(),\n ec: !1,\n oc: s\n }, this.databaseId, this.M, this.ignoreUndefinedProperties);\n }\n}\n\nfunction eh(t) {\n const e = t._freezeSettings(), n = Wo(t._databaseId);\n return new th(t._databaseId, !!e.ignoreUndefinedProperties, n);\n}\n\n/** Parse document data from a set() call. */ function nh(t, e, n, s, i, r = {}) {\n const o = t.ac(r.merge || r.mergeFields ? 2 /* MergeSet */ : 0 /* Set */ , e, n, i);\n wh(\"Data must be an object, but it was:\", o, s);\n const u = dh(s, o);\n let a, c;\n if (r.merge) a = new gt(o.fieldMask), c = o.fieldTransforms; else if (r.mergeFields) {\n const t = [];\n for (const s of r.mergeFields) {\n const i = mh(e, s, n);\n if (!o.contains(i)) throw new Q(G.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);\n Ih(t, i) || t.push(i);\n }\n a = new gt(t), c = o.fieldTransforms.filter((t => a.covers(t.field)));\n } else a = null, c = o.fieldTransforms;\n return new Jc(new te(u), a, c);\n}\n\nclass sh extends Wc {\n _toFieldTransform(t) {\n if (2 /* MergeSet */ !== t.Xa) throw 1 /* Update */ === t.Xa ? t.rc(`${this._methodName}() can only appear at the top level of your update data`) : t.rc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n return t.fieldMask.push(t.path), null;\n }\n isEqual(t) {\n return t instanceof sh;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */ function ih(t, e, n) {\n return new Zc({\n Xa: 3 /* Argument */ ,\n uc: e.settings.uc,\n methodName: t._methodName,\n ec: n\n }, e.databaseId, e.M, e.ignoreUndefinedProperties);\n}\n\nclass rh extends Wc {\n _toFieldTransform(t) {\n return new wn(t.path, new un);\n }\n isEqual(t) {\n return t instanceof rh;\n }\n}\n\nclass oh extends Wc {\n constructor(t, e) {\n super(t), this.cc = e;\n }\n _toFieldTransform(t) {\n const e = ih(this, t, \n /*array=*/ !0), n = this.cc.map((t => fh(t, e))), s = new an(n);\n return new wn(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass uh extends Wc {\n constructor(t, e) {\n super(t), this.cc = e;\n }\n _toFieldTransform(t) {\n const e = ih(this, t, \n /*array=*/ !0), n = this.cc.map((t => fh(t, e))), s = new hn(n);\n return new wn(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass ah extends Wc {\n constructor(t, e) {\n super(t), this.hc = e;\n }\n _toFieldTransform(t) {\n const e = new fn(t.M, en(t.M, this.hc));\n return new wn(t.path, e);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\n/** Parse update data from an update() call. */ function ch(t, e, n, s) {\n const i = t.ac(1 /* Update */ , e, n);\n wh(\"Data must be an object, but it was:\", i, s);\n const r = [], o = te.empty();\n lt(s, ((t, s) => {\n const u = yh(e, t, n);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n s = getModularInstance(s);\n const a = i.sc(u);\n if (s instanceof sh) \n // Add it to the field mask, but don't add anything to updateData.\n r.push(u); else {\n const t = fh(s, a);\n null != t && (r.push(u), o.set(u, t));\n }\n }));\n const u = new gt(r);\n return new Yc(o, u, i.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */ function hh(t, e, n, s, i, r) {\n const o = t.ac(1 /* Update */ , e, n), u = [ mh(e, s, n) ], a = [ i ];\n if (r.length % 2 != 0) throw new Q(G.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);\n for (let t = 0; t < r.length; t += 2) u.push(mh(e, r[t])), a.push(r[t + 1]);\n const c = [], h = te.empty();\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let t = u.length - 1; t >= 0; --t) if (!Ih(c, u[t])) {\n const e = u[t];\n let n = a[t];\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n n = getModularInstance(n);\n const s = o.sc(e);\n if (n instanceof sh) \n // Add it to the field mask, but don't add anything to updateData.\n c.push(e); else {\n const t = fh(n, s);\n null != t && (c.push(e), h.set(e, t));\n }\n }\n const l = new gt(c);\n return new Yc(h, l, o.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */ function lh(t, e, n, s = !1) {\n return fh(n, t.ac(s ? 4 /* ArrayArgument */ : 3 /* Argument */ , e));\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */ function fh(t, e) {\n if (_h(\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n t = getModularInstance(t))) return wh(\"Unsupported field value:\", e, t), dh(t, e);\n if (t instanceof Wc) \n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n return function(t, e) {\n // Sentinels are only supported with writes, and not within arrays.\n if (!Xc(e.Xa)) throw e.rc(`${t._methodName}() can only be used with update() and set()`);\n if (!e.path) throw e.rc(`${t._methodName}() is not currently supported inside arrays`);\n const n = t._toFieldTransform(e);\n n && e.fieldTransforms.push(n);\n }\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */ (t, e), null;\n if (void 0 === t && e.ignoreUndefinedProperties) \n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n if (\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n e.path && e.fieldMask.push(e.path), t instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (e.settings.ec && 4 /* ArrayArgument */ !== e.Xa) throw e.rc(\"Nested arrays are not supported\");\n return function(t, e) {\n const n = [];\n let s = 0;\n for (const i of t) {\n let t = fh(i, e.ic(s));\n null == t && (\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n t = {\n nullValue: \"NULL_VALUE\"\n }), n.push(t), s++;\n }\n return {\n arrayValue: {\n values: n\n }\n };\n }(t, e);\n }\n return function(t, e) {\n if (null === (t = getModularInstance(t))) return {\n nullValue: \"NULL_VALUE\"\n };\n if (\"number\" == typeof t) return en(e.M, t);\n if (\"boolean\" == typeof t) return {\n booleanValue: t\n };\n if (\"string\" == typeof t) return {\n stringValue: t\n };\n if (t instanceof Date) {\n const n = at.fromDate(t);\n return {\n timestampValue: ds(e.M, n)\n };\n }\n if (t instanceof at) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const n = new at(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));\n return {\n timestampValue: ds(e.M, n)\n };\n }\n if (t instanceof zc) return {\n geoPointValue: {\n latitude: t.latitude,\n longitude: t.longitude\n }\n };\n if (t instanceof jc) return {\n bytesValue: _s(e.M, t._byteString)\n };\n if (t instanceof mc) {\n const n = e.databaseId, s = t.firestore._databaseId;\n if (!s.isEqual(n)) throw e.rc(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);\n return {\n referenceValue: gs(t.firestore._databaseId || e.databaseId, t._key.path)\n };\n }\n throw e.rc(`Unsupported field value: ${hc(t)}`);\n }\n /**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */ (t, e);\n}\n\nfunction dh(t, e) {\n const n = {};\n return ft(t) ? \n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n e.path && e.path.length > 0 && e.fieldMask.push(e.path) : lt(t, ((t, s) => {\n const i = fh(s, e.tc(t));\n null != i && (n[t] = i);\n })), {\n mapValue: {\n fields: n\n }\n };\n}\n\nfunction _h(t) {\n return !(\"object\" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof at || t instanceof zc || t instanceof jc || t instanceof mc || t instanceof Wc);\n}\n\nfunction wh(t, e, n) {\n if (!_h(n) || !function(t) {\n return \"object\" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));\n }(n)) {\n const s = hc(n);\n throw \"an object\" === s ? e.rc(t + \" a custom object\") : e.rc(t + \" \" + s);\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */ function mh(t, e, n) {\n if ((\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n e = getModularInstance(e)) instanceof Gc) return e._internalPath;\n if (\"string\" == typeof e) return yh(t, e);\n throw ph(\"Field path arguments must be of type string or \", t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */ const gh = new RegExp(\"[~\\\\*/\\\\[\\\\]]\");\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */ function yh(t, e, n) {\n if (e.search(gh) >= 0) throw ph(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n try {\n return new Gc(...e.split(\".\"))._internalPath;\n } catch (s) {\n throw ph(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n }\n}\n\nfunction ph(t, e, n, s, i) {\n const r = s && !s.isEmpty(), o = void 0 !== i;\n let u = `Function ${e}() called with invalid data`;\n n && (u += \" (via `toFirestore()`)\"), u += \". \";\n let a = \"\";\n return (r || o) && (a += \" (found\", r && (a += ` in field ${s}`), o && (a += ` in document ${i}`), \n a += \")\"), new Q(G.INVALID_ARGUMENT, u + t + a);\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Ih(t, e) {\n return t.some((t => t.isEqual(e)));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class Th {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n /** @hideconstructor protected */\n constructor(t, e, n, s, i) {\n this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s, \n this._converter = i;\n }\n /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */ get ref() {\n return new mc(this._firestore, this._converter, this._key);\n }\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */ exists() {\n return null !== this._document;\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */ data() {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const t = new Eh(this._firestore, this._userDataWriter, this._key, this._document, \n /* converter= */ null);\n return this._converter.fromFirestore(t);\n }\n return this._userDataWriter.convertValue(this._document.data.value);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t) {\n if (this._document) {\n const e = this._document.data.field(Ah(\"DocumentSnapshot.get\", t));\n if (null !== e) return this._userDataWriter.convertValue(e);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class Eh extends Th {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data() {\n return super.data();\n }\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */ function Ah(t, e) {\n return \"string\" == typeof e ? yh(t, e) : e instanceof Gc ? e._internalPath : e._delegate._internalPath;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */ class Rh {\n /** @hideconstructor */\n constructor(t, e) {\n this.hasPendingWrites = t, this.fromCache = e;\n }\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */ isEqual(t) {\n return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;\n }\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get()` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class Ph extends Th {\n /** @hideconstructor protected */\n constructor(t, e, n, s, i, r) {\n super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;\n }\n /**\n * Returns whether or not the data exists. True if the document exists.\n */ exists() {\n return super.exists();\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */ data(t = {}) {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const e = new bh(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, \n /* converter= */ null);\n return this._converter.fromFirestore(e, t);\n }\n return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t, e = {}) {\n if (this._document) {\n const n = this._document.data.field(Ah(\"DocumentSnapshot.get\", t));\n if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get()` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class bh extends Ph {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(t = {}) {\n return super.data(t);\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */ class Vh {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new Rh(s.hasPendingWrites, s.fromCache), \n this.query = n;\n }\n /** An array of all the documents in the `QuerySnapshot`. */ get docs() {\n const t = [];\n return this.forEach((e => t.push(e))), t;\n }\n /** The number of documents in the `QuerySnapshot`. */ get size() {\n return this._snapshot.docs.size;\n }\n /** True if there are no documents in the `QuerySnapshot`. */ get empty() {\n return 0 === this.size;\n }\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */ forEach(t, e) {\n this._snapshot.docs.forEach((n => {\n t.call(e, new bh(this._firestore, this._userDataWriter, n.key, n, new Rh(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));\n }));\n }\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */ docChanges(t = {}) {\n const e = !!t.includeMetadataChanges;\n if (e && this._snapshot.excludesMetadataChanges) throw new Q(G.INVALID_ARGUMENT, \"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().\");\n return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges = \n /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\n function(t, e) {\n if (t._snapshot.oldDocs.isEmpty()) {\n let e = 0;\n return t._snapshot.docChanges.map((n => ({\n type: \"added\",\n doc: new bh(t._firestore, t._userDataWriter, n.doc.key, n.doc, new Rh(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter),\n oldIndex: -1,\n newIndex: e++\n })));\n }\n {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let n = t._snapshot.oldDocs;\n return t._snapshot.docChanges.filter((t => e || 3 /* Metadata */ !== t.type)).map((e => {\n const s = new bh(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Rh(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);\n let i = -1, r = -1;\n return 0 /* Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), \n 1 /* Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)), {\n type: vh(e.type),\n doc: s,\n oldIndex: i,\n newIndex: r\n };\n }));\n }\n }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;\n }\n}\n\nfunction vh(t) {\n switch (t) {\n case 0 /* Added */ :\n return \"added\";\n\n case 2 /* Modified */ :\n case 3 /* Metadata */ :\n return \"modified\";\n\n case 1 /* Removed */ :\n return \"removed\";\n\n default:\n return L();\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */ function Sh(t, e) {\n return t instanceof Ph && e instanceof Ph ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof Vh && e instanceof Vh && (t._firestore === e._firestore && Ac(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function Dh(t) {\n if (Be(t) && 0 === t.explicitOrderBy.length) throw new Q(G.UNIMPLEMENTED, \"limitToLast() queries require specifying at least one orderBy() clause\");\n}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link\n * endBefore:1}, {@link (endAt:1)}, {@link limit} or {@link limitToLast} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */ class Ch {}\n\n/**\n * Creates a new immutable instance of {@link Query} that is extended to also include\n * additional query constraints.\n *\n * @param query - The {@link Query} instance to use as a base for the new constraints.\n * @param queryConstraints - The list of {@link QueryConstraint}s to apply.\n * @throws if any of the provided query constraints cannot be combined with the\n * existing or new constraints.\n */ function xh(t, ...e) {\n for (const n of e) t = n._apply(t);\n return t;\n}\n\nclass Nh extends Ch {\n constructor(t, e, n) {\n super(), this.lc = t, this.fc = e, this.dc = n, this.type = \"where\";\n }\n _apply(t) {\n const e = eh(t.firestore), n = function(t, e, n, s, i, r, o) {\n let u;\n if (i.isKeyField()) {\n if (\"array-contains\" /* ARRAY_CONTAINS */ === r || \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ === r) throw new Q(G.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);\n if (\"in\" /* IN */ === r || \"not-in\" /* NOT_IN */ === r) {\n zh(o, r);\n const e = [];\n for (const n of o) e.push(Wh(s, t, n));\n u = {\n arrayValue: {\n values: e\n }\n };\n } else u = Wh(s, t, o);\n } else \"in\" /* IN */ !== r && \"not-in\" /* NOT_IN */ !== r && \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ !== r || zh(o, r), \n u = lh(n, e, o, \n /* allowArrays= */ \"in\" /* IN */ === r || \"not-in\" /* NOT_IN */ === r);\n const a = Te.create(i, r, u);\n return function(t, e) {\n if (e.S()) {\n const n = Ue(t);\n if (null !== n && !n.isEqual(e.field)) throw new Q(G.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${e.field.toString()}'`);\n const s = Le(t);\n null !== s && Hh(t, e.field, s);\n }\n const n = function(t, e) {\n for (const n of t.filters) if (e.indexOf(n.op) >= 0) return n.op;\n return null;\n }(t, \n /**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one array operator is allowed.\n * 2. Only one disjunctive operator is allowed.\n * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.\n * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n *\n * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`\n * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`\n */\n function(t) {\n switch (t) {\n case \"!=\" /* NOT_EQUAL */ :\n return [ \"!=\" /* NOT_EQUAL */ , \"not-in\" /* NOT_IN */ ];\n\n case \"array-contains\" /* ARRAY_CONTAINS */ :\n return [ \"array-contains\" /* ARRAY_CONTAINS */ , \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ , \"not-in\" /* NOT_IN */ ];\n\n case \"in\" /* IN */ :\n return [ \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ , \"in\" /* IN */ , \"not-in\" /* NOT_IN */ ];\n\n case \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ :\n return [ \"array-contains\" /* ARRAY_CONTAINS */ , \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ , \"in\" /* IN */ , \"not-in\" /* NOT_IN */ ];\n\n case \"not-in\" /* NOT_IN */ :\n return [ \"array-contains\" /* ARRAY_CONTAINS */ , \"array-contains-any\" /* ARRAY_CONTAINS_ANY */ , \"in\" /* IN */ , \"not-in\" /* NOT_IN */ , \"!=\" /* NOT_EQUAL */ ];\n\n default:\n return [];\n }\n }(e.op));\n if (null !== n) \n // Special case when it's a duplicate op to give a slightly clearer error message.\n throw n === e.op ? new Q(G.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new Q(G.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);\n }(t, a), a;\n }(t._query, \"where\", e, t.firestore._databaseId, this.lc, this.fc, this.dc);\n return new gc(t.firestore, t.converter, function(t, e) {\n const n = t.filters.concat([ e ]);\n return new Me(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);\n }(t._query, n));\n }\n}\n\n/**\n * Creates a {@link QueryConstraint} that enforces that documents must contain the\n * specified field and that the value should satisfy the relation constraint\n * provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"<\", \"<=\", \"==\", \"<\",\n * \"<=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link Query}.\n */ function kh(t, e, n) {\n const s = e, i = Ah(\"where\", t);\n return new Nh(i, s, n);\n}\n\nclass Mh extends Ch {\n constructor(t, e) {\n super(), this.lc = t, this._c = e, this.type = \"orderBy\";\n }\n _apply(t) {\n const e = function(t, e, n) {\n if (null !== t.startAt) throw new Q(G.INVALID_ARGUMENT, \"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");\n if (null !== t.endAt) throw new Q(G.INVALID_ARGUMENT, \"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");\n const s = new Ce(e, n);\n return function(t, e) {\n if (null === Le(t)) {\n // This is the first order by. It must match any inequality.\n const n = Ue(t);\n null !== n && Hh(t, n, e.field);\n }\n }(t, s), s;\n }\n /**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ (t._query, this.lc, this._c);\n return new gc(t.firestore, t.converter, function(t, e) {\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const n = t.explicitOrderBy.concat([ e ]);\n return new Me(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }(t._query, e));\n }\n}\n\n/**\n * Creates a {@link QueryConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link Query}.\n */ function Oh(t, e = \"asc\") {\n const n = e, s = Ah(\"orderBy\", t);\n return new Mh(s, n);\n}\n\nclass Fh extends Ch {\n constructor(t, e, n) {\n super(), this.type = t, this.wc = e, this.mc = n;\n }\n _apply(t) {\n return new gc(t.firestore, t.converter, Qe(t._query, this.wc, this.mc));\n }\n}\n\n/**\n * Creates a {@link QueryConstraint} that only returns the first matching documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link Query}.\n */ function $h(t) {\n return fc(\"limit\", t), new Fh(\"limit\", t, \"F\" /* First */);\n}\n\n/**\n * Creates a {@link QueryConstraint} that only returns the last matching documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link Query}.\n */ function Bh(t) {\n return fc(\"limitToLast\", t), new Fh(\"limitToLast\", t, \"L\" /* Last */);\n}\n\nclass Lh extends Ch {\n constructor(t, e, n) {\n super(), this.type = t, this.gc = e, this.yc = n;\n }\n _apply(t) {\n const e = jh(t, this.type, this.gc, this.yc);\n return new gc(t.firestore, t.converter, function(t, e) {\n return new Me(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);\n }(t._query, e));\n }\n}\n\nfunction Uh(...t) {\n return new Lh(\"startAt\", t, \n /*inclusive=*/ !0);\n}\n\nfunction qh(...t) {\n return new Lh(\"startAfter\", t, \n /*inclusive=*/ !1);\n}\n\nclass Kh extends Ch {\n constructor(t, e, n) {\n super(), this.type = t, this.gc = e, this.yc = n;\n }\n _apply(t) {\n const e = jh(t, this.type, this.gc, this.yc);\n return new gc(t.firestore, t.converter, function(t, e) {\n return new Me(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);\n }(t._query, e));\n }\n}\n\nfunction Gh(...t) {\n return new Kh(\"endBefore\", t, \n /*inclusive=*/ !1);\n}\n\nfunction Qh(...t) {\n return new Kh(\"endAt\", t, /*inclusive=*/ !0);\n}\n\n/** Helper function to create a bound from a document or fields */ function jh(t, e, n, s) {\n if (n[0] = getModularInstance(n[0]), n[0] instanceof Th) return function(t, e, n, s, i) {\n if (!s) throw new Q(G.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);\n const r = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const n of Ke(t)) if (n.field.isKeyField()) r.push(qt(e, s.key)); else {\n const t = s.data.field(n.field);\n if (Rt(t)) throw new Q(G.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.)');\n if (null === t) {\n const t = n.field.canonicalString();\n throw new Q(G.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);\n }\n r.push(t);\n }\n return new De(r, i);\n }\n /**\n * Converts a list of field values to a `Bound` for the given query.\n */ (t._query, t.firestore._databaseId, e, n[0]._document, s);\n {\n const i = eh(t.firestore);\n return function(t, e, n, s, i, r) {\n // Use explicit order by's because it has to match the query the user made\n const o = t.explicitOrderBy;\n if (i.length > o.length) throw new Q(G.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);\n const u = [];\n for (let r = 0; r < i.length; r++) {\n const a = i[r];\n if (o[r].field.isKeyField()) {\n if (\"string\" != typeof a) throw new Q(G.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof a}`);\n if (!qe(t) && -1 !== a.indexOf(\"/\")) throw new Q(G.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${a}' contains a slash.`);\n const n = t.path.child(_t.fromString(a));\n if (!xt.isDocumentKey(n)) throw new Q(G.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);\n const i = new xt(n);\n u.push(qt(e, i));\n } else {\n const t = lh(n, s, a);\n u.push(t);\n }\n }\n return new De(u, r);\n }\n /**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */ (t._query, t.firestore._databaseId, i, e, n, s);\n }\n}\n\nfunction Wh(t, e, n) {\n if (\"string\" == typeof (n = getModularInstance(n))) {\n if (\"\" === n) throw new Q(G.INVALID_ARGUMENT, \"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.\");\n if (!qe(e) && -1 !== n.indexOf(\"/\")) throw new Q(G.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);\n const s = e.path.child(_t.fromString(n));\n if (!xt.isDocumentKey(s)) throw new Q(G.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);\n return qt(t, new xt(s));\n }\n if (n instanceof mc) return qt(t, n._key);\n throw new Q(G.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${hc(n)}.`);\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */ function zh(t, e) {\n if (!Array.isArray(t) || 0 === t.length) throw new Q(G.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);\n if (t.length > 10) throw new Q(G.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`);\n}\n\nfunction Hh(t, e, n) {\n if (!n.isEqual(e)) throw new Q(G.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */ class Jh {\n convertValue(t, e = \"none\") {\n switch (Mt(t)) {\n case 0 /* NullValue */ :\n return null;\n\n case 1 /* BooleanValue */ :\n return t.booleanValue;\n\n case 2 /* NumberValue */ :\n return Et(t.integerValue || t.doubleValue);\n\n case 3 /* TimestampValue */ :\n return this.convertTimestamp(t.timestampValue);\n\n case 4 /* ServerTimestampValue */ :\n return this.convertServerTimestamp(t, e);\n\n case 5 /* StringValue */ :\n return t.stringValue;\n\n case 6 /* BlobValue */ :\n return this.convertBytes(At(t.bytesValue));\n\n case 7 /* RefValue */ :\n return this.convertReference(t.referenceValue);\n\n case 8 /* GeoPointValue */ :\n return this.convertGeoPoint(t.geoPointValue);\n\n case 9 /* ArrayValue */ :\n return this.convertArray(t.arrayValue, e);\n\n case 10 /* ObjectValue */ :\n return this.convertObject(t.mapValue, e);\n\n default:\n throw L();\n }\n }\n convertObject(t, e) {\n const n = {};\n return lt(t.fields, ((t, s) => {\n n[t] = this.convertValue(s, e);\n })), n;\n }\n convertGeoPoint(t) {\n return new zc(Et(t.latitude), Et(t.longitude));\n }\n convertArray(t, e) {\n return (t.values || []).map((t => this.convertValue(t, e)));\n }\n convertServerTimestamp(t, e) {\n switch (e) {\n case \"previous\":\n const n = Pt(t);\n return null == n ? null : this.convertValue(n, e);\n\n case \"estimate\":\n return this.convertTimestamp(bt(t));\n\n default:\n return null;\n }\n }\n convertTimestamp(t) {\n const e = Tt(t);\n return new at(e.seconds, e.nanos);\n }\n convertDocumentKey(t, e) {\n const n = _t.fromString(t);\n U(Gs(n));\n const s = new vt(n.get(1), n.get(3)), i = new xt(n.popFirst(5));\n return s.isEqual(e) || \n // TODO(b/64130202): Somehow support foreign references.\n F(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), \n i;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */ function Yh(t, e, n) {\n let s;\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e, \n s;\n}\n\nclass Xh extends Jh {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new jc(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new mc(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */ class Zh {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, \n this._dataReader = eh(t);\n }\n set(t, e, n) {\n this._verifyNotCommitted();\n const s = tl(t, this._firestore), i = Yh(s.converter, e, n), r = nh(this._dataReader, \"WriteBatch.set\", s._key, i, null !== s.converter, n);\n return this._mutations.push(r.toMutation(s._key, yn.none())), this;\n }\n update(t, e, n, ...s) {\n this._verifyNotCommitted();\n const i = tl(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = getModularInstance(e)) || e instanceof Gc ? hh(this._dataReader, \"WriteBatch.update\", i._key, e, n, s) : ch(this._dataReader, \"WriteBatch.update\", i._key, e), \n this._mutations.push(r.toMutation(i._key, yn.exists(!0))), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */ delete(t) {\n this._verifyNotCommitted();\n const e = tl(t, this._firestore);\n return this._mutations = this._mutations.concat(new Cn(e._key, yn.none())), this;\n }\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */ commit() {\n return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();\n }\n _verifyNotCommitted() {\n if (this._committed) throw new Q(G.FAILED_PRECONDITION, \"A write batch can no longer be used after commit() has been called.\");\n }\n}\n\nfunction tl(t, e) {\n if ((t = getModularInstance(t)).firestore !== e) throw new Q(G.INVALID_ARGUMENT, \"Provided document reference is from a different Firestore instance.\");\n return t;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */\nfunction el(t) {\n t = lc(t, mc);\n const e = lc(t.firestore, vc);\n return Xa(Cc(e), t._key).then((n => wl(e, t, n)));\n}\n\nclass nl extends Jh {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new jc(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new mc(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function sl(t) {\n t = lc(t, mc);\n const e = lc(t.firestore, vc), n = Cc(e), s = new nl(e);\n return Ya(n, t._key).then((n => new Ph(e, s, t._key, n, new Rh(null !== n && n.hasLocalMutations, \n /* fromCache= */ !0), t.converter)));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function il(t) {\n t = lc(t, mc);\n const e = lc(t.firestore, vc);\n return Xa(Cc(e), t._key, {\n source: \"server\"\n }).then((n => wl(e, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function rl(t) {\n t = lc(t, gc);\n const e = lc(t.firestore, vc), n = Cc(e), s = new nl(e);\n return Dh(t._query), tc(n, t._query).then((n => new Vh(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function ol(t) {\n t = lc(t, gc);\n const e = lc(t.firestore, vc), n = Cc(e), s = new nl(e);\n return Za(n, t._query).then((n => new Vh(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function ul(t) {\n t = lc(t, gc);\n const e = lc(t.firestore, vc), n = Cc(e), s = new nl(e);\n return tc(n, t._query, {\n source: \"server\"\n }).then((n => new Vh(e, s, t, n)));\n}\n\nfunction al(t, e, n) {\n t = lc(t, mc);\n const s = lc(t.firestore, vc), i = Yh(t.converter, e, n);\n return _l(s, [ nh(eh(s), \"setDoc\", t._key, i, null !== t.converter, n).toMutation(t._key, yn.none()) ]);\n}\n\nfunction cl(t, e, n, ...s) {\n t = lc(t, mc);\n const i = lc(t.firestore, vc), r = eh(i);\n let o;\n o = \"string\" == typeof (\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n e = getModularInstance(e)) || e instanceof Gc ? hh(r, \"updateDoc\", t._key, e, n, s) : ch(r, \"updateDoc\", t._key, e);\n return _l(i, [ o.toMutation(t._key, yn.exists(!0)) ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */ function hl(t) {\n return _l(lc(t.firestore, vc), [ new Cn(t._key, yn.none()) ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */ function ll(t, e) {\n const n = lc(t.firestore, vc), s = Tc(t), i = Yh(t.converter, e);\n return _l(n, [ nh(eh(t.firestore), \"addDoc\", s._key, i, null !== t.converter, {}).toMutation(s._key, yn.exists(!1)) ]).then((() => s));\n}\n\nfunction fl(t, ...e) {\n var n, s, i;\n t = getModularInstance(t);\n let r = {\n includeMetadataChanges: !1\n }, o = 0;\n \"object\" != typeof e[o] || Pc(e[o]) || (r = e[o], o++);\n const u = {\n includeMetadataChanges: r.includeMetadataChanges\n };\n if (Pc(e[o])) {\n const t = e[o];\n e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t), \n e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);\n }\n let a, c, h;\n if (t instanceof mc) c = lc(t.firestore, vc), h = Fe(t._key.path), a = {\n next: n => {\n e[o] && e[o](wl(c, t, n));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }; else {\n const n = lc(t, gc);\n c = lc(n.firestore, vc), h = n._query;\n const s = new nl(c);\n a = {\n next: t => {\n e[o] && e[o](new Vh(c, s, n, t));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }, Dh(t._query);\n }\n return function(t, e, n, s) {\n const i = new Ma(s), r = new Uu(e, i, n);\n return t.asyncQueue.enqueueAndForget((async () => Ou(await za(t), r))), () => {\n i.Ia(), t.asyncQueue.enqueueAndForget((async () => Fu(await za(t), r)));\n };\n }(Cc(c), h, u, a);\n}\n\nfunction dl(t, e) {\n return ec(Cc(t = lc(t, vc)), Pc(e) ? e : {\n next: e\n });\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */ function _l(t, e) {\n return function(t, e) {\n const n = new j;\n return t.asyncQueue.enqueueAndForget((async () => ea(await Wa(t), e, n))), n.promise;\n }(Cc(t), e);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */ function wl(t, e, n) {\n const s = n.docs.get(e._key), i = new nl(t);\n return new Ph(t, i, e._key, s, new Rh(n.hasPendingWrites, n.fromCache), e.converter);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */ class ml extends class {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._transaction = e, this._dataReader = eh(t);\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = tl(t, this._firestore), n = new Xh(this._firestore);\n return this._transaction.lookup([ e._key ]).then((t => {\n if (!t || 1 !== t.length) return L();\n const s = t[0];\n if (s.isFoundDocument()) return new Th(this._firestore, n, s.key, s, e.converter);\n if (s.isNoDocument()) return new Th(this._firestore, n, e._key, null, e.converter);\n throw L();\n }));\n }\n set(t, e, n) {\n const s = tl(t, this._firestore), i = Yh(s.converter, e, n), r = nh(this._dataReader, \"Transaction.set\", s._key, i, null !== s.converter, n);\n return this._transaction.set(s._key, r), this;\n }\n update(t, e, n, ...s) {\n const i = tl(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = getModularInstance(e)) || e instanceof Gc ? hh(this._dataReader, \"Transaction.update\", i._key, e, n, s) : ch(this._dataReader, \"Transaction.update\", i._key, e), \n this._transaction.update(i._key, r), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */ delete(t) {\n const e = tl(t, this._firestore);\n return this._transaction.delete(e._key), this;\n }\n} {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n /** @hideconstructor */\n constructor(t, e) {\n super(t, e), this._firestore = t;\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = tl(t, this._firestore), n = new nl(this._firestore);\n return super.get(t).then((t => new Ph(this._firestore, n, e._key, t._document, new Rh(\n /* hasPendingWrites= */ !1, \n /* fromCache= */ !1), e.converter)));\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */ function gl(t, e) {\n return nc(Cc(t = lc(t, vc)), (n => e(new ml(t, n))));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */ function yl() {\n return new sh(\"deleteField\");\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */ function pl() {\n return new rh(\"serverTimestamp\");\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */ function Il(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new oh(\"arrayUnion\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function Tl(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new uh(\"arrayRemove\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function El(t) {\n return new ah(\"increment\", t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */ function Al(t) {\n return Cc(t = lc(t, vc)), new Zh(t, (e => _l(t, e)));\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function Rl(t, e) {\n Cc(t = lc(t, vc));\n const n = \"string\" == typeof e ? function(t) {\n try {\n return JSON.parse(t);\n } catch (t) {\n throw new Q(G.INVALID_ARGUMENT, \"Failed to parse JSON:\" + t.message);\n }\n }(e) : e, s = [];\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n if (Array.isArray(n.indexes)) for (const t of n.indexes) {\n const e = Pl(t, \"collectionGroup\"), n = [];\n if (Array.isArray(t.fields)) for (const e of t.fields) {\n const t = yh(\"setIndexConfiguration\", Pl(e, \"fieldPath\"));\n \"CONTAINS\" === e.arrayConfig ? n.push(new oe(t, 2 /* CONTAINS */)) : \"ASCENDING\" === e.order ? n.push(new oe(t, 0 /* ASCENDING */)) : \"DESCENDING\" === e.order && n.push(new oe(t, 1 /* DESCENDING */));\n }\n s.push(new se(se.UNKNOWN_ID, e, n, ue.empty()));\n }\n // TODO(indexing): Configure indexes\n return Promise.resolve();\n}\n\nfunction Pl(t, e) {\n if (\"string\" != typeof t[e]) throw new Q(G.INVALID_ARGUMENT, \"Missing string value for: \" + e);\n return t[e];\n}\n\n/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */ !function(t, e = !0) {\n !function(t) {\n x = t;\n }(SDK_VERSION), _registerComponent(new Component(\"firestore\", ((t, {options: n}) => {\n const s = t.getProvider(\"app\").getImmediate(), i = new vc(s, new J(t.getProvider(\"auth-internal\")), new tt(t.getProvider(\"app-check-internal\")));\n return n = Object.assign({\n useFetchStreams: e\n }, n), i._setSettings(n), i;\n }), \"PUBLIC\")), registerVersion(D, \"3.4.8\", t), \n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n registerVersion(D, \"3.4.8\", \"esm2017\");\n}();\n\nexport { Jh as AbstractUserDataWriter, jc as Bytes, Vc as CACHE_SIZE_UNLIMITED, yc as CollectionReference, mc as DocumentReference, Ph as DocumentSnapshot, Gc as FieldPath, Wc as FieldValue, vc as Firestore, Q as FirestoreError, zc as GeoPoint, bc as LoadBundleTask, gc as Query, Ch as QueryConstraint, bh as QueryDocumentSnapshot, Vh as QuerySnapshot, Rh as SnapshotMetadata, at as Timestamp, ml as Transaction, Zh as WriteBatch, vt as _DatabaseId, xt as _DocumentKey, et as _EmptyAppCheckTokenProvider, z as _EmptyAuthCredentialsProvider, mt as _FieldPath, lc as _cast, q as _debugAssert, yt as _isBase64Available, $ as _logWarn, Rl as _setIndexConfiguration, uc as _validateIsNotUsedTogether, ll as addDoc, Tl as arrayRemove, Il as arrayUnion, Oc as clearIndexedDbPersistence, pc as collection, Ic as collectionGroup, wc as connectFirestoreEmulator, hl as deleteDoc, yl as deleteField, Bc as disableNetwork, Tc as doc, Qc as documentId, Nc as enableIndexedDbPersistence, kc as enableMultiTabIndexedDbPersistence, $c as enableNetwork, Qh as endAt, Gh as endBefore, Cc as ensureFirestoreConfigured, _l as executeWrite, el as getDoc, sl as getDocFromCache, il as getDocFromServer, rl as getDocs, ol as getDocsFromCache, ul as getDocsFromServer, Dc as getFirestore, El as increment, Sc as initializeFirestore, $h as limit, Bh as limitToLast, Uc as loadBundle, qc as namedQuery, fl as onSnapshot, dl as onSnapshotsInSync, Oh as orderBy, xh as query, Ac as queryEqual, Ec as refEqual, gl as runTransaction, pl as serverTimestamp, al as setDoc, M as setLogLevel, Sh as snapshotEqual, qh as startAfter, Uh as startAt, Lc as terminate, cl as updateDoc, Fc as waitForPendingWrites, kh as where, Al as writeBatch };\n//# sourceMappingURL=index.esm2017.js.map\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n","import { ErrorFactory, deepEqual, isBrowserExtension, isMobileCordova, isReactNative, FirebaseError, querystring, getModularInstance, base64Decode, getUA, isIE, createSubscribe, querystringDecode, extractQuerystring, isEmpty } from '@firebase/util';\nimport { SDK_VERSION, _getProvider, _registerComponent, registerVersion, getApp } from '@firebase/app';\nimport { __rest } from 'tslib';\nimport { Logger, LogLevel } from '@firebase/logger';\nimport { Component } from '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An enum of factors that may be used for multifactor authentication.\r\n *\r\n * @public\r\n */\r\nconst FactorId = {\r\n /** Phone as second factor */\r\n PHONE: 'phone'\r\n};\r\n/**\r\n * Enumeration of supported providers.\r\n *\r\n * @public\r\n */\r\nconst ProviderId = {\r\n /** Facebook provider ID */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub provider ID */\r\n GITHUB: 'github.com',\r\n /** Google provider ID */\r\n GOOGLE: 'google.com',\r\n /** Password provider */\r\n PASSWORD: 'password',\r\n /** Phone provider */\r\n PHONE: 'phone',\r\n /** Twitter provider ID */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported sign-in methods.\r\n *\r\n * @public\r\n */\r\nconst SignInMethod = {\r\n /** Email link sign in method */\r\n EMAIL_LINK: 'emailLink',\r\n /** Email/password sign in method */\r\n EMAIL_PASSWORD: 'password',\r\n /** Facebook sign in method */\r\n FACEBOOK: 'facebook.com',\r\n /** GitHub sign in method */\r\n GITHUB: 'github.com',\r\n /** Google sign in method */\r\n GOOGLE: 'google.com',\r\n /** Phone sign in method */\r\n PHONE: 'phone',\r\n /** Twitter sign in method */\r\n TWITTER: 'twitter.com'\r\n};\r\n/**\r\n * Enumeration of supported operation types.\r\n *\r\n * @public\r\n */\r\nconst OperationType = {\r\n /** Operation involving linking an additional provider to an already signed-in user. */\r\n LINK: 'link',\r\n /** Operation involving using a provider to reauthenticate an already signed-in user. */\r\n REAUTHENTICATE: 'reauthenticate',\r\n /** Operation involving signing in a user. */\r\n SIGN_IN: 'signIn'\r\n};\r\n/**\r\n * An enumeration of the possible email action types.\r\n *\r\n * @public\r\n */\r\nconst ActionCodeOperation = {\r\n /** The email link sign-in action. */\r\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\r\n /** The password reset action. */\r\n PASSWORD_RESET: 'PASSWORD_RESET',\r\n /** The email revocation action. */\r\n RECOVER_EMAIL: 'RECOVER_EMAIL',\r\n /** The revert second factor addition email action. */\r\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\r\n /** The revert second factor addition email action. */\r\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\r\n /** The email verification action. */\r\n VERIFY_EMAIL: 'VERIFY_EMAIL'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _debugErrorMap() {\r\n return {\r\n [\"admin-restricted-operation\" /* ADMIN_ONLY_OPERATION */]: 'This operation is restricted to administrators only.',\r\n [\"argument-error\" /* ARGUMENT_ERROR */]: '',\r\n [\"app-not-authorized\" /* APP_NOT_AUTHORIZED */]: \"This app, identified by the domain where it's hosted, is not \" +\r\n 'authorized to use Firebase Authentication with the provided API key. ' +\r\n 'Review your key configuration in the Google API console.',\r\n [\"app-not-installed\" /* APP_NOT_INSTALLED */]: 'The requested mobile application corresponding to the identifier (' +\r\n 'Android package name or iOS bundle ID) provided is not installed on ' +\r\n 'this device.',\r\n [\"captcha-check-failed\" /* CAPTCHA_CHECK_FAILED */]: 'The reCAPTCHA response token provided is either invalid, expired, ' +\r\n 'already used or the domain associated with it does not match the list ' +\r\n 'of whitelisted domains.',\r\n [\"code-expired\" /* CODE_EXPIRED */]: 'The SMS code has expired. Please re-send the verification code to try ' +\r\n 'again.',\r\n [\"cordova-not-ready\" /* CORDOVA_NOT_READY */]: 'Cordova framework is not ready.',\r\n [\"cors-unsupported\" /* CORS_UNSUPPORTED */]: 'This browser is not supported.',\r\n [\"credential-already-in-use\" /* CREDENTIAL_ALREADY_IN_USE */]: 'This credential is already associated with a different user account.',\r\n [\"custom-token-mismatch\" /* CREDENTIAL_MISMATCH */]: 'The custom token corresponds to a different audience.',\r\n [\"requires-recent-login\" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: 'This operation is sensitive and requires recent authentication. Log in ' +\r\n 'again before retrying this request.',\r\n [\"dependent-sdk-initialized-before-auth\" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.',\r\n [\"dynamic-link-not-activated\" /* DYNAMIC_LINK_NOT_ACTIVATED */]: 'Please activate Dynamic Links in the Firebase Console and agree to the terms and ' +\r\n 'conditions.',\r\n [\"email-change-needs-verification\" /* EMAIL_CHANGE_NEEDS_VERIFICATION */]: 'Multi-factor users must always have a verified email.',\r\n [\"email-already-in-use\" /* EMAIL_EXISTS */]: 'The email address is already in use by another account.',\r\n [\"emulator-config-failed\" /* EMULATOR_CONFIG_FAILED */]: 'Auth instance has already been used to make a network call. Auth can ' +\r\n 'no longer be configured to use the emulator. Try calling ' +\r\n '\"connectAuthEmulator()\" sooner.',\r\n [\"expired-action-code\" /* EXPIRED_OOB_CODE */]: 'The action code has expired.',\r\n [\"cancelled-popup-request\" /* EXPIRED_POPUP_REQUEST */]: 'This operation has been cancelled due to another conflicting popup being opened.',\r\n [\"internal-error\" /* INTERNAL_ERROR */]: 'An internal AuthError has occurred.',\r\n [\"invalid-app-credential\" /* INVALID_APP_CREDENTIAL */]: 'The phone verification request contains an invalid application verifier.' +\r\n ' The reCAPTCHA token response is either invalid or expired.',\r\n [\"invalid-app-id\" /* INVALID_APP_ID */]: 'The mobile app identifier is not registed for the current project.',\r\n [\"invalid-user-token\" /* INVALID_AUTH */]: \"This user's credential isn't valid for this project. This can happen \" +\r\n \"if the user's token has been tampered with, or if the user isn't for \" +\r\n 'the project associated with this API key.',\r\n [\"invalid-auth-event\" /* INVALID_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"invalid-verification-code\" /* INVALID_CODE */]: 'The SMS verification code used to create the phone auth credential is ' +\r\n 'invalid. Please resend the verification code sms and be sure to use the ' +\r\n 'verification code provided by the user.',\r\n [\"invalid-continue-uri\" /* INVALID_CONTINUE_URI */]: 'The continue URL provided in the request is invalid.',\r\n [\"invalid-cordova-configuration\" /* INVALID_CORDOVA_CONFIGURATION */]: 'The following Cordova plugins must be installed to enable OAuth sign-in: ' +\r\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\r\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\r\n 'cordova-plugin-customurlscheme.',\r\n [\"invalid-custom-token\" /* INVALID_CUSTOM_TOKEN */]: 'The custom token format is incorrect. Please check the documentation.',\r\n [\"invalid-dynamic-link-domain\" /* INVALID_DYNAMIC_LINK_DOMAIN */]: 'The provided dynamic link domain is not configured or authorized for the current project.',\r\n [\"invalid-email\" /* INVALID_EMAIL */]: 'The email address is badly formatted.',\r\n [\"invalid-emulator-scheme\" /* INVALID_EMULATOR_SCHEME */]: 'Emulator URL must start with a valid scheme (http:// or https://).',\r\n [\"invalid-api-key\" /* INVALID_API_KEY */]: 'Your API key is invalid, please check you have copied it correctly.',\r\n [\"invalid-cert-hash\" /* INVALID_CERT_HASH */]: 'The SHA-1 certificate hash provided is invalid.',\r\n [\"invalid-credential\" /* INVALID_IDP_RESPONSE */]: 'The supplied auth credential is malformed or has expired.',\r\n [\"invalid-message-payload\" /* INVALID_MESSAGE_PAYLOAD */]: 'The email template corresponding to this action contains invalid characters in its message. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-multi-factor-session\" /* INVALID_MFA_SESSION */]: 'The request does not contain a valid proof of first factor successful sign-in.',\r\n [\"invalid-oauth-provider\" /* INVALID_OAUTH_PROVIDER */]: 'EmailAuthProvider is not supported for this operation. This operation ' +\r\n 'only supports OAuth providers.',\r\n [\"invalid-oauth-client-id\" /* INVALID_OAUTH_CLIENT_ID */]: 'The OAuth client ID provided is either invalid or does not match the ' +\r\n 'specified API key.',\r\n [\"unauthorized-domain\" /* INVALID_ORIGIN */]: 'This domain is not authorized for OAuth operations for your Firebase ' +\r\n 'project. Edit the list of authorized domains from the Firebase console.',\r\n [\"invalid-action-code\" /* INVALID_OOB_CODE */]: 'The action code is invalid. This can happen if the code is malformed, ' +\r\n 'expired, or has already been used.',\r\n [\"wrong-password\" /* INVALID_PASSWORD */]: 'The password is invalid or the user does not have a password.',\r\n [\"invalid-persistence-type\" /* INVALID_PERSISTENCE */]: 'The specified persistence type is invalid. It can only be local, session or none.',\r\n [\"invalid-phone-number\" /* INVALID_PHONE_NUMBER */]: 'The format of the phone number provided is incorrect. Please enter the ' +\r\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\r\n 'phone numbers are written in the format [+][country code][subscriber ' +\r\n 'number including area code].',\r\n [\"invalid-provider-id\" /* INVALID_PROVIDER_ID */]: 'The specified provider ID is invalid.',\r\n [\"invalid-recipient-email\" /* INVALID_RECIPIENT_EMAIL */]: 'The email corresponding to this action failed to send as the provided ' +\r\n 'recipient email address is invalid.',\r\n [\"invalid-sender\" /* INVALID_SENDER */]: 'The email template corresponding to this action contains an invalid sender email or name. ' +\r\n 'Please fix by going to the Auth email templates section in the Firebase Console.',\r\n [\"invalid-verification-id\" /* INVALID_SESSION_INFO */]: 'The verification ID used to create the phone auth credential is invalid.',\r\n [\"invalid-tenant-id\" /* INVALID_TENANT_ID */]: \"The Auth instance's tenant ID is invalid.\",\r\n [\"missing-android-pkg-name\" /* MISSING_ANDROID_PACKAGE_NAME */]: 'An Android Package Name must be provided if the Android App is required to be installed.',\r\n [\"auth-domain-config-required\" /* MISSING_AUTH_DOMAIN */]: 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\r\n 'by following the instructions in the Firebase console.',\r\n [\"missing-app-credential\" /* MISSING_APP_CREDENTIAL */]: 'The phone verification request is missing an application verifier ' +\r\n 'assertion. A reCAPTCHA response token needs to be provided.',\r\n [\"missing-verification-code\" /* MISSING_CODE */]: 'The phone auth credential was created with an empty SMS verification code.',\r\n [\"missing-continue-uri\" /* MISSING_CONTINUE_URI */]: 'A continue URL must be provided in the request.',\r\n [\"missing-iframe-start\" /* MISSING_IFRAME_START */]: 'An internal AuthError has occurred.',\r\n [\"missing-ios-bundle-id\" /* MISSING_IOS_BUNDLE_ID */]: 'An iOS Bundle ID must be provided if an App Store ID is provided.',\r\n [\"missing-or-invalid-nonce\" /* MISSING_OR_INVALID_NONCE */]: 'The request does not contain a valid nonce. This can occur if the ' +\r\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\r\n 'in the ID token payload.',\r\n [\"missing-multi-factor-info\" /* MISSING_MFA_INFO */]: 'No second factor identifier is provided.',\r\n [\"missing-multi-factor-session\" /* MISSING_MFA_SESSION */]: 'The request is missing proof of first factor successful sign-in.',\r\n [\"missing-phone-number\" /* MISSING_PHONE_NUMBER */]: 'To send verification codes, provide a phone number for the recipient.',\r\n [\"missing-verification-id\" /* MISSING_SESSION_INFO */]: 'The phone auth credential was created with an empty verification ID.',\r\n [\"app-deleted\" /* MODULE_DESTROYED */]: 'This instance of FirebaseApp has been deleted.',\r\n [\"multi-factor-info-not-found\" /* MFA_INFO_NOT_FOUND */]: 'The user does not have a second factor matching the identifier provided.',\r\n [\"multi-factor-auth-required\" /* MFA_REQUIRED */]: 'Proof of ownership of a second factor is required to complete sign-in.',\r\n [\"account-exists-with-different-credential\" /* NEED_CONFIRMATION */]: 'An account already exists with the same email address but different ' +\r\n 'sign-in credentials. Sign in using a provider associated with this ' +\r\n 'email address.',\r\n [\"network-request-failed\" /* NETWORK_REQUEST_FAILED */]: 'A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.',\r\n [\"no-auth-event\" /* NO_AUTH_EVENT */]: 'An internal AuthError has occurred.',\r\n [\"no-such-provider\" /* NO_SUCH_PROVIDER */]: 'User was not linked to an account with the given provider.',\r\n [\"null-user\" /* NULL_USER */]: 'A null user object was provided as the argument for an operation which ' +\r\n 'requires a non-null user object.',\r\n [\"operation-not-allowed\" /* OPERATION_NOT_ALLOWED */]: 'The given sign-in provider is disabled for this Firebase project. ' +\r\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\r\n 'Auth section.',\r\n [\"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */]: 'This operation is not supported in the environment this application is ' +\r\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\r\n ' and web storage must be enabled.',\r\n [\"popup-blocked\" /* POPUP_BLOCKED */]: 'Unable to establish a connection with the popup. It may have been blocked by the browser.',\r\n [\"popup-closed-by-user\" /* POPUP_CLOSED_BY_USER */]: 'The popup has been closed by the user before finalizing the operation.',\r\n [\"provider-already-linked\" /* PROVIDER_ALREADY_LINKED */]: 'User can only be linked to one identity for the given provider.',\r\n [\"quota-exceeded\" /* QUOTA_EXCEEDED */]: \"The project's quota for this operation has been exceeded.\",\r\n [\"redirect-cancelled-by-user\" /* REDIRECT_CANCELLED_BY_USER */]: 'The redirect operation has been cancelled by the user before finalizing.',\r\n [\"redirect-operation-pending\" /* REDIRECT_OPERATION_PENDING */]: 'A redirect sign-in operation is already pending.',\r\n [\"rejected-credential\" /* REJECTED_CREDENTIAL */]: 'The request contains malformed or mismatching credentials.',\r\n [\"second-factor-already-in-use\" /* SECOND_FACTOR_ALREADY_ENROLLED */]: 'The second factor is already enrolled on this account.',\r\n [\"maximum-second-factor-count-exceeded\" /* SECOND_FACTOR_LIMIT_EXCEEDED */]: 'The maximum allowed number of second factors on a user has been exceeded.',\r\n [\"tenant-id-mismatch\" /* TENANT_ID_MISMATCH */]: \"The provided tenant ID does not match the Auth instance's tenant ID\",\r\n [\"timeout\" /* TIMEOUT */]: 'The operation has timed out.',\r\n [\"user-token-expired\" /* TOKEN_EXPIRED */]: \"The user's credential is no longer valid. The user must sign in again.\",\r\n [\"too-many-requests\" /* TOO_MANY_ATTEMPTS_TRY_LATER */]: 'We have blocked all requests from this device due to unusual activity. ' +\r\n 'Try again later.',\r\n [\"unauthorized-continue-uri\" /* UNAUTHORIZED_DOMAIN */]: 'The domain of the continue URL is not whitelisted. Please whitelist ' +\r\n 'the domain in the Firebase console.',\r\n [\"unsupported-first-factor\" /* UNSUPPORTED_FIRST_FACTOR */]: 'Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.',\r\n [\"unsupported-persistence-type\" /* UNSUPPORTED_PERSISTENCE */]: 'The current environment does not support the specified persistence type.',\r\n [\"unsupported-tenant-operation\" /* UNSUPPORTED_TENANT_OPERATION */]: 'This operation is not supported in a multi-tenant context.',\r\n [\"unverified-email\" /* UNVERIFIED_EMAIL */]: 'The operation requires a verified email.',\r\n [\"user-cancelled\" /* USER_CANCELLED */]: 'The user did not grant your application the permissions it requested.',\r\n [\"user-not-found\" /* USER_DELETED */]: 'There is no user record corresponding to this identifier. The user may ' +\r\n 'have been deleted.',\r\n [\"user-disabled\" /* USER_DISABLED */]: 'The user account has been disabled by an administrator.',\r\n [\"user-mismatch\" /* USER_MISMATCH */]: 'The supplied credentials do not correspond to the previously signed in user.',\r\n [\"user-signed-out\" /* USER_SIGNED_OUT */]: '',\r\n [\"weak-password\" /* WEAK_PASSWORD */]: 'The password must be 6 characters long or more.',\r\n [\"web-storage-unsupported\" /* WEB_STORAGE_UNSUPPORTED */]: 'This browser is not supported or 3rd party cookies and data may be disabled.',\r\n [\"already-initialized\" /* ALREADY_INITIALIZED */]: 'initializeAuth() has already been called with ' +\r\n 'different options. To avoid this error, call initializeAuth() with the ' +\r\n 'same options as when it was originally called, or call getAuth() to return the' +\r\n ' already initialized instance.'\r\n };\r\n}\r\nfunction _prodErrorMap() {\r\n // We will include this one message in the prod error map since by the very\r\n // nature of this error, developers will never be able to see the message\r\n // using the debugErrorMap (which is installed during auth initialization).\r\n return {\r\n [\"dependent-sdk-initialized-before-auth\" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */]: 'Another Firebase SDK was initialized and is trying to use Auth before Auth is ' +\r\n 'initialized. Please be sure to call `initializeAuth` or `getAuth` before ' +\r\n 'starting any other Firebase SDK.'\r\n };\r\n}\r\n/**\r\n * A verbose error map with detailed descriptions for most error codes.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst debugErrorMap = _debugErrorMap;\r\n/**\r\n * A minimal error map with all verbose error messages stripped.\r\n *\r\n * See discussion at {@link AuthErrorMap}\r\n *\r\n * @public\r\n */\r\nconst prodErrorMap = _prodErrorMap;\r\nconst _DEFAULT_AUTH_ERROR_FACTORY = new ErrorFactory('auth', 'Firebase', _prodErrorMap());\r\n/**\r\n * A map of potential `Auth` error codes, for easier comparison with errors\r\n * thrown by the SDK.\r\n *\r\n * @remarks\r\n * Note that you can't tree-shake individual keys\r\n * in the map, so by using the map you might substantially increase your\r\n * bundle size.\r\n *\r\n * @public\r\n */\r\nconst AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY = {\r\n ADMIN_ONLY_OPERATION: 'auth/admin-restricted-operation',\r\n ARGUMENT_ERROR: 'auth/argument-error',\r\n APP_NOT_AUTHORIZED: 'auth/app-not-authorized',\r\n APP_NOT_INSTALLED: 'auth/app-not-installed',\r\n CAPTCHA_CHECK_FAILED: 'auth/captcha-check-failed',\r\n CODE_EXPIRED: 'auth/code-expired',\r\n CORDOVA_NOT_READY: 'auth/cordova-not-ready',\r\n CORS_UNSUPPORTED: 'auth/cors-unsupported',\r\n CREDENTIAL_ALREADY_IN_USE: 'auth/credential-already-in-use',\r\n CREDENTIAL_MISMATCH: 'auth/custom-token-mismatch',\r\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'auth/requires-recent-login',\r\n DEPENDENT_SDK_INIT_BEFORE_AUTH: 'auth/dependent-sdk-initialized-before-auth',\r\n DYNAMIC_LINK_NOT_ACTIVATED: 'auth/dynamic-link-not-activated',\r\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'auth/email-change-needs-verification',\r\n EMAIL_EXISTS: 'auth/email-already-in-use',\r\n EMULATOR_CONFIG_FAILED: 'auth/emulator-config-failed',\r\n EXPIRED_OOB_CODE: 'auth/expired-action-code',\r\n EXPIRED_POPUP_REQUEST: 'auth/cancelled-popup-request',\r\n INTERNAL_ERROR: 'auth/internal-error',\r\n INVALID_API_KEY: 'auth/invalid-api-key',\r\n INVALID_APP_CREDENTIAL: 'auth/invalid-app-credential',\r\n INVALID_APP_ID: 'auth/invalid-app-id',\r\n INVALID_AUTH: 'auth/invalid-user-token',\r\n INVALID_AUTH_EVENT: 'auth/invalid-auth-event',\r\n INVALID_CERT_HASH: 'auth/invalid-cert-hash',\r\n INVALID_CODE: 'auth/invalid-verification-code',\r\n INVALID_CONTINUE_URI: 'auth/invalid-continue-uri',\r\n INVALID_CORDOVA_CONFIGURATION: 'auth/invalid-cordova-configuration',\r\n INVALID_CUSTOM_TOKEN: 'auth/invalid-custom-token',\r\n INVALID_DYNAMIC_LINK_DOMAIN: 'auth/invalid-dynamic-link-domain',\r\n INVALID_EMAIL: 'auth/invalid-email',\r\n INVALID_EMULATOR_SCHEME: 'auth/invalid-emulator-scheme',\r\n INVALID_IDP_RESPONSE: 'auth/invalid-credential',\r\n INVALID_MESSAGE_PAYLOAD: 'auth/invalid-message-payload',\r\n INVALID_MFA_SESSION: 'auth/invalid-multi-factor-session',\r\n INVALID_OAUTH_CLIENT_ID: 'auth/invalid-oauth-client-id',\r\n INVALID_OAUTH_PROVIDER: 'auth/invalid-oauth-provider',\r\n INVALID_OOB_CODE: 'auth/invalid-action-code',\r\n INVALID_ORIGIN: 'auth/unauthorized-domain',\r\n INVALID_PASSWORD: 'auth/wrong-password',\r\n INVALID_PERSISTENCE: 'auth/invalid-persistence-type',\r\n INVALID_PHONE_NUMBER: 'auth/invalid-phone-number',\r\n INVALID_PROVIDER_ID: 'auth/invalid-provider-id',\r\n INVALID_RECIPIENT_EMAIL: 'auth/invalid-recipient-email',\r\n INVALID_SENDER: 'auth/invalid-sender',\r\n INVALID_SESSION_INFO: 'auth/invalid-verification-id',\r\n INVALID_TENANT_ID: 'auth/invalid-tenant-id',\r\n MFA_INFO_NOT_FOUND: 'auth/multi-factor-info-not-found',\r\n MFA_REQUIRED: 'auth/multi-factor-auth-required',\r\n MISSING_ANDROID_PACKAGE_NAME: 'auth/missing-android-pkg-name',\r\n MISSING_APP_CREDENTIAL: 'auth/missing-app-credential',\r\n MISSING_AUTH_DOMAIN: 'auth/auth-domain-config-required',\r\n MISSING_CODE: 'auth/missing-verification-code',\r\n MISSING_CONTINUE_URI: 'auth/missing-continue-uri',\r\n MISSING_IFRAME_START: 'auth/missing-iframe-start',\r\n MISSING_IOS_BUNDLE_ID: 'auth/missing-ios-bundle-id',\r\n MISSING_OR_INVALID_NONCE: 'auth/missing-or-invalid-nonce',\r\n MISSING_MFA_INFO: 'auth/missing-multi-factor-info',\r\n MISSING_MFA_SESSION: 'auth/missing-multi-factor-session',\r\n MISSING_PHONE_NUMBER: 'auth/missing-phone-number',\r\n MISSING_SESSION_INFO: 'auth/missing-verification-id',\r\n MODULE_DESTROYED: 'auth/app-deleted',\r\n NEED_CONFIRMATION: 'auth/account-exists-with-different-credential',\r\n NETWORK_REQUEST_FAILED: 'auth/network-request-failed',\r\n NULL_USER: 'auth/null-user',\r\n NO_AUTH_EVENT: 'auth/no-auth-event',\r\n NO_SUCH_PROVIDER: 'auth/no-such-provider',\r\n OPERATION_NOT_ALLOWED: 'auth/operation-not-allowed',\r\n OPERATION_NOT_SUPPORTED: 'auth/operation-not-supported-in-this-environment',\r\n POPUP_BLOCKED: 'auth/popup-blocked',\r\n POPUP_CLOSED_BY_USER: 'auth/popup-closed-by-user',\r\n PROVIDER_ALREADY_LINKED: 'auth/provider-already-linked',\r\n QUOTA_EXCEEDED: 'auth/quota-exceeded',\r\n REDIRECT_CANCELLED_BY_USER: 'auth/redirect-cancelled-by-user',\r\n REDIRECT_OPERATION_PENDING: 'auth/redirect-operation-pending',\r\n REJECTED_CREDENTIAL: 'auth/rejected-credential',\r\n SECOND_FACTOR_ALREADY_ENROLLED: 'auth/second-factor-already-in-use',\r\n SECOND_FACTOR_LIMIT_EXCEEDED: 'auth/maximum-second-factor-count-exceeded',\r\n TENANT_ID_MISMATCH: 'auth/tenant-id-mismatch',\r\n TIMEOUT: 'auth/timeout',\r\n TOKEN_EXPIRED: 'auth/user-token-expired',\r\n TOO_MANY_ATTEMPTS_TRY_LATER: 'auth/too-many-requests',\r\n UNAUTHORIZED_DOMAIN: 'auth/unauthorized-continue-uri',\r\n UNSUPPORTED_FIRST_FACTOR: 'auth/unsupported-first-factor',\r\n UNSUPPORTED_PERSISTENCE: 'auth/unsupported-persistence-type',\r\n UNSUPPORTED_TENANT_OPERATION: 'auth/unsupported-tenant-operation',\r\n UNVERIFIED_EMAIL: 'auth/unverified-email',\r\n USER_CANCELLED: 'auth/user-cancelled',\r\n USER_DELETED: 'auth/user-not-found',\r\n USER_DISABLED: 'auth/user-disabled',\r\n USER_MISMATCH: 'auth/user-mismatch',\r\n USER_SIGNED_OUT: 'auth/user-signed-out',\r\n WEAK_PASSWORD: 'auth/weak-password',\r\n WEB_STORAGE_UNSUPPORTED: 'auth/web-storage-unsupported',\r\n ALREADY_INITIALIZED: 'auth/already-initialized'\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logClient = new Logger('@firebase/auth');\r\nfunction _logError(msg, ...args) {\r\n if (logClient.logLevel <= LogLevel.ERROR) {\r\n logClient.error(`Auth (${SDK_VERSION}): ${msg}`, ...args);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _fail(authOrCode, ...rest) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _createError(authOrCode, ...rest) {\r\n return createErrorInternal(authOrCode, ...rest);\r\n}\r\nfunction _errorWithCustomMessage(auth, code, message) {\r\n const errorMap = Object.assign(Object.assign({}, prodErrorMap()), { [code]: message });\r\n const factory = new ErrorFactory('auth', 'Firebase', errorMap);\r\n return factory.create(code, {\r\n appName: auth.name,\r\n });\r\n}\r\nfunction _assertInstanceOf(auth, object, instance) {\r\n const constructorInstance = instance;\r\n if (!(object instanceof constructorInstance)) {\r\n if (constructorInstance.name !== object.constructor.name) {\r\n _fail(auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n }\r\n throw _errorWithCustomMessage(auth, \"argument-error\" /* ARGUMENT_ERROR */, `Type of ${object.constructor.name} does not match expected instance.` +\r\n `Did you pass a reference from a different Auth SDK?`);\r\n }\r\n}\r\nfunction createErrorInternal(authOrCode, ...rest) {\r\n if (typeof authOrCode !== 'string') {\r\n const code = rest[0];\r\n const fullParams = [...rest.slice(1)];\r\n if (fullParams[0]) {\r\n fullParams[0].appName = authOrCode.name;\r\n }\r\n return authOrCode._errorFactory.create(code, ...fullParams);\r\n }\r\n return _DEFAULT_AUTH_ERROR_FACTORY.create(authOrCode, ...rest);\r\n}\r\nfunction _assert(assertion, authOrCode, ...rest) {\r\n if (!assertion) {\r\n throw createErrorInternal(authOrCode, ...rest);\r\n }\r\n}\r\n/**\r\n * Unconditionally fails, throwing an internal error with the given message.\r\n *\r\n * @param failure type of failure encountered\r\n * @throws Error\r\n */\r\nfunction debugFail(failure) {\r\n // Log the failure in addition to throw an exception, just in case the\r\n // exception is swallowed.\r\n const message = `INTERNAL ASSERTION FAILED: ` + failure;\r\n _logError(message);\r\n // NOTE: We don't use FirebaseError here because these are internal failures\r\n // that cannot be handled by the user. (Also it would create a circular\r\n // dependency between the error and assert modules which doesn't work.)\r\n throw new Error(message);\r\n}\r\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n *\r\n * @param assertion\r\n * @param message\r\n */\r\nfunction debugAssert(assertion, message) {\r\n if (!assertion) {\r\n debugFail(message);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst instanceCache = new Map();\r\nfunction _getInstance(cls) {\r\n debugAssert(cls instanceof Function, 'Expected a class definition');\r\n let instance = instanceCache.get(cls);\r\n if (instance) {\r\n debugAssert(instance instanceof cls, 'Instance stored in cache mismatched with class');\r\n return instance;\r\n }\r\n instance = new cls();\r\n instanceCache.set(cls, instance);\r\n return instance;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Initializes an {@link Auth} instance with fine-grained control over\r\n * {@link Dependencies}.\r\n *\r\n * @remarks\r\n *\r\n * This function allows more control over the {@link Auth} instance than\r\n * {@link getAuth}. `getAuth` uses platform-specific defaults to supply\r\n * the {@link Dependencies}. In general, `getAuth` is the easiest way to\r\n * initialize Auth and works for most use cases. Use `initializeAuth` if you\r\n * need control over which persistence layer is used, or to minimize bundle\r\n * size if you're not using either `signInWithPopup` or `signInWithRedirect`.\r\n *\r\n * For example, if your app only uses anonymous accounts and you only want\r\n * accounts saved for the current session, initialize `Auth` with:\r\n *\r\n * ```js\r\n * const auth = initializeAuth(app, {\r\n * persistence: browserSessionPersistence,\r\n * popupRedirectResolver: undefined,\r\n * });\r\n * ```\r\n *\r\n * @public\r\n */\r\nfunction initializeAuth(app, deps) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n const auth = provider.getImmediate();\r\n const initialOptions = provider.getOptions();\r\n if (deepEqual(initialOptions, deps !== null && deps !== void 0 ? deps : {})) {\r\n return auth;\r\n }\r\n else {\r\n _fail(auth, \"already-initialized\" /* ALREADY_INITIALIZED */);\r\n }\r\n }\r\n const auth = provider.initialize({ options: deps });\r\n return auth;\r\n}\r\nfunction _initializeAuthInstance(auth, deps) {\r\n const persistence = (deps === null || deps === void 0 ? void 0 : deps.persistence) || [];\r\n const hierarchy = (Array.isArray(persistence) ? persistence : [persistence]).map(_getInstance);\r\n if (deps === null || deps === void 0 ? void 0 : deps.errorMap) {\r\n auth._updateErrorMap(deps.errorMap);\r\n }\r\n // This promise is intended to float; auth initialization happens in the\r\n // background, meanwhile the auth object may be used by the app.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n auth._initializeWithPersistence(hierarchy, deps === null || deps === void 0 ? void 0 : deps.popupRedirectResolver);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _getCurrentUrl() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.href)) || '';\r\n}\r\nfunction _isHttpOrHttps() {\r\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\nfunction _getCurrentScheme() {\r\n var _a;\r\n return (typeof self !== 'undefined' && ((_a = self.location) === null || _a === void 0 ? void 0 : _a.protocol)) || null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine whether the browser is working online\r\n */\r\nfunction _isOnline() {\r\n if (typeof navigator !== 'undefined' &&\r\n navigator &&\r\n 'onLine' in navigator &&\r\n typeof navigator.onLine === 'boolean' &&\r\n // Apply only for traditional web apps and Chrome extensions.\r\n // This is especially true for Cordova apps which have unreliable\r\n // navigator.onLine behavior unless cordova-plugin-network-information is\r\n // installed which overwrites the native navigator.onLine value and\r\n // defines navigator.connection.\r\n (_isHttpOrHttps() || isBrowserExtension() || 'connection' in navigator)) {\r\n return navigator.onLine;\r\n }\r\n // If we can't determine the state, assume it is online.\r\n return true;\r\n}\r\nfunction _getUserLanguage() {\r\n if (typeof navigator === 'undefined') {\r\n return null;\r\n }\r\n const navigatorLanguage = navigator;\r\n return (\r\n // Most reliable, but only supported in Chrome/Firefox.\r\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\r\n // Supported in most browsers, but returns the language of the browser\r\n // UI, not the language set in browser settings.\r\n navigatorLanguage.language ||\r\n // Couldn't determine language.\r\n null);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A structure to help pick between a range of long and short delay durations\r\n * depending on the current environment. In general, the long delay is used for\r\n * mobile environments whereas short delays are used for desktop environments.\r\n */\r\nclass Delay {\r\n constructor(shortDelay, longDelay) {\r\n this.shortDelay = shortDelay;\r\n this.longDelay = longDelay;\r\n // Internal error when improperly initialized.\r\n debugAssert(longDelay > shortDelay, 'Short delay should be less than long delay!');\r\n this.isMobile = isMobileCordova() || isReactNative();\r\n }\r\n get() {\r\n if (!_isOnline()) {\r\n // Pick the shorter timeout.\r\n return Math.min(5000 /* OFFLINE */, this.shortDelay);\r\n }\r\n // If running in a mobile environment, return the long delay, otherwise\r\n // return the short delay.\r\n // This could be improved in the future to dynamically change based on other\r\n // variables instead of just reading the current environment.\r\n return this.isMobile ? this.longDelay : this.shortDelay;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _emulatorUrl(config, path) {\r\n debugAssert(config.emulator, 'Emulator should always be set here');\r\n const { url } = config.emulator;\r\n if (!path) {\r\n return url;\r\n }\r\n return `${url}${path.startsWith('/') ? path.slice(1) : path}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass FetchProvider {\r\n static initialize(fetchImpl, headersImpl, responseImpl) {\r\n this.fetchImpl = fetchImpl;\r\n if (headersImpl) {\r\n this.headersImpl = headersImpl;\r\n }\r\n if (responseImpl) {\r\n this.responseImpl = responseImpl;\r\n }\r\n }\r\n static fetch() {\r\n if (this.fetchImpl) {\r\n return this.fetchImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'fetch' in self) {\r\n return self.fetch;\r\n }\r\n debugFail('Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static headers() {\r\n if (this.headersImpl) {\r\n return this.headersImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Headers' in self) {\r\n return self.Headers;\r\n }\r\n debugFail('Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n static response() {\r\n if (this.responseImpl) {\r\n return this.responseImpl;\r\n }\r\n if (typeof self !== 'undefined' && 'Response' in self) {\r\n return self.Response;\r\n }\r\n debugFail('Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Map from errors returned by the server to errors to developer visible errors\r\n */\r\nconst SERVER_ERROR_MAP = {\r\n // Custom token errors.\r\n [\"CREDENTIAL_MISMATCH\" /* CREDENTIAL_MISMATCH */]: \"custom-token-mismatch\" /* CREDENTIAL_MISMATCH */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CUSTOM_TOKEN\" /* MISSING_CUSTOM_TOKEN */]: \"internal-error\" /* INTERNAL_ERROR */,\r\n // Create Auth URI errors.\r\n [\"INVALID_IDENTIFIER\" /* INVALID_IDENTIFIER */]: \"invalid-email\" /* INVALID_EMAIL */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_CONTINUE_URI\" /* MISSING_CONTINUE_URI */]: \"internal-error\" /* INTERNAL_ERROR */,\r\n // Sign in with email and password errors (some apply to sign up too).\r\n [\"INVALID_PASSWORD\" /* INVALID_PASSWORD */]: \"wrong-password\" /* INVALID_PASSWORD */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_PASSWORD\" /* MISSING_PASSWORD */]: \"internal-error\" /* INTERNAL_ERROR */,\r\n // Sign up with email and password errors.\r\n [\"EMAIL_EXISTS\" /* EMAIL_EXISTS */]: \"email-already-in-use\" /* EMAIL_EXISTS */,\r\n [\"PASSWORD_LOGIN_DISABLED\" /* PASSWORD_LOGIN_DISABLED */]: \"operation-not-allowed\" /* OPERATION_NOT_ALLOWED */,\r\n // Verify assertion for sign in with credential errors:\r\n [\"INVALID_IDP_RESPONSE\" /* INVALID_IDP_RESPONSE */]: \"invalid-credential\" /* INVALID_IDP_RESPONSE */,\r\n [\"INVALID_PENDING_TOKEN\" /* INVALID_PENDING_TOKEN */]: \"invalid-credential\" /* INVALID_IDP_RESPONSE */,\r\n [\"FEDERATED_USER_ID_ALREADY_LINKED\" /* FEDERATED_USER_ID_ALREADY_LINKED */]: \"credential-already-in-use\" /* CREDENTIAL_ALREADY_IN_USE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_REQ_TYPE\" /* MISSING_REQ_TYPE */]: \"internal-error\" /* INTERNAL_ERROR */,\r\n // Send Password reset email errors:\r\n [\"EMAIL_NOT_FOUND\" /* EMAIL_NOT_FOUND */]: \"user-not-found\" /* USER_DELETED */,\r\n [\"RESET_PASSWORD_EXCEED_LIMIT\" /* RESET_PASSWORD_EXCEED_LIMIT */]: \"too-many-requests\" /* TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n [\"EXPIRED_OOB_CODE\" /* EXPIRED_OOB_CODE */]: \"expired-action-code\" /* EXPIRED_OOB_CODE */,\r\n [\"INVALID_OOB_CODE\" /* INVALID_OOB_CODE */]: \"invalid-action-code\" /* INVALID_OOB_CODE */,\r\n // This can only happen if the SDK sends a bad request.\r\n [\"MISSING_OOB_CODE\" /* MISSING_OOB_CODE */]: \"internal-error\" /* INTERNAL_ERROR */,\r\n // Operations that require ID token in request:\r\n [\"CREDENTIAL_TOO_OLD_LOGIN_AGAIN\" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */]: \"requires-recent-login\" /* CREDENTIAL_TOO_OLD_LOGIN_AGAIN */,\r\n [\"INVALID_ID_TOKEN\" /* INVALID_ID_TOKEN */]: \"invalid-user-token\" /* INVALID_AUTH */,\r\n [\"TOKEN_EXPIRED\" /* TOKEN_EXPIRED */]: \"user-token-expired\" /* TOKEN_EXPIRED */,\r\n [\"USER_NOT_FOUND\" /* USER_NOT_FOUND */]: \"user-token-expired\" /* TOKEN_EXPIRED */,\r\n // Other errors.\r\n [\"TOO_MANY_ATTEMPTS_TRY_LATER\" /* TOO_MANY_ATTEMPTS_TRY_LATER */]: \"too-many-requests\" /* TOO_MANY_ATTEMPTS_TRY_LATER */,\r\n // Phone Auth related errors.\r\n [\"INVALID_CODE\" /* INVALID_CODE */]: \"invalid-verification-code\" /* INVALID_CODE */,\r\n [\"INVALID_SESSION_INFO\" /* INVALID_SESSION_INFO */]: \"invalid-verification-id\" /* INVALID_SESSION_INFO */,\r\n [\"INVALID_TEMPORARY_PROOF\" /* INVALID_TEMPORARY_PROOF */]: \"invalid-credential\" /* INVALID_IDP_RESPONSE */,\r\n [\"MISSING_SESSION_INFO\" /* MISSING_SESSION_INFO */]: \"missing-verification-id\" /* MISSING_SESSION_INFO */,\r\n [\"SESSION_EXPIRED\" /* SESSION_EXPIRED */]: \"code-expired\" /* CODE_EXPIRED */,\r\n // Other action code errors when additional settings passed.\r\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\r\n // This is OK as this error will be caught by client side validation.\r\n [\"MISSING_ANDROID_PACKAGE_NAME\" /* MISSING_ANDROID_PACKAGE_NAME */]: \"missing-android-pkg-name\" /* MISSING_ANDROID_PACKAGE_NAME */,\r\n [\"UNAUTHORIZED_DOMAIN\" /* UNAUTHORIZED_DOMAIN */]: \"unauthorized-continue-uri\" /* UNAUTHORIZED_DOMAIN */,\r\n // getProjectConfig errors when clientId is passed.\r\n [\"INVALID_OAUTH_CLIENT_ID\" /* INVALID_OAUTH_CLIENT_ID */]: \"invalid-oauth-client-id\" /* INVALID_OAUTH_CLIENT_ID */,\r\n // User actions (sign-up or deletion) disabled errors.\r\n [\"ADMIN_ONLY_OPERATION\" /* ADMIN_ONLY_OPERATION */]: \"admin-restricted-operation\" /* ADMIN_ONLY_OPERATION */,\r\n // Multi factor related errors.\r\n [\"INVALID_MFA_PENDING_CREDENTIAL\" /* INVALID_MFA_PENDING_CREDENTIAL */]: \"invalid-multi-factor-session\" /* INVALID_MFA_SESSION */,\r\n [\"MFA_ENROLLMENT_NOT_FOUND\" /* MFA_ENROLLMENT_NOT_FOUND */]: \"multi-factor-info-not-found\" /* MFA_INFO_NOT_FOUND */,\r\n [\"MISSING_MFA_ENROLLMENT_ID\" /* MISSING_MFA_ENROLLMENT_ID */]: \"missing-multi-factor-info\" /* MISSING_MFA_INFO */,\r\n [\"MISSING_MFA_PENDING_CREDENTIAL\" /* MISSING_MFA_PENDING_CREDENTIAL */]: \"missing-multi-factor-session\" /* MISSING_MFA_SESSION */,\r\n [\"SECOND_FACTOR_EXISTS\" /* SECOND_FACTOR_EXISTS */]: \"second-factor-already-in-use\" /* SECOND_FACTOR_ALREADY_ENROLLED */,\r\n [\"SECOND_FACTOR_LIMIT_EXCEEDED\" /* SECOND_FACTOR_LIMIT_EXCEEDED */]: \"maximum-second-factor-count-exceeded\" /* SECOND_FACTOR_LIMIT_EXCEEDED */,\r\n // Blocking functions related errors.\r\n [\"BLOCKING_FUNCTION_ERROR_RESPONSE\" /* BLOCKING_FUNCTION_ERROR_RESPONSE */]: \"internal-error\" /* INTERNAL_ERROR */,\r\n};\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DEFAULT_API_TIMEOUT_MS = new Delay(30000, 60000);\r\nfunction _addTidIfNecessary(auth, request) {\r\n if (auth.tenantId && !request.tenantId) {\r\n return Object.assign(Object.assign({}, request), { tenantId: auth.tenantId });\r\n }\r\n return request;\r\n}\r\nasync function _performApiRequest(auth, method, path, request, customErrorMap = {}) {\r\n return _performFetchWithErrorHandling(auth, customErrorMap, async () => {\r\n let body = {};\r\n let params = {};\r\n if (request) {\r\n if (method === \"GET\" /* GET */) {\r\n params = request;\r\n }\r\n else {\r\n body = {\r\n body: JSON.stringify(request)\r\n };\r\n }\r\n }\r\n const query = querystring(Object.assign({ key: auth.config.apiKey }, params)).slice(1);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* CONTENT_TYPE */] = 'application/json';\r\n if (auth.languageCode) {\r\n headers[\"X-Firebase-Locale\" /* X_FIREBASE_LOCALE */] = auth.languageCode;\r\n }\r\n return FetchProvider.fetch()(_getFinalTarget(auth, auth.config.apiHost, path, query), Object.assign({ method,\r\n headers, referrerPolicy: 'no-referrer' }, body));\r\n });\r\n}\r\nasync function _performFetchWithErrorHandling(auth, customErrorMap, fetchFn) {\r\n auth._canInitEmulator = false;\r\n const errorMap = Object.assign(Object.assign({}, SERVER_ERROR_MAP), customErrorMap);\r\n try {\r\n const networkTimeout = new NetworkTimeout(auth);\r\n const response = await Promise.race([\r\n fetchFn(),\r\n networkTimeout.promise\r\n ]);\r\n // If we've reached this point, the fetch succeeded and the networkTimeout\r\n // didn't throw; clear the network timeout delay so that Node won't hang\r\n networkTimeout.clearNetworkTimeout();\r\n const json = await response.json();\r\n if ('needConfirmation' in json) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* NEED_CONFIRMATION */, json);\r\n }\r\n if (response.ok && !('errorMessage' in json)) {\r\n return json;\r\n }\r\n else {\r\n const errorMessage = response.ok ? json.errorMessage : json.error.message;\r\n const [serverErrorCode, serverErrorMessage] = errorMessage.split(' : ');\r\n if (serverErrorCode === \"FEDERATED_USER_ID_ALREADY_LINKED\" /* FEDERATED_USER_ID_ALREADY_LINKED */) {\r\n throw _makeTaggedError(auth, \"credential-already-in-use\" /* CREDENTIAL_ALREADY_IN_USE */, json);\r\n }\r\n else if (serverErrorCode === \"EMAIL_EXISTS\" /* EMAIL_EXISTS */) {\r\n throw _makeTaggedError(auth, \"email-already-in-use\" /* EMAIL_EXISTS */, json);\r\n }\r\n const authError = errorMap[serverErrorCode] ||\r\n serverErrorCode\r\n .toLowerCase()\r\n .replace(/[_\\s]+/g, '-');\r\n if (serverErrorMessage) {\r\n throw _errorWithCustomMessage(auth, authError, serverErrorMessage);\r\n }\r\n else {\r\n _fail(auth, authError);\r\n }\r\n }\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError) {\r\n throw e;\r\n }\r\n _fail(auth, \"network-request-failed\" /* NETWORK_REQUEST_FAILED */);\r\n }\r\n}\r\nasync function _performSignInRequest(auth, method, path, request, customErrorMap = {}) {\r\n const serverResponse = (await _performApiRequest(auth, method, path, request, customErrorMap));\r\n if ('mfaPendingCredential' in serverResponse) {\r\n _fail(auth, \"multi-factor-auth-required\" /* MFA_REQUIRED */, {\r\n _serverResponse: serverResponse\r\n });\r\n }\r\n return serverResponse;\r\n}\r\nfunction _getFinalTarget(auth, host, path, query) {\r\n const base = `${host}${path}?${query}`;\r\n if (!auth.config.emulator) {\r\n return `${auth.config.apiScheme}://${base}`;\r\n }\r\n return _emulatorUrl(auth.config, base);\r\n}\r\nclass NetworkTimeout {\r\n constructor(auth) {\r\n this.auth = auth;\r\n // Node timers and browser timers are fundamentally incompatible, but we\r\n // don't care about the value here\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timer = null;\r\n this.promise = new Promise((_, reject) => {\r\n this.timer = setTimeout(() => {\r\n return reject(_createError(this.auth, \"network-request-failed\" /* NETWORK_REQUEST_FAILED */));\r\n }, DEFAULT_API_TIMEOUT_MS.get());\r\n });\r\n }\r\n clearNetworkTimeout() {\r\n clearTimeout(this.timer);\r\n }\r\n}\r\nfunction _makeTaggedError(auth, code, response) {\r\n const errorParams = {\r\n appName: auth.name\r\n };\r\n if (response.email) {\r\n errorParams.email = response.email;\r\n }\r\n if (response.phoneNumber) {\r\n errorParams.phoneNumber = response.phoneNumber;\r\n }\r\n const error = _createError(auth, code, errorParams);\r\n // We know customData is defined on error because errorParams is defined\r\n error.customData._tokenResponse = response;\r\n return error;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteAccount(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:delete\" /* DELETE_ACCOUNT */, request);\r\n}\r\nasync function deleteLinkedAccounts(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:update\" /* SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function getAccountInfo(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:lookup\" /* GET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction utcTimestampToDateString(utcTimestamp) {\r\n if (!utcTimestamp) {\r\n return undefined;\r\n }\r\n try {\r\n // Convert to date object.\r\n const date = new Date(Number(utcTimestamp));\r\n // Test date is valid.\r\n if (!isNaN(date.getTime())) {\r\n // Convert to UTC date string.\r\n return date.toUTCString();\r\n }\r\n }\r\n catch (e) {\r\n // Do nothing. undefined will be returned.\r\n }\r\n return undefined;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a JSON Web Token (JWT) used to identify the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nfunction getIdToken(user, forceRefresh = false) {\r\n return getModularInstance(user).getIdToken(forceRefresh);\r\n}\r\n/**\r\n * Returns a deserialized JSON Web Token (JWT) used to identitfy the user to a Firebase service.\r\n *\r\n * @remarks\r\n * Returns the current token if it has not expired or if it will not expire in the next five\r\n * minutes. Otherwise, this will refresh the token and return a new one.\r\n *\r\n * @param user - The user.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getIdTokenResult(user, forceRefresh = false) {\r\n const userInternal = getModularInstance(user);\r\n const token = await userInternal.getIdToken(forceRefresh);\r\n const claims = _parseToken(token);\r\n _assert(claims && claims.exp && claims.auth_time && claims.iat, userInternal.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const firebase = typeof claims.firebase === 'object' ? claims.firebase : undefined;\r\n const signInProvider = firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_provider'];\r\n return {\r\n claims,\r\n token,\r\n authTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.auth_time)),\r\n issuedAtTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.iat)),\r\n expirationTime: utcTimestampToDateString(secondsStringToMilliseconds(claims.exp)),\r\n signInProvider: signInProvider || null,\r\n signInSecondFactor: (firebase === null || firebase === void 0 ? void 0 : firebase['sign_in_second_factor']) || null\r\n };\r\n}\r\nfunction secondsStringToMilliseconds(seconds) {\r\n return Number(seconds) * 1000;\r\n}\r\nfunction _parseToken(token) {\r\n const [algorithm, payload, signature] = token.split('.');\r\n if (algorithm === undefined ||\r\n payload === undefined ||\r\n signature === undefined) {\r\n _logError('JWT malformed, contained fewer than 3 sections');\r\n return null;\r\n }\r\n try {\r\n const decoded = base64Decode(payload);\r\n if (!decoded) {\r\n _logError('Failed to decode base64 JWT payload');\r\n return null;\r\n }\r\n return JSON.parse(decoded);\r\n }\r\n catch (e) {\r\n _logError('Caught error parsing JWT payload as JSON', e);\r\n return null;\r\n }\r\n}\r\n/**\r\n * Extract expiresIn TTL from a token by subtracting the expiration from the issuance.\r\n */\r\nfunction _tokenExpiresIn(token) {\r\n const parsedToken = _parseToken(token);\r\n _assert(parsedToken, \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.exp !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof parsedToken.iat !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n return Number(parsedToken.exp) - Number(parsedToken.iat);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _logoutIfInvalidated(user, promise, bypassAuthState = false) {\r\n if (bypassAuthState) {\r\n return promise;\r\n }\r\n try {\r\n return await promise;\r\n }\r\n catch (e) {\r\n if (e instanceof FirebaseError && isUserInvalidated(e)) {\r\n if (user.auth.currentUser === user) {\r\n await user.auth.signOut();\r\n }\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isUserInvalidated({ code }) {\r\n return (code === `auth/${\"user-disabled\" /* USER_DISABLED */}` ||\r\n code === `auth/${\"user-token-expired\" /* TOKEN_EXPIRED */}`);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ProactiveRefresh {\r\n constructor(user) {\r\n this.user = user;\r\n this.isRunning = false;\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.timerId = null;\r\n this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;\r\n }\r\n _start() {\r\n if (this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = true;\r\n this.schedule();\r\n }\r\n _stop() {\r\n if (!this.isRunning) {\r\n return;\r\n }\r\n this.isRunning = false;\r\n if (this.timerId !== null) {\r\n clearTimeout(this.timerId);\r\n }\r\n }\r\n getInterval(wasError) {\r\n var _a;\r\n if (wasError) {\r\n const interval = this.errorBackoff;\r\n this.errorBackoff = Math.min(this.errorBackoff * 2, 960000 /* RETRY_BACKOFF_MAX */);\r\n return interval;\r\n }\r\n else {\r\n // Reset the error backoff\r\n this.errorBackoff = 30000 /* RETRY_BACKOFF_MIN */;\r\n const expTime = (_a = this.user.stsTokenManager.expirationTime) !== null && _a !== void 0 ? _a : 0;\r\n const interval = expTime - Date.now() - 300000 /* OFFSET */;\r\n return Math.max(0, interval);\r\n }\r\n }\r\n schedule(wasError = false) {\r\n if (!this.isRunning) {\r\n // Just in case...\r\n return;\r\n }\r\n const interval = this.getInterval(wasError);\r\n this.timerId = setTimeout(async () => {\r\n await this.iteration();\r\n }, interval);\r\n }\r\n async iteration() {\r\n try {\r\n await this.user.getIdToken(true);\r\n }\r\n catch (e) {\r\n // Only retry on network errors\r\n if (e.code === `auth/${\"network-request-failed\" /* NETWORK_REQUEST_FAILED */}`) {\r\n this.schedule(/* wasError */ true);\r\n }\r\n return;\r\n }\r\n this.schedule();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserMetadata {\r\n constructor(createdAt, lastLoginAt) {\r\n this.createdAt = createdAt;\r\n this.lastLoginAt = lastLoginAt;\r\n this._initializeTime();\r\n }\r\n _initializeTime() {\r\n this.lastSignInTime = utcTimestampToDateString(this.lastLoginAt);\r\n this.creationTime = utcTimestampToDateString(this.createdAt);\r\n }\r\n _copy(metadata) {\r\n this.createdAt = metadata.createdAt;\r\n this.lastLoginAt = metadata.lastLoginAt;\r\n this._initializeTime();\r\n }\r\n toJSON() {\r\n return {\r\n createdAt: this.createdAt,\r\n lastLoginAt: this.lastLoginAt\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reloadWithoutSaving(user) {\r\n var _a;\r\n const auth = user.auth;\r\n const idToken = await user.getIdToken();\r\n const response = await _logoutIfInvalidated(user, getAccountInfo(auth, { idToken }));\r\n _assert(response === null || response === void 0 ? void 0 : response.users.length, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const coreAccount = response.users[0];\r\n user._notifyReloadListener(coreAccount);\r\n const newProviderData = ((_a = coreAccount.providerUserInfo) === null || _a === void 0 ? void 0 : _a.length)\r\n ? extractProviderData(coreAccount.providerUserInfo)\r\n : [];\r\n const providerData = mergeProviderData(user.providerData, newProviderData);\r\n // Preserves the non-nonymous status of the stored user, even if no more\r\n // credentials (federated or email/password) are linked to the user. If\r\n // the user was previously anonymous, then use provider data to update.\r\n // On the other hand, if it was not anonymous before, it should never be\r\n // considered anonymous now.\r\n const oldIsAnonymous = user.isAnonymous;\r\n const newIsAnonymous = !(user.email && coreAccount.passwordHash) && !(providerData === null || providerData === void 0 ? void 0 : providerData.length);\r\n const isAnonymous = !oldIsAnonymous ? false : newIsAnonymous;\r\n const updates = {\r\n uid: coreAccount.localId,\r\n displayName: coreAccount.displayName || null,\r\n photoURL: coreAccount.photoUrl || null,\r\n email: coreAccount.email || null,\r\n emailVerified: coreAccount.emailVerified || false,\r\n phoneNumber: coreAccount.phoneNumber || null,\r\n tenantId: coreAccount.tenantId || null,\r\n providerData,\r\n metadata: new UserMetadata(coreAccount.createdAt, coreAccount.lastLoginAt),\r\n isAnonymous\r\n };\r\n Object.assign(user, updates);\r\n}\r\n/**\r\n * Reloads user account data, if signed in.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function reload(user) {\r\n const userInternal = getModularInstance(user);\r\n await _reloadWithoutSaving(userInternal);\r\n // Even though the current user hasn't changed, update\r\n // current user will trigger a persistence update w/ the\r\n // new info.\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n userInternal.auth._notifyListenersIfCurrent(userInternal);\r\n}\r\nfunction mergeProviderData(original, newData) {\r\n const deduped = original.filter(o => !newData.some(n => n.providerId === o.providerId));\r\n return [...deduped, ...newData];\r\n}\r\nfunction extractProviderData(providers) {\r\n return providers.map((_a) => {\r\n var { providerId } = _a, provider = __rest(_a, [\"providerId\"]);\r\n return {\r\n providerId,\r\n uid: provider.rawId || '',\r\n displayName: provider.displayName || null,\r\n email: provider.email || null,\r\n phoneNumber: provider.phoneNumber || null,\r\n photoURL: provider.photoUrl || null\r\n };\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function requestStsToken(auth, refreshToken) {\r\n const response = await _performFetchWithErrorHandling(auth, {}, async () => {\r\n const body = querystring({\r\n 'grant_type': 'refresh_token',\r\n 'refresh_token': refreshToken\r\n }).slice(1);\r\n const { tokenApiHost, apiKey } = auth.config;\r\n const url = _getFinalTarget(auth, tokenApiHost, \"/v1/token\" /* TOKEN */, `key=${apiKey}`);\r\n const headers = await auth._getAdditionalHeaders();\r\n headers[\"Content-Type\" /* CONTENT_TYPE */] = 'application/x-www-form-urlencoded';\r\n return FetchProvider.fetch()(url, {\r\n method: \"POST\" /* POST */,\r\n headers,\r\n body\r\n });\r\n });\r\n // The response comes back in snake_case. Convert to camel:\r\n return {\r\n accessToken: response.access_token,\r\n expiresIn: response.expires_in,\r\n refreshToken: response.refresh_token\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * We need to mark this class as internal explicitly to exclude it in the public typings, because\r\n * it references AuthInternal which has a circular dependency with UserInternal.\r\n *\r\n * @internal\r\n */\r\nclass StsTokenManager {\r\n constructor() {\r\n this.refreshToken = null;\r\n this.accessToken = null;\r\n this.expirationTime = null;\r\n }\r\n get isExpired() {\r\n return (!this.expirationTime ||\r\n Date.now() > this.expirationTime - 30000 /* TOKEN_REFRESH */);\r\n }\r\n updateFromServerResponse(response) {\r\n _assert(response.idToken, \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof response.idToken !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof response.refreshToken !== 'undefined', \"internal-error\" /* INTERNAL_ERROR */);\r\n const expiresIn = 'expiresIn' in response && typeof response.expiresIn !== 'undefined'\r\n ? Number(response.expiresIn)\r\n : _tokenExpiresIn(response.idToken);\r\n this.updateTokensAndExpiration(response.idToken, response.refreshToken, expiresIn);\r\n }\r\n async getToken(auth, forceRefresh = false) {\r\n _assert(!this.accessToken || this.refreshToken, auth, \"user-token-expired\" /* TOKEN_EXPIRED */);\r\n if (!forceRefresh && this.accessToken && !this.isExpired) {\r\n return this.accessToken;\r\n }\r\n if (this.refreshToken) {\r\n await this.refresh(auth, this.refreshToken);\r\n return this.accessToken;\r\n }\r\n return null;\r\n }\r\n clearRefreshToken() {\r\n this.refreshToken = null;\r\n }\r\n async refresh(auth, oldToken) {\r\n const { accessToken, refreshToken, expiresIn } = await requestStsToken(auth, oldToken);\r\n this.updateTokensAndExpiration(accessToken, refreshToken, Number(expiresIn));\r\n }\r\n updateTokensAndExpiration(accessToken, refreshToken, expiresInSec) {\r\n this.refreshToken = refreshToken || null;\r\n this.accessToken = accessToken || null;\r\n this.expirationTime = Date.now() + expiresInSec * 1000;\r\n }\r\n static fromJSON(appName, object) {\r\n const { refreshToken, accessToken, expirationTime } = object;\r\n const manager = new StsTokenManager();\r\n if (refreshToken) {\r\n _assert(typeof refreshToken === 'string', \"internal-error\" /* INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.refreshToken = refreshToken;\r\n }\r\n if (accessToken) {\r\n _assert(typeof accessToken === 'string', \"internal-error\" /* INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.accessToken = accessToken;\r\n }\r\n if (expirationTime) {\r\n _assert(typeof expirationTime === 'number', \"internal-error\" /* INTERNAL_ERROR */, {\r\n appName\r\n });\r\n manager.expirationTime = expirationTime;\r\n }\r\n return manager;\r\n }\r\n toJSON() {\r\n return {\r\n refreshToken: this.refreshToken,\r\n accessToken: this.accessToken,\r\n expirationTime: this.expirationTime\r\n };\r\n }\r\n _assign(stsTokenManager) {\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.refreshToken = stsTokenManager.refreshToken;\r\n this.expirationTime = stsTokenManager.expirationTime;\r\n }\r\n _clone() {\r\n return Object.assign(new StsTokenManager(), this.toJSON());\r\n }\r\n _performRefresh() {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction assertStringOrUndefined(assertion, appName) {\r\n _assert(typeof assertion === 'string' || typeof assertion === 'undefined', \"internal-error\" /* INTERNAL_ERROR */, { appName });\r\n}\r\nclass UserImpl {\r\n constructor(_a) {\r\n var { uid, auth, stsTokenManager } = _a, opt = __rest(_a, [\"uid\", \"auth\", \"stsTokenManager\"]);\r\n // For the user object, provider is always Firebase.\r\n this.providerId = \"firebase\" /* FIREBASE */;\r\n this.proactiveRefresh = new ProactiveRefresh(this);\r\n this.reloadUserInfo = null;\r\n this.reloadListener = null;\r\n this.uid = uid;\r\n this.auth = auth;\r\n this.stsTokenManager = stsTokenManager;\r\n this.accessToken = stsTokenManager.accessToken;\r\n this.displayName = opt.displayName || null;\r\n this.email = opt.email || null;\r\n this.emailVerified = opt.emailVerified || false;\r\n this.phoneNumber = opt.phoneNumber || null;\r\n this.photoURL = opt.photoURL || null;\r\n this.isAnonymous = opt.isAnonymous || false;\r\n this.tenantId = opt.tenantId || null;\r\n this.providerData = opt.providerData ? [...opt.providerData] : [];\r\n this.metadata = new UserMetadata(opt.createdAt || undefined, opt.lastLoginAt || undefined);\r\n }\r\n async getIdToken(forceRefresh) {\r\n const accessToken = await _logoutIfInvalidated(this, this.stsTokenManager.getToken(this.auth, forceRefresh));\r\n _assert(accessToken, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n if (this.accessToken !== accessToken) {\r\n this.accessToken = accessToken;\r\n await this.auth._persistUserIfCurrent(this);\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n return accessToken;\r\n }\r\n getIdTokenResult(forceRefresh) {\r\n return getIdTokenResult(this, forceRefresh);\r\n }\r\n reload() {\r\n return reload(this);\r\n }\r\n _assign(user) {\r\n if (this === user) {\r\n return;\r\n }\r\n _assert(this.uid === user.uid, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n this.displayName = user.displayName;\r\n this.photoURL = user.photoURL;\r\n this.email = user.email;\r\n this.emailVerified = user.emailVerified;\r\n this.phoneNumber = user.phoneNumber;\r\n this.isAnonymous = user.isAnonymous;\r\n this.tenantId = user.tenantId;\r\n this.providerData = user.providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n this.metadata._copy(user.metadata);\r\n this.stsTokenManager._assign(user.stsTokenManager);\r\n }\r\n _clone(auth) {\r\n return new UserImpl(Object.assign(Object.assign({}, this), { auth, stsTokenManager: this.stsTokenManager._clone() }));\r\n }\r\n _onReload(callback) {\r\n // There should only ever be one listener, and that is a single instance of MultiFactorUser\r\n _assert(!this.reloadListener, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n this.reloadListener = callback;\r\n if (this.reloadUserInfo) {\r\n this._notifyReloadListener(this.reloadUserInfo);\r\n this.reloadUserInfo = null;\r\n }\r\n }\r\n _notifyReloadListener(userInfo) {\r\n if (this.reloadListener) {\r\n this.reloadListener(userInfo);\r\n }\r\n else {\r\n // If no listener is subscribed yet, save the result so it's available when they do subscribe\r\n this.reloadUserInfo = userInfo;\r\n }\r\n }\r\n _startProactiveRefresh() {\r\n this.proactiveRefresh._start();\r\n }\r\n _stopProactiveRefresh() {\r\n this.proactiveRefresh._stop();\r\n }\r\n async _updateTokensIfNecessary(response, reload = false) {\r\n let tokensRefreshed = false;\r\n if (response.idToken &&\r\n response.idToken !== this.stsTokenManager.accessToken) {\r\n this.stsTokenManager.updateFromServerResponse(response);\r\n tokensRefreshed = true;\r\n }\r\n if (reload) {\r\n await _reloadWithoutSaving(this);\r\n }\r\n await this.auth._persistUserIfCurrent(this);\r\n if (tokensRefreshed) {\r\n this.auth._notifyListenersIfCurrent(this);\r\n }\r\n }\r\n async delete() {\r\n const idToken = await this.getIdToken();\r\n await _logoutIfInvalidated(this, deleteAccount(this.auth, { idToken }));\r\n this.stsTokenManager.clearRefreshToken();\r\n // TODO: Determine if cancellable-promises are necessary to use in this class so that delete()\r\n // cancels pending actions...\r\n return this.auth.signOut();\r\n }\r\n toJSON() {\r\n return Object.assign(Object.assign({ uid: this.uid, email: this.email || undefined, emailVerified: this.emailVerified, displayName: this.displayName || undefined, isAnonymous: this.isAnonymous, photoURL: this.photoURL || undefined, phoneNumber: this.phoneNumber || undefined, tenantId: this.tenantId || undefined, providerData: this.providerData.map(userInfo => (Object.assign({}, userInfo))), stsTokenManager: this.stsTokenManager.toJSON(), \r\n // Redirect event ID must be maintained in case there is a pending\r\n // redirect event.\r\n _redirectEventId: this._redirectEventId }, this.metadata.toJSON()), { \r\n // Required for compatibility with the legacy SDK (go/firebase-auth-sdk-persistence-parsing):\r\n apiKey: this.auth.config.apiKey, appName: this.auth.name });\r\n }\r\n get refreshToken() {\r\n return this.stsTokenManager.refreshToken || '';\r\n }\r\n static _fromJSON(auth, object) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h;\r\n const displayName = (_a = object.displayName) !== null && _a !== void 0 ? _a : undefined;\r\n const email = (_b = object.email) !== null && _b !== void 0 ? _b : undefined;\r\n const phoneNumber = (_c = object.phoneNumber) !== null && _c !== void 0 ? _c : undefined;\r\n const photoURL = (_d = object.photoURL) !== null && _d !== void 0 ? _d : undefined;\r\n const tenantId = (_e = object.tenantId) !== null && _e !== void 0 ? _e : undefined;\r\n const _redirectEventId = (_f = object._redirectEventId) !== null && _f !== void 0 ? _f : undefined;\r\n const createdAt = (_g = object.createdAt) !== null && _g !== void 0 ? _g : undefined;\r\n const lastLoginAt = (_h = object.lastLoginAt) !== null && _h !== void 0 ? _h : undefined;\r\n const { uid, emailVerified, isAnonymous, providerData, stsTokenManager: plainObjectTokenManager } = object;\r\n _assert(uid && plainObjectTokenManager, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const stsTokenManager = StsTokenManager.fromJSON(this.name, plainObjectTokenManager);\r\n _assert(typeof uid === 'string', auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n assertStringOrUndefined(displayName, auth.name);\r\n assertStringOrUndefined(email, auth.name);\r\n _assert(typeof emailVerified === 'boolean', auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n _assert(typeof isAnonymous === 'boolean', auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n assertStringOrUndefined(phoneNumber, auth.name);\r\n assertStringOrUndefined(photoURL, auth.name);\r\n assertStringOrUndefined(tenantId, auth.name);\r\n assertStringOrUndefined(_redirectEventId, auth.name);\r\n assertStringOrUndefined(createdAt, auth.name);\r\n assertStringOrUndefined(lastLoginAt, auth.name);\r\n const user = new UserImpl({\r\n uid,\r\n auth,\r\n email,\r\n emailVerified,\r\n displayName,\r\n isAnonymous,\r\n photoURL,\r\n phoneNumber,\r\n tenantId,\r\n stsTokenManager,\r\n createdAt,\r\n lastLoginAt\r\n });\r\n if (providerData && Array.isArray(providerData)) {\r\n user.providerData = providerData.map(userInfo => (Object.assign({}, userInfo)));\r\n }\r\n if (_redirectEventId) {\r\n user._redirectEventId = _redirectEventId;\r\n }\r\n return user;\r\n }\r\n /**\r\n * Initialize a User from an idToken server response\r\n * @param auth\r\n * @param idTokenResponse\r\n */\r\n static async _fromIdTokenResponse(auth, idTokenResponse, isAnonymous = false) {\r\n const stsTokenManager = new StsTokenManager();\r\n stsTokenManager.updateFromServerResponse(idTokenResponse);\r\n // Initialize the Firebase Auth user.\r\n const user = new UserImpl({\r\n uid: idTokenResponse.localId,\r\n auth,\r\n stsTokenManager,\r\n isAnonymous\r\n });\r\n // Updates the user info and data and resolves with a user instance.\r\n await _reloadWithoutSaving(user);\r\n return user;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass InMemoryPersistence {\r\n constructor() {\r\n this.type = \"NONE\" /* NONE */;\r\n this.storage = {};\r\n }\r\n async _isAvailable() {\r\n return true;\r\n }\r\n async _set(key, value) {\r\n this.storage[key] = value;\r\n }\r\n async _get(key) {\r\n const value = this.storage[key];\r\n return value === undefined ? null : value;\r\n }\r\n async _remove(key) {\r\n delete this.storage[key];\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for in-memory storage since it cannot be shared across windows/workers\r\n return;\r\n }\r\n}\r\nInMemoryPersistence.type = 'NONE';\r\n/**\r\n * An implementation of {@link Persistence} of type 'NONE'.\r\n *\r\n * @public\r\n */\r\nconst inMemoryPersistence = InMemoryPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _persistenceKeyName(key, apiKey, appName) {\r\n return `${\"firebase\" /* PERSISTENCE */}:${key}:${apiKey}:${appName}`;\r\n}\r\nclass PersistenceUserManager {\r\n constructor(persistence, auth, userKey) {\r\n this.persistence = persistence;\r\n this.auth = auth;\r\n this.userKey = userKey;\r\n const { config, name } = this.auth;\r\n this.fullUserKey = _persistenceKeyName(this.userKey, config.apiKey, name);\r\n this.fullPersistenceKey = _persistenceKeyName(\"persistence\" /* PERSISTENCE_USER */, config.apiKey, name);\r\n this.boundEventHandler = auth._onStorageEvent.bind(auth);\r\n this.persistence._addListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n setCurrentUser(user) {\r\n return this.persistence._set(this.fullUserKey, user.toJSON());\r\n }\r\n async getCurrentUser() {\r\n const blob = await this.persistence._get(this.fullUserKey);\r\n return blob ? UserImpl._fromJSON(this.auth, blob) : null;\r\n }\r\n removeCurrentUser() {\r\n return this.persistence._remove(this.fullUserKey);\r\n }\r\n savePersistenceForRedirect() {\r\n return this.persistence._set(this.fullPersistenceKey, this.persistence.type);\r\n }\r\n async setPersistence(newPersistence) {\r\n if (this.persistence === newPersistence) {\r\n return;\r\n }\r\n const currentUser = await this.getCurrentUser();\r\n await this.removeCurrentUser();\r\n this.persistence = newPersistence;\r\n if (currentUser) {\r\n return this.setCurrentUser(currentUser);\r\n }\r\n }\r\n delete() {\r\n this.persistence._removeListener(this.fullUserKey, this.boundEventHandler);\r\n }\r\n static async create(auth, persistenceHierarchy, userKey = \"authUser\" /* AUTH_USER */) {\r\n if (!persistenceHierarchy.length) {\r\n return new PersistenceUserManager(_getInstance(inMemoryPersistence), auth, userKey);\r\n }\r\n // Eliminate any persistences that are not available\r\n const availablePersistences = (await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (await persistence._isAvailable()) {\r\n return persistence;\r\n }\r\n return undefined;\r\n }))).filter(persistence => persistence);\r\n // Fall back to the first persistence listed, or in memory if none available\r\n let selectedPersistence = availablePersistences[0] ||\r\n _getInstance(inMemoryPersistence);\r\n const key = _persistenceKeyName(userKey, auth.config.apiKey, auth.name);\r\n // Pull out the existing user, setting the chosen persistence to that\r\n // persistence if the user exists.\r\n let userToMigrate = null;\r\n // Note, here we check for a user in _all_ persistences, not just the\r\n // ones deemed available. If we can migrate a user out of a broken\r\n // persistence, we will (but only if that persistence supports migration).\r\n for (const persistence of persistenceHierarchy) {\r\n try {\r\n const blob = await persistence._get(key);\r\n if (blob) {\r\n const user = UserImpl._fromJSON(auth, blob); // throws for unparsable blob (wrong format)\r\n if (persistence !== selectedPersistence) {\r\n userToMigrate = user;\r\n }\r\n selectedPersistence = persistence;\r\n break;\r\n }\r\n }\r\n catch (_a) { }\r\n }\r\n // If we find the user in a persistence that does support migration, use\r\n // that migration path (of only persistences that support migration)\r\n const migrationHierarchy = availablePersistences.filter(p => p._shouldAllowMigration);\r\n // If the persistence does _not_ allow migration, just finish off here\r\n if (!selectedPersistence._shouldAllowMigration ||\r\n !migrationHierarchy.length) {\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n selectedPersistence = migrationHierarchy[0];\r\n if (userToMigrate) {\r\n // This normally shouldn't throw since chosenPersistence.isAvailable() is true, but if it does\r\n // we'll just let it bubble to surface the error.\r\n await selectedPersistence._set(key, userToMigrate.toJSON());\r\n }\r\n // Attempt to clear the key in other persistences but ignore errors. This helps prevent issues\r\n // such as users getting stuck with a previous account after signing out and refreshing the tab.\r\n await Promise.all(persistenceHierarchy.map(async (persistence) => {\r\n if (persistence !== selectedPersistence) {\r\n try {\r\n await persistence._remove(key);\r\n }\r\n catch (_a) { }\r\n }\r\n }));\r\n return new PersistenceUserManager(selectedPersistence, auth, userKey);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Determine the browser for the purposes of reporting usage to the API\r\n */\r\nfunction _getBrowserName(userAgent) {\r\n const ua = userAgent.toLowerCase();\r\n if (ua.includes('opera/') || ua.includes('opr/') || ua.includes('opios/')) {\r\n return \"Opera\" /* OPERA */;\r\n }\r\n else if (_isIEMobile(ua)) {\r\n // Windows phone IEMobile browser.\r\n return \"IEMobile\" /* IEMOBILE */;\r\n }\r\n else if (ua.includes('msie') || ua.includes('trident/')) {\r\n return \"IE\" /* IE */;\r\n }\r\n else if (ua.includes('edge/')) {\r\n return \"Edge\" /* EDGE */;\r\n }\r\n else if (_isFirefox(ua)) {\r\n return \"Firefox\" /* FIREFOX */;\r\n }\r\n else if (ua.includes('silk/')) {\r\n return \"Silk\" /* SILK */;\r\n }\r\n else if (_isBlackBerry(ua)) {\r\n // Blackberry browser.\r\n return \"Blackberry\" /* BLACKBERRY */;\r\n }\r\n else if (_isWebOS(ua)) {\r\n // WebOS default browser.\r\n return \"Webos\" /* WEBOS */;\r\n }\r\n else if (_isSafari(ua)) {\r\n return \"Safari\" /* SAFARI */;\r\n }\r\n else if ((ua.includes('chrome/') || _isChromeIOS(ua)) &&\r\n !ua.includes('edge/')) {\r\n return \"Chrome\" /* CHROME */;\r\n }\r\n else if (_isAndroid(ua)) {\r\n // Android stock browser.\r\n return \"Android\" /* ANDROID */;\r\n }\r\n else {\r\n // Most modern browsers have name/version at end of user agent string.\r\n const re = /([a-zA-Z\\d\\.]+)\\/[a-zA-Z\\d\\.]*$/;\r\n const matches = userAgent.match(re);\r\n if ((matches === null || matches === void 0 ? void 0 : matches.length) === 2) {\r\n return matches[1];\r\n }\r\n }\r\n return \"Other\" /* OTHER */;\r\n}\r\nfunction _isFirefox(ua = getUA()) {\r\n return /firefox\\//i.test(ua);\r\n}\r\nfunction _isSafari(userAgent = getUA()) {\r\n const ua = userAgent.toLowerCase();\r\n return (ua.includes('safari/') &&\r\n !ua.includes('chrome/') &&\r\n !ua.includes('crios/') &&\r\n !ua.includes('android'));\r\n}\r\nfunction _isChromeIOS(ua = getUA()) {\r\n return /crios\\//i.test(ua);\r\n}\r\nfunction _isIEMobile(ua = getUA()) {\r\n return /iemobile/i.test(ua);\r\n}\r\nfunction _isAndroid(ua = getUA()) {\r\n return /android/i.test(ua);\r\n}\r\nfunction _isBlackBerry(ua = getUA()) {\r\n return /blackberry/i.test(ua);\r\n}\r\nfunction _isWebOS(ua = getUA()) {\r\n return /webos/i.test(ua);\r\n}\r\nfunction _isIOS(ua = getUA()) {\r\n return /iphone|ipad|ipod/i.test(ua);\r\n}\r\nfunction _isIOS7Or8(ua = getUA()) {\r\n return (/(iPad|iPhone|iPod).*OS 7_\\d/i.test(ua) ||\r\n /(iPad|iPhone|iPod).*OS 8_\\d/i.test(ua));\r\n}\r\nfunction _isIOSStandalone(ua = getUA()) {\r\n var _a;\r\n return _isIOS(ua) && !!((_a = window.navigator) === null || _a === void 0 ? void 0 : _a.standalone);\r\n}\r\nfunction _isIE10() {\r\n return isIE() && document.documentMode === 10;\r\n}\r\nfunction _isMobileBrowser(ua = getUA()) {\r\n // TODO: implement getBrowserName equivalent for OS.\r\n return (_isIOS(ua) ||\r\n _isAndroid(ua) ||\r\n _isWebOS(ua) ||\r\n _isBlackBerry(ua) ||\r\n /windows phone/i.test(ua) ||\r\n _isIEMobile(ua));\r\n}\r\nfunction _isIframe() {\r\n try {\r\n // Check that the current window is not the top window.\r\n // If so, return true.\r\n return !!(window && window !== window.top);\r\n }\r\n catch (e) {\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/*\r\n * Determine the SDK version string\r\n */\r\nfunction _getClientVersion(clientPlatform, frameworks = []) {\r\n let reportedPlatform;\r\n switch (clientPlatform) {\r\n case \"Browser\" /* BROWSER */:\r\n // In a browser environment, report the browser name.\r\n reportedPlatform = _getBrowserName(getUA());\r\n break;\r\n case \"Worker\" /* WORKER */:\r\n // Technically a worker runs from a browser but we need to differentiate a\r\n // worker from a browser.\r\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\r\n reportedPlatform = `${_getBrowserName(getUA())}-${clientPlatform}`;\r\n break;\r\n default:\r\n reportedPlatform = clientPlatform;\r\n }\r\n const reportedFrameworks = frameworks.length\r\n ? frameworks.join(',')\r\n : 'FirebaseCore-web'; /* default value if no other framework is used */\r\n return `${reportedPlatform}/${\"JsCore\" /* CORE */}/${SDK_VERSION}/${reportedFrameworks}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthImpl {\r\n constructor(app, heartbeatServiceProvider, config) {\r\n this.app = app;\r\n this.heartbeatServiceProvider = heartbeatServiceProvider;\r\n this.config = config;\r\n this.currentUser = null;\r\n this.emulatorConfig = null;\r\n this.operations = Promise.resolve();\r\n this.authStateSubscription = new Subscription(this);\r\n this.idTokenSubscription = new Subscription(this);\r\n this.redirectUser = null;\r\n this.isProactiveRefreshEnabled = false;\r\n // Any network calls will set this to true and prevent subsequent emulator\r\n // initialization\r\n this._canInitEmulator = true;\r\n this._isInitialized = false;\r\n this._deleted = false;\r\n this._initializationPromise = null;\r\n this._popupRedirectResolver = null;\r\n this._errorFactory = _DEFAULT_AUTH_ERROR_FACTORY;\r\n // Tracks the last notified UID for state change listeners to prevent\r\n // repeated calls to the callbacks. Undefined means it's never been\r\n // called, whereas null means it's been called with a signed out user\r\n this.lastNotifiedUid = undefined;\r\n this.languageCode = null;\r\n this.tenantId = null;\r\n this.settings = { appVerificationDisabledForTesting: false };\r\n this.frameworks = [];\r\n this.name = app.name;\r\n this.clientVersion = config.sdkClientVersion;\r\n }\r\n _initializeWithPersistence(persistenceHierarchy, popupRedirectResolver) {\r\n if (popupRedirectResolver) {\r\n this._popupRedirectResolver = _getInstance(popupRedirectResolver);\r\n }\r\n // Have to check for app deletion throughout initialization (after each\r\n // promise resolution)\r\n this._initializationPromise = this.queue(async () => {\r\n var _a, _b;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this.persistenceManager = await PersistenceUserManager.create(this, persistenceHierarchy);\r\n if (this._deleted) {\r\n return;\r\n }\r\n // Initialize the resolver early if necessary (only applicable to web:\r\n // this will cause the iframe to load immediately in certain cases)\r\n if ((_a = this._popupRedirectResolver) === null || _a === void 0 ? void 0 : _a._shouldInitProactively) {\r\n // If this fails, don't halt auth loading\r\n try {\r\n await this._popupRedirectResolver._initialize(this);\r\n }\r\n catch (e) { /* Ignore the error */ }\r\n }\r\n await this.initializeCurrentUser(popupRedirectResolver);\r\n this.lastNotifiedUid = ((_b = this.currentUser) === null || _b === void 0 ? void 0 : _b.uid) || null;\r\n if (this._deleted) {\r\n return;\r\n }\r\n this._isInitialized = true;\r\n });\r\n return this._initializationPromise;\r\n }\r\n /**\r\n * If the persistence is changed in another window, the user manager will let us know\r\n */\r\n async _onStorageEvent() {\r\n if (this._deleted) {\r\n return;\r\n }\r\n const user = await this.assertedPersistence.getCurrentUser();\r\n if (!this.currentUser && !user) {\r\n // No change, do nothing (was signed out and remained signed out).\r\n return;\r\n }\r\n // If the same user is to be synchronized.\r\n if (this.currentUser && user && this.currentUser.uid === user.uid) {\r\n // Data update, simply copy data changes.\r\n this._currentUser._assign(user);\r\n // If tokens changed from previous user tokens, this will trigger\r\n // notifyAuthListeners_.\r\n await this.currentUser.getIdToken();\r\n return;\r\n }\r\n // Update current Auth state. Either a new login or logout.\r\n await this._updateCurrentUser(user);\r\n }\r\n async initializeCurrentUser(popupRedirectResolver) {\r\n var _a;\r\n // First check to see if we have a pending redirect event.\r\n let storedUser = (await this.assertedPersistence.getCurrentUser());\r\n if (popupRedirectResolver && this.config.authDomain) {\r\n await this.getOrInitRedirectPersistenceManager();\r\n const redirectUserEventId = (_a = this.redirectUser) === null || _a === void 0 ? void 0 : _a._redirectEventId;\r\n const storedUserEventId = storedUser === null || storedUser === void 0 ? void 0 : storedUser._redirectEventId;\r\n const result = await this.tryRedirectSignIn(popupRedirectResolver);\r\n // If the stored user (i.e. the old \"currentUser\") has a redirectId that\r\n // matches the redirect user, then we want to initially sign in with the\r\n // new user object from result.\r\n // TODO(samgho): More thoroughly test all of this\r\n if ((!redirectUserEventId || redirectUserEventId === storedUserEventId) &&\r\n (result === null || result === void 0 ? void 0 : result.user)) {\r\n storedUser = result.user;\r\n }\r\n }\r\n // If no user in persistence, there is no current user. Set to null.\r\n if (!storedUser) {\r\n return this.directlySetCurrentUser(null);\r\n }\r\n if (!storedUser._redirectEventId) {\r\n // This isn't a redirect user, we can reload and bail\r\n // This will also catch the redirected user, if available, as that method\r\n // strips the _redirectEventId\r\n return this.reloadAndSetCurrentUserOrClear(storedUser);\r\n }\r\n _assert(this._popupRedirectResolver, this, \"argument-error\" /* ARGUMENT_ERROR */);\r\n await this.getOrInitRedirectPersistenceManager();\r\n // If the redirect user's event ID matches the current user's event ID,\r\n // DO NOT reload the current user, otherwise they'll be cleared from storage.\r\n // This is important for the reauthenticateWithRedirect() flow.\r\n if (this.redirectUser &&\r\n this.redirectUser._redirectEventId === storedUser._redirectEventId) {\r\n return this.directlySetCurrentUser(storedUser);\r\n }\r\n return this.reloadAndSetCurrentUserOrClear(storedUser);\r\n }\r\n async tryRedirectSignIn(redirectResolver) {\r\n // The redirect user needs to be checked (and signed in if available)\r\n // during auth initialization. All of the normal sign in and link/reauth\r\n // flows call back into auth and push things onto the promise queue. We\r\n // need to await the result of the redirect sign in *inside the promise\r\n // queue*. This presents a problem: we run into deadlock. See:\r\n // ┌> [Initialization] ─────┐\r\n // ┌> [] │\r\n // └─ [getRedirectResult] <─┘\r\n // where [] are tasks on the queue and arrows denote awaits\r\n // Initialization will never complete because it's waiting on something\r\n // that's waiting for initialization to complete!\r\n //\r\n // Instead, this method calls getRedirectResult() (stored in\r\n // _completeRedirectFn) with an optional parameter that instructs all of\r\n // the underlying auth operations to skip anything that mutates auth state.\r\n let result = null;\r\n try {\r\n // We know this._popupRedirectResolver is set since redirectResolver\r\n // is passed in. The _completeRedirectFn expects the unwrapped extern.\r\n result = await this._popupRedirectResolver._completeRedirectFn(this, redirectResolver, true);\r\n }\r\n catch (e) {\r\n // Swallow any errors here; the code can retrieve them in\r\n // getRedirectResult().\r\n await this._setRedirectUser(null);\r\n }\r\n return result;\r\n }\r\n async reloadAndSetCurrentUserOrClear(user) {\r\n try {\r\n await _reloadWithoutSaving(user);\r\n }\r\n catch (e) {\r\n if (e.code !== `auth/${\"network-request-failed\" /* NETWORK_REQUEST_FAILED */}`) {\r\n // Something's wrong with the user's token. Log them out and remove\r\n // them from storage\r\n return this.directlySetCurrentUser(null);\r\n }\r\n }\r\n return this.directlySetCurrentUser(user);\r\n }\r\n useDeviceLanguage() {\r\n this.languageCode = _getUserLanguage();\r\n }\r\n async _delete() {\r\n this._deleted = true;\r\n }\r\n async updateCurrentUser(userExtern) {\r\n // The public updateCurrentUser method needs to make a copy of the user,\r\n // and also check that the project matches\r\n const user = userExtern\r\n ? getModularInstance(userExtern)\r\n : null;\r\n if (user) {\r\n _assert(user.auth.config.apiKey === this.config.apiKey, this, \"invalid-user-token\" /* INVALID_AUTH */);\r\n }\r\n return this._updateCurrentUser(user && user._clone(this));\r\n }\r\n async _updateCurrentUser(user) {\r\n if (this._deleted) {\r\n return;\r\n }\r\n if (user) {\r\n _assert(this.tenantId === user.tenantId, this, \"tenant-id-mismatch\" /* TENANT_ID_MISMATCH */);\r\n }\r\n return this.queue(async () => {\r\n await this.directlySetCurrentUser(user);\r\n this.notifyAuthListeners();\r\n });\r\n }\r\n async signOut() {\r\n // Clear the redirect user when signOut is called\r\n if (this.redirectPersistenceManager || this._popupRedirectResolver) {\r\n await this._setRedirectUser(null);\r\n }\r\n return this._updateCurrentUser(null);\r\n }\r\n setPersistence(persistence) {\r\n return this.queue(async () => {\r\n await this.assertedPersistence.setPersistence(_getInstance(persistence));\r\n });\r\n }\r\n _getPersistence() {\r\n return this.assertedPersistence.persistence.type;\r\n }\r\n _updateErrorMap(errorMap) {\r\n this._errorFactory = new ErrorFactory('auth', 'Firebase', errorMap());\r\n }\r\n onAuthStateChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.authStateSubscription, nextOrObserver, error, completed);\r\n }\r\n onIdTokenChanged(nextOrObserver, error, completed) {\r\n return this.registerStateListener(this.idTokenSubscription, nextOrObserver, error, completed);\r\n }\r\n toJSON() {\r\n var _a;\r\n return {\r\n apiKey: this.config.apiKey,\r\n authDomain: this.config.authDomain,\r\n appName: this.name,\r\n currentUser: (_a = this._currentUser) === null || _a === void 0 ? void 0 : _a.toJSON()\r\n };\r\n }\r\n async _setRedirectUser(user, popupRedirectResolver) {\r\n const redirectManager = await this.getOrInitRedirectPersistenceManager(popupRedirectResolver);\r\n return user === null\r\n ? redirectManager.removeCurrentUser()\r\n : redirectManager.setCurrentUser(user);\r\n }\r\n async getOrInitRedirectPersistenceManager(popupRedirectResolver) {\r\n if (!this.redirectPersistenceManager) {\r\n const resolver = (popupRedirectResolver && _getInstance(popupRedirectResolver)) ||\r\n this._popupRedirectResolver;\r\n _assert(resolver, this, \"argument-error\" /* ARGUMENT_ERROR */);\r\n this.redirectPersistenceManager = await PersistenceUserManager.create(this, [_getInstance(resolver._redirectPersistence)], \"redirectUser\" /* REDIRECT_USER */);\r\n this.redirectUser =\r\n await this.redirectPersistenceManager.getCurrentUser();\r\n }\r\n return this.redirectPersistenceManager;\r\n }\r\n async _redirectUserForId(id) {\r\n var _a, _b;\r\n // Make sure we've cleared any pending persistence actions if we're not in\r\n // the initializer\r\n if (this._isInitialized) {\r\n await this.queue(async () => { });\r\n }\r\n if (((_a = this._currentUser) === null || _a === void 0 ? void 0 : _a._redirectEventId) === id) {\r\n return this._currentUser;\r\n }\r\n if (((_b = this.redirectUser) === null || _b === void 0 ? void 0 : _b._redirectEventId) === id) {\r\n return this.redirectUser;\r\n }\r\n return null;\r\n }\r\n async _persistUserIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n return this.queue(async () => this.directlySetCurrentUser(user));\r\n }\r\n }\r\n /** Notifies listeners only if the user is current */\r\n _notifyListenersIfCurrent(user) {\r\n if (user === this.currentUser) {\r\n this.notifyAuthListeners();\r\n }\r\n }\r\n _key() {\r\n return `${this.config.authDomain}:${this.config.apiKey}:${this.name}`;\r\n }\r\n _startProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = true;\r\n if (this.currentUser) {\r\n this._currentUser._startProactiveRefresh();\r\n }\r\n }\r\n _stopProactiveRefresh() {\r\n this.isProactiveRefreshEnabled = false;\r\n if (this.currentUser) {\r\n this._currentUser._stopProactiveRefresh();\r\n }\r\n }\r\n /** Returns the current user cast as the internal type */\r\n get _currentUser() {\r\n return this.currentUser;\r\n }\r\n notifyAuthListeners() {\r\n var _a, _b;\r\n if (!this._isInitialized) {\r\n return;\r\n }\r\n this.idTokenSubscription.next(this.currentUser);\r\n const currentUid = (_b = (_a = this.currentUser) === null || _a === void 0 ? void 0 : _a.uid) !== null && _b !== void 0 ? _b : null;\r\n if (this.lastNotifiedUid !== currentUid) {\r\n this.lastNotifiedUid = currentUid;\r\n this.authStateSubscription.next(this.currentUser);\r\n }\r\n }\r\n registerStateListener(subscription, nextOrObserver, error, completed) {\r\n if (this._deleted) {\r\n return () => { };\r\n }\r\n const cb = typeof nextOrObserver === 'function'\r\n ? nextOrObserver\r\n : nextOrObserver.next.bind(nextOrObserver);\r\n const promise = this._isInitialized\r\n ? Promise.resolve()\r\n : this._initializationPromise;\r\n _assert(promise, this, \"internal-error\" /* INTERNAL_ERROR */);\r\n // The callback needs to be called asynchronously per the spec.\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n promise.then(() => cb(this.currentUser));\r\n if (typeof nextOrObserver === 'function') {\r\n return subscription.addObserver(nextOrObserver, error, completed);\r\n }\r\n else {\r\n return subscription.addObserver(nextOrObserver);\r\n }\r\n }\r\n /**\r\n * Unprotected (from race conditions) method to set the current user. This\r\n * should only be called from within a queued callback. This is necessary\r\n * because the queue shouldn't rely on another queued callback.\r\n */\r\n async directlySetCurrentUser(user) {\r\n if (this.currentUser && this.currentUser !== user) {\r\n this._currentUser._stopProactiveRefresh();\r\n if (user && this.isProactiveRefreshEnabled) {\r\n user._startProactiveRefresh();\r\n }\r\n }\r\n this.currentUser = user;\r\n if (user) {\r\n await this.assertedPersistence.setCurrentUser(user);\r\n }\r\n else {\r\n await this.assertedPersistence.removeCurrentUser();\r\n }\r\n }\r\n queue(action) {\r\n // In case something errors, the callback still should be called in order\r\n // to keep the promise chain alive\r\n this.operations = this.operations.then(action, action);\r\n return this.operations;\r\n }\r\n get assertedPersistence() {\r\n _assert(this.persistenceManager, this, \"internal-error\" /* INTERNAL_ERROR */);\r\n return this.persistenceManager;\r\n }\r\n _logFramework(framework) {\r\n if (!framework || this.frameworks.includes(framework)) {\r\n return;\r\n }\r\n this.frameworks.push(framework);\r\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\r\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\r\n this.frameworks.sort();\r\n this.clientVersion = _getClientVersion(this.config.clientPlatform, this._getFrameworks());\r\n }\r\n _getFrameworks() {\r\n return this.frameworks;\r\n }\r\n async _getAdditionalHeaders() {\r\n var _a;\r\n // Additional headers on every request\r\n const headers = {\r\n [\"X-Client-Version\" /* X_CLIENT_VERSION */]: this.clientVersion,\r\n };\r\n if (this.app.options.appId) {\r\n headers[\"X-Firebase-gmpid\" /* X_FIREBASE_GMPID */] = this.app.options.appId;\r\n }\r\n // If the heartbeat service exists, add the heartbeat string\r\n const heartbeatsHeader = await ((_a = this.heartbeatServiceProvider.getImmediate({\r\n optional: true,\r\n })) === null || _a === void 0 ? void 0 : _a.getHeartbeatsHeader());\r\n if (heartbeatsHeader) {\r\n headers[\"X-Firebase-Client\" /* X_FIREBASE_CLIENT */] = heartbeatsHeader;\r\n }\r\n return headers;\r\n }\r\n}\r\n/**\r\n * Method to be used to cast down to our private implmentation of Auth.\r\n * It will also handle unwrapping from the compat type if necessary\r\n *\r\n * @param auth Auth object passed in from developer\r\n */\r\nfunction _castAuth(auth) {\r\n return getModularInstance(auth);\r\n}\r\n/** Helper class to wrap subscriber logic */\r\nclass Subscription {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.observer = null;\r\n this.addObserver = createSubscribe(observer => (this.observer = observer));\r\n }\r\n get next() {\r\n _assert(this.observer, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n return this.observer.next.bind(this.observer);\r\n }\r\n}\n\n/**\r\n * Changes the {@link Auth} instance to communicate with the Firebase Auth Emulator, instead of production\r\n * Firebase Auth services.\r\n *\r\n * @remarks\r\n * This must be called synchronously immediately following the first call to\r\n * {@link initializeAuth}. Do not use with production credentials as emulator\r\n * traffic is not encrypted.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * connectAuthEmulator(auth, 'http://127.0.0.1:9099', { disableWarnings: true });\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param url - The URL at which the emulator is running (eg, 'http://localhost:9099').\r\n * @param options - Optional. `options.disableWarnings` defaults to `false`. Set it to\r\n * `true` to disable the warning banner attached to the DOM.\r\n *\r\n * @public\r\n */\r\nfunction connectAuthEmulator(auth, url, options) {\r\n const authInternal = _castAuth(auth);\r\n _assert(authInternal._canInitEmulator, authInternal, \"emulator-config-failed\" /* EMULATOR_CONFIG_FAILED */);\r\n _assert(/^https?:\\/\\//.test(url), authInternal, \"invalid-emulator-scheme\" /* INVALID_EMULATOR_SCHEME */);\r\n const disableWarnings = !!(options === null || options === void 0 ? void 0 : options.disableWarnings);\r\n const protocol = extractProtocol(url);\r\n const { host, port } = extractHostAndPort(url);\r\n const portStr = port === null ? '' : `:${port}`;\r\n // Always replace path with \"/\" (even if input url had no path at all, or had a different one).\r\n authInternal.config.emulator = { url: `${protocol}//${host}${portStr}/` };\r\n authInternal.settings.appVerificationDisabledForTesting = true;\r\n authInternal.emulatorConfig = Object.freeze({\r\n host,\r\n port,\r\n protocol: protocol.replace(':', ''),\r\n options: Object.freeze({ disableWarnings })\r\n });\r\n if (!disableWarnings) {\r\n emitEmulatorWarning();\r\n }\r\n}\r\nfunction extractProtocol(url) {\r\n const protocolEnd = url.indexOf(':');\r\n return protocolEnd < 0 ? '' : url.substr(0, protocolEnd + 1);\r\n}\r\nfunction extractHostAndPort(url) {\r\n const protocol = extractProtocol(url);\r\n const authority = /(\\/\\/)?([^?#/]+)/.exec(url.substr(protocol.length)); // Between // and /, ? or #.\r\n if (!authority) {\r\n return { host: '', port: null };\r\n }\r\n const hostAndPort = authority[2].split('@').pop() || ''; // Strip out \"username:password@\".\r\n const bracketedIPv6 = /^(\\[[^\\]]+\\])(:|$)/.exec(hostAndPort);\r\n if (bracketedIPv6) {\r\n const host = bracketedIPv6[1];\r\n return { host, port: parsePort(hostAndPort.substr(host.length + 1)) };\r\n }\r\n else {\r\n const [host, port] = hostAndPort.split(':');\r\n return { host, port: parsePort(port) };\r\n }\r\n}\r\nfunction parsePort(portStr) {\r\n if (!portStr) {\r\n return null;\r\n }\r\n const port = Number(portStr);\r\n if (isNaN(port)) {\r\n return null;\r\n }\r\n return port;\r\n}\r\nfunction emitEmulatorWarning() {\r\n function attachBanner() {\r\n const el = document.createElement('p');\r\n const sty = el.style;\r\n el.innerText =\r\n 'Running in emulator mode. Do not use with production credentials.';\r\n sty.position = 'fixed';\r\n sty.width = '100%';\r\n sty.backgroundColor = '#ffffff';\r\n sty.border = '.1em solid #000000';\r\n sty.color = '#b50000';\r\n sty.bottom = '0px';\r\n sty.left = '0px';\r\n sty.margin = '0px';\r\n sty.zIndex = '10000';\r\n sty.textAlign = 'center';\r\n el.classList.add('firebase-emulator-warning');\r\n document.body.appendChild(el);\r\n }\r\n if (typeof console !== 'undefined' && typeof console.info === 'function') {\r\n console.info('WARNING: You are using the Auth Emulator,' +\r\n ' which is intended for local testing only. Do not use with' +\r\n ' production credentials.');\r\n }\r\n if (typeof window !== 'undefined' &&\r\n typeof document !== 'undefined') {\r\n if (document.readyState === 'loading') {\r\n window.addEventListener('DOMContentLoaded', attachBanner);\r\n }\r\n else {\r\n attachBanner();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by an {@link AuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /**\r\n * The authentication provider ID for the credential.\r\n *\r\n * @remarks\r\n * For example, 'facebook.com', or 'google.com'.\r\n */\r\n providerId, \r\n /**\r\n * The authentication sign in method for the credential.\r\n *\r\n * @remarks\r\n * For example, {@link SignInMethod}.EMAIL_PASSWORD, or\r\n * {@link SignInMethod}.EMAIL_LINK. This corresponds to the sign-in method\r\n * identifier as returned in {@link fetchSignInMethodsForEmail}.\r\n */\r\n signInMethod) {\r\n this.providerId = providerId;\r\n this.signInMethod = signInMethod;\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n *\r\n * @returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _linkToIdToken(_auth, _idToken) {\r\n return debugFail('not implemented');\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(_auth) {\r\n return debugFail('not implemented');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function resetPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:resetPassword\" /* RESET_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function updateEmailPassword(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:update\" /* SET_ACCOUNT_INFO */, request);\r\n}\r\nasync function applyActionCode$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:update\" /* SET_ACCOUNT_INFO */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithPassword(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithPassword\" /* SIGN_IN_WITH_PASSWORD */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendOobCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:sendOobCode\" /* SEND_OOB_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function sendEmailVerification$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendPasswordResetEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function sendSignInLinkToEmail$1(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\r\nasync function verifyAndChangeEmail(auth, request) {\r\n return sendOobCode(auth, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithEmailLink$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithEmailLink\" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithEmailLinkForLinking(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithEmailLink\" /* SIGN_IN_WITH_EMAIL_LINK */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface that represents the credentials returned by {@link EmailAuthProvider} for\r\n * {@link ProviderId}.PASSWORD\r\n *\r\n * @remarks\r\n * Covers both {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(\r\n /** @internal */\r\n _email, \r\n /** @internal */\r\n _password, signInMethod, \r\n /** @internal */\r\n _tenantId = null) {\r\n super(\"password\" /* PASSWORD */, signInMethod);\r\n this._email = _email;\r\n this._password = _password;\r\n this._tenantId = _tenantId;\r\n }\r\n /** @internal */\r\n static _fromEmailAndPassword(email, password) {\r\n return new EmailAuthCredential(email, password, \"password\" /* EMAIL_PASSWORD */);\r\n }\r\n /** @internal */\r\n static _fromEmailAndCode(email, oobCode, tenantId = null) {\r\n return new EmailAuthCredential(email, oobCode, \"emailLink\" /* EMAIL_LINK */, tenantId);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n email: this._email,\r\n password: this._password,\r\n signInMethod: this.signInMethod,\r\n tenantId: this._tenantId\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an {@link AuthCredential}.\r\n *\r\n * @param json - Either `object` or the stringified representation of the object. When string is\r\n * provided, `JSON.parse` would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n if ((obj === null || obj === void 0 ? void 0 : obj.email) && (obj === null || obj === void 0 ? void 0 : obj.password)) {\r\n if (obj.signInMethod === \"password\" /* EMAIL_PASSWORD */) {\r\n return this._fromEmailAndPassword(obj.email, obj.password);\r\n }\r\n else if (obj.signInMethod === \"emailLink\" /* EMAIL_LINK */) {\r\n return this._fromEmailAndCode(obj.email, obj.password, obj.tenantId);\r\n }\r\n }\r\n return null;\r\n }\r\n /** @internal */\r\n async _getIdTokenResponse(auth) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* EMAIL_PASSWORD */:\r\n return signInWithPassword(auth, {\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password\r\n });\r\n case \"emailLink\" /* EMAIL_LINK */:\r\n return signInWithEmailLink$1(auth, {\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n async _linkToIdToken(auth, idToken) {\r\n switch (this.signInMethod) {\r\n case \"password\" /* EMAIL_PASSWORD */:\r\n return updateEmailPassword(auth, {\r\n idToken,\r\n returnSecureToken: true,\r\n email: this._email,\r\n password: this._password\r\n });\r\n case \"emailLink\" /* EMAIL_LINK */:\r\n return signInWithEmailLinkForLinking(auth, {\r\n idToken,\r\n email: this._email,\r\n oobCode: this._password\r\n });\r\n default:\r\n _fail(auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n }\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return this._getIdTokenResponse(auth);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithIdp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithIdp\" /* SIGN_IN_WITH_IDP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI$1 = 'http://localhost';\r\n/**\r\n * Represents the OAuth credentials returned by an {@link OAuthProvider}.\r\n *\r\n * @remarks\r\n * Implementations specify the details about each auth provider's credential requirements.\r\n *\r\n * @public\r\n */\r\nclass OAuthCredential extends AuthCredential {\r\n constructor() {\r\n super(...arguments);\r\n this.pendingToken = null;\r\n }\r\n /** @internal */\r\n static _fromParams(params) {\r\n const cred = new OAuthCredential(params.providerId, params.signInMethod);\r\n if (params.idToken || params.accessToken) {\r\n // OAuth 2 and either ID token or access token.\r\n if (params.idToken) {\r\n cred.idToken = params.idToken;\r\n }\r\n if (params.accessToken) {\r\n cred.accessToken = params.accessToken;\r\n }\r\n // Add nonce if available and no pendingToken is present.\r\n if (params.nonce && !params.pendingToken) {\r\n cred.nonce = params.nonce;\r\n }\r\n if (params.pendingToken) {\r\n cred.pendingToken = params.pendingToken;\r\n }\r\n }\r\n else if (params.oauthToken && params.oauthTokenSecret) {\r\n // OAuth 1 and OAuth token with token secret\r\n cred.accessToken = params.oauthToken;\r\n cred.secret = params.oauthTokenSecret;\r\n }\r\n else {\r\n _fail(\"argument-error\" /* ARGUMENT_ERROR */);\r\n }\r\n return cred;\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n idToken: this.idToken,\r\n accessToken: this.accessToken,\r\n secret: this.secret,\r\n nonce: this.nonce,\r\n pendingToken: this.pendingToken,\r\n providerId: this.providerId,\r\n signInMethod: this.signInMethod\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod } = obj, rest = __rest(obj, [\"providerId\", \"signInMethod\"]);\r\n if (!providerId || !signInMethod) {\r\n return null;\r\n }\r\n const cred = new OAuthCredential(providerId, signInMethod);\r\n cred.idToken = rest.idToken || undefined;\r\n cred.accessToken = rest.accessToken || undefined;\r\n cred.secret = rest.secret;\r\n cred.nonce = rest.nonce;\r\n cred.pendingToken = rest.pendingToken || null;\r\n return cred;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n buildRequest() {\r\n const request = {\r\n requestUri: IDP_REQUEST_URI$1,\r\n returnSecureToken: true\r\n };\r\n if (this.pendingToken) {\r\n request.pendingToken = this.pendingToken;\r\n }\r\n else {\r\n const postBody = {};\r\n if (this.idToken) {\r\n postBody['id_token'] = this.idToken;\r\n }\r\n if (this.accessToken) {\r\n postBody['access_token'] = this.accessToken;\r\n }\r\n if (this.secret) {\r\n postBody['oauth_token_secret'] = this.secret;\r\n }\r\n postBody['providerId'] = this.providerId;\r\n if (this.nonce && !this.pendingToken) {\r\n postBody['nonce'] = this.nonce;\r\n }\r\n request.postBody = querystring(postBody);\r\n }\r\n return request;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function sendPhoneVerificationCode(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:sendVerificationCode\" /* SEND_VERIFICATION_CODE */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function signInWithPhoneNumber$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithPhoneNumber\" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n}\r\nasync function linkWithPhoneNumber$1(auth, request) {\r\n const response = await _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithPhoneNumber\" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, request));\r\n if (response.temporaryProof) {\r\n throw _makeTaggedError(auth, \"account-exists-with-different-credential\" /* NEED_CONFIRMATION */, response);\r\n }\r\n return response;\r\n}\r\nconst VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_ = {\r\n [\"USER_NOT_FOUND\" /* USER_NOT_FOUND */]: \"user-not-found\" /* USER_DELETED */\r\n};\r\nasync function verifyPhoneNumberForExisting(auth, request) {\r\n const apiRequest = Object.assign(Object.assign({}, request), { operation: 'REAUTH' });\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithPhoneNumber\" /* SIGN_IN_WITH_PHONE_NUMBER */, _addTidIfNecessary(auth, apiRequest), VERIFY_PHONE_NUMBER_FOR_EXISTING_ERROR_MAP_);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Represents the credentials returned by {@link PhoneAuthProvider}.\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"phone\" /* PHONE */, \"phone\" /* PHONE */);\r\n this.params = params;\r\n }\r\n /** @internal */\r\n static _fromVerification(verificationId, verificationCode) {\r\n return new PhoneAuthCredential({ verificationId, verificationCode });\r\n }\r\n /** @internal */\r\n static _fromTokenResponse(phoneNumber, temporaryProof) {\r\n return new PhoneAuthCredential({ phoneNumber, temporaryProof });\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n return signInWithPhoneNumber$1(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n return linkWithPhoneNumber$1(auth, Object.assign({ idToken }, this._makeVerificationRequest()));\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n return verifyPhoneNumberForExisting(auth, this._makeVerificationRequest());\r\n }\r\n /** @internal */\r\n _makeVerificationRequest() {\r\n const { temporaryProof, phoneNumber, verificationId, verificationCode } = this.params;\r\n if (temporaryProof && phoneNumber) {\r\n return { temporaryProof, phoneNumber };\r\n }\r\n return {\r\n sessionInfo: verificationId,\r\n code: verificationCode\r\n };\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n const obj = {\r\n providerId: this.providerId\r\n };\r\n if (this.params.phoneNumber) {\r\n obj.phoneNumber = this.params.phoneNumber;\r\n }\r\n if (this.params.temporaryProof) {\r\n obj.temporaryProof = this.params.temporaryProof;\r\n }\r\n if (this.params.verificationCode) {\r\n obj.verificationCode = this.params.verificationCode;\r\n }\r\n if (this.params.verificationId) {\r\n obj.verificationId = this.params.verificationId;\r\n }\r\n return obj;\r\n }\r\n /** Generates a phone credential based on a plain object or a JSON string. */\r\n static fromJSON(json) {\r\n if (typeof json === 'string') {\r\n json = JSON.parse(json);\r\n }\r\n const { verificationId, verificationCode, phoneNumber, temporaryProof } = json;\r\n if (!verificationCode &&\r\n !verificationId &&\r\n !phoneNumber &&\r\n !temporaryProof) {\r\n return null;\r\n }\r\n return new PhoneAuthCredential({\r\n verificationId,\r\n verificationCode,\r\n phoneNumber,\r\n temporaryProof\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Maps the mode string in action code URL to Action Code Info operation.\r\n *\r\n * @param mode\r\n */\r\nfunction parseMode(mode) {\r\n switch (mode) {\r\n case 'recoverEmail':\r\n return \"RECOVER_EMAIL\" /* RECOVER_EMAIL */;\r\n case 'resetPassword':\r\n return \"PASSWORD_RESET\" /* PASSWORD_RESET */;\r\n case 'signIn':\r\n return \"EMAIL_SIGNIN\" /* EMAIL_SIGNIN */;\r\n case 'verifyEmail':\r\n return \"VERIFY_EMAIL\" /* VERIFY_EMAIL */;\r\n case 'verifyAndChangeEmail':\r\n return \"VERIFY_AND_CHANGE_EMAIL\" /* VERIFY_AND_CHANGE_EMAIL */;\r\n case 'revertSecondFactorAddition':\r\n return \"REVERT_SECOND_FACTOR_ADDITION\" /* REVERT_SECOND_FACTOR_ADDITION */;\r\n default:\r\n return null;\r\n }\r\n}\r\n/**\r\n * Helper to parse FDL links\r\n *\r\n * @param url\r\n */\r\nfunction parseDeepLink(url) {\r\n const link = querystringDecode(extractQuerystring(url))['link'];\r\n // Double link case (automatic redirect).\r\n const doubleDeepLink = link\r\n ? querystringDecode(extractQuerystring(link))['deep_link_id']\r\n : null;\r\n // iOS custom scheme links.\r\n const iOSDeepLink = querystringDecode(extractQuerystring(url))['deep_link_id'];\r\n const iOSDoubleDeepLink = iOSDeepLink\r\n ? querystringDecode(extractQuerystring(iOSDeepLink))['link']\r\n : null;\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * A utility class to parse email action URLs such as password reset, email verification,\r\n * email link sign in, etc.\r\n *\r\n * @public\r\n */\r\nclass ActionCodeURL {\r\n /**\r\n * @param actionLink - The link from which to extract the URL.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @internal\r\n */\r\n constructor(actionLink) {\r\n var _a, _b, _c, _d, _e, _f;\r\n const searchParams = querystringDecode(extractQuerystring(actionLink));\r\n const apiKey = (_a = searchParams[\"apiKey\" /* API_KEY */]) !== null && _a !== void 0 ? _a : null;\r\n const code = (_b = searchParams[\"oobCode\" /* CODE */]) !== null && _b !== void 0 ? _b : null;\r\n const operation = parseMode((_c = searchParams[\"mode\" /* MODE */]) !== null && _c !== void 0 ? _c : null);\r\n // Validate API key, code and mode.\r\n _assert(apiKey && code && operation, \"argument-error\" /* ARGUMENT_ERROR */);\r\n this.apiKey = apiKey;\r\n this.operation = operation;\r\n this.code = code;\r\n this.continueUrl = (_d = searchParams[\"continueUrl\" /* CONTINUE_URL */]) !== null && _d !== void 0 ? _d : null;\r\n this.languageCode = (_e = searchParams[\"languageCode\" /* LANGUAGE_CODE */]) !== null && _e !== void 0 ? _e : null;\r\n this.tenantId = (_f = searchParams[\"tenantId\" /* TENANT_ID */]) !== null && _f !== void 0 ? _f : null;\r\n }\r\n /**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if the link is valid,\r\n * otherwise returns null.\r\n *\r\n * @param link - The email action link string.\r\n * @returns The {@link ActionCodeURL} object, or null if the link is invalid.\r\n *\r\n * @public\r\n */\r\n static parseLink(link) {\r\n const actionLink = parseDeepLink(link);\r\n try {\r\n return new ActionCodeURL(actionLink);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Parses the email action link string and returns an {@link ActionCodeURL} if\r\n * the link is valid, otherwise returns null.\r\n *\r\n * @public\r\n */\r\nfunction parseActionCodeURL(link) {\r\n return ActionCodeURL.parseLink(link);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating {@link EmailAuthCredential}.\r\n *\r\n * @public\r\n */\r\nclass EmailAuthProvider {\r\n constructor() {\r\n /**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\n this.providerId = EmailAuthProvider.PROVIDER_ID;\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and password.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credential(email, password);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * const userCredential = await signInWithEmailAndPassword(auth, email, password);\r\n * ```\r\n *\r\n * @param email - Email address.\r\n * @param password - User account password.\r\n * @returns The auth provider credential.\r\n */\r\n static credential(email, password) {\r\n return EmailAuthCredential._fromEmailAndPassword(email, password);\r\n }\r\n /**\r\n * Initialize an {@link AuthCredential} using an email and an email link after a sign in with\r\n * email link operation.\r\n *\r\n * @example\r\n * ```javascript\r\n * const authCredential = EmailAuthProvider.credentialWithLink(auth, email, emailLink);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * await sendSignInLinkToEmail(auth, email);\r\n * // Obtain emailLink from user.\r\n * const userCredential = await signInWithEmailLink(auth, email, emailLink);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance used to verify the link.\r\n * @param email - Email address.\r\n * @param emailLink - Sign-in email link.\r\n * @returns - The auth provider credential.\r\n */\r\n static credentialWithLink(email, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n _assert(actionCodeUrl, \"argument-error\" /* ARGUMENT_ERROR */);\r\n return EmailAuthCredential._fromEmailAndCode(email, actionCodeUrl.code, actionCodeUrl.tenantId);\r\n }\r\n}\r\n/**\r\n * Always set to {@link ProviderId}.PASSWORD, even for email link.\r\n */\r\nEmailAuthProvider.PROVIDER_ID = \"password\" /* PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_PASSWORD.\r\n */\r\nEmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD = \"password\" /* EMAIL_PASSWORD */;\r\n/**\r\n * Always set to {@link SignInMethod}.EMAIL_LINK.\r\n */\r\nEmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD = \"emailLink\" /* EMAIL_LINK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The base class for all Federated providers (OAuth (including OIDC), SAML).\r\n *\r\n * This class is not meant to be instantiated directly.\r\n *\r\n * @public\r\n */\r\nclass FederatedAuthProvider {\r\n /**\r\n * Constructor for generic OAuth providers.\r\n *\r\n * @param providerId - Provider for which credentials should be generated.\r\n */\r\n constructor(providerId) {\r\n this.providerId = providerId;\r\n /** @internal */\r\n this.defaultLanguageCode = null;\r\n /** @internal */\r\n this.customParameters = {};\r\n }\r\n /**\r\n * Set the language gode.\r\n *\r\n * @param languageCode - language code\r\n */\r\n setDefaultLanguage(languageCode) {\r\n this.defaultLanguageCode = languageCode;\r\n }\r\n /**\r\n * Sets the OAuth custom parameters to pass in an OAuth request for popup and redirect sign-in\r\n * operations.\r\n *\r\n * @remarks\r\n * For a detailed list, check the reserved required OAuth 2.0 parameters such as `client_id`,\r\n * `redirect_uri`, `scope`, `response_type`, and `state` are not allowed and will be ignored.\r\n *\r\n * @param customOAuthParameters - The custom OAuth parameters to pass in the OAuth request.\r\n */\r\n setCustomParameters(customOAuthParameters) {\r\n this.customParameters = customOAuthParameters;\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of {@link CustomParameters}.\r\n */\r\n getCustomParameters() {\r\n return this.customParameters;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Common code to all OAuth providers. This is separate from the\r\n * {@link OAuthProvider} so that child providers (like\r\n * {@link GoogleAuthProvider}) don't inherit the `credential` instance method.\r\n * Instead, they rely on a static `credential` method.\r\n */\r\nclass BaseOAuthProvider extends FederatedAuthProvider {\r\n constructor() {\r\n super(...arguments);\r\n /** @internal */\r\n this.scopes = [];\r\n }\r\n /**\r\n * Add an OAuth scope to the credential.\r\n *\r\n * @param scope - Provider OAuth scope to add.\r\n */\r\n addScope(scope) {\r\n // If not already added, add scope to list.\r\n if (!this.scopes.includes(scope)) {\r\n this.scopes.push(scope);\r\n }\r\n return this;\r\n }\r\n /**\r\n * Retrieve the current list of OAuth scopes.\r\n */\r\n getScopes() {\r\n return [...this.scopes];\r\n }\r\n}\r\n/**\r\n * Provider for generating generic {@link OAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new OAuthProvider('google.com');\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new OAuthProvider('google.com');\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a OAuth Access Token for the provider.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass OAuthProvider extends BaseOAuthProvider {\r\n /**\r\n * Creates an {@link OAuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n _assert('providerId' in obj && 'signInMethod' in obj, \"argument-error\" /* ARGUMENT_ERROR */);\r\n return OAuthCredential._fromParams(obj);\r\n }\r\n /**\r\n * Creates a {@link OAuthCredential} from a generic OAuth provider's access token or ID token.\r\n *\r\n * @remarks\r\n * The raw nonce is required when an ID token with a nonce field is provided. The SHA-256 hash of\r\n * the raw nonce must match the nonce field in the ID token.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `googleUser` from the onsuccess Google Sign In callback.\r\n * // Initialize a generate OAuth provider with a `google.com` providerId.\r\n * const provider = new OAuthProvider('google.com');\r\n * const credential = provider.credential({\r\n * idToken: googleUser.getAuthResponse().id_token,\r\n * });\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param params - Either the options object containing the ID token, access token and raw nonce\r\n * or the ID token string.\r\n */\r\n credential(params) {\r\n return this._credential(Object.assign(Object.assign({}, params), { nonce: params.rawNonce }));\r\n }\r\n /** An internal credential method that accepts more permissive options */\r\n _credential(params) {\r\n _assert(params.idToken || params.accessToken, \"argument-error\" /* ARGUMENT_ERROR */);\r\n // For OAuthCredential, sign in method is same as providerId.\r\n return OAuthCredential._fromParams(Object.assign(Object.assign({}, params), { providerId: this.providerId, signInMethod: this.providerId }));\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return OAuthProvider.oauthCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n static oauthCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce, providerId } = tokenResponse;\r\n if (!oauthAccessToken &&\r\n !oauthTokenSecret &&\r\n !oauthIdToken &&\r\n !pendingToken) {\r\n return null;\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n try {\r\n return new OAuthProvider(providerId)._credential({\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken,\r\n nonce,\r\n pendingToken\r\n });\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.FACEBOOK.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('user_birthday');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * provider.addScope('user_birthday');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = FacebookAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass FacebookAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"facebook.com\" /* FACEBOOK */);\r\n }\r\n /**\r\n * Creates a credential for Facebook.\r\n *\r\n * @example\r\n * ```javascript\r\n * // `event` from the Facebook auth.authResponseChange callback.\r\n * const credential = FacebookAuthProvider.credential(event.authResponse.accessToken);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param accessToken - Facebook access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: FacebookAuthProvider.PROVIDER_ID,\r\n signInMethod: FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return FacebookAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return FacebookAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return FacebookAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.FACEBOOK. */\r\nFacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD = \"facebook.com\" /* FACEBOOK */;\r\n/** Always set to {@link ProviderId}.FACEBOOK. */\r\nFacebookAuthProvider.PROVIDER_ID = \"facebook.com\" /* FACEBOOK */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an an {@link OAuthCredential} for {@link ProviderId}.GOOGLE.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GoogleAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GoogleAuthProvider();\r\n * provider.addScope('profile');\r\n * provider.addScope('email');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Google Access Token.\r\n * const credential = GoogleAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass GoogleAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"google.com\" /* GOOGLE */);\r\n this.addScope('profile');\r\n }\r\n /**\r\n * Creates a credential for Google. At least one of ID token and access token is required.\r\n *\r\n * @example\r\n * ```javascript\r\n * // \\`googleUser\\` from the onsuccess Google Sign In callback.\r\n * const credential = GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);\r\n * const result = await signInWithCredential(credential);\r\n * ```\r\n *\r\n * @param idToken - Google ID token.\r\n * @param accessToken - Google access token.\r\n */\r\n static credential(idToken, accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GoogleAuthProvider.PROVIDER_ID,\r\n signInMethod: GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,\r\n idToken,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GoogleAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GoogleAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthIdToken, oauthAccessToken } = tokenResponse;\r\n if (!oauthIdToken && !oauthAccessToken) {\r\n // This could be an oauth 1 credential or a phone credential\r\n return null;\r\n }\r\n try {\r\n return GoogleAuthProvider.credential(oauthIdToken, oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GOOGLE. */\r\nGoogleAuthProvider.GOOGLE_SIGN_IN_METHOD = \"google.com\" /* GOOGLE */;\r\n/** Always set to {@link ProviderId}.GOOGLE. */\r\nGoogleAuthProvider.PROVIDER_ID = \"google.com\" /* GOOGLE */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.GITHUB.\r\n *\r\n * @remarks\r\n * GitHub requires an OAuth 2.0 redirect, so you can either handle the redirect directly, or use\r\n * the {@link signInWithPopup} handler:\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new GithubAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * provider.addScope('repo');\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new GithubAuthProvider();\r\n * provider.addScope('repo');\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Github Access Token.\r\n * const credential = GithubAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * ```\r\n * @public\r\n */\r\nclass GithubAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"github.com\" /* GITHUB */);\r\n }\r\n /**\r\n * Creates a credential for Github.\r\n *\r\n * @param accessToken - Github access token.\r\n */\r\n static credential(accessToken) {\r\n return OAuthCredential._fromParams({\r\n providerId: GithubAuthProvider.PROVIDER_ID,\r\n signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD,\r\n accessToken\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return GithubAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return GithubAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) {\r\n return null;\r\n }\r\n if (!tokenResponse.oauthAccessToken) {\r\n return null;\r\n }\r\n try {\r\n return GithubAuthProvider.credential(tokenResponse.oauthAccessToken);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.GITHUB. */\r\nGithubAuthProvider.GITHUB_SIGN_IN_METHOD = \"github.com\" /* GITHUB */;\r\n/** Always set to {@link ProviderId}.GITHUB. */\r\nGithubAuthProvider.PROVIDER_ID = \"github.com\" /* GITHUB */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IDP_REQUEST_URI = 'http://localhost';\r\n/**\r\n * @public\r\n */\r\nclass SAMLAuthCredential extends AuthCredential {\r\n /** @internal */\r\n constructor(providerId, pendingToken) {\r\n super(providerId, providerId);\r\n this.pendingToken = pendingToken;\r\n }\r\n /** @internal */\r\n _getIdTokenResponse(auth) {\r\n const request = this.buildRequest();\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _linkToIdToken(auth, idToken) {\r\n const request = this.buildRequest();\r\n request.idToken = idToken;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** @internal */\r\n _getReauthenticationResolver(auth) {\r\n const request = this.buildRequest();\r\n request.autoCreate = false;\r\n return signInWithIdp(auth, request);\r\n }\r\n /** {@inheritdoc AuthCredential.toJSON} */\r\n toJSON() {\r\n return {\r\n signInMethod: this.signInMethod,\r\n providerId: this.providerId,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n /**\r\n * Static method to deserialize a JSON representation of an object into an\r\n * {@link AuthCredential}.\r\n *\r\n * @param json - Input can be either Object or the stringified representation of the object.\r\n * When string is provided, JSON.parse would be called first.\r\n *\r\n * @returns If the JSON input does not represent an {@link AuthCredential}, null is returned.\r\n */\r\n static fromJSON(json) {\r\n const obj = typeof json === 'string' ? JSON.parse(json) : json;\r\n const { providerId, signInMethod, pendingToken } = obj;\r\n if (!providerId ||\r\n !signInMethod ||\r\n !pendingToken ||\r\n providerId !== signInMethod) {\r\n return null;\r\n }\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n /**\r\n * Helper static method to avoid exposing the constructor to end users.\r\n *\r\n * @internal\r\n */\r\n static _create(providerId, pendingToken) {\r\n return new SAMLAuthCredential(providerId, pendingToken);\r\n }\r\n buildRequest() {\r\n return {\r\n requestUri: IDP_REQUEST_URI,\r\n returnSecureToken: true,\r\n pendingToken: this.pendingToken\r\n };\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SAML_PROVIDER_PREFIX = 'saml.';\r\n/**\r\n * An {@link AuthProvider} for SAML.\r\n *\r\n * @public\r\n */\r\nclass SAMLAuthProvider extends FederatedAuthProvider {\r\n /**\r\n * Constructor. The providerId must start with \"saml.\"\r\n * @param providerId - SAML provider ID.\r\n */\r\n constructor(providerId) {\r\n _assert(providerId.startsWith(SAML_PROVIDER_PREFIX), \"argument-error\" /* ARGUMENT_ERROR */);\r\n super(providerId);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential} after a\r\n * successful SAML flow completes.\r\n *\r\n * @remarks\r\n *\r\n * For example, to get an {@link AuthCredential}, you could write the\r\n * following code:\r\n *\r\n * ```js\r\n * const userCredential = await signInWithPopup(auth, samlProvider);\r\n * const credential = SAMLAuthProvider.credentialFromResult(userCredential);\r\n * ```\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return SAMLAuthProvider.samlCredentialFromTaggedObject((error.customData || {}));\r\n }\r\n /**\r\n * Creates an {@link AuthCredential} from a JSON string or a plain object.\r\n * @param json - A plain object or a JSON string\r\n */\r\n static credentialFromJSON(json) {\r\n const credential = SAMLAuthCredential.fromJSON(json);\r\n _assert(credential, \"argument-error\" /* ARGUMENT_ERROR */);\r\n return credential;\r\n }\r\n static samlCredentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { pendingToken, providerId } = tokenResponse;\r\n if (!pendingToken || !providerId) {\r\n return null;\r\n }\r\n try {\r\n return SAMLAuthCredential._create(providerId, pendingToken);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link OAuthCredential} for {@link ProviderId}.TWITTER.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new TwitterAuthProvider();\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * }\r\n * ```\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new TwitterAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Twitter Access Token and Secret.\r\n * const credential = TwitterAuthProvider.credentialFromResult(result);\r\n * const token = credential.accessToken;\r\n * const secret = credential.secret;\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass TwitterAuthProvider extends BaseOAuthProvider {\r\n constructor() {\r\n super(\"twitter.com\" /* TWITTER */);\r\n }\r\n /**\r\n * Creates a credential for Twitter.\r\n *\r\n * @param token - Twitter access token.\r\n * @param secret - Twitter secret.\r\n */\r\n static credential(token, secret) {\r\n return OAuthCredential._fromParams({\r\n providerId: TwitterAuthProvider.PROVIDER_ID,\r\n signInMethod: TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,\r\n oauthToken: token,\r\n oauthTokenSecret: secret\r\n });\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link UserCredential}.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n return TwitterAuthProvider.credentialFromTaggedObject(userCredential);\r\n }\r\n /**\r\n * Used to extract the underlying {@link OAuthCredential} from a {@link AuthError} which was\r\n * thrown during a sign-in, link, or reauthenticate operation.\r\n *\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromError(error) {\r\n return TwitterAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { oauthAccessToken, oauthTokenSecret } = tokenResponse;\r\n if (!oauthAccessToken || !oauthTokenSecret) {\r\n return null;\r\n }\r\n try {\r\n return TwitterAuthProvider.credential(oauthAccessToken, oauthTokenSecret);\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n }\r\n}\r\n/** Always set to {@link SignInMethod}.TWITTER. */\r\nTwitterAuthProvider.TWITTER_SIGN_IN_METHOD = \"twitter.com\" /* TWITTER */;\r\n/** Always set to {@link ProviderId}.TWITTER. */\r\nTwitterAuthProvider.PROVIDER_ID = \"twitter.com\" /* TWITTER */;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signUp(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signUp\" /* SIGN_UP */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass UserCredentialImpl {\r\n constructor(params) {\r\n this.user = params.user;\r\n this.providerId = params.providerId;\r\n this._tokenResponse = params._tokenResponse;\r\n this.operationType = params.operationType;\r\n }\r\n static async _fromIdTokenResponse(auth, operationType, idTokenResponse, isAnonymous = false) {\r\n const user = await UserImpl._fromIdTokenResponse(auth, idTokenResponse, isAnonymous);\r\n const providerId = providerIdForResponse(idTokenResponse);\r\n const userCred = new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: idTokenResponse,\r\n operationType\r\n });\r\n return userCred;\r\n }\r\n static async _forOperation(user, operationType, response) {\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n const providerId = providerIdForResponse(response);\r\n return new UserCredentialImpl({\r\n user,\r\n providerId,\r\n _tokenResponse: response,\r\n operationType\r\n });\r\n }\r\n}\r\nfunction providerIdForResponse(response) {\r\n if (response.providerId) {\r\n return response.providerId;\r\n }\r\n if ('phoneNumber' in response) {\r\n return \"phone\" /* PHONE */;\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in as an anonymous user.\r\n *\r\n * @remarks\r\n * If there is already an anonymous user signed in, that user will be returned; otherwise, a\r\n * new anonymous user identity will be created and returned.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nasync function signInAnonymously(auth) {\r\n var _a;\r\n const authInternal = _castAuth(auth);\r\n await authInternal._initializationPromise;\r\n if ((_a = authInternal.currentUser) === null || _a === void 0 ? void 0 : _a.isAnonymous) {\r\n // If an anonymous user is already signed in, no need to sign them in again.\r\n return new UserCredentialImpl({\r\n user: authInternal.currentUser,\r\n providerId: null,\r\n operationType: \"signIn\" /* SIGN_IN */\r\n });\r\n }\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* SIGN_IN */, response, true);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorError extends FirebaseError {\r\n constructor(auth, error, operationType, user) {\r\n var _a;\r\n super(error.code, error.message);\r\n this.operationType = operationType;\r\n this.user = user;\r\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\r\n Object.setPrototypeOf(this, MultiFactorError.prototype);\r\n this.customData = {\r\n appName: auth.name,\r\n tenantId: (_a = auth.tenantId) !== null && _a !== void 0 ? _a : undefined,\r\n _serverResponse: error.customData._serverResponse,\r\n operationType,\r\n };\r\n }\r\n static _fromErrorAndOperation(auth, error, operationType, user) {\r\n return new MultiFactorError(auth, error, operationType, user);\r\n }\r\n}\r\nfunction _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user) {\r\n const idTokenProvider = operationType === \"reauthenticate\" /* REAUTHENTICATE */\r\n ? credential._getReauthenticationResolver(auth)\r\n : credential._getIdTokenResponse(auth);\r\n return idTokenProvider.catch(error => {\r\n if (error.code === `auth/${\"multi-factor-auth-required\" /* MFA_REQUIRED */}`) {\r\n throw MultiFactorError._fromErrorAndOperation(auth, error, operationType, user);\r\n }\r\n throw error;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Takes a set of UserInfo provider data and converts it to a set of names\r\n */\r\nfunction providerDataAsNames(providerData) {\r\n return new Set(providerData\r\n .map(({ providerId }) => providerId)\r\n .filter(pid => !!pid));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Unlinks a provider from a user account.\r\n *\r\n * @param user - The user.\r\n * @param providerId - The provider to unlink.\r\n *\r\n * @public\r\n */\r\nasync function unlink(user, providerId) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(true, userInternal, providerId);\r\n const { providerUserInfo } = await deleteLinkedAccounts(userInternal.auth, {\r\n idToken: await userInternal.getIdToken(),\r\n deleteProvider: [providerId]\r\n });\r\n const providersLeft = providerDataAsNames(providerUserInfo || []);\r\n userInternal.providerData = userInternal.providerData.filter(pd => providersLeft.has(pd.providerId));\r\n if (!providersLeft.has(\"phone\" /* PHONE */)) {\r\n userInternal.phoneNumber = null;\r\n }\r\n await userInternal.auth._persistUserIfCurrent(userInternal);\r\n return userInternal;\r\n}\r\nasync function _link$1(user, credential, bypassAuthState = false) {\r\n const response = await _logoutIfInvalidated(user, credential._linkToIdToken(user.auth, await user.getIdToken()), bypassAuthState);\r\n return UserCredentialImpl._forOperation(user, \"link\" /* LINK */, response);\r\n}\r\nasync function _assertLinkedStatus(expected, user, provider) {\r\n await _reloadWithoutSaving(user);\r\n const providerIds = providerDataAsNames(user.providerData);\r\n const code = expected === false\r\n ? \"provider-already-linked\" /* PROVIDER_ALREADY_LINKED */\r\n : \"no-such-provider\" /* NO_SUCH_PROVIDER */;\r\n _assert(providerIds.has(provider) === expected, user.auth, code);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _reauthenticate(user, credential, bypassAuthState = false) {\r\n const { auth } = user;\r\n const operationType = \"reauthenticate\" /* REAUTHENTICATE */;\r\n try {\r\n const response = await _logoutIfInvalidated(user, _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential, user), bypassAuthState);\r\n _assert(response.idToken, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const parsed = _parseToken(response.idToken);\r\n _assert(parsed, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const { sub: localId } = parsed;\r\n _assert(user.uid === localId, auth, \"user-mismatch\" /* USER_MISMATCH */);\r\n return UserCredentialImpl._forOperation(user, operationType, response);\r\n }\r\n catch (e) {\r\n // Convert user deleted error into user mismatch\r\n if ((e === null || e === void 0 ? void 0 : e.code) === `auth/${\"user-not-found\" /* USER_DELETED */}`) {\r\n _fail(auth, \"user-mismatch\" /* USER_MISMATCH */);\r\n }\r\n throw e;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _signInWithCredential(auth, credential, bypassAuthState = false) {\r\n const operationType = \"signIn\" /* SIGN_IN */;\r\n const response = await _processCredentialSavingMfaContextIfNecessary(auth, operationType, credential);\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, operationType, response);\r\n if (!bypassAuthState) {\r\n await auth._updateCurrentUser(userCredential.user);\r\n }\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCredential(auth, credential) {\r\n return _signInWithCredential(_castAuth(auth), credential);\r\n}\r\n/**\r\n * Links the user account with the given credentials.\r\n *\r\n * @remarks\r\n * An {@link AuthProvider} can be used to generate the credential.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function linkWithCredential(user, credential) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, credential.providerId);\r\n return _link$1(userInternal, credential);\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh credential.\r\n *\r\n * @remarks\r\n * Use before operations such as {@link updatePassword} that require tokens from recent sign-in\r\n * attempts. This method can be used to recover from a `CREDENTIAL_TOO_OLD_LOGIN_AGAIN` error.\r\n *\r\n * @param user - The user.\r\n * @param credential - The auth credential.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithCredential(user, credential) {\r\n return _reauthenticate(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function signInWithCustomToken$1(auth, request) {\r\n return _performSignInRequest(auth, \"POST\" /* POST */, \"/v1/accounts:signInWithCustomToken\" /* SIGN_IN_WITH_CUSTOM_TOKEN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Asynchronously signs in using a custom token.\r\n *\r\n * @remarks\r\n * Custom tokens are used to integrate Firebase Auth with existing auth systems, and must\r\n * be generated by an auth backend using the\r\n * {@link https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth#createcustomtoken | createCustomToken}\r\n * method in the {@link https://firebase.google.com/docs/auth/admin | Admin SDK} .\r\n *\r\n * Fails with an error if the token is invalid, expired, or not accepted by the Firebase Auth service.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param customToken - The custom token to sign in with.\r\n *\r\n * @public\r\n */\r\nasync function signInWithCustomToken(auth, customToken) {\r\n const authInternal = _castAuth(auth);\r\n const response = await signInWithCustomToken$1(authInternal, {\r\n token: customToken,\r\n returnSecureToken: true\r\n });\r\n const cred = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(cred.user);\r\n return cred;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorInfoImpl {\r\n constructor(factorId, response) {\r\n this.factorId = factorId;\r\n this.uid = response.mfaEnrollmentId;\r\n this.enrollmentTime = new Date(response.enrolledAt).toUTCString();\r\n this.displayName = response.displayName;\r\n }\r\n static _fromServerResponse(auth, enrollment) {\r\n if ('phoneInfo' in enrollment) {\r\n return PhoneMultiFactorInfoImpl._fromServerResponse(auth, enrollment);\r\n }\r\n return _fail(auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n }\r\n}\r\nclass PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl {\r\n constructor(response) {\r\n super(\"phone\" /* PHONE */, response);\r\n this.phoneNumber = response.phoneInfo;\r\n }\r\n static _fromServerResponse(_auth, enrollment) {\r\n return new PhoneMultiFactorInfoImpl(enrollment);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _setActionCodeSettingsOnRequest(auth, request, actionCodeSettings) {\r\n var _a;\r\n _assert(((_a = actionCodeSettings.url) === null || _a === void 0 ? void 0 : _a.length) > 0, auth, \"invalid-continue-uri\" /* INVALID_CONTINUE_URI */);\r\n _assert(typeof actionCodeSettings.dynamicLinkDomain === 'undefined' ||\r\n actionCodeSettings.dynamicLinkDomain.length > 0, auth, \"invalid-dynamic-link-domain\" /* INVALID_DYNAMIC_LINK_DOMAIN */);\r\n request.continueUrl = actionCodeSettings.url;\r\n request.dynamicLinkDomain = actionCodeSettings.dynamicLinkDomain;\r\n request.canHandleCodeInApp = actionCodeSettings.handleCodeInApp;\r\n if (actionCodeSettings.iOS) {\r\n _assert(actionCodeSettings.iOS.bundleId.length > 0, auth, \"missing-ios-bundle-id\" /* MISSING_IOS_BUNDLE_ID */);\r\n request.iOSBundleId = actionCodeSettings.iOS.bundleId;\r\n }\r\n if (actionCodeSettings.android) {\r\n _assert(actionCodeSettings.android.packageName.length > 0, auth, \"missing-android-pkg-name\" /* MISSING_ANDROID_PACKAGE_NAME */);\r\n request.androidInstallApp = actionCodeSettings.android.installApp;\r\n request.androidMinimumVersionCode =\r\n actionCodeSettings.android.minimumVersion;\r\n request.androidPackageName = actionCodeSettings.android.packageName;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a password reset email to the given email address.\r\n *\r\n * @remarks\r\n * To complete the password reset, call {@link confirmPasswordReset} with the code supplied in\r\n * the email sent to the user, along with the new password specified by the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendPasswordResetEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain code from user.\r\n * await confirmPasswordReset('user@example.com', code);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendPasswordResetEmail(auth, email, actionCodeSettings) {\r\n const authModular = getModularInstance(auth);\r\n const request = {\r\n requestType: \"PASSWORD_RESET\" /* PASSWORD_RESET */,\r\n email\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\r\n }\r\n await sendPasswordResetEmail$1(authModular, request);\r\n}\r\n/**\r\n * Completes the password reset process, given a confirmation code and new password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A confirmation code sent to the user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nasync function confirmPasswordReset(auth, oobCode, newPassword) {\r\n await resetPassword(getModularInstance(auth), {\r\n oobCode,\r\n newPassword\r\n });\r\n // Do not return the email.\r\n}\r\n/**\r\n * Applies a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function applyActionCode(auth, oobCode) {\r\n await applyActionCode$1(getModularInstance(auth), { oobCode });\r\n}\r\n/**\r\n * Checks a verification code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns metadata about the code.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param oobCode - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function checkActionCode(auth, oobCode) {\r\n const authModular = getModularInstance(auth);\r\n const response = await resetPassword(authModular, { oobCode });\r\n // Email could be empty only if the request type is EMAIL_SIGNIN or\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // New email should not be empty if the request type is\r\n // VERIFY_AND_CHANGE_EMAIL.\r\n // Multi-factor info could not be empty if the request type is\r\n // REVERT_SECOND_FACTOR_ADDITION.\r\n const operation = response.requestType;\r\n _assert(operation, authModular, \"internal-error\" /* INTERNAL_ERROR */);\r\n switch (operation) {\r\n case \"EMAIL_SIGNIN\" /* EMAIL_SIGNIN */:\r\n break;\r\n case \"VERIFY_AND_CHANGE_EMAIL\" /* VERIFY_AND_CHANGE_EMAIL */:\r\n _assert(response.newEmail, authModular, \"internal-error\" /* INTERNAL_ERROR */);\r\n break;\r\n case \"REVERT_SECOND_FACTOR_ADDITION\" /* REVERT_SECOND_FACTOR_ADDITION */:\r\n _assert(response.mfaInfo, authModular, \"internal-error\" /* INTERNAL_ERROR */);\r\n // fall through\r\n default:\r\n _assert(response.email, authModular, \"internal-error\" /* INTERNAL_ERROR */);\r\n }\r\n // The multi-factor info for revert second factor addition\r\n let multiFactorInfo = null;\r\n if (response.mfaInfo) {\r\n multiFactorInfo = MultiFactorInfoImpl._fromServerResponse(_castAuth(authModular), response.mfaInfo);\r\n }\r\n return {\r\n data: {\r\n email: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* VERIFY_AND_CHANGE_EMAIL */\r\n ? response.newEmail\r\n : response.email) || null,\r\n previousEmail: (response.requestType === \"VERIFY_AND_CHANGE_EMAIL\" /* VERIFY_AND_CHANGE_EMAIL */\r\n ? response.email\r\n : response.newEmail) || null,\r\n multiFactorInfo\r\n },\r\n operation\r\n };\r\n}\r\n/**\r\n * Checks a password reset code sent to the user by email or other out-of-band mechanism.\r\n *\r\n * @returns the user's email address if valid.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param code - A verification code sent to the user.\r\n *\r\n * @public\r\n */\r\nasync function verifyPasswordResetCode(auth, code) {\r\n const { data } = await checkActionCode(getModularInstance(auth), code);\r\n // Email should always be present since a code was sent to it\r\n return data.email;\r\n}\r\n/**\r\n * Creates a new user account associated with the specified email address and password.\r\n *\r\n * @remarks\r\n * On successful creation of the user account, this user will also be signed in to your application.\r\n *\r\n * User account creation can fail if the account already exists or the password is invalid.\r\n *\r\n * Note: The email address acts as a unique identifier for the user and enables an email-based\r\n * password reset. This function will create a new user account and set the initial user password.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param password - The user's chosen password.\r\n *\r\n * @public\r\n */\r\nasync function createUserWithEmailAndPassword(auth, email, password) {\r\n const authInternal = _castAuth(auth);\r\n const response = await signUp(authInternal, {\r\n returnSecureToken: true,\r\n email,\r\n password\r\n });\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(authInternal, \"signIn\" /* SIGN_IN */, response);\r\n await authInternal._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and password.\r\n *\r\n * @remarks\r\n * Fails with an error if the email address and password do not match.\r\n *\r\n * Note: The user's password is NOT the password used to access the user's email account. The\r\n * email address serves as a unique identifier for the user, and the password is used to access\r\n * the user's account in your Firebase project. See also: {@link createUserWithEmailAndPassword}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The users email address.\r\n * @param password - The users password.\r\n *\r\n * @public\r\n */\r\nfunction signInWithEmailAndPassword(auth, email, password) {\r\n return signInWithCredential(getModularInstance(auth), EmailAuthProvider.credential(email, password));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sends a sign-in email link to the user with the specified email.\r\n *\r\n * @remarks\r\n * The sign-in operation has to always be completed in the app unlike other out of band email\r\n * actions (password reset and email verifications). This is because, at the end of the flow,\r\n * the user is expected to be signed in and their Auth state persisted within the app.\r\n *\r\n * To complete sign in with the email link, call {@link signInWithEmailLink} with the email\r\n * address and the email link supplied in the email sent to the user.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param authInternal - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendSignInLinkToEmail(auth, email, actionCodeSettings) {\r\n const authModular = getModularInstance(auth);\r\n const request = {\r\n requestType: \"EMAIL_SIGNIN\" /* EMAIL_SIGNIN */,\r\n email\r\n };\r\n _assert(actionCodeSettings.handleCodeInApp, authModular, \"argument-error\" /* ARGUMENT_ERROR */);\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(authModular, request, actionCodeSettings);\r\n }\r\n await sendSignInLinkToEmail$1(authModular, request);\r\n}\r\n/**\r\n * Checks if an incoming link is a sign-in with email link suitable for {@link signInWithEmailLink}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nfunction isSignInWithEmailLink(auth, emailLink) {\r\n const actionCodeUrl = ActionCodeURL.parseLink(emailLink);\r\n return (actionCodeUrl === null || actionCodeUrl === void 0 ? void 0 : actionCodeUrl.operation) === \"EMAIL_SIGNIN\" /* EMAIL_SIGNIN */;\r\n}\r\n/**\r\n * Asynchronously signs in using an email and sign-in email link.\r\n *\r\n * @remarks\r\n * If no link is passed, the link is inferred from the current URL.\r\n *\r\n * Fails with an error if the email address is invalid or OTP in email link expires.\r\n *\r\n * Note: Confirm the link is a sign-in email link before calling this method firebase.auth.Auth.isSignInWithEmailLink.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendSignInLinkToEmail(auth, 'user@example.com', actionCodeSettings);\r\n * // Obtain emailLink from the user.\r\n * if(isSignInWithEmailLink(auth, emailLink)) {\r\n * await signInWithEmailLink(auth, 'user@example.com', emailLink);\r\n * }\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n * @param emailLink - The link sent to the user's email address.\r\n *\r\n * @public\r\n */\r\nasync function signInWithEmailLink(auth, email, emailLink) {\r\n const authModular = getModularInstance(auth);\r\n const credential = EmailAuthProvider.credentialWithLink(email, emailLink || _getCurrentUrl());\r\n // Check if the tenant ID in the email link matches the tenant ID on Auth\r\n // instance.\r\n _assert(credential._tenantId === (authModular.tenantId || null), authModular, \"tenant-id-mismatch\" /* TENANT_ID_MISMATCH */);\r\n return signInWithCredential(authModular, credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createAuthUri(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:createAuthUri\" /* CREATE_AUTH_URI */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Gets the list of possible sign in methods for the given email address.\r\n *\r\n * @remarks\r\n * This is useful to differentiate methods of sign-in for the same provider, eg.\r\n * {@link EmailAuthProvider} which has 2 methods of sign-in,\r\n * {@link SignInMethod}.EMAIL_PASSWORD and\r\n * {@link SignInMethod}.EMAIL_LINK.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param email - The user's email address.\r\n *\r\n * @public\r\n */\r\nasync function fetchSignInMethodsForEmail(auth, email) {\r\n // createAuthUri returns an error if continue URI is not http or https.\r\n // For environments like Cordova, Chrome extensions, native frameworks, file\r\n // systems, etc, use http://localhost as continue URL.\r\n const continueUri = _isHttpOrHttps() ? _getCurrentUrl() : 'http://localhost';\r\n const request = {\r\n identifier: email,\r\n continueUri\r\n };\r\n const { signinMethods } = await createAuthUri(getModularInstance(auth), request);\r\n return signinMethods || [];\r\n}\r\n/**\r\n * Sends a verification email to a user.\r\n *\r\n * @remarks\r\n * The verification process is completed by calling {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await sendEmailVerification(user, actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function sendEmailVerification(user, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_EMAIL\" /* VERIFY_EMAIL */,\r\n idToken\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await sendEmailVerification$1(userInternal.auth, request);\r\n if (email !== user.email) {\r\n await user.reload();\r\n }\r\n}\r\n/**\r\n * Sends a verification email to a new email address.\r\n *\r\n * @remarks\r\n * The user's email will be updated to the new one after being verified.\r\n *\r\n * If you have a custom email action handler, you can complete the verification process by calling\r\n * {@link applyActionCode}.\r\n *\r\n * @example\r\n * ```javascript\r\n * const actionCodeSettings = {\r\n * url: 'https://www.example.com/?email=user@example.com',\r\n * iOS: {\r\n * bundleId: 'com.example.ios'\r\n * },\r\n * android: {\r\n * packageName: 'com.example.android',\r\n * installApp: true,\r\n * minimumVersion: '12'\r\n * },\r\n * handleCodeInApp: true\r\n * };\r\n * await verifyBeforeUpdateEmail(user, 'newemail@example.com', actionCodeSettings);\r\n * // Obtain code from the user.\r\n * await applyActionCode(auth, code);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address to be verified before update.\r\n * @param actionCodeSettings - The {@link ActionCodeSettings}.\r\n *\r\n * @public\r\n */\r\nasync function verifyBeforeUpdateEmail(user, newEmail, actionCodeSettings) {\r\n const userInternal = getModularInstance(user);\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n requestType: \"VERIFY_AND_CHANGE_EMAIL\" /* VERIFY_AND_CHANGE_EMAIL */,\r\n idToken,\r\n newEmail\r\n };\r\n if (actionCodeSettings) {\r\n _setActionCodeSettingsOnRequest(userInternal.auth, request, actionCodeSettings);\r\n }\r\n const { email } = await verifyAndChangeEmail(userInternal.auth, request);\r\n if (email !== user.email) {\r\n // If the local copy of the email on user is outdated, reload the\r\n // user.\r\n await user.reload();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function updateProfile$1(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v1/accounts:update\" /* SET_ACCOUNT_INFO */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates a user's profile data.\r\n *\r\n * @param user - The user.\r\n * @param profile - The profile's `displayName` and `photoURL` to update.\r\n *\r\n * @public\r\n */\r\nasync function updateProfile(user, { displayName, photoURL: photoUrl }) {\r\n if (displayName === undefined && photoUrl === undefined) {\r\n return;\r\n }\r\n const userInternal = getModularInstance(user);\r\n const idToken = await userInternal.getIdToken();\r\n const profileRequest = {\r\n idToken,\r\n displayName,\r\n photoUrl,\r\n returnSecureToken: true\r\n };\r\n const response = await _logoutIfInvalidated(userInternal, updateProfile$1(userInternal.auth, profileRequest));\r\n userInternal.displayName = response.displayName || null;\r\n userInternal.photoURL = response.photoUrl || null;\r\n // Update the password provider as well\r\n const passwordProvider = userInternal.providerData.find(({ providerId }) => providerId === \"password\" /* PASSWORD */);\r\n if (passwordProvider) {\r\n passwordProvider.displayName = userInternal.displayName;\r\n passwordProvider.photoURL = userInternal.photoURL;\r\n }\r\n await userInternal._updateTokensIfNecessary(response);\r\n}\r\n/**\r\n * Updates the user's email address.\r\n *\r\n * @remarks\r\n * An email will be sent to the original email address (if it was set) that allows to revoke the\r\n * email address change, in order to protect them from account hijacking.\r\n *\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newEmail - The new email address.\r\n *\r\n * @public\r\n */\r\nfunction updateEmail(user, newEmail) {\r\n return updateEmailOrPassword(getModularInstance(user), newEmail, null);\r\n}\r\n/**\r\n * Updates the user's password.\r\n *\r\n * @remarks\r\n * Important: this is a security sensitive operation that requires the user to have recently signed\r\n * in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n * @param newPassword - The new password.\r\n *\r\n * @public\r\n */\r\nfunction updatePassword(user, newPassword) {\r\n return updateEmailOrPassword(getModularInstance(user), null, newPassword);\r\n}\r\nasync function updateEmailOrPassword(user, email, password) {\r\n const { auth } = user;\r\n const idToken = await user.getIdToken();\r\n const request = {\r\n idToken,\r\n returnSecureToken: true\r\n };\r\n if (email) {\r\n request.email = email;\r\n }\r\n if (password) {\r\n request.password = password;\r\n }\r\n const response = await _logoutIfInvalidated(user, updateEmailPassword(auth, request));\r\n await user._updateTokensIfNecessary(response, /* reload */ true);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Parse the `AdditionalUserInfo` from the ID token response.\r\n *\r\n */\r\nfunction _fromIdTokenResponse(idTokenResponse) {\r\n var _a, _b;\r\n if (!idTokenResponse) {\r\n return null;\r\n }\r\n const { providerId } = idTokenResponse;\r\n const profile = idTokenResponse.rawUserInfo\r\n ? JSON.parse(idTokenResponse.rawUserInfo)\r\n : {};\r\n const isNewUser = idTokenResponse.isNewUser ||\r\n idTokenResponse.kind === \"identitytoolkit#SignupNewUserResponse\" /* SignupNewUser */;\r\n if (!providerId && (idTokenResponse === null || idTokenResponse === void 0 ? void 0 : idTokenResponse.idToken)) {\r\n const signInProvider = (_b = (_a = _parseToken(idTokenResponse.idToken)) === null || _a === void 0 ? void 0 : _a.firebase) === null || _b === void 0 ? void 0 : _b['sign_in_provider'];\r\n if (signInProvider) {\r\n const filteredProviderId = signInProvider !== \"anonymous\" /* ANONYMOUS */ &&\r\n signInProvider !== \"custom\" /* CUSTOM */\r\n ? signInProvider\r\n : null;\r\n // Uses generic class in accordance with the legacy SDK.\r\n return new GenericAdditionalUserInfo(isNewUser, filteredProviderId);\r\n }\r\n }\r\n if (!providerId) {\r\n return null;\r\n }\r\n switch (providerId) {\r\n case \"facebook.com\" /* FACEBOOK */:\r\n return new FacebookAdditionalUserInfo(isNewUser, profile);\r\n case \"github.com\" /* GITHUB */:\r\n return new GithubAdditionalUserInfo(isNewUser, profile);\r\n case \"google.com\" /* GOOGLE */:\r\n return new GoogleAdditionalUserInfo(isNewUser, profile);\r\n case \"twitter.com\" /* TWITTER */:\r\n return new TwitterAdditionalUserInfo(isNewUser, profile, idTokenResponse.screenName || null);\r\n case \"custom\" /* CUSTOM */:\r\n case \"anonymous\" /* ANONYMOUS */:\r\n return new GenericAdditionalUserInfo(isNewUser, null);\r\n default:\r\n return new GenericAdditionalUserInfo(isNewUser, providerId, profile);\r\n }\r\n}\r\nclass GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile = {}) {\r\n this.isNewUser = isNewUser;\r\n this.providerId = providerId;\r\n this.profile = profile;\r\n }\r\n}\r\nclass FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, providerId, profile, username) {\r\n super(isNewUser, providerId, profile);\r\n this.username = username;\r\n }\r\n}\r\nclass FacebookAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"facebook.com\" /* FACEBOOK */, profile);\r\n }\r\n}\r\nclass GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"github.com\" /* GITHUB */, profile, typeof (profile === null || profile === void 0 ? void 0 : profile.login) === 'string' ? profile === null || profile === void 0 ? void 0 : profile.login : null);\r\n }\r\n}\r\nclass GoogleAdditionalUserInfo extends GenericAdditionalUserInfo {\r\n constructor(isNewUser, profile) {\r\n super(isNewUser, \"google.com\" /* GOOGLE */, profile);\r\n }\r\n}\r\nclass TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername {\r\n constructor(isNewUser, profile, screenName) {\r\n super(isNewUser, \"twitter.com\" /* TWITTER */, profile, screenName);\r\n }\r\n}\r\n/**\r\n * Extracts provider specific {@link AdditionalUserInfo} for the given credential.\r\n *\r\n * @param userCredential - The user credential.\r\n *\r\n * @public\r\n */\r\nfunction getAdditionalUserInfo(userCredential) {\r\n const { user, _tokenResponse } = userCredential;\r\n if (user.isAnonymous && !_tokenResponse) {\r\n // Handle the special case where signInAnonymously() gets called twice.\r\n // No network call is made so there's nothing to actually fill this in\r\n return {\r\n providerId: null,\r\n isNewUser: false,\r\n profile: null\r\n };\r\n }\r\n return _fromIdTokenResponse(_tokenResponse);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Non-optional auth methods.\r\n/**\r\n * Changes the type of persistence on the {@link Auth} instance for the currently saved\r\n * `Auth` session and applies this type of persistence for future sign-in requests, including\r\n * sign-in with redirect requests.\r\n *\r\n * @remarks\r\n * This makes it easy for a user signing in to specify whether their session should be\r\n * remembered or not. It also makes it easier to never persist the `Auth` state for applications\r\n * that are shared by other users or have sensitive data.\r\n *\r\n * @example\r\n * ```javascript\r\n * setPersistence(auth, browserSessionPersistence);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param persistence - The {@link Persistence} to use.\r\n * @returns A `Promise` that resolves once the persistence change has completed\r\n *\r\n * @public\r\n */\r\nfunction setPersistence(auth, persistence) {\r\n return getModularInstance(auth).setPersistence(persistence);\r\n}\r\n/**\r\n * Adds an observer for changes to the signed-in user's ID token, which includes sign-in,\r\n * sign-out, and token refresh events.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - callback triggered on error.\r\n * @param completed - callback triggered when observer is removed.\r\n *\r\n * @public\r\n */\r\nfunction onIdTokenChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onIdTokenChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Adds an observer for changes to the user's sign-in state.\r\n *\r\n * @remarks\r\n * To keep the old behavior, see {@link onIdTokenChanged}.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param nextOrObserver - callback triggered on change.\r\n * @param error - callback triggered on error.\r\n * @param completed - callback triggered when observer is removed.\r\n *\r\n * @public\r\n */\r\nfunction onAuthStateChanged(auth, nextOrObserver, error, completed) {\r\n return getModularInstance(auth).onAuthStateChanged(nextOrObserver, error, completed);\r\n}\r\n/**\r\n * Sets the current language to the default device/browser preference.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction useDeviceLanguage(auth) {\r\n getModularInstance(auth).useDeviceLanguage();\r\n}\r\n/**\r\n * Asynchronously sets the provided user as {@link Auth.currentUser} on the\r\n * {@link Auth} instance.\r\n *\r\n * @remarks\r\n * A new instance copy of the user provided will be made and set as currentUser.\r\n *\r\n * This will trigger {@link onAuthStateChanged} and {@link onIdTokenChanged} listeners\r\n * like other sign in methods.\r\n *\r\n * The operation fails with an error if the user to be updated belongs to a different Firebase\r\n * project.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param user - The new {@link User}.\r\n *\r\n * @public\r\n */\r\nfunction updateCurrentUser(auth, user) {\r\n return getModularInstance(auth).updateCurrentUser(user);\r\n}\r\n/**\r\n * Signs out the current user.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n *\r\n * @public\r\n */\r\nfunction signOut(auth) {\r\n return getModularInstance(auth).signOut();\r\n}\r\n/**\r\n * Deletes and signs out the user.\r\n *\r\n * @remarks\r\n * Important: this is a security-sensitive operation that requires the user to have recently\r\n * signed in. If this requirement isn't met, ask the user to authenticate again and then call\r\n * {@link reauthenticateWithCredential}.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nasync function deleteUser(user) {\r\n return getModularInstance(user).delete();\r\n}\n\nclass MultiFactorSessionImpl {\r\n constructor(type, credential) {\r\n this.type = type;\r\n this.credential = credential;\r\n }\r\n static _fromIdtoken(idToken) {\r\n return new MultiFactorSessionImpl(\"enroll\" /* ENROLL */, idToken);\r\n }\r\n static _fromMfaPendingCredential(mfaPendingCredential) {\r\n return new MultiFactorSessionImpl(\"signin\" /* SIGN_IN */, mfaPendingCredential);\r\n }\r\n toJSON() {\r\n const key = this.type === \"enroll\" /* ENROLL */\r\n ? 'idToken'\r\n : 'pendingCredential';\r\n return {\r\n multiFactorSession: {\r\n [key]: this.credential\r\n }\r\n };\r\n }\r\n static fromJSON(obj) {\r\n var _a, _b;\r\n if (obj === null || obj === void 0 ? void 0 : obj.multiFactorSession) {\r\n if ((_a = obj.multiFactorSession) === null || _a === void 0 ? void 0 : _a.pendingCredential) {\r\n return MultiFactorSessionImpl._fromMfaPendingCredential(obj.multiFactorSession.pendingCredential);\r\n }\r\n else if ((_b = obj.multiFactorSession) === null || _b === void 0 ? void 0 : _b.idToken) {\r\n return MultiFactorSessionImpl._fromIdtoken(obj.multiFactorSession.idToken);\r\n }\r\n }\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass MultiFactorResolverImpl {\r\n constructor(session, hints, signInResolver) {\r\n this.session = session;\r\n this.hints = hints;\r\n this.signInResolver = signInResolver;\r\n }\r\n /** @internal */\r\n static _fromError(authExtern, error) {\r\n const auth = _castAuth(authExtern);\r\n const serverResponse = error.customData._serverResponse;\r\n const hints = (serverResponse.mfaInfo || []).map(enrollment => MultiFactorInfoImpl._fromServerResponse(auth, enrollment));\r\n _assert(serverResponse.mfaPendingCredential, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const session = MultiFactorSessionImpl._fromMfaPendingCredential(serverResponse.mfaPendingCredential);\r\n return new MultiFactorResolverImpl(session, hints, async (assertion) => {\r\n const mfaResponse = await assertion._process(auth, session);\r\n // Clear out the unneeded fields from the old login response\r\n delete serverResponse.mfaInfo;\r\n delete serverResponse.mfaPendingCredential;\r\n // Use in the new token & refresh token in the old response\r\n const idTokenResponse = Object.assign(Object.assign({}, serverResponse), { idToken: mfaResponse.idToken, refreshToken: mfaResponse.refreshToken });\r\n // TODO: we should collapse this switch statement into UserCredentialImpl._forOperation and have it support the SIGN_IN case\r\n switch (error.operationType) {\r\n case \"signIn\" /* SIGN_IN */:\r\n const userCredential = await UserCredentialImpl._fromIdTokenResponse(auth, error.operationType, idTokenResponse);\r\n await auth._updateCurrentUser(userCredential.user);\r\n return userCredential;\r\n case \"reauthenticate\" /* REAUTHENTICATE */:\r\n _assert(error.user, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n return UserCredentialImpl._forOperation(error.user, error.operationType, idTokenResponse);\r\n default:\r\n _fail(auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n }\r\n });\r\n }\r\n async resolveSignIn(assertionExtern) {\r\n const assertion = assertionExtern;\r\n return this.signInResolver(assertion);\r\n }\r\n}\r\n/**\r\n * Provides a {@link MultiFactorResolver} suitable for completion of a\r\n * multi-factor flow.\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param error - The {@link MultiFactorError} raised during a sign-in, or\r\n * reauthentication operation.\r\n *\r\n * @public\r\n */\r\nfunction getMultiFactorResolver(auth, error) {\r\n var _a;\r\n const authModular = getModularInstance(auth);\r\n const errorInternal = error;\r\n _assert(error.customData.operationType, authModular, \"argument-error\" /* ARGUMENT_ERROR */);\r\n _assert((_a = errorInternal.customData._serverResponse) === null || _a === void 0 ? void 0 : _a.mfaPendingCredential, authModular, \"argument-error\" /* ARGUMENT_ERROR */);\r\n return MultiFactorResolverImpl._fromError(authModular, errorInternal);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v2/accounts/mfaEnrollment:start\" /* START_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeEnrollPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v2/accounts/mfaEnrollment:finalize\" /* FINALIZE_PHONE_MFA_ENROLLMENT */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction withdrawMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v2/accounts/mfaEnrollment:withdraw\" /* WITHDRAW_MFA */, _addTidIfNecessary(auth, request));\r\n}\n\nclass MultiFactorUserImpl {\r\n constructor(user) {\r\n this.user = user;\r\n this.enrolledFactors = [];\r\n user._onReload(userInfo => {\r\n if (userInfo.mfaInfo) {\r\n this.enrolledFactors = userInfo.mfaInfo.map(enrollment => MultiFactorInfoImpl._fromServerResponse(user.auth, enrollment));\r\n }\r\n });\r\n }\r\n static _fromUser(user) {\r\n return new MultiFactorUserImpl(user);\r\n }\r\n async getSession() {\r\n return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken());\r\n }\r\n async enroll(assertionExtern, displayName) {\r\n const assertion = assertionExtern;\r\n const session = (await this.getSession());\r\n const finalizeMfaResponse = await _logoutIfInvalidated(this.user, assertion._process(this.user.auth, session, displayName));\r\n // New tokens will be issued after enrollment of the new second factors.\r\n // They need to be updated on the user.\r\n await this.user._updateTokensIfNecessary(finalizeMfaResponse);\r\n // The user needs to be reloaded to get the new multi-factor information\r\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\r\n // will be updated.\r\n return this.user.reload();\r\n }\r\n async unenroll(infoOrUid) {\r\n const mfaEnrollmentId = typeof infoOrUid === 'string' ? infoOrUid : infoOrUid.uid;\r\n const idToken = await this.user.getIdToken();\r\n const idTokenResponse = await _logoutIfInvalidated(this.user, withdrawMfa(this.user.auth, {\r\n idToken,\r\n mfaEnrollmentId\r\n }));\r\n // Remove the second factor from the user's list.\r\n this.enrolledFactors = this.enrolledFactors.filter(({ uid }) => uid !== mfaEnrollmentId);\r\n // Depending on whether the backend decided to revoke the user's session,\r\n // the tokenResponse may be empty. If the tokens were not updated (and they\r\n // are now invalid), reloading the user will discover this and invalidate\r\n // the user's state accordingly.\r\n await this.user._updateTokensIfNecessary(idTokenResponse);\r\n try {\r\n await this.user.reload();\r\n }\r\n catch (e) {\r\n if (e.code !== `auth/${\"user-token-expired\" /* TOKEN_EXPIRED */}`) {\r\n throw e;\r\n }\r\n }\r\n }\r\n}\r\nconst multiFactorUserCache = new WeakMap();\r\n/**\r\n * The {@link MultiFactorUser} corresponding to the user.\r\n *\r\n * @remarks\r\n * This is used to access all multi-factor properties and operations related to the user.\r\n *\r\n * @param user - The user.\r\n *\r\n * @public\r\n */\r\nfunction multiFactor(user) {\r\n const userModular = getModularInstance(user);\r\n if (!multiFactorUserCache.has(userModular)) {\r\n multiFactorUserCache.set(userModular, MultiFactorUserImpl._fromUser(userModular));\r\n }\r\n return multiFactorUserCache.get(userModular);\r\n}\n\nconst STORAGE_AVAILABLE_KEY = '__sak';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// There are two different browser persistence types: local and session.\r\n// Both have the same implementation but use a different underlying storage\r\n// object.\r\nclass BrowserPersistenceClass {\r\n constructor(storageRetriever, type) {\r\n this.storageRetriever = storageRetriever;\r\n this.type = type;\r\n }\r\n _isAvailable() {\r\n try {\r\n if (!this.storage) {\r\n return Promise.resolve(false);\r\n }\r\n this.storage.setItem(STORAGE_AVAILABLE_KEY, '1');\r\n this.storage.removeItem(STORAGE_AVAILABLE_KEY);\r\n return Promise.resolve(true);\r\n }\r\n catch (_a) {\r\n return Promise.resolve(false);\r\n }\r\n }\r\n _set(key, value) {\r\n this.storage.setItem(key, JSON.stringify(value));\r\n return Promise.resolve();\r\n }\r\n _get(key) {\r\n const json = this.storage.getItem(key);\r\n return Promise.resolve(json ? JSON.parse(json) : null);\r\n }\r\n _remove(key) {\r\n this.storage.removeItem(key);\r\n return Promise.resolve();\r\n }\r\n get storage() {\r\n return this.storageRetriever();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _iframeCannotSyncWebStorage() {\r\n const ua = getUA();\r\n return _isSafari(ua) || _isIOS(ua);\r\n}\r\n// The polling period in case events are not supported\r\nconst _POLLING_INTERVAL_MS$1 = 1000;\r\n// The IE 10 localStorage cross tab synchronization delay in milliseconds\r\nconst IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\r\nclass BrowserLocalPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.localStorage, \"LOCAL\" /* LOCAL */);\r\n this.boundEventHandler = (event, poll) => this.onStorageEvent(event, poll);\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n // Safari or iOS browser and embedded in an iframe.\r\n this.safariLocalStorageNotSynced = _iframeCannotSyncWebStorage() && _isIframe();\r\n // Whether to use polling instead of depending on window events\r\n this.fallbackToPolling = _isMobileBrowser();\r\n this._shouldAllowMigration = true;\r\n }\r\n forAllChangedKeys(cb) {\r\n // Check all keys with listeners on them.\r\n for (const key of Object.keys(this.listeners)) {\r\n // Get value from localStorage.\r\n const newValue = this.storage.getItem(key);\r\n const oldValue = this.localCache[key];\r\n // If local map value does not match, trigger listener with storage event.\r\n // Differentiate this simulated event from the real storage event.\r\n if (newValue !== oldValue) {\r\n cb(key, oldValue, newValue);\r\n }\r\n }\r\n }\r\n onStorageEvent(event, poll = false) {\r\n // Key would be null in some situations, like when localStorage is cleared\r\n if (!event.key) {\r\n this.forAllChangedKeys((key, _oldValue, newValue) => {\r\n this.notifyListeners(key, newValue);\r\n });\r\n return;\r\n }\r\n const key = event.key;\r\n // Check the mechanism how this event was detected.\r\n // The first event will dictate the mechanism to be used.\r\n if (poll) {\r\n // Environment detects storage changes via polling.\r\n // Remove storage event listener to prevent possible event duplication.\r\n this.detachListener();\r\n }\r\n else {\r\n // Environment detects storage changes via storage event listener.\r\n // Remove polling listener to prevent possible event duplication.\r\n this.stopPolling();\r\n }\r\n // Safari embedded iframe. Storage event will trigger with the delta\r\n // changes but no changes will be applied to the iframe localStorage.\r\n if (this.safariLocalStorageNotSynced) {\r\n // Get current iframe page value.\r\n const storedValue = this.storage.getItem(key);\r\n // Value not synchronized, synchronize manually.\r\n if (event.newValue !== storedValue) {\r\n if (event.newValue !== null) {\r\n // Value changed from current value.\r\n this.storage.setItem(key, event.newValue);\r\n }\r\n else {\r\n // Current value deleted.\r\n this.storage.removeItem(key);\r\n }\r\n }\r\n else if (this.localCache[key] === event.newValue && !poll) {\r\n // Already detected and processed, do not trigger listeners again.\r\n return;\r\n }\r\n }\r\n const triggerListeners = () => {\r\n // Keep local map up to date in case storage event is triggered before\r\n // poll.\r\n const storedValue = this.storage.getItem(key);\r\n if (!poll && this.localCache[key] === storedValue) {\r\n // Real storage event which has already been detected, do nothing.\r\n // This seems to trigger in some IE browsers for some reason.\r\n return;\r\n }\r\n this.notifyListeners(key, storedValue);\r\n };\r\n const storedValue = this.storage.getItem(key);\r\n if (_isIE10() &&\r\n storedValue !== event.newValue &&\r\n event.newValue !== event.oldValue) {\r\n // IE 10 has this weird bug where a storage event would trigger with the\r\n // correct key, oldValue and newValue but localStorage.getItem(key) does\r\n // not yield the updated value until a few milliseconds. This ensures\r\n // this recovers from that situation.\r\n setTimeout(triggerListeners, IE10_LOCAL_STORAGE_SYNC_DELAY);\r\n }\r\n else {\r\n triggerListeners();\r\n }\r\n }\r\n notifyListeners(key, value) {\r\n this.localCache[key] = value;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(value ? JSON.parse(value) : value);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(() => {\r\n this.forAllChangedKeys((key, oldValue, newValue) => {\r\n this.onStorageEvent(new StorageEvent('storage', {\r\n key,\r\n oldValue,\r\n newValue\r\n }), \r\n /* poll */ true);\r\n });\r\n }, _POLLING_INTERVAL_MS$1);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n attachListener() {\r\n window.addEventListener('storage', this.boundEventHandler);\r\n }\r\n detachListener() {\r\n window.removeEventListener('storage', this.boundEventHandler);\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n // Whether browser can detect storage event when it had already been pushed to the background.\r\n // This may happen in some mobile browsers. A localStorage change in the foreground window\r\n // will not be detected in the background window via the storage event.\r\n // This was detected in iOS 7.x mobile browsers\r\n if (this.fallbackToPolling) {\r\n this.startPolling();\r\n }\r\n else {\r\n this.attachListener();\r\n }\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n this.localCache[key] = this.storage.getItem(key);\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.detachListener();\r\n this.stopPolling();\r\n }\r\n }\r\n // Update local cache on base operations:\r\n async _set(key, value) {\r\n await super._set(key, value);\r\n this.localCache[key] = JSON.stringify(value);\r\n }\r\n async _get(key) {\r\n const value = await super._get(key);\r\n this.localCache[key] = JSON.stringify(value);\r\n return value;\r\n }\r\n async _remove(key) {\r\n await super._remove(key);\r\n delete this.localCache[key];\r\n }\r\n}\r\nBrowserLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `localStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserLocalPersistence = BrowserLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass BrowserSessionPersistence extends BrowserPersistenceClass {\r\n constructor() {\r\n super(() => window.sessionStorage, \"SESSION\" /* SESSION */);\r\n }\r\n _addListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n _removeListener(_key, _listener) {\r\n // Listeners are not supported for session storage since it cannot be shared across windows\r\n return;\r\n }\r\n}\r\nBrowserSessionPersistence.type = 'SESSION';\r\n/**\r\n * An implementation of {@link Persistence} of `SESSION` using `sessionStorage`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst browserSessionPersistence = BrowserSessionPersistence;\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Shim for Promise.allSettled, note the slightly different format of `fulfilled` vs `status`.\r\n *\r\n * @param promises - Array of promises to wait on.\r\n */\r\nfunction _allSettled(promises) {\r\n return Promise.all(promises.map(async (promise) => {\r\n try {\r\n const value = await promise;\r\n return {\r\n fulfilled: true,\r\n value\r\n };\r\n }\r\n catch (reason) {\r\n return {\r\n fulfilled: false,\r\n reason\r\n };\r\n }\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface class for receiving messages.\r\n *\r\n */\r\nclass Receiver {\r\n constructor(eventTarget) {\r\n this.eventTarget = eventTarget;\r\n this.handlersMap = {};\r\n this.boundEventHandler = this.handleEvent.bind(this);\r\n }\r\n /**\r\n * Obtain an instance of a Receiver for a given event target, if none exists it will be created.\r\n *\r\n * @param eventTarget - An event target (such as window or self) through which the underlying\r\n * messages will be received.\r\n */\r\n static _getInstance(eventTarget) {\r\n // The results are stored in an array since objects can't be keys for other\r\n // objects. In addition, setting a unique property on an event target as a\r\n // hash map key may not be allowed due to CORS restrictions.\r\n const existingInstance = this.receivers.find(receiver => receiver.isListeningto(eventTarget));\r\n if (existingInstance) {\r\n return existingInstance;\r\n }\r\n const newInstance = new Receiver(eventTarget);\r\n this.receivers.push(newInstance);\r\n return newInstance;\r\n }\r\n isListeningto(eventTarget) {\r\n return this.eventTarget === eventTarget;\r\n }\r\n /**\r\n * Fans out a MessageEvent to the appropriate listeners.\r\n *\r\n * @remarks\r\n * Sends an {@link Status.ACK} upon receipt and a {@link Status.DONE} once all handlers have\r\n * finished processing.\r\n *\r\n * @param event - The MessageEvent.\r\n *\r\n */\r\n async handleEvent(event) {\r\n const messageEvent = event;\r\n const { eventId, eventType, data } = messageEvent.data;\r\n const handlers = this.handlersMap[eventType];\r\n if (!(handlers === null || handlers === void 0 ? void 0 : handlers.size)) {\r\n return;\r\n }\r\n messageEvent.ports[0].postMessage({\r\n status: \"ack\" /* ACK */,\r\n eventId,\r\n eventType\r\n });\r\n const promises = Array.from(handlers).map(async (handler) => handler(messageEvent.origin, data));\r\n const response = await _allSettled(promises);\r\n messageEvent.ports[0].postMessage({\r\n status: \"done\" /* DONE */,\r\n eventId,\r\n eventType,\r\n response\r\n });\r\n }\r\n /**\r\n * Subscribe an event handler for a particular event.\r\n *\r\n * @param eventType - Event name to subscribe to.\r\n * @param eventHandler - The event handler which should receive the events.\r\n *\r\n */\r\n _subscribe(eventType, eventHandler) {\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.addEventListener('message', this.boundEventHandler);\r\n }\r\n if (!this.handlersMap[eventType]) {\r\n this.handlersMap[eventType] = new Set();\r\n }\r\n this.handlersMap[eventType].add(eventHandler);\r\n }\r\n /**\r\n * Unsubscribe an event handler from a particular event.\r\n *\r\n * @param eventType - Event name to unsubscribe from.\r\n * @param eventHandler - Optinoal event handler, if none provided, unsubscribe all handlers on this event.\r\n *\r\n */\r\n _unsubscribe(eventType, eventHandler) {\r\n if (this.handlersMap[eventType] && eventHandler) {\r\n this.handlersMap[eventType].delete(eventHandler);\r\n }\r\n if (!eventHandler || this.handlersMap[eventType].size === 0) {\r\n delete this.handlersMap[eventType];\r\n }\r\n if (Object.keys(this.handlersMap).length === 0) {\r\n this.eventTarget.removeEventListener('message', this.boundEventHandler);\r\n }\r\n }\r\n}\r\nReceiver.receivers = [];\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _generateEventId(prefix = '', digits = 10) {\r\n let random = '';\r\n for (let i = 0; i < digits; i++) {\r\n random += Math.floor(Math.random() * 10);\r\n }\r\n return prefix + random;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface for sending messages and waiting for a completion response.\r\n *\r\n */\r\nclass Sender {\r\n constructor(target) {\r\n this.target = target;\r\n this.handlers = new Set();\r\n }\r\n /**\r\n * Unsubscribe the handler and remove it from our tracking Set.\r\n *\r\n * @param handler - The handler to unsubscribe.\r\n */\r\n removeMessageHandler(handler) {\r\n if (handler.messageChannel) {\r\n handler.messageChannel.port1.removeEventListener('message', handler.onMessage);\r\n handler.messageChannel.port1.close();\r\n }\r\n this.handlers.delete(handler);\r\n }\r\n /**\r\n * Send a message to the Receiver located at {@link target}.\r\n *\r\n * @remarks\r\n * We'll first wait a bit for an ACK , if we get one we will wait significantly longer until the\r\n * receiver has had a chance to fully process the event.\r\n *\r\n * @param eventType - Type of event to send.\r\n * @param data - The payload of the event.\r\n * @param timeout - Timeout for waiting on an ACK from the receiver.\r\n *\r\n * @returns An array of settled promises from all the handlers that were listening on the receiver.\r\n */\r\n async _send(eventType, data, timeout = 50 /* ACK */) {\r\n const messageChannel = typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\r\n if (!messageChannel) {\r\n throw new Error(\"connection_unavailable\" /* CONNECTION_UNAVAILABLE */);\r\n }\r\n // Node timers and browser timers return fundamentally different types.\r\n // We don't actually care what the value is but TS won't accept unknown and\r\n // we can't cast properly in both environments.\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n let completionTimer;\r\n let handler;\r\n return new Promise((resolve, reject) => {\r\n const eventId = _generateEventId('', 20);\r\n messageChannel.port1.start();\r\n const ackTimer = setTimeout(() => {\r\n reject(new Error(\"unsupported_event\" /* UNSUPPORTED_EVENT */));\r\n }, timeout);\r\n handler = {\r\n messageChannel,\r\n onMessage(event) {\r\n const messageEvent = event;\r\n if (messageEvent.data.eventId !== eventId) {\r\n return;\r\n }\r\n switch (messageEvent.data.status) {\r\n case \"ack\" /* ACK */:\r\n // The receiver should ACK first.\r\n clearTimeout(ackTimer);\r\n completionTimer = setTimeout(() => {\r\n reject(new Error(\"timeout\" /* TIMEOUT */));\r\n }, 3000 /* COMPLETION */);\r\n break;\r\n case \"done\" /* DONE */:\r\n // Once the receiver's handlers are finished we will get the results.\r\n clearTimeout(completionTimer);\r\n resolve(messageEvent.data.response);\r\n break;\r\n default:\r\n clearTimeout(ackTimer);\r\n clearTimeout(completionTimer);\r\n reject(new Error(\"invalid_response\" /* INVALID_RESPONSE */));\r\n break;\r\n }\r\n }\r\n };\r\n this.handlers.add(handler);\r\n messageChannel.port1.addEventListener('message', handler.onMessage);\r\n this.target.postMessage({\r\n eventType,\r\n eventId,\r\n data\r\n }, [messageChannel.port2]);\r\n }).finally(() => {\r\n if (handler) {\r\n this.removeMessageHandler(handler);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Lazy accessor for window, since the compat layer won't tree shake this out,\r\n * we need to make sure not to mess with window unless we have to\r\n */\r\nfunction _window() {\r\n return window;\r\n}\r\nfunction _setWindowLocation(url) {\r\n _window().location.href = url;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _isWorker() {\r\n return (typeof _window()['WorkerGlobalScope'] !== 'undefined' &&\r\n typeof _window()['importScripts'] === 'function');\r\n}\r\nasync function _getActiveServiceWorker() {\r\n if (!(navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker)) {\r\n return null;\r\n }\r\n try {\r\n const registration = await navigator.serviceWorker.ready;\r\n return registration.active;\r\n }\r\n catch (_a) {\r\n return null;\r\n }\r\n}\r\nfunction _getServiceWorkerController() {\r\n var _a;\r\n return ((_a = navigator === null || navigator === void 0 ? void 0 : navigator.serviceWorker) === null || _a === void 0 ? void 0 : _a.controller) || null;\r\n}\r\nfunction _getWorkerGlobalScope() {\r\n return _isWorker() ? self : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DB_NAME = 'firebaseLocalStorageDb';\r\nconst DB_VERSION = 1;\r\nconst DB_OBJECTSTORE_NAME = 'firebaseLocalStorage';\r\nconst DB_DATA_KEYPATH = 'fbase_key';\r\n/**\r\n * Promise wrapper for IDBRequest\r\n *\r\n * Unfortunately we can't cleanly extend Promise since promises are not callable in ES6\r\n *\r\n */\r\nclass DBPromise {\r\n constructor(request) {\r\n this.request = request;\r\n }\r\n toPromise() {\r\n return new Promise((resolve, reject) => {\r\n this.request.addEventListener('success', () => {\r\n resolve(this.request.result);\r\n });\r\n this.request.addEventListener('error', () => {\r\n reject(this.request.error);\r\n });\r\n });\r\n }\r\n}\r\nfunction getObjectStore(db, isReadWrite) {\r\n return db\r\n .transaction([DB_OBJECTSTORE_NAME], isReadWrite ? 'readwrite' : 'readonly')\r\n .objectStore(DB_OBJECTSTORE_NAME);\r\n}\r\nfunction _deleteDatabase() {\r\n const request = indexedDB.deleteDatabase(DB_NAME);\r\n return new DBPromise(request).toPromise();\r\n}\r\nfunction _openDatabase() {\r\n const request = indexedDB.open(DB_NAME, DB_VERSION);\r\n return new Promise((resolve, reject) => {\r\n request.addEventListener('error', () => {\r\n reject(request.error);\r\n });\r\n request.addEventListener('upgradeneeded', () => {\r\n const db = request.result;\r\n try {\r\n db.createObjectStore(DB_OBJECTSTORE_NAME, { keyPath: DB_DATA_KEYPATH });\r\n }\r\n catch (e) {\r\n reject(e);\r\n }\r\n });\r\n request.addEventListener('success', async () => {\r\n const db = request.result;\r\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\r\n // same time. The only way to recover seems to be deleting the database\r\n // and re-initializing it.\r\n // https://github.com/firebase/firebase-js-sdk/issues/634\r\n if (!db.objectStoreNames.contains(DB_OBJECTSTORE_NAME)) {\r\n // Need to close the database or else you get a `blocked` event\r\n db.close();\r\n await _deleteDatabase();\r\n resolve(await _openDatabase());\r\n }\r\n else {\r\n resolve(db);\r\n }\r\n });\r\n });\r\n}\r\nasync function _putObject(db, key, value) {\r\n const request = getObjectStore(db, true).put({\r\n [DB_DATA_KEYPATH]: key,\r\n value\r\n });\r\n return new DBPromise(request).toPromise();\r\n}\r\nasync function getObject(db, key) {\r\n const request = getObjectStore(db, false).get(key);\r\n const data = await new DBPromise(request).toPromise();\r\n return data === undefined ? null : data.value;\r\n}\r\nfunction _deleteObject(db, key) {\r\n const request = getObjectStore(db, true).delete(key);\r\n return new DBPromise(request).toPromise();\r\n}\r\nconst _POLLING_INTERVAL_MS = 800;\r\nconst _TRANSACTION_RETRY_COUNT = 3;\r\nclass IndexedDBLocalPersistence {\r\n constructor() {\r\n this.type = \"LOCAL\" /* LOCAL */;\r\n this._shouldAllowMigration = true;\r\n this.listeners = {};\r\n this.localCache = {};\r\n // setTimeout return value is platform specific\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.pollTimer = null;\r\n this.pendingWrites = 0;\r\n this.receiver = null;\r\n this.sender = null;\r\n this.serviceWorkerReceiverAvailable = false;\r\n this.activeServiceWorker = null;\r\n // Fire & forget the service worker registration as it may never resolve\r\n this._workerInitializationPromise =\r\n this.initializeServiceWorkerMessaging().then(() => { }, () => { });\r\n }\r\n async _openDb() {\r\n if (this.db) {\r\n return this.db;\r\n }\r\n this.db = await _openDatabase();\r\n return this.db;\r\n }\r\n async _withRetries(op) {\r\n let numAttempts = 0;\r\n while (true) {\r\n try {\r\n const db = await this._openDb();\r\n return await op(db);\r\n }\r\n catch (e) {\r\n if (numAttempts++ > _TRANSACTION_RETRY_COUNT) {\r\n throw e;\r\n }\r\n if (this.db) {\r\n this.db.close();\r\n this.db = undefined;\r\n }\r\n // TODO: consider adding exponential backoff\r\n }\r\n }\r\n }\r\n /**\r\n * IndexedDB events do not propagate from the main window to the worker context. We rely on a\r\n * postMessage interface to send these events to the worker ourselves.\r\n */\r\n async initializeServiceWorkerMessaging() {\r\n return _isWorker() ? this.initializeReceiver() : this.initializeSender();\r\n }\r\n /**\r\n * As the worker we should listen to events from the main window.\r\n */\r\n async initializeReceiver() {\r\n this.receiver = Receiver._getInstance(_getWorkerGlobalScope());\r\n // Refresh from persistence if we receive a KeyChanged message.\r\n this.receiver._subscribe(\"keyChanged\" /* KEY_CHANGED */, async (_origin, data) => {\r\n const keys = await this._poll();\r\n return {\r\n keyProcessed: keys.includes(data.key)\r\n };\r\n });\r\n // Let the sender know that we are listening so they give us more timeout.\r\n this.receiver._subscribe(\"ping\" /* PING */, async (_origin, _data) => {\r\n return [\"keyChanged\" /* KEY_CHANGED */];\r\n });\r\n }\r\n /**\r\n * As the main window, we should let the worker know when keys change (set and remove).\r\n *\r\n * @remarks\r\n * {@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready | ServiceWorkerContainer.ready}\r\n * may not resolve.\r\n */\r\n async initializeSender() {\r\n var _a, _b;\r\n // Check to see if there's an active service worker.\r\n this.activeServiceWorker = await _getActiveServiceWorker();\r\n if (!this.activeServiceWorker) {\r\n return;\r\n }\r\n this.sender = new Sender(this.activeServiceWorker);\r\n // Ping the service worker to check what events they can handle.\r\n const results = await this.sender._send(\"ping\" /* PING */, {}, 800 /* LONG_ACK */);\r\n if (!results) {\r\n return;\r\n }\r\n if (((_a = results[0]) === null || _a === void 0 ? void 0 : _a.fulfilled) &&\r\n ((_b = results[0]) === null || _b === void 0 ? void 0 : _b.value.includes(\"keyChanged\" /* KEY_CHANGED */))) {\r\n this.serviceWorkerReceiverAvailable = true;\r\n }\r\n }\r\n /**\r\n * Let the worker know about a changed key, the exact key doesn't technically matter since the\r\n * worker will just trigger a full sync anyway.\r\n *\r\n * @remarks\r\n * For now, we only support one service worker per page.\r\n *\r\n * @param key - Storage key which changed.\r\n */\r\n async notifyServiceWorker(key) {\r\n if (!this.sender ||\r\n !this.activeServiceWorker ||\r\n _getServiceWorkerController() !== this.activeServiceWorker) {\r\n return;\r\n }\r\n try {\r\n await this.sender._send(\"keyChanged\" /* KEY_CHANGED */, { key }, \r\n // Use long timeout if receiver has previously responded to a ping from us.\r\n this.serviceWorkerReceiverAvailable\r\n ? 800 /* LONG_ACK */\r\n : 50 /* ACK */);\r\n }\r\n catch (_a) {\r\n // This is a best effort approach. Ignore errors.\r\n }\r\n }\r\n async _isAvailable() {\r\n try {\r\n if (!indexedDB) {\r\n return false;\r\n }\r\n const db = await _openDatabase();\r\n await _putObject(db, STORAGE_AVAILABLE_KEY, '1');\r\n await _deleteObject(db, STORAGE_AVAILABLE_KEY);\r\n return true;\r\n }\r\n catch (_a) { }\r\n return false;\r\n }\r\n async _withPendingWrite(write) {\r\n this.pendingWrites++;\r\n try {\r\n await write();\r\n }\r\n finally {\r\n this.pendingWrites--;\r\n }\r\n }\r\n async _set(key, value) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _putObject(db, key, value));\r\n this.localCache[key] = value;\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _get(key) {\r\n const obj = (await this._withRetries((db) => getObject(db, key)));\r\n this.localCache[key] = obj;\r\n return obj;\r\n }\r\n async _remove(key) {\r\n return this._withPendingWrite(async () => {\r\n await this._withRetries((db) => _deleteObject(db, key));\r\n delete this.localCache[key];\r\n return this.notifyServiceWorker(key);\r\n });\r\n }\r\n async _poll() {\r\n // TODO: check if we need to fallback if getAll is not supported\r\n const result = await this._withRetries((db) => {\r\n const getAllRequest = getObjectStore(db, false).getAll();\r\n return new DBPromise(getAllRequest).toPromise();\r\n });\r\n if (!result) {\r\n return [];\r\n }\r\n // If we have pending writes in progress abort, we'll get picked up on the next poll\r\n if (this.pendingWrites !== 0) {\r\n return [];\r\n }\r\n const keys = [];\r\n const keysInResult = new Set();\r\n for (const { fbase_key: key, value } of result) {\r\n keysInResult.add(key);\r\n if (JSON.stringify(this.localCache[key]) !== JSON.stringify(value)) {\r\n this.notifyListeners(key, value);\r\n keys.push(key);\r\n }\r\n }\r\n for (const localKey of Object.keys(this.localCache)) {\r\n if (this.localCache[localKey] && !keysInResult.has(localKey)) {\r\n // Deleted\r\n this.notifyListeners(localKey, null);\r\n keys.push(localKey);\r\n }\r\n }\r\n return keys;\r\n }\r\n notifyListeners(key, newValue) {\r\n this.localCache[key] = newValue;\r\n const listeners = this.listeners[key];\r\n if (listeners) {\r\n for (const listener of Array.from(listeners)) {\r\n listener(newValue);\r\n }\r\n }\r\n }\r\n startPolling() {\r\n this.stopPolling();\r\n this.pollTimer = setInterval(async () => this._poll(), _POLLING_INTERVAL_MS);\r\n }\r\n stopPolling() {\r\n if (this.pollTimer) {\r\n clearInterval(this.pollTimer);\r\n this.pollTimer = null;\r\n }\r\n }\r\n _addListener(key, listener) {\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.startPolling();\r\n }\r\n if (!this.listeners[key]) {\r\n this.listeners[key] = new Set();\r\n // Populate the cache to avoid spuriously triggering on first poll.\r\n void this._get(key); // This can happen in the background async and we can return immediately.\r\n }\r\n this.listeners[key].add(listener);\r\n }\r\n _removeListener(key, listener) {\r\n if (this.listeners[key]) {\r\n this.listeners[key].delete(listener);\r\n if (this.listeners[key].size === 0) {\r\n delete this.listeners[key];\r\n }\r\n }\r\n if (Object.keys(this.listeners).length === 0) {\r\n this.stopPolling();\r\n }\r\n }\r\n}\r\nIndexedDBLocalPersistence.type = 'LOCAL';\r\n/**\r\n * An implementation of {@link Persistence} of type `LOCAL` using `indexedDB`\r\n * for the underlying storage.\r\n *\r\n * @public\r\n */\r\nconst indexedDBLocalPersistence = IndexedDBLocalPersistence;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction startSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v2/accounts/mfaSignIn:start\" /* START_PHONE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\r\nfunction finalizeSignInPhoneMfa(auth, request) {\r\n return _performApiRequest(auth, \"POST\" /* POST */, \"/v2/accounts/mfaSignIn:finalize\" /* FINALIZE_PHONE_MFA_SIGN_IN */, _addTidIfNecessary(auth, request));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function getRecaptchaParams(auth) {\r\n return ((await _performApiRequest(auth, \"GET\" /* GET */, \"/v1/recaptchaParams\" /* GET_RECAPTCHA_PARAM */)).recaptchaSiteKey || '');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getScriptParentElement() {\r\n var _a, _b;\r\n return (_b = (_a = document.getElementsByTagName('head')) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : document;\r\n}\r\nfunction _loadJS(url) {\r\n // TODO: consider adding timeout support & cancellation\r\n return new Promise((resolve, reject) => {\r\n const el = document.createElement('script');\r\n el.setAttribute('src', url);\r\n el.onload = resolve;\r\n el.onerror = e => {\r\n const error = _createError(\"internal-error\" /* INTERNAL_ERROR */);\r\n error.customData = e;\r\n reject(error);\r\n };\r\n el.type = 'text/javascript';\r\n el.charset = 'UTF-8';\r\n getScriptParentElement().appendChild(el);\r\n });\r\n}\r\nfunction _generateCallbackName(prefix) {\r\n return `__${prefix}${Math.floor(Math.random() * 1000000)}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _SOLVE_TIME_MS = 500;\r\nconst _EXPIRATION_TIME_MS = 60000;\r\nconst _WIDGET_ID_START = 1000000000000;\r\nclass MockReCaptcha {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.counter = _WIDGET_ID_START;\r\n this._widgets = new Map();\r\n }\r\n render(container, parameters) {\r\n const id = this.counter;\r\n this._widgets.set(id, new MockWidget(container, this.auth.name, parameters || {}));\r\n this.counter++;\r\n return id;\r\n }\r\n reset(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.delete());\r\n this._widgets.delete(id);\r\n }\r\n getResponse(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n return ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.getResponse()) || '';\r\n }\r\n async execute(optWidgetId) {\r\n var _a;\r\n const id = optWidgetId || _WIDGET_ID_START;\r\n void ((_a = this._widgets.get(id)) === null || _a === void 0 ? void 0 : _a.execute());\r\n return '';\r\n }\r\n}\r\nclass MockWidget {\r\n constructor(containerOrId, appName, params) {\r\n this.params = params;\r\n this.timerId = null;\r\n this.deleted = false;\r\n this.responseToken = null;\r\n this.clickHandler = () => {\r\n this.execute();\r\n };\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, \"argument-error\" /* ARGUMENT_ERROR */, { appName });\r\n this.container = container;\r\n this.isVisible = this.params.size !== 'invisible';\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n else {\r\n this.container.addEventListener('click', this.clickHandler);\r\n }\r\n }\r\n getResponse() {\r\n this.checkIfDeleted();\r\n return this.responseToken;\r\n }\r\n delete() {\r\n this.checkIfDeleted();\r\n this.deleted = true;\r\n if (this.timerId) {\r\n clearTimeout(this.timerId);\r\n this.timerId = null;\r\n }\r\n this.container.removeEventListener('click', this.clickHandler);\r\n }\r\n execute() {\r\n this.checkIfDeleted();\r\n if (this.timerId) {\r\n return;\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.responseToken = generateRandomAlphaNumericString(50);\r\n const { callback, 'expired-callback': expiredCallback } = this.params;\r\n if (callback) {\r\n try {\r\n callback(this.responseToken);\r\n }\r\n catch (e) { }\r\n }\r\n this.timerId = window.setTimeout(() => {\r\n this.timerId = null;\r\n this.responseToken = null;\r\n if (expiredCallback) {\r\n try {\r\n expiredCallback();\r\n }\r\n catch (e) { }\r\n }\r\n if (this.isVisible) {\r\n this.execute();\r\n }\r\n }, _EXPIRATION_TIME_MS);\r\n }, _SOLVE_TIME_MS);\r\n }\r\n checkIfDeleted() {\r\n if (this.deleted) {\r\n throw new Error('reCAPTCHA mock was already deleted!');\r\n }\r\n }\r\n}\r\nfunction generateRandomAlphaNumericString(len) {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < len; i++) {\r\n chars.push(allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)));\r\n }\r\n return chars.join('');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// ReCaptcha will load using the same callback, so the callback function needs\r\n// to be kept around\r\nconst _JSLOAD_CALLBACK = _generateCallbackName('rcb');\r\nconst NETWORK_TIMEOUT_DELAY = new Delay(30000, 60000);\r\nconst RECAPTCHA_BASE = 'https://www.google.com/recaptcha/api.js?';\r\n/**\r\n * Loader for the GReCaptcha library. There should only ever be one of this.\r\n */\r\nclass ReCaptchaLoaderImpl {\r\n constructor() {\r\n this.hostLanguage = '';\r\n this.counter = 0;\r\n this.librarySeparatelyLoaded = !!_window().grecaptcha;\r\n }\r\n load(auth, hl = '') {\r\n _assert(isHostLanguageValid(hl), auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n if (this.shouldResolveImmediately(hl)) {\r\n return Promise.resolve(_window().grecaptcha);\r\n }\r\n return new Promise((resolve, reject) => {\r\n const networkTimeout = _window().setTimeout(() => {\r\n reject(_createError(auth, \"network-request-failed\" /* NETWORK_REQUEST_FAILED */));\r\n }, NETWORK_TIMEOUT_DELAY.get());\r\n _window()[_JSLOAD_CALLBACK] = () => {\r\n _window().clearTimeout(networkTimeout);\r\n delete _window()[_JSLOAD_CALLBACK];\r\n const recaptcha = _window().grecaptcha;\r\n if (!recaptcha) {\r\n reject(_createError(auth, \"internal-error\" /* INTERNAL_ERROR */));\r\n return;\r\n }\r\n // Wrap the greptcha render function so that we know if the developer has\r\n // called it separately\r\n const render = recaptcha.render;\r\n recaptcha.render = (container, params) => {\r\n const widgetId = render(container, params);\r\n this.counter++;\r\n return widgetId;\r\n };\r\n this.hostLanguage = hl;\r\n resolve(recaptcha);\r\n };\r\n const url = `${RECAPTCHA_BASE}?${querystring({\r\n onload: _JSLOAD_CALLBACK,\r\n render: 'explicit',\r\n hl\r\n })}`;\r\n _loadJS(url).catch(() => {\r\n clearTimeout(networkTimeout);\r\n reject(_createError(auth, \"internal-error\" /* INTERNAL_ERROR */));\r\n });\r\n });\r\n }\r\n clearedOneInstance() {\r\n this.counter--;\r\n }\r\n shouldResolveImmediately(hl) {\r\n // We can resolve immediately if:\r\n // • grecaptcha is already defined AND (\r\n // 1. the requested language codes are the same OR\r\n // 2. there exists already a ReCaptcha on the page\r\n // 3. the library was already loaded by the app\r\n // In cases (2) and (3), we _can't_ reload as it would break the recaptchas\r\n // that are already in the page\r\n return (!!_window().grecaptcha &&\r\n (hl === this.hostLanguage ||\r\n this.counter > 0 ||\r\n this.librarySeparatelyLoaded));\r\n }\r\n}\r\nfunction isHostLanguageValid(hl) {\r\n return hl.length <= 6 && /^\\s*[a-zA-Z0-9\\-]*\\s*$/.test(hl);\r\n}\r\nclass MockReCaptchaLoaderImpl {\r\n async load(auth) {\r\n return new MockReCaptcha(auth);\r\n }\r\n clearedOneInstance() { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECAPTCHA_VERIFIER_TYPE = 'recaptcha';\r\nconst DEFAULT_PARAMS = {\r\n theme: 'light',\r\n type: 'image'\r\n};\r\n/**\r\n * An {@link https://www.google.com/recaptcha/ | reCAPTCHA}-based application verifier.\r\n *\r\n * @public\r\n */\r\nclass RecaptchaVerifier {\r\n /**\r\n *\r\n * @param containerOrId - The reCAPTCHA container parameter.\r\n *\r\n * @remarks\r\n * This has different meaning depending on whether the reCAPTCHA is hidden or visible. For a\r\n * visible reCAPTCHA the container must be empty. If a string is used, it has to correspond to\r\n * an element ID. The corresponding element must also must be in the DOM at the time of\r\n * initialization.\r\n *\r\n * @param parameters - The optional reCAPTCHA parameters.\r\n *\r\n * @remarks\r\n * Check the reCAPTCHA docs for a comprehensive list. All parameters are accepted except for\r\n * the sitekey. Firebase Auth backend provisions a reCAPTCHA for each project and will\r\n * configure this upon rendering. For an invisible reCAPTCHA, a size key must have the value\r\n * 'invisible'.\r\n *\r\n * @param authExtern - The corresponding Firebase {@link Auth} instance.\r\n *\r\n * @remarks\r\n * If none is provided, the default Firebase {@link Auth} instance is used. A Firebase {@link Auth} instance\r\n * must be initialized with an API key, otherwise an error will be thrown.\r\n */\r\n constructor(containerOrId, parameters = Object.assign({}, DEFAULT_PARAMS), authExtern) {\r\n this.parameters = parameters;\r\n /**\r\n * The application verifier type.\r\n *\r\n * @remarks\r\n * For a reCAPTCHA verifier, this is 'recaptcha'.\r\n */\r\n this.type = RECAPTCHA_VERIFIER_TYPE;\r\n this.destroyed = false;\r\n this.widgetId = null;\r\n this.tokenChangeListeners = new Set();\r\n this.renderPromise = null;\r\n this.recaptcha = null;\r\n this.auth = _castAuth(authExtern);\r\n this.isInvisible = this.parameters.size === 'invisible';\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n const container = typeof containerOrId === 'string'\r\n ? document.getElementById(containerOrId)\r\n : containerOrId;\r\n _assert(container, this.auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n this.container = container;\r\n this.parameters.callback = this.makeTokenCallback(this.parameters.callback);\r\n this._recaptchaLoader = this.auth.settings.appVerificationDisabledForTesting\r\n ? new MockReCaptchaLoaderImpl()\r\n : new ReCaptchaLoaderImpl();\r\n this.validateStartingState();\r\n // TODO: Figure out if sdk version is needed\r\n }\r\n /**\r\n * Waits for the user to solve the reCAPTCHA and resolves with the reCAPTCHA token.\r\n *\r\n * @returns A Promise for the reCAPTCHA token.\r\n */\r\n async verify() {\r\n this.assertNotDestroyed();\r\n const id = await this.render();\r\n const recaptcha = this.getAssertedRecaptcha();\r\n const response = recaptcha.getResponse(id);\r\n if (response) {\r\n return response;\r\n }\r\n return new Promise(resolve => {\r\n const tokenChange = (token) => {\r\n if (!token) {\r\n return; // Ignore token expirations.\r\n }\r\n this.tokenChangeListeners.delete(tokenChange);\r\n resolve(token);\r\n };\r\n this.tokenChangeListeners.add(tokenChange);\r\n if (this.isInvisible) {\r\n recaptcha.execute(id);\r\n }\r\n });\r\n }\r\n /**\r\n * Renders the reCAPTCHA widget on the page.\r\n *\r\n * @returns A Promise that resolves with the reCAPTCHA widget ID.\r\n */\r\n render() {\r\n try {\r\n this.assertNotDestroyed();\r\n }\r\n catch (e) {\r\n // This method returns a promise. Since it's not async (we want to return the\r\n // _same_ promise if rendering is still occurring), the API surface should\r\n // reject with the error rather than just throw\r\n return Promise.reject(e);\r\n }\r\n if (this.renderPromise) {\r\n return this.renderPromise;\r\n }\r\n this.renderPromise = this.makeRenderPromise().catch(e => {\r\n this.renderPromise = null;\r\n throw e;\r\n });\r\n return this.renderPromise;\r\n }\r\n /** @internal */\r\n _reset() {\r\n this.assertNotDestroyed();\r\n if (this.widgetId !== null) {\r\n this.getAssertedRecaptcha().reset(this.widgetId);\r\n }\r\n }\r\n /**\r\n * Clears the reCAPTCHA widget from the page and destroys the instance.\r\n */\r\n clear() {\r\n this.assertNotDestroyed();\r\n this.destroyed = true;\r\n this._recaptchaLoader.clearedOneInstance();\r\n if (!this.isInvisible) {\r\n this.container.childNodes.forEach(node => {\r\n this.container.removeChild(node);\r\n });\r\n }\r\n }\r\n validateStartingState() {\r\n _assert(!this.parameters.sitekey, this.auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n _assert(this.isInvisible || !this.container.hasChildNodes(), this.auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n _assert(typeof document !== 'undefined', this.auth, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n }\r\n makeTokenCallback(existing) {\r\n return token => {\r\n this.tokenChangeListeners.forEach(listener => listener(token));\r\n if (typeof existing === 'function') {\r\n existing(token);\r\n }\r\n else if (typeof existing === 'string') {\r\n const globalFunc = _window()[existing];\r\n if (typeof globalFunc === 'function') {\r\n globalFunc(token);\r\n }\r\n }\r\n };\r\n }\r\n assertNotDestroyed() {\r\n _assert(!this.destroyed, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n }\r\n async makeRenderPromise() {\r\n await this.init();\r\n if (!this.widgetId) {\r\n let container = this.container;\r\n if (!this.isInvisible) {\r\n const guaranteedEmpty = document.createElement('div');\r\n container.appendChild(guaranteedEmpty);\r\n container = guaranteedEmpty;\r\n }\r\n this.widgetId = this.getAssertedRecaptcha().render(container, this.parameters);\r\n }\r\n return this.widgetId;\r\n }\r\n async init() {\r\n _assert(_isHttpOrHttps() && !_isWorker(), this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n await domReady();\r\n this.recaptcha = await this._recaptchaLoader.load(this.auth, this.auth.languageCode || undefined);\r\n const siteKey = await getRecaptchaParams(this.auth);\r\n _assert(siteKey, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n this.parameters.sitekey = siteKey;\r\n }\r\n getAssertedRecaptcha() {\r\n _assert(this.recaptcha, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n return this.recaptcha;\r\n }\r\n}\r\nfunction domReady() {\r\n let resolver = null;\r\n return new Promise(resolve => {\r\n if (document.readyState === 'complete') {\r\n resolve();\r\n return;\r\n }\r\n // Document not ready, wait for load before resolving.\r\n // Save resolver, so we can remove listener in case it was externally\r\n // cancelled.\r\n resolver = () => resolve();\r\n window.addEventListener('load', resolver);\r\n }).catch(e => {\r\n if (resolver) {\r\n window.removeEventListener('load', resolver);\r\n }\r\n throw e;\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ConfirmationResultImpl {\r\n constructor(verificationId, onConfirmation) {\r\n this.verificationId = verificationId;\r\n this.onConfirmation = onConfirmation;\r\n }\r\n confirm(verificationCode) {\r\n const authCredential = PhoneAuthCredential._fromVerification(this.verificationId, verificationCode);\r\n return this.onConfirmation(authCredential);\r\n }\r\n}\r\n/**\r\n * Asynchronously signs in using a phone number.\r\n *\r\n * @remarks\r\n * This method sends a code via SMS to the given\r\n * phone number, and returns a {@link ConfirmationResult}. After the user\r\n * provides the code sent to their phone, call {@link ConfirmationResult.confirm}\r\n * with the code to sign the user in.\r\n *\r\n * For abuse prevention, this method also requires a {@link ApplicationVerifier}.\r\n * This SDK includes a reCAPTCHA-based implementation, {@link RecaptchaVerifier}.\r\n * This function can work on other platforms that do not support the\r\n * {@link RecaptchaVerifier} (like React Native), but you need to use a\r\n * third-party {@link ApplicationVerifier} implementation.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain a verificationCode from the user.\r\n * const credential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function signInWithPhoneNumber(auth, phoneNumber, appVerifier) {\r\n const authInternal = _castAuth(auth);\r\n const verificationId = await _verifyPhoneNumber(authInternal, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => signInWithCredential(authInternal, cred));\r\n}\r\n/**\r\n * Links the user account with the given phone number.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n await _assertLinkedStatus(false, userInternal, \"phone\" /* PHONE */);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => linkWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Re-authenticates a user using a fresh phone credential.\r\n *\r\n * @remarks Use before operations such as {@link updatePassword} that require tokens from recent sign-in attempts.\r\n *\r\n * @param user - The user.\r\n * @param phoneNumber - The user's phone number in E.164 format (e.g. +16505550101).\r\n * @param appVerifier - The {@link ApplicationVerifier}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPhoneNumber(user, phoneNumber, appVerifier) {\r\n const userInternal = getModularInstance(user);\r\n const verificationId = await _verifyPhoneNumber(userInternal.auth, phoneNumber, getModularInstance(appVerifier));\r\n return new ConfirmationResultImpl(verificationId, cred => reauthenticateWithCredential(userInternal, cred));\r\n}\r\n/**\r\n * Returns a verification ID to be used in conjunction with the SMS code that is sent.\r\n *\r\n */\r\nasync function _verifyPhoneNumber(auth, options, verifier) {\r\n var _a;\r\n const recaptchaToken = await verifier.verify();\r\n try {\r\n _assert(typeof recaptchaToken === 'string', auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n _assert(verifier.type === RECAPTCHA_VERIFIER_TYPE, auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n let phoneInfoOptions;\r\n if (typeof options === 'string') {\r\n phoneInfoOptions = {\r\n phoneNumber: options\r\n };\r\n }\r\n else {\r\n phoneInfoOptions = options;\r\n }\r\n if ('session' in phoneInfoOptions) {\r\n const session = phoneInfoOptions.session;\r\n if ('phoneNumber' in phoneInfoOptions) {\r\n _assert(session.type === \"enroll\" /* ENROLL */, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const response = await startEnrollPhoneMfa(auth, {\r\n idToken: session.credential,\r\n phoneEnrollmentInfo: {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneSessionInfo.sessionInfo;\r\n }\r\n else {\r\n _assert(session.type === \"signin\" /* SIGN_IN */, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n const mfaEnrollmentId = ((_a = phoneInfoOptions.multiFactorHint) === null || _a === void 0 ? void 0 : _a.uid) ||\r\n phoneInfoOptions.multiFactorUid;\r\n _assert(mfaEnrollmentId, auth, \"missing-multi-factor-info\" /* MISSING_MFA_INFO */);\r\n const response = await startSignInPhoneMfa(auth, {\r\n mfaPendingCredential: session.credential,\r\n mfaEnrollmentId,\r\n phoneSignInInfo: {\r\n recaptchaToken\r\n }\r\n });\r\n return response.phoneResponseInfo.sessionInfo;\r\n }\r\n }\r\n else {\r\n const { sessionInfo } = await sendPhoneVerificationCode(auth, {\r\n phoneNumber: phoneInfoOptions.phoneNumber,\r\n recaptchaToken\r\n });\r\n return sessionInfo;\r\n }\r\n }\r\n finally {\r\n verifier._reset();\r\n }\r\n}\r\n/**\r\n * Updates the user's phone number.\r\n *\r\n * @example\r\n * ```\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * await updatePhoneNumber(user, phoneCredential);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param credential - A credential authenticating the new phone number.\r\n *\r\n * @public\r\n */\r\nasync function updatePhoneNumber(user, credential) {\r\n await _link$1(getModularInstance(user), credential);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Provider for generating an {@link PhoneAuthCredential}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // 'recaptcha-container' is the ID of an element in the DOM.\r\n * const applicationVerifier = new RecaptchaVerifier('recaptcha-container');\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);\r\n * // Obtain the verificationCode from the user.\r\n * const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, phoneCredential);\r\n * ```\r\n *\r\n * @public\r\n */\r\nclass PhoneAuthProvider {\r\n /**\r\n * @param auth - The Firebase {@link Auth} instance in which sign-ins should occur.\r\n *\r\n */\r\n constructor(auth) {\r\n /** Always set to {@link ProviderId}.PHONE. */\r\n this.providerId = PhoneAuthProvider.PROVIDER_ID;\r\n this.auth = _castAuth(auth);\r\n }\r\n /**\r\n *\r\n * Starts a phone number authentication flow by sending a verification code to the given phone\r\n * number.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = await signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param phoneInfoOptions - The user's {@link PhoneInfoOptions}. The phone number should be in\r\n * E.164 format (e.g. +16505550101).\r\n * @param applicationVerifier - For abuse prevention, this method also requires a\r\n * {@link ApplicationVerifier}. This SDK includes a reCAPTCHA-based implementation,\r\n * {@link RecaptchaVerifier}.\r\n *\r\n * @returns A Promise for a verification ID that can be passed to\r\n * {@link PhoneAuthProvider.credential} to identify this flow..\r\n */\r\n verifyPhoneNumber(phoneOptions, applicationVerifier) {\r\n return _verifyPhoneNumber(this.auth, phoneOptions, getModularInstance(applicationVerifier));\r\n }\r\n /**\r\n * Creates a phone auth credential, given the verification ID from\r\n * {@link PhoneAuthProvider.verifyPhoneNumber} and the code that was sent to the user's\r\n * mobile device.\r\n *\r\n * @example\r\n * ```javascript\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = provider.verifyPhoneNumber(phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const authCredential = PhoneAuthProvider.credential(verificationId, verificationCode);\r\n * const userCredential = signInWithCredential(auth, authCredential);\r\n * ```\r\n *\r\n * @example\r\n * An alternative flow is provided using the `signInWithPhoneNumber` method.\r\n * ```javascript\r\n * const confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, applicationVerifier);\r\n * // Obtain verificationCode from the user.\r\n * const userCredential = await confirmationResult.confirm(verificationCode);\r\n * ```\r\n *\r\n * @param verificationId - The verification ID returned from {@link PhoneAuthProvider.verifyPhoneNumber}.\r\n * @param verificationCode - The verification code sent to the user's mobile device.\r\n *\r\n * @returns The auth provider credential.\r\n */\r\n static credential(verificationId, verificationCode) {\r\n return PhoneAuthCredential._fromVerification(verificationId, verificationCode);\r\n }\r\n /**\r\n * Generates an {@link AuthCredential} from a {@link UserCredential}.\r\n * @param userCredential - The user credential.\r\n */\r\n static credentialFromResult(userCredential) {\r\n const credential = userCredential;\r\n return PhoneAuthProvider.credentialFromTaggedObject(credential);\r\n }\r\n /**\r\n * Returns an {@link AuthCredential} when passed an error.\r\n *\r\n * @remarks\r\n *\r\n * This method works for errors like\r\n * `auth/account-exists-with-different-credentials`. This is useful for\r\n * recovering when attempting to set a user's phone number but the number\r\n * in question is already tied to another account. For example, the following\r\n * code tries to update the current user's phone number, and if that\r\n * fails, links the user with the account associated with that number:\r\n *\r\n * ```js\r\n * const provider = new PhoneAuthProvider(auth);\r\n * const verificationId = await provider.verifyPhoneNumber(number, verifier);\r\n * try {\r\n * const code = ''; // Prompt the user for the verification code\r\n * await updatePhoneNumber(\r\n * auth.currentUser,\r\n * PhoneAuthProvider.credential(verificationId, code));\r\n * } catch (e) {\r\n * if (e.code === 'auth/account-exists-with-different-credential') {\r\n * const cred = PhoneAuthProvider.credentialFromError(e);\r\n * await linkWithCredential(auth.currentUser, cred);\r\n * }\r\n * }\r\n *\r\n * // At this point, auth.currentUser.phoneNumber === number.\r\n * ```\r\n *\r\n * @param error - The error to generate a credential from.\r\n */\r\n static credentialFromError(error) {\r\n return PhoneAuthProvider.credentialFromTaggedObject((error.customData || {}));\r\n }\r\n static credentialFromTaggedObject({ _tokenResponse: tokenResponse }) {\r\n if (!tokenResponse) {\r\n return null;\r\n }\r\n const { phoneNumber, temporaryProof } = tokenResponse;\r\n if (phoneNumber && temporaryProof) {\r\n return PhoneAuthCredential._fromTokenResponse(phoneNumber, temporaryProof);\r\n }\r\n return null;\r\n }\r\n}\r\n/** Always set to {@link ProviderId}.PHONE. */\r\nPhoneAuthProvider.PROVIDER_ID = \"phone\" /* PHONE */;\r\n/** Always set to {@link SignInMethod}.PHONE. */\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = \"phone\" /* PHONE */;\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Chooses a popup/redirect resolver to use. This prefers the override (which\r\n * is directly passed in), and falls back to the property set on the auth\r\n * object. If neither are available, this function errors w/ an argument error.\r\n */\r\nfunction _withDefaultResolver(auth, resolverOverride) {\r\n if (resolverOverride) {\r\n return _getInstance(resolverOverride);\r\n }\r\n _assert(auth._popupRedirectResolver, auth, \"argument-error\" /* ARGUMENT_ERROR */);\r\n return auth._popupRedirectResolver;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass IdpCredential extends AuthCredential {\r\n constructor(params) {\r\n super(\"custom\" /* CUSTOM */, \"custom\" /* CUSTOM */);\r\n this.params = params;\r\n }\r\n _getIdTokenResponse(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _linkToIdToken(auth, idToken) {\r\n return signInWithIdp(auth, this._buildIdpRequest(idToken));\r\n }\r\n _getReauthenticationResolver(auth) {\r\n return signInWithIdp(auth, this._buildIdpRequest());\r\n }\r\n _buildIdpRequest(idToken) {\r\n const request = {\r\n requestUri: this.params.requestUri,\r\n sessionId: this.params.sessionId,\r\n postBody: this.params.postBody,\r\n tenantId: this.params.tenantId,\r\n pendingToken: this.params.pendingToken,\r\n returnSecureToken: true,\r\n returnIdpCredential: true\r\n };\r\n if (idToken) {\r\n request.idToken = idToken;\r\n }\r\n return request;\r\n }\r\n}\r\nfunction _signIn(params) {\r\n return _signInWithCredential(params.auth, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nfunction _reauth(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n return _reauthenticate(user, new IdpCredential(params), params.bypassAuthState);\r\n}\r\nasync function _link(params) {\r\n const { auth, user } = params;\r\n _assert(user, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n return _link$1(user, new IdpCredential(params), params.bypassAuthState);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n */\r\nclass AbstractPopupRedirectOperation {\r\n constructor(auth, filter, resolver, user, bypassAuthState = false) {\r\n this.auth = auth;\r\n this.resolver = resolver;\r\n this.user = user;\r\n this.bypassAuthState = bypassAuthState;\r\n this.pendingPromise = null;\r\n this.eventManager = null;\r\n this.filter = Array.isArray(filter) ? filter : [filter];\r\n }\r\n execute() {\r\n return new Promise(async (resolve, reject) => {\r\n this.pendingPromise = { resolve, reject };\r\n try {\r\n this.eventManager = await this.resolver._initialize(this.auth);\r\n await this.onExecution();\r\n this.eventManager.registerConsumer(this);\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n });\r\n }\r\n async onAuthEvent(event) {\r\n const { urlResponse, sessionId, postBody, tenantId, error, type } = event;\r\n if (error) {\r\n this.reject(error);\r\n return;\r\n }\r\n const params = {\r\n auth: this.auth,\r\n requestUri: urlResponse,\r\n sessionId: sessionId,\r\n tenantId: tenantId || undefined,\r\n postBody: postBody || undefined,\r\n user: this.user,\r\n bypassAuthState: this.bypassAuthState\r\n };\r\n try {\r\n this.resolve(await this.getIdpTask(type)(params));\r\n }\r\n catch (e) {\r\n this.reject(e);\r\n }\r\n }\r\n onError(error) {\r\n this.reject(error);\r\n }\r\n getIdpTask(type) {\r\n switch (type) {\r\n case \"signInViaPopup\" /* SIGN_IN_VIA_POPUP */:\r\n case \"signInViaRedirect\" /* SIGN_IN_VIA_REDIRECT */:\r\n return _signIn;\r\n case \"linkViaPopup\" /* LINK_VIA_POPUP */:\r\n case \"linkViaRedirect\" /* LINK_VIA_REDIRECT */:\r\n return _link;\r\n case \"reauthViaPopup\" /* REAUTH_VIA_POPUP */:\r\n case \"reauthViaRedirect\" /* REAUTH_VIA_REDIRECT */:\r\n return _reauth;\r\n default:\r\n _fail(this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n }\r\n }\r\n resolve(cred) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.resolve(cred);\r\n this.unregisterAndCleanUp();\r\n }\r\n reject(error) {\r\n debugAssert(this.pendingPromise, 'Pending promise was never set');\r\n this.pendingPromise.reject(error);\r\n this.unregisterAndCleanUp();\r\n }\r\n unregisterAndCleanUp() {\r\n if (this.eventManager) {\r\n this.eventManager.unregisterConsumer(this);\r\n }\r\n this.pendingPromise = null;\r\n this.cleanUp();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _POLL_WINDOW_CLOSE_TIMEOUT = new Delay(2000, 10000);\r\n/**\r\n * Authenticates a Firebase client using a popup-based OAuth authentication flow.\r\n *\r\n * @remarks\r\n * If succeeds, returns the signed in user along with the provider's credential. If sign in was\r\n * unsuccessful, returns an error object containing additional information about the error.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n *\r\n * // The signed-in user info.\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n *\r\n * @public\r\n */\r\nasync function signInWithPopup(auth, provider, resolver) {\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n const action = new PopupOperation(authInternal, \"signInViaPopup\" /* SIGN_IN_VIA_POPUP */, provider, resolverInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a pop-up based\r\n * OAuth flow.\r\n *\r\n * @remarks\r\n * If the reauthentication is successful, the returned result will contain the user and the\r\n * provider's credential.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithPopup(auth, provider);\r\n * // Reauthenticate using a popup.\r\n * await reauthenticateWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function reauthenticateWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"reauthViaPopup\" /* REAUTH_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Links the authenticated provider to the user account using a pop-up based OAuth flow.\r\n *\r\n * @remarks\r\n * If the linking is successful, the returned result will contain the user and the provider's credential.\r\n *\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a popup.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithPopup(result.user, provider);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function linkWithPopup(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n const action = new PopupOperation(userInternal.auth, \"linkViaPopup\" /* LINK_VIA_POPUP */, provider, resolverInternal, userInternal);\r\n return action.executeNotNull();\r\n}\r\n/**\r\n * Popup event manager. Handles the popup's entire lifecycle; listens to auth\r\n * events\r\n *\r\n */\r\nclass PopupOperation extends AbstractPopupRedirectOperation {\r\n constructor(auth, filter, provider, resolver, user) {\r\n super(auth, filter, resolver, user);\r\n this.provider = provider;\r\n this.authWindow = null;\r\n this.pollId = null;\r\n if (PopupOperation.currentPopupAction) {\r\n PopupOperation.currentPopupAction.cancel();\r\n }\r\n PopupOperation.currentPopupAction = this;\r\n }\r\n async executeNotNull() {\r\n const result = await this.execute();\r\n _assert(result, this.auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n return result;\r\n }\r\n async onExecution() {\r\n debugAssert(this.filter.length === 1, 'Popup operations only handle one event');\r\n const eventId = _generateEventId();\r\n this.authWindow = await this.resolver._openPopup(this.auth, this.provider, this.filter[0], // There's always one, see constructor\r\n eventId);\r\n this.authWindow.associatedEvent = eventId;\r\n // Check for web storage support and origin validation _after_ the popup is\r\n // loaded. These operations are slow (~1 second or so) Rather than\r\n // waiting on them before opening the window, optimistically open the popup\r\n // and check for storage support at the same time. If storage support is\r\n // not available, this will cause the whole thing to reject properly. It\r\n // will also close the popup, but since the promise has already rejected,\r\n // the popup closed by user poll will reject into the void.\r\n this.resolver._originValidation(this.auth).catch(e => {\r\n this.reject(e);\r\n });\r\n this.resolver._isIframeWebStorageSupported(this.auth, isSupported => {\r\n if (!isSupported) {\r\n this.reject(_createError(this.auth, \"web-storage-unsupported\" /* WEB_STORAGE_UNSUPPORTED */));\r\n }\r\n });\r\n // Handle user closure. Notice this does *not* use await\r\n this.pollUserCancellation();\r\n }\r\n get eventId() {\r\n var _a;\r\n return ((_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.associatedEvent) || null;\r\n }\r\n cancel() {\r\n this.reject(_createError(this.auth, \"cancelled-popup-request\" /* EXPIRED_POPUP_REQUEST */));\r\n }\r\n cleanUp() {\r\n if (this.authWindow) {\r\n this.authWindow.close();\r\n }\r\n if (this.pollId) {\r\n window.clearTimeout(this.pollId);\r\n }\r\n this.authWindow = null;\r\n this.pollId = null;\r\n PopupOperation.currentPopupAction = null;\r\n }\r\n pollUserCancellation() {\r\n const poll = () => {\r\n var _a, _b;\r\n if ((_b = (_a = this.authWindow) === null || _a === void 0 ? void 0 : _a.window) === null || _b === void 0 ? void 0 : _b.closed) {\r\n // Make sure that there is sufficient time for whatever action to\r\n // complete. The window could have closed but the sign in network\r\n // call could still be in flight.\r\n this.pollId = window.setTimeout(() => {\r\n this.pollId = null;\r\n this.reject(_createError(this.auth, \"popup-closed-by-user\" /* POPUP_CLOSED_BY_USER */));\r\n }, 2000 /* AUTH_EVENT */);\r\n return;\r\n }\r\n this.pollId = window.setTimeout(poll, _POLL_WINDOW_CLOSE_TIMEOUT.get());\r\n };\r\n poll();\r\n }\r\n}\r\n// Only one popup is ever shown at once. The lifecycle of the current popup\r\n// can be managed / cancelled by the constructor.\r\nPopupOperation.currentPopupAction = null;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_REDIRECT_KEY = 'pendingRedirect';\r\n// We only get one redirect outcome for any one auth, so just store it\r\n// in here.\r\nconst redirectOutcomeMap = new Map();\r\nclass RedirectAction extends AbstractPopupRedirectOperation {\r\n constructor(auth, resolver, bypassAuthState = false) {\r\n super(auth, [\r\n \"signInViaRedirect\" /* SIGN_IN_VIA_REDIRECT */,\r\n \"linkViaRedirect\" /* LINK_VIA_REDIRECT */,\r\n \"reauthViaRedirect\" /* REAUTH_VIA_REDIRECT */,\r\n \"unknown\" /* UNKNOWN */\r\n ], resolver, undefined, bypassAuthState);\r\n this.eventId = null;\r\n }\r\n /**\r\n * Override the execute function; if we already have a redirect result, then\r\n * just return it.\r\n */\r\n async execute() {\r\n let readyOutcome = redirectOutcomeMap.get(this.auth._key());\r\n if (!readyOutcome) {\r\n try {\r\n const hasPendingRedirect = await _getAndClearPendingRedirectStatus(this.resolver, this.auth);\r\n const result = hasPendingRedirect ? await super.execute() : null;\r\n readyOutcome = () => Promise.resolve(result);\r\n }\r\n catch (e) {\r\n readyOutcome = () => Promise.reject(e);\r\n }\r\n redirectOutcomeMap.set(this.auth._key(), readyOutcome);\r\n }\r\n // If we're not bypassing auth state, the ready outcome should be set to\r\n // null.\r\n if (!this.bypassAuthState) {\r\n redirectOutcomeMap.set(this.auth._key(), () => Promise.resolve(null));\r\n }\r\n return readyOutcome();\r\n }\r\n async onAuthEvent(event) {\r\n if (event.type === \"signInViaRedirect\" /* SIGN_IN_VIA_REDIRECT */) {\r\n return super.onAuthEvent(event);\r\n }\r\n else if (event.type === \"unknown\" /* UNKNOWN */) {\r\n // This is a sentinel value indicating there's no pending redirect\r\n this.resolve(null);\r\n return;\r\n }\r\n if (event.eventId) {\r\n const user = await this.auth._redirectUserForId(event.eventId);\r\n if (user) {\r\n this.user = user;\r\n return super.onAuthEvent(event);\r\n }\r\n else {\r\n this.resolve(null);\r\n }\r\n }\r\n }\r\n async onExecution() { }\r\n cleanUp() { }\r\n}\r\nasync function _getAndClearPendingRedirectStatus(resolver, auth) {\r\n const key = pendingRedirectKey(auth);\r\n const persistence = resolverPersistence(resolver);\r\n if (!(await persistence._isAvailable())) {\r\n return false;\r\n }\r\n const hasPendingRedirect = (await persistence._get(key)) === 'true';\r\n await persistence._remove(key);\r\n return hasPendingRedirect;\r\n}\r\nasync function _setPendingRedirectStatus(resolver, auth) {\r\n return resolverPersistence(resolver)._set(pendingRedirectKey(auth), 'true');\r\n}\r\nfunction _clearRedirectOutcomes() {\r\n redirectOutcomeMap.clear();\r\n}\r\nfunction resolverPersistence(resolver) {\r\n return _getInstance(resolver._redirectPersistence);\r\n}\r\nfunction pendingRedirectKey(auth) {\r\n return _persistenceKeyName(PENDING_REDIRECT_KEY, auth.config.apiKey, auth.name);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Authenticates a Firebase client using a full-page redirect flow.\r\n *\r\n * @remarks\r\n * To handle the results and errors for this operation, refer to {@link getRedirectResult}.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction signInWithRedirect(auth, provider, resolver) {\r\n return _signInWithRedirect(auth, provider, resolver);\r\n}\r\nasync function _signInWithRedirect(auth, provider, resolver) {\r\n const authInternal = _castAuth(auth);\r\n _assertInstanceOf(auth, provider, FederatedAuthProvider);\r\n const resolverInternal = _withDefaultResolver(authInternal, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, authInternal);\r\n return resolverInternal._openRedirect(authInternal, provider, \"signInViaRedirect\" /* SIGN_IN_VIA_REDIRECT */);\r\n}\r\n/**\r\n * Reauthenticates the current user with the specified {@link OAuthProvider} using a full-page redirect flow.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * const result = await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * // Link using a redirect.\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will again trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nfunction reauthenticateWithRedirect(user, provider, resolver) {\r\n return _reauthenticateWithRedirect(user, provider, resolver);\r\n}\r\nasync function _reauthenticateWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"reauthViaRedirect\" /* REAUTH_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Links the {@link OAuthProvider} to the user account using a full-page redirect flow.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using some other provider.\r\n * const result = await signInWithEmailAndPassword(auth, email, password);\r\n * // Link using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * await linkWithRedirect(result.user, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * ```\r\n *\r\n * @param user - The user.\r\n * @param provider - The provider to authenticate. The provider has to be an {@link OAuthProvider}.\r\n * Non-OAuth providers like {@link EmailAuthProvider} will throw an error.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n *\r\n * @public\r\n */\r\nfunction linkWithRedirect(user, provider, resolver) {\r\n return _linkWithRedirect(user, provider, resolver);\r\n}\r\nasync function _linkWithRedirect(user, provider, resolver) {\r\n const userInternal = getModularInstance(user);\r\n _assertInstanceOf(userInternal.auth, provider, FederatedAuthProvider);\r\n // Allow the resolver to error before persisting the redirect user\r\n const resolverInternal = _withDefaultResolver(userInternal.auth, resolver);\r\n await _assertLinkedStatus(false, userInternal, provider.providerId);\r\n await _setPendingRedirectStatus(resolverInternal, userInternal.auth);\r\n const eventId = await prepareUserForRedirect(userInternal);\r\n return resolverInternal._openRedirect(userInternal.auth, provider, \"linkViaRedirect\" /* LINK_VIA_REDIRECT */, eventId);\r\n}\r\n/**\r\n * Returns a {@link UserCredential} from the redirect-based sign-in flow.\r\n *\r\n * @remarks\r\n * If sign-in succeeded, returns the signed in user. If sign-in was unsuccessful, fails with an\r\n * error. If no redirect operation was called, returns a {@link UserCredential}\r\n * with a null `user`.\r\n *\r\n * @example\r\n * ```javascript\r\n * // Sign in using a redirect.\r\n * const provider = new FacebookAuthProvider();\r\n * // You can add additional scopes to the provider:\r\n * provider.addScope('user_birthday');\r\n * // Start a sign in process for an unauthenticated user.\r\n * await signInWithRedirect(auth, provider);\r\n * // This will trigger a full page redirect away from your app\r\n *\r\n * // After returning from the redirect when your app initializes you can obtain the result\r\n * const result = await getRedirectResult(auth);\r\n * if (result) {\r\n * // This is the signed-in user\r\n * const user = result.user;\r\n * // This gives you a Facebook Access Token.\r\n * const credential = provider.credentialFromResult(auth, result);\r\n * const token = credential.accessToken;\r\n * }\r\n * // As this API can be used for sign-in, linking and reauthentication,\r\n * // check the operationType to determine what triggered this redirect\r\n * // operation.\r\n * const operationType = result.operationType;\r\n * ```\r\n *\r\n * @param auth - The {@link Auth} instance.\r\n * @param resolver - An instance of {@link PopupRedirectResolver}, optional\r\n * if already supplied to {@link initializeAuth} or provided by {@link getAuth}.\r\n *\r\n * @public\r\n */\r\nasync function getRedirectResult(auth, resolver) {\r\n await _castAuth(auth)._initializationPromise;\r\n return _getRedirectResult(auth, resolver, false);\r\n}\r\nasync function _getRedirectResult(auth, resolverExtern, bypassAuthState = false) {\r\n const authInternal = _castAuth(auth);\r\n const resolver = _withDefaultResolver(authInternal, resolverExtern);\r\n const action = new RedirectAction(authInternal, resolver, bypassAuthState);\r\n const result = await action.execute();\r\n if (result && !bypassAuthState) {\r\n delete result.user._redirectEventId;\r\n await authInternal._persistUserIfCurrent(result.user);\r\n await authInternal._setRedirectUser(null, resolverExtern);\r\n }\r\n return result;\r\n}\r\nasync function prepareUserForRedirect(user) {\r\n const eventId = _generateEventId(`${user.uid}:::`);\r\n user._redirectEventId = eventId;\r\n await user.auth._setRedirectUser(user);\r\n await user.auth._persistUserIfCurrent(user);\r\n return eventId;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// The amount of time to store the UIDs of seen events; this is\r\n// set to 10 min by default\r\nconst EVENT_DUPLICATION_CACHE_DURATION_MS = 10 * 60 * 1000;\r\nclass AuthEventManager {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.cachedEventUids = new Set();\r\n this.consumers = new Set();\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n registerConsumer(authEventConsumer) {\r\n this.consumers.add(authEventConsumer);\r\n if (this.queuedRedirectEvent &&\r\n this.isEventForConsumer(this.queuedRedirectEvent, authEventConsumer)) {\r\n this.sendToConsumer(this.queuedRedirectEvent, authEventConsumer);\r\n this.saveEventToCache(this.queuedRedirectEvent);\r\n this.queuedRedirectEvent = null;\r\n }\r\n }\r\n unregisterConsumer(authEventConsumer) {\r\n this.consumers.delete(authEventConsumer);\r\n }\r\n onEvent(event) {\r\n // Check if the event has already been handled\r\n if (this.hasEventBeenHandled(event)) {\r\n return false;\r\n }\r\n let handled = false;\r\n this.consumers.forEach(consumer => {\r\n if (this.isEventForConsumer(event, consumer)) {\r\n handled = true;\r\n this.sendToConsumer(event, consumer);\r\n this.saveEventToCache(event);\r\n }\r\n });\r\n if (this.hasHandledPotentialRedirect || !isRedirectEvent(event)) {\r\n // If we've already seen a redirect before, or this is a popup event,\r\n // bail now\r\n return handled;\r\n }\r\n this.hasHandledPotentialRedirect = true;\r\n // If the redirect wasn't handled, hang on to it\r\n if (!handled) {\r\n this.queuedRedirectEvent = event;\r\n handled = true;\r\n }\r\n return handled;\r\n }\r\n sendToConsumer(event, consumer) {\r\n var _a;\r\n if (event.error && !isNullRedirectEvent(event)) {\r\n const code = ((_a = event.error.code) === null || _a === void 0 ? void 0 : _a.split('auth/')[1]) ||\r\n \"internal-error\" /* INTERNAL_ERROR */;\r\n consumer.onError(_createError(this.auth, code));\r\n }\r\n else {\r\n consumer.onAuthEvent(event);\r\n }\r\n }\r\n isEventForConsumer(event, consumer) {\r\n const eventIdMatches = consumer.eventId === null ||\r\n (!!event.eventId && event.eventId === consumer.eventId);\r\n return consumer.filter.includes(event.type) && eventIdMatches;\r\n }\r\n hasEventBeenHandled(event) {\r\n if (Date.now() - this.lastProcessedEventTime >=\r\n EVENT_DUPLICATION_CACHE_DURATION_MS) {\r\n this.cachedEventUids.clear();\r\n }\r\n return this.cachedEventUids.has(eventUid(event));\r\n }\r\n saveEventToCache(event) {\r\n this.cachedEventUids.add(eventUid(event));\r\n this.lastProcessedEventTime = Date.now();\r\n }\r\n}\r\nfunction eventUid(e) {\r\n return [e.type, e.eventId, e.sessionId, e.tenantId].filter(v => v).join('-');\r\n}\r\nfunction isNullRedirectEvent({ type, error }) {\r\n return (type === \"unknown\" /* UNKNOWN */ &&\r\n (error === null || error === void 0 ? void 0 : error.code) === `auth/${\"no-auth-event\" /* NO_AUTH_EVENT */}`);\r\n}\r\nfunction isRedirectEvent(event) {\r\n switch (event.type) {\r\n case \"signInViaRedirect\" /* SIGN_IN_VIA_REDIRECT */:\r\n case \"linkViaRedirect\" /* LINK_VIA_REDIRECT */:\r\n case \"reauthViaRedirect\" /* REAUTH_VIA_REDIRECT */:\r\n return true;\r\n case \"unknown\" /* UNKNOWN */:\r\n return isNullRedirectEvent(event);\r\n default:\r\n return false;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function _getProjectConfig(auth, request = {}) {\r\n return _performApiRequest(auth, \"GET\" /* GET */, \"/v1/projects\" /* GET_PROJECT_CONFIG */, request);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst IP_ADDRESS_REGEX = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\r\nconst HTTP_REGEX = /^https?/;\r\nasync function _validateOrigin(auth) {\r\n // Skip origin validation if we are in an emulated environment\r\n if (auth.config.emulator) {\r\n return;\r\n }\r\n const { authorizedDomains } = await _getProjectConfig(auth);\r\n for (const domain of authorizedDomains) {\r\n try {\r\n if (matchDomain(domain)) {\r\n return;\r\n }\r\n }\r\n catch (_a) {\r\n // Do nothing if there's a URL error; just continue searching\r\n }\r\n }\r\n // In the old SDK, this error also provides helpful messages.\r\n _fail(auth, \"unauthorized-domain\" /* INVALID_ORIGIN */);\r\n}\r\nfunction matchDomain(expected) {\r\n const currentUrl = _getCurrentUrl();\r\n const { protocol, hostname } = new URL(currentUrl);\r\n if (expected.startsWith('chrome-extension://')) {\r\n const ceUrl = new URL(expected);\r\n if (ceUrl.hostname === '' && hostname === '') {\r\n // For some reason we're not parsing chrome URLs properly\r\n return (protocol === 'chrome-extension:' &&\r\n expected.replace('chrome-extension://', '') ===\r\n currentUrl.replace('chrome-extension://', ''));\r\n }\r\n return protocol === 'chrome-extension:' && ceUrl.hostname === hostname;\r\n }\r\n if (!HTTP_REGEX.test(protocol)) {\r\n return false;\r\n }\r\n if (IP_ADDRESS_REGEX.test(expected)) {\r\n // The domain has to be exactly equal to the pattern, as an IP domain will\r\n // only contain the IP, no extra character.\r\n return hostname === expected;\r\n }\r\n // Dots in pattern should be escaped.\r\n const escapedDomainPattern = expected.replace(/\\./g, '\\\\.');\r\n // Non ip address domains.\r\n // domain.com = *.domain.com OR domain.com\r\n const re = new RegExp('^(.+\\\\.' + escapedDomainPattern + '|' + escapedDomainPattern + ')$', 'i');\r\n return re.test(hostname);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst NETWORK_TIMEOUT = new Delay(30000, 60000);\r\n/**\r\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\r\n * it will stop working after a retrial. This is a hack to fix this issue.\r\n */\r\nfunction resetUnloadedGapiModules() {\r\n // Clear last failed gapi.load state to force next gapi.load to first\r\n // load the failed gapi.iframes module.\r\n // Get gapix.beacon context.\r\n const beacon = _window().___jsl;\r\n // Get current hint.\r\n if (beacon === null || beacon === void 0 ? void 0 : beacon.H) {\r\n // Get gapi hint.\r\n for (const hint of Object.keys(beacon.H)) {\r\n // Requested modules.\r\n beacon.H[hint].r = beacon.H[hint].r || [];\r\n // Loaded modules.\r\n beacon.H[hint].L = beacon.H[hint].L || [];\r\n // Set requested modules to a copy of the loaded modules.\r\n beacon.H[hint].r = [...beacon.H[hint].L];\r\n // Clear pending callbacks.\r\n if (beacon.CP) {\r\n for (let i = 0; i < beacon.CP.length; i++) {\r\n // Remove all failed pending callbacks.\r\n beacon.CP[i] = null;\r\n }\r\n }\r\n }\r\n }\r\n}\r\nfunction loadGapi(auth) {\r\n return new Promise((resolve, reject) => {\r\n var _a, _b, _c;\r\n // Function to run when gapi.load is ready.\r\n function loadGapiIframe() {\r\n // The developer may have tried to previously run gapi.load and failed.\r\n // Run this to fix that.\r\n resetUnloadedGapiModules();\r\n gapi.load('gapi.iframes', {\r\n callback: () => {\r\n resolve(gapi.iframes.getContext());\r\n },\r\n ontimeout: () => {\r\n // The above reset may be sufficient, but having this reset after\r\n // failure ensures that if the developer calls gapi.load after the\r\n // connection is re-established and before another attempt to embed\r\n // the iframe, it would work and would not be broken because of our\r\n // failed attempt.\r\n // Timeout when gapi.iframes.Iframe not loaded.\r\n resetUnloadedGapiModules();\r\n reject(_createError(auth, \"network-request-failed\" /* NETWORK_REQUEST_FAILED */));\r\n },\r\n timeout: NETWORK_TIMEOUT.get()\r\n });\r\n }\r\n if ((_b = (_a = _window().gapi) === null || _a === void 0 ? void 0 : _a.iframes) === null || _b === void 0 ? void 0 : _b.Iframe) {\r\n // If gapi.iframes.Iframe available, resolve.\r\n resolve(gapi.iframes.getContext());\r\n }\r\n else if (!!((_c = _window().gapi) === null || _c === void 0 ? void 0 : _c.load)) {\r\n // Gapi loader ready, load gapi.iframes.\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Create a new iframe callback when this is called so as not to overwrite\r\n // any previous defined callback. This happens if this method is called\r\n // multiple times in parallel and could result in the later callback\r\n // overwriting the previous one. This would end up with a iframe\r\n // timeout.\r\n const cbName = _generateCallbackName('iframefcb');\r\n // GApi loader not available, dynamically load platform.js.\r\n _window()[cbName] = () => {\r\n // GApi loader should be ready.\r\n if (!!gapi.load) {\r\n loadGapiIframe();\r\n }\r\n else {\r\n // Gapi loader failed, throw error.\r\n reject(_createError(auth, \"network-request-failed\" /* NETWORK_REQUEST_FAILED */));\r\n }\r\n };\r\n // Load GApi loader.\r\n return _loadJS(`https://apis.google.com/js/api.js?onload=${cbName}`).catch(e => reject(e));\r\n }\r\n }).catch(error => {\r\n // Reset cached promise to allow for retrial.\r\n cachedGApiLoader = null;\r\n throw error;\r\n });\r\n}\r\nlet cachedGApiLoader = null;\r\nfunction _loadGapi(auth) {\r\n cachedGApiLoader = cachedGApiLoader || loadGapi(auth);\r\n return cachedGApiLoader;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PING_TIMEOUT = new Delay(5000, 15000);\r\nconst IFRAME_PATH = '__/auth/iframe';\r\nconst EMULATED_IFRAME_PATH = 'emulator/auth/iframe';\r\nconst IFRAME_ATTRIBUTES = {\r\n style: {\r\n position: 'absolute',\r\n top: '-100px',\r\n width: '1px',\r\n height: '1px'\r\n },\r\n 'aria-hidden': 'true',\r\n tabindex: '-1'\r\n};\r\n// Map from apiHost to endpoint ID for passing into iframe. In current SDK, apiHost can be set to\r\n// anything (not from a list of endpoints with IDs as in legacy), so this is the closest we can get.\r\nconst EID_FROM_APIHOST = new Map([\r\n [\"identitytoolkit.googleapis.com\" /* API_HOST */, 'p'],\r\n ['staging-identitytoolkit.sandbox.googleapis.com', 's'],\r\n ['test-identitytoolkit.sandbox.googleapis.com', 't'] // test\r\n]);\r\nfunction getIframeUrl(auth) {\r\n const config = auth.config;\r\n _assert(config.authDomain, auth, \"auth-domain-config-required\" /* MISSING_AUTH_DOMAIN */);\r\n const url = config.emulator\r\n ? _emulatorUrl(config, EMULATED_IFRAME_PATH)\r\n : `https://${auth.config.authDomain}/${IFRAME_PATH}`;\r\n const params = {\r\n apiKey: config.apiKey,\r\n appName: auth.name,\r\n v: SDK_VERSION\r\n };\r\n const eid = EID_FROM_APIHOST.get(auth.config.apiHost);\r\n if (eid) {\r\n params.eid = eid;\r\n }\r\n const frameworks = auth._getFrameworks();\r\n if (frameworks.length) {\r\n params.fw = frameworks.join(',');\r\n }\r\n return `${url}?${querystring(params).slice(1)}`;\r\n}\r\nasync function _openIframe(auth) {\r\n const context = await _loadGapi(auth);\r\n const gapi = _window().gapi;\r\n _assert(gapi, auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n return context.open({\r\n where: document.body,\r\n url: getIframeUrl(auth),\r\n messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER,\r\n attributes: IFRAME_ATTRIBUTES,\r\n dontclear: true\r\n }, (iframe) => new Promise(async (resolve, reject) => {\r\n await iframe.restyle({\r\n // Prevent iframe from closing on mouse out.\r\n setHideOnLeave: false\r\n });\r\n const networkError = _createError(auth, \"network-request-failed\" /* NETWORK_REQUEST_FAILED */);\r\n // Confirm iframe is correctly loaded.\r\n // To fallback on failure, set a timeout.\r\n const networkErrorTimer = _window().setTimeout(() => {\r\n reject(networkError);\r\n }, PING_TIMEOUT.get());\r\n // Clear timer and resolve pending iframe ready promise.\r\n function clearTimerAndResolve() {\r\n _window().clearTimeout(networkErrorTimer);\r\n resolve(iframe);\r\n }\r\n // This returns an IThenable. However the reject part does not call\r\n // when the iframe is not loaded.\r\n iframe.ping(clearTimerAndResolve).then(clearTimerAndResolve, () => {\r\n reject(networkError);\r\n });\r\n }));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst BASE_POPUP_OPTIONS = {\r\n location: 'yes',\r\n resizable: 'yes',\r\n statusbar: 'yes',\r\n toolbar: 'no'\r\n};\r\nconst DEFAULT_WIDTH = 500;\r\nconst DEFAULT_HEIGHT = 600;\r\nconst TARGET_BLANK = '_blank';\r\nconst FIREFOX_EMPTY_URL = 'http://localhost';\r\nclass AuthPopup {\r\n constructor(window) {\r\n this.window = window;\r\n this.associatedEvent = null;\r\n }\r\n close() {\r\n if (this.window) {\r\n try {\r\n this.window.close();\r\n }\r\n catch (e) { }\r\n }\r\n }\r\n}\r\nfunction _open(auth, url, name, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT) {\r\n const top = Math.max((window.screen.availHeight - height) / 2, 0).toString();\r\n const left = Math.max((window.screen.availWidth - width) / 2, 0).toString();\r\n let target = '';\r\n const options = Object.assign(Object.assign({}, BASE_POPUP_OPTIONS), { width: width.toString(), height: height.toString(), top,\r\n left });\r\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\r\n // specified, even though the popup is not necessarily blocked.\r\n const ua = getUA().toLowerCase();\r\n if (name) {\r\n target = _isChromeIOS(ua) ? TARGET_BLANK : name;\r\n }\r\n if (_isFirefox(ua)) {\r\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\r\n url = url || FIREFOX_EMPTY_URL;\r\n // Firefox disables by default scrolling on popup windows, which can create\r\n // issues when the user has many Google accounts, for instance.\r\n options.scrollbars = 'yes';\r\n }\r\n const optionsString = Object.entries(options).reduce((accum, [key, value]) => `${accum}${key}=${value},`, '');\r\n if (_isIOSStandalone(ua) && target !== '_self') {\r\n openAsNewWindowIOS(url || '', target);\r\n return new AuthPopup(null);\r\n }\r\n // about:blank getting sanitized causing browsers like IE/Edge to display\r\n // brief error message before redirecting to handler.\r\n const newWin = window.open(url || '', target, optionsString);\r\n _assert(newWin, auth, \"popup-blocked\" /* POPUP_BLOCKED */);\r\n // Flaky on IE edge, encapsulate with a try and catch.\r\n try {\r\n newWin.focus();\r\n }\r\n catch (e) { }\r\n return new AuthPopup(newWin);\r\n}\r\nfunction openAsNewWindowIOS(url, target) {\r\n const el = document.createElement('a');\r\n el.href = url;\r\n el.target = target;\r\n const click = document.createEvent('MouseEvent');\r\n click.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 1, null);\r\n el.dispatchEvent(click);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * URL for Authentication widget which will initiate the OAuth handshake\r\n *\r\n * @internal\r\n */\r\nconst WIDGET_PATH = '__/auth/handler';\r\n/**\r\n * URL for emulated environment\r\n *\r\n * @internal\r\n */\r\nconst EMULATOR_WIDGET_PATH = 'emulator/auth/handler';\r\nfunction _getRedirectUrl(auth, provider, authType, redirectUrl, eventId, additionalParams) {\r\n _assert(auth.config.authDomain, auth, \"auth-domain-config-required\" /* MISSING_AUTH_DOMAIN */);\r\n _assert(auth.config.apiKey, auth, \"invalid-api-key\" /* INVALID_API_KEY */);\r\n const params = {\r\n apiKey: auth.config.apiKey,\r\n appName: auth.name,\r\n authType,\r\n redirectUrl,\r\n v: SDK_VERSION,\r\n eventId\r\n };\r\n if (provider instanceof FederatedAuthProvider) {\r\n provider.setDefaultLanguage(auth.languageCode);\r\n params.providerId = provider.providerId || '';\r\n if (!isEmpty(provider.getCustomParameters())) {\r\n params.customParameters = JSON.stringify(provider.getCustomParameters());\r\n }\r\n // TODO set additionalParams from the provider as well?\r\n for (const [key, value] of Object.entries(additionalParams || {})) {\r\n params[key] = value;\r\n }\r\n }\r\n if (provider instanceof BaseOAuthProvider) {\r\n const scopes = provider.getScopes().filter(scope => scope !== '');\r\n if (scopes.length > 0) {\r\n params.scopes = scopes.join(',');\r\n }\r\n }\r\n if (auth.tenantId) {\r\n params.tid = auth.tenantId;\r\n }\r\n // TODO: maybe set eid as endipointId\r\n // TODO: maybe set fw as Frameworks.join(\",\")\r\n const paramsDict = params;\r\n for (const key of Object.keys(paramsDict)) {\r\n if (paramsDict[key] === undefined) {\r\n delete paramsDict[key];\r\n }\r\n }\r\n return `${getHandlerBase(auth)}?${querystring(paramsDict).slice(1)}`;\r\n}\r\nfunction getHandlerBase({ config }) {\r\n if (!config.emulator) {\r\n return `https://${config.authDomain}/${WIDGET_PATH}`;\r\n }\r\n return _emulatorUrl(config, EMULATOR_WIDGET_PATH);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The special web storage event\r\n *\r\n */\r\nconst WEB_STORAGE_SUPPORT_KEY = 'webStorageSupport';\r\nclass BrowserPopupRedirectResolver {\r\n constructor() {\r\n this.eventManagers = {};\r\n this.iframes = {};\r\n this.originValidationPromises = {};\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._completeRedirectFn = _getRedirectResult;\r\n }\r\n // Wrapping in async even though we don't await anywhere in order\r\n // to make sure errors are raised as promise rejections\r\n async _openPopup(auth, provider, authType, eventId) {\r\n var _a;\r\n debugAssert((_a = this.eventManagers[auth._key()]) === null || _a === void 0 ? void 0 : _a.manager, '_initialize() not called before _openPopup()');\r\n const url = _getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId);\r\n return _open(auth, url, _generateEventId());\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n await this._originValidation(auth);\r\n _setWindowLocation(_getRedirectUrl(auth, provider, authType, _getCurrentUrl(), eventId));\r\n return new Promise(() => { });\r\n }\r\n _initialize(auth) {\r\n const key = auth._key();\r\n if (this.eventManagers[key]) {\r\n const { manager, promise } = this.eventManagers[key];\r\n if (manager) {\r\n return Promise.resolve(manager);\r\n }\r\n else {\r\n debugAssert(promise, 'If manager is not set, promise should be');\r\n return promise;\r\n }\r\n }\r\n const promise = this.initAndGetManager(auth);\r\n this.eventManagers[key] = { promise };\r\n // If the promise is rejected, the key should be removed so that the\r\n // operation can be retried later.\r\n promise.catch(() => {\r\n delete this.eventManagers[key];\r\n });\r\n return promise;\r\n }\r\n async initAndGetManager(auth) {\r\n const iframe = await _openIframe(auth);\r\n const manager = new AuthEventManager(auth);\r\n iframe.register('authEvent', (iframeEvent) => {\r\n _assert(iframeEvent === null || iframeEvent === void 0 ? void 0 : iframeEvent.authEvent, auth, \"invalid-auth-event\" /* INVALID_AUTH_EVENT */);\r\n // TODO: Consider splitting redirect and popup events earlier on\r\n const handled = manager.onEvent(iframeEvent.authEvent);\r\n return { status: handled ? \"ACK\" /* ACK */ : \"ERROR\" /* ERROR */ };\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n this.eventManagers[auth._key()] = { manager };\r\n this.iframes[auth._key()] = iframe;\r\n return manager;\r\n }\r\n _isIframeWebStorageSupported(auth, cb) {\r\n const iframe = this.iframes[auth._key()];\r\n iframe.send(WEB_STORAGE_SUPPORT_KEY, { type: WEB_STORAGE_SUPPORT_KEY }, result => {\r\n var _a;\r\n const isSupported = (_a = result === null || result === void 0 ? void 0 : result[0]) === null || _a === void 0 ? void 0 : _a[WEB_STORAGE_SUPPORT_KEY];\r\n if (isSupported !== undefined) {\r\n cb(!!isSupported);\r\n }\r\n _fail(auth, \"internal-error\" /* INTERNAL_ERROR */);\r\n }, gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n get _shouldInitProactively() {\r\n // Mobile browsers and Safari need to optimistically initialize\r\n return _isMobileBrowser() || _isSafari() || _isIOS();\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for browser\r\n * based applications.\r\n *\r\n * @public\r\n */\r\nconst browserPopupRedirectResolver = BrowserPopupRedirectResolver;\n\nclass MultiFactorAssertionImpl {\r\n constructor(factorId) {\r\n this.factorId = factorId;\r\n }\r\n _process(auth, session, displayName) {\r\n switch (session.type) {\r\n case \"enroll\" /* ENROLL */:\r\n return this._finalizeEnroll(auth, session.credential, displayName);\r\n case \"signin\" /* SIGN_IN */:\r\n return this._finalizeSignIn(auth, session.credential);\r\n default:\r\n return debugFail('unexpected MultiFactorSessionType');\r\n }\r\n }\r\n}\n\n/**\r\n * {@inheritdoc PhoneMultiFactorAssertion}\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl {\r\n constructor(credential) {\r\n super(\"phone\" /* PHONE */);\r\n this.credential = credential;\r\n }\r\n /** @internal */\r\n static _fromCredential(credential) {\r\n return new PhoneMultiFactorAssertionImpl(credential);\r\n }\r\n /** @internal */\r\n _finalizeEnroll(auth, idToken, displayName) {\r\n return finalizeEnrollPhoneMfa(auth, {\r\n idToken,\r\n displayName,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n /** @internal */\r\n _finalizeSignIn(auth, mfaPendingCredential) {\r\n return finalizeSignInPhoneMfa(auth, {\r\n mfaPendingCredential,\r\n phoneVerificationInfo: this.credential._makeVerificationRequest()\r\n });\r\n }\r\n}\r\n/**\r\n * Provider for generating a {@link PhoneMultiFactorAssertion}.\r\n *\r\n * @public\r\n */\r\nclass PhoneMultiFactorGenerator {\r\n constructor() { }\r\n /**\r\n * Provides a {@link PhoneMultiFactorAssertion} to confirm ownership of the phone second factor.\r\n *\r\n * @param phoneAuthCredential - A credential provided by {@link PhoneAuthProvider.credential}.\r\n * @returns A {@link PhoneMultiFactorAssertion} which can be used with\r\n * {@link MultiFactorResolver.resolveSignIn}\r\n */\r\n static assertion(credential) {\r\n return PhoneMultiFactorAssertionImpl._fromCredential(credential);\r\n }\r\n}\r\n/**\r\n * The identifier of the phone second factor: `phone`.\r\n */\r\nPhoneMultiFactorGenerator.FACTOR_ID = 'phone';\n\nvar name = \"@firebase/auth\";\nvar version = \"0.19.12\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AuthInterop {\r\n constructor(auth) {\r\n this.auth = auth;\r\n this.internalListeners = new Map();\r\n }\r\n getUid() {\r\n var _a;\r\n this.assertAuthConfigured();\r\n return ((_a = this.auth.currentUser) === null || _a === void 0 ? void 0 : _a.uid) || null;\r\n }\r\n async getToken(forceRefresh) {\r\n this.assertAuthConfigured();\r\n await this.auth._initializationPromise;\r\n if (!this.auth.currentUser) {\r\n return null;\r\n }\r\n const accessToken = await this.auth.currentUser.getIdToken(forceRefresh);\r\n return { accessToken };\r\n }\r\n addAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n if (this.internalListeners.has(listener)) {\r\n return;\r\n }\r\n const unsubscribe = this.auth.onIdTokenChanged(user => {\r\n var _a;\r\n listener(((_a = user) === null || _a === void 0 ? void 0 : _a.stsTokenManager.accessToken) || null);\r\n });\r\n this.internalListeners.set(listener, unsubscribe);\r\n this.updateProactiveRefresh();\r\n }\r\n removeAuthTokenListener(listener) {\r\n this.assertAuthConfigured();\r\n const unsubscribe = this.internalListeners.get(listener);\r\n if (!unsubscribe) {\r\n return;\r\n }\r\n this.internalListeners.delete(listener);\r\n unsubscribe();\r\n this.updateProactiveRefresh();\r\n }\r\n assertAuthConfigured() {\r\n _assert(this.auth._initializationPromise, \"dependent-sdk-initialized-before-auth\" /* DEPENDENT_SDK_INIT_BEFORE_AUTH */);\r\n }\r\n updateProactiveRefresh() {\r\n if (this.internalListeners.size > 0) {\r\n this.auth._startProactiveRefresh();\r\n }\r\n else {\r\n this.auth._stopProactiveRefresh();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getVersionForPlatform(clientPlatform) {\r\n switch (clientPlatform) {\r\n case \"Node\" /* NODE */:\r\n return 'node';\r\n case \"ReactNative\" /* REACT_NATIVE */:\r\n return 'rn';\r\n case \"Worker\" /* WORKER */:\r\n return 'webworker';\r\n case \"Cordova\" /* CORDOVA */:\r\n return 'cordova';\r\n default:\r\n return undefined;\r\n }\r\n}\r\n/** @internal */\r\nfunction registerAuth(clientPlatform) {\r\n _registerComponent(new Component(\"auth\" /* AUTH */, (container, { options: deps }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const heartbeatServiceProvider = container.getProvider('heartbeat');\r\n const { apiKey, authDomain } = app.options;\r\n return ((app, heartbeatServiceProvider) => {\r\n _assert(apiKey && !apiKey.includes(':'), \"invalid-api-key\" /* INVALID_API_KEY */, { appName: app.name });\r\n // Auth domain is optional if IdP sign in isn't being used\r\n _assert(!(authDomain === null || authDomain === void 0 ? void 0 : authDomain.includes(':')), \"argument-error\" /* ARGUMENT_ERROR */, {\r\n appName: app.name\r\n });\r\n const config = {\r\n apiKey,\r\n authDomain,\r\n clientPlatform,\r\n apiHost: \"identitytoolkit.googleapis.com\" /* API_HOST */,\r\n tokenApiHost: \"securetoken.googleapis.com\" /* TOKEN_API_HOST */,\r\n apiScheme: \"https\" /* API_SCHEME */,\r\n sdkClientVersion: _getClientVersion(clientPlatform)\r\n };\r\n const authInstance = new AuthImpl(app, heartbeatServiceProvider, config);\r\n _initializeAuthInstance(authInstance, deps);\r\n return authInstance;\r\n })(app, heartbeatServiceProvider);\r\n }, \"PUBLIC\" /* PUBLIC */)\r\n /**\r\n * Auth can only be initialized by explicitly calling getAuth() or initializeAuth()\r\n * For why we do this, See go/firebase-next-auth-init\r\n */\r\n .setInstantiationMode(\"EXPLICIT\" /* EXPLICIT */)\r\n /**\r\n * Because all firebase products that depend on auth depend on auth-internal directly,\r\n * we need to initialize auth-internal after auth is initialized to make it available to other firebase products.\r\n */\r\n .setInstanceCreatedCallback((container, _instanceIdentifier, _instance) => {\r\n const authInternalProvider = container.getProvider(\"auth-internal\" /* AUTH_INTERNAL */);\r\n authInternalProvider.initialize();\r\n }));\r\n _registerComponent(new Component(\"auth-internal\" /* AUTH_INTERNAL */, container => {\r\n const auth = _castAuth(container.getProvider(\"auth\" /* AUTH */).getImmediate());\r\n return (auth => new AuthInterop(auth))(auth);\r\n }, \"PRIVATE\" /* PRIVATE */).setInstantiationMode(\"EXPLICIT\" /* EXPLICIT */));\r\n registerVersion(name, version, getVersionForPlatform(clientPlatform));\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the Auth instance associated with the provided {@link @firebase/app#FirebaseApp}.\r\n * If no instance exists, initializes an Auth instance with platform-specific default dependencies.\r\n *\r\n * @param app - The Firebase App.\r\n *\r\n * @public\r\n */\r\nfunction getAuth(app = getApp()) {\r\n const provider = _getProvider(app, 'auth');\r\n if (provider.isInitialized()) {\r\n return provider.getImmediate();\r\n }\r\n return initializeAuth(app, {\r\n popupRedirectResolver: browserPopupRedirectResolver,\r\n persistence: [\r\n indexedDBLocalPersistence,\r\n browserLocalPersistence,\r\n browserSessionPersistence\r\n ]\r\n });\r\n}\r\nregisterAuth(\"Browser\" /* BROWSER */);\n\nexport { sendPasswordResetEmail as $, ActionCodeOperation as A, prodErrorMap as B, AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY as C, initializeAuth as D, connectAuthEmulator as E, FactorId as F, AuthCredential as G, EmailAuthCredential as H, OAuthCredential as I, PhoneAuthCredential as J, inMemoryPersistence as K, EmailAuthProvider as L, FacebookAuthProvider as M, GoogleAuthProvider as N, OperationType as O, PhoneAuthProvider as P, GithubAuthProvider as Q, RecaptchaVerifier as R, SignInMethod as S, OAuthProvider as T, SAMLAuthProvider as U, TwitterAuthProvider as V, signInAnonymously as W, signInWithCredential as X, linkWithCredential as Y, reauthenticateWithCredential as Z, signInWithCustomToken as _, browserSessionPersistence as a, confirmPasswordReset as a0, applyActionCode as a1, checkActionCode as a2, verifyPasswordResetCode as a3, createUserWithEmailAndPassword as a4, signInWithEmailAndPassword as a5, sendSignInLinkToEmail as a6, isSignInWithEmailLink as a7, signInWithEmailLink as a8, fetchSignInMethodsForEmail as a9, _getRedirectResult as aA, _clearRedirectOutcomes as aB, _castAuth as aC, UserImpl as aD, AuthImpl as aE, _getClientVersion as aF, _generateEventId as aG, AuthPopup as aH, FetchProvider as aI, SAMLAuthCredential as aJ, sendEmailVerification as aa, verifyBeforeUpdateEmail as ab, ActionCodeURL as ac, parseActionCodeURL as ad, updateProfile as ae, updateEmail as af, updatePassword as ag, getIdToken as ah, getIdTokenResult as ai, unlink as aj, getAdditionalUserInfo as ak, reload as al, getMultiFactorResolver as am, multiFactor as an, _isIOS7Or8 as ao, debugAssert as ap, _isIOS as aq, _isAndroid as ar, _fail as as, _getRedirectUrl as at, _getProjectConfig as au, _createError as av, _assert as aw, _getInstance as ax, _persistenceKeyName as ay, AuthEventManager as az, browserLocalPersistence as b, signInWithPopup as c, linkWithPopup as d, reauthenticateWithPopup as e, signInWithRedirect as f, linkWithRedirect as g, reauthenticateWithRedirect as h, indexedDBLocalPersistence as i, getRedirectResult as j, browserPopupRedirectResolver as k, linkWithPhoneNumber as l, PhoneMultiFactorGenerator as m, getAuth as n, ProviderId as o, setPersistence as p, onIdTokenChanged as q, reauthenticateWithPhoneNumber as r, signInWithPhoneNumber as s, onAuthStateChanged as t, updatePhoneNumber as u, useDeviceLanguage as v, updateCurrentUser as w, signOut as x, deleteUser as y, debugErrorMap as z };\n//# sourceMappingURL=index-7078a255.js.map\n","import { ao as _isIOS7Or8, ap as debugAssert, aq as _isIOS, ar as _isAndroid, as as _fail, at as _getRedirectUrl, au as _getProjectConfig, av as _createError, aw as _assert, ax as _getInstance, b as browserLocalPersistence, ay as _persistenceKeyName, az as AuthEventManager, a as browserSessionPersistence, aA as _getRedirectResult, aB as _clearRedirectOutcomes, aC as _castAuth } from './index-7078a255.js';\nexport { A as ActionCodeOperation, ac as ActionCodeURL, G as AuthCredential, C as AuthErrorCodes, aE as AuthImpl, aH as AuthPopup, H as EmailAuthCredential, L as EmailAuthProvider, M as FacebookAuthProvider, F as FactorId, aI as FetchProvider, Q as GithubAuthProvider, N as GoogleAuthProvider, I as OAuthCredential, T as OAuthProvider, O as OperationType, J as PhoneAuthCredential, P as PhoneAuthProvider, m as PhoneMultiFactorGenerator, o as ProviderId, R as RecaptchaVerifier, aJ as SAMLAuthCredential, U as SAMLAuthProvider, S as SignInMethod, V as TwitterAuthProvider, aD as UserImpl, aw as _assert, aC as _castAuth, as as _fail, aG as _generateEventId, aF as _getClientVersion, ax as _getInstance, aA as _getRedirectResult, ay as _persistenceKeyName, a1 as applyActionCode, b as browserLocalPersistence, k as browserPopupRedirectResolver, a as browserSessionPersistence, a2 as checkActionCode, a0 as confirmPasswordReset, E as connectAuthEmulator, a4 as createUserWithEmailAndPassword, z as debugErrorMap, y as deleteUser, a9 as fetchSignInMethodsForEmail, ak as getAdditionalUserInfo, n as getAuth, ah as getIdToken, ai as getIdTokenResult, am as getMultiFactorResolver, j as getRedirectResult, K as inMemoryPersistence, i as indexedDBLocalPersistence, D as initializeAuth, a7 as isSignInWithEmailLink, Y as linkWithCredential, l as linkWithPhoneNumber, d as linkWithPopup, g as linkWithRedirect, an as multiFactor, t as onAuthStateChanged, q as onIdTokenChanged, ad as parseActionCodeURL, B as prodErrorMap, Z as reauthenticateWithCredential, r as reauthenticateWithPhoneNumber, e as reauthenticateWithPopup, h as reauthenticateWithRedirect, al as reload, aa as sendEmailVerification, $ as sendPasswordResetEmail, a6 as sendSignInLinkToEmail, p as setPersistence, W as signInAnonymously, X as signInWithCredential, _ as signInWithCustomToken, a5 as signInWithEmailAndPassword, a8 as signInWithEmailLink, s as signInWithPhoneNumber, c as signInWithPopup, f as signInWithRedirect, x as signOut, aj as unlink, w as updateCurrentUser, af as updateEmail, ag as updatePassword, u as updatePhoneNumber, ae as updateProfile, v as useDeviceLanguage, ab as verifyBeforeUpdateEmail, a3 as verifyPasswordResetCode } from './index-7078a255.js';\nimport { querystringDecode } from '@firebase/util';\nimport '@firebase/app';\nimport 'tslib';\nimport '@firebase/logger';\nimport '@firebase/component';\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction _cordovaWindow() {\r\n return window;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * How long to wait after the app comes back into focus before concluding that\r\n * the user closed the sign in tab.\r\n */\r\nconst REDIRECT_TIMEOUT_MS = 2000;\r\n/**\r\n * Generates the URL for the OAuth handler.\r\n */\r\nasync function _generateHandlerUrl(auth, event, provider) {\r\n var _a;\r\n // Get the cordova plugins\r\n const { BuildInfo } = _cordovaWindow();\r\n debugAssert(event.sessionId, 'AuthEvent did not contain a session ID');\r\n const sessionDigest = await computeSha256(event.sessionId);\r\n const additionalParams = {};\r\n if (_isIOS()) {\r\n // iOS app identifier\r\n additionalParams['ibi'] = BuildInfo.packageName;\r\n }\r\n else if (_isAndroid()) {\r\n // Android app identifier\r\n additionalParams['apn'] = BuildInfo.packageName;\r\n }\r\n else {\r\n _fail(auth, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n }\r\n // Add the display name if available\r\n if (BuildInfo.displayName) {\r\n additionalParams['appDisplayName'] = BuildInfo.displayName;\r\n }\r\n // Attached the hashed session ID\r\n additionalParams['sessionId'] = sessionDigest;\r\n return _getRedirectUrl(auth, provider, event.type, undefined, (_a = event.eventId) !== null && _a !== void 0 ? _a : undefined, additionalParams);\r\n}\r\n/**\r\n * Validates that this app is valid for this project configuration\r\n */\r\nasync function _validateOrigin(auth) {\r\n const { BuildInfo } = _cordovaWindow();\r\n const request = {};\r\n if (_isIOS()) {\r\n request.iosBundleId = BuildInfo.packageName;\r\n }\r\n else if (_isAndroid()) {\r\n request.androidPackageName = BuildInfo.packageName;\r\n }\r\n else {\r\n _fail(auth, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n }\r\n // Will fail automatically if package name is not authorized\r\n await _getProjectConfig(auth, request);\r\n}\r\nfunction _performRedirect(handlerUrl) {\r\n // Get the cordova plugins\r\n const { cordova } = _cordovaWindow();\r\n return new Promise(resolve => {\r\n cordova.plugins.browsertab.isAvailable(browserTabIsAvailable => {\r\n let iabRef = null;\r\n if (browserTabIsAvailable) {\r\n cordova.plugins.browsertab.openUrl(handlerUrl);\r\n }\r\n else {\r\n // TODO: Return the inappbrowser ref that's returned from the open call\r\n iabRef = cordova.InAppBrowser.open(handlerUrl, _isIOS7Or8() ? '_blank' : '_system', 'location=yes');\r\n }\r\n resolve(iabRef);\r\n });\r\n });\r\n}\r\n/**\r\n * This function waits for app activity to be seen before resolving. It does\r\n * this by attaching listeners to various dom events. Once the app is determined\r\n * to be visible, this promise resolves. AFTER that resolution, the listeners\r\n * are detached and any browser tabs left open will be closed.\r\n */\r\nasync function _waitForAppResume(auth, eventListener, iabRef) {\r\n // Get the cordova plugins\r\n const { cordova } = _cordovaWindow();\r\n let cleanup = () => { };\r\n try {\r\n await new Promise((resolve, reject) => {\r\n let onCloseTimer = null;\r\n // DEFINE ALL THE CALLBACKS =====\r\n function authEventSeen() {\r\n var _a;\r\n // Auth event was detected. Resolve this promise and close the extra\r\n // window if it's still open.\r\n resolve();\r\n const closeBrowserTab = (_a = cordova.plugins.browsertab) === null || _a === void 0 ? void 0 : _a.close;\r\n if (typeof closeBrowserTab === 'function') {\r\n closeBrowserTab();\r\n }\r\n // Close inappbrowser emebedded webview in iOS7 and 8 case if still\r\n // open.\r\n if (typeof (iabRef === null || iabRef === void 0 ? void 0 : iabRef.close) === 'function') {\r\n iabRef.close();\r\n }\r\n }\r\n function resumed() {\r\n if (onCloseTimer) {\r\n // This code already ran; do not rerun.\r\n return;\r\n }\r\n onCloseTimer = window.setTimeout(() => {\r\n // Wait two seeconds after resume then reject.\r\n reject(_createError(auth, \"redirect-cancelled-by-user\" /* REDIRECT_CANCELLED_BY_USER */));\r\n }, REDIRECT_TIMEOUT_MS);\r\n }\r\n function visibilityChanged() {\r\n if ((document === null || document === void 0 ? void 0 : document.visibilityState) === 'visible') {\r\n resumed();\r\n }\r\n }\r\n // ATTACH ALL THE LISTENERS =====\r\n // Listen for the auth event\r\n eventListener.addPassiveListener(authEventSeen);\r\n // Listen for resume and visibility events\r\n document.addEventListener('resume', resumed, false);\r\n if (_isAndroid()) {\r\n document.addEventListener('visibilitychange', visibilityChanged, false);\r\n }\r\n // SETUP THE CLEANUP FUNCTION =====\r\n cleanup = () => {\r\n eventListener.removePassiveListener(authEventSeen);\r\n document.removeEventListener('resume', resumed, false);\r\n document.removeEventListener('visibilitychange', visibilityChanged, false);\r\n if (onCloseTimer) {\r\n window.clearTimeout(onCloseTimer);\r\n }\r\n };\r\n });\r\n }\r\n finally {\r\n cleanup();\r\n }\r\n}\r\n/**\r\n * Checks the configuration of the Cordova environment. This has no side effect\r\n * if the configuration is correct; otherwise it throws an error with the\r\n * missing plugin.\r\n */\r\nfunction _checkCordovaConfiguration(auth) {\r\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;\r\n const win = _cordovaWindow();\r\n // Check all dependencies installed.\r\n // https://github.com/nordnet/cordova-universal-links-plugin\r\n // Note that cordova-universal-links-plugin has been abandoned.\r\n // A fork with latest fixes is available at:\r\n // https://www.npmjs.com/package/cordova-universal-links-plugin-fix\r\n _assert(typeof ((_a = win === null || win === void 0 ? void 0 : win.universalLinks) === null || _a === void 0 ? void 0 : _a.subscribe) === 'function', auth, \"invalid-cordova-configuration\" /* INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-universal-links-plugin-fix'\r\n });\r\n // https://www.npmjs.com/package/cordova-plugin-buildinfo\r\n _assert(typeof ((_b = win === null || win === void 0 ? void 0 : win.BuildInfo) === null || _b === void 0 ? void 0 : _b.packageName) !== 'undefined', auth, \"invalid-cordova-configuration\" /* INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-buildInfo'\r\n });\r\n // https://github.com/google/cordova-plugin-browsertab\r\n _assert(typeof ((_e = (_d = (_c = win === null || win === void 0 ? void 0 : win.cordova) === null || _c === void 0 ? void 0 : _c.plugins) === null || _d === void 0 ? void 0 : _d.browsertab) === null || _e === void 0 ? void 0 : _e.openUrl) === 'function', auth, \"invalid-cordova-configuration\" /* INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-browsertab'\r\n });\r\n _assert(typeof ((_h = (_g = (_f = win === null || win === void 0 ? void 0 : win.cordova) === null || _f === void 0 ? void 0 : _f.plugins) === null || _g === void 0 ? void 0 : _g.browsertab) === null || _h === void 0 ? void 0 : _h.isAvailable) === 'function', auth, \"invalid-cordova-configuration\" /* INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-browsertab'\r\n });\r\n // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/\r\n _assert(typeof ((_k = (_j = win === null || win === void 0 ? void 0 : win.cordova) === null || _j === void 0 ? void 0 : _j.InAppBrowser) === null || _k === void 0 ? void 0 : _k.open) === 'function', auth, \"invalid-cordova-configuration\" /* INVALID_CORDOVA_CONFIGURATION */, {\r\n missingPlugin: 'cordova-plugin-inappbrowser'\r\n });\r\n}\r\n/**\r\n * Computes the SHA-256 of a session ID. The SubtleCrypto interface is only\r\n * available in \"secure\" contexts, which covers Cordova (which is served on a file\r\n * protocol).\r\n */\r\nasync function computeSha256(sessionId) {\r\n const bytes = stringToArrayBuffer(sessionId);\r\n // TODO: For IE11 crypto has a different name and this operation comes back\r\n // as an object, not a promise. This is the old proposed standard that\r\n // is used by IE11:\r\n // https://www.w3.org/TR/2013/WD-WebCryptoAPI-20130108/#cryptooperation-interface\r\n const buf = await crypto.subtle.digest('SHA-256', bytes);\r\n const arr = Array.from(new Uint8Array(buf));\r\n return arr.map(num => num.toString(16).padStart(2, '0')).join('');\r\n}\r\nfunction stringToArrayBuffer(str) {\r\n // This function is only meant to deal with an ASCII charset and makes\r\n // certain simplifying assumptions.\r\n debugAssert(/[0-9a-zA-Z]+/.test(str), 'Can only convert alpha-numeric strings');\r\n if (typeof TextEncoder !== 'undefined') {\r\n return new TextEncoder().encode(str);\r\n }\r\n const buff = new ArrayBuffer(str.length);\r\n const view = new Uint8Array(buff);\r\n for (let i = 0; i < str.length; i++) {\r\n view[i] = str.charCodeAt(i);\r\n }\r\n return view;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SESSION_ID_LENGTH = 20;\r\n/** Custom AuthEventManager that adds passive listeners to events */\r\nclass CordovaAuthEventManager extends AuthEventManager {\r\n constructor() {\r\n super(...arguments);\r\n this.passiveListeners = new Set();\r\n this.initPromise = new Promise(resolve => {\r\n this.resolveInialized = resolve;\r\n });\r\n }\r\n addPassiveListener(cb) {\r\n this.passiveListeners.add(cb);\r\n }\r\n removePassiveListener(cb) {\r\n this.passiveListeners.delete(cb);\r\n }\r\n // In a Cordova environment, this manager can live through multiple redirect\r\n // operations\r\n resetRedirect() {\r\n this.queuedRedirectEvent = null;\r\n this.hasHandledPotentialRedirect = false;\r\n }\r\n /** Override the onEvent method */\r\n onEvent(event) {\r\n this.resolveInialized();\r\n this.passiveListeners.forEach(cb => cb(event));\r\n return super.onEvent(event);\r\n }\r\n async initialized() {\r\n await this.initPromise;\r\n }\r\n}\r\n/**\r\n * Generates a (partial) {@link AuthEvent}.\r\n */\r\nfunction _generateNewEvent(auth, type, eventId = null) {\r\n return {\r\n type,\r\n eventId,\r\n urlResponse: null,\r\n sessionId: generateSessionId(),\r\n postBody: null,\r\n tenantId: auth.tenantId,\r\n error: _createError(auth, \"no-auth-event\" /* NO_AUTH_EVENT */)\r\n };\r\n}\r\nfunction _savePartialEvent(auth, event) {\r\n return storage()._set(persistenceKey(auth), event);\r\n}\r\nasync function _getAndRemoveEvent(auth) {\r\n const event = (await storage()._get(persistenceKey(auth)));\r\n if (event) {\r\n await storage()._remove(persistenceKey(auth));\r\n }\r\n return event;\r\n}\r\nfunction _eventFromPartialAndUrl(partialEvent, url) {\r\n var _a, _b;\r\n // Parse the deep link within the dynamic link URL.\r\n const callbackUrl = _getDeepLinkFromCallback(url);\r\n // Confirm it is actually a callback URL.\r\n // Currently the universal link will be of this format:\r\n // https:///__/auth/callback\r\n // This is a fake URL but is not intended to take the user anywhere\r\n // and just redirect to the app.\r\n if (callbackUrl.includes('/__/auth/callback')) {\r\n // Check if there is an error in the URL.\r\n // This mechanism is also used to pass errors back to the app:\r\n // https:///__/auth/callback?firebaseError=\r\n const params = searchParamsOrEmpty(callbackUrl);\r\n // Get the error object corresponding to the stringified error if found.\r\n const errorObject = params['firebaseError']\r\n ? parseJsonOrNull(decodeURIComponent(params['firebaseError']))\r\n : null;\r\n const code = (_b = (_a = errorObject === null || errorObject === void 0 ? void 0 : errorObject['code']) === null || _a === void 0 ? void 0 : _a.split('auth/')) === null || _b === void 0 ? void 0 : _b[1];\r\n const error = code ? _createError(code) : null;\r\n if (error) {\r\n return {\r\n type: partialEvent.type,\r\n eventId: partialEvent.eventId,\r\n tenantId: partialEvent.tenantId,\r\n error,\r\n urlResponse: null,\r\n sessionId: null,\r\n postBody: null\r\n };\r\n }\r\n else {\r\n return {\r\n type: partialEvent.type,\r\n eventId: partialEvent.eventId,\r\n tenantId: partialEvent.tenantId,\r\n sessionId: partialEvent.sessionId,\r\n urlResponse: callbackUrl,\r\n postBody: null\r\n };\r\n }\r\n }\r\n return null;\r\n}\r\nfunction generateSessionId() {\r\n const chars = [];\r\n const allowedChars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\r\n for (let i = 0; i < SESSION_ID_LENGTH; i++) {\r\n const idx = Math.floor(Math.random() * allowedChars.length);\r\n chars.push(allowedChars.charAt(idx));\r\n }\r\n return chars.join('');\r\n}\r\nfunction storage() {\r\n return _getInstance(browserLocalPersistence);\r\n}\r\nfunction persistenceKey(auth) {\r\n return _persistenceKeyName(\"authEvent\" /* AUTH_EVENT */, auth.config.apiKey, auth.name);\r\n}\r\nfunction parseJsonOrNull(json) {\r\n try {\r\n return JSON.parse(json);\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n}\r\n// Exported for testing\r\nfunction _getDeepLinkFromCallback(url) {\r\n const params = searchParamsOrEmpty(url);\r\n const link = params['link'] ? decodeURIComponent(params['link']) : undefined;\r\n // Double link case (automatic redirect)\r\n const doubleDeepLink = searchParamsOrEmpty(link)['link'];\r\n // iOS custom scheme links.\r\n const iOSDeepLink = params['deep_link_id']\r\n ? decodeURIComponent(params['deep_link_id'])\r\n : undefined;\r\n const iOSDoubleDeepLink = searchParamsOrEmpty(iOSDeepLink)['link'];\r\n return iOSDoubleDeepLink || iOSDeepLink || doubleDeepLink || link || url;\r\n}\r\n/**\r\n * Optimistically tries to get search params from a string, or else returns an\r\n * empty search params object.\r\n */\r\nfunction searchParamsOrEmpty(url) {\r\n if (!(url === null || url === void 0 ? void 0 : url.includes('?'))) {\r\n return {};\r\n }\r\n const [_, ...rest] = url.split('?');\r\n return querystringDecode(rest.join('?'));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * How long to wait for the initial auth event before concluding no\r\n * redirect pending\r\n */\r\nconst INITIAL_EVENT_TIMEOUT_MS = 500;\r\nclass CordovaPopupRedirectResolver {\r\n constructor() {\r\n this._redirectPersistence = browserSessionPersistence;\r\n this._shouldInitProactively = true; // This is lightweight for Cordova\r\n this.eventManagers = new Map();\r\n this.originValidationPromises = {};\r\n this._completeRedirectFn = _getRedirectResult;\r\n }\r\n async _initialize(auth) {\r\n const key = auth._key();\r\n let manager = this.eventManagers.get(key);\r\n if (!manager) {\r\n manager = new CordovaAuthEventManager(auth);\r\n this.eventManagers.set(key, manager);\r\n this.attachCallbackListeners(auth, manager);\r\n }\r\n return manager;\r\n }\r\n _openPopup(auth) {\r\n _fail(auth, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n _checkCordovaConfiguration(auth);\r\n const manager = await this._initialize(auth);\r\n await manager.initialized();\r\n // Reset the persisted redirect states. This does not matter on Web where\r\n // the redirect always blows away application state entirely. On Cordova,\r\n // the app maintains control flow through the redirect.\r\n manager.resetRedirect();\r\n _clearRedirectOutcomes();\r\n await this._originValidation(auth);\r\n const event = _generateNewEvent(auth, authType, eventId);\r\n await _savePartialEvent(auth, event);\r\n const url = await _generateHandlerUrl(auth, event, provider);\r\n const iabRef = await _performRedirect(url);\r\n return _waitForAppResume(auth, manager, iabRef);\r\n }\r\n _isIframeWebStorageSupported(_auth, _cb) {\r\n throw new Error('Method not implemented.');\r\n }\r\n _originValidation(auth) {\r\n const key = auth._key();\r\n if (!this.originValidationPromises[key]) {\r\n this.originValidationPromises[key] = _validateOrigin(auth);\r\n }\r\n return this.originValidationPromises[key];\r\n }\r\n attachCallbackListeners(auth, manager) {\r\n // Get the global plugins\r\n const { universalLinks, handleOpenURL, BuildInfo } = _cordovaWindow();\r\n const noEventTimeout = setTimeout(async () => {\r\n // We didn't see that initial event. Clear any pending object and\r\n // dispatch no event\r\n await _getAndRemoveEvent(auth);\r\n manager.onEvent(generateNoEvent());\r\n }, INITIAL_EVENT_TIMEOUT_MS);\r\n const universalLinksCb = async (eventData) => {\r\n // We have an event so we can clear the no event timeout\r\n clearTimeout(noEventTimeout);\r\n const partialEvent = await _getAndRemoveEvent(auth);\r\n let finalEvent = null;\r\n if (partialEvent && (eventData === null || eventData === void 0 ? void 0 : eventData['url'])) {\r\n finalEvent = _eventFromPartialAndUrl(partialEvent, eventData['url']);\r\n }\r\n // If finalEvent is never filled, trigger with no event\r\n manager.onEvent(finalEvent || generateNoEvent());\r\n };\r\n // Universal links subscriber doesn't exist for iOS, so we need to check\r\n if (typeof universalLinks !== 'undefined' &&\r\n typeof universalLinks.subscribe === 'function') {\r\n universalLinks.subscribe(null, universalLinksCb);\r\n }\r\n // iOS 7 or 8 custom URL schemes.\r\n // This is also the current default behavior for iOS 9+.\r\n // For this to work, cordova-plugin-customurlscheme needs to be installed.\r\n // https://github.com/EddyVerbruggen/Custom-URL-scheme\r\n // Do not overwrite the existing developer's URL handler.\r\n const existingHandleOpenURL = handleOpenURL;\r\n const packagePrefix = `${BuildInfo.packageName.toLowerCase()}://`;\r\n _cordovaWindow().handleOpenURL = async (url) => {\r\n if (url.toLowerCase().startsWith(packagePrefix)) {\r\n // We want this intentionally to float\r\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\r\n universalLinksCb({ url });\r\n }\r\n // Call the developer's handler if it is present.\r\n if (typeof existingHandleOpenURL === 'function') {\r\n try {\r\n existingHandleOpenURL(url);\r\n }\r\n catch (e) {\r\n // This is a developer error. Don't stop the flow of the SDK.\r\n console.error(e);\r\n }\r\n }\r\n };\r\n }\r\n}\r\n/**\r\n * An implementation of {@link PopupRedirectResolver} suitable for Cordova\r\n * based applications.\r\n *\r\n * @public\r\n */\r\nconst cordovaPopupRedirectResolver = CordovaPopupRedirectResolver;\r\nfunction generateNoEvent() {\r\n return {\r\n type: \"unknown\" /* UNKNOWN */,\r\n eventId: null,\r\n sessionId: null,\r\n urlResponse: null,\r\n postBody: null,\r\n tenantId: null,\r\n error: _createError(\"no-auth-event\" /* NO_AUTH_EVENT */)\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\r\n// It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it out\r\n// of autogenerated documentation pages to reduce accidental misuse.\r\nfunction addFrameworkForLogging(auth, framework) {\r\n _castAuth(auth)._logFramework(framework);\r\n}\n\nexport { addFrameworkForLogging, cordovaPopupRedirectResolver };\n//# sourceMappingURL=internal.js.map\n","import '@firebase/auth-compat';\n//# sourceMappingURL=index.esm.js.map\n","import { getApp, _getProvider, _registerComponent, registerVersion } from '@firebase/app';\nimport { Component } from '@firebase/component';\nimport { ErrorFactory, FirebaseError, openDB } from '@firebase/util';\n\nconst name = \"@firebase/installations\";\nconst version = \"0.5.8\";\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst PENDING_TIMEOUT_MS = 10000;\r\nconst PACKAGE_VERSION = `w:${version}`;\r\nconst INTERNAL_AUTH_VERSION = 'FIS_v2';\r\nconst INSTALLATIONS_API_URL = 'https://firebaseinstallations.googleapis.com/v1';\r\nconst TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\r\nconst SERVICE = 'installations';\r\nconst SERVICE_NAME = 'Installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERROR_DESCRIPTION_MAP = {\r\n [\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */]: 'Missing App configuration value: \"{$valueName}\"',\r\n [\"not-registered\" /* NOT_REGISTERED */]: 'Firebase Installation is not registered.',\r\n [\"installation-not-found\" /* INSTALLATION_NOT_FOUND */]: 'Firebase Installation not found.',\r\n [\"request-failed\" /* REQUEST_FAILED */]: '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\r\n [\"app-offline\" /* APP_OFFLINE */]: 'Could not process request. Application offline.',\r\n [\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */]: \"Can't delete installation while there is a pending registration request.\"\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory(SERVICE, SERVICE_NAME, ERROR_DESCRIPTION_MAP);\r\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\r\nfunction isServerError(error) {\r\n return (error instanceof FirebaseError &&\r\n error.code.includes(\"request-failed\" /* REQUEST_FAILED */));\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction getInstallationsEndpoint({ projectId }) {\r\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\r\n}\r\nfunction extractAuthTokenInfoFromResponse(response) {\r\n return {\r\n token: response.token,\r\n requestStatus: 2 /* COMPLETED */,\r\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\r\n creationTime: Date.now()\r\n };\r\n}\r\nasync function getErrorFromResponse(requestName, response) {\r\n const responseJson = await response.json();\r\n const errorData = responseJson.error;\r\n return ERROR_FACTORY.create(\"request-failed\" /* REQUEST_FAILED */, {\r\n requestName,\r\n serverCode: errorData.code,\r\n serverMessage: errorData.message,\r\n serverStatus: errorData.status\r\n });\r\n}\r\nfunction getHeaders({ apiKey }) {\r\n return new Headers({\r\n 'Content-Type': 'application/json',\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\nfunction getHeadersWithAuth(appConfig, { refreshToken }) {\r\n const headers = getHeaders(appConfig);\r\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\r\n return headers;\r\n}\r\n/**\r\n * Calls the passed in fetch wrapper and returns the response.\r\n * If the returned response has a status of 5xx, re-runs the function once and\r\n * returns the response.\r\n */\r\nasync function retryIfServerError(fn) {\r\n const result = await fn();\r\n if (result.status >= 500 && result.status < 600) {\r\n // Internal Server Error. Retry request.\r\n return fn();\r\n }\r\n return result;\r\n}\r\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn) {\r\n // This works because the server will never respond with fractions of a second.\r\n return Number(responseExpiresIn.replace('s', '000'));\r\n}\r\nfunction getAuthorizationHeader(refreshToken) {\r\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function createInstallationRequest({ appConfig, heartbeatServiceProvider }, { fid }) {\r\n const endpoint = getInstallationsEndpoint(appConfig);\r\n const headers = getHeaders(appConfig);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n fid,\r\n authVersion: INTERNAL_AUTH_VERSION,\r\n appId: appConfig.appId,\r\n sdkVersion: PACKAGE_VERSION\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const registeredInstallationEntry = {\r\n fid: responseValue.fid || fid,\r\n registrationStatus: 2 /* COMPLETED */,\r\n refreshToken: responseValue.refreshToken,\r\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\r\n };\r\n return registeredInstallationEntry;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Create Installation', response);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a promise that resolves after given time passes. */\r\nfunction sleep(ms) {\r\n return new Promise(resolve => {\r\n setTimeout(resolve, ms);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction bufferToBase64UrlSafe(array) {\r\n const b64 = btoa(String.fromCharCode(...array));\r\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\r\nconst INVALID_FID = '';\r\n/**\r\n * Generates a new FID using random values from Web Crypto API.\r\n * Returns an empty string if FID generation fails for any reason.\r\n */\r\nfunction generateFid() {\r\n try {\r\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\r\n // bytes. our implementation generates a 17 byte array instead.\r\n const fidByteArray = new Uint8Array(17);\r\n const crypto = self.crypto || self.msCrypto;\r\n crypto.getRandomValues(fidByteArray);\r\n // Replace the first 4 random bits with the constant FID header of 0b0111.\r\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\r\n const fid = encode(fidByteArray);\r\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\r\n }\r\n catch (_a) {\r\n // FID generation errored\r\n return INVALID_FID;\r\n }\r\n}\r\n/** Converts a FID Uint8Array to a base64 string representation. */\r\nfunction encode(fidByteArray) {\r\n const b64String = bufferToBase64UrlSafe(fidByteArray);\r\n // Remove the 23rd character that was added because of the extra 4 bits at the\r\n // end of our 17 byte array, and the '=' padding.\r\n return b64String.substr(0, 22);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Returns a string key that can be used to identify the app. */\r\nfunction getKey(appConfig) {\r\n return `${appConfig.appName}!${appConfig.appId}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst fidChangeCallbacks = new Map();\r\n/**\r\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\r\n * change to other tabs.\r\n */\r\nfunction fidChanged(appConfig, fid) {\r\n const key = getKey(appConfig);\r\n callFidChangeCallbacks(key, fid);\r\n broadcastFidChange(key, fid);\r\n}\r\nfunction addCallback(appConfig, callback) {\r\n // Open the broadcast channel if it's not already open,\r\n // to be able to listen to change events from other tabs.\r\n getBroadcastChannel();\r\n const key = getKey(appConfig);\r\n let callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n callbackSet = new Set();\r\n fidChangeCallbacks.set(key, callbackSet);\r\n }\r\n callbackSet.add(callback);\r\n}\r\nfunction removeCallback(appConfig, callback) {\r\n const key = getKey(appConfig);\r\n const callbackSet = fidChangeCallbacks.get(key);\r\n if (!callbackSet) {\r\n return;\r\n }\r\n callbackSet.delete(callback);\r\n if (callbackSet.size === 0) {\r\n fidChangeCallbacks.delete(key);\r\n }\r\n // Close broadcast channel if there are no more callbacks.\r\n closeBroadcastChannel();\r\n}\r\nfunction callFidChangeCallbacks(key, fid) {\r\n const callbacks = fidChangeCallbacks.get(key);\r\n if (!callbacks) {\r\n return;\r\n }\r\n for (const callback of callbacks) {\r\n callback(fid);\r\n }\r\n}\r\nfunction broadcastFidChange(key, fid) {\r\n const channel = getBroadcastChannel();\r\n if (channel) {\r\n channel.postMessage({ key, fid });\r\n }\r\n closeBroadcastChannel();\r\n}\r\nlet broadcastChannel = null;\r\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\r\nfunction getBroadcastChannel() {\r\n if (!broadcastChannel && 'BroadcastChannel' in self) {\r\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\r\n broadcastChannel.onmessage = e => {\r\n callFidChangeCallbacks(e.data.key, e.data.fid);\r\n };\r\n }\r\n return broadcastChannel;\r\n}\r\nfunction closeBroadcastChannel() {\r\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\r\n broadcastChannel.close();\r\n broadcastChannel = null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst DATABASE_NAME = 'firebase-installations-database';\r\nconst DATABASE_VERSION = 1;\r\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\r\nlet dbPromise = null;\r\nfunction getDbPromise() {\r\n if (!dbPromise) {\r\n dbPromise = openDB(DATABASE_NAME, DATABASE_VERSION, (db, oldVersion) => {\r\n // We don't use 'break' in this switch statement, the fall-through\r\n // behavior is what we want, because if there are multiple versions between\r\n // the old version and the current version, we want ALL the migrations\r\n // that correspond to those versions to run, not only the last one.\r\n // eslint-disable-next-line default-case\r\n switch (oldVersion) {\r\n case 0:\r\n db.createObjectStore(OBJECT_STORE_NAME);\r\n }\r\n });\r\n }\r\n return dbPromise;\r\n}\r\n/** Assigns or overwrites the record for the given key with the given value. */\r\nasync function set(appConfig, value) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await objectStore.get(key));\r\n await objectStore.put(value, key);\r\n await tx.complete;\r\n if (!oldValue || oldValue.fid !== value.fid) {\r\n fidChanged(appConfig, value.fid);\r\n }\r\n return value;\r\n}\r\n/** Removes record(s) from the objectStore that match the given key. */\r\nasync function remove(appConfig) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\r\n await tx.complete;\r\n}\r\n/**\r\n * Atomically updates a record with the result of updateFn, which gets\r\n * called with the current value. If newValue is undefined, the record is\r\n * deleted instead.\r\n * @return Updated value\r\n */\r\nasync function update(appConfig, updateFn) {\r\n const key = getKey(appConfig);\r\n const db = await getDbPromise();\r\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\r\n const store = tx.objectStore(OBJECT_STORE_NAME);\r\n const oldValue = (await store.get(key));\r\n const newValue = updateFn(oldValue);\r\n if (newValue === undefined) {\r\n await store.delete(key);\r\n }\r\n else {\r\n await store.put(newValue, key);\r\n }\r\n await tx.complete;\r\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\r\n fidChanged(appConfig, newValue.fid);\r\n }\r\n return newValue;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Updates and returns the InstallationEntry from the database.\r\n * Also triggers a registration request if it is necessary and possible.\r\n */\r\nasync function getInstallationEntry(installations) {\r\n let registrationPromise;\r\n const installationEntry = await update(installations.appConfig, oldEntry => {\r\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\r\n const entryWithPromise = triggerRegistrationIfNecessary(installations, installationEntry);\r\n registrationPromise = entryWithPromise.registrationPromise;\r\n return entryWithPromise.installationEntry;\r\n });\r\n if (installationEntry.fid === INVALID_FID) {\r\n // FID generation failed. Waiting for the FID from the server.\r\n return { installationEntry: await registrationPromise };\r\n }\r\n return {\r\n installationEntry,\r\n registrationPromise\r\n };\r\n}\r\n/**\r\n * Creates a new Installation Entry if one does not exist.\r\n * Also clears timed out pending requests.\r\n */\r\nfunction updateOrCreateInstallationEntry(oldEntry) {\r\n const entry = oldEntry || {\r\n fid: generateFid(),\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n return clearTimedOutRequest(entry);\r\n}\r\n/**\r\n * If the Firebase Installation is not registered yet, this will trigger the\r\n * registration and return an InProgressInstallationEntry.\r\n *\r\n * If registrationPromise does not exist, the installationEntry is guaranteed\r\n * to be registered.\r\n */\r\nfunction triggerRegistrationIfNecessary(installations, installationEntry) {\r\n if (installationEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n if (!navigator.onLine) {\r\n // Registration required but app is offline.\r\n const registrationPromiseWithError = Promise.reject(ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */));\r\n return {\r\n installationEntry,\r\n registrationPromise: registrationPromiseWithError\r\n };\r\n }\r\n // Try registering. Change status to IN_PROGRESS.\r\n const inProgressEntry = {\r\n fid: installationEntry.fid,\r\n registrationStatus: 1 /* IN_PROGRESS */,\r\n registrationTime: Date.now()\r\n };\r\n const registrationPromise = registerInstallation(installations, inProgressEntry);\r\n return { installationEntry: inProgressEntry, registrationPromise };\r\n }\r\n else if (installationEntry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n return {\r\n installationEntry,\r\n registrationPromise: waitUntilFidRegistration(installations)\r\n };\r\n }\r\n else {\r\n return { installationEntry };\r\n }\r\n}\r\n/** This will be executed only once for each new Firebase Installation. */\r\nasync function registerInstallation(installations, installationEntry) {\r\n try {\r\n const registeredInstallationEntry = await createInstallationRequest(installations, installationEntry);\r\n return set(installations.appConfig, registeredInstallationEntry);\r\n }\r\n catch (e) {\r\n if (isServerError(e) && e.customData.serverCode === 409) {\r\n // Server returned a \"FID can not be used\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n // Registration failed. Set FID as not registered.\r\n await set(installations.appConfig, {\r\n fid: installationEntry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n });\r\n }\r\n throw e;\r\n }\r\n}\r\n/** Call if FID registration is pending in another request. */\r\nasync function waitUntilFidRegistration(installations) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateInstallationRequest(installations.appConfig);\r\n while (entry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n // createInstallation request still in progress.\r\n await sleep(100);\r\n entry = await updateInstallationRequest(installations.appConfig);\r\n }\r\n if (entry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n return registrationPromise;\r\n }\r\n else {\r\n // if there is no registrationPromise, entry is registered.\r\n return installationEntry;\r\n }\r\n }\r\n return entry;\r\n}\r\n/**\r\n * Called only if there is a CreateInstallation request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * CreateInstallation request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateInstallationRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!oldEntry) {\r\n throw ERROR_FACTORY.create(\"installation-not-found\" /* INSTALLATION_NOT_FOUND */);\r\n }\r\n return clearTimedOutRequest(oldEntry);\r\n });\r\n}\r\nfunction clearTimedOutRequest(entry) {\r\n if (hasInstallationRequestTimedOut(entry)) {\r\n return {\r\n fid: entry.fid,\r\n registrationStatus: 0 /* NOT_STARTED */\r\n };\r\n }\r\n return entry;\r\n}\r\nfunction hasInstallationRequestTimedOut(installationEntry) {\r\n return (installationEntry.registrationStatus === 1 /* IN_PROGRESS */ &&\r\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function generateAuthTokenRequest({ appConfig, heartbeatServiceProvider }, installationEntry) {\r\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n // If heartbeat service exists, add the heartbeat string to the header.\r\n const heartbeatService = heartbeatServiceProvider.getImmediate({\r\n optional: true\r\n });\r\n if (heartbeatService) {\r\n const heartbeatsHeader = await heartbeatService.getHeartbeatsHeader();\r\n if (heartbeatsHeader) {\r\n headers.append('x-firebase-client', heartbeatsHeader);\r\n }\r\n }\r\n const body = {\r\n installation: {\r\n sdkVersion: PACKAGE_VERSION,\r\n appId: appConfig.appId\r\n }\r\n };\r\n const request = {\r\n method: 'POST',\r\n headers,\r\n body: JSON.stringify(body)\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (response.ok) {\r\n const responseValue = await response.json();\r\n const completedAuthToken = extractAuthTokenInfoFromResponse(responseValue);\r\n return completedAuthToken;\r\n }\r\n else {\r\n throw await getErrorFromResponse('Generate Auth Token', response);\r\n }\r\n}\r\nfunction getGenerateAuthTokenEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a valid authentication token for the installation. Generates a new\r\n * token if one doesn't exist, is expired or about to expire.\r\n *\r\n * Should only be called if the Firebase Installation is registered.\r\n */\r\nasync function refreshAuthToken(installations, forceRefresh = false) {\r\n let tokenPromise;\r\n const entry = await update(installations.appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\r\n // There is a valid token in the DB.\r\n return oldEntry;\r\n }\r\n else if (oldAuthToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // There already is a token request in progress.\r\n tokenPromise = waitUntilAuthTokenRequest(installations, forceRefresh);\r\n return oldEntry;\r\n }\r\n else {\r\n // No token or token expired.\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\r\n tokenPromise = fetchAuthTokenFromServer(installations, inProgressEntry);\r\n return inProgressEntry;\r\n }\r\n });\r\n const authToken = tokenPromise\r\n ? await tokenPromise\r\n : entry.authToken;\r\n return authToken;\r\n}\r\n/**\r\n * Call only if FID is registered and Auth Token request is in progress.\r\n *\r\n * Waits until the current pending request finishes. If the request times out,\r\n * tries once in this thread as well.\r\n */\r\nasync function waitUntilAuthTokenRequest(installations, forceRefresh) {\r\n // Unfortunately, there is no way of reliably observing when a value in\r\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\r\n // so we need to poll.\r\n let entry = await updateAuthTokenRequest(installations.appConfig);\r\n while (entry.authToken.requestStatus === 1 /* IN_PROGRESS */) {\r\n // generateAuthToken still in progress.\r\n await sleep(100);\r\n entry = await updateAuthTokenRequest(installations.appConfig);\r\n }\r\n const authToken = entry.authToken;\r\n if (authToken.requestStatus === 0 /* NOT_STARTED */) {\r\n // The request timed out or failed in a different call. Try again.\r\n return refreshAuthToken(installations, forceRefresh);\r\n }\r\n else {\r\n return authToken;\r\n }\r\n}\r\n/**\r\n * Called only if there is a GenerateAuthToken request in progress.\r\n *\r\n * Updates the InstallationEntry in the DB based on the status of the\r\n * GenerateAuthToken request.\r\n *\r\n * Returns the updated InstallationEntry.\r\n */\r\nfunction updateAuthTokenRequest(appConfig) {\r\n return update(appConfig, oldEntry => {\r\n if (!isEntryRegistered(oldEntry)) {\r\n throw ERROR_FACTORY.create(\"not-registered\" /* NOT_REGISTERED */);\r\n }\r\n const oldAuthToken = oldEntry.authToken;\r\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n }\r\n return oldEntry;\r\n });\r\n}\r\nasync function fetchAuthTokenFromServer(installations, installationEntry) {\r\n try {\r\n const authToken = await generateAuthTokenRequest(installations, installationEntry);\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n return authToken;\r\n }\r\n catch (e) {\r\n if (isServerError(e) &&\r\n (e.customData.serverCode === 401 || e.customData.serverCode === 404)) {\r\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\r\n // Generate a new ID next time.\r\n await remove(installations.appConfig);\r\n }\r\n else {\r\n const updatedInstallationEntry = Object.assign(Object.assign({}, installationEntry), { authToken: { requestStatus: 0 /* NOT_STARTED */ } });\r\n await set(installations.appConfig, updatedInstallationEntry);\r\n }\r\n throw e;\r\n }\r\n}\r\nfunction isEntryRegistered(installationEntry) {\r\n return (installationEntry !== undefined &&\r\n installationEntry.registrationStatus === 2 /* COMPLETED */);\r\n}\r\nfunction isAuthTokenValid(authToken) {\r\n return (authToken.requestStatus === 2 /* COMPLETED */ &&\r\n !isAuthTokenExpired(authToken));\r\n}\r\nfunction isAuthTokenExpired(authToken) {\r\n const now = Date.now();\r\n return (now < authToken.creationTime ||\r\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER);\r\n}\r\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\r\nfunction makeAuthTokenRequestInProgressEntry(oldEntry) {\r\n const inProgressAuthToken = {\r\n requestStatus: 1 /* IN_PROGRESS */,\r\n requestTime: Date.now()\r\n };\r\n return Object.assign(Object.assign({}, oldEntry), { authToken: inProgressAuthToken });\r\n}\r\nfunction hasAuthTokenRequestTimedOut(authToken) {\r\n return (authToken.requestStatus === 1 /* IN_PROGRESS */ &&\r\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now());\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Creates a Firebase Installation if there isn't one for the app and\r\n * returns the Installation ID.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function getId(installations) {\r\n const installationsImpl = installations;\r\n const { installationEntry, registrationPromise } = await getInstallationEntry(installationsImpl);\r\n if (registrationPromise) {\r\n registrationPromise.catch(console.error);\r\n }\r\n else {\r\n // If the installation is already registered, update the authentication\r\n // token if needed.\r\n refreshAuthToken(installationsImpl).catch(console.error);\r\n }\r\n return installationEntry.fid;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns a Firebase Installations auth token, identifying the current\r\n * Firebase Installation.\r\n * @param installations - The `Installations` instance.\r\n * @param forceRefresh - Force refresh regardless of token expiration.\r\n *\r\n * @public\r\n */\r\nasync function getToken(installations, forceRefresh = false) {\r\n const installationsImpl = installations;\r\n await completeInstallationRegistration(installationsImpl);\r\n // At this point we either have a Registered Installation in the DB, or we've\r\n // already thrown an error.\r\n const authToken = await refreshAuthToken(installationsImpl, forceRefresh);\r\n return authToken.token;\r\n}\r\nasync function completeInstallationRegistration(installations) {\r\n const { registrationPromise } = await getInstallationEntry(installations);\r\n if (registrationPromise) {\r\n // A createInstallation request is in progress. Wait until it finishes.\r\n await registrationPromise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function deleteInstallationRequest(appConfig, installationEntry) {\r\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\r\n const headers = getHeadersWithAuth(appConfig, installationEntry);\r\n const request = {\r\n method: 'DELETE',\r\n headers\r\n };\r\n const response = await retryIfServerError(() => fetch(endpoint, request));\r\n if (!response.ok) {\r\n throw await getErrorFromResponse('Delete Installation', response);\r\n }\r\n}\r\nfunction getDeleteEndpoint(appConfig, { fid }) {\r\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Deletes the Firebase Installation and all associated data.\r\n * @param installations - The `Installations` instance.\r\n *\r\n * @public\r\n */\r\nasync function deleteInstallations(installations) {\r\n const { appConfig } = installations;\r\n const entry = await update(appConfig, oldEntry => {\r\n if (oldEntry && oldEntry.registrationStatus === 0 /* NOT_STARTED */) {\r\n // Delete the unregistered entry without sending a deleteInstallation request.\r\n return undefined;\r\n }\r\n return oldEntry;\r\n });\r\n if (entry) {\r\n if (entry.registrationStatus === 1 /* IN_PROGRESS */) {\r\n // Can't delete while trying to register.\r\n throw ERROR_FACTORY.create(\"delete-pending-registration\" /* DELETE_PENDING_REGISTRATION */);\r\n }\r\n else if (entry.registrationStatus === 2 /* COMPLETED */) {\r\n if (!navigator.onLine) {\r\n throw ERROR_FACTORY.create(\"app-offline\" /* APP_OFFLINE */);\r\n }\r\n else {\r\n await deleteInstallationRequest(appConfig, entry);\r\n await remove(appConfig);\r\n }\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Sets a new callback that will get called when Installation ID changes.\r\n * Returns an unsubscribe function that will remove the callback when called.\r\n * @param installations - The `Installations` instance.\r\n * @param callback - The callback function that is invoked when FID changes.\r\n * @returns A function that can be called to unsubscribe.\r\n *\r\n * @public\r\n */\r\nfunction onIdChange(installations, callback) {\r\n const { appConfig } = installations;\r\n addCallback(appConfig, callback);\r\n return () => {\r\n removeCallback(appConfig, callback);\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns an instance of {@link Installations} associated with the given\r\n * {@link @firebase/app#FirebaseApp} instance.\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance.\r\n *\r\n * @public\r\n */\r\nfunction getInstallations(app = getApp()) {\r\n const installationsImpl = _getProvider(app, 'installations').getImmediate();\r\n return installationsImpl;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction extractAppConfig(app) {\r\n if (!app || !app.options) {\r\n throw getMissingValueError('App Configuration');\r\n }\r\n if (!app.name) {\r\n throw getMissingValueError('App Name');\r\n }\r\n // Required app config keys\r\n const configKeys = [\r\n 'projectId',\r\n 'apiKey',\r\n 'appId'\r\n ];\r\n for (const keyName of configKeys) {\r\n if (!app.options[keyName]) {\r\n throw getMissingValueError(keyName);\r\n }\r\n }\r\n return {\r\n appName: app.name,\r\n projectId: app.options.projectId,\r\n apiKey: app.options.apiKey,\r\n appId: app.options.appId\r\n };\r\n}\r\nfunction getMissingValueError(valueName) {\r\n return ERROR_FACTORY.create(\"missing-app-config-values\" /* MISSING_APP_CONFIG_VALUES */, {\r\n valueName\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INSTALLATIONS_NAME = 'installations';\r\nconst INSTALLATIONS_NAME_INTERNAL = 'installations-internal';\r\nconst publicFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Throws if app isn't configured properly.\r\n const appConfig = extractAppConfig(app);\r\n const heartbeatServiceProvider = _getProvider(app, 'heartbeat');\r\n const installationsImpl = {\r\n app,\r\n appConfig,\r\n heartbeatServiceProvider,\r\n _delete: () => Promise.resolve()\r\n };\r\n return installationsImpl;\r\n};\r\nconst internalFactory = (container) => {\r\n const app = container.getProvider('app').getImmediate();\r\n // Internal FIS instance relies on public FIS instance.\r\n const installations = _getProvider(app, INSTALLATIONS_NAME).getImmediate();\r\n const installationsInternal = {\r\n getId: () => getId(installations),\r\n getToken: (forceRefresh) => getToken(installations, forceRefresh)\r\n };\r\n return installationsInternal;\r\n};\r\nfunction registerInstallations() {\r\n _registerComponent(new Component(INSTALLATIONS_NAME, publicFactory, \"PUBLIC\" /* PUBLIC */));\r\n _registerComponent(new Component(INSTALLATIONS_NAME_INTERNAL, internalFactory, \"PRIVATE\" /* PRIVATE */));\r\n}\n\n/**\r\n * Firebase Installations\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterInstallations();\r\nregisterVersion(name, version);\r\n// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\nregisterVersion(name, version, 'esm2017');\n\nexport { deleteInstallations, getId, getInstallations, getToken, onIdChange };\n//# sourceMappingURL=index.esm2017.js.map\n","import { getApp, _getProvider, _registerComponent, registerVersion } from '@firebase/app';\nimport { Logger } from '@firebase/logger';\nimport { ErrorFactory, calculateBackoffMillis, FirebaseError, isIndexedDBAvailable, validateIndexedDBOpenable, isBrowserExtension, areCookiesEnabled, getModularInstance, deepEqual } from '@firebase/util';\nimport { Component } from '@firebase/component';\nimport '@firebase/installations';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Type constant for Firebase Analytics.\r\n */\r\nconst ANALYTICS_TYPE = 'analytics';\r\n// Key to attach FID to in gtag params.\r\nconst GA_FID_KEY = 'firebase_id';\r\nconst ORIGIN_KEY = 'origin';\r\nconst FETCH_TIMEOUT_MILLIS = 60 * 1000;\r\nconst DYNAMIC_CONFIG_URL = 'https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig';\r\nconst GTAG_URL = 'https://www.googletagmanager.com/gtag/js';\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst logger = new Logger('@firebase/analytics');\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Makeshift polyfill for Promise.allSettled(). Resolves when all promises\r\n * have either resolved or rejected.\r\n *\r\n * @param promises Array of promises to wait for.\r\n */\r\nfunction promiseAllSettled(promises) {\r\n return Promise.all(promises.map(promise => promise.catch(e => e)));\r\n}\r\n/**\r\n * Inserts gtag script tag into the page to asynchronously download gtag.\r\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\r\n */\r\nfunction insertScriptTag(dataLayerName, measurementId) {\r\n const script = document.createElement('script');\r\n // We are not providing an analyticsId in the URL because it would trigger a `page_view`\r\n // without fid. We will initialize ga-id using gtag (config) command together with fid.\r\n script.src = `${GTAG_URL}?l=${dataLayerName}&id=${measurementId}`;\r\n script.async = true;\r\n document.head.appendChild(script);\r\n}\r\n/**\r\n * Get reference to, or create, global datalayer.\r\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\").\r\n */\r\nfunction getOrCreateDataLayer(dataLayerName) {\r\n // Check for existing dataLayer and create if needed.\r\n let dataLayer = [];\r\n if (Array.isArray(window[dataLayerName])) {\r\n dataLayer = window[dataLayerName];\r\n }\r\n else {\r\n window[dataLayerName] = dataLayer;\r\n }\r\n return dataLayer;\r\n}\r\n/**\r\n * Wrapped gtag logic when gtag is called with 'config' command.\r\n *\r\n * @param gtagCore Basic gtag function that just appends to dataLayer.\r\n * @param initializationPromisesMap Map of appIds to their initialization promises.\r\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\r\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\r\n * @param measurementId GA Measurement ID to set config for.\r\n * @param gtagParams Gtag config params to set.\r\n */\r\nasync function gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, measurementId, gtagParams) {\r\n // If config is already fetched, we know the appId and can use it to look up what FID promise we\r\n /// are waiting for, and wait only on that one.\r\n const correspondingAppId = measurementIdToAppId[measurementId];\r\n try {\r\n if (correspondingAppId) {\r\n await initializationPromisesMap[correspondingAppId];\r\n }\r\n else {\r\n // If config is not fetched yet, wait for all configs (we don't know which one we need) and\r\n // find the appId (if any) corresponding to this measurementId. If there is one, wait on\r\n // that appId's initialization promise. If there is none, promise resolves and gtag\r\n // call goes through.\r\n const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList);\r\n const foundConfig = dynamicConfigResults.find(config => config.measurementId === measurementId);\r\n if (foundConfig) {\r\n await initializationPromisesMap[foundConfig.appId];\r\n }\r\n }\r\n }\r\n catch (e) {\r\n logger.error(e);\r\n }\r\n gtagCore(\"config\" /* CONFIG */, measurementId, gtagParams);\r\n}\r\n/**\r\n * Wrapped gtag logic when gtag is called with 'event' command.\r\n *\r\n * @param gtagCore Basic gtag function that just appends to dataLayer.\r\n * @param initializationPromisesMap Map of appIds to their initialization promises.\r\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\r\n * @param measurementId GA Measurement ID to log event to.\r\n * @param gtagParams Params to log with this event.\r\n */\r\nasync function gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementId, gtagParams) {\r\n try {\r\n let initializationPromisesToWaitFor = [];\r\n // If there's a 'send_to' param, check if any ID specified matches\r\n // an initializeIds() promise we are waiting for.\r\n if (gtagParams && gtagParams['send_to']) {\r\n let gaSendToList = gtagParams['send_to'];\r\n // Make it an array if is isn't, so it can be dealt with the same way.\r\n if (!Array.isArray(gaSendToList)) {\r\n gaSendToList = [gaSendToList];\r\n }\r\n // Checking 'send_to' fields requires having all measurement ID results back from\r\n // the dynamic config fetch.\r\n const dynamicConfigResults = await promiseAllSettled(dynamicConfigPromisesList);\r\n for (const sendToId of gaSendToList) {\r\n // Any fetched dynamic measurement ID that matches this 'send_to' ID\r\n const foundConfig = dynamicConfigResults.find(config => config.measurementId === sendToId);\r\n const initializationPromise = foundConfig && initializationPromisesMap[foundConfig.appId];\r\n if (initializationPromise) {\r\n initializationPromisesToWaitFor.push(initializationPromise);\r\n }\r\n else {\r\n // Found an item in 'send_to' that is not associated\r\n // directly with an FID, possibly a group. Empty this array,\r\n // exit the loop early, and let it get populated below.\r\n initializationPromisesToWaitFor = [];\r\n break;\r\n }\r\n }\r\n }\r\n // This will be unpopulated if there was no 'send_to' field , or\r\n // if not all entries in the 'send_to' field could be mapped to\r\n // a FID. In these cases, wait on all pending initialization promises.\r\n if (initializationPromisesToWaitFor.length === 0) {\r\n initializationPromisesToWaitFor = Object.values(initializationPromisesMap);\r\n }\r\n // Run core gtag function with args after all relevant initialization\r\n // promises have been resolved.\r\n await Promise.all(initializationPromisesToWaitFor);\r\n // Workaround for http://b/141370449 - third argument cannot be undefined.\r\n gtagCore(\"event\" /* EVENT */, measurementId, gtagParams || {});\r\n }\r\n catch (e) {\r\n logger.error(e);\r\n }\r\n}\r\n/**\r\n * Wraps a standard gtag function with extra code to wait for completion of\r\n * relevant initialization promises before sending requests.\r\n *\r\n * @param gtagCore Basic gtag function that just appends to dataLayer.\r\n * @param initializationPromisesMap Map of appIds to their initialization promises.\r\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\r\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\r\n */\r\nfunction wrapGtag(gtagCore, \r\n/**\r\n * Allows wrapped gtag calls to wait on whichever intialization promises are required,\r\n * depending on the contents of the gtag params' `send_to` field, if any.\r\n */\r\ninitializationPromisesMap, \r\n/**\r\n * Wrapped gtag calls sometimes require all dynamic config fetches to have returned\r\n * before determining what initialization promises (which include FIDs) to wait for.\r\n */\r\ndynamicConfigPromisesList, \r\n/**\r\n * Wrapped gtag config calls can narrow down which initialization promise (with FID)\r\n * to wait for if the measurementId is already fetched, by getting the corresponding appId,\r\n * which is the key for the initialization promises map.\r\n */\r\nmeasurementIdToAppId) {\r\n /**\r\n * Wrapper around gtag that ensures FID is sent with gtag calls.\r\n * @param command Gtag command type.\r\n * @param idOrNameOrParams Measurement ID if command is EVENT/CONFIG, params if command is SET.\r\n * @param gtagParams Params if event is EVENT/CONFIG.\r\n */\r\n async function gtagWrapper(command, idOrNameOrParams, gtagParams) {\r\n try {\r\n // If event, check that relevant initialization promises have completed.\r\n if (command === \"event\" /* EVENT */) {\r\n // If EVENT, second arg must be measurementId.\r\n await gtagOnEvent(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, idOrNameOrParams, gtagParams);\r\n }\r\n else if (command === \"config\" /* CONFIG */) {\r\n // If CONFIG, second arg must be measurementId.\r\n await gtagOnConfig(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, idOrNameOrParams, gtagParams);\r\n }\r\n else {\r\n // If SET, second arg must be params.\r\n gtagCore(\"set\" /* SET */, idOrNameOrParams);\r\n }\r\n }\r\n catch (e) {\r\n logger.error(e);\r\n }\r\n }\r\n return gtagWrapper;\r\n}\r\n/**\r\n * Creates global gtag function or wraps existing one if found.\r\n * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and\r\n * 'event' calls that belong to the GAID associated with this Firebase instance.\r\n *\r\n * @param initializationPromisesMap Map of appIds to their initialization promises.\r\n * @param dynamicConfigPromisesList Array of dynamic config fetch promises.\r\n * @param measurementIdToAppId Map of GA measurementIDs to corresponding Firebase appId.\r\n * @param dataLayerName Name of global GA datalayer array.\r\n * @param gtagFunctionName Name of global gtag function (\"gtag\" if not user-specified).\r\n */\r\nfunction wrapOrCreateGtag(initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId, dataLayerName, gtagFunctionName) {\r\n // Create a basic core gtag function\r\n let gtagCore = function (..._args) {\r\n // Must push IArguments object, not an array.\r\n window[dataLayerName].push(arguments);\r\n };\r\n // Replace it with existing one if found\r\n if (window[gtagFunctionName] &&\r\n typeof window[gtagFunctionName] === 'function') {\r\n // @ts-ignore\r\n gtagCore = window[gtagFunctionName];\r\n }\r\n window[gtagFunctionName] = wrapGtag(gtagCore, initializationPromisesMap, dynamicConfigPromisesList, measurementIdToAppId);\r\n return {\r\n gtagCore,\r\n wrappedGtag: window[gtagFunctionName]\r\n };\r\n}\r\n/**\r\n * Returns first script tag in DOM matching our gtag url pattern.\r\n */\r\nfunction findGtagScriptOnPage() {\r\n const scriptTags = window.document.getElementsByTagName('script');\r\n for (const tag of Object.values(scriptTags)) {\r\n if (tag.src && tag.src.includes(GTAG_URL)) {\r\n return tag;\r\n }\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2019 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst ERRORS = {\r\n [\"already-exists\" /* ALREADY_EXISTS */]: 'A Firebase Analytics instance with the appId {$id} ' +\r\n ' already exists. ' +\r\n 'Only one Firebase Analytics instance can be created for each appId.',\r\n [\"already-initialized\" /* ALREADY_INITIALIZED */]: 'initializeAnalytics() cannot be called again with different options than those ' +\r\n 'it was initially called with. It can be called again with the same options to ' +\r\n 'return the existing instance, or getAnalytics() can be used ' +\r\n 'to get a reference to the already-intialized instance.',\r\n [\"already-initialized-settings\" /* ALREADY_INITIALIZED_SETTINGS */]: 'Firebase Analytics has already been initialized.' +\r\n 'settings() must be called before initializing any Analytics instance' +\r\n 'or it will have no effect.',\r\n [\"interop-component-reg-failed\" /* INTEROP_COMPONENT_REG_FAILED */]: 'Firebase Analytics Interop Component failed to instantiate: {$reason}',\r\n [\"invalid-analytics-context\" /* INVALID_ANALYTICS_CONTEXT */]: 'Firebase Analytics is not supported in this environment. ' +\r\n 'Wrap initialization of analytics in analytics.isSupported() ' +\r\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\r\n [\"indexeddb-unavailable\" /* INDEXEDDB_UNAVAILABLE */]: 'IndexedDB unavailable or restricted in this environment. ' +\r\n 'Wrap initialization of analytics in analytics.isSupported() ' +\r\n 'to prevent initialization in unsupported environments. Details: {$errorInfo}',\r\n [\"fetch-throttle\" /* FETCH_THROTTLE */]: 'The config fetch request timed out while in an exponential backoff state.' +\r\n ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\r\n [\"config-fetch-failed\" /* CONFIG_FETCH_FAILED */]: 'Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}',\r\n [\"no-api-key\" /* NO_API_KEY */]: 'The \"apiKey\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\r\n 'contain a valid API key.',\r\n [\"no-app-id\" /* NO_APP_ID */]: 'The \"appId\" field is empty in the local Firebase config. Firebase Analytics requires this field to' +\r\n 'contain a valid app ID.'\r\n};\r\nconst ERROR_FACTORY = new ErrorFactory('analytics', 'Analytics', ERRORS);\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Backoff factor for 503 errors, which we want to be conservative about\r\n * to avoid overloading servers. Each retry interval will be\r\n * BASE_INTERVAL_MILLIS * LONG_RETRY_FACTOR ^ retryCount, so the second one\r\n * will be ~30 seconds (with fuzzing).\r\n */\r\nconst LONG_RETRY_FACTOR = 30;\r\n/**\r\n * Base wait interval to multiplied by backoffFactor^backoffCount.\r\n */\r\nconst BASE_INTERVAL_MILLIS = 1000;\r\n/**\r\n * Stubbable retry data storage class.\r\n */\r\nclass RetryData {\r\n constructor(throttleMetadata = {}, intervalMillis = BASE_INTERVAL_MILLIS) {\r\n this.throttleMetadata = throttleMetadata;\r\n this.intervalMillis = intervalMillis;\r\n }\r\n getThrottleMetadata(appId) {\r\n return this.throttleMetadata[appId];\r\n }\r\n setThrottleMetadata(appId, metadata) {\r\n this.throttleMetadata[appId] = metadata;\r\n }\r\n deleteThrottleMetadata(appId) {\r\n delete this.throttleMetadata[appId];\r\n }\r\n}\r\nconst defaultRetryData = new RetryData();\r\n/**\r\n * Set GET request headers.\r\n * @param apiKey App API key.\r\n */\r\nfunction getHeaders(apiKey) {\r\n return new Headers({\r\n Accept: 'application/json',\r\n 'x-goog-api-key': apiKey\r\n });\r\n}\r\n/**\r\n * Fetches dynamic config from backend.\r\n * @param app Firebase app to fetch config for.\r\n */\r\nasync function fetchDynamicConfig(appFields) {\r\n var _a;\r\n const { appId, apiKey } = appFields;\r\n const request = {\r\n method: 'GET',\r\n headers: getHeaders(apiKey)\r\n };\r\n const appUrl = DYNAMIC_CONFIG_URL.replace('{app-id}', appId);\r\n const response = await fetch(appUrl, request);\r\n if (response.status !== 200 && response.status !== 304) {\r\n let errorMessage = '';\r\n try {\r\n // Try to get any error message text from server response.\r\n const jsonResponse = (await response.json());\r\n if ((_a = jsonResponse.error) === null || _a === void 0 ? void 0 : _a.message) {\r\n errorMessage = jsonResponse.error.message;\r\n }\r\n }\r\n catch (_ignored) { }\r\n throw ERROR_FACTORY.create(\"config-fetch-failed\" /* CONFIG_FETCH_FAILED */, {\r\n httpStatus: response.status,\r\n responseMessage: errorMessage\r\n });\r\n }\r\n return response.json();\r\n}\r\n/**\r\n * Fetches dynamic config from backend, retrying if failed.\r\n * @param app Firebase app to fetch config for.\r\n */\r\nasync function fetchDynamicConfigWithRetry(app, \r\n// retryData and timeoutMillis are parameterized to allow passing a different value for testing.\r\nretryData = defaultRetryData, timeoutMillis) {\r\n const { appId, apiKey, measurementId } = app.options;\r\n if (!appId) {\r\n throw ERROR_FACTORY.create(\"no-app-id\" /* NO_APP_ID */);\r\n }\r\n if (!apiKey) {\r\n if (measurementId) {\r\n return {\r\n measurementId,\r\n appId\r\n };\r\n }\r\n throw ERROR_FACTORY.create(\"no-api-key\" /* NO_API_KEY */);\r\n }\r\n const throttleMetadata = retryData.getThrottleMetadata(appId) || {\r\n backoffCount: 0,\r\n throttleEndTimeMillis: Date.now()\r\n };\r\n const signal = new AnalyticsAbortSignal();\r\n setTimeout(async () => {\r\n // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\r\n signal.abort();\r\n }, timeoutMillis !== undefined ? timeoutMillis : FETCH_TIMEOUT_MILLIS);\r\n return attemptFetchDynamicConfigWithRetry({ appId, apiKey, measurementId }, throttleMetadata, signal, retryData);\r\n}\r\n/**\r\n * Runs one retry attempt.\r\n * @param appFields Necessary app config fields.\r\n * @param throttleMetadata Ongoing metadata to determine throttling times.\r\n * @param signal Abort signal.\r\n */\r\nasync function attemptFetchDynamicConfigWithRetry(appFields, { throttleEndTimeMillis, backoffCount }, signal, retryData = defaultRetryData // for testing\r\n) {\r\n const { appId, measurementId } = appFields;\r\n // Starts with a (potentially zero) timeout to support resumption from stored state.\r\n // Ensures the throttle end time is honored if the last attempt timed out.\r\n // Note the SDK will never make a request if the fetch timeout expires at this point.\r\n try {\r\n await setAbortableTimeout(signal, throttleEndTimeMillis);\r\n }\r\n catch (e) {\r\n if (measurementId) {\r\n logger.warn(`Timed out fetching this Firebase app's measurement ID from the server.` +\r\n ` Falling back to the measurement ID ${measurementId}` +\r\n ` provided in the \"measurementId\" field in the local Firebase config. [${e.message}]`);\r\n return { appId, measurementId };\r\n }\r\n throw e;\r\n }\r\n try {\r\n const response = await fetchDynamicConfig(appFields);\r\n // Note the SDK only clears throttle state if response is success or non-retriable.\r\n retryData.deleteThrottleMetadata(appId);\r\n return response;\r\n }\r\n catch (e) {\r\n if (!isRetriableError(e)) {\r\n retryData.deleteThrottleMetadata(appId);\r\n if (measurementId) {\r\n logger.warn(`Failed to fetch this Firebase app's measurement ID from the server.` +\r\n ` Falling back to the measurement ID ${measurementId}` +\r\n ` provided in the \"measurementId\" field in the local Firebase config. [${e.message}]`);\r\n return { appId, measurementId };\r\n }\r\n else {\r\n throw e;\r\n }\r\n }\r\n const backoffMillis = Number(e.customData.httpStatus) === 503\r\n ? calculateBackoffMillis(backoffCount, retryData.intervalMillis, LONG_RETRY_FACTOR)\r\n : calculateBackoffMillis(backoffCount, retryData.intervalMillis);\r\n // Increments backoff state.\r\n const throttleMetadata = {\r\n throttleEndTimeMillis: Date.now() + backoffMillis,\r\n backoffCount: backoffCount + 1\r\n };\r\n // Persists state.\r\n retryData.setThrottleMetadata(appId, throttleMetadata);\r\n logger.debug(`Calling attemptFetch again in ${backoffMillis} millis`);\r\n return attemptFetchDynamicConfigWithRetry(appFields, throttleMetadata, signal, retryData);\r\n }\r\n}\r\n/**\r\n * Supports waiting on a backoff by:\r\n *\r\n *
    \r\n *
  • Promisifying setTimeout, so we can set a timeout in our Promise chain
  • \r\n *
  • Listening on a signal bus for abort events, just like the Fetch API
  • \r\n *
  • Failing in the same way the Fetch API fails, so timing out a live request and a throttled\r\n * request appear the same.
  • \r\n *
\r\n *\r\n *

Visible for testing.\r\n */\r\nfunction setAbortableTimeout(signal, throttleEndTimeMillis) {\r\n return new Promise((resolve, reject) => {\r\n // Derives backoff from given end time, normalizing negative numbers to zero.\r\n const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);\r\n const timeout = setTimeout(resolve, backoffMillis);\r\n // Adds listener, rather than sets onabort, because signal is a shared object.\r\n signal.addEventListener(() => {\r\n clearTimeout(timeout);\r\n // If the request completes before this timeout, the rejection has no effect.\r\n reject(ERROR_FACTORY.create(\"fetch-throttle\" /* FETCH_THROTTLE */, {\r\n throttleEndTimeMillis\r\n }));\r\n });\r\n });\r\n}\r\n/**\r\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\r\n */\r\nfunction isRetriableError(e) {\r\n if (!(e instanceof FirebaseError) || !e.customData) {\r\n return false;\r\n }\r\n // Uses string index defined by ErrorData, which FirebaseError implements.\r\n const httpStatus = Number(e.customData['httpStatus']);\r\n return (httpStatus === 429 ||\r\n httpStatus === 500 ||\r\n httpStatus === 503 ||\r\n httpStatus === 504);\r\n}\r\n/**\r\n * Shims a minimal AbortSignal (copied from Remote Config).\r\n *\r\n *

AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects\r\n * of networking, such as retries. Firebase doesn't use AbortController enough to justify a\r\n * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be\r\n * swapped out if/when we do.\r\n */\r\nclass AnalyticsAbortSignal {\r\n constructor() {\r\n this.listeners = [];\r\n }\r\n addEventListener(listener) {\r\n this.listeners.push(listener);\r\n }\r\n abort() {\r\n this.listeners.forEach(listener => listener());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nasync function validateIndexedDB() {\r\n if (!isIndexedDBAvailable()) {\r\n logger.warn(ERROR_FACTORY.create(\"indexeddb-unavailable\" /* INDEXEDDB_UNAVAILABLE */, {\r\n errorInfo: 'IndexedDB is not available in this environment.'\r\n }).message);\r\n return false;\r\n }\r\n else {\r\n try {\r\n await validateIndexedDBOpenable();\r\n }\r\n catch (e) {\r\n logger.warn(ERROR_FACTORY.create(\"indexeddb-unavailable\" /* INDEXEDDB_UNAVAILABLE */, {\r\n errorInfo: e\r\n }).message);\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * Initialize the analytics instance in gtag.js by calling config command with fid.\r\n *\r\n * NOTE: We combine analytics initialization and setting fid together because we want fid to be\r\n * part of the `page_view` event that's sent during the initialization\r\n * @param app Firebase app\r\n * @param gtagCore The gtag function that's not wrapped.\r\n * @param dynamicConfigPromisesList Array of all dynamic config promises.\r\n * @param measurementIdToAppId Maps measurementID to appID.\r\n * @param installations _FirebaseInstallationsInternal instance.\r\n *\r\n * @returns Measurement ID.\r\n */\r\nasync function _initializeAnalytics(app, dynamicConfigPromisesList, measurementIdToAppId, installations, gtagCore, dataLayerName, options) {\r\n var _a;\r\n const dynamicConfigPromise = fetchDynamicConfigWithRetry(app);\r\n // Once fetched, map measurementIds to appId, for ease of lookup in wrapped gtag function.\r\n dynamicConfigPromise\r\n .then(config => {\r\n measurementIdToAppId[config.measurementId] = config.appId;\r\n if (app.options.measurementId &&\r\n config.measurementId !== app.options.measurementId) {\r\n logger.warn(`The measurement ID in the local Firebase config (${app.options.measurementId})` +\r\n ` does not match the measurement ID fetched from the server (${config.measurementId}).` +\r\n ` To ensure analytics events are always sent to the correct Analytics property,` +\r\n ` update the` +\r\n ` measurement ID field in the local config or remove it from the local config.`);\r\n }\r\n })\r\n .catch(e => logger.error(e));\r\n // Add to list to track state of all dynamic config promises.\r\n dynamicConfigPromisesList.push(dynamicConfigPromise);\r\n const fidPromise = validateIndexedDB().then(envIsValid => {\r\n if (envIsValid) {\r\n return installations.getId();\r\n }\r\n else {\r\n return undefined;\r\n }\r\n });\r\n const [dynamicConfig, fid] = await Promise.all([\r\n dynamicConfigPromise,\r\n fidPromise\r\n ]);\r\n // Detect if user has already put the gtag ';\r\n }\r\n const iframeContents = '' + script + '';\r\n try {\r\n this.myIFrame.doc.open();\r\n this.myIFrame.doc.write(iframeContents);\r\n this.myIFrame.doc.close();\r\n }\r\n catch (e) {\r\n log('frame writing exception');\r\n if (e.stack) {\r\n log(e.stack);\r\n }\r\n log(e);\r\n }\r\n }\r\n else {\r\n this.commandCB = commandCB;\r\n this.onMessageCB = onMessageCB;\r\n }\r\n }\r\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n */\r\n static createIFrame_() {\r\n const iframe = document.createElement('iframe');\r\n iframe.style.display = 'none';\r\n // This is necessary in order to initialize the document inside the iframe\r\n if (document.body) {\r\n document.body.appendChild(iframe);\r\n try {\r\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\r\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\r\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\r\n const a = iframe.contentWindow.document;\r\n if (!a) {\r\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\r\n log('No IE domain setting required');\r\n }\r\n }\r\n catch (e) {\r\n const domain = document.domain;\r\n iframe.src =\r\n \"javascript:void((function(){document.open();document.domain='\" +\r\n domain +\r\n \"';document.close();})())\";\r\n }\r\n }\r\n else {\r\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\r\n // never gets hit.\r\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\r\n }\r\n // Get the document of the iframe in a browser-specific way.\r\n if (iframe.contentDocument) {\r\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\r\n }\r\n else if (iframe.contentWindow) {\r\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }\r\n else if (iframe.document) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n iframe.doc = iframe.document; //others?\r\n }\r\n return iframe;\r\n }\r\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\n */\r\n close() {\r\n //Mark this iframe as dead, so no new requests are sent.\r\n this.alive = false;\r\n if (this.myIFrame) {\r\n //We have to actually remove all of the html inside this iframe before removing it from the\r\n //window, or IE will continue loading and executing the script tags we've already added, which\r\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\r\n this.myIFrame.doc.body.innerHTML = '';\r\n setTimeout(() => {\r\n if (this.myIFrame !== null) {\r\n document.body.removeChild(this.myIFrame);\r\n this.myIFrame = null;\r\n }\r\n }, Math.floor(0));\r\n }\r\n // Protect from being called recursively.\r\n const onDisconnect = this.onDisconnect;\r\n if (onDisconnect) {\r\n this.onDisconnect = null;\r\n onDisconnect();\r\n }\r\n }\r\n /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param id - The ID of this connection\r\n * @param pw - The password for this connection\r\n */\r\n startLongPoll(id, pw) {\r\n this.myID = id;\r\n this.myPW = pw;\r\n this.alive = true;\r\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\r\n while (this.newRequest_()) { }\r\n }\r\n /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\r\n newRequest_() {\r\n // We keep one outstanding request open all the time to receive data, but if we need to send data\r\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\r\n // close the old request.\r\n if (this.alive &&\r\n this.sendNewPolls &&\r\n this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {\r\n //construct our url\r\n this.currentSerial++;\r\n const urlParams = {};\r\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\r\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\r\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\r\n let theURL = this.urlFn(urlParams);\r\n //Now add as much data as we can.\r\n let curDataString = '';\r\n let i = 0;\r\n while (this.pendingSegs.length > 0) {\r\n //first, lets see if the next segment will fit.\r\n const nextSeg = this.pendingSegs[0];\r\n if (nextSeg.d.length +\r\n SEG_HEADER_SIZE +\r\n curDataString.length <=\r\n MAX_URL_DATA_SIZE) {\r\n //great, the segment will fit. Lets append it.\r\n const theSeg = this.pendingSegs.shift();\r\n curDataString =\r\n curDataString +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\r\n i +\r\n '=' +\r\n theSeg.seg +\r\n '&' +\r\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\r\n i +\r\n '=' +\r\n theSeg.ts +\r\n '&' +\r\n FIREBASE_LONGPOLL_DATA_PARAM +\r\n i +\r\n '=' +\r\n theSeg.d;\r\n i++;\r\n }\r\n else {\r\n break;\r\n }\r\n }\r\n theURL = theURL + curDataString;\r\n this.addLongPollTag_(theURL, this.currentSerial);\r\n return true;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\r\n enqueueSegment(segnum, totalsegs, data) {\r\n //add this to the queue of segments to send.\r\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\r\n //send the data immediately if there isn't already data being transmitted, unless\r\n //startLongPoll hasn't been called yet.\r\n if (this.alive) {\r\n this.newRequest_();\r\n }\r\n }\r\n /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param url - The URL of the script tag.\r\n * @param serial - The serial number of the request.\r\n */\r\n addLongPollTag_(url, serial) {\r\n //remember that we sent this request.\r\n this.outstandingRequests.add(serial);\r\n const doNewRequest = () => {\r\n this.outstandingRequests.delete(serial);\r\n this.newRequest_();\r\n };\r\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\r\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\r\n const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\r\n const readyStateCB = () => {\r\n // Request completed. Cancel the keepalive.\r\n clearTimeout(keepaliveTimeout);\r\n // Trigger a new request so we can continue receiving data.\r\n doNewRequest();\r\n };\r\n this.addTag(url, readyStateCB);\r\n }\r\n /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param url - The URL for the script tag source.\r\n * @param loadCB - A callback to be triggered once the script has loaded.\r\n */\r\n addTag(url, loadCB) {\r\n if (isNodeSdk()) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n this.doNodeLongPoll(url, loadCB);\r\n }\r\n else {\r\n setTimeout(() => {\r\n try {\r\n // if we're already closed, don't add this poll\r\n if (!this.sendNewPolls) {\r\n return;\r\n }\r\n const newScript = this.myIFrame.doc.createElement('script');\r\n newScript.type = 'text/javascript';\r\n newScript.async = true;\r\n newScript.src = url;\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange =\r\n function () {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const rstate = newScript.readyState;\r\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n newScript.onload = newScript.onreadystatechange = null;\r\n if (newScript.parentNode) {\r\n newScript.parentNode.removeChild(newScript);\r\n }\r\n loadCB();\r\n }\r\n };\r\n newScript.onerror = () => {\r\n log('Long-poll script failed to load: ' + url);\r\n this.sendNewPolls = false;\r\n this.close();\r\n };\r\n this.myIFrame.doc.body.appendChild(newScript);\r\n }\r\n catch (e) {\r\n // TODO: we should make this error visible somehow\r\n }\r\n }, Math.floor(1));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\r\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\r\nlet WebSocketImpl = null;\r\nif (typeof MozWebSocket !== 'undefined') {\r\n WebSocketImpl = MozWebSocket;\r\n}\r\nelse if (typeof WebSocket !== 'undefined') {\r\n WebSocketImpl = WebSocket;\r\n}\r\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n */\r\nclass WebSocketConnection {\r\n /**\r\n * @param connId identifier for this transport\r\n * @param repoInfo The info for the websocket endpoint.\r\n * @param applicationId The Firebase App ID for this project.\r\n * @param appCheckToken The App Check Token for this client.\r\n * @param authToken The Auth Token for this client.\r\n * @param transportSessionId Optional transportSessionId if this is connecting\r\n * to an existing transport session\r\n * @param lastSessionId Optional lastSessionId if there was a previous\r\n * connection\r\n */\r\n constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {\r\n this.connId = connId;\r\n this.applicationId = applicationId;\r\n this.appCheckToken = appCheckToken;\r\n this.authToken = authToken;\r\n this.keepaliveTimer = null;\r\n this.frames = null;\r\n this.totalFrames = 0;\r\n this.bytesSent = 0;\r\n this.bytesReceived = 0;\r\n this.log_ = logWrapper(this.connId);\r\n this.stats_ = statsManagerGetCollection(repoInfo);\r\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken);\r\n this.nodeAdmin = repoInfo.nodeAdmin;\r\n }\r\n /**\r\n * @param repoInfo - The info for the websocket endpoint.\r\n * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param lastSessionId - Optional lastSessionId if there was a previous connection\r\n * @returns connection url\r\n */\r\n static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken) {\r\n const urlParams = {};\r\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\r\n if (!isNodeSdk() &&\r\n typeof location !== 'undefined' &&\r\n location.hostname &&\r\n FORGE_DOMAIN_RE.test(location.hostname)) {\r\n urlParams[REFERER_PARAM] = FORGE_REF;\r\n }\r\n if (transportSessionId) {\r\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\r\n }\r\n if (lastSessionId) {\r\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\r\n }\r\n if (appCheckToken) {\r\n urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;\r\n }\r\n return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);\r\n }\r\n /**\r\n * @param onMessage - Callback when messages arrive\r\n * @param onDisconnect - Callback with connection lost.\r\n */\r\n open(onMessage, onDisconnect) {\r\n this.onDisconnect = onDisconnect;\r\n this.onMessage = onMessage;\r\n this.log_('Websocket connecting to ' + this.connURL);\r\n this.everConnected_ = false;\r\n // Assume failure until proven otherwise.\r\n PersistentStorage.set('previous_websocket_failure', true);\r\n try {\r\n if (isNodeSdk()) {\r\n const device = this.nodeAdmin ? 'AdminNode' : 'Node';\r\n // UA Format: Firebase////\r\n const options = {\r\n headers: {\r\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${SDK_VERSION}/${process.platform}/${device}`,\r\n 'X-Firebase-GMPID': this.applicationId || ''\r\n }\r\n };\r\n // If using Node with admin creds, AppCheck-related checks are unnecessary.\r\n // Note that we send the credentials here even if they aren't admin credentials, which is\r\n // not a problem.\r\n // Note that this header is just used to bypass appcheck, and the token should still be sent\r\n // through the websocket connection once it is established.\r\n if (this.authToken) {\r\n options.headers['Authorization'] = `Bearer ${this.authToken}`;\r\n }\r\n if (this.appCheckToken) {\r\n options.headers['X-Firebase-AppCheck'] = this.appCheckToken;\r\n }\r\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\r\n const env = process['env'];\r\n const proxy = this.connURL.indexOf('wss://') === 0\r\n ? env['HTTPS_PROXY'] || env['https_proxy']\r\n : env['HTTP_PROXY'] || env['http_proxy'];\r\n if (proxy) {\r\n options['proxy'] = { origin: proxy };\r\n }\r\n this.mySock = new WebSocketImpl(this.connURL, [], options);\r\n }\r\n else {\r\n const options = {\r\n headers: {\r\n 'X-Firebase-GMPID': this.applicationId || '',\r\n 'X-Firebase-AppCheck': this.appCheckToken || ''\r\n }\r\n };\r\n this.mySock = new WebSocketImpl(this.connURL, [], options);\r\n }\r\n }\r\n catch (e) {\r\n this.log_('Error instantiating WebSocket.');\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n return;\r\n }\r\n this.mySock.onopen = () => {\r\n this.log_('Websocket connected.');\r\n this.everConnected_ = true;\r\n };\r\n this.mySock.onclose = () => {\r\n this.log_('Websocket connection was disconnected.');\r\n this.mySock = null;\r\n this.onClosed_();\r\n };\r\n this.mySock.onmessage = m => {\r\n this.handleIncomingFrame(m);\r\n };\r\n this.mySock.onerror = e => {\r\n this.log_('WebSocket error. Closing connection.');\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const error = e.message || e.data;\r\n if (error) {\r\n this.log_(error);\r\n }\r\n this.onClosed_();\r\n };\r\n }\r\n /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\n */\r\n start() { }\r\n static forceDisallow() {\r\n WebSocketConnection.forceDisallow_ = true;\r\n }\r\n static isAvailable() {\r\n let isOldAndroid = false;\r\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\r\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\r\n const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\r\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\r\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\r\n isOldAndroid = true;\r\n }\r\n }\r\n }\r\n return (!isOldAndroid &&\r\n WebSocketImpl !== null &&\r\n !WebSocketConnection.forceDisallow_);\r\n }\r\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n */\r\n static previouslyFailed() {\r\n // If our persistent storage is actually only in-memory storage,\r\n // we default to assuming that it previously failed to be safe.\r\n return (PersistentStorage.isInMemoryStorage ||\r\n PersistentStorage.get('previous_websocket_failure') === true);\r\n }\r\n markConnectionHealthy() {\r\n PersistentStorage.remove('previous_websocket_failure');\r\n }\r\n appendFrame_(data) {\r\n this.frames.push(data);\r\n if (this.frames.length === this.totalFrames) {\r\n const fullMess = this.frames.join('');\r\n this.frames = null;\r\n const jsonMess = jsonEval(fullMess);\r\n //handle the message\r\n this.onMessage(jsonMess);\r\n }\r\n }\r\n /**\r\n * @param frameCount - The number of frames we are expecting from the server\r\n */\r\n handleNewFrameCount_(frameCount) {\r\n this.totalFrames = frameCount;\r\n this.frames = [];\r\n }\r\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @returns Any remaining data to be process, or null if there is none\r\n */\r\n extractFrameCount_(data) {\r\n assert(this.frames === null, 'We already have a frame buffer');\r\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\r\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\r\n if (data.length <= 6) {\r\n const frameCount = Number(data);\r\n if (!isNaN(frameCount)) {\r\n this.handleNewFrameCount_(frameCount);\r\n return null;\r\n }\r\n }\r\n this.handleNewFrameCount_(1);\r\n return data;\r\n }\r\n /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess - The frame data\r\n */\r\n handleIncomingFrame(mess) {\r\n if (this.mySock === null) {\r\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\r\n }\r\n const data = mess['data'];\r\n this.bytesReceived += data.length;\r\n this.stats_.incrementCounter('bytes_received', data.length);\r\n this.resetKeepAlive();\r\n if (this.frames !== null) {\r\n // we're buffering\r\n this.appendFrame_(data);\r\n }\r\n else {\r\n // try to parse out a frame count, otherwise, assume 1 and process it\r\n const remainingData = this.extractFrameCount_(data);\r\n if (remainingData !== null) {\r\n this.appendFrame_(remainingData);\r\n }\r\n }\r\n }\r\n /**\r\n * Send a message to the server\r\n * @param data - The JSON object to transmit\r\n */\r\n send(data) {\r\n this.resetKeepAlive();\r\n const dataStr = stringify(data);\r\n this.bytesSent += dataStr.length;\r\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\r\n //We can only fit a certain amount in each websocket frame, so we need to split this request\r\n //up into multiple pieces if it doesn't fit in one request.\r\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\r\n //Send the length header\r\n if (dataSegs.length > 1) {\r\n this.sendString_(String(dataSegs.length));\r\n }\r\n //Send the actual data in segments.\r\n for (let i = 0; i < dataSegs.length; i++) {\r\n this.sendString_(dataSegs[i]);\r\n }\r\n }\r\n shutdown_() {\r\n this.isClosed_ = true;\r\n if (this.keepaliveTimer) {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = null;\r\n }\r\n if (this.mySock) {\r\n this.mySock.close();\r\n this.mySock = null;\r\n }\r\n }\r\n onClosed_() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is closing itself');\r\n this.shutdown_();\r\n // since this is an internal close, trigger the close listener\r\n if (this.onDisconnect) {\r\n this.onDisconnect(this.everConnected_);\r\n this.onDisconnect = null;\r\n }\r\n }\r\n }\r\n /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\r\n close() {\r\n if (!this.isClosed_) {\r\n this.log_('WebSocket is being closed');\r\n this.shutdown_();\r\n }\r\n }\r\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\r\n resetKeepAlive() {\r\n clearInterval(this.keepaliveTimer);\r\n this.keepaliveTimer = setInterval(() => {\r\n //If there has been no websocket activity for a while, send a no-op\r\n if (this.mySock) {\r\n this.sendString_('0');\r\n }\r\n this.resetKeepAlive();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\r\n }\r\n /**\r\n * Send a string over the websocket.\r\n *\r\n * @param str - String to send.\r\n */\r\n sendString_(str) {\r\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\r\n // calls for some unknown reason. We treat these as an error and disconnect.\r\n // See https://app.asana.com/0/58926111402292/68021340250410\r\n try {\r\n this.mySock.send(str);\r\n }\r\n catch (e) {\r\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\r\n setTimeout(this.onClosed_.bind(this), 0);\r\n }\r\n }\r\n}\r\n/**\r\n * Number of response before we consider the connection \"healthy.\"\r\n */\r\nWebSocketConnection.responsesRequiredToBeHealthy = 2;\r\n/**\r\n * Time to wait for the connection te become healthy before giving up.\r\n */\r\nWebSocketConnection.healthyTimeout = 30000;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\r\n * lifecycle.\r\n *\r\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\r\n * they are available.\r\n */\r\nclass TransportManager {\r\n /**\r\n * @param repoInfo - Metadata around the namespace we're connecting to\r\n */\r\n constructor(repoInfo) {\r\n this.initTransports_(repoInfo);\r\n }\r\n static get ALL_TRANSPORTS() {\r\n return [BrowserPollConnection, WebSocketConnection];\r\n }\r\n initTransports_(repoInfo) {\r\n const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\r\n let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\r\n if (repoInfo.webSocketOnly) {\r\n if (!isWebSocketsAvailable) {\r\n warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\r\n }\r\n isSkipPollConnection = true;\r\n }\r\n if (isSkipPollConnection) {\r\n this.transports_ = [WebSocketConnection];\r\n }\r\n else {\r\n const transports = (this.transports_ = []);\r\n for (const transport of TransportManager.ALL_TRANSPORTS) {\r\n if (transport && transport['isAvailable']()) {\r\n transports.push(transport);\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the initial transport to use\r\n */\r\n initialTransport() {\r\n if (this.transports_.length > 0) {\r\n return this.transports_[0];\r\n }\r\n else {\r\n throw new Error('No transports available');\r\n }\r\n }\r\n /**\r\n * @returns The constructor for the next transport, or null\r\n */\r\n upgradeTransport() {\r\n if (this.transports_.length > 1) {\r\n return this.transports_[1];\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Abort upgrade attempt if it takes longer than 60s.\r\nconst UPGRADE_TIMEOUT = 60000;\r\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\r\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\r\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\r\n// If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\r\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\r\n// but we've sent/received enough bytes, we don't cancel the connection.\r\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\r\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\r\nconst MESSAGE_TYPE = 't';\r\nconst MESSAGE_DATA = 'd';\r\nconst CONTROL_SHUTDOWN = 's';\r\nconst CONTROL_RESET = 'r';\r\nconst CONTROL_ERROR = 'e';\r\nconst CONTROL_PONG = 'o';\r\nconst SWITCH_ACK = 'a';\r\nconst END_TRANSMISSION = 'n';\r\nconst PING = 'p';\r\nconst SERVER_HELLO = 'h';\r\n/**\r\n * Creates a new real-time connection to the server using whichever method works\r\n * best in the current browser.\r\n */\r\nclass Connection {\r\n /**\r\n * @param id - an id for this connection\r\n * @param repoInfo_ - the info for the endpoint to connect to\r\n * @param applicationId_ - the Firebase App ID for this project\r\n * @param appCheckToken_ - The App Check Token for this device.\r\n * @param authToken_ - The auth token for this session.\r\n * @param onMessage_ - the callback to be triggered when a server-push message arrives\r\n * @param onReady_ - the callback to be triggered when this connection is ready to send messages.\r\n * @param onDisconnect_ - the callback to be triggered when a connection was lost\r\n * @param onKill_ - the callback to be triggered when this connection has permanently shut down.\r\n * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\r\n */\r\n constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\r\n this.id = id;\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.appCheckToken_ = appCheckToken_;\r\n this.authToken_ = authToken_;\r\n this.onMessage_ = onMessage_;\r\n this.onReady_ = onReady_;\r\n this.onDisconnect_ = onDisconnect_;\r\n this.onKill_ = onKill_;\r\n this.lastSessionId = lastSessionId;\r\n this.connectionCount = 0;\r\n this.pendingDataMessages = [];\r\n this.state_ = 0 /* CONNECTING */;\r\n this.log_ = logWrapper('c:' + this.id + ':');\r\n this.transportManager_ = new TransportManager(repoInfo_);\r\n this.log_('Connection created');\r\n this.start_();\r\n }\r\n /**\r\n * Starts a connection attempt\r\n */\r\n start_() {\r\n const conn = this.transportManager_.initialTransport();\r\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessageReceived = this.connReceiver_(this.conn_);\r\n const onConnectionLost = this.disconnReceiver_(this.conn_);\r\n this.tx_ = this.conn_;\r\n this.rx_ = this.conn_;\r\n this.secondaryConn_ = null;\r\n this.isHealthy_ = false;\r\n /*\r\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\r\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\r\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\r\n * still have the context of your originating frame.\r\n */\r\n setTimeout(() => {\r\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\r\n this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);\r\n }, Math.floor(0));\r\n const healthyTimeoutMS = conn['healthyTimeout'] || 0;\r\n if (healthyTimeoutMS > 0) {\r\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\r\n this.healthyTimeout_ = null;\r\n if (!this.isHealthy_) {\r\n if (this.conn_ &&\r\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has received ' +\r\n this.conn_.bytesReceived +\r\n ' bytes. Marking connection healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n else if (this.conn_ &&\r\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\r\n this.log_('Connection exceeded healthy timeout but has sent ' +\r\n this.conn_.bytesSent +\r\n ' bytes. Leaving connection alive.');\r\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\r\n // the server.\r\n }\r\n else {\r\n this.log_('Closing unhealthy connection after timeout.');\r\n this.close();\r\n }\r\n }\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(healthyTimeoutMS));\r\n }\r\n }\r\n nextTransportId_() {\r\n return 'c:' + this.id + ':' + this.connectionCount++;\r\n }\r\n disconnReceiver_(conn) {\r\n return everConnected => {\r\n if (conn === this.conn_) {\r\n this.onConnectionLost_(everConnected);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.log_('Secondary connection lost.');\r\n this.onSecondaryConnectionLost_();\r\n }\r\n else {\r\n this.log_('closing an old connection');\r\n }\r\n };\r\n }\r\n connReceiver_(conn) {\r\n return (message) => {\r\n if (this.state_ !== 2 /* DISCONNECTED */) {\r\n if (conn === this.rx_) {\r\n this.onPrimaryMessageReceived_(message);\r\n }\r\n else if (conn === this.secondaryConn_) {\r\n this.onSecondaryMessageReceived_(message);\r\n }\r\n else {\r\n this.log_('message on old connection');\r\n }\r\n }\r\n };\r\n }\r\n /**\r\n * @param dataMsg - An arbitrary data message to be sent to the server\r\n */\r\n sendRequest(dataMsg) {\r\n // wrap in a data message envelope and send it on\r\n const msg = { t: 'd', d: dataMsg };\r\n this.sendData_(msg);\r\n }\r\n tryCleanupConnection() {\r\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\r\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\r\n this.conn_ = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n // the server will shutdown the old connection\r\n }\r\n }\r\n onSecondaryControl_(controlData) {\r\n if (MESSAGE_TYPE in controlData) {\r\n const cmd = controlData[MESSAGE_TYPE];\r\n if (cmd === SWITCH_ACK) {\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // Most likely the session wasn't valid. Abandon the switch attempt\r\n this.log_('Got a reset on secondary, closing it');\r\n this.secondaryConn_.close();\r\n // If we were already using this connection for something, than we need to fully close\r\n if (this.tx_ === this.secondaryConn_ ||\r\n this.rx_ === this.secondaryConn_) {\r\n this.close();\r\n }\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on secondary.');\r\n this.secondaryResponsesRequired_--;\r\n this.upgradeIfSecondaryHealthy_();\r\n }\r\n }\r\n }\r\n onSecondaryMessageReceived_(parsedData) {\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onSecondaryControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n // got a data message, but we're still second connection. Need to buffer it up\r\n this.pendingDataMessages.push(data);\r\n }\r\n else {\r\n throw new Error('Unknown protocol layer: ' + layer);\r\n }\r\n }\r\n upgradeIfSecondaryHealthy_() {\r\n if (this.secondaryResponsesRequired_ <= 0) {\r\n this.log_('Secondary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.secondaryConn_.markConnectionHealthy();\r\n this.proceedWithUpgrade_();\r\n }\r\n else {\r\n // Send a ping to make sure the connection is healthy.\r\n this.log_('sending ping on secondary.');\r\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n proceedWithUpgrade_() {\r\n // tell this connection to consider itself open\r\n this.secondaryConn_.start();\r\n // send ack\r\n this.log_('sending client ack on secondary');\r\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\r\n // send end packet on primary transport, switch to sending on this one\r\n // can receive on this one, buffer responses until end received on primary transport\r\n this.log_('Ending transmission on primary');\r\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\r\n this.tx_ = this.secondaryConn_;\r\n this.tryCleanupConnection();\r\n }\r\n onPrimaryMessageReceived_(parsedData) {\r\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\r\n const layer = requireKey('t', parsedData);\r\n const data = requireKey('d', parsedData);\r\n if (layer === 'c') {\r\n this.onControl_(data);\r\n }\r\n else if (layer === 'd') {\r\n this.onDataMessage_(data);\r\n }\r\n }\r\n onDataMessage_(message) {\r\n this.onPrimaryResponse_();\r\n // We don't do anything with data messages, just kick them up a level\r\n this.onMessage_(message);\r\n }\r\n onPrimaryResponse_() {\r\n if (!this.isHealthy_) {\r\n this.primaryResponsesRequired_--;\r\n if (this.primaryResponsesRequired_ <= 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n this.conn_.markConnectionHealthy();\r\n }\r\n }\r\n }\r\n onControl_(controlData) {\r\n const cmd = requireKey(MESSAGE_TYPE, controlData);\r\n if (MESSAGE_DATA in controlData) {\r\n const payload = controlData[MESSAGE_DATA];\r\n if (cmd === SERVER_HELLO) {\r\n this.onHandshake_(payload);\r\n }\r\n else if (cmd === END_TRANSMISSION) {\r\n this.log_('recvd end transmission on primary');\r\n this.rx_ = this.secondaryConn_;\r\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\r\n this.onDataMessage_(this.pendingDataMessages[i]);\r\n }\r\n this.pendingDataMessages = [];\r\n this.tryCleanupConnection();\r\n }\r\n else if (cmd === CONTROL_SHUTDOWN) {\r\n // This was previously the 'onKill' callback passed to the lower-level connection\r\n // payload in this case is the reason for the shutdown. Generally a human-readable error\r\n this.onConnectionShutdown_(payload);\r\n }\r\n else if (cmd === CONTROL_RESET) {\r\n // payload in this case is the host we should contact\r\n this.onReset_(payload);\r\n }\r\n else if (cmd === CONTROL_ERROR) {\r\n error('Server Error: ' + payload);\r\n }\r\n else if (cmd === CONTROL_PONG) {\r\n this.log_('got pong on primary.');\r\n this.onPrimaryResponse_();\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }\r\n else {\r\n error('Unknown control packet command: ' + cmd);\r\n }\r\n }\r\n }\r\n /**\r\n * @param handshake - The handshake data returned from the server\r\n */\r\n onHandshake_(handshake) {\r\n const timestamp = handshake.ts;\r\n const version = handshake.v;\r\n const host = handshake.h;\r\n this.sessionId = handshake.s;\r\n this.repoInfo_.host = host;\r\n // if we've already closed the connection, then don't bother trying to progress further\r\n if (this.state_ === 0 /* CONNECTING */) {\r\n this.conn_.start();\r\n this.onConnectionEstablished_(this.conn_, timestamp);\r\n if (PROTOCOL_VERSION !== version) {\r\n warn('Protocol version mismatch detected');\r\n }\r\n // TODO: do we want to upgrade? when? maybe a delay?\r\n this.tryStartUpgrade_();\r\n }\r\n }\r\n tryStartUpgrade_() {\r\n const conn = this.transportManager_.upgradeTransport();\r\n if (conn) {\r\n this.startUpgrade_(conn);\r\n }\r\n }\r\n startUpgrade_(conn) {\r\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);\r\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\r\n // can consider the transport healthy.\r\n this.secondaryResponsesRequired_ =\r\n conn['responsesRequiredToBeHealthy'] || 0;\r\n const onMessage = this.connReceiver_(this.secondaryConn_);\r\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\r\n this.secondaryConn_.open(onMessage, onDisconnect);\r\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\r\n setTimeoutNonBlocking(() => {\r\n if (this.secondaryConn_) {\r\n this.log_('Timed out trying to upgrade.');\r\n this.secondaryConn_.close();\r\n }\r\n }, Math.floor(UPGRADE_TIMEOUT));\r\n }\r\n onReset_(host) {\r\n this.log_('Reset packet received. New host: ' + host);\r\n this.repoInfo_.host = host;\r\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\r\n // We don't currently support resets after the connection has already been established\r\n if (this.state_ === 1 /* CONNECTED */) {\r\n this.close();\r\n }\r\n else {\r\n // Close whatever connections we have open and start again.\r\n this.closeConnections_();\r\n this.start_();\r\n }\r\n }\r\n onConnectionEstablished_(conn, timestamp) {\r\n this.log_('Realtime connection established.');\r\n this.conn_ = conn;\r\n this.state_ = 1 /* CONNECTED */;\r\n if (this.onReady_) {\r\n this.onReady_(timestamp, this.sessionId);\r\n this.onReady_ = null;\r\n }\r\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\r\n // send some pings.\r\n if (this.primaryResponsesRequired_ === 0) {\r\n this.log_('Primary connection is healthy.');\r\n this.isHealthy_ = true;\r\n }\r\n else {\r\n setTimeoutNonBlocking(() => {\r\n this.sendPingOnPrimaryIfNecessary_();\r\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\r\n }\r\n }\r\n sendPingOnPrimaryIfNecessary_() {\r\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\r\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\r\n this.log_('sending ping on primary.');\r\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\r\n }\r\n }\r\n onSecondaryConnectionLost_() {\r\n const conn = this.secondaryConn_;\r\n this.secondaryConn_ = null;\r\n if (this.tx_ === conn || this.rx_ === conn) {\r\n // we are relying on this connection already in some capacity. Therefore, a failure is real\r\n this.close();\r\n }\r\n }\r\n /**\r\n * @param everConnected - Whether or not the connection ever reached a server. Used to determine if\r\n * we should flush the host cache\r\n */\r\n onConnectionLost_(everConnected) {\r\n this.conn_ = null;\r\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\r\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\r\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\r\n this.log_('Realtime connection failed.');\r\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\r\n if (this.repoInfo_.isCacheableHost()) {\r\n PersistentStorage.remove('host:' + this.repoInfo_.host);\r\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\r\n this.repoInfo_.internalHost = this.repoInfo_.host;\r\n }\r\n }\r\n else if (this.state_ === 1 /* CONNECTED */) {\r\n this.log_('Realtime connection lost.');\r\n }\r\n this.close();\r\n }\r\n onConnectionShutdown_(reason) {\r\n this.log_('Connection shutdown command received. Shutting down...');\r\n if (this.onKill_) {\r\n this.onKill_(reason);\r\n this.onKill_ = null;\r\n }\r\n // We intentionally don't want to fire onDisconnect (kill is a different case),\r\n // so clear the callback.\r\n this.onDisconnect_ = null;\r\n this.close();\r\n }\r\n sendData_(data) {\r\n if (this.state_ !== 1 /* CONNECTED */) {\r\n throw 'Connection is not connected';\r\n }\r\n else {\r\n this.tx_.send(data);\r\n }\r\n }\r\n /**\r\n * Cleans up this connection, calling the appropriate callbacks\r\n */\r\n close() {\r\n if (this.state_ !== 2 /* DISCONNECTED */) {\r\n this.log_('Closing realtime connection.');\r\n this.state_ = 2 /* DISCONNECTED */;\r\n this.closeConnections_();\r\n if (this.onDisconnect_) {\r\n this.onDisconnect_();\r\n this.onDisconnect_ = null;\r\n }\r\n }\r\n }\r\n closeConnections_() {\r\n this.log_('Shutting down all connections');\r\n if (this.conn_) {\r\n this.conn_.close();\r\n this.conn_ = null;\r\n }\r\n if (this.secondaryConn_) {\r\n this.secondaryConn_.close();\r\n this.secondaryConn_ = null;\r\n }\r\n if (this.healthyTimeout_) {\r\n clearTimeout(this.healthyTimeout_);\r\n this.healthyTimeout_ = null;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\r\nclass ServerActions {\r\n put(pathString, data, onComplete, hash) { }\r\n merge(pathString, data, onComplete, hash) { }\r\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param token - The authentication token\r\n */\r\n refreshAuthToken(token) { }\r\n /**\r\n * Refreshes the app check token for the current connection.\r\n * @param token The app check token\r\n */\r\n refreshAppCheckToken(token) { }\r\n onDisconnectPut(pathString, data, onComplete) { }\r\n onDisconnectMerge(pathString, data, onComplete) { }\r\n onDisconnectCancel(pathString, onComplete) { }\r\n reportStats(stats) { }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Base class to be used if you want to emit events. Call the constructor with\r\n * the set of allowed event names.\r\n */\r\nclass EventEmitter {\r\n constructor(allowedEvents_) {\r\n this.allowedEvents_ = allowedEvents_;\r\n this.listeners_ = {};\r\n assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\r\n }\r\n /**\r\n * To be called by derived classes to trigger events.\r\n */\r\n trigger(eventType, ...varArgs) {\r\n if (Array.isArray(this.listeners_[eventType])) {\r\n // Clone the list, since callbacks could add/remove listeners.\r\n const listeners = [...this.listeners_[eventType]];\r\n for (let i = 0; i < listeners.length; i++) {\r\n listeners[i].callback.apply(listeners[i].context, varArgs);\r\n }\r\n }\r\n }\r\n on(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n this.listeners_[eventType] = this.listeners_[eventType] || [];\r\n this.listeners_[eventType].push({ callback, context });\r\n const eventData = this.getInitialEvent(eventType);\r\n if (eventData) {\r\n callback.apply(context, eventData);\r\n }\r\n }\r\n off(eventType, callback, context) {\r\n this.validateEventType_(eventType);\r\n const listeners = this.listeners_[eventType] || [];\r\n for (let i = 0; i < listeners.length; i++) {\r\n if (listeners[i].callback === callback &&\r\n (!context || context === listeners[i].context)) {\r\n listeners.splice(i, 1);\r\n return;\r\n }\r\n }\r\n }\r\n validateEventType_(eventType) {\r\n assert(this.allowedEvents_.find(et => {\r\n return et === eventType;\r\n }), 'Unknown event: ' + eventType);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Monitors online state (as reported by window.online/offline events).\r\n *\r\n * The expectation is that this could have many false positives (thinks we are online\r\n * when we're not), but no false negatives. So we can safely use it to determine when\r\n * we definitely cannot reach the internet.\r\n */\r\nclass OnlineMonitor extends EventEmitter {\r\n constructor() {\r\n super(['online']);\r\n this.online_ = true;\r\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\r\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\r\n // It would seem that the 'online' event does not always fire consistently. So we disable it\r\n // for Cordova.\r\n if (typeof window !== 'undefined' &&\r\n typeof window.addEventListener !== 'undefined' &&\r\n !isMobileCordova()) {\r\n window.addEventListener('online', () => {\r\n if (!this.online_) {\r\n this.online_ = true;\r\n this.trigger('online', true);\r\n }\r\n }, false);\r\n window.addEventListener('offline', () => {\r\n if (this.online_) {\r\n this.online_ = false;\r\n this.trigger('online', false);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new OnlineMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\r\n return [this.online_];\r\n }\r\n currentlyOnline() {\r\n return this.online_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/** Maximum key depth. */\r\nconst MAX_PATH_DEPTH = 32;\r\n/** Maximum number of (UTF8) bytes in a Firebase path. */\r\nconst MAX_PATH_LENGTH_BYTES = 768;\r\n/**\r\n * An immutable object representing a parsed path. It's immutable so that you\r\n * can pass them around to other functions without worrying about them changing\r\n * it.\r\n */\r\nclass Path {\r\n /**\r\n * @param pathOrString - Path string to parse, or another path, or the raw\r\n * tokens array\r\n */\r\n constructor(pathOrString, pieceNum) {\r\n if (pieceNum === void 0) {\r\n this.pieces_ = pathOrString.split('/');\r\n // Remove empty pieces.\r\n let copyTo = 0;\r\n for (let i = 0; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i].length > 0) {\r\n this.pieces_[copyTo] = this.pieces_[i];\r\n copyTo++;\r\n }\r\n }\r\n this.pieces_.length = copyTo;\r\n this.pieceNum_ = 0;\r\n }\r\n else {\r\n this.pieces_ = pathOrString;\r\n this.pieceNum_ = pieceNum;\r\n }\r\n }\r\n toString() {\r\n let pathString = '';\r\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\r\n if (this.pieces_[i] !== '') {\r\n pathString += '/' + this.pieces_[i];\r\n }\r\n }\r\n return pathString || '/';\r\n }\r\n}\r\nfunction newEmptyPath() {\r\n return new Path('');\r\n}\r\nfunction pathGetFront(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n return path.pieces_[path.pieceNum_];\r\n}\r\n/**\r\n * @returns The number of segments in this path\r\n */\r\nfunction pathGetLength(path) {\r\n return path.pieces_.length - path.pieceNum_;\r\n}\r\nfunction pathPopFront(path) {\r\n let pieceNum = path.pieceNum_;\r\n if (pieceNum < path.pieces_.length) {\r\n pieceNum++;\r\n }\r\n return new Path(path.pieces_, pieceNum);\r\n}\r\nfunction pathGetBack(path) {\r\n if (path.pieceNum_ < path.pieces_.length) {\r\n return path.pieces_[path.pieces_.length - 1];\r\n }\r\n return null;\r\n}\r\nfunction pathToUrlEncodedString(path) {\r\n let pathString = '';\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n if (path.pieces_[i] !== '') {\r\n pathString += '/' + encodeURIComponent(String(path.pieces_[i]));\r\n }\r\n }\r\n return pathString || '/';\r\n}\r\n/**\r\n * Shallow copy of the parts of the path.\r\n *\r\n */\r\nfunction pathSlice(path, begin = 0) {\r\n return path.pieces_.slice(path.pieceNum_ + begin);\r\n}\r\nfunction pathParent(path) {\r\n if (path.pieceNum_ >= path.pieces_.length) {\r\n return null;\r\n }\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length - 1; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n return new Path(pieces, 0);\r\n}\r\nfunction pathChild(path, childPathObj) {\r\n const pieces = [];\r\n for (let i = path.pieceNum_; i < path.pieces_.length; i++) {\r\n pieces.push(path.pieces_[i]);\r\n }\r\n if (childPathObj instanceof Path) {\r\n for (let i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\r\n pieces.push(childPathObj.pieces_[i]);\r\n }\r\n }\r\n else {\r\n const childPieces = childPathObj.split('/');\r\n for (let i = 0; i < childPieces.length; i++) {\r\n if (childPieces[i].length > 0) {\r\n pieces.push(childPieces[i]);\r\n }\r\n }\r\n }\r\n return new Path(pieces, 0);\r\n}\r\n/**\r\n * @returns True if there are no segments in this path\r\n */\r\nfunction pathIsEmpty(path) {\r\n return path.pieceNum_ >= path.pieces_.length;\r\n}\r\n/**\r\n * @returns The path from outerPath to innerPath\r\n */\r\nfunction newRelativePath(outerPath, innerPath) {\r\n const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);\r\n if (outer === null) {\r\n return innerPath;\r\n }\r\n else if (outer === inner) {\r\n return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));\r\n }\r\n else {\r\n throw new Error('INTERNAL ERROR: innerPath (' +\r\n innerPath +\r\n ') is not within ' +\r\n 'outerPath (' +\r\n outerPath +\r\n ')');\r\n }\r\n}\r\n/**\r\n * @returns -1, 0, 1 if left is less, equal, or greater than the right.\r\n */\r\nfunction pathCompare(left, right) {\r\n const leftKeys = pathSlice(left, 0);\r\n const rightKeys = pathSlice(right, 0);\r\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\r\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\r\n if (cmp !== 0) {\r\n return cmp;\r\n }\r\n }\r\n if (leftKeys.length === rightKeys.length) {\r\n return 0;\r\n }\r\n return leftKeys.length < rightKeys.length ? -1 : 1;\r\n}\r\n/**\r\n * @returns true if paths are the same.\r\n */\r\nfunction pathEquals(path, other) {\r\n if (pathGetLength(path) !== pathGetLength(other)) {\r\n return false;\r\n }\r\n for (let i = path.pieceNum_, j = other.pieceNum_; i <= path.pieces_.length; i++, j++) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n}\r\n/**\r\n * @returns True if this path is a parent (or the same as) other\r\n */\r\nfunction pathContains(path, other) {\r\n let i = path.pieceNum_;\r\n let j = other.pieceNum_;\r\n if (pathGetLength(path) > pathGetLength(other)) {\r\n return false;\r\n }\r\n while (i < path.pieces_.length) {\r\n if (path.pieces_[i] !== other.pieces_[j]) {\r\n return false;\r\n }\r\n ++i;\r\n ++j;\r\n }\r\n return true;\r\n}\r\n/**\r\n * Dynamic (mutable) path used to count path lengths.\r\n *\r\n * This class is used to efficiently check paths for valid\r\n * length (in UTF8 bytes) and depth (used in path validation).\r\n *\r\n * Throws Error exception if path is ever invalid.\r\n *\r\n * The definition of a path always begins with '/'.\r\n */\r\nclass ValidationPath {\r\n /**\r\n * @param path - Initial Path.\r\n * @param errorPrefix_ - Prefix for any error messages.\r\n */\r\n constructor(path, errorPrefix_) {\r\n this.errorPrefix_ = errorPrefix_;\r\n this.parts_ = pathSlice(path, 0);\r\n /** Initialize to number of '/' chars needed in path. */\r\n this.byteLength_ = Math.max(1, this.parts_.length);\r\n for (let i = 0; i < this.parts_.length; i++) {\r\n this.byteLength_ += stringLength(this.parts_[i]);\r\n }\r\n validationPathCheckValid(this);\r\n }\r\n}\r\nfunction validationPathPush(validationPath, child) {\r\n // Count the needed '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ += 1;\r\n }\r\n validationPath.parts_.push(child);\r\n validationPath.byteLength_ += stringLength(child);\r\n validationPathCheckValid(validationPath);\r\n}\r\nfunction validationPathPop(validationPath) {\r\n const last = validationPath.parts_.pop();\r\n validationPath.byteLength_ -= stringLength(last);\r\n // Un-count the previous '/'\r\n if (validationPath.parts_.length > 0) {\r\n validationPath.byteLength_ -= 1;\r\n }\r\n}\r\nfunction validationPathCheckValid(validationPath) {\r\n if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'has a key path longer than ' +\r\n MAX_PATH_LENGTH_BYTES +\r\n ' bytes (' +\r\n validationPath.byteLength_ +\r\n ').');\r\n }\r\n if (validationPath.parts_.length > MAX_PATH_DEPTH) {\r\n throw new Error(validationPath.errorPrefix_ +\r\n 'path specified exceeds the maximum depth that can be written (' +\r\n MAX_PATH_DEPTH +\r\n ') or object contains a cycle ' +\r\n validationPathToErrorString(validationPath));\r\n }\r\n}\r\n/**\r\n * String for use in error messages - uses '.' notation for path.\r\n */\r\nfunction validationPathToErrorString(validationPath) {\r\n if (validationPath.parts_.length === 0) {\r\n return '';\r\n }\r\n return \"in property '\" + validationPath.parts_.join('.') + \"'\";\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass VisibilityMonitor extends EventEmitter {\r\n constructor() {\r\n super(['visible']);\r\n let hidden;\r\n let visibilityChange;\r\n if (typeof document !== 'undefined' &&\r\n typeof document.addEventListener !== 'undefined') {\r\n if (typeof document['hidden'] !== 'undefined') {\r\n // Opera 12.10 and Firefox 18 and later support\r\n visibilityChange = 'visibilitychange';\r\n hidden = 'hidden';\r\n }\r\n else if (typeof document['mozHidden'] !== 'undefined') {\r\n visibilityChange = 'mozvisibilitychange';\r\n hidden = 'mozHidden';\r\n }\r\n else if (typeof document['msHidden'] !== 'undefined') {\r\n visibilityChange = 'msvisibilitychange';\r\n hidden = 'msHidden';\r\n }\r\n else if (typeof document['webkitHidden'] !== 'undefined') {\r\n visibilityChange = 'webkitvisibilitychange';\r\n hidden = 'webkitHidden';\r\n }\r\n }\r\n // Initially, we always assume we are visible. This ensures that in browsers\r\n // without page visibility support or in cases where we are never visible\r\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\r\n // reconnects\r\n this.visible_ = true;\r\n if (visibilityChange) {\r\n document.addEventListener(visibilityChange, () => {\r\n const visible = !document[hidden];\r\n if (visible !== this.visible_) {\r\n this.visible_ = visible;\r\n this.trigger('visible', visible);\r\n }\r\n }, false);\r\n }\r\n }\r\n static getInstance() {\r\n return new VisibilityMonitor();\r\n }\r\n getInitialEvent(eventType) {\r\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\r\n return [this.visible_];\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst RECONNECT_MIN_DELAY = 1000;\r\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\r\nconst GET_CONNECT_TIMEOUT = 3 * 1000;\r\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\r\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\r\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\r\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\r\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\r\nconst INVALID_TOKEN_THRESHOLD = 3;\r\n/**\r\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\r\n *\r\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\r\n * in quotes to make sure the closure compiler does not minify them.\r\n */\r\nclass PersistentConnection extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param applicationId_ - The Firebase App ID for this project\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.applicationId_ = applicationId_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.onConnectStatus_ = onConnectStatus_;\r\n this.onServerInfoUpdate_ = onServerInfoUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n this.authOverride_ = authOverride_;\r\n // Used for diagnostic logging.\r\n this.id = PersistentConnection.nextPersistentConnectionId_++;\r\n this.log_ = logWrapper('p:' + this.id + ':');\r\n this.interruptReasons_ = {};\r\n this.listens = new Map();\r\n this.outstandingPuts_ = [];\r\n this.outstandingGets_ = [];\r\n this.outstandingPutCount_ = 0;\r\n this.outstandingGetCount_ = 0;\r\n this.onDisconnectRequestQueue_ = [];\r\n this.connected_ = false;\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\r\n this.securityDebugCallback_ = null;\r\n this.lastSessionId = null;\r\n this.establishConnectionTimer_ = null;\r\n this.visible_ = false;\r\n // Before we get connected, we keep a queue of pending messages to send.\r\n this.requestCBHash_ = {};\r\n this.requestNumber_ = 0;\r\n this.realtime_ = null;\r\n this.authToken_ = null;\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = false;\r\n this.invalidAuthTokenCount_ = 0;\r\n this.invalidAppCheckTokenCount_ = 0;\r\n this.firstConnection_ = true;\r\n this.lastConnectionAttemptTime_ = null;\r\n this.lastConnectionEstablishedTime_ = null;\r\n if (authOverride_ && !isNodeSdk()) {\r\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\r\n }\r\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\r\n if (repoInfo_.host.indexOf('fblocal') === -1) {\r\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\r\n }\r\n }\r\n sendRequest(action, body, onResponse) {\r\n const curReqNum = ++this.requestNumber_;\r\n const msg = { r: curReqNum, a: action, b: body };\r\n this.log_(stringify(msg));\r\n assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\r\n this.realtime_.sendRequest(msg);\r\n if (onResponse) {\r\n this.requestCBHash_[curReqNum] = onResponse;\r\n }\r\n }\r\n get(query) {\r\n this.initConnection_();\r\n const deferred = new Deferred();\r\n const request = {\r\n p: query._path.toString(),\r\n q: query._queryObject\r\n };\r\n const outstandingGet = {\r\n action: 'g',\r\n request,\r\n onComplete: (message) => {\r\n const payload = message['d'];\r\n if (message['s'] === 'ok') {\r\n this.onDataUpdate_(request['p'], payload, \r\n /*isMerge*/ false, \r\n /*tag*/ null);\r\n deferred.resolve(payload);\r\n }\r\n else {\r\n deferred.reject(payload);\r\n }\r\n }\r\n };\r\n this.outstandingGets_.push(outstandingGet);\r\n this.outstandingGetCount_++;\r\n const index = this.outstandingGets_.length - 1;\r\n if (!this.connected_) {\r\n setTimeout(() => {\r\n const get = this.outstandingGets_[index];\r\n if (get === undefined || outstandingGet !== get) {\r\n return;\r\n }\r\n delete this.outstandingGets_[index];\r\n this.outstandingGetCount_--;\r\n if (this.outstandingGetCount_ === 0) {\r\n this.outstandingGets_ = [];\r\n }\r\n this.log_('get ' + index + ' timed out on connection');\r\n deferred.reject(new Error('Client is offline.'));\r\n }, GET_CONNECT_TIMEOUT);\r\n }\r\n if (this.connected_) {\r\n this.sendGet_(index);\r\n }\r\n return deferred.promise;\r\n }\r\n listen(query, currentHashFn, tag, onComplete) {\r\n this.initConnection_();\r\n const queryId = query._queryIdentifier;\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + queryId);\r\n if (!this.listens.has(pathString)) {\r\n this.listens.set(pathString, new Map());\r\n }\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'listen() called for non-default but complete query');\r\n assert(!this.listens.get(pathString).has(queryId), 'listen() called twice for same path/queryId.');\r\n const listenSpec = {\r\n onComplete,\r\n hashFn: currentHashFn,\r\n query,\r\n tag\r\n };\r\n this.listens.get(pathString).set(queryId, listenSpec);\r\n if (this.connected_) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n sendGet_(index) {\r\n const get = this.outstandingGets_[index];\r\n this.sendRequest('g', get.request, (message) => {\r\n delete this.outstandingGets_[index];\r\n this.outstandingGetCount_--;\r\n if (this.outstandingGetCount_ === 0) {\r\n this.outstandingGets_ = [];\r\n }\r\n if (get.onComplete) {\r\n get.onComplete(message);\r\n }\r\n });\r\n }\r\n sendListen_(listenSpec) {\r\n const query = listenSpec.query;\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Listen on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'q';\r\n // Only bother to send query if it's non-default.\r\n if (listenSpec.tag) {\r\n req['q'] = query._queryObject;\r\n req['t'] = listenSpec.tag;\r\n }\r\n req[ /*hash*/'h'] = listenSpec.hashFn();\r\n this.sendRequest(action, req, (message) => {\r\n const payload = message[ /*data*/'d'];\r\n const status = message[ /*status*/'s'];\r\n // print warnings in any case...\r\n PersistentConnection.warnOnListenWarnings_(payload, query);\r\n const currentListenSpec = this.listens.get(pathString) &&\r\n this.listens.get(pathString).get(queryId);\r\n // only trigger actions if the listen hasn't been removed and readded\r\n if (currentListenSpec === listenSpec) {\r\n this.log_('listen response', message);\r\n if (status !== 'ok') {\r\n this.removeListen_(pathString, queryId);\r\n }\r\n if (listenSpec.onComplete) {\r\n listenSpec.onComplete(status, payload);\r\n }\r\n }\r\n });\r\n }\r\n static warnOnListenWarnings_(payload, query) {\r\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const warnings = safeGet(payload, 'w');\r\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\r\n const indexSpec = '\".indexOn\": \"' + query._queryParams.getIndex().toString() + '\"';\r\n const indexPath = query._path.toString();\r\n warn(`Using an unspecified index. Your data will be downloaded and ` +\r\n `filtered on the client. Consider adding ${indexSpec} at ` +\r\n `${indexPath} to your security rules for better performance.`);\r\n }\r\n }\r\n }\r\n refreshAuthToken(token) {\r\n this.authToken_ = token;\r\n this.log_('Auth token refreshed');\r\n if (this.authToken_) {\r\n this.tryAuth();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\r\n //the credential so we dont become authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unauth', {}, () => { });\r\n }\r\n }\r\n this.reduceReconnectDelayIfAdminCredential_(token);\r\n }\r\n reduceReconnectDelayIfAdminCredential_(credential) {\r\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\r\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\r\n const isFirebaseSecret = credential && credential.length === 40;\r\n if (isFirebaseSecret || isAdmin(credential)) {\r\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\r\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n }\r\n }\r\n refreshAppCheckToken(token) {\r\n this.appCheckToken_ = token;\r\n this.log_('App check token refreshed');\r\n if (this.appCheckToken_) {\r\n this.tryAppCheck();\r\n }\r\n else {\r\n //If we're connected we want to let the server know to unauthenticate us.\r\n //If we're not connected, simply delete the credential so we dont become\r\n // authenticated next time we connect.\r\n if (this.connected_) {\r\n this.sendRequest('unappeck', {}, () => { });\r\n }\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\r\n * a auth revoked (the connection is closed).\r\n */\r\n tryAuth() {\r\n if (this.connected_ && this.authToken_) {\r\n const token = this.authToken_;\r\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\r\n const requestData = { cred: token };\r\n if (this.authOverride_ === null) {\r\n requestData['noauth'] = true;\r\n }\r\n else if (typeof this.authOverride_ === 'object') {\r\n requestData['authvar'] = this.authOverride_;\r\n }\r\n this.sendRequest(authMethod, requestData, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (this.authToken_ === token) {\r\n if (status === 'ok') {\r\n this.invalidAuthTokenCount_ = 0;\r\n }\r\n else {\r\n // Triggers reconnect and force refresh for auth token\r\n this.onAuthRevoked_(status, data);\r\n }\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * Attempts to authenticate with the given token. If the authentication\r\n * attempt fails, it's triggered like the token was revoked (the connection is\r\n * closed).\r\n */\r\n tryAppCheck() {\r\n if (this.connected_ && this.appCheckToken_) {\r\n this.sendRequest('appcheck', { 'token': this.appCheckToken_ }, (res) => {\r\n const status = res[ /*status*/'s'];\r\n const data = res[ /*data*/'d'] || 'error';\r\n if (status === 'ok') {\r\n this.invalidAppCheckTokenCount_ = 0;\r\n }\r\n else {\r\n this.onAppCheckRevoked_(status, data);\r\n }\r\n });\r\n }\r\n }\r\n /**\r\n * @inheritDoc\r\n */\r\n unlisten(query, tag) {\r\n const pathString = query._path.toString();\r\n const queryId = query._queryIdentifier;\r\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\r\n assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), 'unlisten() called for non-default but complete query');\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && this.connected_) {\r\n this.sendUnlisten_(pathString, queryId, query._queryObject, tag);\r\n }\r\n }\r\n sendUnlisten_(pathString, queryId, queryObj, tag) {\r\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\r\n const req = { /*path*/ p: pathString };\r\n const action = 'n';\r\n // Only bother sending queryId if it's non-default.\r\n if (tag) {\r\n req['q'] = queryObj;\r\n req['t'] = tag;\r\n }\r\n this.sendRequest(action, req);\r\n }\r\n onDisconnectPut(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('o', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'o',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectMerge(pathString, data, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('om', pathString, data, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'om',\r\n data,\r\n onComplete\r\n });\r\n }\r\n }\r\n onDisconnectCancel(pathString, onComplete) {\r\n this.initConnection_();\r\n if (this.connected_) {\r\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\r\n }\r\n else {\r\n this.onDisconnectRequestQueue_.push({\r\n pathString,\r\n action: 'oc',\r\n data: null,\r\n onComplete\r\n });\r\n }\r\n }\r\n sendOnDisconnect_(action, pathString, data, onComplete) {\r\n const request = { /*path*/ p: pathString, /*data*/ d: data };\r\n this.log_('onDisconnect ' + action, request);\r\n this.sendRequest(action, request, (response) => {\r\n if (onComplete) {\r\n setTimeout(() => {\r\n onComplete(response[ /*status*/'s'], response[ /* data */'d']);\r\n }, Math.floor(0));\r\n }\r\n });\r\n }\r\n put(pathString, data, onComplete, hash) {\r\n this.putInternal('p', pathString, data, onComplete, hash);\r\n }\r\n merge(pathString, data, onComplete, hash) {\r\n this.putInternal('m', pathString, data, onComplete, hash);\r\n }\r\n putInternal(action, pathString, data, onComplete, hash) {\r\n this.initConnection_();\r\n const request = {\r\n /*path*/ p: pathString,\r\n /*data*/ d: data\r\n };\r\n if (hash !== undefined) {\r\n request[ /*hash*/'h'] = hash;\r\n }\r\n // TODO: Only keep track of the most recent put for a given path?\r\n this.outstandingPuts_.push({\r\n action,\r\n request,\r\n onComplete\r\n });\r\n this.outstandingPutCount_++;\r\n const index = this.outstandingPuts_.length - 1;\r\n if (this.connected_) {\r\n this.sendPut_(index);\r\n }\r\n else {\r\n this.log_('Buffering put: ' + pathString);\r\n }\r\n }\r\n sendPut_(index) {\r\n const action = this.outstandingPuts_[index].action;\r\n const request = this.outstandingPuts_[index].request;\r\n const onComplete = this.outstandingPuts_[index].onComplete;\r\n this.outstandingPuts_[index].queued = this.connected_;\r\n this.sendRequest(action, request, (message) => {\r\n this.log_(action + ' response', message);\r\n delete this.outstandingPuts_[index];\r\n this.outstandingPutCount_--;\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n if (onComplete) {\r\n onComplete(message[ /*status*/'s'], message[ /* data */'d']);\r\n }\r\n });\r\n }\r\n reportStats(stats) {\r\n // If we're not connected, we just drop the stats.\r\n if (this.connected_) {\r\n const request = { /*counters*/ c: stats };\r\n this.log_('reportStats', request);\r\n this.sendRequest(/*stats*/ 's', request, result => {\r\n const status = result[ /*status*/'s'];\r\n if (status !== 'ok') {\r\n const errorReason = result[ /* data */'d'];\r\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\r\n }\r\n });\r\n }\r\n }\r\n onDataMessage_(message) {\r\n if ('r' in message) {\r\n // this is a response\r\n this.log_('from server: ' + stringify(message));\r\n const reqNum = message['r'];\r\n const onResponse = this.requestCBHash_[reqNum];\r\n if (onResponse) {\r\n delete this.requestCBHash_[reqNum];\r\n onResponse(message[ /*body*/'b']);\r\n }\r\n }\r\n else if ('error' in message) {\r\n throw 'A server-side error has occurred: ' + message['error'];\r\n }\r\n else if ('a' in message) {\r\n // a and b are action and body, respectively\r\n this.onDataPush_(message['a'], message['b']);\r\n }\r\n }\r\n onDataPush_(action, body) {\r\n this.log_('handleServerMessage', action, body);\r\n if (action === 'd') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge*/ false, body['t']);\r\n }\r\n else if (action === 'm') {\r\n this.onDataUpdate_(body[ /*path*/'p'], body[ /*data*/'d'], \r\n /*isMerge=*/ true, body['t']);\r\n }\r\n else if (action === 'c') {\r\n this.onListenRevoked_(body[ /*path*/'p'], body[ /*query*/'q']);\r\n }\r\n else if (action === 'ac') {\r\n this.onAuthRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'apc') {\r\n this.onAppCheckRevoked_(body[ /*status code*/'s'], body[ /* explanation */'d']);\r\n }\r\n else if (action === 'sd') {\r\n this.onSecurityDebugPacket_(body);\r\n }\r\n else {\r\n error('Unrecognized action received from server: ' +\r\n stringify(action) +\r\n '\\nAre you using the latest client?');\r\n }\r\n }\r\n onReady_(timestamp, sessionId) {\r\n this.log_('connection ready');\r\n this.connected_ = true;\r\n this.lastConnectionEstablishedTime_ = new Date().getTime();\r\n this.handleTimestamp_(timestamp);\r\n this.lastSessionId = sessionId;\r\n if (this.firstConnection_) {\r\n this.sendConnectStats_();\r\n }\r\n this.restoreState_();\r\n this.firstConnection_ = false;\r\n this.onConnectStatus_(true);\r\n }\r\n scheduleConnect_(timeout) {\r\n assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n }\r\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\r\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\r\n this.establishConnectionTimer_ = setTimeout(() => {\r\n this.establishConnectionTimer_ = null;\r\n this.establishConnection_();\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n }, Math.floor(timeout));\r\n }\r\n initConnection_() {\r\n if (!this.realtime_ && this.firstConnection_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n onVisible_(visible) {\r\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\r\n if (visible &&\r\n !this.visible_ &&\r\n this.reconnectDelay_ === this.maxReconnectDelay_) {\r\n this.log_('Window became visible. Reducing delay.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n this.visible_ = visible;\r\n }\r\n onOnline_(online) {\r\n if (online) {\r\n this.log_('Browser went online.');\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n else {\r\n this.log_('Browser went offline. Killing connection.');\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n }\r\n }\r\n onRealtimeDisconnect_() {\r\n this.log_('data client disconnected');\r\n this.connected_ = false;\r\n this.realtime_ = null;\r\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\r\n this.cancelSentTransactions_();\r\n // Clear out the pending requests.\r\n this.requestCBHash_ = {};\r\n if (this.shouldReconnect_()) {\r\n if (!this.visible_) {\r\n this.log_(\"Window isn't visible. Delaying reconnect.\");\r\n this.reconnectDelay_ = this.maxReconnectDelay_;\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n }\r\n else if (this.lastConnectionEstablishedTime_) {\r\n // If we've been connected long enough, reset reconnect delay to minimum.\r\n const timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\r\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n }\r\n this.lastConnectionEstablishedTime_ = null;\r\n }\r\n const timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\r\n let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\r\n reconnectDelay = Math.random() * reconnectDelay;\r\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\r\n this.scheduleConnect_(reconnectDelay);\r\n // Adjust reconnect delay for next time.\r\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\r\n }\r\n this.onConnectStatus_(false);\r\n }\r\n async establishConnection_() {\r\n if (this.shouldReconnect_()) {\r\n this.log_('Making a connection attempt');\r\n this.lastConnectionAttemptTime_ = new Date().getTime();\r\n this.lastConnectionEstablishedTime_ = null;\r\n const onDataMessage = this.onDataMessage_.bind(this);\r\n const onReady = this.onReady_.bind(this);\r\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\r\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\r\n const lastSessionId = this.lastSessionId;\r\n let canceled = false;\r\n let connection = null;\r\n const closeFn = function () {\r\n if (connection) {\r\n connection.close();\r\n }\r\n else {\r\n canceled = true;\r\n onDisconnect();\r\n }\r\n };\r\n const sendRequestFn = function (msg) {\r\n assert(connection, \"sendRequest call when we're not connected not allowed.\");\r\n connection.sendRequest(msg);\r\n };\r\n this.realtime_ = {\r\n close: closeFn,\r\n sendRequest: sendRequestFn\r\n };\r\n const forceRefresh = this.forceTokenRefresh_;\r\n this.forceTokenRefresh_ = false;\r\n try {\r\n // First fetch auth and app check token, and establish connection after\r\n // fetching the token was successful\r\n const [authToken, appCheckToken] = await Promise.all([\r\n this.authTokenProvider_.getToken(forceRefresh),\r\n this.appCheckTokenProvider_.getToken(forceRefresh)\r\n ]);\r\n if (!canceled) {\r\n log('getToken() completed. Creating connection.');\r\n this.authToken_ = authToken && authToken.accessToken;\r\n this.appCheckToken_ = appCheckToken && appCheckToken.token;\r\n connection = new Connection(connId, this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, onDataMessage, onReady, onDisconnect, \r\n /* onKill= */ reason => {\r\n warn(reason + ' (' + this.repoInfo_.toString() + ')');\r\n this.interrupt(SERVER_KILL_INTERRUPT_REASON);\r\n }, lastSessionId);\r\n }\r\n else {\r\n log('getToken() completed but was canceled');\r\n }\r\n }\r\n catch (error) {\r\n this.log_('Failed to get token: ' + error);\r\n if (!canceled) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\r\n // But getToken() may also just have temporarily failed, so we still want to\r\n // continue retrying.\r\n warn(error);\r\n }\r\n closeFn();\r\n }\r\n }\r\n }\r\n }\r\n interrupt(reason) {\r\n log('Interrupting connection for reason: ' + reason);\r\n this.interruptReasons_[reason] = true;\r\n if (this.realtime_) {\r\n this.realtime_.close();\r\n }\r\n else {\r\n if (this.establishConnectionTimer_) {\r\n clearTimeout(this.establishConnectionTimer_);\r\n this.establishConnectionTimer_ = null;\r\n }\r\n if (this.connected_) {\r\n this.onRealtimeDisconnect_();\r\n }\r\n }\r\n }\r\n resume(reason) {\r\n log('Resuming connection for reason: ' + reason);\r\n delete this.interruptReasons_[reason];\r\n if (isEmpty(this.interruptReasons_)) {\r\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\r\n if (!this.realtime_) {\r\n this.scheduleConnect_(0);\r\n }\r\n }\r\n }\r\n handleTimestamp_(timestamp) {\r\n const delta = timestamp - new Date().getTime();\r\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\r\n }\r\n cancelSentTransactions_() {\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n const put = this.outstandingPuts_[i];\r\n if (put && /*hash*/ 'h' in put.request && put.queued) {\r\n if (put.onComplete) {\r\n put.onComplete('disconnect');\r\n }\r\n delete this.outstandingPuts_[i];\r\n this.outstandingPutCount_--;\r\n }\r\n }\r\n // Clean up array occasionally.\r\n if (this.outstandingPutCount_ === 0) {\r\n this.outstandingPuts_ = [];\r\n }\r\n }\r\n onListenRevoked_(pathString, query) {\r\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\r\n let queryId;\r\n if (!query) {\r\n queryId = 'default';\r\n }\r\n else {\r\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\r\n }\r\n const listen = this.removeListen_(pathString, queryId);\r\n if (listen && listen.onComplete) {\r\n listen.onComplete('permission_denied');\r\n }\r\n }\r\n removeListen_(pathString, queryId) {\r\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\r\n let listen;\r\n if (this.listens.has(normalizedPathString)) {\r\n const map = this.listens.get(normalizedPathString);\r\n listen = map.get(queryId);\r\n map.delete(queryId);\r\n if (map.size === 0) {\r\n this.listens.delete(normalizedPathString);\r\n }\r\n }\r\n else {\r\n // all listens for this path has already been removed\r\n listen = undefined;\r\n }\r\n return listen;\r\n }\r\n onAuthRevoked_(statusCode, explanation) {\r\n log('Auth token revoked: ' + statusCode + '/' + explanation);\r\n this.authToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n this.realtime_.close();\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAuthTokenCount_++;\r\n if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n // Set a long reconnect delay because recovery is unlikely\r\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\r\n // Notify the auth token provider that the token is invalid, which will log\r\n // a warning\r\n this.authTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onAppCheckRevoked_(statusCode, explanation) {\r\n log('App check token revoked: ' + statusCode + '/' + explanation);\r\n this.appCheckToken_ = null;\r\n this.forceTokenRefresh_ = true;\r\n // Note: We don't close the connection as the developer may not have\r\n // enforcement enabled. The backend closes connections with enforcements.\r\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\r\n // We'll wait a couple times before logging the warning / increasing the\r\n // retry period since oauth tokens will report as \"invalid\" if they're\r\n // just expired. Plus there may be transient issues that resolve themselves.\r\n this.invalidAppCheckTokenCount_++;\r\n if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {\r\n this.appCheckTokenProvider_.notifyForInvalidToken();\r\n }\r\n }\r\n }\r\n onSecurityDebugPacket_(body) {\r\n if (this.securityDebugCallback_) {\r\n this.securityDebugCallback_(body);\r\n }\r\n else {\r\n if ('msg' in body) {\r\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\r\n }\r\n }\r\n }\r\n restoreState_() {\r\n //Re-authenticate ourselves if we have a credential stored.\r\n this.tryAuth();\r\n this.tryAppCheck();\r\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\r\n // make sure to send listens before puts.\r\n for (const queries of this.listens.values()) {\r\n for (const listenSpec of queries.values()) {\r\n this.sendListen_(listenSpec);\r\n }\r\n }\r\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\r\n if (this.outstandingPuts_[i]) {\r\n this.sendPut_(i);\r\n }\r\n }\r\n while (this.onDisconnectRequestQueue_.length) {\r\n const request = this.onDisconnectRequestQueue_.shift();\r\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\r\n }\r\n for (let i = 0; i < this.outstandingGets_.length; i++) {\r\n if (this.outstandingGets_[i]) {\r\n this.sendGet_(i);\r\n }\r\n }\r\n }\r\n /**\r\n * Sends client stats for first connection\r\n */\r\n sendConnectStats_() {\r\n const stats = {};\r\n let clientName = 'js';\r\n if (isNodeSdk()) {\r\n if (this.repoInfo_.nodeAdmin) {\r\n clientName = 'admin_node';\r\n }\r\n else {\r\n clientName = 'node';\r\n }\r\n }\r\n stats['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 1;\r\n if (isMobileCordova()) {\r\n stats['framework.cordova'] = 1;\r\n }\r\n else if (isReactNative()) {\r\n stats['framework.reactnative'] = 1;\r\n }\r\n this.reportStats(stats);\r\n }\r\n shouldReconnect_() {\r\n const online = OnlineMonitor.getInstance().currentlyOnline();\r\n return isEmpty(this.interruptReasons_) && online;\r\n }\r\n}\r\nPersistentConnection.nextPersistentConnectionId_ = 0;\r\n/**\r\n * Counter for number of connections created. Mainly used for tagging in the logs\r\n */\r\nPersistentConnection.nextConnectionId_ = 0;\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass NamedNode {\r\n constructor(name, node) {\r\n this.name = name;\r\n this.node = node;\r\n }\r\n static Wrap(name, node) {\r\n return new NamedNode(name, node);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Index {\r\n /**\r\n * @returns A standalone comparison function for\r\n * this index\r\n */\r\n getCompare() {\r\n return this.compare.bind(this);\r\n }\r\n /**\r\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\r\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\r\n *\r\n *\r\n * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode\r\n */\r\n indexedValueChanged(oldNode, newNode) {\r\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\r\n const newWrapped = new NamedNode(MIN_NAME, newNode);\r\n return this.compare(oldWrapped, newWrapped) !== 0;\r\n }\r\n /**\r\n * @returns a node wrapper that will sort equal to or less than\r\n * any other node wrapper, using this index\r\n */\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __EMPTY_NODE;\r\nclass KeyIndex extends Index {\r\n static get __EMPTY_NODE() {\r\n return __EMPTY_NODE;\r\n }\r\n static set __EMPTY_NODE(val) {\r\n __EMPTY_NODE = val;\r\n }\r\n compare(a, b) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n isDefinedOn(node) {\r\n // We could probably return true here (since every node has a key), but it's never called\r\n // so just leaving unimplemented for now.\r\n throw assertionError('KeyIndex.isDefinedOn not expected to be called.');\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return false; // The key for a node never changes.\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // TODO: This should really be created once and cached in a static property, but\r\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\r\n return new NamedNode(MAX_NAME, __EMPTY_NODE);\r\n }\r\n makePost(indexValue, name) {\r\n assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\r\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\r\n return new NamedNode(indexValue, __EMPTY_NODE);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.key';\r\n }\r\n}\r\nconst KEY_INDEX = new KeyIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An iterator over an LLRBNode.\r\n */\r\nclass SortedMapIterator {\r\n /**\r\n * @param node - Node to iterate.\r\n * @param isReverse_ - Whether or not to iterate in reverse\r\n */\r\n constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {\r\n this.isReverse_ = isReverse_;\r\n this.resultGenerator_ = resultGenerator_;\r\n this.nodeStack_ = [];\r\n let cmp = 1;\r\n while (!node.isEmpty()) {\r\n node = node;\r\n cmp = startKey ? comparator(node.key, startKey) : 1;\r\n // flip the comparison if we're going in reverse\r\n if (isReverse_) {\r\n cmp *= -1;\r\n }\r\n if (cmp < 0) {\r\n // This node is less than our start key. ignore it\r\n if (this.isReverse_) {\r\n node = node.left;\r\n }\r\n else {\r\n node = node.right;\r\n }\r\n }\r\n else if (cmp === 0) {\r\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\r\n this.nodeStack_.push(node);\r\n break;\r\n }\r\n else {\r\n // This node is greater than our start key, add it to the stack and move to the next one\r\n this.nodeStack_.push(node);\r\n if (this.isReverse_) {\r\n node = node.right;\r\n }\r\n else {\r\n node = node.left;\r\n }\r\n }\r\n }\r\n }\r\n getNext() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n let node = this.nodeStack_.pop();\r\n let result;\r\n if (this.resultGenerator_) {\r\n result = this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n result = { key: node.key, value: node.value };\r\n }\r\n if (this.isReverse_) {\r\n node = node.left;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.right;\r\n }\r\n }\r\n else {\r\n node = node.right;\r\n while (!node.isEmpty()) {\r\n this.nodeStack_.push(node);\r\n node = node.left;\r\n }\r\n }\r\n return result;\r\n }\r\n hasNext() {\r\n return this.nodeStack_.length > 0;\r\n }\r\n peek() {\r\n if (this.nodeStack_.length === 0) {\r\n return null;\r\n }\r\n const node = this.nodeStack_[this.nodeStack_.length - 1];\r\n if (this.resultGenerator_) {\r\n return this.resultGenerator_(node.key, node.value);\r\n }\r\n else {\r\n return { key: node.key, value: node.value };\r\n }\r\n }\r\n}\r\n/**\r\n * Represents a node in a Left-leaning Red-Black tree.\r\n */\r\nclass LLRBNode {\r\n /**\r\n * @param key - Key associated with this node.\r\n * @param value - Value associated with this node.\r\n * @param color - Whether this node is red.\r\n * @param left - Left child.\r\n * @param right - Right child.\r\n */\r\n constructor(key, value, color, left, right) {\r\n this.key = key;\r\n this.value = value;\r\n this.color = color != null ? color : LLRBNode.RED;\r\n this.left =\r\n left != null ? left : SortedMap.EMPTY_NODE;\r\n this.right =\r\n right != null ? right : SortedMap.EMPTY_NODE;\r\n }\r\n /**\r\n * Returns a copy of the current node, optionally replacing pieces of it.\r\n *\r\n * @param key - New key for the node, or null.\r\n * @param value - New value for the node, or null.\r\n * @param color - New color for the node, or null.\r\n * @param left - New left child for the node, or null.\r\n * @param right - New right child for the node, or null.\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return this.left.count() + 1 + this.right.count();\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return (this.left.inorderTraversal(action) ||\r\n !!action(this.key, this.value) ||\r\n this.right.inorderTraversal(action));\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return (this.right.reverseTraversal(action) ||\r\n action(this.key, this.value) ||\r\n this.left.reverseTraversal(action));\r\n }\r\n /**\r\n * @returns The minimum node in the tree.\r\n */\r\n min_() {\r\n if (this.left.isEmpty()) {\r\n return this;\r\n }\r\n else {\r\n return this.left.min_();\r\n }\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n minKey() {\r\n return this.min_().key;\r\n }\r\n /**\r\n * @returns The maximum key in the tree.\r\n */\r\n maxKey() {\r\n if (this.right.isEmpty()) {\r\n return this.key;\r\n }\r\n else {\r\n return this.right.maxKey();\r\n }\r\n }\r\n /**\r\n * @param key - Key to insert.\r\n * @param value - Value to insert.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the key/value added.\r\n */\r\n insert(key, value, comparator) {\r\n let n = this;\r\n const cmp = comparator(key, n.key);\r\n if (cmp < 0) {\r\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\r\n }\r\n else if (cmp === 0) {\r\n n = n.copy(null, value, null, null, null);\r\n }\r\n else {\r\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns New tree, with the minimum key removed.\r\n */\r\n removeMin_() {\r\n if (this.left.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n let n = this;\r\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.removeMin_(), null);\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @param key - The key of the item to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with the specified item removed.\r\n */\r\n remove(key, comparator) {\r\n let n, smallest;\r\n n = this;\r\n if (comparator(key, n.key) < 0) {\r\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\r\n n = n.moveRedLeft_();\r\n }\r\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\r\n }\r\n else {\r\n if (n.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\r\n n = n.moveRedRight_();\r\n }\r\n if (comparator(key, n.key) === 0) {\r\n if (n.right.isEmpty()) {\r\n return SortedMap.EMPTY_NODE;\r\n }\r\n else {\r\n smallest = n.right.min_();\r\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\r\n }\r\n }\r\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\r\n }\r\n return n.fixUp_();\r\n }\r\n /**\r\n * @returns Whether this is a RED node.\r\n */\r\n isRed_() {\r\n return this.color;\r\n }\r\n /**\r\n * @returns New tree after performing any needed rotations.\r\n */\r\n fixUp_() {\r\n let n = this;\r\n if (n.right.isRed_() && !n.left.isRed_()) {\r\n n = n.rotateLeft_();\r\n }\r\n if (n.left.isRed_() && n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n }\r\n if (n.left.isRed_() && n.right.isRed_()) {\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedLeft.\r\n */\r\n moveRedLeft_() {\r\n let n = this.colorFlip_();\r\n if (n.right.left.isRed_()) {\r\n n = n.copy(null, null, null, null, n.right.rotateRight_());\r\n n = n.rotateLeft_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after moveRedRight.\r\n */\r\n moveRedRight_() {\r\n let n = this.colorFlip_();\r\n if (n.left.left.isRed_()) {\r\n n = n.rotateRight_();\r\n n = n.colorFlip_();\r\n }\r\n return n;\r\n }\r\n /**\r\n * @returns New tree, after rotateLeft.\r\n */\r\n rotateLeft_() {\r\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\r\n return this.right.copy(null, null, this.color, nl, null);\r\n }\r\n /**\r\n * @returns New tree, after rotateRight.\r\n */\r\n rotateRight_() {\r\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\r\n return this.left.copy(null, null, this.color, null, nr);\r\n }\r\n /**\r\n * @returns Newt ree, after colorFlip.\r\n */\r\n colorFlip_() {\r\n const left = this.left.copy(null, null, !this.left.color, null, null);\r\n const right = this.right.copy(null, null, !this.right.color, null, null);\r\n return this.copy(null, null, !this.color, left, right);\r\n }\r\n /**\r\n * For testing.\r\n *\r\n * @returns True if all is well.\r\n */\r\n checkMaxDepth_() {\r\n const blackDepth = this.check_();\r\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\r\n }\r\n check_() {\r\n if (this.isRed_() && this.left.isRed_()) {\r\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\r\n }\r\n if (this.right.isRed_()) {\r\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\r\n }\r\n const blackDepth = this.left.check_();\r\n if (blackDepth !== this.right.check_()) {\r\n throw new Error('Black depths differ');\r\n }\r\n else {\r\n return blackDepth + (this.isRed_() ? 0 : 1);\r\n }\r\n }\r\n}\r\nLLRBNode.RED = true;\r\nLLRBNode.BLACK = false;\r\n/**\r\n * Represents an empty node (a leaf node in the Red-Black Tree).\r\n */\r\nclass LLRBEmptyNode {\r\n /**\r\n * Returns a copy of the current node.\r\n *\r\n * @returns The node copy.\r\n */\r\n copy(key, value, color, left, right) {\r\n return this;\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key/value added.\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item added.\r\n */\r\n insert(key, value, comparator) {\r\n return new LLRBNode(key, value, null);\r\n }\r\n /**\r\n * Returns a copy of the tree, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @param comparator - Comparator.\r\n * @returns New tree, with item removed.\r\n */\r\n remove(key, comparator) {\r\n return this;\r\n }\r\n /**\r\n * @returns The total number of nodes in the tree.\r\n */\r\n count() {\r\n return 0;\r\n }\r\n /**\r\n * @returns True if the tree is empty.\r\n */\r\n isEmpty() {\r\n return true;\r\n }\r\n /**\r\n * Traverses the tree in key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n inorderTraversal(action) {\r\n return false;\r\n }\r\n /**\r\n * Traverses the tree in reverse key order and calls the specified action function\r\n * for each node.\r\n *\r\n * @param action - Callback function to be called for each\r\n * node. If it returns true, traversal is aborted.\r\n * @returns True if traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return false;\r\n }\r\n minKey() {\r\n return null;\r\n }\r\n maxKey() {\r\n return null;\r\n }\r\n check_() {\r\n return 0;\r\n }\r\n /**\r\n * @returns Whether this node is red.\r\n */\r\n isRed_() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\r\n * tree.\r\n */\r\nclass SortedMap {\r\n /**\r\n * @param comparator_ - Key comparator.\r\n * @param root_ - Optional root node for the map.\r\n */\r\n constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {\r\n this.comparator_ = comparator_;\r\n this.root_ = root_;\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key/value added or replaced.\r\n * (TODO: We should perhaps rename this method to 'put')\r\n *\r\n * @param key - Key to be added.\r\n * @param value - Value to be added.\r\n * @returns New map, with item added.\r\n */\r\n insert(key, value) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .insert(key, value, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns a copy of the map, with the specified key removed.\r\n *\r\n * @param key - The key to remove.\r\n * @returns New map, with item removed.\r\n */\r\n remove(key) {\r\n return new SortedMap(this.comparator_, this.root_\r\n .remove(key, this.comparator_)\r\n .copy(null, null, LLRBNode.BLACK, null, null));\r\n }\r\n /**\r\n * Returns the value of the node with the given key, or null.\r\n *\r\n * @param key - The key to look up.\r\n * @returns The value of the node with the given key, or null if the\r\n * key doesn't exist.\r\n */\r\n get(key) {\r\n let cmp;\r\n let node = this.root_;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n return node.value;\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n node = node.right;\r\n }\r\n }\r\n return null;\r\n }\r\n /**\r\n * Returns the key of the item *before* the specified key, or null if key is the first item.\r\n * @param key - The key to find the predecessor of\r\n * @returns The predecessor key.\r\n */\r\n getPredecessorKey(key) {\r\n let cmp, node = this.root_, rightParent = null;\r\n while (!node.isEmpty()) {\r\n cmp = this.comparator_(key, node.key);\r\n if (cmp === 0) {\r\n if (!node.left.isEmpty()) {\r\n node = node.left;\r\n while (!node.right.isEmpty()) {\r\n node = node.right;\r\n }\r\n return node.key;\r\n }\r\n else if (rightParent) {\r\n return rightParent.key;\r\n }\r\n else {\r\n return null; // first item.\r\n }\r\n }\r\n else if (cmp < 0) {\r\n node = node.left;\r\n }\r\n else if (cmp > 0) {\r\n rightParent = node;\r\n node = node.right;\r\n }\r\n }\r\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\r\n }\r\n /**\r\n * @returns True if the map is empty.\r\n */\r\n isEmpty() {\r\n return this.root_.isEmpty();\r\n }\r\n /**\r\n * @returns The total number of nodes in the map.\r\n */\r\n count() {\r\n return this.root_.count();\r\n }\r\n /**\r\n * @returns The minimum key in the map.\r\n */\r\n minKey() {\r\n return this.root_.minKey();\r\n }\r\n /**\r\n * @returns The maximum key in the map.\r\n */\r\n maxKey() {\r\n return this.root_.maxKey();\r\n }\r\n /**\r\n * Traverses the map in key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns The first truthy value returned by action, or the last falsey\r\n * value returned by action\r\n */\r\n inorderTraversal(action) {\r\n return this.root_.inorderTraversal(action);\r\n }\r\n /**\r\n * Traverses the map in reverse key order and calls the specified action function\r\n * for each key/value pair.\r\n *\r\n * @param action - Callback function to be called\r\n * for each key/value pair. If action returns true, traversal is aborted.\r\n * @returns True if the traversal was aborted.\r\n */\r\n reverseTraversal(action) {\r\n return this.root_.reverseTraversal(action);\r\n }\r\n /**\r\n * Returns an iterator over the SortedMap.\r\n * @returns The iterator.\r\n */\r\n getIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\r\n }\r\n getIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\r\n }\r\n getReverseIteratorFrom(key, resultGenerator) {\r\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\r\n }\r\n getReverseIterator(resultGenerator) {\r\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\r\n }\r\n}\r\n/**\r\n * Always use the same empty node, to reduce memory.\r\n */\r\nSortedMap.EMPTY_NODE = new LLRBEmptyNode();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction NAME_ONLY_COMPARATOR(left, right) {\r\n return nameCompare(left.name, right.name);\r\n}\r\nfunction NAME_COMPARATOR(left, right) {\r\n return nameCompare(left, right);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet MAX_NODE$2;\r\nfunction setMaxNode$1(val) {\r\n MAX_NODE$2 = val;\r\n}\r\nconst priorityHashText = function (priority) {\r\n if (typeof priority === 'number') {\r\n return 'number:' + doubleToIEEE754String(priority);\r\n }\r\n else {\r\n return 'string:' + priority;\r\n }\r\n};\r\n/**\r\n * Validates that a priority snapshot Node is valid.\r\n */\r\nconst validatePriorityNode = function (priorityNode) {\r\n if (priorityNode.isLeafNode()) {\r\n const val = priorityNode.val();\r\n assert(typeof val === 'string' ||\r\n typeof val === 'number' ||\r\n (typeof val === 'object' && contains(val, '.sv')), 'Priority must be a string or number.');\r\n }\r\n else {\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), 'priority of unexpected type.');\r\n }\r\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\r\n assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet __childrenNodeConstructor;\r\n/**\r\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\r\n * implements Node and stores the value of the node (a string,\r\n * number, or boolean) accessible via getValue().\r\n */\r\nclass LeafNode {\r\n /**\r\n * @param value_ - The value to store in this leaf node. The object type is\r\n * possible in the event of a deferred value\r\n * @param priorityNode_ - The priority of this node.\r\n */\r\n constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n this.value_ = value_;\r\n this.priorityNode_ = priorityNode_;\r\n this.lazyHash_ = null;\r\n assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n static set __childrenNodeConstructor(val) {\r\n __childrenNodeConstructor = val;\r\n }\r\n static get __childrenNodeConstructor() {\r\n return __childrenNodeConstructor;\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return true;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n return new LeafNode(this.value_, newPriorityNode);\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n if (pathIsEmpty(path)) {\r\n return this;\r\n }\r\n else if (pathGetFront(path) === '.priority') {\r\n return this.priorityNode_;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\r\n }\r\n }\r\n hasChild() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode) {\r\n return null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else if (newChildNode.isEmpty() && childName !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else if (newChildNode.isEmpty() && front !== '.priority') {\r\n return this;\r\n }\r\n else {\r\n assert(front !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return 0;\r\n }\r\n /** @inheritDoc */\r\n forEachChild(index, action) {\r\n return false;\r\n }\r\n val(exportFormat) {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n return {\r\n '.value': this.getValue(),\r\n '.priority': this.getPriority().val()\r\n };\r\n }\r\n else {\r\n return this.getValue();\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.priorityNode_.isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.priorityNode_.val()) +\r\n ':';\r\n }\r\n const type = typeof this.value_;\r\n toHash += type + ':';\r\n if (type === 'number') {\r\n toHash += doubleToIEEE754String(this.value_);\r\n }\r\n else {\r\n toHash += this.value_;\r\n }\r\n this.lazyHash_ = sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /**\r\n * Returns the value of the leaf node.\r\n * @returns The value of the node.\r\n */\r\n getValue() {\r\n return this.value_;\r\n }\r\n compareTo(other) {\r\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\r\n return 1;\r\n }\r\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\r\n return -1;\r\n }\r\n else {\r\n assert(other.isLeafNode(), 'Unknown node type');\r\n return this.compareToLeafNode_(other);\r\n }\r\n }\r\n /**\r\n * Comparison specifically for two leaf nodes\r\n */\r\n compareToLeafNode_(otherLeaf) {\r\n const otherLeafType = typeof otherLeaf.value_;\r\n const thisLeafType = typeof this.value_;\r\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\r\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\r\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\r\n assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\r\n if (otherIndex === thisIndex) {\r\n // Same type, compare values\r\n if (thisLeafType === 'object') {\r\n // Deferred value nodes are all equal, but we should also never get to this point...\r\n return 0;\r\n }\r\n else {\r\n // Note that this works because true > false, all others are number or string comparisons\r\n if (this.value_ < otherLeaf.value_) {\r\n return -1;\r\n }\r\n else if (this.value_ === otherLeaf.value_) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n }\r\n else {\r\n return thisIndex - otherIndex;\r\n }\r\n }\r\n withIndex() {\r\n return this;\r\n }\r\n isIndexed() {\r\n return true;\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n const otherLeaf = other;\r\n return (this.value_ === otherLeaf.value_ &&\r\n this.priorityNode_.equals(otherLeaf.priorityNode_));\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n}\r\n/**\r\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\r\n * the same type, the comparison falls back to their value\r\n */\r\nLeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet nodeFromJSON$1;\r\nlet MAX_NODE$1;\r\nfunction setNodeFromJSON(val) {\r\n nodeFromJSON$1 = val;\r\n}\r\nfunction setMaxNode(val) {\r\n MAX_NODE$1 = val;\r\n}\r\nclass PriorityIndex extends Index {\r\n compare(a, b) {\r\n const aPriority = a.node.getPriority();\r\n const bPriority = b.node.getPriority();\r\n const indexCmp = aPriority.compareTo(bPriority);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return !node.getPriority().isEmpty();\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.getPriority().equals(newNode.getPriority());\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE$1));\r\n }\r\n makePost(indexValue, name) {\r\n const priorityNode = nodeFromJSON$1(indexValue);\r\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.priority';\r\n }\r\n}\r\nconst PRIORITY_INDEX = new PriorityIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst LOG_2 = Math.log(2);\r\nclass Base12Num {\r\n constructor(length) {\r\n const logBase2 = (num) => \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n parseInt((Math.log(num) / LOG_2), 10);\r\n const bitMask = (bits) => parseInt(Array(bits + 1).join('1'), 2);\r\n this.count = logBase2(length + 1);\r\n this.current_ = this.count - 1;\r\n const mask = bitMask(this.count);\r\n this.bits_ = (length + 1) & mask;\r\n }\r\n nextBitIsOne() {\r\n //noinspection JSBitwiseOperatorUsage\r\n const result = !(this.bits_ & (0x1 << this.current_));\r\n this.current_--;\r\n return result;\r\n }\r\n}\r\n/**\r\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\r\n * function\r\n *\r\n * Uses the algorithm described in the paper linked here:\r\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\r\n *\r\n * @param childList - Unsorted list of children\r\n * @param cmp - The comparison method to be used\r\n * @param keyFn - An optional function to extract K from a node wrapper, if K's\r\n * type is not NamedNode\r\n * @param mapSortFn - An optional override for comparator used by the generated sorted map\r\n */\r\nconst buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\r\n childList.sort(cmp);\r\n const buildBalancedTree = function (low, high) {\r\n const length = high - low;\r\n let namedNode;\r\n let key;\r\n if (length === 0) {\r\n return null;\r\n }\r\n else if (length === 1) {\r\n namedNode = childList[low];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);\r\n }\r\n else {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n const middle = parseInt((length / 2), 10) + low;\r\n const left = buildBalancedTree(low, middle);\r\n const right = buildBalancedTree(middle + 1, high);\r\n namedNode = childList[middle];\r\n key = keyFn ? keyFn(namedNode) : namedNode;\r\n return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);\r\n }\r\n };\r\n const buildFrom12Array = function (base12) {\r\n let node = null;\r\n let root = null;\r\n let index = childList.length;\r\n const buildPennant = function (chunkSize, color) {\r\n const low = index - chunkSize;\r\n const high = index;\r\n index -= chunkSize;\r\n const childTree = buildBalancedTree(low + 1, high);\r\n const namedNode = childList[low];\r\n const key = keyFn ? keyFn(namedNode) : namedNode;\r\n attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));\r\n };\r\n const attachPennant = function (pennant) {\r\n if (node) {\r\n node.left = pennant;\r\n node = pennant;\r\n }\r\n else {\r\n root = pennant;\r\n node = pennant;\r\n }\r\n };\r\n for (let i = 0; i < base12.count; ++i) {\r\n const isOne = base12.nextBitIsOne();\r\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\r\n const chunkSize = Math.pow(2, base12.count - (i + 1));\r\n if (isOne) {\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n }\r\n else {\r\n // current == 2\r\n buildPennant(chunkSize, LLRBNode.BLACK);\r\n buildPennant(chunkSize, LLRBNode.RED);\r\n }\r\n }\r\n return root;\r\n };\r\n const base12 = new Base12Num(childList.length);\r\n const root = buildFrom12Array(base12);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return new SortedMap(mapSortFn || cmp, root);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet _defaultIndexMap;\r\nconst fallbackObject = {};\r\nclass IndexMap {\r\n constructor(indexes_, indexSet_) {\r\n this.indexes_ = indexes_;\r\n this.indexSet_ = indexSet_;\r\n }\r\n /**\r\n * The default IndexMap for nodes without a priority\r\n */\r\n static get Default() {\r\n assert(fallbackObject && PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\r\n _defaultIndexMap =\r\n _defaultIndexMap ||\r\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PRIORITY_INDEX });\r\n return _defaultIndexMap;\r\n }\r\n get(indexKey) {\r\n const sortedMap = safeGet(this.indexes_, indexKey);\r\n if (!sortedMap) {\r\n throw new Error('No index defined for ' + indexKey);\r\n }\r\n if (sortedMap instanceof SortedMap) {\r\n return sortedMap;\r\n }\r\n else {\r\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\r\n // regular child map\r\n return null;\r\n }\r\n }\r\n hasIndex(indexDefinition) {\r\n return contains(this.indexSet_, indexDefinition.toString());\r\n }\r\n addIndex(indexDefinition, existingChildren) {\r\n assert(indexDefinition !== KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\r\n const childList = [];\r\n let sawIndexedValue = false;\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n sawIndexedValue =\r\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\r\n childList.push(next);\r\n next = iter.getNext();\r\n }\r\n let newIndex;\r\n if (sawIndexedValue) {\r\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\r\n }\r\n else {\r\n newIndex = fallbackObject;\r\n }\r\n const indexName = indexDefinition.toString();\r\n const newIndexSet = Object.assign({}, this.indexSet_);\r\n newIndexSet[indexName] = indexDefinition;\r\n const newIndexes = Object.assign({}, this.indexes_);\r\n newIndexes[indexName] = newIndex;\r\n return new IndexMap(newIndexes, newIndexSet);\r\n }\r\n /**\r\n * Ensure that this node is properly tracked in any indexes that we're maintaining\r\n */\r\n addToIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {\r\n const index = safeGet(this.indexSet_, indexName);\r\n assert(index, 'Missing index implementation for ' + indexName);\r\n if (indexedChildren === fallbackObject) {\r\n // Check to see if we need to index everything\r\n if (index.isDefinedOn(namedNode.node)) {\r\n // We need to build this index\r\n const childList = [];\r\n const iter = existingChildren.getIterator(NamedNode.Wrap);\r\n let next = iter.getNext();\r\n while (next) {\r\n if (next.name !== namedNode.name) {\r\n childList.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n childList.push(namedNode);\r\n return buildChildSet(childList, index.getCompare());\r\n }\r\n else {\r\n // No change, this remains a fallback\r\n return fallbackObject;\r\n }\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n let newChildren = indexedChildren;\r\n if (existingSnap) {\r\n newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n return newChildren.insert(namedNode, namedNode.node);\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n /**\r\n * Create a new IndexMap instance with the given value removed\r\n */\r\n removeFromIndexes(namedNode, existingChildren) {\r\n const newIndexes = map(this.indexes_, (indexedChildren) => {\r\n if (indexedChildren === fallbackObject) {\r\n // This is the fallback. Just return it, nothing to do in this case\r\n return indexedChildren;\r\n }\r\n else {\r\n const existingSnap = existingChildren.get(namedNode.name);\r\n if (existingSnap) {\r\n return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));\r\n }\r\n else {\r\n // No record of this child\r\n return indexedChildren;\r\n }\r\n }\r\n });\r\n return new IndexMap(newIndexes, this.indexSet_);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\r\nlet EMPTY_NODE;\r\n/**\r\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\r\n * (i.e. nodes with children). It implements Node and stores the\r\n * list of children in the children property, sorted by child name.\r\n */\r\nclass ChildrenNode {\r\n /**\r\n * @param children_ - List of children of this node..\r\n * @param priorityNode_ - The priority of this node (as a snapshot node).\r\n */\r\n constructor(children_, priorityNode_, indexMap_) {\r\n this.children_ = children_;\r\n this.priorityNode_ = priorityNode_;\r\n this.indexMap_ = indexMap_;\r\n this.lazyHash_ = null;\r\n /**\r\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\r\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\r\n * class instead of an empty ChildrenNode.\r\n */\r\n if (this.priorityNode_) {\r\n validatePriorityNode(this.priorityNode_);\r\n }\r\n if (this.children_.isEmpty()) {\r\n assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\r\n }\r\n }\r\n static get EMPTY_NODE() {\r\n return (EMPTY_NODE ||\r\n (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default)));\r\n }\r\n /** @inheritDoc */\r\n isLeafNode() {\r\n return false;\r\n }\r\n /** @inheritDoc */\r\n getPriority() {\r\n return this.priorityNode_ || EMPTY_NODE;\r\n }\r\n /** @inheritDoc */\r\n updatePriority(newPriorityNode) {\r\n if (this.children_.isEmpty()) {\r\n // Don't allow priorities on empty nodes\r\n return this;\r\n }\r\n else {\r\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\r\n }\r\n }\r\n /** @inheritDoc */\r\n getImmediateChild(childName) {\r\n // Hack to treat priority as a regular child\r\n if (childName === '.priority') {\r\n return this.getPriority();\r\n }\r\n else {\r\n const child = this.children_.get(childName);\r\n return child === null ? EMPTY_NODE : child;\r\n }\r\n }\r\n /** @inheritDoc */\r\n getChild(path) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return this;\r\n }\r\n return this.getImmediateChild(front).getChild(pathPopFront(path));\r\n }\r\n /** @inheritDoc */\r\n hasChild(childName) {\r\n return this.children_.get(childName) !== null;\r\n }\r\n /** @inheritDoc */\r\n updateImmediateChild(childName, newChildNode) {\r\n assert(newChildNode, 'We should always be passing snapshot nodes');\r\n if (childName === '.priority') {\r\n return this.updatePriority(newChildNode);\r\n }\r\n else {\r\n const namedNode = new NamedNode(childName, newChildNode);\r\n let newChildren, newIndexMap;\r\n if (newChildNode.isEmpty()) {\r\n newChildren = this.children_.remove(childName);\r\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\r\n }\r\n else {\r\n newChildren = this.children_.insert(childName, newChildNode);\r\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\r\n }\r\n const newPriority = newChildren.isEmpty()\r\n ? EMPTY_NODE\r\n : this.priorityNode_;\r\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\r\n }\r\n }\r\n /** @inheritDoc */\r\n updateChild(path, newChildNode) {\r\n const front = pathGetFront(path);\r\n if (front === null) {\r\n return newChildNode;\r\n }\r\n else {\r\n assert(pathGetFront(path) !== '.priority' || pathGetLength(path) === 1, '.priority must be the last token in a path');\r\n const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);\r\n return this.updateImmediateChild(front, newImmediateChild);\r\n }\r\n }\r\n /** @inheritDoc */\r\n isEmpty() {\r\n return this.children_.isEmpty();\r\n }\r\n /** @inheritDoc */\r\n numChildren() {\r\n return this.children_.count();\r\n }\r\n /** @inheritDoc */\r\n val(exportFormat) {\r\n if (this.isEmpty()) {\r\n return null;\r\n }\r\n const obj = {};\r\n let numKeys = 0, maxKey = 0, allIntegerKeys = true;\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n obj[key] = childNode.val(exportFormat);\r\n numKeys++;\r\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\r\n maxKey = Math.max(maxKey, Number(key));\r\n }\r\n else {\r\n allIntegerKeys = false;\r\n }\r\n });\r\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\r\n // convert to array.\r\n const array = [];\r\n // eslint-disable-next-line guard-for-in\r\n for (const key in obj) {\r\n array[key] = obj[key];\r\n }\r\n return array;\r\n }\r\n else {\r\n if (exportFormat && !this.getPriority().isEmpty()) {\r\n obj['.priority'] = this.getPriority().val();\r\n }\r\n return obj;\r\n }\r\n }\r\n /** @inheritDoc */\r\n hash() {\r\n if (this.lazyHash_ === null) {\r\n let toHash = '';\r\n if (!this.getPriority().isEmpty()) {\r\n toHash +=\r\n 'priority:' +\r\n priorityHashText(this.getPriority().val()) +\r\n ':';\r\n }\r\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n const childHash = childNode.hash();\r\n if (childHash !== '') {\r\n toHash += ':' + key + ':' + childHash;\r\n }\r\n });\r\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\r\n }\r\n return this.lazyHash_;\r\n }\r\n /** @inheritDoc */\r\n getPredecessorChildName(childName, childNode, index) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));\r\n return predecessor ? predecessor.name : null;\r\n }\r\n else {\r\n return this.children_.getPredecessorKey(childName);\r\n }\r\n }\r\n getFirstChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const minKey = idx.minKey();\r\n return minKey && minKey.name;\r\n }\r\n else {\r\n return this.children_.minKey();\r\n }\r\n }\r\n getFirstChild(indexDefinition) {\r\n const minKey = this.getFirstChildName(indexDefinition);\r\n if (minKey) {\r\n return new NamedNode(minKey, this.children_.get(minKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n /**\r\n * Given an index, return the key name of the largest value we have, according to that index\r\n */\r\n getLastChildName(indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n const maxKey = idx.maxKey();\r\n return maxKey && maxKey.name;\r\n }\r\n else {\r\n return this.children_.maxKey();\r\n }\r\n }\r\n getLastChild(indexDefinition) {\r\n const maxKey = this.getLastChildName(indexDefinition);\r\n if (maxKey) {\r\n return new NamedNode(maxKey, this.children_.get(maxKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n forEachChild(index, action) {\r\n const idx = this.resolveIndex_(index);\r\n if (idx) {\r\n return idx.inorderTraversal(wrappedNode => {\r\n return action(wrappedNode.name, wrappedNode.node);\r\n });\r\n }\r\n else {\r\n return this.children_.inorderTraversal(action);\r\n }\r\n }\r\n getIterator(indexDefinition) {\r\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\r\n }\r\n getIteratorFrom(startPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getIteratorFrom(startPost, key => key);\r\n }\r\n else {\r\n const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n getReverseIterator(indexDefinition) {\r\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\r\n }\r\n getReverseIteratorFrom(endPost, indexDefinition) {\r\n const idx = this.resolveIndex_(indexDefinition);\r\n if (idx) {\r\n return idx.getReverseIteratorFrom(endPost, key => {\r\n return key;\r\n });\r\n }\r\n else {\r\n const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);\r\n let next = iterator.peek();\r\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\r\n iterator.getNext();\r\n next = iterator.peek();\r\n }\r\n return iterator;\r\n }\r\n }\r\n compareTo(other) {\r\n if (this.isEmpty()) {\r\n if (other.isEmpty()) {\r\n return 0;\r\n }\r\n else {\r\n return -1;\r\n }\r\n }\r\n else if (other.isLeafNode() || other.isEmpty()) {\r\n return 1;\r\n }\r\n else if (other === MAX_NODE) {\r\n return -1;\r\n }\r\n else {\r\n // Must be another node with children.\r\n return 0;\r\n }\r\n }\r\n withIndex(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX ||\r\n this.indexMap_.hasIndex(indexDefinition)) {\r\n return this;\r\n }\r\n else {\r\n const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\r\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\r\n }\r\n }\r\n isIndexed(index) {\r\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\r\n }\r\n equals(other) {\r\n if (other === this) {\r\n return true;\r\n }\r\n else if (other.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n const otherChildrenNode = other;\r\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\r\n return false;\r\n }\r\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\r\n const thisIter = this.getIterator(PRIORITY_INDEX);\r\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\r\n let thisCurrent = thisIter.getNext();\r\n let otherCurrent = otherIter.getNext();\r\n while (thisCurrent && otherCurrent) {\r\n if (thisCurrent.name !== otherCurrent.name ||\r\n !thisCurrent.node.equals(otherCurrent.node)) {\r\n return false;\r\n }\r\n thisCurrent = thisIter.getNext();\r\n otherCurrent = otherIter.getNext();\r\n }\r\n return thisCurrent === null && otherCurrent === null;\r\n }\r\n else {\r\n return false;\r\n }\r\n }\r\n }\r\n /**\r\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\r\n * instead.\r\n *\r\n */\r\n resolveIndex_(indexDefinition) {\r\n if (indexDefinition === KEY_INDEX) {\r\n return null;\r\n }\r\n else {\r\n return this.indexMap_.get(indexDefinition.toString());\r\n }\r\n }\r\n}\r\nChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\r\nclass MaxNode extends ChildrenNode {\r\n constructor() {\r\n super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);\r\n }\r\n compareTo(other) {\r\n if (other === this) {\r\n return 0;\r\n }\r\n else {\r\n return 1;\r\n }\r\n }\r\n equals(other) {\r\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\r\n return other === this;\r\n }\r\n getPriority() {\r\n return this;\r\n }\r\n getImmediateChild(childName) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n isEmpty() {\r\n return false;\r\n }\r\n}\r\n/**\r\n * Marker that will sort higher than any other snapshot.\r\n */\r\nconst MAX_NODE = new MaxNode();\r\nObject.defineProperties(NamedNode, {\r\n MIN: {\r\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\r\n },\r\n MAX: {\r\n value: new NamedNode(MAX_NAME, MAX_NODE)\r\n }\r\n});\r\n/**\r\n * Reference Extensions\r\n */\r\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\r\nLeafNode.__childrenNodeConstructor = ChildrenNode;\r\nsetMaxNode$1(MAX_NODE);\r\nsetMaxNode(MAX_NODE);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst USE_HINZE = true;\r\n/**\r\n * Constructs a snapshot node representing the passed JSON and returns it.\r\n * @param json - JSON to create a node for.\r\n * @param priority - Optional priority to use. This will be ignored if the\r\n * passed JSON contains a .priority property.\r\n */\r\nfunction nodeFromJSON(json, priority = null) {\r\n if (json === null) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n if (typeof json === 'object' && '.priority' in json) {\r\n priority = json['.priority'];\r\n }\r\n assert(priority === null ||\r\n typeof priority === 'string' ||\r\n typeof priority === 'number' ||\r\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\r\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\r\n json = json['.value'];\r\n }\r\n // Valid leaf nodes include non-objects or server-value wrapper objects\r\n if (typeof json !== 'object' || '.sv' in json) {\r\n const jsonLeaf = json;\r\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\r\n }\r\n if (!(json instanceof Array) && USE_HINZE) {\r\n const children = [];\r\n let childrenHavePriority = false;\r\n const hinzeJsonObj = json;\r\n each(hinzeJsonObj, (key, child) => {\r\n if (key.substring(0, 1) !== '.') {\r\n // Ignore metadata nodes\r\n const childNode = nodeFromJSON(child);\r\n if (!childNode.isEmpty()) {\r\n childrenHavePriority =\r\n childrenHavePriority || !childNode.getPriority().isEmpty();\r\n children.push(new NamedNode(key, childNode));\r\n }\r\n }\r\n });\r\n if (children.length === 0) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, namedNode => namedNode.name, NAME_COMPARATOR);\r\n if (childrenHavePriority) {\r\n const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ '.priority': sortedChildSet }, { '.priority': PRIORITY_INDEX }));\r\n }\r\n else {\r\n return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);\r\n }\r\n }\r\n else {\r\n let node = ChildrenNode.EMPTY_NODE;\r\n each(json, (key, childData) => {\r\n if (contains(json, key)) {\r\n if (key.substring(0, 1) !== '.') {\r\n // ignore metadata nodes.\r\n const childNode = nodeFromJSON(childData);\r\n if (childNode.isLeafNode() || !childNode.isEmpty()) {\r\n node = node.updateImmediateChild(key, childNode);\r\n }\r\n }\r\n }\r\n });\r\n return node.updatePriority(nodeFromJSON(priority));\r\n }\r\n}\r\nsetNodeFromJSON(nodeFromJSON);\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PathIndex extends Index {\r\n constructor(indexPath_) {\r\n super();\r\n this.indexPath_ = indexPath_;\r\n assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\r\n }\r\n extractChild(snap) {\r\n return snap.getChild(this.indexPath_);\r\n }\r\n isDefinedOn(node) {\r\n return !node.getChild(this.indexPath_).isEmpty();\r\n }\r\n compare(a, b) {\r\n const aChild = this.extractChild(a.node);\r\n const bChild = this.extractChild(b.node);\r\n const indexCmp = aChild.compareTo(bChild);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\r\n return new NamedNode(name, node);\r\n }\r\n maxPost() {\r\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\r\n return new NamedNode(MAX_NAME, node);\r\n }\r\n toString() {\r\n return pathSlice(this.indexPath_, 0).join('/');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ValueIndex extends Index {\r\n compare(a, b) {\r\n const indexCmp = a.node.compareTo(b.node);\r\n if (indexCmp === 0) {\r\n return nameCompare(a.name, b.name);\r\n }\r\n else {\r\n return indexCmp;\r\n }\r\n }\r\n isDefinedOn(node) {\r\n return true;\r\n }\r\n indexedValueChanged(oldNode, newNode) {\r\n return !oldNode.equals(newNode);\r\n }\r\n minPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MIN;\r\n }\r\n maxPost() {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return NamedNode.MAX;\r\n }\r\n makePost(indexValue, name) {\r\n const valueNode = nodeFromJSON(indexValue);\r\n return new NamedNode(name, valueNode);\r\n }\r\n /**\r\n * @returns String representation for inclusion in a query spec\r\n */\r\n toString() {\r\n return '.value';\r\n }\r\n}\r\nconst VALUE_INDEX = new ValueIndex();\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Modeled after base64 web-safe chars, but ordered by ASCII.\r\nconst PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\r\nconst MIN_PUSH_CHAR = '-';\r\nconst MAX_PUSH_CHAR = 'z';\r\nconst MAX_KEY_LEN = 786;\r\n/**\r\n * Fancy ID generator that creates 20-character string identifiers with the\r\n * following properties:\r\n *\r\n * 1. They're based on timestamp so that they sort *after* any existing ids.\r\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\r\n * collide with other clients' IDs.\r\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\r\n * that will sort properly).\r\n * 4. They're monotonically increasing. Even if you generate more than one in\r\n * the same timestamp, the latter ones will sort after the former ones. We do\r\n * this by using the previous random bits but \"incrementing\" them by 1 (only\r\n * in the case of a timestamp collision).\r\n */\r\nconst nextPushId = (function () {\r\n // Timestamp of last push, used to prevent local collisions if you push twice\r\n // in one ms.\r\n let lastPushTime = 0;\r\n // We generate 72-bits of randomness which get turned into 12 characters and\r\n // appended to the timestamp to prevent collisions with other clients. We\r\n // store the last characters we generated because in the event of a collision,\r\n // we'll use those same characters except \"incremented\" by one.\r\n const lastRandChars = [];\r\n return function (now) {\r\n const duplicateTime = now === lastPushTime;\r\n lastPushTime = now;\r\n let i;\r\n const timeStampChars = new Array(8);\r\n for (i = 7; i >= 0; i--) {\r\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\r\n // NOTE: Can't use << here because javascript will convert to int and lose\r\n // the upper bits.\r\n now = Math.floor(now / 64);\r\n }\r\n assert(now === 0, 'Cannot push at time == 0');\r\n let id = timeStampChars.join('');\r\n if (!duplicateTime) {\r\n for (i = 0; i < 12; i++) {\r\n lastRandChars[i] = Math.floor(Math.random() * 64);\r\n }\r\n }\r\n else {\r\n // If the timestamp hasn't changed since last push, use the same random\r\n // number, except incremented by 1.\r\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\r\n lastRandChars[i] = 0;\r\n }\r\n lastRandChars[i]++;\r\n }\r\n for (i = 0; i < 12; i++) {\r\n id += PUSH_CHARS.charAt(lastRandChars[i]);\r\n }\r\n assert(id.length === 20, 'nextPushId: Length should be 20.');\r\n return id;\r\n };\r\n})();\r\nconst successor = function (key) {\r\n if (key === '' + INTEGER_32_MAX) {\r\n // See https://firebase.google.com/docs/database/web/lists-of-data#data-order\r\n return MIN_PUSH_CHAR;\r\n }\r\n const keyAsInt = tryParseInt(key);\r\n if (keyAsInt != null) {\r\n return '' + (keyAsInt + 1);\r\n }\r\n const next = new Array(key.length);\r\n for (let i = 0; i < next.length; i++) {\r\n next[i] = key.charAt(i);\r\n }\r\n if (next.length < MAX_KEY_LEN) {\r\n next.push(MIN_PUSH_CHAR);\r\n return next.join('');\r\n }\r\n let i = next.length - 1;\r\n while (i >= 0 && next[i] === MAX_PUSH_CHAR) {\r\n i--;\r\n }\r\n // `successor` was called on the largest possible key, so return the\r\n // MAX_NAME, which sorts larger than all keys.\r\n if (i === -1) {\r\n return MAX_NAME;\r\n }\r\n const source = next[i];\r\n const sourcePlusOne = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(source) + 1);\r\n next[i] = sourcePlusOne;\r\n return next.slice(0, i + 1).join('');\r\n};\r\n// `key` is assumed to be non-empty.\r\nconst predecessor = function (key) {\r\n if (key === '' + INTEGER_32_MIN) {\r\n return MIN_NAME;\r\n }\r\n const keyAsInt = tryParseInt(key);\r\n if (keyAsInt != null) {\r\n return '' + (keyAsInt - 1);\r\n }\r\n const next = new Array(key.length);\r\n for (let i = 0; i < next.length; i++) {\r\n next[i] = key.charAt(i);\r\n }\r\n // If `key` ends in `MIN_PUSH_CHAR`, the largest key lexicographically\r\n // smaller than `key`, is `key[0:key.length - 1]`. The next key smaller\r\n // than that, `predecessor(predecessor(key))`, is\r\n //\r\n // `key[0:key.length - 2] + (key[key.length - 1] - 1) + \\\r\n // { MAX_PUSH_CHAR repeated MAX_KEY_LEN - (key.length - 1) times }\r\n //\r\n // analogous to increment/decrement for base-10 integers.\r\n //\r\n // This works because lexigographic comparison works character-by-character,\r\n // using length as a tie-breaker if one key is a prefix of the other.\r\n if (next[next.length - 1] === MIN_PUSH_CHAR) {\r\n if (next.length === 1) {\r\n // See https://firebase.google.com/docs/database/web/lists-of-data#orderbykey\r\n return '' + INTEGER_32_MAX;\r\n }\r\n delete next[next.length - 1];\r\n return next.join('');\r\n }\r\n // Replace the last character with it's immediate predecessor, and\r\n // fill the suffix of the key with MAX_PUSH_CHAR. This is the\r\n // lexicographically largest possible key smaller than `key`.\r\n next[next.length - 1] = PUSH_CHARS.charAt(PUSH_CHARS.indexOf(next[next.length - 1]) - 1);\r\n return next.join('') + MAX_PUSH_CHAR.repeat(MAX_KEY_LEN - next.length);\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction changeValue(snapshotNode) {\r\n return { type: \"value\" /* VALUE */, snapshotNode };\r\n}\r\nfunction changeChildAdded(childName, snapshotNode) {\r\n return { type: \"child_added\" /* CHILD_ADDED */, snapshotNode, childName };\r\n}\r\nfunction changeChildRemoved(childName, snapshotNode) {\r\n return { type: \"child_removed\" /* CHILD_REMOVED */, snapshotNode, childName };\r\n}\r\nfunction changeChildChanged(childName, snapshotNode, oldSnap) {\r\n return {\r\n type: \"child_changed\" /* CHILD_CHANGED */,\r\n snapshotNode,\r\n childName,\r\n oldSnap\r\n };\r\n}\r\nfunction changeChildMoved(childName, snapshotNode) {\r\n return { type: \"child_moved\" /* CHILD_MOVED */, snapshotNode, childName };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\r\n */\r\nclass IndexedFilter {\r\n constructor(index_) {\r\n this.index_ = index_;\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\r\n const oldChild = snap.getImmediateChild(key);\r\n // Check if anything actually changed.\r\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\r\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\r\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\r\n // to avoid treating these cases as \"nothing changed.\"\r\n if (oldChild.isEmpty() === newChild.isEmpty()) {\r\n // Nothing changed.\r\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\r\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\r\n return snap;\r\n }\r\n }\r\n if (optChangeAccumulator != null) {\r\n if (newChild.isEmpty()) {\r\n if (snap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));\r\n }\r\n else {\r\n assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\r\n }\r\n }\r\n else if (oldChild.isEmpty()) {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));\r\n }\r\n }\r\n if (snap.isLeafNode() && newChild.isEmpty()) {\r\n return snap;\r\n }\r\n else {\r\n // Make sure the node is indexed\r\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (optChangeAccumulator != null) {\r\n if (!oldSnap.isLeafNode()) {\r\n oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!newSnap.hasChild(key)) {\r\n optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));\r\n }\r\n });\r\n }\r\n if (!newSnap.isLeafNode()) {\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (oldSnap.hasChild(key)) {\r\n const oldChild = oldSnap.getImmediateChild(key);\r\n if (!oldChild.equals(childNode)) {\r\n optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));\r\n }\r\n }\r\n else {\r\n optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));\r\n }\r\n });\r\n }\r\n }\r\n return newSnap.withIndex(this.index_);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n if (oldSnap.isEmpty()) {\r\n return ChildrenNode.EMPTY_NODE;\r\n }\r\n else {\r\n return oldSnap.updatePriority(newPriority);\r\n }\r\n }\r\n filtersNodes() {\r\n return false;\r\n }\r\n getIndexedFilter() {\r\n return this;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\r\n */\r\nclass RangedFilter {\r\n constructor(params) {\r\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\r\n this.index_ = params.getIndex();\r\n this.startPost_ = RangedFilter.getStartPost_(params);\r\n this.endPost_ = RangedFilter.getEndPost_(params);\r\n }\r\n getStartPost() {\r\n return this.startPost_;\r\n }\r\n getEndPost() {\r\n return this.endPost_;\r\n }\r\n matches(node) {\r\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\r\n this.index_.compare(node, this.getEndPost()) <= 0);\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n if (newSnap.isLeafNode()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n newSnap = ChildrenNode.EMPTY_NODE;\r\n }\r\n let filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n const self = this;\r\n newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n if (!self.matches(new NamedNode(key, childNode))) {\r\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\r\n }\r\n });\r\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.indexedFilter_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n static getStartPost_(params) {\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\r\n }\r\n else {\r\n return params.getIndex().minPost();\r\n }\r\n }\r\n static getEndPost_(params) {\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\r\n }\r\n else {\r\n return params.getIndex().maxPost();\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\r\n */\r\nclass LimitedFilter {\r\n constructor(params) {\r\n this.rangedFilter_ = new RangedFilter(params);\r\n this.index_ = params.getIndex();\r\n this.limit_ = params.getLimit();\r\n this.reverse_ = !params.isViewFromLeft();\r\n }\r\n updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {\r\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n if (snap.getImmediateChild(key).equals(newChild)) {\r\n // No change\r\n return snap;\r\n }\r\n else if (snap.numChildren() < this.limit_) {\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\r\n }\r\n else {\r\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\r\n }\r\n }\r\n updateFullNode(oldSnap, newSnap, optChangeAccumulator) {\r\n let filtered;\r\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\r\n // Make sure we have a children node with the correct index, not a leaf node;\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n }\r\n else {\r\n if (this.limit_ * 2 < newSnap.numChildren() &&\r\n newSnap.isIndexed(this.index_)) {\r\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\r\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\r\n // anchor to the startPost, endPost, or last element as appropriate\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\r\n }\r\n else {\r\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\r\n }\r\n let count = 0;\r\n while (iterator.hasNext() && count < this.limit_) {\r\n const next = iterator.getNext();\r\n let inRange;\r\n if (this.reverse_) {\r\n inRange =\r\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\r\n }\r\n else {\r\n inRange =\r\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\r\n }\r\n if (inRange) {\r\n filtered = filtered.updateImmediateChild(next.name, next.node);\r\n count++;\r\n }\r\n else {\r\n // if we have reached the end post, we cannot keep adding elemments\r\n break;\r\n }\r\n }\r\n }\r\n else {\r\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\r\n filtered = newSnap.withIndex(this.index_);\r\n // Don't support priorities on queries\r\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\r\n let startPost;\r\n let endPost;\r\n let cmp;\r\n let iterator;\r\n if (this.reverse_) {\r\n iterator = filtered.getReverseIterator(this.index_);\r\n startPost = this.rangedFilter_.getEndPost();\r\n endPost = this.rangedFilter_.getStartPost();\r\n const indexCompare = this.index_.getCompare();\r\n cmp = (a, b) => indexCompare(b, a);\r\n }\r\n else {\r\n iterator = filtered.getIterator(this.index_);\r\n startPost = this.rangedFilter_.getStartPost();\r\n endPost = this.rangedFilter_.getEndPost();\r\n cmp = this.index_.getCompare();\r\n }\r\n let count = 0;\r\n let foundStartPost = false;\r\n while (iterator.hasNext()) {\r\n const next = iterator.getNext();\r\n if (!foundStartPost && cmp(startPost, next) <= 0) {\r\n // start adding\r\n foundStartPost = true;\r\n }\r\n const inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\r\n if (inRange) {\r\n count++;\r\n }\r\n else {\r\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n }\r\n }\r\n }\r\n return this.rangedFilter_\r\n .getIndexedFilter()\r\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\r\n }\r\n updatePriority(oldSnap, newPriority) {\r\n // Don't support priorities on queries\r\n return oldSnap;\r\n }\r\n filtersNodes() {\r\n return true;\r\n }\r\n getIndexedFilter() {\r\n return this.rangedFilter_.getIndexedFilter();\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {\r\n // TODO: rename all cache stuff etc to general snap terminology\r\n let cmp;\r\n if (this.reverse_) {\r\n const indexCmp = this.index_.getCompare();\r\n cmp = (a, b) => indexCmp(b, a);\r\n }\r\n else {\r\n cmp = this.index_.getCompare();\r\n }\r\n const oldEventCache = snap;\r\n assert(oldEventCache.numChildren() === this.limit_, '');\r\n const newChildNamedNode = new NamedNode(childKey, childSnap);\r\n const windowBoundary = this.reverse_\r\n ? oldEventCache.getFirstChild(this.index_)\r\n : oldEventCache.getLastChild(this.index_);\r\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\r\n if (oldEventCache.hasChild(childKey)) {\r\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\r\n let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\r\n while (nextChild != null &&\r\n (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {\r\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\r\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\r\n // the limited filter...\r\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\r\n }\r\n const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\r\n const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\r\n if (remainsInWindow) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));\r\n }\r\n return oldEventCache.updateImmediateChild(childKey, childSnap);\r\n }\r\n else {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));\r\n }\r\n const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\r\n const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\r\n if (nextChildInRange) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));\r\n }\r\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\r\n }\r\n else {\r\n return newEventCache;\r\n }\r\n }\r\n }\r\n else if (childSnap.isEmpty()) {\r\n // we're deleting a node, but it was not in the window, so ignore it\r\n return snap;\r\n }\r\n else if (inRange) {\r\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\r\n if (changeAccumulator != null) {\r\n changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));\r\n changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));\r\n }\r\n return oldEventCache\r\n .updateImmediateChild(childKey, childSnap)\r\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n else {\r\n return snap;\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\r\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\r\n * user-facing API level, so it is not done here.\r\n *\r\n * @internal\r\n */\r\nclass QueryParams {\r\n constructor() {\r\n this.limitSet_ = false;\r\n this.startSet_ = false;\r\n this.startNameSet_ = false;\r\n this.startAfterSet_ = false;\r\n this.endSet_ = false;\r\n this.endNameSet_ = false;\r\n this.endBeforeSet_ = false;\r\n this.limit_ = 0;\r\n this.viewFrom_ = '';\r\n this.indexStartValue_ = null;\r\n this.indexStartName_ = '';\r\n this.indexEndValue_ = null;\r\n this.indexEndName_ = '';\r\n this.index_ = PRIORITY_INDEX;\r\n }\r\n hasStart() {\r\n return this.startSet_;\r\n }\r\n hasStartAfter() {\r\n return this.startAfterSet_;\r\n }\r\n hasEndBefore() {\r\n return this.endBeforeSet_;\r\n }\r\n /**\r\n * @returns True if it would return from left.\r\n */\r\n isViewFromLeft() {\r\n if (this.viewFrom_ === '') {\r\n // limit(), rather than limitToFirst or limitToLast was called.\r\n // This means that only one of startSet_ and endSet_ is true. Use them\r\n // to calculate which side of the view to anchor to. If neither is set,\r\n // anchor to the end.\r\n return this.startSet_;\r\n }\r\n else {\r\n return this.viewFrom_ === \"l\" /* VIEW_FROM_LEFT */;\r\n }\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true\r\n */\r\n getIndexStartValue() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n return this.indexStartValue_;\r\n }\r\n /**\r\n * Only valid to call if hasStart() returns true.\r\n * Returns the starting key name for the range defined by these query parameters\r\n */\r\n getIndexStartName() {\r\n assert(this.startSet_, 'Only valid if start has been set');\r\n if (this.startNameSet_) {\r\n return this.indexStartName_;\r\n }\r\n else {\r\n return MIN_NAME;\r\n }\r\n }\r\n hasEnd() {\r\n return this.endSet_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n */\r\n getIndexEndValue() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n return this.indexEndValue_;\r\n }\r\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * Returns the end key name for the range defined by these query parameters\r\n */\r\n getIndexEndName() {\r\n assert(this.endSet_, 'Only valid if end has been set');\r\n if (this.endNameSet_) {\r\n return this.indexEndName_;\r\n }\r\n else {\r\n return MAX_NAME;\r\n }\r\n }\r\n hasLimit() {\r\n return this.limitSet_;\r\n }\r\n /**\r\n * @returns True if a limit has been set and it has been explicitly anchored\r\n */\r\n hasAnchoredLimit() {\r\n return this.limitSet_ && this.viewFrom_ !== '';\r\n }\r\n /**\r\n * Only valid to call if hasLimit() returns true\r\n */\r\n getLimit() {\r\n assert(this.limitSet_, 'Only valid if limit has been set');\r\n return this.limit_;\r\n }\r\n getIndex() {\r\n return this.index_;\r\n }\r\n loadsAllData() {\r\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\r\n }\r\n isDefault() {\r\n return this.loadsAllData() && this.index_ === PRIORITY_INDEX;\r\n }\r\n copy() {\r\n const copy = new QueryParams();\r\n copy.limitSet_ = this.limitSet_;\r\n copy.limit_ = this.limit_;\r\n copy.startSet_ = this.startSet_;\r\n copy.indexStartValue_ = this.indexStartValue_;\r\n copy.startNameSet_ = this.startNameSet_;\r\n copy.indexStartName_ = this.indexStartName_;\r\n copy.endSet_ = this.endSet_;\r\n copy.indexEndValue_ = this.indexEndValue_;\r\n copy.endNameSet_ = this.endNameSet_;\r\n copy.indexEndName_ = this.indexEndName_;\r\n copy.index_ = this.index_;\r\n copy.viewFrom_ = this.viewFrom_;\r\n return copy;\r\n }\r\n}\r\nfunction queryParamsGetNodeFilter(queryParams) {\r\n if (queryParams.loadsAllData()) {\r\n return new IndexedFilter(queryParams.getIndex());\r\n }\r\n else if (queryParams.hasLimit()) {\r\n return new LimitedFilter(queryParams);\r\n }\r\n else {\r\n return new RangedFilter(queryParams);\r\n }\r\n}\r\nfunction queryParamsLimitToFirst(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"l\" /* VIEW_FROM_LEFT */;\r\n return newParams;\r\n}\r\nfunction queryParamsLimitToLast(queryParams, newLimit) {\r\n const newParams = queryParams.copy();\r\n newParams.limitSet_ = true;\r\n newParams.limit_ = newLimit;\r\n newParams.viewFrom_ = \"r\" /* VIEW_FROM_RIGHT */;\r\n return newParams;\r\n}\r\nfunction queryParamsStartAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.startSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexStartValue_ = indexValue;\r\n if (key != null) {\r\n newParams.startNameSet_ = true;\r\n newParams.indexStartName_ = key;\r\n }\r\n else {\r\n newParams.startNameSet_ = false;\r\n newParams.indexStartName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsStartAfter(queryParams, indexValue, key) {\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX) {\r\n if (typeof indexValue === 'string') {\r\n indexValue = successor(indexValue);\r\n }\r\n params = queryParamsStartAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n let childKey;\r\n if (key == null) {\r\n childKey = MAX_NAME;\r\n }\r\n else {\r\n childKey = successor(key);\r\n }\r\n params = queryParamsStartAt(queryParams, indexValue, childKey);\r\n }\r\n params.startAfterSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsEndAt(queryParams, indexValue, key) {\r\n const newParams = queryParams.copy();\r\n newParams.endSet_ = true;\r\n if (indexValue === undefined) {\r\n indexValue = null;\r\n }\r\n newParams.indexEndValue_ = indexValue;\r\n if (key !== undefined) {\r\n newParams.endNameSet_ = true;\r\n newParams.indexEndName_ = key;\r\n }\r\n else {\r\n newParams.endNameSet_ = false;\r\n newParams.indexEndName_ = '';\r\n }\r\n return newParams;\r\n}\r\nfunction queryParamsEndBefore(queryParams, indexValue, key) {\r\n let childKey;\r\n let params;\r\n if (queryParams.index_ === KEY_INDEX) {\r\n if (typeof indexValue === 'string') {\r\n indexValue = predecessor(indexValue);\r\n }\r\n params = queryParamsEndAt(queryParams, indexValue, key);\r\n }\r\n else {\r\n if (key == null) {\r\n childKey = MIN_NAME;\r\n }\r\n else {\r\n childKey = predecessor(key);\r\n }\r\n params = queryParamsEndAt(queryParams, indexValue, childKey);\r\n }\r\n params.endBeforeSet_ = true;\r\n return params;\r\n}\r\nfunction queryParamsOrderBy(queryParams, index) {\r\n const newParams = queryParams.copy();\r\n newParams.index_ = index;\r\n return newParams;\r\n}\r\n/**\r\n * Returns a set of REST query string parameters representing this query.\r\n *\r\n * @returns query string parameters\r\n */\r\nfunction queryParamsToRestQueryStringParameters(queryParams) {\r\n const qs = {};\r\n if (queryParams.isDefault()) {\r\n return qs;\r\n }\r\n let orderBy;\r\n if (queryParams.index_ === PRIORITY_INDEX) {\r\n orderBy = \"$priority\" /* PRIORITY_INDEX */;\r\n }\r\n else if (queryParams.index_ === VALUE_INDEX) {\r\n orderBy = \"$value\" /* VALUE_INDEX */;\r\n }\r\n else if (queryParams.index_ === KEY_INDEX) {\r\n orderBy = \"$key\" /* KEY_INDEX */;\r\n }\r\n else {\r\n assert(queryParams.index_ instanceof PathIndex, 'Unrecognized index type!');\r\n orderBy = queryParams.index_.toString();\r\n }\r\n qs[\"orderBy\" /* ORDER_BY */] = stringify(orderBy);\r\n if (queryParams.startSet_) {\r\n qs[\"startAt\" /* START_AT */] = stringify(queryParams.indexStartValue_);\r\n if (queryParams.startNameSet_) {\r\n qs[\"startAt\" /* START_AT */] +=\r\n ',' + stringify(queryParams.indexStartName_);\r\n }\r\n }\r\n if (queryParams.endSet_) {\r\n qs[\"endAt\" /* END_AT */] = stringify(queryParams.indexEndValue_);\r\n if (queryParams.endNameSet_) {\r\n qs[\"endAt\" /* END_AT */] +=\r\n ',' + stringify(queryParams.indexEndName_);\r\n }\r\n }\r\n if (queryParams.limitSet_) {\r\n if (queryParams.isViewFromLeft()) {\r\n qs[\"limitToFirst\" /* LIMIT_TO_FIRST */] = queryParams.limit_;\r\n }\r\n else {\r\n qs[\"limitToLast\" /* LIMIT_TO_LAST */] = queryParams.limit_;\r\n }\r\n }\r\n return qs;\r\n}\r\nfunction queryParamsGetQueryObject(queryParams) {\r\n const obj = {};\r\n if (queryParams.startSet_) {\r\n obj[\"sp\" /* INDEX_START_VALUE */] =\r\n queryParams.indexStartValue_;\r\n if (queryParams.startNameSet_) {\r\n obj[\"sn\" /* INDEX_START_NAME */] =\r\n queryParams.indexStartName_;\r\n }\r\n }\r\n if (queryParams.endSet_) {\r\n obj[\"ep\" /* INDEX_END_VALUE */] = queryParams.indexEndValue_;\r\n if (queryParams.endNameSet_) {\r\n obj[\"en\" /* INDEX_END_NAME */] = queryParams.indexEndName_;\r\n }\r\n }\r\n if (queryParams.limitSet_) {\r\n obj[\"l\" /* LIMIT */] = queryParams.limit_;\r\n let viewFrom = queryParams.viewFrom_;\r\n if (viewFrom === '') {\r\n if (queryParams.isViewFromLeft()) {\r\n viewFrom = \"l\" /* VIEW_FROM_LEFT */;\r\n }\r\n else {\r\n viewFrom = \"r\" /* VIEW_FROM_RIGHT */;\r\n }\r\n }\r\n obj[\"vf\" /* VIEW_FROM */] = viewFrom;\r\n }\r\n // For now, priority index is the default, so we only specify if it's some other index\r\n if (queryParams.index_ !== PRIORITY_INDEX) {\r\n obj[\"i\" /* INDEX */] = queryParams.index_.toString();\r\n }\r\n return obj;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of ServerActions that communicates with the server via REST requests.\r\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\r\n * persistent connection (using WebSockets or long-polling)\r\n */\r\nclass ReadonlyRestClient extends ServerActions {\r\n /**\r\n * @param repoInfo_ - Data about the namespace we are connecting to\r\n * @param onDataUpdate_ - A callback for new data from the server\r\n */\r\n constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {\r\n super();\r\n this.repoInfo_ = repoInfo_;\r\n this.onDataUpdate_ = onDataUpdate_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckTokenProvider_ = appCheckTokenProvider_;\r\n /** @private {function(...[*])} */\r\n this.log_ = logWrapper('p:rest:');\r\n /**\r\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\r\n * that's been removed. :-/\r\n */\r\n this.listens_ = {};\r\n }\r\n reportStats(stats) {\r\n throw new Error('Method not implemented.');\r\n }\r\n static getListenId_(query, tag) {\r\n if (tag !== undefined) {\r\n return 'tag$' + tag;\r\n }\r\n else {\r\n assert(query._queryParams.isDefault(), \"should have a tag if it's not a default query.\");\r\n return query._path.toString();\r\n }\r\n }\r\n /** @inheritDoc */\r\n listen(query, currentHashFn, tag, onComplete) {\r\n const pathString = query._path.toString();\r\n this.log_('Listen called for ' + pathString + ' ' + query._queryIdentifier);\r\n // Mark this listener so we can tell if it's removed.\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n const thisListen = {};\r\n this.listens_[listenId] = thisListen;\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\r\n }\r\n if (safeGet(this.listens_, listenId) === thisListen) {\r\n let status;\r\n if (!error) {\r\n status = 'ok';\r\n }\r\n else if (error === 401) {\r\n status = 'permission_denied';\r\n }\r\n else {\r\n status = 'rest_error:' + error;\r\n }\r\n onComplete(status, null);\r\n }\r\n });\r\n }\r\n /** @inheritDoc */\r\n unlisten(query, tag) {\r\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\r\n delete this.listens_[listenId];\r\n }\r\n get(query) {\r\n const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);\r\n const pathString = query._path.toString();\r\n const deferred = new Deferred();\r\n this.restRequest_(pathString + '.json', queryStringParameters, (error, result) => {\r\n let data = result;\r\n if (error === 404) {\r\n data = null;\r\n error = null;\r\n }\r\n if (error === null) {\r\n this.onDataUpdate_(pathString, data, \r\n /*isMerge=*/ false, \r\n /*tag=*/ null);\r\n deferred.resolve(data);\r\n }\r\n else {\r\n deferred.reject(new Error(data));\r\n }\r\n });\r\n return deferred.promise;\r\n }\r\n /** @inheritDoc */\r\n refreshAuthToken(token) {\r\n // no-op since we just always call getToken.\r\n }\r\n /**\r\n * Performs a REST request to the given path, with the provided query string parameters,\r\n * and any auth credentials we have.\r\n */\r\n restRequest_(pathString, queryStringParameters = {}, callback) {\r\n queryStringParameters['format'] = 'export';\r\n return Promise.all([\r\n this.authTokenProvider_.getToken(/*forceRefresh=*/ false),\r\n this.appCheckTokenProvider_.getToken(/*forceRefresh=*/ false)\r\n ]).then(([authToken, appCheckToken]) => {\r\n if (authToken && authToken.accessToken) {\r\n queryStringParameters['auth'] = authToken.accessToken;\r\n }\r\n if (appCheckToken && appCheckToken.token) {\r\n queryStringParameters['ac'] = appCheckToken.token;\r\n }\r\n const url = (this.repoInfo_.secure ? 'https://' : 'http://') +\r\n this.repoInfo_.host +\r\n pathString +\r\n '?' +\r\n 'ns=' +\r\n this.repoInfo_.namespace +\r\n querystring(queryStringParameters);\r\n this.log_('Sending REST request for ' + url);\r\n const xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange = () => {\r\n if (callback && xhr.readyState === 4) {\r\n this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\r\n let res = null;\r\n if (xhr.status >= 200 && xhr.status < 300) {\r\n try {\r\n res = jsonEval(xhr.responseText);\r\n }\r\n catch (e) {\r\n warn('Failed to parse JSON response for ' +\r\n url +\r\n ': ' +\r\n xhr.responseText);\r\n }\r\n callback(null, res);\r\n }\r\n else {\r\n // 401 and 404 are expected.\r\n if (xhr.status !== 401 && xhr.status !== 404) {\r\n warn('Got unsuccessful REST response for ' +\r\n url +\r\n ' Status: ' +\r\n xhr.status);\r\n }\r\n callback(xhr.status);\r\n }\r\n callback = null;\r\n }\r\n };\r\n xhr.open('GET', url, /*asynchronous=*/ true);\r\n xhr.send();\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\r\n */\r\nclass SnapshotHolder {\r\n constructor() {\r\n this.rootNode_ = ChildrenNode.EMPTY_NODE;\r\n }\r\n getNode(path) {\r\n return this.rootNode_.getChild(path);\r\n }\r\n updateSnapshot(path, newSnapshotNode) {\r\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newSparseSnapshotTree() {\r\n return {\r\n value: null,\r\n children: new Map()\r\n };\r\n}\r\n/**\r\n * Stores the given node at the specified path. If there is already a node\r\n * at a shallower path, it merges the new data into that snapshot node.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @param data - The new data, or null.\r\n */\r\nfunction sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = data;\r\n sparseSnapshotTree.children.clear();\r\n }\r\n else if (sparseSnapshotTree.value !== null) {\r\n sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n if (!sparseSnapshotTree.children.has(childKey)) {\r\n sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());\r\n }\r\n const child = sparseSnapshotTree.children.get(childKey);\r\n path = pathPopFront(path);\r\n sparseSnapshotTreeRemember(child, path, data);\r\n }\r\n}\r\n/**\r\n * Purge the data at path from the cache.\r\n *\r\n * @param path - Path to look up snapshot for.\r\n * @returns True if this node should now be removed.\r\n */\r\nfunction sparseSnapshotTreeForget(sparseSnapshotTree, path) {\r\n if (pathIsEmpty(path)) {\r\n sparseSnapshotTree.value = null;\r\n sparseSnapshotTree.children.clear();\r\n return true;\r\n }\r\n else {\r\n if (sparseSnapshotTree.value !== null) {\r\n if (sparseSnapshotTree.value.isLeafNode()) {\r\n // We're trying to forget a node that doesn't exist\r\n return false;\r\n }\r\n else {\r\n const value = sparseSnapshotTree.value;\r\n sparseSnapshotTree.value = null;\r\n value.forEachChild(PRIORITY_INDEX, (key, tree) => {\r\n sparseSnapshotTreeRemember(sparseSnapshotTree, new Path(key), tree);\r\n });\r\n return sparseSnapshotTreeForget(sparseSnapshotTree, path);\r\n }\r\n }\r\n else if (sparseSnapshotTree.children.size > 0) {\r\n const childKey = pathGetFront(path);\r\n path = pathPopFront(path);\r\n if (sparseSnapshotTree.children.has(childKey)) {\r\n const safeToRemove = sparseSnapshotTreeForget(sparseSnapshotTree.children.get(childKey), path);\r\n if (safeToRemove) {\r\n sparseSnapshotTree.children.delete(childKey);\r\n }\r\n }\r\n return sparseSnapshotTree.children.size === 0;\r\n }\r\n else {\r\n return true;\r\n }\r\n }\r\n}\r\n/**\r\n * Recursively iterates through all of the stored tree and calls the\r\n * callback on each one.\r\n *\r\n * @param prefixPath - Path to look up node for.\r\n * @param func - The function to invoke for each tree.\r\n */\r\nfunction sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {\r\n if (sparseSnapshotTree.value !== null) {\r\n func(prefixPath, sparseSnapshotTree.value);\r\n }\r\n else {\r\n sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {\r\n const path = new Path(prefixPath.toString() + '/' + key);\r\n sparseSnapshotTreeForEachTree(tree, path, func);\r\n });\r\n }\r\n}\r\n/**\r\n * Iterates through each immediate child and triggers the callback.\r\n * Only seems to be used in tests.\r\n *\r\n * @param func - The function to invoke for each child.\r\n */\r\nfunction sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {\r\n sparseSnapshotTree.children.forEach((tree, key) => {\r\n func(key, tree);\r\n });\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Returns the delta from the previous call to get stats.\r\n *\r\n * @param collection_ - The collection to \"listen\" to.\r\n */\r\nclass StatsListener {\r\n constructor(collection_) {\r\n this.collection_ = collection_;\r\n this.last_ = null;\r\n }\r\n get() {\r\n const newStats = this.collection_.get();\r\n const delta = Object.assign({}, newStats);\r\n if (this.last_) {\r\n each(this.last_, (stat, value) => {\r\n delta[stat] = delta[stat] - value;\r\n });\r\n }\r\n this.last_ = newStats;\r\n return delta;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\r\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\r\n// seconds to try to ensure the Firebase connection is established / settled.\r\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\r\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\r\n// We'll continue to report stats on average every 5 minutes.\r\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\r\nclass StatsReporter {\r\n constructor(collection, server_) {\r\n this.server_ = server_;\r\n this.statsToReport_ = {};\r\n this.statsListener_ = new StatsListener(collection);\r\n const timeout = FIRST_STATS_MIN_TIME +\r\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\r\n }\r\n reportStats_() {\r\n const stats = this.statsListener_.get();\r\n const reportedStats = {};\r\n let haveStatsToReport = false;\r\n each(stats, (stat, value) => {\r\n if (value > 0 && contains(this.statsToReport_, stat)) {\r\n reportedStats[stat] = value;\r\n haveStatsToReport = true;\r\n }\r\n });\r\n if (haveStatsToReport) {\r\n this.server_.reportStats(reportedStats);\r\n }\r\n // queue our next run.\r\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n *\r\n * @enum\r\n */\r\nvar OperationType;\r\n(function (OperationType) {\r\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\r\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\r\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\r\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\r\n})(OperationType || (OperationType = {}));\r\nfunction newOperationSourceUser() {\r\n return {\r\n fromUser: true,\r\n fromServer: false,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServer() {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId: null,\r\n tagged: false\r\n };\r\n}\r\nfunction newOperationSourceServerTaggedQuery(queryId) {\r\n return {\r\n fromUser: false,\r\n fromServer: true,\r\n queryId,\r\n tagged: true\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass AckUserWrite {\r\n /**\r\n * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.\r\n */\r\n constructor(\r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ affectedTree, \r\n /** @inheritDoc */ revert) {\r\n this.path = path;\r\n this.affectedTree = affectedTree;\r\n this.revert = revert;\r\n /** @inheritDoc */\r\n this.type = OperationType.ACK_USER_WRITE;\r\n /** @inheritDoc */\r\n this.source = newOperationSourceUser();\r\n }\r\n operationForChild(childName) {\r\n if (!pathIsEmpty(this.path)) {\r\n assert(pathGetFront(this.path) === childName, 'operationForChild called for unrelated child.');\r\n return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);\r\n }\r\n else if (this.affectedTree.value != null) {\r\n assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\r\n // All child locations are affected as well; just return same operation.\r\n return this;\r\n }\r\n else {\r\n const childTree = this.affectedTree.subtree(new Path(childName));\r\n return new AckUserWrite(newEmptyPath(), childTree, this.revert);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ListenComplete {\r\n constructor(source, path) {\r\n this.source = source;\r\n this.path = path;\r\n /** @inheritDoc */\r\n this.type = OperationType.LISTEN_COMPLETE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new ListenComplete(this.source, newEmptyPath());\r\n }\r\n else {\r\n return new ListenComplete(this.source, pathPopFront(this.path));\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Overwrite {\r\n constructor(source, path, snap) {\r\n this.source = source;\r\n this.path = path;\r\n this.snap = snap;\r\n /** @inheritDoc */\r\n this.type = OperationType.OVERWRITE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));\r\n }\r\n else {\r\n return new Overwrite(this.source, pathPopFront(this.path), this.snap);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass Merge {\r\n constructor(\r\n /** @inheritDoc */ source, \r\n /** @inheritDoc */ path, \r\n /** @inheritDoc */ children) {\r\n this.source = source;\r\n this.path = path;\r\n this.children = children;\r\n /** @inheritDoc */\r\n this.type = OperationType.MERGE;\r\n }\r\n operationForChild(childName) {\r\n if (pathIsEmpty(this.path)) {\r\n const childTree = this.children.subtree(new Path(childName));\r\n if (childTree.isEmpty()) {\r\n // This child is unaffected\r\n return null;\r\n }\r\n else if (childTree.value) {\r\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\r\n return new Overwrite(this.source, newEmptyPath(), childTree.value);\r\n }\r\n else {\r\n // This is a merge at a deeper level\r\n return new Merge(this.source, newEmptyPath(), childTree);\r\n }\r\n }\r\n else {\r\n assert(pathGetFront(this.path) === childName, \"Can't get a merge for a child not on the path of the operation\");\r\n return new Merge(this.source, pathPopFront(this.path), this.children);\r\n }\r\n }\r\n toString() {\r\n return ('Operation(' +\r\n this.path +\r\n ': ' +\r\n this.source.toString() +\r\n ' merge: ' +\r\n this.children.toString() +\r\n ')');\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\r\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\r\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\r\n * whether a node potentially had children removed due to a filter.\r\n */\r\nclass CacheNode {\r\n constructor(node_, fullyInitialized_, filtered_) {\r\n this.node_ = node_;\r\n this.fullyInitialized_ = fullyInitialized_;\r\n this.filtered_ = filtered_;\r\n }\r\n /**\r\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\r\n */\r\n isFullyInitialized() {\r\n return this.fullyInitialized_;\r\n }\r\n /**\r\n * Returns whether this node is potentially missing children due to a filter applied to the node\r\n */\r\n isFiltered() {\r\n return this.filtered_;\r\n }\r\n isCompleteForPath(path) {\r\n if (pathIsEmpty(path)) {\r\n return this.isFullyInitialized() && !this.filtered_;\r\n }\r\n const childKey = pathGetFront(path);\r\n return this.isCompleteForChild(childKey);\r\n }\r\n isCompleteForChild(key) {\r\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\r\n }\r\n getNode() {\r\n return this.node_;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\r\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\r\n * for details.\r\n *\r\n */\r\nclass EventGenerator {\r\n constructor(query_) {\r\n this.query_ = query_;\r\n this.index_ = this.query_._queryParams.getIndex();\r\n }\r\n}\r\n/**\r\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\r\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\r\n *\r\n * Notes:\r\n * - child_moved events will be synthesized at this time for any child_changed events that affect\r\n * our index.\r\n * - prevName will be calculated based on the index ordering.\r\n */\r\nfunction eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {\r\n const events = [];\r\n const moves = [];\r\n changes.forEach(change => {\r\n if (change.type === \"child_changed\" /* CHILD_CHANGED */ &&\r\n eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\r\n moves.push(changeChildMoved(change.childName, change.snapshotNode));\r\n }\r\n });\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_removed\" /* CHILD_REMOVED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_added\" /* CHILD_ADDED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_moved\" /* CHILD_MOVED */, moves, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"child_changed\" /* CHILD_CHANGED */, changes, eventRegistrations, eventCache);\r\n eventGeneratorGenerateEventsForType(eventGenerator, events, \"value\" /* VALUE */, changes, eventRegistrations, eventCache);\r\n return events;\r\n}\r\n/**\r\n * Given changes of a single change type, generate the corresponding events.\r\n */\r\nfunction eventGeneratorGenerateEventsForType(eventGenerator, events, eventType, changes, registrations, eventCache) {\r\n const filteredChanges = changes.filter(change => change.type === eventType);\r\n filteredChanges.sort((a, b) => eventGeneratorCompareChanges(eventGenerator, a, b));\r\n filteredChanges.forEach(change => {\r\n const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);\r\n registrations.forEach(registration => {\r\n if (registration.respondsTo(change.type)) {\r\n events.push(registration.createEvent(materializedChange, eventGenerator.query_));\r\n }\r\n });\r\n });\r\n}\r\nfunction eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {\r\n if (change.type === 'value' || change.type === 'child_removed') {\r\n return change;\r\n }\r\n else {\r\n change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);\r\n return change;\r\n }\r\n}\r\nfunction eventGeneratorCompareChanges(eventGenerator, a, b) {\r\n if (a.childName == null || b.childName == null) {\r\n throw assertionError('Should only compare child_ events.');\r\n }\r\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\r\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\r\n return eventGenerator.index_.compare(aWrapped, bWrapped);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewCache(eventCache, serverCache) {\r\n return { eventCache, serverCache };\r\n}\r\nfunction viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {\r\n return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);\r\n}\r\nfunction viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {\r\n return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));\r\n}\r\nfunction viewCacheGetCompleteEventSnap(viewCache) {\r\n return viewCache.eventCache.isFullyInitialized()\r\n ? viewCache.eventCache.getNode()\r\n : null;\r\n}\r\nfunction viewCacheGetCompleteServerSnap(viewCache) {\r\n return viewCache.serverCache.isFullyInitialized()\r\n ? viewCache.serverCache.getNode()\r\n : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet emptyChildrenSingleton;\r\n/**\r\n * Singleton empty children collection.\r\n *\r\n */\r\nconst EmptyChildren = () => {\r\n if (!emptyChildrenSingleton) {\r\n emptyChildrenSingleton = new SortedMap(stringCompare);\r\n }\r\n return emptyChildrenSingleton;\r\n};\r\n/**\r\n * A tree with immutable elements.\r\n */\r\nclass ImmutableTree {\r\n constructor(value, children = EmptyChildren()) {\r\n this.value = value;\r\n this.children = children;\r\n }\r\n static fromObject(obj) {\r\n let tree = new ImmutableTree(null);\r\n each(obj, (childPath, childSnap) => {\r\n tree = tree.set(new Path(childPath), childSnap);\r\n });\r\n return tree;\r\n }\r\n /**\r\n * True if the value is empty and there are no children\r\n */\r\n isEmpty() {\r\n return this.value === null && this.children.isEmpty();\r\n }\r\n /**\r\n * Given a path and predicate, return the first node and the path to that node\r\n * where the predicate returns true.\r\n *\r\n * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`\r\n * objects on the way back out, it may be better to pass down a pathSoFar obj.\r\n *\r\n * @param relativePath - The remainder of the path\r\n * @param predicate - The predicate to satisfy to return a node\r\n */\r\n findRootMostMatchingPathAndValue(relativePath, predicate) {\r\n if (this.value != null && predicate(this.value)) {\r\n return { path: newEmptyPath(), value: this.value };\r\n }\r\n else {\r\n if (pathIsEmpty(relativePath)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child !== null) {\r\n const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);\r\n if (childExistingPathAndValue != null) {\r\n const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);\r\n return { path: fullPath, value: childExistingPathAndValue.value };\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n /**\r\n * Find, if it exists, the shortest subpath of the given path that points a defined\r\n * value in the tree\r\n */\r\n findRootMostValueAndPath(relativePath) {\r\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\r\n }\r\n /**\r\n * @returns The subtree at the given path\r\n */\r\n subtree(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const childTree = this.children.get(front);\r\n if (childTree !== null) {\r\n return childTree.subtree(pathPopFront(relativePath));\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Sets a value at the specified path.\r\n *\r\n * @param relativePath - Path to set value at.\r\n * @param toSet - Value to set.\r\n * @returns Resulting tree.\r\n */\r\n set(relativePath, toSet) {\r\n if (pathIsEmpty(relativePath)) {\r\n return new ImmutableTree(toSet, this.children);\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.set(pathPopFront(relativePath), toSet);\r\n const newChildren = this.children.insert(front, newChild);\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Removes the value at the specified path.\r\n *\r\n * @param relativePath - Path to value to remove.\r\n * @returns Resulting tree.\r\n */\r\n remove(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n if (this.children.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(null, this.children);\r\n }\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n const newChild = child.remove(pathPopFront(relativePath));\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n if (this.value === null && newChildren.isEmpty()) {\r\n return new ImmutableTree(null);\r\n }\r\n else {\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n else {\r\n return this;\r\n }\r\n }\r\n }\r\n /**\r\n * Gets a value from the tree.\r\n *\r\n * @param relativePath - Path to get value for.\r\n * @returns Value at path, or null.\r\n */\r\n get(relativePath) {\r\n if (pathIsEmpty(relativePath)) {\r\n return this.value;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front);\r\n if (child) {\r\n return child.get(pathPopFront(relativePath));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n /**\r\n * Replace the subtree at the specified path with the given new tree.\r\n *\r\n * @param relativePath - Path to replace subtree for.\r\n * @param newTree - New tree.\r\n * @returns Resulting tree.\r\n */\r\n setTree(relativePath, newTree) {\r\n if (pathIsEmpty(relativePath)) {\r\n return newTree;\r\n }\r\n else {\r\n const front = pathGetFront(relativePath);\r\n const child = this.children.get(front) || new ImmutableTree(null);\r\n const newChild = child.setTree(pathPopFront(relativePath), newTree);\r\n let newChildren;\r\n if (newChild.isEmpty()) {\r\n newChildren = this.children.remove(front);\r\n }\r\n else {\r\n newChildren = this.children.insert(front, newChild);\r\n }\r\n return new ImmutableTree(this.value, newChildren);\r\n }\r\n }\r\n /**\r\n * Performs a depth first fold on this tree. Transforms a tree into a single\r\n * value, given a function that operates on the path to a node, an optional\r\n * current value, and a map of child names to folded subtrees\r\n */\r\n fold(fn) {\r\n return this.fold_(newEmptyPath(), fn);\r\n }\r\n /**\r\n * Recursive helper for public-facing fold() method\r\n */\r\n fold_(pathSoFar, fn) {\r\n const accum = {};\r\n this.children.inorderTraversal((childKey, childTree) => {\r\n accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn);\r\n });\r\n return fn(pathSoFar, this.value, accum);\r\n }\r\n /**\r\n * Find the first matching value on the given path. Return the result of applying f to it.\r\n */\r\n findOnPath(path, f) {\r\n return this.findOnPath_(path, newEmptyPath(), f);\r\n }\r\n findOnPath_(pathToFollow, pathSoFar, f) {\r\n const result = this.value ? f(pathSoFar, this.value) : false;\r\n if (result) {\r\n return result;\r\n }\r\n else {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return null;\r\n }\r\n else {\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n }\r\n }\r\n foreachOnPath(path, f) {\r\n return this.foreachOnPath_(path, newEmptyPath(), f);\r\n }\r\n foreachOnPath_(pathToFollow, currentRelativePath, f) {\r\n if (pathIsEmpty(pathToFollow)) {\r\n return this;\r\n }\r\n else {\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n const front = pathGetFront(pathToFollow);\r\n const nextChild = this.children.get(front);\r\n if (nextChild) {\r\n return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f);\r\n }\r\n else {\r\n return new ImmutableTree(null);\r\n }\r\n }\r\n }\r\n /**\r\n * Calls the given function for each node in the tree that has a value.\r\n *\r\n * @param f - A function to be called with the path from the root of the tree to\r\n * a node, and the value at that node. Called in depth-first order.\r\n */\r\n foreach(f) {\r\n this.foreach_(newEmptyPath(), f);\r\n }\r\n foreach_(currentRelativePath, f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n childTree.foreach_(pathChild(currentRelativePath, childName), f);\r\n });\r\n if (this.value) {\r\n f(currentRelativePath, this.value);\r\n }\r\n }\r\n foreachChild(f) {\r\n this.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value) {\r\n f(childName, childTree.value);\r\n }\r\n });\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\r\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\r\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\r\n * to reflect the write added.\r\n */\r\nclass CompoundWrite {\r\n constructor(writeTree_) {\r\n this.writeTree_ = writeTree_;\r\n }\r\n static empty() {\r\n return new CompoundWrite(new ImmutableTree(null));\r\n }\r\n}\r\nfunction compoundWriteAddWrite(compoundWrite, path, node) {\r\n if (pathIsEmpty(path)) {\r\n return new CompoundWrite(new ImmutableTree(node));\r\n }\r\n else {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n const rootMostPath = rootmost.path;\r\n let value = rootmost.value;\r\n const relativePath = newRelativePath(rootMostPath, path);\r\n value = value.updateChild(relativePath, node);\r\n return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));\r\n }\r\n else {\r\n const subtree = new ImmutableTree(node);\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, subtree);\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n }\r\n}\r\nfunction compoundWriteAddWrites(compoundWrite, path, updates) {\r\n let newWrite = compoundWrite;\r\n each(updates, (childKey, node) => {\r\n newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);\r\n });\r\n return newWrite;\r\n}\r\n/**\r\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\r\n * location, which must be removed by calling this method with that path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to remove.\r\n * @param path - The path at which a write and all deeper writes should be removed\r\n * @returns The new CompoundWrite with the removed path\r\n */\r\nfunction compoundWriteRemoveWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return CompoundWrite.empty();\r\n }\r\n else {\r\n const newWriteTree = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));\r\n return new CompoundWrite(newWriteTree);\r\n }\r\n}\r\n/**\r\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\r\n * considered \"complete\".\r\n *\r\n * @param compoundWrite - The CompoundWrite to check.\r\n * @param path - The path to check for\r\n * @returns Whether there is a complete write at that path\r\n */\r\nfunction compoundWriteHasCompleteWrite(compoundWrite, path) {\r\n return compoundWriteGetCompleteNode(compoundWrite, path) != null;\r\n}\r\n/**\r\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\r\n * writes from deeper paths, but will return child nodes from a more shallow path.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get the node from.\r\n * @param path - The path to get a complete write\r\n * @returns The node if complete at that path, or null otherwise.\r\n */\r\nfunction compoundWriteGetCompleteNode(compoundWrite, path) {\r\n const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);\r\n if (rootmost != null) {\r\n return compoundWrite.writeTree_\r\n .get(rootmost.path)\r\n .getChild(newRelativePath(rootmost.path, path));\r\n }\r\n else {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Returns all children that are guaranteed to be a complete overwrite.\r\n *\r\n * @param compoundWrite - The CompoundWrite to get children from.\r\n * @returns A list of all complete children.\r\n */\r\nfunction compoundWriteGetCompleteChildren(compoundWrite) {\r\n const children = [];\r\n const node = compoundWrite.writeTree_.value;\r\n if (node != null) {\r\n // If it's a leaf node, it has no children; so nothing to do.\r\n if (!node.isLeafNode()) {\r\n node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n children.push(new NamedNode(childName, childNode));\r\n });\r\n }\r\n }\r\n else {\r\n compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {\r\n if (childTree.value != null) {\r\n children.push(new NamedNode(childName, childTree.value));\r\n }\r\n });\r\n }\r\n return children;\r\n}\r\nfunction compoundWriteChildCompoundWrite(compoundWrite, path) {\r\n if (pathIsEmpty(path)) {\r\n return compoundWrite;\r\n }\r\n else {\r\n const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);\r\n if (shadowingNode != null) {\r\n return new CompoundWrite(new ImmutableTree(shadowingNode));\r\n }\r\n else {\r\n return new CompoundWrite(compoundWrite.writeTree_.subtree(path));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\r\n * @returns Whether this CompoundWrite is empty\r\n */\r\nfunction compoundWriteIsEmpty(compoundWrite) {\r\n return compoundWrite.writeTree_.isEmpty();\r\n}\r\n/**\r\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\r\n * node\r\n * @param node - The node to apply this CompoundWrite to\r\n * @returns The node with all writes applied\r\n */\r\nfunction compoundWriteApply(compoundWrite, node) {\r\n return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);\r\n}\r\nfunction applySubtreeWrite(relativePath, writeTree, node) {\r\n if (writeTree.value != null) {\r\n // Since there a write is always a leaf, we're done here\r\n return node.updateChild(relativePath, writeTree.value);\r\n }\r\n else {\r\n let priorityWrite = null;\r\n writeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (childKey === '.priority') {\r\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\r\n // to apply priorities to empty nodes that are later filled\r\n assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\r\n priorityWrite = childTree.value;\r\n }\r\n else {\r\n node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);\r\n }\r\n });\r\n // If there was a priority write, we only apply it if the node is not empty\r\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\r\n node = node.updateChild(pathChild(relativePath, '.priority'), priorityWrite);\r\n }\r\n return node;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\r\n *\r\n */\r\nfunction writeTreeChildWrites(writeTree, path) {\r\n return newWriteTreeRef(path, writeTree);\r\n}\r\n/**\r\n * Record a new overwrite from user code.\r\n *\r\n * @param visible - This is set to false by some transactions. It should be excluded from event caches\r\n */\r\nfunction writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older write on top of newer ones');\r\n if (visible === undefined) {\r\n visible = true;\r\n }\r\n writeTree.allWrites.push({\r\n path,\r\n snap,\r\n writeId,\r\n visible\r\n });\r\n if (visible) {\r\n writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);\r\n }\r\n writeTree.lastWriteId = writeId;\r\n}\r\n/**\r\n * Record a new merge from user code.\r\n */\r\nfunction writeTreeAddMerge(writeTree, path, changedChildren, writeId) {\r\n assert(writeId > writeTree.lastWriteId, 'Stacking an older merge on top of newer ones');\r\n writeTree.allWrites.push({\r\n path,\r\n children: changedChildren,\r\n writeId,\r\n visible: true\r\n });\r\n writeTree.visibleWrites = compoundWriteAddWrites(writeTree.visibleWrites, path, changedChildren);\r\n writeTree.lastWriteId = writeId;\r\n}\r\nfunction writeTreeGetWrite(writeTree, writeId) {\r\n for (let i = 0; i < writeTree.allWrites.length; i++) {\r\n const record = writeTree.allWrites[i];\r\n if (record.writeId === writeId) {\r\n return record;\r\n }\r\n }\r\n return null;\r\n}\r\n/**\r\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\r\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\r\n *\r\n * @returns true if the write may have been visible (meaning we'll need to reevaluate / raise\r\n * events as a result).\r\n */\r\nfunction writeTreeRemoveWrite(writeTree, writeId) {\r\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\r\n // out of order.\r\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\r\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\r\n const idx = writeTree.allWrites.findIndex(s => {\r\n return s.writeId === writeId;\r\n });\r\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\r\n const writeToRemove = writeTree.allWrites[idx];\r\n writeTree.allWrites.splice(idx, 1);\r\n let removedWriteWasVisible = writeToRemove.visible;\r\n let removedWriteOverlapsWithOtherWrites = false;\r\n let i = writeTree.allWrites.length - 1;\r\n while (removedWriteWasVisible && i >= 0) {\r\n const currentWrite = writeTree.allWrites[i];\r\n if (currentWrite.visible) {\r\n if (i >= idx &&\r\n writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {\r\n // The removed write was completely shadowed by a subsequent write.\r\n removedWriteWasVisible = false;\r\n }\r\n else if (pathContains(writeToRemove.path, currentWrite.path)) {\r\n // Either we're covering some writes or they're covering part of us (depending on which came first).\r\n removedWriteOverlapsWithOtherWrites = true;\r\n }\r\n }\r\n i--;\r\n }\r\n if (!removedWriteWasVisible) {\r\n return false;\r\n }\r\n else if (removedWriteOverlapsWithOtherWrites) {\r\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\r\n writeTreeResetTree_(writeTree);\r\n return true;\r\n }\r\n else {\r\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\r\n if (writeToRemove.snap) {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);\r\n }\r\n else {\r\n const children = writeToRemove.children;\r\n each(children, (childName) => {\r\n writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));\r\n });\r\n }\r\n return true;\r\n }\r\n}\r\nfunction writeTreeRecordContainsPath_(writeRecord, path) {\r\n if (writeRecord.snap) {\r\n return pathContains(writeRecord.path, path);\r\n }\r\n else {\r\n for (const childName in writeRecord.children) {\r\n if (writeRecord.children.hasOwnProperty(childName) &&\r\n pathContains(pathChild(writeRecord.path, childName), path)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n}\r\n/**\r\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\r\n */\r\nfunction writeTreeResetTree_(writeTree) {\r\n writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());\r\n if (writeTree.allWrites.length > 0) {\r\n writeTree.lastWriteId =\r\n writeTree.allWrites[writeTree.allWrites.length - 1].writeId;\r\n }\r\n else {\r\n writeTree.lastWriteId = -1;\r\n }\r\n}\r\n/**\r\n * The default filter used when constructing the tree. Keep everything that's visible.\r\n */\r\nfunction writeTreeDefaultFilter_(write) {\r\n return write.visible;\r\n}\r\n/**\r\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\r\n * event data at that path.\r\n */\r\nfunction writeTreeLayerTree_(writes, filter, treeRoot) {\r\n let compoundWrite = CompoundWrite.empty();\r\n for (let i = 0; i < writes.length; ++i) {\r\n const write = writes[i];\r\n // Theory, a later set will either:\r\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\r\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\r\n if (filter(write)) {\r\n const writePath = write.path;\r\n let relativePath;\r\n if (write.snap) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));\r\n }\r\n else ;\r\n }\r\n else if (write.children) {\r\n if (pathContains(treeRoot, writePath)) {\r\n relativePath = newRelativePath(treeRoot, writePath);\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);\r\n }\r\n else if (pathContains(writePath, treeRoot)) {\r\n relativePath = newRelativePath(writePath, treeRoot);\r\n if (pathIsEmpty(relativePath)) {\r\n compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);\r\n }\r\n else {\r\n const child = safeGet(write.children, pathGetFront(relativePath));\r\n if (child) {\r\n // There exists a child in this node that matches the root path\r\n const deepNode = child.getChild(pathPopFront(relativePath));\r\n compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);\r\n }\r\n }\r\n }\r\n else ;\r\n }\r\n else {\r\n throw assertionError('WriteRecord should have .snap or .children');\r\n }\r\n }\r\n }\r\n return compoundWrite;\r\n}\r\n/**\r\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\r\n * writes), attempt to calculate a complete snapshot for the given path\r\n *\r\n * @param writeIdsToExclude - An optional set to be excluded\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n if (!writeIdsToExclude && !includeHiddenWrites) {\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (compoundWriteIsEmpty(subMerge)) {\r\n return completeServerCache;\r\n }\r\n else if (completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {\r\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\r\n return null;\r\n }\r\n else {\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(subMerge, layeredCache);\r\n }\r\n }\r\n }\r\n else {\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {\r\n return completeServerCache;\r\n }\r\n else {\r\n // If the server cache is null, and we don't have a complete cache, we need to return null\r\n if (!includeHiddenWrites &&\r\n completeServerCache == null &&\r\n !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {\r\n return null;\r\n }\r\n else {\r\n const filter = function (write) {\r\n return ((write.visible || includeHiddenWrites) &&\r\n (!writeIdsToExclude ||\r\n !~writeIdsToExclude.indexOf(write.writeId)) &&\r\n (pathContains(write.path, treePath) ||\r\n pathContains(treePath, write.path)));\r\n };\r\n const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);\r\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\r\n return compoundWriteApply(mergeAtPath, layeredCache);\r\n }\r\n }\r\n }\r\n}\r\n/**\r\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\r\n * Used when creating new views, to pre-fill their complete event children snapshot.\r\n */\r\nfunction writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {\r\n let completeChildren = ChildrenNode.EMPTY_NODE;\r\n const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);\r\n if (topLevelSet) {\r\n if (!topLevelSet.isLeafNode()) {\r\n // we're shadowing everything. Return the children.\r\n topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {\r\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\r\n });\r\n }\r\n return completeChildren;\r\n }\r\n else if (completeServerChildren) {\r\n // Layer any children we have on top of this\r\n // We know we don't have a top-level set, so just enumerate existing children\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);\r\n completeChildren = completeChildren.updateImmediateChild(childName, node);\r\n });\r\n // Add any complete children we have from the set\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n else {\r\n // We don't have anything to layer on top of. Layer on any children we have\r\n // Note that we can return an empty snap if we have a defined delete\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n compoundWriteGetCompleteChildren(merge).forEach(namedNode => {\r\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\r\n });\r\n return completeChildren;\r\n }\r\n}\r\n/**\r\n * Given that the underlying server data has updated, determine what, if anything, needs to be\r\n * applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist\r\n */\r\nfunction writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {\r\n assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\r\n const path = pathChild(treePath, childPath);\r\n if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {\r\n // At this point we can probably guarantee that we're in case 2, meaning no events\r\n // May need to check visibility while doing the findRootMostValueAndPath call\r\n return null;\r\n }\r\n else {\r\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n if (compoundWriteIsEmpty(childMerge)) {\r\n // We're not shadowing at all. Case 1\r\n return existingServerSnap.getChild(childPath);\r\n }\r\n else {\r\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\r\n // However this is tricky to find out, since user updates don't necessary change the server\r\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\r\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\r\n // only check if the updates change the serverNode.\r\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\r\n return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {\r\n const path = pathChild(treePath, childKey);\r\n const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n if (shadowingNode != null) {\r\n return shadowingNode;\r\n }\r\n else {\r\n if (existingServerSnap.isCompleteForChild(childKey)) {\r\n const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);\r\n return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n */\r\nfunction writeTreeShadowingWrite(writeTree, path) {\r\n return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window.\r\n */\r\nfunction writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index) {\r\n let toIterate;\r\n const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);\r\n const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());\r\n if (shadowingNode != null) {\r\n toIterate = shadowingNode;\r\n }\r\n else if (completeServerData != null) {\r\n toIterate = compoundWriteApply(merge, completeServerData);\r\n }\r\n else {\r\n // no children to iterate on\r\n return [];\r\n }\r\n toIterate = toIterate.withIndex(index);\r\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\r\n const nodes = [];\r\n const cmp = index.getCompare();\r\n const iter = reverse\r\n ? toIterate.getReverseIteratorFrom(startPost, index)\r\n : toIterate.getIteratorFrom(startPost, index);\r\n let next = iter.getNext();\r\n while (next && nodes.length < count) {\r\n if (cmp(next, startPost) !== 0) {\r\n nodes.push(next);\r\n }\r\n next = iter.getNext();\r\n }\r\n return nodes;\r\n }\r\n else {\r\n return [];\r\n }\r\n}\r\nfunction newWriteTree() {\r\n return {\r\n visibleWrites: CompoundWrite.empty(),\r\n allWrites: [],\r\n lastWriteId: -1\r\n };\r\n}\r\n/**\r\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\r\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\r\n * can lead to a more expensive calculation.\r\n *\r\n * @param writeIdsToExclude - Optional writes to exclude.\r\n * @param includeHiddenWrites - Defaults to false, whether or not to layer on writes with visible set to false\r\n */\r\nfunction writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\r\n return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);\r\n}\r\n/**\r\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\r\n * mix of the given server data and write data.\r\n *\r\n */\r\nfunction writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {\r\n return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);\r\n}\r\n/**\r\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\r\n * if anything, needs to be applied to the event cache.\r\n *\r\n * Possibilities:\r\n *\r\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\r\n *\r\n * 2. Some write is completely shadowing. No events to be raised\r\n *\r\n * 3. Is partially shadowed. Events should be raised\r\n *\r\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\r\n *\r\n *\r\n */\r\nfunction writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {\r\n return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);\r\n}\r\n/**\r\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\r\n * a higher path, this will return the child of that write relative to the write and this path.\r\n * Returns null if there is no write at this path.\r\n *\r\n */\r\nfunction writeTreeRefShadowingWrite(writeTreeRef, path) {\r\n return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));\r\n}\r\n/**\r\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\r\n * the window, but may now be in the window\r\n */\r\nfunction writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index) {\r\n return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index);\r\n}\r\n/**\r\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\r\n * complete child for this ChildKey.\r\n */\r\nfunction writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {\r\n return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);\r\n}\r\n/**\r\n * Return a WriteTreeRef for a child.\r\n */\r\nfunction writeTreeRefChild(writeTreeRef, childName) {\r\n return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);\r\n}\r\nfunction newWriteTreeRef(path, writeTree) {\r\n return {\r\n treePath: path,\r\n writeTree\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ChildChangeAccumulator {\r\n constructor() {\r\n this.changeMap = new Map();\r\n }\r\n trackChildChange(change) {\r\n const type = change.type;\r\n const childKey = change.childName;\r\n assert(type === \"child_added\" /* CHILD_ADDED */ ||\r\n type === \"child_changed\" /* CHILD_CHANGED */ ||\r\n type === \"child_removed\" /* CHILD_REMOVED */, 'Only child changes supported for tracking');\r\n assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\r\n const oldChange = this.changeMap.get(childKey);\r\n if (oldChange) {\r\n const oldType = oldChange.type;\r\n if (type === \"child_added\" /* CHILD_ADDED */ &&\r\n oldType === \"child_removed\" /* CHILD_REMOVED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));\r\n }\r\n else if (type === \"child_removed\" /* CHILD_REMOVED */ &&\r\n oldType === \"child_added\" /* CHILD_ADDED */) {\r\n this.changeMap.delete(childKey);\r\n }\r\n else if (type === \"child_removed\" /* CHILD_REMOVED */ &&\r\n oldType === \"child_changed\" /* CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));\r\n }\r\n else if (type === \"child_changed\" /* CHILD_CHANGED */ &&\r\n oldType === \"child_added\" /* CHILD_ADDED */) {\r\n this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));\r\n }\r\n else if (type === \"child_changed\" /* CHILD_CHANGED */ &&\r\n oldType === \"child_changed\" /* CHILD_CHANGED */) {\r\n this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));\r\n }\r\n else {\r\n throw assertionError('Illegal combination of changes: ' +\r\n change +\r\n ' occurred after ' +\r\n oldChange);\r\n }\r\n }\r\n else {\r\n this.changeMap.set(childKey, change);\r\n }\r\n }\r\n getChanges() {\r\n return Array.from(this.changeMap.values());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * An implementation of CompleteChildSource that never returns any additional children\r\n */\r\n// eslint-disable-next-line @typescript-eslint/naming-convention\r\nclass NoCompleteChildSource_ {\r\n getCompleteChild(childKey) {\r\n return null;\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n return null;\r\n }\r\n}\r\n/**\r\n * Singleton instance.\r\n */\r\nconst NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\r\n/**\r\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\r\n * old event caches available to calculate complete children.\r\n */\r\nclass WriteTreeCompleteChildSource {\r\n constructor(writes_, viewCache_, optCompleteServerCache_ = null) {\r\n this.writes_ = writes_;\r\n this.viewCache_ = viewCache_;\r\n this.optCompleteServerCache_ = optCompleteServerCache_;\r\n }\r\n getCompleteChild(childKey) {\r\n const node = this.viewCache_.eventCache;\r\n if (node.isCompleteForChild(childKey)) {\r\n return node.getNode().getImmediateChild(childKey);\r\n }\r\n else {\r\n const serverNode = this.optCompleteServerCache_ != null\r\n ? new CacheNode(this.optCompleteServerCache_, true, false)\r\n : this.viewCache_.serverCache;\r\n return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);\r\n }\r\n }\r\n getChildAfterChild(index, child, reverse) {\r\n const completeServerData = this.optCompleteServerCache_ != null\r\n ? this.optCompleteServerCache_\r\n : viewCacheGetCompleteServerSnap(this.viewCache_);\r\n const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child, 1, reverse, index);\r\n if (nodes.length === 0) {\r\n return null;\r\n }\r\n else {\r\n return nodes[0];\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction newViewProcessor(filter) {\r\n return { filter };\r\n}\r\nfunction viewProcessorAssertIndexed(viewProcessor, viewCache) {\r\n assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Event snap not indexed');\r\n assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), 'Server snap not indexed');\r\n}\r\nfunction viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {\r\n const accumulator = new ChildChangeAccumulator();\r\n let newViewCache, filterServerNode;\r\n if (operation.type === OperationType.OVERWRITE) {\r\n const overwrite = operation;\r\n if (overwrite.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(overwrite.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered and the\r\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\r\n // again\r\n filterServerNode =\r\n overwrite.source.tagged ||\r\n (oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path));\r\n newViewCache = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.MERGE) {\r\n const merge = operation;\r\n if (merge.source.fromUser) {\r\n newViewCache = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n assert(merge.source.fromServer, 'Unknown source.');\r\n // We filter the node if it's a tagged update or the node has been previously filtered\r\n filterServerNode =\r\n merge.source.tagged || oldViewCache.serverCache.isFiltered();\r\n newViewCache = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.ACK_USER_WRITE) {\r\n const ackUserWrite = operation;\r\n if (!ackUserWrite.revert) {\r\n newViewCache = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\r\n }\r\n else {\r\n newViewCache = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\r\n }\r\n }\r\n else if (operation.type === OperationType.LISTEN_COMPLETE) {\r\n newViewCache = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);\r\n }\r\n else {\r\n throw assertionError('Unknown operation type: ' + operation.type);\r\n }\r\n const changes = accumulator.getChanges();\r\n viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, changes);\r\n return { viewCache: newViewCache, changes };\r\n}\r\nfunction viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache, accumulator) {\r\n const eventSnap = newViewCache.eventCache;\r\n if (eventSnap.isFullyInitialized()) {\r\n const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\r\n const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);\r\n if (accumulator.length > 0 ||\r\n !oldViewCache.eventCache.isFullyInitialized() ||\r\n (isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap)) ||\r\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {\r\n accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache)));\r\n }\r\n }\r\n}\r\nfunction viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {\r\n const oldEventSnap = viewCache.eventCache;\r\n if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {\r\n // we have a shadowing write, ignore changes\r\n return viewCache;\r\n }\r\n else {\r\n let newEventCache, serverNode;\r\n if (pathIsEmpty(changePath)) {\r\n // TODO: figure out how this plays with \"sliding ack windows\"\r\n assert(viewCache.serverCache.isFullyInitialized(), 'If change path is empty, we must have complete server data');\r\n if (viewCache.serverCache.isFiltered()) {\r\n // We need to special case this, because we need to only apply writes to complete children, or\r\n // we might end up raising events for incomplete children. If the server data is filtered deep\r\n // writes cannot be guaranteed to be complete\r\n const serverCache = viewCacheGetCompleteServerSnap(viewCache);\r\n const completeChildren = serverCache instanceof ChildrenNode\r\n ? serverCache\r\n : ChildrenNode.EMPTY_NODE;\r\n const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);\r\n }\r\n else {\r\n const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);\r\n }\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n assert(pathGetLength(changePath) === 1, \"Can't have a priority with additional path components\");\r\n const oldEventNode = oldEventSnap.getNode();\r\n serverNode = viewCache.serverCache.getNode();\r\n // we might have overwrites for this priority\r\n const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);\r\n if (updatedPriority != null) {\r\n newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);\r\n }\r\n else {\r\n // priority didn't change, keep old node\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n // update child\r\n let newEventChild;\r\n if (oldEventSnap.isCompleteForChild(childKey)) {\r\n serverNode = viewCache.serverCache.getNode();\r\n const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);\r\n if (eventChildUpdate != null) {\r\n newEventChild = oldEventSnap\r\n .getNode()\r\n .getImmediateChild(childKey)\r\n .updateChild(childChangePath, eventChildUpdate);\r\n }\r\n else {\r\n // Nothing changed, just keep the old child\r\n newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n }\r\n }\r\n else {\r\n newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n }\r\n if (newEventChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\r\n }\r\n else {\r\n // no complete child available or no change\r\n newEventCache = oldEventSnap.getNode();\r\n }\r\n }\r\n }\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());\r\n }\r\n}\r\nfunction viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\r\n const oldServerSnap = oldViewCache.serverCache;\r\n let newServerCache;\r\n const serverFilter = filterServerNode\r\n ? viewProcessor.filter\r\n : viewProcessor.filter.getIndexedFilter();\r\n if (pathIsEmpty(changePath)) {\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\r\n }\r\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\r\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\r\n const newServerNode = oldServerSnap\r\n .getNode()\r\n .updateChild(changePath, changedSnap);\r\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (!oldServerSnap.isCompleteForPath(changePath) &&\r\n pathGetLength(changePath) > 1) {\r\n // We don't update incomplete nodes with updates intended for other listeners\r\n return oldViewCache;\r\n }\r\n const childChangePath = pathPopFront(changePath);\r\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\r\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\r\n if (childKey === '.priority') {\r\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\r\n }\r\n else {\r\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);\r\n }\r\n }\r\n const newViewCache = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());\r\n const source = new WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, changePath, writesCache, source, accumulator);\r\n}\r\nfunction viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\r\n const oldEventSnap = oldViewCache.eventCache;\r\n let newViewCache, newEventCache;\r\n const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\r\n if (pathIsEmpty(changePath)) {\r\n newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n const childKey = pathGetFront(changePath);\r\n if (childKey === '.priority') {\r\n newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\r\n }\r\n else {\r\n const childChangePath = pathPopFront(changePath);\r\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\r\n let newChild;\r\n if (pathIsEmpty(childChangePath)) {\r\n // Child overwrite, we can replace the child\r\n newChild = changedSnap;\r\n }\r\n else {\r\n const childNode = source.getCompleteChild(childKey);\r\n if (childNode != null) {\r\n if (pathGetBack(childChangePath) === '.priority' &&\r\n childNode.getChild(pathParent(childChangePath)).isEmpty()) {\r\n // This is a priority update on an empty node. If this node exists on the server, the\r\n // server will send down the priority in the update, so ignore for now\r\n newChild = childNode;\r\n }\r\n else {\r\n newChild = childNode.updateChild(childChangePath, changedSnap);\r\n }\r\n }\r\n else {\r\n // There is no complete child node available\r\n newChild = ChildrenNode.EMPTY_NODE;\r\n }\r\n }\r\n if (!oldChild.equals(newChild)) {\r\n const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\r\n newViewCache = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());\r\n }\r\n else {\r\n newViewCache = oldViewCache;\r\n }\r\n }\r\n }\r\n return newViewCache;\r\n}\r\nfunction viewProcessorCacheHasChild(viewCache, childKey) {\r\n return viewCache.eventCache.isCompleteForChild(childKey);\r\n}\r\nfunction viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n changedChildren.foreach((relativePath, childNode) => {\r\n const writePath = pathChild(path, relativePath);\r\n if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {\r\n curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorApplyMerge(viewProcessor, node, merge) {\r\n merge.foreach((relativePath, childNode) => {\r\n node = node.updateChild(relativePath, childNode);\r\n });\r\n return node;\r\n}\r\nfunction viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\r\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\r\n // wait for the complete data update coming soon.\r\n if (viewCache.serverCache.getNode().isEmpty() &&\r\n !viewCache.serverCache.isFullyInitialized()) {\r\n return viewCache;\r\n }\r\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\r\n // window leaving room for new items. It's important we process these changes first, so we\r\n // iterate the changes twice, first processing any that affect items currently in view.\r\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\r\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\r\n // not the other.\r\n let curViewCache = viewCache;\r\n let viewMergeTree;\r\n if (pathIsEmpty(path)) {\r\n viewMergeTree = changedChildren;\r\n }\r\n else {\r\n viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);\r\n }\r\n const serverNode = viewCache.serverCache.getNode();\r\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\r\n if (serverNode.hasChild(childKey)) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\r\n const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) &&\r\n childMergeTree.value === undefined;\r\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\r\n const serverChild = viewCache.serverCache\r\n .getNode()\r\n .getImmediateChild(childKey);\r\n const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);\r\n curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\r\n }\r\n });\r\n return curViewCache;\r\n}\r\nfunction viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\r\n if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {\r\n return viewCache;\r\n }\r\n // Only filter server node if it is currently filtered\r\n const filterServerNode = viewCache.serverCache.isFiltered();\r\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\r\n // now that it won't be shadowed.\r\n const serverCache = viewCache.serverCache;\r\n if (affectedTree.value != null) {\r\n // This is an overwrite.\r\n if ((pathIsEmpty(ackPath) && serverCache.isFullyInitialized()) ||\r\n serverCache.isCompleteForPath(ackPath)) {\r\n return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else if (pathIsEmpty(ackPath)) {\r\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\r\n // should just re-apply whatever we have in our cache as a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n serverCache.getNode().forEachChild(KEY_INDEX, (name, node) => {\r\n changedChildren = changedChildren.set(new Path(name), node);\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n else {\r\n return viewCache;\r\n }\r\n }\r\n else {\r\n // This is a merge.\r\n let changedChildren = new ImmutableTree(null);\r\n affectedTree.foreach((mergePath, value) => {\r\n const serverCachePath = pathChild(ackPath, mergePath);\r\n if (serverCache.isCompleteForPath(serverCachePath)) {\r\n changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));\r\n }\r\n });\r\n return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);\r\n }\r\n}\r\nfunction viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {\r\n const oldServerNode = viewCache.serverCache;\r\n const newViewCache = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());\r\n return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);\r\n}\r\nfunction viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {\r\n let complete;\r\n if (writeTreeRefShadowingWrite(writesCache, path) != null) {\r\n return viewCache;\r\n }\r\n else {\r\n const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\r\n const oldEventCache = viewCache.eventCache.getNode();\r\n let newEventCache;\r\n if (pathIsEmpty(path) || pathGetFront(path) === '.priority') {\r\n let newNode;\r\n if (viewCache.serverCache.isFullyInitialized()) {\r\n newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n }\r\n else {\r\n const serverChildren = viewCache.serverCache.getNode();\r\n assert(serverChildren instanceof ChildrenNode, 'serverChildren would be complete if leaf node');\r\n newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);\r\n }\r\n newNode = newNode;\r\n newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);\r\n }\r\n else {\r\n const childKey = pathGetFront(path);\r\n let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);\r\n if (newChild == null &&\r\n viewCache.serverCache.isCompleteForChild(childKey)) {\r\n newChild = oldEventCache.getImmediateChild(childKey);\r\n }\r\n if (newChild != null) {\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);\r\n }\r\n else if (viewCache.eventCache.getNode().hasChild(childKey)) {\r\n // No complete child available, delete the existing one, if any\r\n newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);\r\n }\r\n else {\r\n newEventCache = oldEventCache;\r\n }\r\n if (newEventCache.isEmpty() &&\r\n viewCache.serverCache.isFullyInitialized()) {\r\n // We might have reverted all child writes. Maybe the old event was a leaf node\r\n complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));\r\n if (complete.isLeafNode()) {\r\n newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);\r\n }\r\n }\r\n }\r\n complete =\r\n viewCache.serverCache.isFullyInitialized() ||\r\n writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;\r\n return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A view represents a specific location and query that has 1 or more event registrations.\r\n *\r\n * It does several things:\r\n * - Maintains the list of event registrations for this location/query.\r\n * - Maintains a cache of the data visible for this location/query.\r\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\r\n * registrations returns the set of events to be raised.\r\n */\r\nclass View {\r\n constructor(query_, initialViewCache) {\r\n this.query_ = query_;\r\n this.eventRegistrations_ = [];\r\n const params = this.query_._queryParams;\r\n const indexFilter = new IndexedFilter(params.getIndex());\r\n const filter = queryParamsGetNodeFilter(params);\r\n this.processor_ = newViewProcessor(filter);\r\n const initialServerCache = initialViewCache.serverCache;\r\n const initialEventCache = initialViewCache.eventCache;\r\n // Don't filter server node with other filter than index, wait for tagged listen\r\n const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\r\n const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\r\n const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\r\n const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\r\n this.viewCache_ = newViewCache(newEventCache, newServerCache);\r\n this.eventGenerator_ = new EventGenerator(this.query_);\r\n }\r\n get query() {\r\n return this.query_;\r\n }\r\n}\r\nfunction viewGetServerCache(view) {\r\n return view.viewCache_.serverCache.getNode();\r\n}\r\nfunction viewGetCompleteNode(view) {\r\n return viewCacheGetCompleteEventSnap(view.viewCache_);\r\n}\r\nfunction viewGetCompleteServerCache(view, path) {\r\n const cache = viewCacheGetCompleteServerSnap(view.viewCache_);\r\n if (cache) {\r\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\r\n // we need to see if it contains the child we're interested in.\r\n if (view.query._queryParams.loadsAllData() ||\r\n (!pathIsEmpty(path) &&\r\n !cache.getImmediateChild(pathGetFront(path)).isEmpty())) {\r\n return cache.getChild(path);\r\n }\r\n }\r\n return null;\r\n}\r\nfunction viewIsEmpty(view) {\r\n return view.eventRegistrations_.length === 0;\r\n}\r\nfunction viewAddEventRegistration(view, eventRegistration) {\r\n view.eventRegistrations_.push(eventRegistration);\r\n}\r\n/**\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction viewRemoveEventRegistration(view, eventRegistration, cancelError) {\r\n const cancelEvents = [];\r\n if (cancelError) {\r\n assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\r\n const path = view.query._path;\r\n view.eventRegistrations_.forEach(registration => {\r\n const maybeEvent = registration.createCancelEvent(cancelError, path);\r\n if (maybeEvent) {\r\n cancelEvents.push(maybeEvent);\r\n }\r\n });\r\n }\r\n if (eventRegistration) {\r\n let remaining = [];\r\n for (let i = 0; i < view.eventRegistrations_.length; ++i) {\r\n const existing = view.eventRegistrations_[i];\r\n if (!existing.matches(eventRegistration)) {\r\n remaining.push(existing);\r\n }\r\n else if (eventRegistration.hasAnyCallback()) {\r\n // We're removing just this one\r\n remaining = remaining.concat(view.eventRegistrations_.slice(i + 1));\r\n break;\r\n }\r\n }\r\n view.eventRegistrations_ = remaining;\r\n }\r\n else {\r\n view.eventRegistrations_ = [];\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Applies the given Operation, updates our cache, and returns the appropriate events.\r\n */\r\nfunction viewApplyOperation(view, operation, writesCache, completeServerCache) {\r\n if (operation.type === OperationType.MERGE &&\r\n operation.source.queryId !== null) {\r\n assert(viewCacheGetCompleteServerSnap(view.viewCache_), 'We should always have a full cache before handling merges');\r\n assert(viewCacheGetCompleteEventSnap(view.viewCache_), 'Missing event cache, even though we have a server cache');\r\n }\r\n const oldViewCache = view.viewCache_;\r\n const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);\r\n viewProcessorAssertIndexed(view.processor_, result.viewCache);\r\n assert(result.viewCache.serverCache.isFullyInitialized() ||\r\n !oldViewCache.serverCache.isFullyInitialized(), 'Once a server snap is complete, it should never go back');\r\n view.viewCache_ = result.viewCache;\r\n return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);\r\n}\r\nfunction viewGetInitialEvents(view, registration) {\r\n const eventSnap = view.viewCache_.eventCache;\r\n const initialChanges = [];\r\n if (!eventSnap.getNode().isLeafNode()) {\r\n const eventNode = eventSnap.getNode();\r\n eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {\r\n initialChanges.push(changeChildAdded(key, childNode));\r\n });\r\n }\r\n if (eventSnap.isFullyInitialized()) {\r\n initialChanges.push(changeValue(eventSnap.getNode()));\r\n }\r\n return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);\r\n}\r\nfunction viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {\r\n const registrations = eventRegistration\r\n ? [eventRegistration]\r\n : view.eventRegistrations_;\r\n return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor$1;\r\n/**\r\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\r\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\r\n * and user writes (set, transaction, update).\r\n *\r\n * It's responsible for:\r\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\r\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\r\n * applyUserOverwrite, etc.)\r\n */\r\nclass SyncPoint {\r\n constructor() {\r\n /**\r\n * The Views being tracked at this location in the tree, stored as a map where the key is a\r\n * queryId and the value is the View for that query.\r\n *\r\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\r\n */\r\n this.views = new Map();\r\n }\r\n}\r\nfunction syncPointSetReferenceConstructor(val) {\r\n assert(!referenceConstructor$1, '__referenceConstructor has already been defined');\r\n referenceConstructor$1 = val;\r\n}\r\nfunction syncPointGetReferenceConstructor() {\r\n assert(referenceConstructor$1, 'Reference.ts has not been loaded');\r\n return referenceConstructor$1;\r\n}\r\nfunction syncPointIsEmpty(syncPoint) {\r\n return syncPoint.views.size === 0;\r\n}\r\nfunction syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {\r\n const queryId = operation.source.queryId;\r\n if (queryId !== null) {\r\n const view = syncPoint.views.get(queryId);\r\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\r\n return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);\r\n }\r\n else {\r\n let events = [];\r\n for (const view of syncPoint.views.values()) {\r\n events = events.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Get a view for the specified query.\r\n *\r\n * @param query - The query to return a view for\r\n * @param writesCache\r\n * @param serverCache\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {\r\n const queryId = query._queryIdentifier;\r\n const view = syncPoint.views.get(queryId);\r\n if (!view) {\r\n // TODO: make writesCache take flag for complete server node\r\n let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);\r\n let eventCacheComplete = false;\r\n if (eventCache) {\r\n eventCacheComplete = true;\r\n }\r\n else if (serverCache instanceof ChildrenNode) {\r\n eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);\r\n eventCacheComplete = false;\r\n }\r\n else {\r\n eventCache = ChildrenNode.EMPTY_NODE;\r\n eventCacheComplete = false;\r\n }\r\n const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));\r\n return new View(query, viewCache);\r\n }\r\n return view;\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @param query\r\n * @param eventRegistration\r\n * @param writesCache\r\n * @param serverCache - Complete server cache, if we have it.\r\n * @param serverCacheComplete\r\n * @returns Events to raise.\r\n */\r\nfunction syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);\r\n if (!syncPoint.views.has(query._queryIdentifier)) {\r\n syncPoint.views.set(query._queryIdentifier, view);\r\n }\r\n // This is guaranteed to exist now, we just created anything that was missing\r\n viewAddEventRegistration(view, eventRegistration);\r\n return viewGetInitialEvents(view, eventRegistration);\r\n}\r\n/**\r\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\r\n *\r\n * If query is the default query, we'll check all views for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\r\n *\r\n * @param eventRegistration - If null, remove all callbacks.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns removed queries and any cancel events\r\n */\r\nfunction syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {\r\n const queryId = query._queryIdentifier;\r\n const removed = [];\r\n let cancelEvents = [];\r\n const hadCompleteView = syncPointHasCompleteView(syncPoint);\r\n if (queryId === 'default') {\r\n // When you do ref.off(...), we search all views for the registration to remove.\r\n for (const [viewQueryId, view] of syncPoint.views.entries()) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(viewQueryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n else {\r\n // remove the callback from the specific view.\r\n const view = syncPoint.views.get(queryId);\r\n if (view) {\r\n cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));\r\n if (viewIsEmpty(view)) {\r\n syncPoint.views.delete(queryId);\r\n // We'll deal with complete views later.\r\n if (!view.query._queryParams.loadsAllData()) {\r\n removed.push(view.query);\r\n }\r\n }\r\n }\r\n }\r\n if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {\r\n // We removed our last complete view.\r\n removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));\r\n }\r\n return { removed, events: cancelEvents };\r\n}\r\nfunction syncPointGetQueryViews(syncPoint) {\r\n const result = [];\r\n for (const view of syncPoint.views.values()) {\r\n if (!view.query._queryParams.loadsAllData()) {\r\n result.push(view);\r\n }\r\n }\r\n return result;\r\n}\r\n/**\r\n * @param path - The path to the desired complete snapshot\r\n * @returns A complete cache, if it exists\r\n */\r\nfunction syncPointGetCompleteServerCache(syncPoint, path) {\r\n let serverCache = null;\r\n for (const view of syncPoint.views.values()) {\r\n serverCache = serverCache || viewGetCompleteServerCache(view, path);\r\n }\r\n return serverCache;\r\n}\r\nfunction syncPointViewForQuery(syncPoint, query) {\r\n const params = query._queryParams;\r\n if (params.loadsAllData()) {\r\n return syncPointGetCompleteView(syncPoint);\r\n }\r\n else {\r\n const queryId = query._queryIdentifier;\r\n return syncPoint.views.get(queryId);\r\n }\r\n}\r\nfunction syncPointViewExistsForQuery(syncPoint, query) {\r\n return syncPointViewForQuery(syncPoint, query) != null;\r\n}\r\nfunction syncPointHasCompleteView(syncPoint) {\r\n return syncPointGetCompleteView(syncPoint) != null;\r\n}\r\nfunction syncPointGetCompleteView(syncPoint) {\r\n for (const view of syncPoint.views.values()) {\r\n if (view.query._queryParams.loadsAllData()) {\r\n return view;\r\n }\r\n }\r\n return null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nlet referenceConstructor;\r\nfunction syncTreeSetReferenceConstructor(val) {\r\n assert(!referenceConstructor, '__referenceConstructor has already been defined');\r\n referenceConstructor = val;\r\n}\r\nfunction syncTreeGetReferenceConstructor() {\r\n assert(referenceConstructor, 'Reference.ts has not been loaded');\r\n return referenceConstructor;\r\n}\r\n/**\r\n * Static tracker for next query tag.\r\n */\r\nlet syncTreeNextQueryTag_ = 1;\r\n/**\r\n * SyncTree is the central class for managing event callback registration, data caching, views\r\n * (query processing), and event generation. There are typically two SyncTree instances for\r\n * each Repo, one for the normal Firebase data, and one for the .info data.\r\n *\r\n * It has a number of responsibilities, including:\r\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\r\n * - Applying and caching data changes for user set(), transaction(), and update() calls\r\n * (applyUserOverwrite(), applyUserMerge()).\r\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\r\n * applyServerMerge()).\r\n * - Generating user-facing events for server and user changes (all of the apply* methods\r\n * return the set of events that need to be raised as a result).\r\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\r\n * to the correct set of paths and queries to satisfy the current set of user event\r\n * callbacks (listens are started/stopped using the provided listenProvider).\r\n *\r\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\r\n * events are returned to the caller rather than raised synchronously.\r\n *\r\n */\r\nclass SyncTree {\r\n /**\r\n * @param listenProvider_ - Used by SyncTree to start / stop listening\r\n * to server data.\r\n */\r\n constructor(listenProvider_) {\r\n this.listenProvider_ = listenProvider_;\r\n /**\r\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\r\n */\r\n this.syncPointTree_ = new ImmutableTree(null);\r\n /**\r\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\r\n */\r\n this.pendingWriteTree_ = newWriteTree();\r\n this.tagToQueryMap = new Map();\r\n this.queryToTagMap = new Map();\r\n }\r\n}\r\n/**\r\n * Apply the data changes for a user-generated set() or transaction() call.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {\r\n // Record pending write.\r\n writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);\r\n if (!visible) {\r\n return [];\r\n }\r\n else {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));\r\n }\r\n}\r\n/**\r\n * Apply the data from a user-generated update() call\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyUserMerge(syncTree, path, changedChildren, writeId) {\r\n // Record pending merge.\r\n writeTreeAddMerge(syncTree.pendingWriteTree_, path, changedChildren, writeId);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceUser(), path, changeTree));\r\n}\r\n/**\r\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\r\n *\r\n * @param revert - True if the given write failed and needs to be reverted\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAckUserWrite(syncTree, writeId, revert = false) {\r\n const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);\r\n const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);\r\n if (!needToReevaluate) {\r\n return [];\r\n }\r\n else {\r\n let affectedTree = new ImmutableTree(null);\r\n if (write.snap != null) {\r\n // overwrite\r\n affectedTree = affectedTree.set(newEmptyPath(), true);\r\n }\r\n else {\r\n each(write.children, (pathString) => {\r\n affectedTree = affectedTree.set(new Path(pathString), true);\r\n });\r\n }\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));\r\n }\r\n}\r\n/**\r\n * Apply new server data for the specified path..\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerOverwrite(syncTree, path, newData) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));\r\n}\r\n/**\r\n * Apply new server data to be merged in at the specified path.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyServerMerge(syncTree, path, changedChildren) {\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));\r\n}\r\n/**\r\n * Apply a listen complete for a query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyListenComplete(syncTree, path) {\r\n return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));\r\n}\r\n/**\r\n * Apply a listen complete for a tagged query\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedListenComplete(syncTree, path, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Remove event callback(s).\r\n *\r\n * If query is the default query, we'll check all queries for the specified eventRegistration.\r\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\r\n *\r\n * @param eventRegistration - If null, all callbacks are removed.\r\n * @param cancelError - If a cancelError is provided, appropriate cancel events will be returned.\r\n * @returns Cancel events, if cancelError was provided.\r\n */\r\nfunction syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError) {\r\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\r\n const path = query._path;\r\n const maybeSyncPoint = syncTree.syncPointTree_.get(path);\r\n let cancelEvents = [];\r\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\r\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\r\n // not loadsAllData().\r\n if (maybeSyncPoint &&\r\n (query._queryIdentifier === 'default' ||\r\n syncPointViewExistsForQuery(maybeSyncPoint, query))) {\r\n const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);\r\n if (syncPointIsEmpty(maybeSyncPoint)) {\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);\r\n }\r\n const removed = removedAndEvents.removed;\r\n cancelEvents = removedAndEvents.events;\r\n // We may have just removed one of many listeners and can short-circuit this whole process\r\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\r\n // properly set up.\r\n //\r\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\r\n // queryId === 'default'\r\n const removingDefault = -1 !==\r\n removed.findIndex(query => {\r\n return query._queryParams.loadsAllData();\r\n });\r\n const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));\r\n if (removingDefault && !covered) {\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\r\n // removal\r\n if (!subtree.isEmpty()) {\r\n // We need to fold over our subtree and collect the listeners to send\r\n const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);\r\n // Ok, we've collected all the listens we need. Set them up.\r\n for (let i = 0; i < newViews.length; ++i) {\r\n const view = newViews[i], newQuery = view.query;\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery_(syncTree, newQuery), listener.hashFn, listener.onComplete);\r\n }\r\n }\r\n }\r\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\r\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\r\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\r\n if (!covered && removed.length > 0 && !cancelError) {\r\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\r\n // default. Otherwise, we need to iterate through and cancel each individual query\r\n if (removingDefault) {\r\n // We don't tag default listeners\r\n const defaultTag = null;\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);\r\n }\r\n else {\r\n removed.forEach((queryToRemove) => {\r\n const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);\r\n });\r\n }\r\n }\r\n // Now, clear all of the tags we're tracking for the removed listens\r\n syncTreeRemoveTags_(syncTree, removed);\r\n }\r\n return cancelEvents;\r\n}\r\n/**\r\n * Apply new server data for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey != null) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // Query must have been removed already\r\n return [];\r\n }\r\n}\r\n/**\r\n * Apply server data to be merged in for the specified tagged query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {\r\n const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);\r\n if (queryKey) {\r\n const r = syncTreeParseQueryKey_(queryKey);\r\n const queryPath = r.path, queryId = r.queryId;\r\n const relativePath = newRelativePath(queryPath, path);\r\n const changeTree = ImmutableTree.fromObject(changedChildren);\r\n const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);\r\n return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);\r\n }\r\n else {\r\n // We've already removed the query. No big deal, ignore the update\r\n return [];\r\n }\r\n}\r\n/**\r\n * Add an event callback for the specified query.\r\n *\r\n * @returns Events to raise.\r\n */\r\nfunction syncTreeAddEventRegistration(syncTree, query, eventRegistration) {\r\n const path = query._path;\r\n let serverCache = null;\r\n let foundAncestorDefaultView = false;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(sp);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n foundAncestorDefaultView =\r\n foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let serverCacheComplete;\r\n if (serverCache != null) {\r\n serverCacheComplete = true;\r\n }\r\n else {\r\n serverCacheComplete = false;\r\n serverCache = ChildrenNode.EMPTY_NODE;\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n subtree.foreachChild((childName, childSyncPoint) => {\r\n const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());\r\n if (completeCache) {\r\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\r\n }\r\n });\r\n }\r\n const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);\r\n if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {\r\n // We need to track a tag for this query\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n assert(!syncTree.queryToTagMap.has(queryKey), 'View does not exist, but we have a tag');\r\n const tag = syncTreeGetNextQueryTag_();\r\n syncTree.queryToTagMap.set(queryKey, tag);\r\n syncTree.tagToQueryMap.set(tag, queryKey);\r\n }\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);\r\n let events = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);\r\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\r\n const view = syncPointViewForQuery(syncPoint, query);\r\n events = events.concat(syncTreeSetupListener_(syncTree, query, view));\r\n }\r\n return events;\r\n}\r\n/**\r\n * Returns a complete cache, if we have one, of the data at a particular path. If the location does not have a\r\n * listener above it, we will get a false \"null\". This shouldn't be a problem because transactions will always\r\n * have a listener above, and atomic operations would correctly show a jitter of ->\r\n * as the write is applied locally and then acknowledged at the server.\r\n *\r\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\r\n *\r\n * @param path - The path to the data we want\r\n * @param writeIdsToExclude - A specific set to be excluded\r\n */\r\nfunction syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {\r\n const includeHiddenSets = true;\r\n const writeTree = syncTree.pendingWriteTree_;\r\n const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {\r\n const relativePath = newRelativePath(pathSoFar, path);\r\n const serverCache = syncPointGetCompleteServerCache(syncPoint, relativePath);\r\n if (serverCache) {\r\n return serverCache;\r\n }\r\n });\r\n return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);\r\n}\r\nfunction syncTreeGetServerValue(syncTree, query) {\r\n const path = query._path;\r\n let serverCache = null;\r\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\r\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\r\n syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {\r\n const relativePath = newRelativePath(pathToSyncPoint, path);\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(sp, relativePath);\r\n });\r\n let syncPoint = syncTree.syncPointTree_.get(path);\r\n if (!syncPoint) {\r\n syncPoint = new SyncPoint();\r\n syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);\r\n }\r\n else {\r\n serverCache =\r\n serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n const serverCacheComplete = serverCache != null;\r\n const serverCacheNode = serverCacheComplete\r\n ? new CacheNode(serverCache, true, false)\r\n : null;\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);\r\n const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);\r\n return viewGetCompleteNode(view);\r\n}\r\n/**\r\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\r\n *\r\n * NOTES:\r\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\r\n *\r\n * - We call applyOperation() on each SyncPoint passing three things:\r\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\r\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\r\n * 3. A snapshot Node with cached server data, if we have it.\r\n *\r\n * - We concatenate all of the events returned by each SyncPoint and return the result.\r\n */\r\nfunction syncTreeApplyOperationToSyncPoints_(syncTree, operation) {\r\n return syncTreeApplyOperationHelper_(operation, syncTree.syncPointTree_, \r\n /*serverCache=*/ null, writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath()));\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n if (pathIsEmpty(operation.path)) {\r\n return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\r\n }\r\n else {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n const childName = pathGetFront(operation.path);\r\n const childOperation = operation.operationForChild(childName);\r\n const childTree = syncPointTree.children.get(childName);\r\n if (childTree && childOperation) {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n events = events.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n }\r\n}\r\n/**\r\n * Recursive helper for applyOperationToSyncPoints_\r\n */\r\nfunction syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {\r\n const syncPoint = syncPointTree.get(newEmptyPath());\r\n // If we don't have cached server data, see if we can get it from this SyncPoint.\r\n if (serverCache == null && syncPoint != null) {\r\n serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());\r\n }\r\n let events = [];\r\n syncPointTree.children.inorderTraversal((childName, childTree) => {\r\n const childServerCache = serverCache\r\n ? serverCache.getImmediateChild(childName)\r\n : null;\r\n const childWritesCache = writeTreeRefChild(writesCache, childName);\r\n const childOperation = operation.operationForChild(childName);\r\n if (childOperation) {\r\n events = events.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\r\n }\r\n });\r\n if (syncPoint) {\r\n events = events.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));\r\n }\r\n return events;\r\n}\r\nfunction syncTreeCreateListenerForView_(syncTree, view) {\r\n const query = view.query;\r\n const tag = syncTreeTagForQuery_(syncTree, query);\r\n return {\r\n hashFn: () => {\r\n const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;\r\n return cache.hash();\r\n },\r\n onComplete: (status) => {\r\n if (status === 'ok') {\r\n if (tag) {\r\n return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);\r\n }\r\n else {\r\n return syncTreeApplyListenComplete(syncTree, query._path);\r\n }\r\n }\r\n else {\r\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\r\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\r\n const error = errorForServerCode(status, query);\r\n return syncTreeRemoveEventRegistration(syncTree, query, \r\n /*eventRegistration*/ null, error);\r\n }\r\n }\r\n };\r\n}\r\n/**\r\n * Return the tag associated with the given query.\r\n */\r\nfunction syncTreeTagForQuery_(syncTree, query) {\r\n const queryKey = syncTreeMakeQueryKey_(query);\r\n return syncTree.queryToTagMap.get(queryKey);\r\n}\r\n/**\r\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\r\n */\r\nfunction syncTreeMakeQueryKey_(query) {\r\n return query._path.toString() + '$' + query._queryIdentifier;\r\n}\r\n/**\r\n * Return the query associated with the given tag, if we have one\r\n */\r\nfunction syncTreeQueryKeyForTag_(syncTree, tag) {\r\n return syncTree.tagToQueryMap.get(tag);\r\n}\r\n/**\r\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\r\n */\r\nfunction syncTreeParseQueryKey_(queryKey) {\r\n const splitIndex = queryKey.indexOf('$');\r\n assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\r\n return {\r\n queryId: queryKey.substr(splitIndex + 1),\r\n path: new Path(queryKey.substr(0, splitIndex))\r\n };\r\n}\r\n/**\r\n * A helper method to apply tagged operations\r\n */\r\nfunction syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {\r\n const syncPoint = syncTree.syncPointTree_.get(queryPath);\r\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\r\n const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);\r\n return syncPointApplyOperation(syncPoint, operation, writesCache, null);\r\n}\r\n/**\r\n * This collapses multiple unfiltered views into a single view, since we only need a single\r\n * listener for them.\r\n */\r\nfunction syncTreeCollectDistinctViewsForSubTree_(subtree) {\r\n return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n const completeView = syncPointGetCompleteView(maybeChildSyncPoint);\r\n return [completeView];\r\n }\r\n else {\r\n // No complete view here, flatten any deeper listens into an array\r\n let views = [];\r\n if (maybeChildSyncPoint) {\r\n views = syncPointGetQueryViews(maybeChildSyncPoint);\r\n }\r\n each(childMap, (_key, childViews) => {\r\n views = views.concat(childViews);\r\n });\r\n return views;\r\n }\r\n });\r\n}\r\n/**\r\n * Normalizes a query to a query we send the server for listening\r\n *\r\n * @returns The normalized query\r\n */\r\nfunction syncTreeQueryForListening_(query) {\r\n if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {\r\n // We treat queries that load all data as default queries\r\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\r\n // from Query\r\n return new (syncTreeGetReferenceConstructor())(query._repo, query._path);\r\n }\r\n else {\r\n return query;\r\n }\r\n}\r\nfunction syncTreeRemoveTags_(syncTree, queries) {\r\n for (let j = 0; j < queries.length; ++j) {\r\n const removedQuery = queries[j];\r\n if (!removedQuery._queryParams.loadsAllData()) {\r\n // We should have a tag for this\r\n const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);\r\n const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);\r\n syncTree.queryToTagMap.delete(removedQueryKey);\r\n syncTree.tagToQueryMap.delete(removedQueryTag);\r\n }\r\n }\r\n}\r\n/**\r\n * Static accessor for query tags.\r\n */\r\nfunction syncTreeGetNextQueryTag_() {\r\n return syncTreeNextQueryTag_++;\r\n}\r\n/**\r\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\r\n *\r\n * @returns This method can return events to support synchronous data sources\r\n */\r\nfunction syncTreeSetupListener_(syncTree, query, view) {\r\n const path = query._path;\r\n const tag = syncTreeTagForQuery_(syncTree, query);\r\n const listener = syncTreeCreateListenerForView_(syncTree, view);\r\n const events = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);\r\n const subtree = syncTree.syncPointTree_.subtree(path);\r\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\r\n // may need to shadow other listens as well.\r\n if (tag) {\r\n assert(!syncPointHasCompleteView(subtree.value), \"If we're adding a query, it shouldn't be shadowed\");\r\n }\r\n else {\r\n // Shadow everything at or below this location, this is a default listener.\r\n const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {\r\n if (!pathIsEmpty(relativePath) &&\r\n maybeChildSyncPoint &&\r\n syncPointHasCompleteView(maybeChildSyncPoint)) {\r\n return [syncPointGetCompleteView(maybeChildSyncPoint).query];\r\n }\r\n else {\r\n // No default listener here, flatten any deeper queries into an array\r\n let queries = [];\r\n if (maybeChildSyncPoint) {\r\n queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map(view => view.query));\r\n }\r\n each(childMap, (_key, childQueries) => {\r\n queries = queries.concat(childQueries);\r\n });\r\n return queries;\r\n }\r\n });\r\n for (let i = 0; i < queriesToStop.length; ++i) {\r\n const queryToStop = queriesToStop[i];\r\n syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery_(syncTree, queryToStop));\r\n }\r\n }\r\n return events;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass ExistingValueProvider {\r\n constructor(node_) {\r\n this.node_ = node_;\r\n }\r\n getImmediateChild(childName) {\r\n const child = this.node_.getImmediateChild(childName);\r\n return new ExistingValueProvider(child);\r\n }\r\n node() {\r\n return this.node_;\r\n }\r\n}\r\nclass DeferredValueProvider {\r\n constructor(syncTree, path) {\r\n this.syncTree_ = syncTree;\r\n this.path_ = path;\r\n }\r\n getImmediateChild(childName) {\r\n const childPath = pathChild(this.path_, childName);\r\n return new DeferredValueProvider(this.syncTree_, childPath);\r\n }\r\n node() {\r\n return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);\r\n }\r\n}\r\n/**\r\n * Generate placeholders for deferred values.\r\n */\r\nconst generateWithValues = function (values) {\r\n values = values || {};\r\n values['timestamp'] = values['timestamp'] || new Date().getTime();\r\n return values;\r\n};\r\n/**\r\n * Value to use when firing local events. When writing server values, fire\r\n * local events with an approximate value, otherwise return value as-is.\r\n */\r\nconst resolveDeferredLeafValue = function (value, existingVal, serverValues) {\r\n if (!value || typeof value !== 'object') {\r\n return value;\r\n }\r\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\r\n if (typeof value['.sv'] === 'string') {\r\n return resolveScalarDeferredValue(value['.sv'], existingVal, serverValues);\r\n }\r\n else if (typeof value['.sv'] === 'object') {\r\n return resolveComplexDeferredValue(value['.sv'], existingVal);\r\n }\r\n else {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(value, null, 2));\r\n }\r\n};\r\nconst resolveScalarDeferredValue = function (op, existing, serverValues) {\r\n switch (op) {\r\n case 'timestamp':\r\n return serverValues['timestamp'];\r\n default:\r\n assert(false, 'Unexpected server value: ' + op);\r\n }\r\n};\r\nconst resolveComplexDeferredValue = function (op, existing, unused) {\r\n if (!op.hasOwnProperty('increment')) {\r\n assert(false, 'Unexpected server value: ' + JSON.stringify(op, null, 2));\r\n }\r\n const delta = op['increment'];\r\n if (typeof delta !== 'number') {\r\n assert(false, 'Unexpected increment value: ' + delta);\r\n }\r\n const existingNode = existing.node();\r\n assert(existingNode !== null && typeof existingNode !== 'undefined', 'Expected ChildrenNode.EMPTY_NODE for nulls');\r\n // Incrementing a non-number sets the value to the incremented amount\r\n if (!existingNode.isLeafNode()) {\r\n return delta;\r\n }\r\n const leaf = existingNode;\r\n const existingVal = leaf.getValue();\r\n if (typeof existingVal !== 'number') {\r\n return delta;\r\n }\r\n // No need to do over/underflow arithmetic here because JS only handles floats under the covers\r\n return existingVal + delta;\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the tree with the\r\n * specified generated replacement values.\r\n * @param path - path to which write is relative\r\n * @param node - new data written at path\r\n * @param syncTree - current data\r\n */\r\nconst resolveDeferredValueTree = function (path, node, syncTree, serverValues) {\r\n return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);\r\n};\r\n/**\r\n * Recursively replace all deferred values and priorities in the node with the\r\n * specified generated replacement values. If there are no server values in the node,\r\n * it'll be returned as-is.\r\n */\r\nconst resolveDeferredValueSnapshot = function (node, existing, serverValues) {\r\n return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);\r\n};\r\nfunction resolveDeferredValue(node, existingVal, serverValues) {\r\n const rawPri = node.getPriority().val();\r\n const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild('.priority'), serverValues);\r\n let newNode;\r\n if (node.isLeafNode()) {\r\n const leafNode = node;\r\n const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);\r\n if (value !== leafNode.getValue() ||\r\n priority !== leafNode.getPriority().val()) {\r\n return new LeafNode(value, nodeFromJSON(priority));\r\n }\r\n else {\r\n return node;\r\n }\r\n }\r\n else {\r\n const childrenNode = node;\r\n newNode = childrenNode;\r\n if (priority !== childrenNode.getPriority().val()) {\r\n newNode = newNode.updatePriority(new LeafNode(priority));\r\n }\r\n childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {\r\n const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);\r\n if (newChildNode !== childNode) {\r\n newNode = newNode.updateImmediateChild(childName, newChildNode);\r\n }\r\n });\r\n return newNode;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A light-weight tree, traversable by path. Nodes can have both values and children.\r\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\r\n * children.\r\n */\r\nclass Tree {\r\n /**\r\n * @param name - Optional name of the node.\r\n * @param parent - Optional parent node.\r\n * @param node - Optional node to wrap.\r\n */\r\n constructor(name = '', parent = null, node = { children: {}, childCount: 0 }) {\r\n this.name = name;\r\n this.parent = parent;\r\n this.node = node;\r\n }\r\n}\r\n/**\r\n * Returns a sub-Tree for the given path.\r\n *\r\n * @param pathObj - Path to look up.\r\n * @returns Tree for path.\r\n */\r\nfunction treeSubTree(tree, pathObj) {\r\n // TODO: Require pathObj to be Path?\r\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\r\n let child = tree, next = pathGetFront(path);\r\n while (next !== null) {\r\n const childNode = safeGet(child.node.children, next) || {\r\n children: {},\r\n childCount: 0\r\n };\r\n child = new Tree(next, child, childNode);\r\n path = pathPopFront(path);\r\n next = pathGetFront(path);\r\n }\r\n return child;\r\n}\r\n/**\r\n * Returns the data associated with this tree node.\r\n *\r\n * @returns The data or null if no data exists.\r\n */\r\nfunction treeGetValue(tree) {\r\n return tree.node.value;\r\n}\r\n/**\r\n * Sets data to this tree node.\r\n *\r\n * @param value - Value to set.\r\n */\r\nfunction treeSetValue(tree, value) {\r\n tree.node.value = value;\r\n treeUpdateParents(tree);\r\n}\r\n/**\r\n * @returns Whether the tree has any children.\r\n */\r\nfunction treeHasChildren(tree) {\r\n return tree.node.childCount > 0;\r\n}\r\n/**\r\n * @returns Whethe rthe tree is empty (no value or children).\r\n */\r\nfunction treeIsEmpty(tree) {\r\n return treeGetValue(tree) === undefined && !treeHasChildren(tree);\r\n}\r\n/**\r\n * Calls action for each child of this tree node.\r\n *\r\n * @param action - Action to be called for each child.\r\n */\r\nfunction treeForEachChild(tree, action) {\r\n each(tree.node.children, (child, childTree) => {\r\n action(new Tree(child, tree, childTree));\r\n });\r\n}\r\n/**\r\n * Does a depth-first traversal of this node's descendants, calling action for each one.\r\n *\r\n * @param action - Action to be called for each child.\r\n * @param includeSelf - Whether to call action on this node as well. Defaults to\r\n * false.\r\n * @param childrenFirst - Whether to call action on children before calling it on\r\n * parent.\r\n */\r\nfunction treeForEachDescendant(tree, action, includeSelf, childrenFirst) {\r\n if (includeSelf && !childrenFirst) {\r\n action(tree);\r\n }\r\n treeForEachChild(tree, child => {\r\n treeForEachDescendant(child, action, true, childrenFirst);\r\n });\r\n if (includeSelf && childrenFirst) {\r\n action(tree);\r\n }\r\n}\r\n/**\r\n * Calls action on each ancestor node.\r\n *\r\n * @param action - Action to be called on each parent; return\r\n * true to abort.\r\n * @param includeSelf - Whether to call action on this node as well.\r\n * @returns true if the action callback returned true.\r\n */\r\nfunction treeForEachAncestor(tree, action, includeSelf) {\r\n let node = includeSelf ? tree : tree.parent;\r\n while (node !== null) {\r\n if (action(node)) {\r\n return true;\r\n }\r\n node = node.parent;\r\n }\r\n return false;\r\n}\r\n/**\r\n * @returns The path of this tree node, as a Path.\r\n */\r\nfunction treeGetPath(tree) {\r\n return new Path(tree.parent === null\r\n ? tree.name\r\n : treeGetPath(tree.parent) + '/' + tree.name);\r\n}\r\n/**\r\n * Adds or removes this child from its parent based on whether it's empty or not.\r\n */\r\nfunction treeUpdateParents(tree) {\r\n if (tree.parent !== null) {\r\n treeUpdateChild(tree.parent, tree.name, tree);\r\n }\r\n}\r\n/**\r\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\r\n *\r\n * @param childName - The name of the child to update.\r\n * @param child - The child to update.\r\n */\r\nfunction treeUpdateChild(tree, childName, child) {\r\n const childEmpty = treeIsEmpty(child);\r\n const childExists = contains(tree.node.children, childName);\r\n if (childEmpty && childExists) {\r\n delete tree.node.children[childName];\r\n tree.node.childCount--;\r\n treeUpdateParents(tree);\r\n }\r\n else if (!childEmpty && !childExists) {\r\n tree.node.children[childName] = child.node;\r\n tree.node.childCount++;\r\n treeUpdateParents(tree);\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * True for invalid Firebase keys\r\n */\r\nconst INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * True for invalid Firebase paths.\r\n * Allows '/' in paths.\r\n */\r\nconst INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\r\n/**\r\n * Maximum number of characters to allow in leaf value\r\n */\r\nconst MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\r\nconst isValidKey = function (key) {\r\n return (typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key));\r\n};\r\nconst isValidPathString = function (pathString) {\r\n return (typeof pathString === 'string' &&\r\n pathString.length !== 0 &&\r\n !INVALID_PATH_REGEX_.test(pathString));\r\n};\r\nconst isValidRootPathString = function (pathString) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n return isValidPathString(pathString);\r\n};\r\nconst isValidPriority = function (priority) {\r\n return (priority === null ||\r\n typeof priority === 'string' ||\r\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\r\n (priority &&\r\n typeof priority === 'object' &&\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n contains(priority, '.sv')));\r\n};\r\n/**\r\n * Pre-validate a datum passed as an argument to Firebase function.\r\n */\r\nconst validateFirebaseDataArg = function (fnName, value, path, optional) {\r\n if (optional && value === undefined) {\r\n return;\r\n }\r\n validateFirebaseData(errorPrefix(fnName, 'value'), value, path);\r\n};\r\n/**\r\n * Validate a data object client-side before sending to server.\r\n */\r\nconst validateFirebaseData = function (errorPrefix, data, path_) {\r\n const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\r\n if (data === undefined) {\r\n throw new Error(errorPrefix + 'contains undefined ' + validationPathToErrorString(path));\r\n }\r\n if (typeof data === 'function') {\r\n throw new Error(errorPrefix +\r\n 'contains a function ' +\r\n validationPathToErrorString(path) +\r\n ' with contents = ' +\r\n data.toString());\r\n }\r\n if (isInvalidJSONNumber(data)) {\r\n throw new Error(errorPrefix +\r\n 'contains ' +\r\n data.toString() +\r\n ' ' +\r\n validationPathToErrorString(path));\r\n }\r\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\r\n if (typeof data === 'string' &&\r\n data.length > MAX_LEAF_SIZE_ / 3 &&\r\n stringLength(data) > MAX_LEAF_SIZE_) {\r\n throw new Error(errorPrefix +\r\n 'contains a string greater than ' +\r\n MAX_LEAF_SIZE_ +\r\n ' utf8 bytes ' +\r\n validationPathToErrorString(path) +\r\n \" ('\" +\r\n data.substring(0, 50) +\r\n \"...')\");\r\n }\r\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\r\n // to save extra walking of large objects.\r\n if (data && typeof data === 'object') {\r\n let hasDotValue = false;\r\n let hasActualChild = false;\r\n each(data, (key, value) => {\r\n if (key === '.value') {\r\n hasDotValue = true;\r\n }\r\n else if (key !== '.priority' && key !== '.sv') {\r\n hasActualChild = true;\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix +\r\n ' contains an invalid key (' +\r\n key +\r\n ') ' +\r\n validationPathToErrorString(path) +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n validationPathPush(path, key);\r\n validateFirebaseData(errorPrefix, value, path);\r\n validationPathPop(path);\r\n });\r\n if (hasDotValue && hasActualChild) {\r\n throw new Error(errorPrefix +\r\n ' contains \".value\" child ' +\r\n validationPathToErrorString(path) +\r\n ' in addition to actual children.');\r\n }\r\n }\r\n};\r\n/**\r\n * Pre-validate paths passed in the firebase function.\r\n */\r\nconst validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\r\n let i, curPath;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n const keys = pathSlice(curPath);\r\n for (let j = 0; j < keys.length; j++) {\r\n if (keys[j] === '.priority' && j === keys.length - 1) ;\r\n else if (!isValidKey(keys[j])) {\r\n throw new Error(errorPrefix +\r\n 'contains an invalid key (' +\r\n keys[j] +\r\n ') in path ' +\r\n curPath.toString() +\r\n '. Keys must be non-empty strings ' +\r\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\r\n }\r\n }\r\n }\r\n // Check that update keys are not descendants of each other.\r\n // We rely on the property that sorting guarantees that ancestors come\r\n // right before descendants.\r\n mergePaths.sort(pathCompare);\r\n let prevPath = null;\r\n for (i = 0; i < mergePaths.length; i++) {\r\n curPath = mergePaths[i];\r\n if (prevPath !== null && pathContains(prevPath, curPath)) {\r\n throw new Error(errorPrefix +\r\n 'contains a path ' +\r\n prevPath.toString() +\r\n ' that is ancestor of another path ' +\r\n curPath.toString());\r\n }\r\n prevPath = curPath;\r\n }\r\n};\r\n/**\r\n * pre-validate an object passed as an argument to firebase function (\r\n * must be an object - e.g. for firebase.update()).\r\n */\r\nconst validateFirebaseMergeDataArg = function (fnName, data, path, optional) {\r\n if (optional && data === undefined) {\r\n return;\r\n }\r\n const errorPrefix$1 = errorPrefix(fnName, 'values');\r\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\r\n throw new Error(errorPrefix$1 + ' must be an object containing the children to replace.');\r\n }\r\n const mergePaths = [];\r\n each(data, (key, value) => {\r\n const curPath = new Path(key);\r\n validateFirebaseData(errorPrefix$1, value, pathChild(path, curPath));\r\n if (pathGetBack(curPath) === '.priority') {\r\n if (!isValidPriority(value)) {\r\n throw new Error(errorPrefix$1 +\r\n \"contains an invalid value for '\" +\r\n curPath.toString() +\r\n \"', which must be a valid \" +\r\n 'Firebase priority (a string, finite number, server value, or null).');\r\n }\r\n }\r\n mergePaths.push(curPath);\r\n });\r\n validateFirebaseMergePaths(errorPrefix$1, mergePaths);\r\n};\r\nconst validatePriority = function (fnName, priority, optional) {\r\n if (optional && priority === undefined) {\r\n return;\r\n }\r\n if (isInvalidJSONNumber(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'is ' +\r\n priority.toString() +\r\n ', but must be a valid Firebase priority (a string, finite number, ' +\r\n 'server value, or null).');\r\n }\r\n // Special case to allow importing data with a .sv.\r\n if (!isValidPriority(priority)) {\r\n throw new Error(errorPrefix(fnName, 'priority') +\r\n 'must be a valid Firebase priority ' +\r\n '(a string, finite number, server value, or null).');\r\n }\r\n};\r\nconst validateKey = function (fnName, argumentName, key, optional) {\r\n if (optional && key === undefined) {\r\n return;\r\n }\r\n if (!isValidKey(key)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid key = \"' +\r\n key +\r\n '\". Firebase keys must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\r\n }\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validatePathString = function (fnName, argumentName, pathString, optional) {\r\n if (optional && pathString === undefined) {\r\n return;\r\n }\r\n if (!isValidPathString(pathString)) {\r\n throw new Error(errorPrefix(fnName, argumentName) +\r\n 'was an invalid path = \"' +\r\n pathString +\r\n '\". Paths must be non-empty strings and ' +\r\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\r\n }\r\n};\r\nconst validateRootPathString = function (fnName, argumentName, pathString, optional) {\r\n if (pathString) {\r\n // Allow '/.info/' at the beginning.\r\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\r\n }\r\n validatePathString(fnName, argumentName, pathString, optional);\r\n};\r\n/**\r\n * @internal\r\n */\r\nconst validateWritablePath = function (fnName, path) {\r\n if (pathGetFront(path) === '.info') {\r\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\r\n }\r\n};\r\nconst validateUrl = function (fnName, parsedUrl) {\r\n // TODO = Validate server better.\r\n const pathString = parsedUrl.path.toString();\r\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\r\n parsedUrl.repoInfo.host.length === 0 ||\r\n (!isValidKey(parsedUrl.repoInfo.namespace) &&\r\n parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\r\n (pathString.length !== 0 && !isValidRootPathString(pathString))) {\r\n throw new Error(errorPrefix(fnName, 'url') +\r\n 'must be a valid firebase URL and ' +\r\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\r\n }\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The event queue serves a few purposes:\r\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\r\n * events being queued.\r\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\r\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\r\n * left off, ensuring that the events are still raised synchronously and in order.\r\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\r\n * events are raised synchronously.\r\n *\r\n * NOTE: This can all go away if/when we move to async events.\r\n *\r\n */\r\nclass EventQueue {\r\n constructor() {\r\n this.eventLists_ = [];\r\n /**\r\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\r\n */\r\n this.recursionDepth_ = 0;\r\n }\r\n}\r\n/**\r\n * @param eventDataList - The new events to queue.\r\n */\r\nfunction eventQueueQueueEvents(eventQueue, eventDataList) {\r\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\r\n let currList = null;\r\n for (let i = 0; i < eventDataList.length; i++) {\r\n const data = eventDataList[i];\r\n const path = data.getPath();\r\n if (currList !== null && !pathEquals(path, currList.path)) {\r\n eventQueue.eventLists_.push(currList);\r\n currList = null;\r\n }\r\n if (currList === null) {\r\n currList = { events: [], path };\r\n }\r\n currList.events.push(data);\r\n }\r\n if (currList) {\r\n eventQueue.eventLists_.push(currList);\r\n }\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones)\r\n * for the specified path.\r\n *\r\n * It is assumed that the new events are all for the specified path.\r\n *\r\n * @param path - The path to raise events for.\r\n * @param eventDataList - The new events to raise.\r\n */\r\nfunction eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathEquals(eventPath, path));\r\n}\r\n/**\r\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\r\n * locations related to the specified change path (i.e. all ancestors and descendants).\r\n *\r\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\r\n *\r\n * @param changedPath - The path to raise events for.\r\n * @param eventDataList - The events to raise\r\n */\r\nfunction eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {\r\n eventQueueQueueEvents(eventQueue, eventDataList);\r\n eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, eventPath => pathContains(eventPath, changedPath) ||\r\n pathContains(changedPath, eventPath));\r\n}\r\nfunction eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {\r\n eventQueue.recursionDepth_++;\r\n let sentAll = true;\r\n for (let i = 0; i < eventQueue.eventLists_.length; i++) {\r\n const eventList = eventQueue.eventLists_[i];\r\n if (eventList) {\r\n const eventPath = eventList.path;\r\n if (predicate(eventPath)) {\r\n eventListRaise(eventQueue.eventLists_[i]);\r\n eventQueue.eventLists_[i] = null;\r\n }\r\n else {\r\n sentAll = false;\r\n }\r\n }\r\n }\r\n if (sentAll) {\r\n eventQueue.eventLists_ = [];\r\n }\r\n eventQueue.recursionDepth_--;\r\n}\r\n/**\r\n * Iterates through the list and raises each event\r\n */\r\nfunction eventListRaise(eventList) {\r\n for (let i = 0; i < eventList.events.length; i++) {\r\n const eventData = eventList.events[i];\r\n if (eventData !== null) {\r\n eventList.events[i] = null;\r\n const eventFn = eventData.getEventRunner();\r\n if (logger) {\r\n log('event: ' + eventData.toString());\r\n }\r\n exceptionGuard(eventFn);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst INTERRUPT_REASON = 'repo_interrupt';\r\n/**\r\n * If a transaction does not succeed after 25 retries, we abort it. Among other\r\n * things this ensure that if there's ever a bug causing a mismatch between\r\n * client / server hashes for some data, we won't retry indefinitely.\r\n */\r\nconst MAX_TRANSACTION_RETRIES = 25;\r\n/**\r\n * A connection to a single data repository.\r\n */\r\nclass Repo {\r\n constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {\r\n this.repoInfo_ = repoInfo_;\r\n this.forceRestClient_ = forceRestClient_;\r\n this.authTokenProvider_ = authTokenProvider_;\r\n this.appCheckProvider_ = appCheckProvider_;\r\n this.dataUpdateCount = 0;\r\n this.statsListener_ = null;\r\n this.eventQueue_ = new EventQueue();\r\n this.nextWriteId_ = 1;\r\n this.interceptServerDataCallback_ = null;\r\n /** A list of data pieces and paths to be set when this client disconnects. */\r\n this.onDisconnect_ = newSparseSnapshotTree();\r\n /** Stores queues of outstanding transactions for Firebase locations. */\r\n this.transactionQueueTree_ = new Tree();\r\n // TODO: This should be @private but it's used by test_access.js and internal.js\r\n this.persistentConnection_ = null;\r\n // This key is intentionally not updated if RepoInfo is later changed or replaced\r\n this.key = this.repoInfo_.toURLString();\r\n }\r\n /**\r\n * @returns The URL corresponding to the root of this Firebase.\r\n */\r\n toString() {\r\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\r\n }\r\n}\r\nfunction repoStart(repo, appId, authOverride) {\r\n repo.stats_ = statsManagerGetCollection(repo.repoInfo_);\r\n if (repo.forceRestClient_ || beingCrawled()) {\r\n repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_);\r\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\r\n setTimeout(() => repoOnConnectStatus(repo, /* connectStatus= */ true), 0);\r\n }\r\n else {\r\n // Validate authOverride\r\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\r\n if (typeof authOverride !== 'object') {\r\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\r\n }\r\n try {\r\n stringify(authOverride);\r\n }\r\n catch (e) {\r\n throw new Error('Invalid authOverride provided: ' + e);\r\n }\r\n }\r\n repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {\r\n repoOnDataUpdate(repo, pathString, data, isMerge, tag);\r\n }, (connectStatus) => {\r\n repoOnConnectStatus(repo, connectStatus);\r\n }, (updates) => {\r\n repoOnServerInfoUpdate(repo, updates);\r\n }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);\r\n repo.server_ = repo.persistentConnection_;\r\n }\r\n repo.authTokenProvider_.addTokenChangeListener(token => {\r\n repo.server_.refreshAuthToken(token);\r\n });\r\n repo.appCheckProvider_.addTokenChangeListener(result => {\r\n repo.server_.refreshAppCheckToken(result.token);\r\n });\r\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\r\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\r\n repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));\r\n // Used for .info.\r\n repo.infoData_ = new SnapshotHolder();\r\n repo.infoSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n let infoEvents = [];\r\n const node = repo.infoData_.getNode(query._path);\r\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\r\n // on initial data...\r\n if (!node.isEmpty()) {\r\n infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);\r\n setTimeout(() => {\r\n onComplete('ok');\r\n }, 0);\r\n }\r\n return infoEvents;\r\n },\r\n stopListening: () => { }\r\n });\r\n repoUpdateInfo(repo, 'connected', false);\r\n repo.serverSyncTree_ = new SyncTree({\r\n startListening: (query, tag, currentHashFn, onComplete) => {\r\n repo.server_.listen(query, currentHashFn, tag, (status, data) => {\r\n const events = onComplete(status, data);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events);\r\n });\r\n // No synchronous events for network-backed sync trees\r\n return [];\r\n },\r\n stopListening: (query, tag) => {\r\n repo.server_.unlisten(query, tag);\r\n }\r\n });\r\n}\r\n/**\r\n * @returns The time in milliseconds, taking the server offset into account if we have one.\r\n */\r\nfunction repoServerTime(repo) {\r\n const offsetNode = repo.infoData_.getNode(new Path('.info/serverTimeOffset'));\r\n const offset = offsetNode.val() || 0;\r\n return new Date().getTime() + offset;\r\n}\r\n/**\r\n * Generate ServerValues using some variables from the repo object.\r\n */\r\nfunction repoGenerateServerValues(repo) {\r\n return generateWithValues({\r\n timestamp: repoServerTime(repo)\r\n });\r\n}\r\n/**\r\n * Called by realtime when we get new messages from the server.\r\n */\r\nfunction repoOnDataUpdate(repo, pathString, data, isMerge, tag) {\r\n // For testing.\r\n repo.dataUpdateCount++;\r\n const path = new Path(pathString);\r\n data = repo.interceptServerDataCallback_\r\n ? repo.interceptServerDataCallback_(pathString, data)\r\n : data;\r\n let events = [];\r\n if (tag) {\r\n if (isMerge) {\r\n const taggedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);\r\n }\r\n else {\r\n const taggedSnap = nodeFromJSON(data);\r\n events = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);\r\n }\r\n }\r\n else if (isMerge) {\r\n const changedChildren = map(data, (raw) => nodeFromJSON(raw));\r\n events = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);\r\n }\r\n else {\r\n const snap = nodeFromJSON(data);\r\n events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);\r\n }\r\n let affectedPath = path;\r\n if (events.length > 0) {\r\n // Since we have a listener outstanding for each transaction, receiving any events\r\n // is a proxy for some change having occurred.\r\n affectedPath = repoRerunTransactions(repo, path);\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events);\r\n}\r\nfunction repoOnConnectStatus(repo, connectStatus) {\r\n repoUpdateInfo(repo, 'connected', connectStatus);\r\n if (connectStatus === false) {\r\n repoRunOnDisconnectEvents(repo);\r\n }\r\n}\r\nfunction repoOnServerInfoUpdate(repo, updates) {\r\n each(updates, (key, value) => {\r\n repoUpdateInfo(repo, key, value);\r\n });\r\n}\r\nfunction repoUpdateInfo(repo, pathString, value) {\r\n const path = new Path('/.info/' + pathString);\r\n const newNode = nodeFromJSON(value);\r\n repo.infoData_.updateSnapshot(path, newNode);\r\n const events = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n}\r\nfunction repoGetNextWriteId(repo) {\r\n return repo.nextWriteId_++;\r\n}\r\n/**\r\n * The purpose of `getValue` is to return the latest known value\r\n * satisfying `query`.\r\n *\r\n * This method will first check for in-memory cached values\r\n * belonging to active listeners. If they are found, such values\r\n * are considered to be the most up-to-date.\r\n *\r\n * If the client is not connected, this method will try to\r\n * establish a connection and request the value for `query`. If\r\n * the client is not able to retrieve the query result, it reports\r\n * an error.\r\n *\r\n * @param query - The query to surface a value for.\r\n */\r\nfunction repoGetValue(repo, query) {\r\n // Only active queries are cached. There is no persisted cache.\r\n const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);\r\n if (cached != null) {\r\n return Promise.resolve(cached);\r\n }\r\n return repo.server_.get(query).then(payload => {\r\n const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());\r\n const events = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n return Promise.resolve(node);\r\n }, err => {\r\n repoLog(repo, 'get for query ' + stringify(query) + ' failed: ' + err);\r\n return Promise.reject(new Error(err));\r\n });\r\n}\r\nfunction repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {\r\n repoLog(repo, 'set', {\r\n path: path.toString(),\r\n value: newVal,\r\n priority: newPriority\r\n });\r\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\r\n // (b) store unresolved paths on JSON parse\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\r\n const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('set at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);\r\n}\r\nfunction repoUpdate(repo, path, childrenToMerge, onComplete) {\r\n repoLog(repo, 'update', { path: path.toString(), value: childrenToMerge });\r\n // Start with our existing data and merge each child into it.\r\n let empty = true;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const changedChildren = {};\r\n each(childrenToMerge, (changedKey, changedValue) => {\r\n empty = false;\r\n changedChildren[changedKey] = resolveDeferredValueTree(pathChild(path, changedKey), nodeFromJSON(changedValue), repo.serverSyncTree_, serverValues);\r\n });\r\n if (!empty) {\r\n const writeId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserMerge(repo.serverSyncTree_, path, changedChildren, writeId);\r\n eventQueueQueueEvents(repo.eventQueue_, events);\r\n repo.server_.merge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n const success = status === 'ok';\r\n if (!success) {\r\n warn('update at ' + path + ' failed: ' + status);\r\n }\r\n const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);\r\n const affectedPath = clearEvents.length > 0 ? repoRerunTransactions(repo, path) : path;\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, clearEvents);\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n each(childrenToMerge, (changedPath) => {\r\n const affectedPath = repoAbortTransactions(repo, pathChild(path, changedPath));\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n // We queued the events above, so just flush the queue here\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, []);\r\n }\r\n else {\r\n log(\"update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n }\r\n}\r\n/**\r\n * Applies all of the changes stored up in the onDisconnect_ tree.\r\n */\r\nfunction repoRunOnDisconnectEvents(repo) {\r\n repoLog(repo, 'onDisconnectEvents');\r\n const serverValues = repoGenerateServerValues(repo);\r\n const resolvedOnDisconnectTree = newSparseSnapshotTree();\r\n sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {\r\n const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);\r\n sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);\r\n });\r\n let events = [];\r\n sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {\r\n events = events.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));\r\n const affectedPath = repoAbortTransactions(repo, path);\r\n repoRerunTransactions(repo, affectedPath);\r\n });\r\n repo.onDisconnect_ = newSparseSnapshotTree();\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events);\r\n}\r\nfunction repoOnDisconnectCancel(repo, path, onComplete) {\r\n repo.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeForget(repo.onDisconnect_, path);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSet(repo, path, value, onComplete) {\r\n const newNode = nodeFromJSON(value);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectSetWithPriority(repo, path, value, priority, onComplete) {\r\n const newNode = nodeFromJSON(value, priority);\r\n repo.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), (status, errorReason) => {\r\n if (status === 'ok') {\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, path, newNode);\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoOnDisconnectUpdate(repo, path, childrenToMerge, onComplete) {\r\n if (isEmpty(childrenToMerge)) {\r\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\r\n repoCallOnCompleteCallback(repo, onComplete, 'ok', undefined);\r\n return;\r\n }\r\n repo.server_.onDisconnectMerge(path.toString(), childrenToMerge, (status, errorReason) => {\r\n if (status === 'ok') {\r\n each(childrenToMerge, (childName, childNode) => {\r\n const newChildNode = nodeFromJSON(childNode);\r\n sparseSnapshotTreeRemember(repo.onDisconnect_, pathChild(path, childName), newChildNode);\r\n });\r\n }\r\n repoCallOnCompleteCallback(repo, onComplete, status, errorReason);\r\n });\r\n}\r\nfunction repoAddEventCallbackForQuery(repo, query, eventRegistration) {\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {\r\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\r\n // a little bit by handling the return values anyways.\r\n let events;\r\n if (pathGetFront(query._path) === '.info') {\r\n events = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);\r\n }\r\n else {\r\n events = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);\r\n }\r\n eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events);\r\n}\r\nfunction repoInterrupt(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.interrupt(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoResume(repo) {\r\n if (repo.persistentConnection_) {\r\n repo.persistentConnection_.resume(INTERRUPT_REASON);\r\n }\r\n}\r\nfunction repoLog(repo, ...varArgs) {\r\n let prefix = '';\r\n if (repo.persistentConnection_) {\r\n prefix = repo.persistentConnection_.id + ':';\r\n }\r\n log(prefix, ...varArgs);\r\n}\r\nfunction repoCallOnCompleteCallback(repo, callback, status, errorReason) {\r\n if (callback) {\r\n exceptionGuard(() => {\r\n if (status === 'ok') {\r\n callback(null);\r\n }\r\n else {\r\n const code = (status || 'error').toUpperCase();\r\n let message = code;\r\n if (errorReason) {\r\n message += ': ' + errorReason;\r\n }\r\n const error = new Error(message);\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n error.code = code;\r\n callback(error);\r\n }\r\n });\r\n }\r\n}\r\n/**\r\n * Creates a new transaction, adds it to the transactions we're tracking, and\r\n * sends it to the server if possible.\r\n *\r\n * @param path - Path at which to do transaction.\r\n * @param transactionUpdate - Update callback.\r\n * @param onComplete - Completion callback.\r\n * @param unwatcher - Function that will be called when the transaction no longer\r\n * need data updates for `path`.\r\n * @param applyLocally - Whether or not to make intermediate results visible\r\n */\r\nfunction repoStartTransaction(repo, path, transactionUpdate, onComplete, unwatcher, applyLocally) {\r\n repoLog(repo, 'transaction on ' + path);\r\n // Initialize transaction.\r\n const transaction = {\r\n path,\r\n update: transactionUpdate,\r\n onComplete,\r\n // One of TransactionStatus enums.\r\n status: null,\r\n // Used when combining transactions at different locations to figure out\r\n // which one goes first.\r\n order: LUIDGenerator(),\r\n // Whether to raise local events for this transaction.\r\n applyLocally,\r\n // Count of how many times we've retried the transaction.\r\n retryCount: 0,\r\n // Function to call to clean up our .on() listener.\r\n unwatcher,\r\n // Stores why a transaction was aborted.\r\n abortReason: null,\r\n currentWriteId: null,\r\n currentInputSnapshot: null,\r\n currentOutputSnapshotRaw: null,\r\n currentOutputSnapshotResolved: null\r\n };\r\n // Run transaction initially.\r\n const currentState = repoGetLatestState(repo, path, undefined);\r\n transaction.currentInputSnapshot = currentState;\r\n const newVal = transaction.update(currentState.val());\r\n if (newVal === undefined) {\r\n // Abort transaction.\r\n transaction.unwatcher();\r\n transaction.currentOutputSnapshotRaw = null;\r\n transaction.currentOutputSnapshotResolved = null;\r\n if (transaction.onComplete) {\r\n transaction.onComplete(null, false, transaction.currentInputSnapshot);\r\n }\r\n }\r\n else {\r\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\r\n // Mark as run and add to our queue.\r\n transaction.status = 0 /* RUN */;\r\n const queueNode = treeSubTree(repo.transactionQueueTree_, path);\r\n const nodeQueue = treeGetValue(queueNode) || [];\r\n nodeQueue.push(transaction);\r\n treeSetValue(queueNode, nodeQueue);\r\n // Update visibleData and raise events\r\n // Note: We intentionally raise events after updating all of our\r\n // transaction state, since the user could start new transactions from the\r\n // event callbacks.\r\n let priorityForNode;\r\n if (typeof newVal === 'object' &&\r\n newVal !== null &&\r\n contains(newVal, '.priority')) {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n priorityForNode = safeGet(newVal, '.priority');\r\n assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\r\n 'Priority must be a valid string, finite number, server value, or null.');\r\n }\r\n else {\r\n const currentNode = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path) ||\r\n ChildrenNode.EMPTY_NODE;\r\n priorityForNode = currentNode.getPriority().val();\r\n }\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\r\n const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, currentState, serverValues);\r\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\r\n transaction.currentOutputSnapshotResolved = newNode;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n const events = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, transaction.currentWriteId, transaction.applyLocally);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n }\r\n}\r\n/**\r\n * @param excludeSets - A specific set to exclude\r\n */\r\nfunction repoGetLatestState(repo, path, excludeSets) {\r\n return (syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) ||\r\n ChildrenNode.EMPTY_NODE);\r\n}\r\n/**\r\n * Sends any already-run transactions that aren't waiting for outstanding\r\n * transactions to complete.\r\n *\r\n * Externally it's called with no arguments, but it calls itself recursively\r\n * with a particular transactionQueueTree node to recurse through the tree.\r\n *\r\n * @param node - transactionQueueTree node to start at.\r\n */\r\nfunction repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {\r\n // Before recursing, make sure any completed transactions are removed.\r\n if (!node) {\r\n repoPruneCompletedTransactionsBelowNode(repo, node);\r\n }\r\n if (treeGetValue(node)) {\r\n const queue = repoBuildTransactionQueue(repo, node);\r\n assert(queue.length > 0, 'Sending zero length transaction queue');\r\n const allRun = queue.every((transaction) => transaction.status === 0 /* RUN */);\r\n // If they're all run (and not sent), we can send them. Else, we must wait.\r\n if (allRun) {\r\n repoSendTransactionQueue(repo, treeGetPath(node), queue);\r\n }\r\n }\r\n else if (treeHasChildren(node)) {\r\n treeForEachChild(node, childNode => {\r\n repoSendReadyTransactions(repo, childNode);\r\n });\r\n }\r\n}\r\n/**\r\n * Given a list of run transactions, send them to the server and then handle\r\n * the result (success or failure).\r\n *\r\n * @param path - The location of the queue.\r\n * @param queue - Queue of transactions under the specified location.\r\n */\r\nfunction repoSendTransactionQueue(repo, path, queue) {\r\n // Mark transactions as sent and increment retry count!\r\n const setsToIgnore = queue.map(txn => {\r\n return txn.currentWriteId;\r\n });\r\n const latestState = repoGetLatestState(repo, path, setsToIgnore);\r\n let snapToSend = latestState;\r\n const latestHash = latestState.hash();\r\n for (let i = 0; i < queue.length; i++) {\r\n const txn = queue[i];\r\n assert(txn.status === 0 /* RUN */, 'tryToSendTransactionQueue_: items in queue should all be run.');\r\n txn.status = 1 /* SENT */;\r\n txn.retryCount++;\r\n const relativePath = newRelativePath(path, txn.path);\r\n // If we've gotten to this point, the output snapshot must be defined.\r\n snapToSend = snapToSend.updateChild(relativePath /** @type {!Node} */, txn.currentOutputSnapshotRaw);\r\n }\r\n const dataToSend = snapToSend.val(true);\r\n const pathToSend = path;\r\n // Send the put.\r\n repo.server_.put(pathToSend.toString(), dataToSend, (status) => {\r\n repoLog(repo, 'transaction put response', {\r\n path: pathToSend.toString(),\r\n status\r\n });\r\n let events = [];\r\n if (status === 'ok') {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more\r\n // transactions or sets.\r\n const callbacks = [];\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 2 /* COMPLETED */;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId));\r\n if (queue[i].onComplete) {\r\n // We never unset the output snapshot, and given that this\r\n // transaction is complete, it should be set\r\n callbacks.push(() => queue[i].onComplete(null, true, queue[i].currentOutputSnapshotResolved));\r\n }\r\n queue[i].unwatcher();\r\n }\r\n // Now remove the completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));\r\n // There may be pending transactions that we can now send.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n // Finally, trigger onComplete callbacks.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n else {\r\n // transactions are no longer sent. Update their status appropriately.\r\n if (status === 'datastale') {\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* SENT_NEEDS_ABORT */) {\r\n queue[i].status = 4 /* NEEDS_ABORT */;\r\n }\r\n else {\r\n queue[i].status = 0 /* RUN */;\r\n }\r\n }\r\n }\r\n else {\r\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\r\n for (let i = 0; i < queue.length; i++) {\r\n queue[i].status = 4 /* NEEDS_ABORT */;\r\n queue[i].abortReason = status;\r\n }\r\n }\r\n repoRerunTransactions(repo, path);\r\n }\r\n }, latestHash);\r\n}\r\n/**\r\n * Finds all transactions dependent on the data at changedPath and reruns them.\r\n *\r\n * Should be called any time cached data changes.\r\n *\r\n * Return the highest path that was affected by rerunning transactions. This\r\n * is the path at which events need to be raised for.\r\n *\r\n * @param changedPath - The path in mergedData that changed.\r\n * @returns The rootmost path that was affected by rerunning transactions.\r\n */\r\nfunction repoRerunTransactions(repo, changedPath) {\r\n const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);\r\n const path = treeGetPath(rootMostTransactionNode);\r\n const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);\r\n repoRerunTransactionQueue(repo, queue, path);\r\n return path;\r\n}\r\n/**\r\n * Does all the work of rerunning transactions (as well as cleans up aborted\r\n * transactions and whatnot).\r\n *\r\n * @param queue - The queue of transactions to run.\r\n * @param path - The path the queue is for.\r\n */\r\nfunction repoRerunTransactionQueue(repo, queue, path) {\r\n if (queue.length === 0) {\r\n return; // Nothing to do!\r\n }\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions or\r\n // sets.\r\n const callbacks = [];\r\n let events = [];\r\n // Ignore all of the sets we're going to re-run.\r\n const txnsToRerun = queue.filter(q => {\r\n return q.status === 0 /* RUN */;\r\n });\r\n const setsToIgnore = txnsToRerun.map(q => {\r\n return q.currentWriteId;\r\n });\r\n for (let i = 0; i < queue.length; i++) {\r\n const transaction = queue[i];\r\n const relativePath = newRelativePath(path, transaction.path);\r\n let abortTransaction = false, abortReason;\r\n assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\r\n if (transaction.status === 4 /* NEEDS_ABORT */) {\r\n abortTransaction = true;\r\n abortReason = transaction.abortReason;\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else if (transaction.status === 0 /* RUN */) {\r\n if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {\r\n abortTransaction = true;\r\n abortReason = 'maxretry';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n else {\r\n // This code reruns a transaction\r\n const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);\r\n transaction.currentInputSnapshot = currentNode;\r\n const newData = queue[i].update(currentNode.val());\r\n if (newData !== undefined) {\r\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\r\n let newDataNode = nodeFromJSON(newData);\r\n const hasExplicitPriority = typeof newData === 'object' &&\r\n newData != null &&\r\n contains(newData, '.priority');\r\n if (!hasExplicitPriority) {\r\n // Keep the old priority if there wasn't a priority explicitly specified.\r\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\r\n }\r\n const oldWriteId = transaction.currentWriteId;\r\n const serverValues = repoGenerateServerValues(repo);\r\n const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);\r\n transaction.currentOutputSnapshotRaw = newDataNode;\r\n transaction.currentOutputSnapshotResolved = newNodeResolved;\r\n transaction.currentWriteId = repoGetNextWriteId(repo);\r\n // Mutates setsToIgnore in place\r\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\r\n events = events.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));\r\n }\r\n else {\r\n abortTransaction = true;\r\n abortReason = 'nodata';\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));\r\n }\r\n }\r\n }\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events);\r\n events = [];\r\n if (abortTransaction) {\r\n // Abort.\r\n queue[i].status = 2 /* COMPLETED */;\r\n // Removing a listener can trigger pruning which can muck with\r\n // mergedData/visibleData (as it prunes data). So defer the unwatcher\r\n // until we're done.\r\n (function (unwatcher) {\r\n setTimeout(unwatcher, Math.floor(0));\r\n })(queue[i].unwatcher);\r\n if (queue[i].onComplete) {\r\n if (abortReason === 'nodata') {\r\n callbacks.push(() => queue[i].onComplete(null, false, queue[i].currentInputSnapshot));\r\n }\r\n else {\r\n callbacks.push(() => queue[i].onComplete(new Error(abortReason), false, null));\r\n }\r\n }\r\n }\r\n }\r\n // Clean up completed transactions.\r\n repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);\r\n // Now fire callbacks, now that we're in a good, known state.\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n // Try to send the transaction result to the server.\r\n repoSendReadyTransactions(repo, repo.transactionQueueTree_);\r\n}\r\n/**\r\n * Returns the rootmost ancestor node of the specified path that has a pending\r\n * transaction on it, or just returns the node for the given path if there are\r\n * no pending transactions on any ancestor.\r\n *\r\n * @param path - The location to start at.\r\n * @returns The rootmost node with a transaction.\r\n */\r\nfunction repoGetAncestorTransactionNode(repo, path) {\r\n let front;\r\n // Start at the root and walk deeper into the tree towards path until we\r\n // find a node with pending transactions.\r\n let transactionNode = repo.transactionQueueTree_;\r\n front = pathGetFront(path);\r\n while (front !== null && treeGetValue(transactionNode) === undefined) {\r\n transactionNode = treeSubTree(transactionNode, front);\r\n path = pathPopFront(path);\r\n front = pathGetFront(path);\r\n }\r\n return transactionNode;\r\n}\r\n/**\r\n * Builds the queue of all transactions at or below the specified\r\n * transactionNode.\r\n *\r\n * @param transactionNode\r\n * @returns The generated queue.\r\n */\r\nfunction repoBuildTransactionQueue(repo, transactionNode) {\r\n // Walk any child transaction queues and aggregate them into a single queue.\r\n const transactionQueue = [];\r\n repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);\r\n // Sort them by the order the transactions were created.\r\n transactionQueue.sort((a, b) => a.order - b.order);\r\n return transactionQueue;\r\n}\r\nfunction repoAggregateTransactionQueuesForNode(repo, node, queue) {\r\n const nodeQueue = treeGetValue(node);\r\n if (nodeQueue) {\r\n for (let i = 0; i < nodeQueue.length; i++) {\r\n queue.push(nodeQueue[i]);\r\n }\r\n }\r\n treeForEachChild(node, child => {\r\n repoAggregateTransactionQueuesForNode(repo, child, queue);\r\n });\r\n}\r\n/**\r\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\r\n */\r\nfunction repoPruneCompletedTransactionsBelowNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n let to = 0;\r\n for (let from = 0; from < queue.length; from++) {\r\n if (queue[from].status !== 2 /* COMPLETED */) {\r\n queue[to] = queue[from];\r\n to++;\r\n }\r\n }\r\n queue.length = to;\r\n treeSetValue(node, queue.length > 0 ? queue : undefined);\r\n }\r\n treeForEachChild(node, childNode => {\r\n repoPruneCompletedTransactionsBelowNode(repo, childNode);\r\n });\r\n}\r\n/**\r\n * Aborts all transactions on ancestors or descendants of the specified path.\r\n * Called when doing a set() or update() since we consider them incompatible\r\n * with transactions.\r\n *\r\n * @param path - Path for which we want to abort related transactions.\r\n */\r\nfunction repoAbortTransactions(repo, path) {\r\n const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));\r\n const transactionNode = treeSubTree(repo.transactionQueueTree_, path);\r\n treeForEachAncestor(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n repoAbortTransactionsOnNode(repo, transactionNode);\r\n treeForEachDescendant(transactionNode, (node) => {\r\n repoAbortTransactionsOnNode(repo, node);\r\n });\r\n return affectedPath;\r\n}\r\n/**\r\n * Abort transactions stored in this transaction queue node.\r\n *\r\n * @param node - Node to abort transactions for.\r\n */\r\nfunction repoAbortTransactionsOnNode(repo, node) {\r\n const queue = treeGetValue(node);\r\n if (queue) {\r\n // Queue up the callbacks and fire them after cleaning up all of our\r\n // transaction state, since the callback could trigger more transactions\r\n // or sets.\r\n const callbacks = [];\r\n // Go through queue. Any already-sent transactions must be marked for\r\n // abort, while the unsent ones can be immediately aborted and removed.\r\n let events = [];\r\n let lastSent = -1;\r\n for (let i = 0; i < queue.length; i++) {\r\n if (queue[i].status === 3 /* SENT_NEEDS_ABORT */) ;\r\n else if (queue[i].status === 1 /* SENT */) {\r\n assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\r\n lastSent = i;\r\n // Mark transaction for abort when it comes back.\r\n queue[i].status = 3 /* SENT_NEEDS_ABORT */;\r\n queue[i].abortReason = 'set';\r\n }\r\n else {\r\n assert(queue[i].status === 0 /* RUN */, 'Unexpected transaction status in abort');\r\n // We can abort it immediately.\r\n queue[i].unwatcher();\r\n events = events.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i].currentWriteId, true));\r\n if (queue[i].onComplete) {\r\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, null));\r\n }\r\n }\r\n }\r\n if (lastSent === -1) {\r\n // We're not waiting for any sent transactions. We can clear the queue.\r\n treeSetValue(node, undefined);\r\n }\r\n else {\r\n // Remove the transactions we aborted.\r\n queue.length = lastSent + 1;\r\n }\r\n // Now fire the callbacks.\r\n eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events);\r\n for (let i = 0; i < callbacks.length; i++) {\r\n exceptionGuard(callbacks[i]);\r\n }\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction decodePath(pathString) {\r\n let pathStringDecoded = '';\r\n const pieces = pathString.split('/');\r\n for (let i = 0; i < pieces.length; i++) {\r\n if (pieces[i].length > 0) {\r\n let piece = pieces[i];\r\n try {\r\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\r\n }\r\n catch (e) { }\r\n pathStringDecoded += '/' + piece;\r\n }\r\n }\r\n return pathStringDecoded;\r\n}\r\n/**\r\n * @returns key value hash\r\n */\r\nfunction decodeQuery(queryString) {\r\n const results = {};\r\n if (queryString.charAt(0) === '?') {\r\n queryString = queryString.substring(1);\r\n }\r\n for (const segment of queryString.split('&')) {\r\n if (segment.length === 0) {\r\n continue;\r\n }\r\n const kv = segment.split('=');\r\n if (kv.length === 2) {\r\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\r\n }\r\n else {\r\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\r\n }\r\n }\r\n return results;\r\n}\r\nconst parseRepoInfo = function (dataURL, nodeAdmin) {\r\n const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;\r\n if (parsedUrl.domain === 'firebase.com') {\r\n fatal(parsedUrl.host +\r\n ' is no longer supported. ' +\r\n 'Please use .firebaseio.com instead');\r\n }\r\n // Catch common error of uninitialized namespace value.\r\n if ((!namespace || namespace === 'undefined') &&\r\n parsedUrl.domain !== 'localhost') {\r\n fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\r\n }\r\n if (!parsedUrl.secure) {\r\n warnIfPageIsSecure();\r\n }\r\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\r\n return {\r\n repoInfo: new RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly, nodeAdmin, \r\n /*persistenceKey=*/ '', \r\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain),\r\n path: new Path(parsedUrl.pathString)\r\n };\r\n};\r\nconst parseDatabaseURL = function (dataURL) {\r\n // Default to empty strings in the event of a malformed string.\r\n let host = '', domain = '', subdomain = '', pathString = '', namespace = '';\r\n // Always default to SSL, unless otherwise specified.\r\n let secure = true, scheme = 'https', port = 443;\r\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\r\n if (typeof dataURL === 'string') {\r\n // Parse scheme.\r\n let colonInd = dataURL.indexOf('//');\r\n if (colonInd >= 0) {\r\n scheme = dataURL.substring(0, colonInd - 1);\r\n dataURL = dataURL.substring(colonInd + 2);\r\n }\r\n // Parse host, path, and query string.\r\n let slashInd = dataURL.indexOf('/');\r\n if (slashInd === -1) {\r\n slashInd = dataURL.length;\r\n }\r\n let questionMarkInd = dataURL.indexOf('?');\r\n if (questionMarkInd === -1) {\r\n questionMarkInd = dataURL.length;\r\n }\r\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\r\n if (slashInd < questionMarkInd) {\r\n // For pathString, questionMarkInd will always come after slashInd\r\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\r\n }\r\n const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));\r\n // If we have a port, use scheme for determining if it's secure.\r\n colonInd = host.indexOf(':');\r\n if (colonInd >= 0) {\r\n secure = scheme === 'https' || scheme === 'wss';\r\n port = parseInt(host.substring(colonInd + 1), 10);\r\n }\r\n else {\r\n colonInd = host.length;\r\n }\r\n const hostWithoutPort = host.slice(0, colonInd);\r\n if (hostWithoutPort.toLowerCase() === 'localhost') {\r\n domain = 'localhost';\r\n }\r\n else if (hostWithoutPort.split('.').length <= 2) {\r\n domain = hostWithoutPort;\r\n }\r\n else {\r\n // Interpret the subdomain of a 3 or more component URL as the namespace name.\r\n const dotInd = host.indexOf('.');\r\n subdomain = host.substring(0, dotInd).toLowerCase();\r\n domain = host.substring(dotInd + 1);\r\n // Normalize namespaces to lowercase to share storage / connection.\r\n namespace = subdomain;\r\n }\r\n // Always treat the value of the `ns` as the namespace name if it is present.\r\n if ('ns' in queryParams) {\r\n namespace = queryParams['ns'];\r\n }\r\n }\r\n return {\r\n host,\r\n port,\r\n domain,\r\n subdomain,\r\n secure,\r\n scheme,\r\n pathString,\r\n namespace\r\n };\r\n};\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * Encapsulates the data needed to raise an event\r\n */\r\nclass DataEvent {\r\n /**\r\n * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed\r\n * @param eventRegistration - The function to call to with the event data. User provided\r\n * @param snapshot - The data backing the event\r\n * @param prevName - Optional, the name of the previous child for child_* events.\r\n */\r\n constructor(eventType, eventRegistration, snapshot, prevName) {\r\n this.eventType = eventType;\r\n this.eventRegistration = eventRegistration;\r\n this.snapshot = snapshot;\r\n this.prevName = prevName;\r\n }\r\n getPath() {\r\n const ref = this.snapshot.ref;\r\n if (this.eventType === 'value') {\r\n return ref._path;\r\n }\r\n else {\r\n return ref.parent._path;\r\n }\r\n }\r\n getEventType() {\r\n return this.eventType;\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return (this.getPath().toString() +\r\n ':' +\r\n this.eventType +\r\n ':' +\r\n stringify(this.snapshot.exportVal()));\r\n }\r\n}\r\nclass CancelEvent {\r\n constructor(eventRegistration, error, path) {\r\n this.eventRegistration = eventRegistration;\r\n this.error = error;\r\n this.path = path;\r\n }\r\n getPath() {\r\n return this.path;\r\n }\r\n getEventType() {\r\n return 'cancel';\r\n }\r\n getEventRunner() {\r\n return this.eventRegistration.getEventRunner(this);\r\n }\r\n toString() {\r\n return this.path.toString() + ':cancel';\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A wrapper class that converts events from the database@exp SDK to the legacy\r\n * Database SDK. Events are not converted directly as event registration relies\r\n * on reference comparison of the original user callback (see `matches()`) and\r\n * relies on equality of the legacy SDK's `context` object.\r\n */\r\nclass CallbackContext {\r\n constructor(snapshotCallback, cancelCallback) {\r\n this.snapshotCallback = snapshotCallback;\r\n this.cancelCallback = cancelCallback;\r\n }\r\n onValue(expDataSnapshot, previousChildName) {\r\n this.snapshotCallback.call(null, expDataSnapshot, previousChildName);\r\n }\r\n onCancel(error) {\r\n assert(this.hasCancelCallback, 'Raising a cancel event on a listener with no cancel callback');\r\n return this.cancelCallback.call(null, error);\r\n }\r\n get hasCancelCallback() {\r\n return !!this.cancelCallback;\r\n }\r\n matches(other) {\r\n return (this.snapshotCallback === other.snapshotCallback ||\r\n (this.snapshotCallback.userCallback !== undefined &&\r\n this.snapshotCallback.userCallback ===\r\n other.snapshotCallback.userCallback &&\r\n this.snapshotCallback.context === other.snapshotCallback.context));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * The `onDisconnect` class allows you to write or clear data when your client\r\n * disconnects from the Database server. These updates occur whether your\r\n * client disconnects cleanly or not, so you can rely on them to clean up data\r\n * even if a connection is dropped or a client crashes.\r\n *\r\n * The `onDisconnect` class is most commonly used to manage presence in\r\n * applications where it is useful to detect how many clients are connected and\r\n * when other clients disconnect. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * To avoid problems when a connection is dropped before the requests can be\r\n * transferred to the Database server, these functions should be called before\r\n * writing any data.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time you reconnect.\r\n */\r\nclass OnDisconnect {\r\n /** @hideconstructor */\r\n constructor(_repo, _path) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n }\r\n /**\r\n * Cancels all previously queued `onDisconnect()` set or update events for this\r\n * location and all children.\r\n *\r\n * If a write has been queued for this location via a `set()` or `update()` at a\r\n * parent location, the write at this location will be canceled, though writes\r\n * to sibling locations will still occur.\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n cancel() {\r\n const deferred = new Deferred();\r\n repoOnDisconnectCancel(this._repo, this._path, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is deleted when the client is disconnected\r\n * (due to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * @returns Resolves when synchronization to the server is complete.\r\n */\r\n remove() {\r\n validateWritablePath('OnDisconnect.remove', this._path);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value when the\r\n * client is disconnected (due to closing the browser, navigating to a new page,\r\n * or network issues).\r\n *\r\n * `set()` is especially useful for implementing \"presence\" systems, where a\r\n * value should be changed or cleared when a user disconnects so that they\r\n * appear \"offline\" to other users. See\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information.\r\n *\r\n * Note that `onDisconnect` operations are only triggered once. If you want an\r\n * operation to occur each time a disconnect occurs, you'll need to re-establish\r\n * the `onDisconnect` operations each time.\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n set(value) {\r\n validateWritablePath('OnDisconnect.set', this._path);\r\n validateFirebaseDataArg('OnDisconnect.set', value, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSet(this._repo, this._path, value, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Ensures the data at this location is set to the specified value and priority\r\n * when the client is disconnected (due to closing the browser, navigating to a\r\n * new page, or network issues).\r\n *\r\n * @param value - The value to be written to this location on disconnect (can\r\n * be an object, array, string, number, boolean, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n setWithPriority(value, priority) {\r\n validateWritablePath('OnDisconnect.setWithPriority', this._path);\r\n validateFirebaseDataArg('OnDisconnect.setWithPriority', value, this._path, false);\r\n validatePriority('OnDisconnect.setWithPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectSetWithPriority(this._repo, this._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n /**\r\n * Writes multiple values at this location when the client is disconnected (due\r\n * to closing the browser, navigating to a new page, or network issues).\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example, \"name/first\")\r\n * from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when synchronization to the Database is complete.\r\n */\r\n update(values) {\r\n validateWritablePath('OnDisconnect.update', this._path);\r\n validateFirebaseMergeDataArg('OnDisconnect.update', values, this._path, false);\r\n const deferred = new Deferred();\r\n repoOnDisconnectUpdate(this._repo, this._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * @internal\r\n */\r\nclass QueryImpl {\r\n /**\r\n * @hideconstructor\r\n */\r\n constructor(_repo, _path, _queryParams, _orderByCalled) {\r\n this._repo = _repo;\r\n this._path = _path;\r\n this._queryParams = _queryParams;\r\n this._orderByCalled = _orderByCalled;\r\n }\r\n get key() {\r\n if (pathIsEmpty(this._path)) {\r\n return null;\r\n }\r\n else {\r\n return pathGetBack(this._path);\r\n }\r\n }\r\n get ref() {\r\n return new ReferenceImpl(this._repo, this._path);\r\n }\r\n get _queryIdentifier() {\r\n const obj = queryParamsGetQueryObject(this._queryParams);\r\n const id = ObjectToUniqueKey(obj);\r\n return id === '{}' ? 'default' : id;\r\n }\r\n /**\r\n * An object representation of the query parameters used by this Query.\r\n */\r\n get _queryObject() {\r\n return queryParamsGetQueryObject(this._queryParams);\r\n }\r\n isEqual(other) {\r\n other = getModularInstance(other);\r\n if (!(other instanceof QueryImpl)) {\r\n return false;\r\n }\r\n const sameRepo = this._repo === other._repo;\r\n const samePath = pathEquals(this._path, other._path);\r\n const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;\r\n return sameRepo && samePath && sameQueryIdentifier;\r\n }\r\n toJSON() {\r\n return this.toString();\r\n }\r\n toString() {\r\n return this._repo.toString() + pathToUrlEncodedString(this._path);\r\n }\r\n}\r\n/**\r\n * Validates that no other order by call has been made\r\n */\r\nfunction validateNoPreviousOrderByCall(query, fnName) {\r\n if (query._orderByCalled === true) {\r\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\r\n }\r\n}\r\n/**\r\n * Validates start/end values for queries.\r\n */\r\nfunction validateQueryEndpoints(params) {\r\n let startNode = null;\r\n let endNode = null;\r\n if (params.hasStart()) {\r\n startNode = params.getIndexStartValue();\r\n }\r\n if (params.hasEnd()) {\r\n endNode = params.getIndexEndValue();\r\n }\r\n if (params.getIndex() === KEY_INDEX) {\r\n const tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\r\n 'startAt(), endAt(), or equalTo().';\r\n const wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), startAfter(), ' +\r\n 'endAt(), endBefore(), or equalTo() must be a string.';\r\n if (params.hasStart()) {\r\n const startName = params.getIndexStartName();\r\n if (startName !== MIN_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof startNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n if (params.hasEnd()) {\r\n const endName = params.getIndexEndName();\r\n if (endName !== MAX_NAME) {\r\n throw new Error(tooManyArgsError);\r\n }\r\n else if (typeof endNode !== 'string') {\r\n throw new Error(wrongArgTypeError);\r\n }\r\n }\r\n }\r\n else if (params.getIndex() === PRIORITY_INDEX) {\r\n if ((startNode != null && !isValidPriority(startNode)) ||\r\n (endNode != null && !isValidPriority(endNode))) {\r\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\r\n 'startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value ' +\r\n '(null, a number, or a string).');\r\n }\r\n }\r\n else {\r\n assert(params.getIndex() instanceof PathIndex ||\r\n params.getIndex() === VALUE_INDEX, 'unknown index type.');\r\n if ((startNode != null && typeof startNode === 'object') ||\r\n (endNode != null && typeof endNode === 'object')) {\r\n throw new Error('Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or ' +\r\n 'equalTo() cannot be an object.');\r\n }\r\n }\r\n}\r\n/**\r\n * Validates that limit* has been called with the correct combination of parameters\r\n */\r\nfunction validateLimit(params) {\r\n if (params.hasStart() &&\r\n params.hasEnd() &&\r\n params.hasLimit() &&\r\n !params.hasAnchoredLimit()) {\r\n throw new Error(\"Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use \" +\r\n 'limitToFirst() or limitToLast() instead.');\r\n }\r\n}\r\n/**\r\n * @internal\r\n */\r\nclass ReferenceImpl extends QueryImpl {\r\n /** @hideconstructor */\r\n constructor(repo, path) {\r\n super(repo, path, new QueryParams(), false);\r\n }\r\n get parent() {\r\n const parentPath = pathParent(this._path);\r\n return parentPath === null\r\n ? null\r\n : new ReferenceImpl(this._repo, parentPath);\r\n }\r\n get root() {\r\n let ref = this;\r\n while (ref.parent !== null) {\r\n ref = ref.parent;\r\n }\r\n return ref;\r\n }\r\n}\r\n/**\r\n * A `DataSnapshot` contains data from a Database location.\r\n *\r\n * Any time you read data from the Database, you receive the data as a\r\n * `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach\r\n * with `on()` or `once()`. You can extract the contents of the snapshot as a\r\n * JavaScript object by calling the `val()` method. Alternatively, you can\r\n * traverse into the snapshot by calling `child()` to return child snapshots\r\n * (which you could then call `val()` on).\r\n *\r\n * A `DataSnapshot` is an efficiently generated, immutable copy of the data at\r\n * a Database location. It cannot be modified and will never change (to modify\r\n * data, you always call the `set()` method on a `Reference` directly).\r\n */\r\nclass DataSnapshot {\r\n /**\r\n * @param _node - A SnapshotNode to wrap.\r\n * @param ref - The location this snapshot came from.\r\n * @param _index - The iteration order for this snapshot\r\n * @hideconstructor\r\n */\r\n constructor(_node, \r\n /**\r\n * The location of this DataSnapshot.\r\n */\r\n ref, _index) {\r\n this._node = _node;\r\n this.ref = ref;\r\n this._index = _index;\r\n }\r\n /**\r\n * Gets the priority value of the data in this `DataSnapshot`.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}\r\n * ).\r\n */\r\n get priority() {\r\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\r\n return this._node.getPriority().val();\r\n }\r\n /**\r\n * The key (last part of the path) of the location of this `DataSnapshot`.\r\n *\r\n * The last token in a Database location is considered its key. For example,\r\n * \"ada\" is the key for the /users/ada/ node. Accessing the key on any\r\n * `DataSnapshot` will return the key for the location that generated it.\r\n * However, accessing the key on the root URL of a Database will return\r\n * `null`.\r\n */\r\n get key() {\r\n return this.ref.key;\r\n }\r\n /** Returns the number of child properties of this `DataSnapshot`. */\r\n get size() {\r\n return this._node.numChildren();\r\n }\r\n /**\r\n * Gets another `DataSnapshot` for the location at the specified relative path.\r\n *\r\n * Passing a relative path to the `child()` method of a DataSnapshot returns\r\n * another `DataSnapshot` for the location at the specified relative path. The\r\n * relative path can either be a simple child name (for example, \"ada\") or a\r\n * deeper, slash-separated path (for example, \"ada/name/first\"). If the child\r\n * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`\r\n * whose value is `null`) is returned.\r\n *\r\n * @param path - A relative path to the location of child data.\r\n */\r\n child(path) {\r\n const childPath = new Path(path);\r\n const childRef = child(this.ref, path);\r\n return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);\r\n }\r\n /**\r\n * Returns true if this `DataSnapshot` contains any data. It is slightly more\r\n * efficient than using `snapshot.val() !== null`.\r\n */\r\n exists() {\r\n return !this._node.isEmpty();\r\n }\r\n /**\r\n * Exports the entire contents of the DataSnapshot as a JavaScript object.\r\n *\r\n * The `exportVal()` method is similar to `val()`, except priority information\r\n * is included (if available), making it suitable for backing up your data.\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n exportVal() {\r\n return this._node.val(true);\r\n }\r\n /**\r\n * Enumerates the top-level children in the `DataSnapshot`.\r\n *\r\n * Because of the way JavaScript objects work, the ordering of data in the\r\n * JavaScript object returned by `val()` is not guaranteed to match the\r\n * ordering on the server nor the ordering of `onChildAdded()` events. That is\r\n * where `forEach()` comes in handy. It guarantees the children of a\r\n * `DataSnapshot` will be iterated in their query order.\r\n *\r\n * If no explicit `orderBy*()` method is used, results are returned\r\n * ordered by key (unless priorities are used, in which case, results are\r\n * returned by priority).\r\n *\r\n * @param action - A function that will be called for each child DataSnapshot.\r\n * The callback can return true to cancel further enumeration.\r\n * @returns true if enumeration was canceled due to your callback returning\r\n * true.\r\n */\r\n forEach(action) {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n const childrenNode = this._node;\r\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\r\n return !!childrenNode.forEachChild(this._index, (key, node) => {\r\n return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));\r\n });\r\n }\r\n /**\r\n * Returns true if the specified child path has (non-null) data.\r\n *\r\n * @param path - A relative path to the location of a potential child.\r\n * @returns `true` if data exists at the specified child path; else\r\n * `false`.\r\n */\r\n hasChild(path) {\r\n const childPath = new Path(path);\r\n return !this._node.getChild(childPath).isEmpty();\r\n }\r\n /**\r\n * Returns whether or not the `DataSnapshot` has any non-`null` child\r\n * properties.\r\n *\r\n * You can use `hasChildren()` to determine if a `DataSnapshot` has any\r\n * children. If it does, you can enumerate them using `forEach()`. If it\r\n * doesn't, then either this snapshot contains a primitive value (which can be\r\n * retrieved with `val()`) or it is empty (in which case, `val()` will return\r\n * `null`).\r\n *\r\n * @returns true if this snapshot has any children; else false.\r\n */\r\n hasChildren() {\r\n if (this._node.isLeafNode()) {\r\n return false;\r\n }\r\n else {\r\n return !this._node.isEmpty();\r\n }\r\n }\r\n /**\r\n * Returns a JSON-serializable representation of this object.\r\n */\r\n toJSON() {\r\n return this.exportVal();\r\n }\r\n /**\r\n * Extracts a JavaScript value from a `DataSnapshot`.\r\n *\r\n * Depending on the data in a `DataSnapshot`, the `val()` method may return a\r\n * scalar type (string, number, or boolean), an array, or an object. It may\r\n * also return null, indicating that the `DataSnapshot` is empty (contains no\r\n * data).\r\n *\r\n * @returns The DataSnapshot's contents as a JavaScript value (Object,\r\n * Array, string, number, boolean, or `null`).\r\n */\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n val() {\r\n return this._node.val();\r\n }\r\n}\r\n/**\r\n *\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided path. If no path is provided, the `Reference`\r\n * will point to the root of the Database.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param path - Optional path representing the location the returned\r\n * `Reference` will point. If not provided, the returned `Reference` will\r\n * point to the root of the Database.\r\n * @returns If a path is provided, a `Reference`\r\n * pointing to the provided path. Otherwise, a `Reference` pointing to the\r\n * root of the Database.\r\n */\r\nfunction ref(db, path) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('ref');\r\n return path !== undefined ? child(db._root, path) : db._root;\r\n}\r\n/**\r\n * Returns a `Reference` representing the location in the Database\r\n * corresponding to the provided Firebase URL.\r\n *\r\n * An exception is thrown if the URL is not a valid Firebase Database URL or it\r\n * has a different domain than the current `Database` instance.\r\n *\r\n * Note that all query parameters (`orderBy`, `limitToLast`, etc.) are ignored\r\n * and are not applied to the returned `Reference`.\r\n *\r\n * @param db - The database instance to obtain a reference for.\r\n * @param url - The Firebase URL at which the returned `Reference` will\r\n * point.\r\n * @returns A `Reference` pointing to the provided\r\n * Firebase URL.\r\n */\r\nfunction refFromURL(db, url) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('refFromURL');\r\n const parsedURL = parseRepoInfo(url, db._repo.repoInfo_.nodeAdmin);\r\n validateUrl('refFromURL', parsedURL);\r\n const repoInfo = parsedURL.repoInfo;\r\n if (!db._repo.repoInfo_.isCustomHost() &&\r\n repoInfo.host !== db._repo.repoInfo_.host) {\r\n fatal('refFromURL' +\r\n ': Host name does not match the current database: ' +\r\n '(found ' +\r\n repoInfo.host +\r\n ' but expected ' +\r\n db._repo.repoInfo_.host +\r\n ')');\r\n }\r\n return ref(db, parsedURL.path.toString());\r\n}\r\n/**\r\n * Gets a `Reference` for the location at the specified relative path.\r\n *\r\n * The relative path can either be a simple child name (for example, \"ada\") or\r\n * a deeper slash-separated path (for example, \"ada/name/first\").\r\n *\r\n * @param parent - The parent location.\r\n * @param path - A relative path from this location to the desired child\r\n * location.\r\n * @returns The specified child location.\r\n */\r\nfunction child(parent, path) {\r\n parent = getModularInstance(parent);\r\n if (pathGetFront(parent._path) === null) {\r\n validateRootPathString('child', 'path', path, false);\r\n }\r\n else {\r\n validatePathString('child', 'path', path, false);\r\n }\r\n return new ReferenceImpl(parent._repo, pathChild(parent._path, path));\r\n}\r\n/**\r\n * Returns an `OnDisconnect` object - see\r\n * {@link https://firebase.google.com/docs/database/web/offline-capabilities | Enabling Offline Capabilities in JavaScript}\r\n * for more information on how to use it.\r\n *\r\n * @param ref - The reference to add OnDisconnect triggers for.\r\n */\r\nfunction onDisconnect(ref) {\r\n ref = getModularInstance(ref);\r\n return new OnDisconnect(ref._repo, ref._path);\r\n}\r\n/**\r\n * Generates a new child location using a unique key and returns its\r\n * `Reference`.\r\n *\r\n * This is the most common pattern for adding data to a collection of items.\r\n *\r\n * If you provide a value to `push()`, the value is written to the\r\n * generated location. If you don't pass a value, nothing is written to the\r\n * database and the child remains empty (but you can use the `Reference`\r\n * elsewhere).\r\n *\r\n * The unique keys generated by `push()` are ordered by the current time, so the\r\n * resulting list of items is chronologically sorted. The keys are also\r\n * designed to be unguessable (they contain 72 random bits of entropy).\r\n *\r\n * See {@link https://firebase.google.com/docs/database/web/lists-of-data#append_to_a_list_of_data | Append to a list of data}\r\n *
See {@link ttps://firebase.googleblog.com/2015/02/the-2120-ways-to-ensure-unique_68.html | The 2^120 Ways to Ensure Unique Identifiers}\r\n *\r\n * @param parent - The parent location.\r\n * @param value - Optional value to be written at the generated location.\r\n * @returns Combined `Promise` and `Reference`; resolves when write is complete,\r\n * but can be used immediately as the `Reference` to the child location.\r\n */\r\nfunction push(parent, value) {\r\n parent = getModularInstance(parent);\r\n validateWritablePath('push', parent._path);\r\n validateFirebaseDataArg('push', value, parent._path, true);\r\n const now = repoServerTime(parent._repo);\r\n const name = nextPushId(now);\r\n // push() returns a ThennableReference whose promise is fulfilled with a\r\n // regular Reference. We use child() to create handles to two different\r\n // references. The first is turned into a ThennableReference below by adding\r\n // then() and catch() methods and is used as the return value of push(). The\r\n // second remains a regular Reference and is used as the fulfilled value of\r\n // the first ThennableReference.\r\n const thennablePushRef = child(parent, name);\r\n const pushRef = child(parent, name);\r\n let promise;\r\n if (value != null) {\r\n promise = set(pushRef, value).then(() => pushRef);\r\n }\r\n else {\r\n promise = Promise.resolve(pushRef);\r\n }\r\n thennablePushRef.then = promise.then.bind(promise);\r\n thennablePushRef.catch = promise.then.bind(promise, undefined);\r\n return thennablePushRef;\r\n}\r\n/**\r\n * Removes the data at this Database location.\r\n *\r\n * Any data at child locations will also be deleted.\r\n *\r\n * The effect of the remove will be visible immediately and the corresponding\r\n * event 'value' will be triggered. Synchronization of the remove to the\r\n * Firebase servers will also be started, and the returned Promise will resolve\r\n * when complete. If provided, the onComplete callback will be called\r\n * asynchronously after synchronization has finished.\r\n *\r\n * @param ref - The location to remove.\r\n * @returns Resolves when remove on server is complete.\r\n */\r\nfunction remove(ref) {\r\n validateWritablePath('remove', ref._path);\r\n return set(ref, null);\r\n}\r\n/**\r\n * Writes data to this Database location.\r\n *\r\n * This will overwrite any data at this location and all child locations.\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events (\"value\", \"child_added\", etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * Passing `null` for the new value is equivalent to calling `remove()`; namely,\r\n * all data at this location and all child locations will be deleted.\r\n *\r\n * `set()` will remove any priority stored at this location, so if priority is\r\n * meant to be preserved, you need to use `setWithPriority()` instead.\r\n *\r\n * Note that modifying data with `set()` will cancel any pending transactions\r\n * at that location, so extreme care should be taken if mixing `set()` and\r\n * `transaction()` to modify the same data.\r\n *\r\n * A single `set()` will generate a single \"value\" event at the location where\r\n * the `set()` was performed.\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction set(ref, value) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('set', ref._path);\r\n validateFirebaseDataArg('set', value, ref._path, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, \r\n /*priority=*/ null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Sets a priority for the data at this Database location.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setPriority(ref, priority) {\r\n ref = getModularInstance(ref);\r\n validateWritablePath('setPriority', ref._path);\r\n validatePriority('setPriority', priority, false);\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, pathChild(ref._path, '.priority'), priority, null, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes data the Database location. Like `set()` but also specifies the\r\n * priority for that data.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data | Sorting and filtering data}\r\n * ).\r\n *\r\n * @param ref - The location to write to.\r\n * @param value - The value to be written (string, number, boolean, object,\r\n * array, or null).\r\n * @param priority - The priority to be written (string, number, or null).\r\n * @returns Resolves when write to server is complete.\r\n */\r\nfunction setWithPriority(ref, value, priority) {\r\n validateWritablePath('setWithPriority', ref._path);\r\n validateFirebaseDataArg('setWithPriority', value, ref._path, false);\r\n validatePriority('setWithPriority', priority, false);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw 'setWithPriority failed: ' + ref.key + ' is a read-only object.';\r\n }\r\n const deferred = new Deferred();\r\n repoSetWithPriority(ref._repo, ref._path, value, priority, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Writes multiple values to the Database at once.\r\n *\r\n * The `values` argument contains multiple property-value pairs that will be\r\n * written to the Database together. Each child property can either be a simple\r\n * property (for example, \"name\") or a relative path (for example,\r\n * \"name/first\") from the current location to the data to update.\r\n *\r\n * As opposed to the `set()` method, `update()` can be use to selectively update\r\n * only the referenced properties at the current location (instead of replacing\r\n * all the child properties at the current location).\r\n *\r\n * The effect of the write will be visible immediately, and the corresponding\r\n * events ('value', 'child_added', etc.) will be triggered. Synchronization of\r\n * the data to the Firebase servers will also be started, and the returned\r\n * Promise will resolve when complete. If provided, the `onComplete` callback\r\n * will be called asynchronously after synchronization has finished.\r\n *\r\n * A single `update()` will generate a single \"value\" event at the location\r\n * where the `update()` was performed, regardless of how many children were\r\n * modified.\r\n *\r\n * Note that modifying data with `update()` will cancel any pending\r\n * transactions at that location, so extreme care should be taken if mixing\r\n * `update()` and `transaction()` to modify the same data.\r\n *\r\n * Passing `null` to `update()` will remove the data at this location.\r\n *\r\n * See\r\n * {@link https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html | Introducing multi-location updates and more}.\r\n *\r\n * @param ref - The location to write to.\r\n * @param values - Object containing multiple values.\r\n * @returns Resolves when update on server is complete.\r\n */\r\nfunction update(ref, values) {\r\n validateFirebaseMergeDataArg('update', values, ref._path, false);\r\n const deferred = new Deferred();\r\n repoUpdate(ref._repo, ref._path, values, deferred.wrapCallback(() => { }));\r\n return deferred.promise;\r\n}\r\n/**\r\n * Gets the most up-to-date result for this query.\r\n *\r\n * @param query - The query to run.\r\n * @returns A `Promise` which resolves to the resulting DataSnapshot if a value is\r\n * available, or rejects if the client is unable to return a value (e.g., if the\r\n * server is unreachable and there is nothing cached).\r\n */\r\nfunction get(query) {\r\n query = getModularInstance(query);\r\n return repoGetValue(query._repo, query).then(node => {\r\n return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());\r\n });\r\n}\r\n/**\r\n * Represents registration for 'value' events.\r\n */\r\nclass ValueEventRegistration {\r\n constructor(callbackContext) {\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n return eventType === 'value';\r\n }\r\n createEvent(change, query) {\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent('value', this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index));\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, null);\r\n }\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n matches(other) {\r\n if (!(other instanceof ValueEventRegistration)) {\r\n return false;\r\n }\r\n else if (!other.callbackContext || !this.callbackContext) {\r\n // If no callback specified, we consider it to match any callback.\r\n return true;\r\n }\r\n else {\r\n return other.callbackContext.matches(this.callbackContext);\r\n }\r\n }\r\n hasAnyCallback() {\r\n return this.callbackContext !== null;\r\n }\r\n}\r\n/**\r\n * Represents the registration of a child_x event.\r\n */\r\nclass ChildEventRegistration {\r\n constructor(eventType, callbackContext) {\r\n this.eventType = eventType;\r\n this.callbackContext = callbackContext;\r\n }\r\n respondsTo(eventType) {\r\n let eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\r\n eventToCheck =\r\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\r\n return this.eventType === eventToCheck;\r\n }\r\n createCancelEvent(error, path) {\r\n if (this.callbackContext.hasCancelCallback) {\r\n return new CancelEvent(this, error, path);\r\n }\r\n else {\r\n return null;\r\n }\r\n }\r\n createEvent(change, query) {\r\n assert(change.childName != null, 'Child events should have a childName.');\r\n const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);\r\n const index = query._queryParams.getIndex();\r\n return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index), change.prevName);\r\n }\r\n getEventRunner(eventData) {\r\n if (eventData.getEventType() === 'cancel') {\r\n return () => this.callbackContext.onCancel(eventData.error);\r\n }\r\n else {\r\n return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);\r\n }\r\n }\r\n matches(other) {\r\n if (other instanceof ChildEventRegistration) {\r\n return (this.eventType === other.eventType &&\r\n (!this.callbackContext ||\r\n !other.callbackContext ||\r\n this.callbackContext.matches(other.callbackContext)));\r\n }\r\n return false;\r\n }\r\n hasAnyCallback() {\r\n return !!this.callbackContext;\r\n }\r\n}\r\nfunction addEventListener(query, eventType, callback, cancelCallbackOrListenOptions, options) {\r\n let cancelCallback;\r\n if (typeof cancelCallbackOrListenOptions === 'object') {\r\n cancelCallback = undefined;\r\n options = cancelCallbackOrListenOptions;\r\n }\r\n if (typeof cancelCallbackOrListenOptions === 'function') {\r\n cancelCallback = cancelCallbackOrListenOptions;\r\n }\r\n if (options && options.onlyOnce) {\r\n const userCallback = callback;\r\n const onceCallback = (dataSnapshot, previousChildName) => {\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n userCallback(dataSnapshot, previousChildName);\r\n };\r\n onceCallback.userCallback = callback.userCallback;\r\n onceCallback.context = callback.context;\r\n callback = onceCallback;\r\n }\r\n const callbackContext = new CallbackContext(callback, cancelCallback || undefined);\r\n const container = eventType === 'value'\r\n ? new ValueEventRegistration(callbackContext)\r\n : new ChildEventRegistration(eventType, callbackContext);\r\n repoAddEventCallbackForQuery(query._repo, query, container);\r\n return () => repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\nfunction onValue(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'value', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildAdded(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_added', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildChanged(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_changed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildMoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_moved', callback, cancelCallbackOrListenOptions, options);\r\n}\r\nfunction onChildRemoved(query, callback, cancelCallbackOrListenOptions, options) {\r\n return addEventListener(query, 'child_removed', callback, cancelCallbackOrListenOptions, options);\r\n}\r\n/**\r\n * Detaches a callback previously attached with `on()`.\r\n *\r\n * Detach a callback previously attached with `on()`. Note that if `on()` was\r\n * called multiple times with the same eventType and callback, the callback\r\n * will be called multiple times for each event, and `off()` must be called\r\n * multiple times to remove the callback. Calling `off()` on a parent listener\r\n * will not automatically remove listeners registered on child nodes, `off()`\r\n * must also be called on any child listeners to remove the callback.\r\n *\r\n * If a callback is not specified, all callbacks for the specified eventType\r\n * will be removed. Similarly, if no eventType is specified, all callbacks\r\n * for the `Reference` will be removed.\r\n *\r\n * Individual listeners can also be removed by invoking their unsubscribe\r\n * callbacks.\r\n *\r\n * @param query - The query that the listener was registered with.\r\n * @param eventType - One of the following strings: \"value\", \"child_added\",\r\n * \"child_changed\", \"child_removed\", or \"child_moved.\" If omitted, all callbacks\r\n * for the `Reference` will be removed.\r\n * @param callback - The callback function that was passed to `on()` or\r\n * `undefined` to remove all callbacks.\r\n */\r\nfunction off(query, eventType, callback) {\r\n let container = null;\r\n const expCallback = callback ? new CallbackContext(callback) : null;\r\n if (eventType === 'value') {\r\n container = new ValueEventRegistration(expCallback);\r\n }\r\n else if (eventType) {\r\n container = new ChildEventRegistration(eventType, expCallback);\r\n }\r\n repoRemoveEventCallbackForQuery(query._repo, query, container);\r\n}\r\n/**\r\n * A `QueryConstraint` is used to narrow the set of documents returned by a\r\n * Database query. `QueryConstraint`s are created by invoking {@link endAt},\r\n * {@link endBefore}, {@link startAt}, {@link startAfter}, {@link\r\n * limitToFirst}, {@link limitToLast}, {@link orderByChild},\r\n * {@link orderByChild}, {@link orderByKey} , {@link orderByPriority} ,\r\n * {@link orderByValue} or {@link equalTo} and\r\n * can then be passed to {@link query} to create a new query instance that\r\n * also contains this `QueryConstraint`.\r\n */\r\nclass QueryConstraint {\r\n}\r\nclass QueryEndAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endAt', this._value, query._path, true);\r\n const newParams = queryParamsEndAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endAt: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name less than or equal\r\n * to the specified key.\r\n *\r\n * You can read more about `endAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to end at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end at, among the children with the previously\r\n * specified priority. This argument is only allowed if ordering by child,\r\n * value, or priority.\r\n */\r\nfunction endAt(value, key) {\r\n validateKey('endAt', 'key', key, true);\r\n return new QueryEndAtConstraint(value, key);\r\n}\r\nclass QueryEndBeforeConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('endBefore', this._value, query._path, false);\r\n const newParams = queryParamsEndBefore(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('endBefore: Starting point was already set (by another call to endAt, ' +\r\n 'endBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified ending point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The ending point is exclusive. If only a value is provided, children\r\n * with a value less than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value lesss than or equal\r\n * to the specified value and a a key name less than the specified key.\r\n *\r\n * @param value - The value to end before. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to end before, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction endBefore(value, key) {\r\n validateKey('endBefore', 'key', key, true);\r\n return new QueryEndBeforeConstraint(value, key);\r\n}\r\nclass QueryStartAtConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAt', this._value, query._path, true);\r\n const newParams = queryParamsStartAt(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAt: Starting point was already set (by another call to startAt, ' +\r\n 'startBefore or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is inclusive, so children with exactly the specified value\r\n * will be included in the query. The optional key argument can be used to\r\n * further limit the range of the query. If it is specified, then children that\r\n * have exactly the specified value must also have a key name greater than or\r\n * equal to the specified key.\r\n *\r\n * You can read more about `startAt()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to start at. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAt(value = null, key) {\r\n validateKey('startAt', 'key', key, true);\r\n return new QueryStartAtConstraint(value, key);\r\n}\r\nclass QueryStartAfterConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('startAfter', this._value, query._path, false);\r\n const newParams = queryParamsStartAfter(query._queryParams, this._value, this._key);\r\n validateLimit(newParams);\r\n validateQueryEndpoints(newParams);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('startAfter: Starting point was already set (by another call to startAt, ' +\r\n 'startAfter, or equalTo).');\r\n }\r\n return new QueryImpl(query._repo, query._path, newParams, query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` with the specified starting point (exclusive).\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The starting point is exclusive. If only a value is provided, children\r\n * with a value greater than the specified value will be included in the query.\r\n * If a key is specified, then children must have a value greater than or equal\r\n * to the specified value and a a key name greater than the specified key.\r\n *\r\n * @param value - The value to start after. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start after. This argument is only allowed if\r\n * ordering by child, value, or priority.\r\n */\r\nfunction startAfter(value, key) {\r\n validateKey('startAfter', 'key', key, true);\r\n return new QueryStartAfterConstraint(value, key);\r\n}\r\nclass QueryLimitToFirstConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToFirst: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToFirst(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that if limited to the first specific number\r\n * of children.\r\n *\r\n * The `limitToFirst()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the first 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToFirst()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToFirst(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToFirst: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToFirstConstraint(limit);\r\n}\r\nclass QueryLimitToLastConstraint extends QueryConstraint {\r\n constructor(_limit) {\r\n super();\r\n this._limit = _limit;\r\n }\r\n _apply(query) {\r\n if (query._queryParams.hasLimit()) {\r\n throw new Error('limitToLast: Limit was already set (by another call to limitToFirst ' +\r\n 'or limitToLast).');\r\n }\r\n return new QueryImpl(query._repo, query._path, queryParamsLimitToLast(query._queryParams, this._limit), query._orderByCalled);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that is limited to return only the last\r\n * specified number of children.\r\n *\r\n * The `limitToLast()` method is used to set a maximum number of children to be\r\n * synced for a given callback. If we set a limit of 100, we will initially only\r\n * receive up to 100 `child_added` events. If we have fewer than 100 messages\r\n * stored in our Database, a `child_added` event will fire for each message.\r\n * However, if we have over 100 messages, we will only receive a `child_added`\r\n * event for the last 100 ordered messages. As items change, we will receive\r\n * `child_removed` events for each item that drops out of the active list so\r\n * that the total number stays at 100.\r\n *\r\n * You can read more about `limitToLast()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param limit - The maximum number of nodes to include in this query.\r\n */\r\nfunction limitToLast(limit) {\r\n if (typeof limit !== 'number' || Math.floor(limit) !== limit || limit <= 0) {\r\n throw new Error('limitToLast: First argument must be a positive integer.');\r\n }\r\n return new QueryLimitToLastConstraint(limit);\r\n}\r\nclass QueryOrderByChildConstraint extends QueryConstraint {\r\n constructor(_path) {\r\n super();\r\n this._path = _path;\r\n }\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByChild');\r\n const parsedPath = new Path(this._path);\r\n if (pathIsEmpty(parsedPath)) {\r\n throw new Error('orderByChild: cannot pass in empty path. Use orderByValue() instead.');\r\n }\r\n const index = new PathIndex(parsedPath);\r\n const newParams = queryParamsOrderBy(query._queryParams, index);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the specified child key.\r\n *\r\n * Queries can only order by one key at a time. Calling `orderByChild()`\r\n * multiple times on the same query is an error.\r\n *\r\n * Firebase queries allow you to order your data by any child key on the fly.\r\n * However, if you know in advance what your indexes will be, you can define\r\n * them via the .indexOn rule in your Security Rules for better performance. See\r\n * the{@link https://firebase.google.com/docs/database/security/indexing-data}\r\n * rule for more information.\r\n *\r\n * You can read more about `orderByChild()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n *\r\n * @param path - The path to order by.\r\n */\r\nfunction orderByChild(path) {\r\n if (path === '$key') {\r\n throw new Error('orderByChild: \"$key\" is invalid. Use orderByKey() instead.');\r\n }\r\n else if (path === '$priority') {\r\n throw new Error('orderByChild: \"$priority\" is invalid. Use orderByPriority() instead.');\r\n }\r\n else if (path === '$value') {\r\n throw new Error('orderByChild: \"$value\" is invalid. Use orderByValue() instead.');\r\n }\r\n validatePathString('orderByChild', 'path', path, false);\r\n return new QueryOrderByChildConstraint(path);\r\n}\r\nclass QueryOrderByKeyConstraint extends QueryConstraint {\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByKey');\r\n const newParams = queryParamsOrderBy(query._queryParams, KEY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by the key.\r\n *\r\n * Sorts the results of a query by their (ascending) key values.\r\n *\r\n * You can read more about `orderByKey()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByKey() {\r\n return new QueryOrderByKeyConstraint();\r\n}\r\nclass QueryOrderByPriorityConstraint extends QueryConstraint {\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByPriority');\r\n const newParams = queryParamsOrderBy(query._queryParams, PRIORITY_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by priority.\r\n *\r\n * Applications need not use priority but can order collections by\r\n * ordinary properties (see\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}\r\n * for alternatives to priority.\r\n */\r\nfunction orderByPriority() {\r\n return new QueryOrderByPriorityConstraint();\r\n}\r\nclass QueryOrderByValueConstraint extends QueryConstraint {\r\n _apply(query) {\r\n validateNoPreviousOrderByCall(query, 'orderByValue');\r\n const newParams = queryParamsOrderBy(query._queryParams, VALUE_INDEX);\r\n validateQueryEndpoints(newParams);\r\n return new QueryImpl(query._repo, query._path, newParams, \r\n /*orderByCalled=*/ true);\r\n }\r\n}\r\n/**\r\n * Creates a new `QueryConstraint` that orders by value.\r\n *\r\n * If the children of a query are all scalar values (string, number, or\r\n * boolean), you can order the results by their (ascending) values.\r\n *\r\n * You can read more about `orderByValue()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#sort_data | Sort data}.\r\n */\r\nfunction orderByValue() {\r\n return new QueryOrderByValueConstraint();\r\n}\r\nclass QueryEqualToValueConstraint extends QueryConstraint {\r\n constructor(_value, _key) {\r\n super();\r\n this._value = _value;\r\n this._key = _key;\r\n }\r\n _apply(query) {\r\n validateFirebaseDataArg('equalTo', this._value, query._path, false);\r\n if (query._queryParams.hasStart()) {\r\n throw new Error('equalTo: Starting point was already set (by another call to startAt/startAfter or ' +\r\n 'equalTo).');\r\n }\r\n if (query._queryParams.hasEnd()) {\r\n throw new Error('equalTo: Ending point was already set (by another call to endAt/endBefore or ' +\r\n 'equalTo).');\r\n }\r\n return new QueryEndAtConstraint(this._value, this._key)._apply(new QueryStartAtConstraint(this._value, this._key)._apply(query));\r\n }\r\n}\r\n/**\r\n * Creates a `QueryConstraint` that includes children that match the specified\r\n * value.\r\n *\r\n * Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`\r\n * allows you to choose arbitrary starting and ending points for your queries.\r\n *\r\n * The optional key argument can be used to further limit the range of the\r\n * query. If it is specified, then children that have exactly the specified\r\n * value must also have exactly the specified key as their key name. This can be\r\n * used to filter result sets with many matches for the same value.\r\n *\r\n * You can read more about `equalTo()` in\r\n * {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.\r\n *\r\n * @param value - The value to match for. The argument type depends on which\r\n * `orderBy*()` function was used in this query. Specify a value that matches\r\n * the `orderBy*()` type. When used in combination with `orderByKey()`, the\r\n * value must be a string.\r\n * @param key - The child key to start at, among the children with the\r\n * previously specified priority. This argument is only allowed if ordering by\r\n * child, value, or priority.\r\n */\r\nfunction equalTo(value, key) {\r\n validateKey('equalTo', 'key', key, true);\r\n return new QueryEqualToValueConstraint(value, key);\r\n}\r\n/**\r\n * Creates a new immutable instance of `Query` that is extended to also include\r\n * additional query constraints.\r\n *\r\n * @param query - The Query instance to use as a base for the new constraints.\r\n * @param queryConstraints - The list of `QueryConstraint`s to apply.\r\n * @throws if any of the provided query constraints cannot be combined with the\r\n * existing or new constraints.\r\n */\r\nfunction query(query, ...queryConstraints) {\r\n let queryImpl = getModularInstance(query);\r\n for (const constraint of queryConstraints) {\r\n queryImpl = constraint._apply(queryImpl);\r\n }\r\n return queryImpl;\r\n}\r\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\r\nsyncPointSetReferenceConstructor(ReferenceImpl);\r\nsyncTreeSetReferenceConstructor(ReferenceImpl);\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * This variable is also defined in the firebase Node.js Admin SDK. Before\r\n * modifying this definition, consult the definition in:\r\n *\r\n * https://github.com/firebase/firebase-admin-node\r\n *\r\n * and make sure the two are consistent.\r\n */\r\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\r\n/**\r\n * Creates and caches `Repo` instances.\r\n */\r\nconst repos = {};\r\n/**\r\n * If true, any new `Repo` will be created to use `ReadonlyRestClient` (for testing purposes).\r\n */\r\nlet useRestClient = false;\r\n/**\r\n * Update an existing `Repo` in place to point to a new host/port.\r\n */\r\nfunction repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {\r\n repo.repoInfo_ = new RepoInfo(`${host}:${port}`, \r\n /* secure= */ false, repo.repoInfo_.namespace, repo.repoInfo_.webSocketOnly, repo.repoInfo_.nodeAdmin, repo.repoInfo_.persistenceKey, repo.repoInfo_.includeNamespaceInQueryParams);\r\n if (tokenProvider) {\r\n repo.authTokenProvider_ = tokenProvider;\r\n }\r\n}\r\n/**\r\n * This function should only ever be called to CREATE a new database instance.\r\n * @internal\r\n */\r\nfunction repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {\r\n let dbUrl = url || app.options.databaseURL;\r\n if (dbUrl === undefined) {\r\n if (!app.options.projectId) {\r\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\r\n ' a Project ID when calling firebase.initializeApp().');\r\n }\r\n log('Using default host for project ', app.options.projectId);\r\n dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;\r\n }\r\n let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n let repoInfo = parsedUrl.repoInfo;\r\n let isEmulator;\r\n let dbEmulatorHost = undefined;\r\n if (typeof process !== 'undefined' && process.env) {\r\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\r\n }\r\n if (dbEmulatorHost) {\r\n isEmulator = true;\r\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\r\n parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);\r\n repoInfo = parsedUrl.repoInfo;\r\n }\r\n else {\r\n isEmulator = !parsedUrl.repoInfo.secure;\r\n }\r\n const authTokenProvider = nodeAdmin && isEmulator\r\n ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)\r\n : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);\r\n validateUrl('Invalid Firebase Database URL', parsedUrl);\r\n if (!pathIsEmpty(parsedUrl.path)) {\r\n fatal('Database URL must point to the root of a Firebase Database ' +\r\n '(not including a child path).');\r\n }\r\n const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));\r\n return new Database(repo, app);\r\n}\r\n/**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n */\r\nfunction repoManagerDeleteRepo(repo, appName) {\r\n const appRepos = repos[appName];\r\n // This should never happen...\r\n if (!appRepos || appRepos[repo.key] !== repo) {\r\n fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);\r\n }\r\n repoInterrupt(repo);\r\n delete appRepos[repo.key];\r\n}\r\n/**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param repoInfo - The metadata about the Repo\r\n * @returns The Repo object for the specified server / repoName.\r\n */\r\nfunction repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {\r\n let appRepos = repos[app.name];\r\n if (!appRepos) {\r\n appRepos = {};\r\n repos[app.name] = appRepos;\r\n }\r\n let repo = appRepos[repoInfo.toURLString()];\r\n if (repo) {\r\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\r\n }\r\n repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);\r\n appRepos[repoInfo.toURLString()] = repo;\r\n return repo;\r\n}\r\n/**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n */\r\nfunction repoManagerForceRestClient(forceRestClient) {\r\n useRestClient = forceRestClient;\r\n}\r\n/**\r\n * Class representing a Firebase Realtime Database.\r\n */\r\nclass Database {\r\n /** @hideconstructor */\r\n constructor(_repoInternal, \r\n /** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */\r\n app) {\r\n this._repoInternal = _repoInternal;\r\n this.app = app;\r\n /** Represents a `Database` instance. */\r\n this['type'] = 'database';\r\n /** Track if the instance has been used (root or repo accessed) */\r\n this._instanceStarted = false;\r\n }\r\n get _repo() {\r\n if (!this._instanceStarted) {\r\n repoStart(this._repoInternal, this.app.options.appId, this.app.options['databaseAuthVariableOverride']);\r\n this._instanceStarted = true;\r\n }\r\n return this._repoInternal;\r\n }\r\n get _root() {\r\n if (!this._rootInternal) {\r\n this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());\r\n }\r\n return this._rootInternal;\r\n }\r\n _delete() {\r\n if (this._rootInternal !== null) {\r\n repoManagerDeleteRepo(this._repo, this.app.name);\r\n this._repoInternal = null;\r\n this._rootInternal = null;\r\n }\r\n return Promise.resolve();\r\n }\r\n _checkNotDeleted(apiName) {\r\n if (this._rootInternal === null) {\r\n fatal('Cannot call ' + apiName + ' on a deleted database.');\r\n }\r\n }\r\n}\r\n/**\r\n * Returns the instance of the Realtime Database SDK that is associated\r\n * with the provided {@link @firebase/app#FirebaseApp}. Initializes a new instance with\r\n * with default settings if no instance exists or if the existing instance uses\r\n * a custom database URL.\r\n *\r\n * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime\r\n * Database instance is associated with.\r\n * @param url - The URL of the Realtime Database instance to connect to. If not\r\n * provided, the SDK connects to the default instance of the Firebase App.\r\n * @returns The `Database` instance of the provided app.\r\n */\r\nfunction getDatabase(app = getApp(), url) {\r\n return _getProvider(app, 'database').getImmediate({\r\n identifier: url\r\n });\r\n}\r\n/**\r\n * Modify the provided instance to communicate with the Realtime Database\r\n * emulator.\r\n *\r\n *

Note: This method must be called before performing any other operation.\r\n *\r\n * @param db - The instance to modify.\r\n * @param host - The emulator host (ex: localhost)\r\n * @param port - The emulator port (ex: 8080)\r\n * @param options.mockUserToken - the mock auth token to use for unit testing Security Rules\r\n */\r\nfunction connectDatabaseEmulator(db, host, port, options = {}) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('useEmulator');\r\n if (db._instanceStarted) {\r\n fatal('Cannot call useEmulator() after instance has already been initialized.');\r\n }\r\n const repo = db._repoInternal;\r\n let tokenProvider = undefined;\r\n if (repo.repoInfo_.nodeAdmin) {\r\n if (options.mockUserToken) {\r\n fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the \"firebase\" package instead of \"firebase-admin\".');\r\n }\r\n tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);\r\n }\r\n else if (options.mockUserToken) {\r\n const token = typeof options.mockUserToken === 'string'\r\n ? options.mockUserToken\r\n : createMockUserToken(options.mockUserToken, db.app.options.projectId);\r\n tokenProvider = new EmulatorTokenProvider(token);\r\n }\r\n // Modify the repo to apply emulator settings\r\n repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);\r\n}\r\n/**\r\n * Disconnects from the server (all Database operations will be completed\r\n * offline).\r\n *\r\n * The client automatically maintains a persistent connection to the Database\r\n * server, which will remain active indefinitely and reconnect when\r\n * disconnected. However, the `goOffline()` and `goOnline()` methods may be used\r\n * to control the client connection in cases where a persistent connection is\r\n * undesirable.\r\n *\r\n * While offline, the client will no longer receive data updates from the\r\n * Database. However, all Database operations performed locally will continue to\r\n * immediately fire events, allowing your application to continue behaving\r\n * normally. Additionally, each operation performed locally will automatically\r\n * be queued and retried upon reconnection to the Database server.\r\n *\r\n * To reconnect to the Database and begin receiving remote events, see\r\n * `goOnline()`.\r\n *\r\n * @param db - The instance to disconnect.\r\n */\r\nfunction goOffline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOffline');\r\n repoInterrupt(db._repo);\r\n}\r\n/**\r\n * Reconnects to the server and synchronizes the offline Database state\r\n * with the server state.\r\n *\r\n * This method should be used after disabling the active connection with\r\n * `goOffline()`. Once reconnected, the client will transmit the proper data\r\n * and fire the appropriate events so that your client \"catches up\"\r\n * automatically.\r\n *\r\n * @param db - The instance to reconnect.\r\n */\r\nfunction goOnline(db) {\r\n db = getModularInstance(db);\r\n db._checkNotDeleted('goOnline');\r\n repoResume(db._repo);\r\n}\r\nfunction enableLogging(logger, persistent) {\r\n enableLogging$1(logger, persistent);\r\n}\n\n/**\r\n * @license\r\n * Copyright 2021 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction registerDatabase(variant) {\r\n setSDKVersion(SDK_VERSION$1);\r\n _registerComponent(new Component('database', (container, { instanceIdentifier: url }) => {\r\n const app = container.getProvider('app').getImmediate();\r\n const authProvider = container.getProvider('auth-internal');\r\n const appCheckProvider = container.getProvider('app-check-internal');\r\n return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);\r\n }, \"PUBLIC\" /* PUBLIC */).setMultipleInstances(true));\r\n registerVersion(name, version, variant);\r\n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\r\n registerVersion(name, version, 'esm2017');\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst SERVER_TIMESTAMP = {\r\n '.sv': 'timestamp'\r\n};\r\n/**\r\n * Returns a placeholder value for auto-populating the current timestamp (time\r\n * since the Unix epoch, in milliseconds) as determined by the Firebase\r\n * servers.\r\n */\r\nfunction serverTimestamp() {\r\n return SERVER_TIMESTAMP;\r\n}\r\n/**\r\n * Returns a placeholder value that can be used to atomically increment the\r\n * current database value by the provided delta.\r\n *\r\n * @param delta - the amount to modify the current value atomically.\r\n * @returns A placeholder value for modifying data atomically server-side.\r\n */\r\nfunction increment(delta) {\r\n return {\r\n '.sv': {\r\n 'increment': delta\r\n }\r\n };\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\n/**\r\n * A type for the resolve value of {@link runTransaction}.\r\n */\r\nclass TransactionResult {\r\n /** @hideconstructor */\r\n constructor(\r\n /** Whether the transaction was successfully committed. */\r\n committed, \r\n /** The resulting data snapshot. */\r\n snapshot) {\r\n this.committed = committed;\r\n this.snapshot = snapshot;\r\n }\r\n /** Returns a JSON-serializable representation of this object. */\r\n toJSON() {\r\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\r\n }\r\n}\r\n/**\r\n * Atomically modifies the data at this location.\r\n *\r\n * Atomically modify the data at this location. Unlike a normal `set()`, which\r\n * just overwrites the data regardless of its previous value, `runTransaction()` is\r\n * used to modify the existing value to a new value, ensuring there are no\r\n * conflicts with other clients writing to the same location at the same time.\r\n *\r\n * To accomplish this, you pass `runTransaction()` an update function which is\r\n * used to transform the current value into a new value. If another client\r\n * writes to the location before your new value is successfully written, your\r\n * update function will be called again with the new current value, and the\r\n * write will be retried. This will happen repeatedly until your write succeeds\r\n * without conflict or you abort the transaction by not returning a value from\r\n * your update function.\r\n *\r\n * Note: Modifying data with `set()` will cancel any pending transactions at\r\n * that location, so extreme care should be taken if mixing `set()` and\r\n * `runTransaction()` to update the same data.\r\n *\r\n * Note: When using transactions with Security and Firebase Rules in place, be\r\n * aware that a client needs `.read` access in addition to `.write` access in\r\n * order to perform a transaction. This is because the client-side nature of\r\n * transactions requires the client to read the data in order to transactionally\r\n * update it.\r\n *\r\n * @param ref - The location to atomically modify.\r\n * @param transactionUpdate - A developer-supplied function which will be passed\r\n * the current data stored at this location (as a JavaScript object). The\r\n * function should return the new value it would like written (as a JavaScript\r\n * object). If `undefined` is returned (i.e. you return with no arguments) the\r\n * transaction will be aborted and the data at this location will not be\r\n * modified.\r\n * @param options - An options object to configure transactions.\r\n * @returns A `Promise` that can optionally be used instead of the `onComplete`\r\n * callback to handle success and failure.\r\n */\r\nfunction runTransaction(ref, \r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\ntransactionUpdate, options) {\r\n var _a;\r\n ref = getModularInstance(ref);\r\n validateWritablePath('Reference.transaction', ref._path);\r\n if (ref.key === '.length' || ref.key === '.keys') {\r\n throw ('Reference.transaction failed: ' + ref.key + ' is a read-only object.');\r\n }\r\n const applyLocally = (_a = options === null || options === void 0 ? void 0 : options.applyLocally) !== null && _a !== void 0 ? _a : true;\r\n const deferred = new Deferred();\r\n const promiseComplete = (error, committed, node) => {\r\n let dataSnapshot = null;\r\n if (error) {\r\n deferred.reject(error);\r\n }\r\n else {\r\n dataSnapshot = new DataSnapshot(node, new ReferenceImpl(ref._repo, ref._path), PRIORITY_INDEX);\r\n deferred.resolve(new TransactionResult(committed, dataSnapshot));\r\n }\r\n };\r\n // Add a watch to make sure we get server updates.\r\n const unwatcher = onValue(ref, () => { });\r\n repoStartTransaction(ref._repo, ref._path, transactionUpdate, promiseComplete, unwatcher, applyLocally);\r\n return deferred.promise;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2017 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nPersistentConnection;\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\r\n this.sendRequest('q', { p: pathString }, onComplete);\r\n};\r\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\r\nPersistentConnection.prototype.echo = function (data, onEcho) {\r\n this.sendRequest('echo', { d: data }, onEcho);\r\n};\r\n// RealTimeConnection properties that we use in tests.\r\nConnection;\r\n/**\r\n * @internal\r\n */\r\nconst hijackHash = function (newHash) {\r\n const oldPut = PersistentConnection.prototype.put;\r\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\r\n if (hash !== undefined) {\r\n hash = newHash();\r\n }\r\n oldPut.call(this, pathString, data, onComplete, hash);\r\n };\r\n return function () {\r\n PersistentConnection.prototype.put = oldPut;\r\n };\r\n};\r\nRepoInfo;\r\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n * @internal\r\n */\r\nconst forceRestClient = function (forceRestClient) {\r\n repoManagerForceRestClient(forceRestClient);\r\n};\n\n/**\r\n * Firebase Realtime Database\r\n *\r\n * @packageDocumentation\r\n */\r\nregisterDatabase();\n\nexport { DataSnapshot, Database, OnDisconnect, QueryConstraint, TransactionResult, QueryImpl as _QueryImpl, QueryParams as _QueryParams, ReferenceImpl as _ReferenceImpl, forceRestClient as _TEST_ACCESS_forceRestClient, hijackHash as _TEST_ACCESS_hijackHash, repoManagerDatabaseFromApp as _repoManagerDatabaseFromApp, setSDKVersion as _setSDKVersion, validatePathString as _validatePathString, validateWritablePath as _validateWritablePath, child, connectDatabaseEmulator, enableLogging, endAt, endBefore, equalTo, get, getDatabase, goOffline, goOnline, increment, limitToFirst, limitToLast, off, onChildAdded, onChildChanged, onChildMoved, onChildRemoved, onDisconnect, onValue, orderByChild, orderByKey, orderByPriority, orderByValue, push, query, ref, refFromURL, remove, runTransaction, serverTimestamp, set, setPriority, setWithPriority, startAfter, startAt, update };\n//# sourceMappingURL=index.esm2017.js.map\n","import firebase from '@firebase/app-compat';\nimport * as exp from '@firebase/auth/internal';\nimport { Component } from '@firebase/component';\nimport { isBrowserExtension, isReactNative, isNode, getUA, isIE, isIndexedDBAvailable, FirebaseError } from '@firebase/util';\n\nvar name = \"@firebase/auth-compat\";\nvar version = \"0.2.12\";\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst CORDOVA_ONDEVICEREADY_TIMEOUT_MS = 1000;\r\nfunction _getCurrentScheme() {\r\n var _a;\r\n return ((_a = self === null || self === void 0 ? void 0 : self.location) === null || _a === void 0 ? void 0 : _a.protocol) || null;\r\n}\r\n/**\r\n * @return {boolean} Whether the current environment is http or https.\r\n */\r\nfunction _isHttpOrHttps() {\r\n return _getCurrentScheme() === 'http:' || _getCurrentScheme() === 'https:';\r\n}\r\n/**\r\n * @param {?string=} ua The user agent.\r\n * @return {boolean} Whether the app is rendered in a mobile iOS or Android\r\n * Cordova environment.\r\n */\r\nfunction _isAndroidOrIosCordovaScheme(ua = getUA()) {\r\n return !!((_getCurrentScheme() === 'file:' || _getCurrentScheme() === 'ionic:') &&\r\n ua.toLowerCase().match(/iphone|ipad|ipod|android/));\r\n}\r\n/**\r\n * @return {boolean} Whether the environment is a native environment, where\r\n * CORS checks do not apply.\r\n */\r\nfunction _isNativeEnvironment() {\r\n return isReactNative() || isNode();\r\n}\r\n/**\r\n * Checks whether the user agent is IE11.\r\n * @return {boolean} True if it is IE11.\r\n */\r\nfunction _isIe11() {\r\n return isIE() && (document === null || document === void 0 ? void 0 : document.documentMode) === 11;\r\n}\r\n/**\r\n * Checks whether the user agent is Edge.\r\n * @param {string} userAgent The browser user agent string.\r\n * @return {boolean} True if it is Edge.\r\n */\r\nfunction _isEdge(ua = getUA()) {\r\n return /Edge\\/\\d+/.test(ua);\r\n}\r\n/**\r\n * @param {?string=} opt_userAgent The navigator user agent.\r\n * @return {boolean} Whether local storage is not synchronized between an iframe\r\n * and a popup of the same domain.\r\n */\r\nfunction _isLocalStorageNotSynchronized(ua = getUA()) {\r\n return _isIe11() || _isEdge(ua);\r\n}\r\n/** @return {boolean} Whether web storage is supported. */\r\nfunction _isWebStorageSupported() {\r\n try {\r\n const storage = self.localStorage;\r\n const key = exp._generateEventId();\r\n if (storage) {\r\n // setItem will throw an exception if we cannot access WebStorage (e.g.,\r\n // Safari in private mode).\r\n storage['setItem'](key, '1');\r\n storage['removeItem'](key);\r\n // For browsers where iframe web storage does not synchronize with a popup\r\n // of the same domain, indexedDB is used for persistent storage. These\r\n // browsers include IE11 and Edge.\r\n // Make sure it is supported (IE11 and Edge private mode does not support\r\n // that).\r\n if (_isLocalStorageNotSynchronized()) {\r\n // In such browsers, if indexedDB is not supported, an iframe cannot be\r\n // notified of the popup sign in result.\r\n return isIndexedDBAvailable();\r\n }\r\n return true;\r\n }\r\n }\r\n catch (e) {\r\n // localStorage is not available from a worker. Test availability of\r\n // indexedDB.\r\n return _isWorker() && isIndexedDBAvailable();\r\n }\r\n return false;\r\n}\r\n/**\r\n * @param {?Object=} global The optional global scope.\r\n * @return {boolean} Whether current environment is a worker.\r\n */\r\nfunction _isWorker() {\r\n // WorkerGlobalScope only defined in worker environment.\r\n return (typeof global !== 'undefined' &&\r\n 'WorkerGlobalScope' in global &&\r\n 'importScripts' in global);\r\n}\r\nfunction _isPopupRedirectSupported() {\r\n return ((_isHttpOrHttps() ||\r\n isBrowserExtension() ||\r\n _isAndroidOrIosCordovaScheme()) &&\r\n // React Native with remote debugging reports its location.protocol as\r\n // http.\r\n !_isNativeEnvironment() &&\r\n // Local storage has to be supported for browser popup and redirect\r\n // operations to work.\r\n _isWebStorageSupported() &&\r\n // DOM, popups and redirects are not supported within a worker.\r\n !_isWorker());\r\n}\r\n/** Quick check that indicates the platform *may* be Cordova */\r\nfunction _isLikelyCordova() {\r\n return _isAndroidOrIosCordovaScheme() && typeof document !== 'undefined';\r\n}\r\nasync function _isCordova() {\r\n if (!_isLikelyCordova()) {\r\n return false;\r\n }\r\n return new Promise(resolve => {\r\n const timeoutId = setTimeout(() => {\r\n // We've waited long enough; the telltale Cordova event didn't happen\r\n resolve(false);\r\n }, CORDOVA_ONDEVICEREADY_TIMEOUT_MS);\r\n document.addEventListener('deviceready', () => {\r\n clearTimeout(timeoutId);\r\n resolve(true);\r\n });\r\n });\r\n}\r\nfunction _getSelfWindow() {\r\n return typeof window !== 'undefined' ? window : null;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst Persistence = {\r\n LOCAL: 'local',\r\n NONE: 'none',\r\n SESSION: 'session'\r\n};\r\nconst _assert$3 = exp._assert;\r\nconst PERSISTENCE_KEY = 'persistence';\r\n/**\r\n * Validates that an argument is a valid persistence value. If an invalid type\r\n * is specified, an error is thrown synchronously.\r\n */\r\nfunction _validatePersistenceArgument(auth, persistence) {\r\n _assert$3(Object.values(Persistence).includes(persistence), auth, \"invalid-persistence-type\" /* INVALID_PERSISTENCE */);\r\n // Validate if the specified type is supported in the current environment.\r\n if (isReactNative()) {\r\n // This is only supported in a browser.\r\n _assert$3(persistence !== Persistence.SESSION, auth, \"unsupported-persistence-type\" /* UNSUPPORTED_PERSISTENCE */);\r\n return;\r\n }\r\n if (isNode()) {\r\n // Only none is supported in Node.js.\r\n _assert$3(persistence === Persistence.NONE, auth, \"unsupported-persistence-type\" /* UNSUPPORTED_PERSISTENCE */);\r\n return;\r\n }\r\n if (_isWorker()) {\r\n // In a worker environment, either LOCAL or NONE are supported.\r\n // If indexedDB not supported and LOCAL provided, throw an error\r\n _assert$3(persistence === Persistence.NONE ||\r\n (persistence === Persistence.LOCAL && isIndexedDBAvailable()), auth, \"unsupported-persistence-type\" /* UNSUPPORTED_PERSISTENCE */);\r\n return;\r\n }\r\n // This is restricted by what the browser supports.\r\n _assert$3(persistence === Persistence.NONE || _isWebStorageSupported(), auth, \"unsupported-persistence-type\" /* UNSUPPORTED_PERSISTENCE */);\r\n}\r\nasync function _savePersistenceForRedirect(auth) {\r\n await auth._initializationPromise;\r\n const session = getSessionStorageIfAvailable();\r\n const key = exp._persistenceKeyName(PERSISTENCE_KEY, auth.config.apiKey, auth.name);\r\n if (session) {\r\n session.setItem(key, auth._getPersistence());\r\n }\r\n}\r\nfunction _getPersistencesFromRedirect(apiKey, appName) {\r\n const session = getSessionStorageIfAvailable();\r\n if (!session) {\r\n return [];\r\n }\r\n const key = exp._persistenceKeyName(PERSISTENCE_KEY, apiKey, appName);\r\n const persistence = session.getItem(key);\r\n switch (persistence) {\r\n case Persistence.NONE:\r\n return [exp.inMemoryPersistence];\r\n case Persistence.LOCAL:\r\n return [exp.indexedDBLocalPersistence, exp.browserSessionPersistence];\r\n case Persistence.SESSION:\r\n return [exp.browserSessionPersistence];\r\n default:\r\n return [];\r\n }\r\n}\r\n/** Returns session storage, or null if the property access errors */\r\nfunction getSessionStorageIfAvailable() {\r\n var _a;\r\n try {\r\n return ((_a = _getSelfWindow()) === null || _a === void 0 ? void 0 : _a.sessionStorage) || null;\r\n }\r\n catch (e) {\r\n return null;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _assert$2 = exp._assert;\r\n/** Platform-agnostic popup-redirect resolver */\r\nclass CompatPopupRedirectResolver {\r\n constructor() {\r\n // Create both resolvers for dynamic resolution later\r\n this.browserResolver = exp._getInstance(exp.browserPopupRedirectResolver);\r\n this.cordovaResolver = exp._getInstance(exp.cordovaPopupRedirectResolver);\r\n // The actual resolver in use: either browserResolver or cordovaResolver.\r\n this.underlyingResolver = null;\r\n this._redirectPersistence = exp.browserSessionPersistence;\r\n this._completeRedirectFn = exp._getRedirectResult;\r\n }\r\n async _initialize(auth) {\r\n await this.selectUnderlyingResolver();\r\n return this.assertedUnderlyingResolver._initialize(auth);\r\n }\r\n async _openPopup(auth, provider, authType, eventId) {\r\n await this.selectUnderlyingResolver();\r\n return this.assertedUnderlyingResolver._openPopup(auth, provider, authType, eventId);\r\n }\r\n async _openRedirect(auth, provider, authType, eventId) {\r\n await this.selectUnderlyingResolver();\r\n return this.assertedUnderlyingResolver._openRedirect(auth, provider, authType, eventId);\r\n }\r\n _isIframeWebStorageSupported(auth, cb) {\r\n this.assertedUnderlyingResolver._isIframeWebStorageSupported(auth, cb);\r\n }\r\n _originValidation(auth) {\r\n return this.assertedUnderlyingResolver._originValidation(auth);\r\n }\r\n get _shouldInitProactively() {\r\n return _isLikelyCordova() || this.browserResolver._shouldInitProactively;\r\n }\r\n get assertedUnderlyingResolver() {\r\n _assert$2(this.underlyingResolver, \"internal-error\" /* INTERNAL_ERROR */);\r\n return this.underlyingResolver;\r\n }\r\n async selectUnderlyingResolver() {\r\n if (this.underlyingResolver) {\r\n return;\r\n }\r\n // We haven't yet determined whether or not we're in Cordova; go ahead\r\n // and determine that state now.\r\n const isCordova = await _isCordova();\r\n this.underlyingResolver = isCordova\r\n ? this.cordovaResolver\r\n : this.browserResolver;\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction unwrap(object) {\r\n return object.unwrap();\r\n}\r\nfunction wrapped(object) {\r\n return object.wrapped();\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nfunction credentialFromResponse(userCredential) {\r\n return credentialFromObject(userCredential);\r\n}\r\nfunction attachExtraErrorFields(auth, e) {\r\n var _a;\r\n // The response contains all fields from the server which may or may not\r\n // actually match the underlying type\r\n const response = (_a = e.customData) === null || _a === void 0 ? void 0 : _a._tokenResponse;\r\n if (e.code === 'auth/multi-factor-auth-required') {\r\n const mfaErr = e;\r\n mfaErr.resolver = new MultiFactorResolver(auth, exp.getMultiFactorResolver(auth, e));\r\n }\r\n else if (response) {\r\n const credential = credentialFromObject(e);\r\n const credErr = e;\r\n if (credential) {\r\n credErr.credential = credential;\r\n credErr.tenantId = response.tenantId || undefined;\r\n credErr.email = response.email || undefined;\r\n credErr.phoneNumber = response.phoneNumber || undefined;\r\n }\r\n }\r\n}\r\nfunction credentialFromObject(object) {\r\n const { _tokenResponse } = (object instanceof FirebaseError ? object.customData : object);\r\n if (!_tokenResponse) {\r\n return null;\r\n }\r\n // Handle phone Auth credential responses, as they have a different format\r\n // from other backend responses (i.e. no providerId). This is also only the\r\n // case for user credentials (does not work for errors).\r\n if (!(object instanceof FirebaseError)) {\r\n if ('temporaryProof' in _tokenResponse && 'phoneNumber' in _tokenResponse) {\r\n return exp.PhoneAuthProvider.credentialFromResult(object);\r\n }\r\n }\r\n const providerId = _tokenResponse.providerId;\r\n // Email and password is not supported as there is no situation where the\r\n // server would return the password to the client.\r\n if (!providerId || providerId === exp.ProviderId.PASSWORD) {\r\n return null;\r\n }\r\n let provider;\r\n switch (providerId) {\r\n case exp.ProviderId.GOOGLE:\r\n provider = exp.GoogleAuthProvider;\r\n break;\r\n case exp.ProviderId.FACEBOOK:\r\n provider = exp.FacebookAuthProvider;\r\n break;\r\n case exp.ProviderId.GITHUB:\r\n provider = exp.GithubAuthProvider;\r\n break;\r\n case exp.ProviderId.TWITTER:\r\n provider = exp.TwitterAuthProvider;\r\n break;\r\n default:\r\n const { oauthIdToken, oauthAccessToken, oauthTokenSecret, pendingToken, nonce } = _tokenResponse;\r\n if (!oauthAccessToken &&\r\n !oauthTokenSecret &&\r\n !oauthIdToken &&\r\n !pendingToken) {\r\n return null;\r\n }\r\n // TODO(avolkovi): uncomment this and get it working with SAML & OIDC\r\n if (pendingToken) {\r\n if (providerId.startsWith('saml.')) {\r\n return exp.SAMLAuthCredential._create(providerId, pendingToken);\r\n }\r\n else {\r\n // OIDC and non-default providers excluding Twitter.\r\n return exp.OAuthCredential._fromParams({\r\n providerId,\r\n signInMethod: providerId,\r\n pendingToken,\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken\r\n });\r\n }\r\n }\r\n return new exp.OAuthProvider(providerId).credential({\r\n idToken: oauthIdToken,\r\n accessToken: oauthAccessToken,\r\n rawNonce: nonce\r\n });\r\n }\r\n return object instanceof FirebaseError\r\n ? provider.credentialFromError(object)\r\n : provider.credentialFromResult(object);\r\n}\r\nfunction convertCredential(auth, credentialPromise) {\r\n return credentialPromise\r\n .catch(e => {\r\n if (e instanceof FirebaseError) {\r\n attachExtraErrorFields(auth, e);\r\n }\r\n throw e;\r\n })\r\n .then(credential => {\r\n const operationType = credential.operationType;\r\n const user = credential.user;\r\n return {\r\n operationType,\r\n credential: credentialFromResponse(credential),\r\n additionalUserInfo: exp.getAdditionalUserInfo(credential),\r\n user: User.getOrCreate(user)\r\n };\r\n });\r\n}\r\nasync function convertConfirmationResult(auth, confirmationResultPromise) {\r\n const confirmationResultExp = await confirmationResultPromise;\r\n return {\r\n verificationId: confirmationResultExp.verificationId,\r\n confirm: (verificationCode) => convertCredential(auth, confirmationResultExp.confirm(verificationCode))\r\n };\r\n}\r\nclass MultiFactorResolver {\r\n constructor(auth, resolver) {\r\n this.resolver = resolver;\r\n this.auth = wrapped(auth);\r\n }\r\n get session() {\r\n return this.resolver.session;\r\n }\r\n get hints() {\r\n return this.resolver.hints;\r\n }\r\n resolveSignIn(assertion) {\r\n return convertCredential(unwrap(this.auth), this.resolver.resolveSignIn(assertion));\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass User {\r\n constructor(_delegate) {\r\n this._delegate = _delegate;\r\n this.multiFactor = exp.multiFactor(_delegate);\r\n }\r\n static getOrCreate(user) {\r\n if (!User.USER_MAP.has(user)) {\r\n User.USER_MAP.set(user, new User(user));\r\n }\r\n return User.USER_MAP.get(user);\r\n }\r\n delete() {\r\n return this._delegate.delete();\r\n }\r\n reload() {\r\n return this._delegate.reload();\r\n }\r\n toJSON() {\r\n return this._delegate.toJSON();\r\n }\r\n getIdTokenResult(forceRefresh) {\r\n return this._delegate.getIdTokenResult(forceRefresh);\r\n }\r\n getIdToken(forceRefresh) {\r\n return this._delegate.getIdToken(forceRefresh);\r\n }\r\n linkAndRetrieveDataWithCredential(credential) {\r\n return this.linkWithCredential(credential);\r\n }\r\n async linkWithCredential(credential) {\r\n return convertCredential(this.auth, exp.linkWithCredential(this._delegate, credential));\r\n }\r\n async linkWithPhoneNumber(phoneNumber, applicationVerifier) {\r\n return convertConfirmationResult(this.auth, exp.linkWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier));\r\n }\r\n async linkWithPopup(provider) {\r\n return convertCredential(this.auth, exp.linkWithPopup(this._delegate, provider, CompatPopupRedirectResolver));\r\n }\r\n async linkWithRedirect(provider) {\r\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\r\n return exp.linkWithRedirect(this._delegate, provider, CompatPopupRedirectResolver);\r\n }\r\n reauthenticateAndRetrieveDataWithCredential(credential) {\r\n return this.reauthenticateWithCredential(credential);\r\n }\r\n async reauthenticateWithCredential(credential) {\r\n return convertCredential(this.auth, exp.reauthenticateWithCredential(this._delegate, credential));\r\n }\r\n reauthenticateWithPhoneNumber(phoneNumber, applicationVerifier) {\r\n return convertConfirmationResult(this.auth, exp.reauthenticateWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier));\r\n }\r\n reauthenticateWithPopup(provider) {\r\n return convertCredential(this.auth, exp.reauthenticateWithPopup(this._delegate, provider, CompatPopupRedirectResolver));\r\n }\r\n async reauthenticateWithRedirect(provider) {\r\n await _savePersistenceForRedirect(exp._castAuth(this.auth));\r\n return exp.reauthenticateWithRedirect(this._delegate, provider, CompatPopupRedirectResolver);\r\n }\r\n sendEmailVerification(actionCodeSettings) {\r\n return exp.sendEmailVerification(this._delegate, actionCodeSettings);\r\n }\r\n async unlink(providerId) {\r\n await exp.unlink(this._delegate, providerId);\r\n return this;\r\n }\r\n updateEmail(newEmail) {\r\n return exp.updateEmail(this._delegate, newEmail);\r\n }\r\n updatePassword(newPassword) {\r\n return exp.updatePassword(this._delegate, newPassword);\r\n }\r\n updatePhoneNumber(phoneCredential) {\r\n return exp.updatePhoneNumber(this._delegate, phoneCredential);\r\n }\r\n updateProfile(profile) {\r\n return exp.updateProfile(this._delegate, profile);\r\n }\r\n verifyBeforeUpdateEmail(newEmail, actionCodeSettings) {\r\n return exp.verifyBeforeUpdateEmail(this._delegate, newEmail, actionCodeSettings);\r\n }\r\n get emailVerified() {\r\n return this._delegate.emailVerified;\r\n }\r\n get isAnonymous() {\r\n return this._delegate.isAnonymous;\r\n }\r\n get metadata() {\r\n return this._delegate.metadata;\r\n }\r\n get phoneNumber() {\r\n return this._delegate.phoneNumber;\r\n }\r\n get providerData() {\r\n return this._delegate.providerData;\r\n }\r\n get refreshToken() {\r\n return this._delegate.refreshToken;\r\n }\r\n get tenantId() {\r\n return this._delegate.tenantId;\r\n }\r\n get displayName() {\r\n return this._delegate.displayName;\r\n }\r\n get email() {\r\n return this._delegate.email;\r\n }\r\n get photoURL() {\r\n return this._delegate.photoURL;\r\n }\r\n get providerId() {\r\n return this._delegate.providerId;\r\n }\r\n get uid() {\r\n return this._delegate.uid;\r\n }\r\n get auth() {\r\n return this._delegate.auth;\r\n }\r\n}\r\n// Maintain a map so that there's always a 1:1 mapping between new User and\r\n// legacy compat users\r\nUser.USER_MAP = new WeakMap();\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _assert$1 = exp._assert;\r\nclass Auth {\r\n constructor(app, provider) {\r\n this.app = app;\r\n if (provider.isInitialized()) {\r\n this._delegate = provider.getImmediate();\r\n this.linkUnderlyingAuth();\r\n return;\r\n }\r\n const { apiKey } = app.options;\r\n // TODO: platform needs to be determined using heuristics\r\n _assert$1(apiKey, \"invalid-api-key\" /* INVALID_API_KEY */, {\r\n appName: app.name\r\n });\r\n // TODO: platform needs to be determined using heuristics\r\n _assert$1(apiKey, \"invalid-api-key\" /* INVALID_API_KEY */, {\r\n appName: app.name\r\n });\r\n // Only use a popup/redirect resolver in browser environments\r\n const resolver = typeof window !== 'undefined' ? CompatPopupRedirectResolver : undefined;\r\n this._delegate = provider.initialize({\r\n options: {\r\n persistence: buildPersistenceHierarchy(apiKey, app.name),\r\n popupRedirectResolver: resolver\r\n }\r\n });\r\n this._delegate._updateErrorMap(exp.debugErrorMap);\r\n this.linkUnderlyingAuth();\r\n }\r\n get emulatorConfig() {\r\n return this._delegate.emulatorConfig;\r\n }\r\n get currentUser() {\r\n if (!this._delegate.currentUser) {\r\n return null;\r\n }\r\n return User.getOrCreate(this._delegate.currentUser);\r\n }\r\n get languageCode() {\r\n return this._delegate.languageCode;\r\n }\r\n set languageCode(languageCode) {\r\n this._delegate.languageCode = languageCode;\r\n }\r\n get settings() {\r\n return this._delegate.settings;\r\n }\r\n get tenantId() {\r\n return this._delegate.tenantId;\r\n }\r\n set tenantId(tid) {\r\n this._delegate.tenantId = tid;\r\n }\r\n useDeviceLanguage() {\r\n this._delegate.useDeviceLanguage();\r\n }\r\n signOut() {\r\n return this._delegate.signOut();\r\n }\r\n useEmulator(url, options) {\r\n exp.connectAuthEmulator(this._delegate, url, options);\r\n }\r\n applyActionCode(code) {\r\n return exp.applyActionCode(this._delegate, code);\r\n }\r\n checkActionCode(code) {\r\n return exp.checkActionCode(this._delegate, code);\r\n }\r\n confirmPasswordReset(code, newPassword) {\r\n return exp.confirmPasswordReset(this._delegate, code, newPassword);\r\n }\r\n async createUserWithEmailAndPassword(email, password) {\r\n return convertCredential(this._delegate, exp.createUserWithEmailAndPassword(this._delegate, email, password));\r\n }\r\n fetchProvidersForEmail(email) {\r\n return this.fetchSignInMethodsForEmail(email);\r\n }\r\n fetchSignInMethodsForEmail(email) {\r\n return exp.fetchSignInMethodsForEmail(this._delegate, email);\r\n }\r\n isSignInWithEmailLink(emailLink) {\r\n return exp.isSignInWithEmailLink(this._delegate, emailLink);\r\n }\r\n async getRedirectResult() {\r\n _assert$1(_isPopupRedirectSupported(), this._delegate, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n const credential = await exp.getRedirectResult(this._delegate, CompatPopupRedirectResolver);\r\n if (!credential) {\r\n return {\r\n credential: null,\r\n user: null\r\n };\r\n }\r\n return convertCredential(this._delegate, Promise.resolve(credential));\r\n }\r\n // This function should only be called by frameworks (e.g. FirebaseUI-web) to log their usage.\r\n // It is not intended for direct use by developer apps. NO jsdoc here to intentionally leave it\r\n // out of autogenerated documentation pages to reduce accidental misuse.\r\n addFrameworkForLogging(framework) {\r\n exp.addFrameworkForLogging(this._delegate, framework);\r\n }\r\n onAuthStateChanged(nextOrObserver, errorFn, completed) {\r\n const { next, error, complete } = wrapObservers(nextOrObserver, errorFn, completed);\r\n return this._delegate.onAuthStateChanged(next, error, complete);\r\n }\r\n onIdTokenChanged(nextOrObserver, errorFn, completed) {\r\n const { next, error, complete } = wrapObservers(nextOrObserver, errorFn, completed);\r\n return this._delegate.onIdTokenChanged(next, error, complete);\r\n }\r\n sendSignInLinkToEmail(email, actionCodeSettings) {\r\n return exp.sendSignInLinkToEmail(this._delegate, email, actionCodeSettings);\r\n }\r\n sendPasswordResetEmail(email, actionCodeSettings) {\r\n return exp.sendPasswordResetEmail(this._delegate, email, actionCodeSettings || undefined);\r\n }\r\n async setPersistence(persistence) {\r\n _validatePersistenceArgument(this._delegate, persistence);\r\n let converted;\r\n switch (persistence) {\r\n case Persistence.SESSION:\r\n converted = exp.browserSessionPersistence;\r\n break;\r\n case Persistence.LOCAL:\r\n // Not using isIndexedDBAvailable() since it only checks if indexedDB is defined.\r\n const isIndexedDBFullySupported = await exp\r\n ._getInstance(exp.indexedDBLocalPersistence)\r\n ._isAvailable();\r\n converted = isIndexedDBFullySupported\r\n ? exp.indexedDBLocalPersistence\r\n : exp.browserLocalPersistence;\r\n break;\r\n case Persistence.NONE:\r\n converted = exp.inMemoryPersistence;\r\n break;\r\n default:\r\n return exp._fail(\"argument-error\" /* ARGUMENT_ERROR */, {\r\n appName: this._delegate.name\r\n });\r\n }\r\n return this._delegate.setPersistence(converted);\r\n }\r\n signInAndRetrieveDataWithCredential(credential) {\r\n return this.signInWithCredential(credential);\r\n }\r\n signInAnonymously() {\r\n return convertCredential(this._delegate, exp.signInAnonymously(this._delegate));\r\n }\r\n signInWithCredential(credential) {\r\n return convertCredential(this._delegate, exp.signInWithCredential(this._delegate, credential));\r\n }\r\n signInWithCustomToken(token) {\r\n return convertCredential(this._delegate, exp.signInWithCustomToken(this._delegate, token));\r\n }\r\n signInWithEmailAndPassword(email, password) {\r\n return convertCredential(this._delegate, exp.signInWithEmailAndPassword(this._delegate, email, password));\r\n }\r\n signInWithEmailLink(email, emailLink) {\r\n return convertCredential(this._delegate, exp.signInWithEmailLink(this._delegate, email, emailLink));\r\n }\r\n signInWithPhoneNumber(phoneNumber, applicationVerifier) {\r\n return convertConfirmationResult(this._delegate, exp.signInWithPhoneNumber(this._delegate, phoneNumber, applicationVerifier));\r\n }\r\n async signInWithPopup(provider) {\r\n _assert$1(_isPopupRedirectSupported(), this._delegate, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n return convertCredential(this._delegate, exp.signInWithPopup(this._delegate, provider, CompatPopupRedirectResolver));\r\n }\r\n async signInWithRedirect(provider) {\r\n _assert$1(_isPopupRedirectSupported(), this._delegate, \"operation-not-supported-in-this-environment\" /* OPERATION_NOT_SUPPORTED */);\r\n await _savePersistenceForRedirect(this._delegate);\r\n return exp.signInWithRedirect(this._delegate, provider, CompatPopupRedirectResolver);\r\n }\r\n updateCurrentUser(user) {\r\n // remove ts-ignore once overloads are defined for exp functions to accept compat objects\r\n // @ts-ignore\r\n return this._delegate.updateCurrentUser(user);\r\n }\r\n verifyPasswordResetCode(code) {\r\n return exp.verifyPasswordResetCode(this._delegate, code);\r\n }\r\n unwrap() {\r\n return this._delegate;\r\n }\r\n _delete() {\r\n return this._delegate._delete();\r\n }\r\n linkUnderlyingAuth() {\r\n this._delegate.wrapped = () => this;\r\n }\r\n}\r\nAuth.Persistence = Persistence;\r\nfunction wrapObservers(nextOrObserver, error, complete) {\r\n let next = nextOrObserver;\r\n if (typeof nextOrObserver !== 'function') {\r\n ({ next, error, complete } = nextOrObserver);\r\n }\r\n // We know 'next' is now a function\r\n const oldNext = next;\r\n const newNext = (user) => oldNext(user && User.getOrCreate(user));\r\n return {\r\n next: newNext,\r\n error: error,\r\n complete\r\n };\r\n}\r\nfunction buildPersistenceHierarchy(apiKey, appName) {\r\n // Note this is slightly different behavior: in this case, the stored\r\n // persistence is checked *first* rather than last. This is because we want\r\n // to prefer stored persistence type in the hierarchy. This is an empty\r\n // array if window is not available or there is no pending redirect\r\n const persistences = _getPersistencesFromRedirect(apiKey, appName);\r\n // If \"self\" is available, add indexedDB\r\n if (typeof self !== 'undefined' &&\r\n !persistences.includes(exp.indexedDBLocalPersistence)) {\r\n persistences.push(exp.indexedDBLocalPersistence);\r\n }\r\n // If \"window\" is available, add HTML Storage persistences\r\n if (typeof window !== 'undefined') {\r\n for (const persistence of [\r\n exp.browserLocalPersistence,\r\n exp.browserSessionPersistence\r\n ]) {\r\n if (!persistences.includes(persistence)) {\r\n persistences.push(persistence);\r\n }\r\n }\r\n }\r\n // Add in-memory as a final fallback\r\n if (!persistences.includes(exp.inMemoryPersistence)) {\r\n persistences.push(exp.inMemoryPersistence);\r\n }\r\n return persistences;\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nclass PhoneAuthProvider {\r\n constructor() {\r\n this.providerId = 'phone';\r\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\r\n // @ts-ignore\r\n this._delegate = new exp.PhoneAuthProvider(unwrap(firebase.auth()));\r\n }\r\n static credential(verificationId, verificationCode) {\r\n return exp.PhoneAuthProvider.credential(verificationId, verificationCode);\r\n }\r\n verifyPhoneNumber(phoneInfoOptions, applicationVerifier) {\r\n return this._delegate.verifyPhoneNumber(\r\n // The implementation matches but the types are subtly incompatible\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n phoneInfoOptions, applicationVerifier);\r\n }\r\n unwrap() {\r\n return this._delegate;\r\n }\r\n}\r\nPhoneAuthProvider.PHONE_SIGN_IN_METHOD = exp.PhoneAuthProvider.PHONE_SIGN_IN_METHOD;\r\nPhoneAuthProvider.PROVIDER_ID = exp.PhoneAuthProvider.PROVIDER_ID;\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst _assert = exp._assert;\r\nclass RecaptchaVerifier {\r\n constructor(container, parameters, app = firebase.app()) {\r\n var _a;\r\n // API key is required for web client RPC calls.\r\n _assert((_a = app.options) === null || _a === void 0 ? void 0 : _a.apiKey, \"invalid-api-key\" /* INVALID_API_KEY */, {\r\n appName: app.name\r\n });\r\n this._delegate = new exp.RecaptchaVerifier(container, \r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n parameters, \r\n // TODO: remove ts-ignore when moving types from auth-types to auth-compat\r\n // @ts-ignore\r\n app.auth());\r\n this.type = this._delegate.type;\r\n }\r\n clear() {\r\n this._delegate.clear();\r\n }\r\n render() {\r\n return this._delegate.render();\r\n }\r\n verify() {\r\n return this._delegate.verify();\r\n }\r\n}\n\n/**\r\n * @license\r\n * Copyright 2020 Google LLC\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\r\nconst AUTH_TYPE = 'auth-compat';\r\n// Create auth components to register with firebase.\r\n// Provides Auth public APIs.\r\nfunction registerAuthCompat(instance) {\r\n instance.INTERNAL.registerComponent(new Component(AUTH_TYPE, container => {\r\n // getImmediate for FirebaseApp will always succeed\r\n const app = container.getProvider('app-compat').getImmediate();\r\n const authProvider = container.getProvider('auth');\r\n return new Auth(app, authProvider);\r\n }, \"PUBLIC\" /* PUBLIC */)\r\n .setServiceProps({\r\n ActionCodeInfo: {\r\n Operation: {\r\n EMAIL_SIGNIN: exp.ActionCodeOperation.EMAIL_SIGNIN,\r\n PASSWORD_RESET: exp.ActionCodeOperation.PASSWORD_RESET,\r\n RECOVER_EMAIL: exp.ActionCodeOperation.RECOVER_EMAIL,\r\n REVERT_SECOND_FACTOR_ADDITION: exp.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,\r\n VERIFY_AND_CHANGE_EMAIL: exp.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,\r\n VERIFY_EMAIL: exp.ActionCodeOperation.VERIFY_EMAIL\r\n }\r\n },\r\n EmailAuthProvider: exp.EmailAuthProvider,\r\n FacebookAuthProvider: exp.FacebookAuthProvider,\r\n GithubAuthProvider: exp.GithubAuthProvider,\r\n GoogleAuthProvider: exp.GoogleAuthProvider,\r\n OAuthProvider: exp.OAuthProvider,\r\n SAMLAuthProvider: exp.SAMLAuthProvider,\r\n PhoneAuthProvider: PhoneAuthProvider,\r\n PhoneMultiFactorGenerator: exp.PhoneMultiFactorGenerator,\r\n RecaptchaVerifier: RecaptchaVerifier,\r\n TwitterAuthProvider: exp.TwitterAuthProvider,\r\n Auth,\r\n AuthCredential: exp.AuthCredential,\r\n Error: FirebaseError\r\n })\r\n .setInstantiationMode(\"LAZY\" /* LAZY */)\r\n .setMultipleInstances(false));\r\n instance.registerVersion(name, version);\r\n}\r\nregisterAuthCompat(firebase);\n//# sourceMappingURL=index.esm2017.js.map\n","var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nvar esm = {};\n\n/*\n\n Copyright The Closure Library Authors.\n SPDX-License-Identifier: Apache-2.0\n*/\nvar k,goog=goog||{},l=commonjsGlobal||self;function aa(){}function ba(a){var b=typeof a;b=\"object\"!=b?b:a?Array.isArray(a)?\"array\":b:\"null\";return \"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function p(a){var b=typeof a;return \"object\"==b&&null!=a||\"function\"==b}function da(a){return Object.prototype.hasOwnProperty.call(a,ea)&&a[ea]||(a[ea]=++fa)}var ea=\"closure_uid_\"+(1E9*Math.random()>>>0),fa=0;function ha(a,b,c){return a.call.apply(a.bind,arguments)}\nfunction ia(a,b,c){if(!a)throw Error();if(2b?null:\"string\"===typeof a?a.charAt(b):a[b]}function qa(a){return Array.prototype.concat.apply([],arguments)}function ra(a){const b=a.length;if(0b?1:0}var x;a:{var va=l.navigator;if(va){var wa=va.userAgent;if(wa){x=wa;break a}}x=\"\";}function xa(a,b,c){for(const d in a)b.call(c,a[d],d,a);}function ya(a){const b={};for(const c in a)b[c]=a[c];return b}var za=\"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");function Aa(a,b){let c,d;for(let e=1;eparseFloat(Oa)){Na=String(Qa);break a}}Na=Oa;}var Ga={};\nfunction Ra(){return Fa(function(){let a=0;const b=ta(String(Na)).split(\".\"),c=ta(\"9\").split(\".\"),d=Math.max(b.length,c.length);for(let h=0;0==a&&h>>0);function hb(a){if(\"function\"===typeof a)return a;a[pb]||(a[pb]=function(b){return a.handleEvent(b)});return a[pb]}function C(){v.call(this);this.i=new $a(this);this.P=this;this.I=null;}t(C,v);C.prototype[B]=!0;C.prototype.removeEventListener=function(a,b,c,d){nb(this,a,b,c,d);};\nfunction D(a,b){var c,d=a.I;if(d)for(c=[];d;d=d.I)c.push(d);a=a.P;d=b.type||b;if(\"string\"===typeof b)b=new z(b,a);else if(b instanceof z)b.target=b.target||a;else {var e=b;b=new z(d,a);Aa(b,e);}e=!0;if(c)for(var f=c.length-1;0<=f;f--){var h=b.g=c[f];e=qb(h,d,!0,b)&&e;}h=b.g=a;e=qb(h,d,!0,b)&&e;e=qb(h,d,!1,b)&&e;if(c)for(f=0;fnew wb,a=>a.reset());\nclass wb{constructor(){this.next=this.g=this.h=null;}set(a,b){this.h=a;this.g=b;this.next=null;}reset(){this.next=this.g=this.h=null;}}function yb(a){l.setTimeout(()=>{throw a;},0);}function zb(a,b){Ab||Bb();Cb||(Ab(),Cb=!0);tb.add(a,b);}var Ab;function Bb(){var a=l.Promise.resolve(void 0);Ab=function(){a.then(Db);};}var Cb=!1,tb=new ub;function Db(){for(var a;a=sb();){try{a.h.call(a.g);}catch(c){yb(c);}var b=vb;b.j(a);100>b.h&&(b.h++,a.next=b.g,b.g=a);}Cb=!1;}function Eb(a,b){C.call(this);this.h=a||1;this.g=b||l;this.j=q(this.kb,this);this.l=Date.now();}t(Eb,C);k=Eb.prototype;k.da=!1;k.S=null;k.kb=function(){if(this.da){var a=Date.now()-this.l;0{a.g=null;a.i&&(a.i=!1,Hb(a));},a.j);const b=a.h;a.h=null;a.m.apply(null,b);}class Ib extends v{constructor(a,b){super();this.m=a;this.j=b;this.h=null;this.i=!1;this.g=null;}l(a){this.h=arguments;this.g?this.i=!0:Hb(this);}M(){super.M();this.g&&(l.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null);}}function E(a){v.call(this);this.h=a;this.g={};}t(E,v);var Jb=[];function Kb(a,b,c,d){Array.isArray(c)||(c&&(Jb[0]=c.toString()),c=Jb);for(var e=0;ed.length)){var e=d[1];if(Array.isArray(e)&&!(1>e.length)){var f=e[0];if(\"noop\"!=f&&\"stop\"!=f&&\"close\"!=f)for(var h=1;hr)&&(3!=r||Ja||this.g&&(this.h.h||this.g.ga()||oc(this.g)))){this.I||4!=r||7==b||(8==b||0>=G?I(3):I(2));pc(this);var c=this.g.ba();this.N=c;b:if(qc(this)){var d=oc(this.g);a=\"\";var e=d.length,f=4==O(this.g);if(!this.h.i){if(\"undefined\"===typeof TextDecoder){P(this);rc(this);var h=\"\";break b}this.h.i=new l.TextDecoder;}for(b=0;bb.length)return hc;b=b.substr(d,c);a.C=d+c;return b}k.cancel=function(){this.I=!0;P(this);};function lc(a){a.Y=Date.now()+a.P;xc(a,a.P);}\nfunction xc(a,b){if(null!=a.B)throw Error(\"WatchDog timer not null\");a.B=K(q(a.eb,a),b);}function pc(a){a.B&&(l.clearTimeout(a.B),a.B=null);}k.eb=function(){this.B=null;const a=Date.now();0<=a-this.Y?(Qb(this.j,this.A),2!=this.K&&(I(3),J(17)),P(this),this.o=2,rc(this)):xc(this,this.Y-a);};function rc(a){0==a.l.G||a.I||uc(a.l,a);}function P(a){pc(a);var b=a.L;b&&\"function\"==typeof b.na&&b.na();a.L=null;Fb(a.W);Lb(a.V);a.g&&(b=a.g,a.g=null,b.abort(),b.na());}\nfunction sc(a,b){try{var c=a.l;if(0!=c.G&&(c.g==a||yc(c.i,a)))if(c.I=a.N,!a.J&&yc(c.i,a)&&3==c.G){try{var d=c.Ca.g.parse(b);}catch(m){d=null;}if(Array.isArray(d)&&3==d.length){var e=d;if(0==e[0])a:{if(!c.u){if(c.g)if(c.g.F+3E3e[2]&&c.N&&0==c.A&&!c.v&&(c.v=K(q(c.ab,c),6E3));if(1>=Cc(c.i)&&c.ka){try{c.ka();}catch(m){}c.ka=void 0;}}else Q(c,11);}else if((a.J||c.g==a)&&zc(c),!sa(b))for(e=c.Ca.g.parse(b),b=0;bb)throw Error(\"Bad port number \"+b);a.m=b;}else a.m=null;}function Sc(a,b,c){b instanceof Rc?(a.h=b,Zc(a.h,a.g)):(c||(b=Uc(b,$c)),a.h=new Rc(b,a.g));}function R(a,b,c){a.h.set(b,c);}function jc(a){R(a,\"zx\",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36));return a}\nfunction ad(a){return a instanceof U?N(a):new U(a,void 0)}function bd(a,b,c,d){var e=new U(null,void 0);a&&Oc(e,a);b&&Pc(e,b);c&&Qc(e,c);d&&(e.l=d);return e}function Tc(a,b){return a?b?decodeURI(a.replace(/%25/g,\"%2525\")):decodeURIComponent(a):\"\"}function Uc(a,b,c){return \"string\"===typeof a?(a=encodeURI(a).replace(b,cd),c&&(a=a.replace(/%25([0-9a-fA-F]{2})/g,\"%$1\")),a):null}function cd(a){a=a.charCodeAt(0);return \"%\"+(a>>4&15).toString(16)+(a&15).toString(16)}\nvar Vc=/[#\\/\\?@]/g,Xc=/[#\\?:]/g,Wc=/[#\\?]/g,$c=/[#\\?@]/g,Yc=/#/g;function Rc(a,b){this.h=this.g=null;this.i=a||null;this.j=!!b;}function V(a){a.g||(a.g=new S,a.h=0,a.i&&Nc(a.i,function(b,c){a.add(decodeURIComponent(b.replace(/\\+/g,\" \")),c);}));}k=Rc.prototype;k.add=function(a,b){V(this);this.i=null;a=W(this,a);var c=this.g.get(a);c||this.g.set(a,c=[]);c.push(b);this.h+=1;return this};\nfunction dd(a,b){V(a);b=W(a,b);T(a.g.h,b)&&(a.i=null,a.h-=a.g.get(b).length,a=a.g,T(a.h,b)&&(delete a.h[b],a.i--,a.g.length>2*a.i&&Lc(a)));}function ed(a,b){V(a);b=W(a,b);return T(a.g.h,b)}k.forEach=function(a,b){V(this);this.g.forEach(function(c,d){na(c,function(e){a.call(b,e,d,this);},this);},this);};k.T=function(){V(this);for(var a=this.g.R(),b=this.g.T(),c=[],d=0;d=a.j:!1}function Cc(a){return a.h?1:a.g?a.g.size:0}function yc(a,b){return a.h?a.h==b:a.g?a.g.has(b):!1}function Dc(a,b){a.g?a.g.add(b):a.h=b;}\nfunction Fc(a,b){a.h&&a.h==b?a.h=null:a.g&&a.g.has(b)&&a.g.delete(b);}gd.prototype.cancel=function(){this.i=jd(this);if(this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const a of this.g.values())a.cancel();this.g.clear();}};function jd(a){if(null!=a.h)return a.i.concat(a.h.D);if(null!=a.g&&0!==a.g.size){let b=a.i;for(const c of a.g.values())b=b.concat(c.D);return b}return ra(a.i)}function kd(){}kd.prototype.stringify=function(a){return l.JSON.stringify(a,void 0)};kd.prototype.parse=function(a){return l.JSON.parse(a,void 0)};function ld(){this.g=new kd;}function md(a,b,c){const d=c||\"\";try{Kc(a,function(e,f){let h=e;p(e)&&(h=rb(e));b.push(d+f+\"=\"+encodeURIComponent(h));});}catch(e){throw b.push(d+\"type=\"+encodeURIComponent(\"_badmap\")),e;}}function nd(a,b){const c=new Mb;if(l.Image){const d=new Image;d.onload=ja(od,c,d,\"TestLoadImage: loaded\",!0,b);d.onerror=ja(od,c,d,\"TestLoadImage: error\",!1,b);d.onabort=ja(od,c,d,\"TestLoadImage: abort\",!1,b);d.ontimeout=ja(od,c,d,\"TestLoadImage: timeout\",!1,b);l.setTimeout(function(){if(d.ontimeout)d.ontimeout();},1E4);d.src=a;}else b(!1);}function od(a,b,c,d,e){try{b.onload=null,b.onerror=null,b.onabort=null,b.ontimeout=null,e(d);}catch(f){}}function pd(a){this.l=a.$b||null;this.j=a.ib||!1;}t(pd,Yb);pd.prototype.g=function(){return new qd(this.l,this.j)};pd.prototype.i=function(a){return function(){return a}}({});function qd(a,b){C.call(this);this.D=a;this.u=b;this.m=void 0;this.readyState=rd;this.status=0;this.responseType=this.responseText=this.response=this.statusText=\"\";this.onreadystatechange=null;this.v=new Headers;this.h=null;this.C=\"GET\";this.B=\"\";this.g=!1;this.A=this.j=this.l=null;}t(qd,C);var rd=0;k=qd.prototype;\nk.open=function(a,b){if(this.readyState!=rd)throw this.abort(),Error(\"Error reopening a connection\");this.C=a;this.B=b;this.readyState=1;sd(this);};k.send=function(a){if(1!=this.readyState)throw this.abort(),Error(\"need to call open() first. \");this.g=!0;const b={headers:this.v,method:this.C,credentials:this.m,cache:void 0};a&&(b.body=a);(this.D||l).fetch(new Request(this.B,b)).then(this.Va.bind(this),this.ha.bind(this));};\nk.abort=function(){this.response=this.responseText=\"\";this.v=new Headers;this.status=0;this.j&&this.j.cancel(\"Request was aborted.\");1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,td(this));this.readyState=rd;};\nk.Va=function(a){if(this.g&&(this.l=a,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=a.headers,this.readyState=2,sd(this)),this.g&&(this.readyState=3,sd(this),this.g)))if(\"arraybuffer\"===this.responseType)a.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(\"undefined\"!==typeof l.ReadableStream&&\"body\"in a){this.j=a.body.getReader();if(this.u){if(this.responseType)throw Error('responseType must be empty for \"streamBinaryChunks\" mode responses.');this.response=\n[];}else this.response=this.responseText=\"\",this.A=new TextDecoder;ud(this);}else a.text().then(this.Ua.bind(this),this.ha.bind(this));};function ud(a){a.j.read().then(a.Sa.bind(a)).catch(a.ha.bind(a));}k.Sa=function(a){if(this.g){if(this.u&&a.value)this.response.push(a.value);else if(!this.u){var b=a.value?a.value:new Uint8Array(0);if(b=this.A.decode(b,{stream:!a.done}))this.response=this.responseText+=b;}a.done?td(this):sd(this);3==this.readyState&&ud(this);}};\nk.Ua=function(a){this.g&&(this.response=this.responseText=a,td(this));};k.Ta=function(a){this.g&&(this.response=a,td(this));};k.ha=function(){this.g&&td(this);};function td(a){a.readyState=4;a.l=null;a.j=null;a.A=null;sd(a);}k.setRequestHeader=function(a,b){this.v.append(a,b);};k.getResponseHeader=function(a){return this.h?this.h.get(a.toLowerCase())||\"\":\"\"};\nk.getAllResponseHeaders=function(){if(!this.h)return \"\";const a=[],b=this.h.entries();for(var c=b.next();!c.done;)c=c.value,a.push(c[0]+\": \"+c[1]),c=b.next();return a.join(\"\\r\\n\")};function sd(a){a.onreadystatechange&&a.onreadystatechange.call(a);}Object.defineProperty(qd.prototype,\"withCredentials\",{get:function(){return \"include\"===this.m},set:function(a){this.m=a?\"include\":\"same-origin\";}});var vd=l.JSON.parse;function X(a){C.call(this);this.headers=new S;this.u=a||null;this.h=!1;this.C=this.g=null;this.H=\"\";this.m=0;this.j=\"\";this.l=this.F=this.v=this.D=!1;this.B=0;this.A=null;this.J=wd;this.K=this.L=!1;}t(X,C);var wd=\"\",xd=/^https?$/i,yd=[\"POST\",\"PUT\"];k=X.prototype;\nk.ea=function(a,b,c,d){if(this.g)throw Error(\"[goog.net.XhrIo] Object is active with another request=\"+this.H+\"; newUri=\"+a);b=b?b.toUpperCase():\"GET\";this.H=a;this.j=\"\";this.m=0;this.D=!1;this.h=!0;this.g=this.u?this.u.g():cc.g();this.C=this.u?Zb(this.u):Zb(cc);this.g.onreadystatechange=q(this.Fa,this);try{this.F=!0,this.g.open(b,String(a),!0),this.F=!1;}catch(f){zd(this,f);return}a=c||\"\";const e=new S(this.headers);d&&Kc(d,function(f,h){e.set(h,f);});d=oa(e.T());c=l.FormData&&a instanceof l.FormData;\n!(0<=ma(yd,b))||d||c||e.set(\"Content-Type\",\"application/x-www-form-urlencoded;charset=utf-8\");e.forEach(function(f,h){this.g.setRequestHeader(h,f);},this);this.J&&(this.g.responseType=this.J);\"withCredentials\"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{Ad(this),0=a.i.j-(a.m?1:0))return !1;if(a.m)return a.l=b.D.concat(a.l),!0;if(1==a.G||2==a.G||a.C>=(a.Xa?0:a.Ya))return !1;a.m=K(q(a.Ha,a,b),Od(a,a.C));a.C++;return !0}\nk.Ha=function(a){if(this.m)if(this.m=null,1==this.G){if(!a){this.V=Math.floor(1E5*Math.random());a=this.V++;const e=new M(this,this.h,a,void 0);let f=this.s;this.P&&(f?(f=ya(f),Aa(f,this.P)):f=this.P);null===this.o&&(e.H=f);if(this.ja)a:{var b=0;for(var c=0;cm)f=Math.max(0,e[u].h-100),n=!1;else try{md(r,h,\"req\"+m+\"_\");}catch(G){d&&d(r);}}if(n){d=h.join(\"&\");break a}}}a=a.l.splice(0,c);b.D=a;return d}function Gc(a){a.g||a.u||(a.Y=1,zb(a.Ga,a),a.A=0);}\nfunction Bc(a){if(a.g||a.u||3<=a.A)return !1;a.Y++;a.u=K(q(a.Ga,a),Od(a,a.A));a.A++;return !0}k.Ga=function(){this.u=null;Rd(this);if(this.$&&!(this.L||null==this.g||0>=this.O)){var a=2*this.O;this.h.info(\"BP detection timer enabled: \"+a);this.B=K(q(this.bb,this),a);}};k.bb=function(){this.B&&(this.B=null,this.h.info(\"BP detection timeout reached.\"),this.h.info(\"Buffering proxy detected and switch to long-polling!\"),this.N=!1,this.L=!0,J(10),Ac(this),Rd(this));};\nfunction wc(a){null!=a.B&&(l.clearTimeout(a.B),a.B=null);}function Rd(a){a.g=new M(a,a.h,\"rpc\",a.Y);null===a.o&&(a.g.H=a.s);a.g.O=0;var b=N(a.oa);R(b,\"RID\",\"rpc\");R(b,\"SID\",a.J);R(b,\"CI\",a.N?\"0\":\"1\");R(b,\"AID\",a.U);Kd(a,b);R(b,\"TYPE\",\"xmlhttp\");a.o&&a.s&&Gd(b,a.o,a.s);a.K&&a.g.setTimeout(a.K);var c=a.g;a=a.la;c.K=1;c.v=jc(N(b));c.s=null;c.U=!0;kc(c,a);}k.ab=function(){null!=this.v&&(this.v=null,Ac(this),Bc(this),J(19));};function zc(a){null!=a.v&&(l.clearTimeout(a.v),a.v=null);}\nfunction uc(a,b){var c=null;if(a.g==b){zc(a);wc(a);a.g=null;var d=2;}else if(yc(a.i,b))c=b.D,Fc(a.i,b),d=1;else return;a.I=b.N;if(0!=a.G)if(b.i)if(1==d){c=b.s?b.s.length:0;b=Date.now()-b.F;var e=a.C;d=Sb();D(d,new Vb(d,c,b,e));Hc(a);}else Gc(a);else if(e=b.o,3==e||0==e&&0